s3: Do an early return in close_remove_share_mode
[jlayton/samba.git] / source3 / smbd / close.c
1 /*
2    Unix SMB/CIFS implementation.
3    file closing
4    Copyright (C) Andrew Tridgell 1992-1998
5    Copyright (C) Jeremy Allison 1992-2007.
6    Copyright (C) Volker Lendecke 2005
7
8    This program is free software; you can redistribute it and/or modify
9    it under the terms of the GNU General Public License as published by
10    the Free Software Foundation; either version 3 of the License, or
11    (at your option) any later version.
12
13    This program is distributed in the hope that it will be useful,
14    but WITHOUT ANY WARRANTY; without even the implied warranty of
15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16    GNU General Public License for more details.
17
18    You should have received a copy of the GNU General Public License
19    along with this program.  If not, see <http://www.gnu.org/licenses/>.
20 */
21
22 #include "includes.h"
23 #include "system/filesys.h"
24 #include "printing.h"
25 #include "smbd/smbd.h"
26 #include "smbd/globals.h"
27 #include "fake_file.h"
28 #include "transfer_file.h"
29 #include "auth.h"
30 #include "messages.h"
31 #include "../librpc/gen_ndr/open_files.h"
32
33 /****************************************************************************
34  Run a file if it is a magic script.
35 ****************************************************************************/
36
37 static NTSTATUS check_magic(struct files_struct *fsp)
38 {
39         int ret;
40         const char *magic_output = NULL;
41         SMB_STRUCT_STAT st;
42         int tmp_fd, outfd;
43         TALLOC_CTX *ctx = NULL;
44         const char *p;
45         struct connection_struct *conn = fsp->conn;
46         char *fname = NULL;
47         NTSTATUS status;
48
49         if (!*lp_magicscript(SNUM(conn))) {
50                 return NT_STATUS_OK;
51         }
52
53         DEBUG(5,("checking magic for %s\n", fsp_str_dbg(fsp)));
54
55         ctx = talloc_stackframe();
56
57         fname = fsp->fsp_name->base_name;
58
59         if (!(p = strrchr_m(fname,'/'))) {
60                 p = fname;
61         } else {
62                 p++;
63         }
64
65         if (!strequal(lp_magicscript(SNUM(conn)),p)) {
66                 status = NT_STATUS_OK;
67                 goto out;
68         }
69
70         if (*lp_magicoutput(SNUM(conn))) {
71                 magic_output = lp_magicoutput(SNUM(conn));
72         } else {
73                 magic_output = talloc_asprintf(ctx,
74                                 "%s.out",
75                                 fname);
76         }
77         if (!magic_output) {
78                 status = NT_STATUS_NO_MEMORY;
79                 goto out;
80         }
81
82         /* Ensure we don't depend on user's PATH. */
83         p = talloc_asprintf(ctx, "./%s", fname);
84         if (!p) {
85                 status = NT_STATUS_NO_MEMORY;
86                 goto out;
87         }
88
89         if (chmod(fname, 0755) == -1) {
90                 status = map_nt_error_from_unix(errno);
91                 goto out;
92         }
93         ret = smbrun(p,&tmp_fd);
94         DEBUG(3,("Invoking magic command %s gave %d\n",
95                 p,ret));
96
97         unlink(fname);
98         if (ret != 0 || tmp_fd == -1) {
99                 if (tmp_fd != -1) {
100                         close(tmp_fd);
101                 }
102                 status = NT_STATUS_UNSUCCESSFUL;
103                 goto out;
104         }
105         outfd = open(magic_output, O_CREAT|O_EXCL|O_RDWR, 0600);
106         if (outfd == -1) {
107                 int err = errno;
108                 close(tmp_fd);
109                 status = map_nt_error_from_unix(err);
110                 goto out;
111         }
112
113         if (sys_fstat(tmp_fd, &st, false) == -1) {
114                 int err = errno;
115                 close(tmp_fd);
116                 close(outfd);
117                 status = map_nt_error_from_unix(err);
118                 goto out;
119         }
120
121         if (transfer_file(tmp_fd,outfd,(off_t)st.st_ex_size) == (off_t)-1) {
122                 int err = errno;
123                 close(tmp_fd);
124                 close(outfd);
125                 status = map_nt_error_from_unix(err);
126                 goto out;
127         }
128         close(tmp_fd);
129         if (close(outfd) == -1) {
130                 status = map_nt_error_from_unix(errno);
131                 goto out;
132         }
133
134         status = NT_STATUS_OK;
135
136  out:
137         TALLOC_FREE(ctx);
138         return status;
139 }
140
141 /****************************************************************************
142   Common code to close a file or a directory.
143 ****************************************************************************/
144
145 static NTSTATUS close_filestruct(files_struct *fsp)
146 {
147         NTSTATUS status = NT_STATUS_OK;
148
149         if (fsp->fh->fd != -1) {
150                 if(flush_write_cache(fsp, CLOSE_FLUSH) == -1) {
151                         status = map_nt_error_from_unix(errno);
152                 }
153                 delete_write_cache(fsp);
154         }
155
156         return status;
157 }
158
159 static int compare_share_mode_times(const void *p1, const void *p2)
160 {
161         const struct share_mode_entry *s1 = (const struct share_mode_entry *)p1;
162         const struct share_mode_entry *s2 = (const struct share_mode_entry *)p2;
163         return timeval_compare(&s1->time, &s2->time);
164 }
165
166 /****************************************************************************
167  If any deferred opens are waiting on this close, notify them.
168 ****************************************************************************/
169
170 static void notify_deferred_opens(struct smbd_server_connection *sconn,
171                                   struct share_mode_lock *lck)
172 {
173         struct server_id self = messaging_server_id(sconn->msg_ctx);
174         uint32_t i, num_deferred;
175         struct share_mode_entry *deferred;
176
177         if (!should_notify_deferred_opens(sconn)) {
178                 return;
179         }
180
181         num_deferred = 0;
182         for (i=0; i<lck->data->num_share_modes; i++) {
183                 struct share_mode_entry *e = &lck->data->share_modes[i];
184
185                 if (!is_deferred_open_entry(e)) {
186                         continue;
187                 }
188                 if (share_mode_stale_pid(lck->data, i)) {
189                         continue;
190                 }
191                 num_deferred += 1;
192         }
193         if (num_deferred == 0) {
194                 return;
195         }
196
197         deferred = talloc_array(talloc_tos(), struct share_mode_entry,
198                                 num_deferred);
199         if (deferred == NULL) {
200                 return;
201         }
202
203         num_deferred = 0;
204         for (i=0; i<lck->data->num_share_modes; i++) {
205                 struct share_mode_entry *e = &lck->data->share_modes[i];
206                 if (is_deferred_open_entry(e)) {
207                         deferred[num_deferred] = *e;
208                         num_deferred += 1;
209                 }
210         }
211
212         /*
213          * We need to sort the notifications by initial request time. Imagine
214          * two opens come in asyncronously, both conflicting with the open we
215          * just close here. If we don't sort the notifications, the one that
216          * came in last might get the response before the one that came in
217          * first. This is demonstrated with the smbtorture4 raw.mux test.
218          *
219          * As long as we had the UNUSED_SHARE_MODE_ENTRY, we happened to
220          * survive this particular test. Without UNUSED_SHARE_MODE_ENTRY, we
221          * shuffle the share mode entries around a bit, so that we do not
222          * survive raw.mux anymore.
223          *
224          * We could have kept the ordering in del_share_mode, but as the
225          * ordering was never formalized I think it is better to do it here
226          * where it is necessary.
227          */
228
229         qsort(deferred, num_deferred, sizeof(struct share_mode_entry),
230               compare_share_mode_times);
231
232         for (i=0; i<num_deferred; i++) {
233                 struct share_mode_entry *e = &deferred[i];
234
235                 if (procid_equal(&self, &e->pid)) {
236                         /*
237                          * We need to notify ourself to retry the open.  Do
238                          * this by finding the queued SMB record, moving it to
239                          * the head of the queue and changing the wait time to
240                          * zero.
241                          */
242                         schedule_deferred_open_message_smb(sconn, e->op_mid);
243                 } else {
244                         char msg[MSG_SMB_SHARE_MODE_ENTRY_SIZE];
245
246                         share_mode_entry_to_message(msg, e);
247
248                         messaging_send_buf(sconn->msg_ctx, e->pid,
249                                            MSG_SMB_OPEN_RETRY,
250                                            (uint8 *)msg,
251                                            MSG_SMB_SHARE_MODE_ENTRY_SIZE);
252                 }
253         }
254         TALLOC_FREE(deferred);
255 }
256
257 /****************************************************************************
258  Delete all streams
259 ****************************************************************************/
260
261 NTSTATUS delete_all_streams(connection_struct *conn, const char *fname)
262 {
263         struct stream_struct *stream_info = NULL;
264         int i;
265         unsigned int num_streams = 0;
266         TALLOC_CTX *frame = talloc_stackframe();
267         NTSTATUS status;
268
269         status = vfs_streaminfo(conn, NULL, fname, talloc_tos(),
270                                 &num_streams, &stream_info);
271
272         if (NT_STATUS_EQUAL(status, NT_STATUS_NOT_IMPLEMENTED)) {
273                 DEBUG(10, ("no streams around\n"));
274                 TALLOC_FREE(frame);
275                 return NT_STATUS_OK;
276         }
277
278         if (!NT_STATUS_IS_OK(status)) {
279                 DEBUG(10, ("vfs_streaminfo failed: %s\n",
280                            nt_errstr(status)));
281                 goto fail;
282         }
283
284         DEBUG(10, ("delete_all_streams found %d streams\n",
285                    num_streams));
286
287         if (num_streams == 0) {
288                 TALLOC_FREE(frame);
289                 return NT_STATUS_OK;
290         }
291
292         for (i=0; i<num_streams; i++) {
293                 int res;
294                 struct smb_filename *smb_fname_stream = NULL;
295
296                 if (strequal(stream_info[i].name, "::$DATA")) {
297                         continue;
298                 }
299
300                 status = create_synthetic_smb_fname(talloc_tos(), fname,
301                                                     stream_info[i].name, NULL,
302                                                     &smb_fname_stream);
303
304                 if (!NT_STATUS_IS_OK(status)) {
305                         DEBUG(0, ("talloc_aprintf failed\n"));
306                         goto fail;
307                 }
308
309                 res = SMB_VFS_UNLINK(conn, smb_fname_stream);
310
311                 if (res == -1) {
312                         status = map_nt_error_from_unix(errno);
313                         DEBUG(10, ("Could not delete stream %s: %s\n",
314                                    smb_fname_str_dbg(smb_fname_stream),
315                                    strerror(errno)));
316                         TALLOC_FREE(smb_fname_stream);
317                         break;
318                 }
319                 TALLOC_FREE(smb_fname_stream);
320         }
321
322  fail:
323         TALLOC_FREE(frame);
324         return status;
325 }
326
327 /****************************************************************************
328  Deal with removing a share mode on last close.
329 ****************************************************************************/
330
331 static NTSTATUS close_remove_share_mode(files_struct *fsp,
332                                         enum file_close_type close_type)
333 {
334         connection_struct *conn = fsp->conn;
335         bool delete_file = false;
336         bool changed_user = false;
337         struct share_mode_lock *lck = NULL;
338         NTSTATUS status = NT_STATUS_OK;
339         NTSTATUS tmp_status;
340         struct file_id id;
341         const struct security_unix_token *del_token = NULL;
342         const struct security_token *del_nt_token = NULL;
343         bool got_tokens = false;
344         bool normal_close;
345
346         /* Ensure any pending write time updates are done. */
347         if (fsp->update_write_time_event) {
348                 update_write_time_handler(fsp->conn->sconn->ev_ctx,
349                                         fsp->update_write_time_event,
350                                         timeval_current(),
351                                         (void *)fsp);
352         }
353
354         /*
355          * Lock the share entries, and determine if we should delete
356          * on close. If so delete whilst the lock is still in effect.
357          * This prevents race conditions with the file being created. JRA.
358          */
359
360         lck = get_existing_share_mode_lock(talloc_tos(), fsp->file_id);
361         if (lck == NULL) {
362                 DEBUG(0, ("close_remove_share_mode: Could not get share mode "
363                           "lock for file %s\n", fsp_str_dbg(fsp)));
364                 return NT_STATUS_INVALID_PARAMETER;
365         }
366
367         if (fsp->write_time_forced) {
368                 DEBUG(10,("close_remove_share_mode: write time forced "
369                         "for file %s\n",
370                         fsp_str_dbg(fsp)));
371                 set_close_write_time(fsp, lck->data->changed_write_time);
372         } else if (fsp->update_write_time_on_close) {
373                 /* Someone had a pending write. */
374                 if (null_timespec(fsp->close_write_time)) {
375                         DEBUG(10,("close_remove_share_mode: update to current time "
376                                 "for file %s\n",
377                                 fsp_str_dbg(fsp)));
378                         /* Update to current time due to "normal" write. */
379                         set_close_write_time(fsp, timespec_current());
380                 } else {
381                         DEBUG(10,("close_remove_share_mode: write time pending "
382                                 "for file %s\n",
383                                 fsp_str_dbg(fsp)));
384                         /* Update to time set on close call. */
385                         set_close_write_time(fsp, fsp->close_write_time);
386                 }
387         }
388
389         if (!del_share_mode(lck, fsp)) {
390                 DEBUG(0, ("close_remove_share_mode: Could not delete share "
391                           "entry for file %s\n",
392                           fsp_str_dbg(fsp)));
393         }
394
395         if (fsp->initial_delete_on_close &&
396                         !is_delete_on_close_set(lck, fsp->name_hash)) {
397                 bool became_user = False;
398
399                 /* Initial delete on close was set and no one else
400                  * wrote a real delete on close. */
401
402                 if (get_current_vuid(conn) != fsp->vuid) {
403                         become_user(conn, fsp->vuid);
404                         became_user = True;
405                 }
406                 fsp->delete_on_close = true;
407                 set_delete_on_close_lck(fsp, lck, True,
408                                 get_current_nttok(conn),
409                                 get_current_utok(conn));
410                 if (became_user) {
411                         unbecome_user();
412                 }
413         }
414
415         delete_file = is_delete_on_close_set(lck, fsp->name_hash);
416
417         if (delete_file) {
418                 int i;
419                 /* See if others still have the file open via this pathname.
420                    If this is the case, then don't delete. If all opens are
421                    POSIX delete now. */
422                 for (i=0; i<lck->data->num_share_modes; i++) {
423                         struct share_mode_entry *e = &lck->data->share_modes[i];
424
425                         if (!is_valid_share_mode_entry(e)) {
426                                 continue;
427                         }
428                         if (e->name_hash != fsp->name_hash) {
429                                 continue;
430                         }
431                         if (fsp->posix_open
432                             && (e->flags & SHARE_MODE_FLAG_POSIX_OPEN)) {
433                                 continue;
434                         }
435                         if (share_mode_stale_pid(lck->data, i)) {
436                                 continue;
437                         }
438                         delete_file = False;
439                         break;
440                 }
441         }
442
443         /* Notify any deferred opens waiting on this close. */
444         notify_deferred_opens(conn->sconn, lck);
445         reply_to_oplock_break_requests(fsp);
446
447         /*
448          * NT can set delete_on_close of the last open
449          * reference to a file.
450          */
451
452         normal_close = (close_type == NORMAL_CLOSE || close_type == SHUTDOWN_CLOSE);
453
454         if (!normal_close || !delete_file) {
455                 TALLOC_FREE(lck);
456                 return NT_STATUS_OK;
457         }
458
459         /*
460          * Ok, we have to delete the file
461          */
462
463         DEBUG(5,("close_remove_share_mode: file %s. Delete on close was set "
464                  "- deleting file.\n", fsp_str_dbg(fsp)));
465
466         /*
467          * Don't try to update the write time when we delete the file
468          */
469         fsp->update_write_time_on_close = false;
470
471         got_tokens = get_delete_on_close_token(lck, fsp->name_hash,
472                                         &del_nt_token, &del_token);
473         SMB_ASSERT(got_tokens);
474
475         if (!unix_token_equal(del_token, get_current_utok(conn))) {
476                 /* Become the user who requested the delete. */
477
478                 DEBUG(5,("close_remove_share_mode: file %s. "
479                         "Change user to uid %u\n",
480                         fsp_str_dbg(fsp),
481                         (unsigned int)del_token->uid));
482
483                 if (!push_sec_ctx()) {
484                         smb_panic("close_remove_share_mode: file %s. failed to push "
485                                   "sec_ctx.\n");
486                 }
487
488                 set_sec_ctx(del_token->uid,
489                             del_token->gid,
490                             del_token->ngroups,
491                             del_token->groups,
492                             del_nt_token);
493
494                 changed_user = true;
495         }
496
497         /* We can only delete the file if the name we have is still valid and
498            hasn't been renamed. */
499
500         tmp_status = vfs_stat_fsp(fsp);
501         if (!NT_STATUS_IS_OK(tmp_status)) {
502                 DEBUG(5,("close_remove_share_mode: file %s. Delete on close "
503                          "was set and stat failed with error %s\n",
504                          fsp_str_dbg(fsp), nt_errstr(tmp_status)));
505                 /*
506                  * Don't save the errno here, we ignore this error
507                  */
508                 goto done;
509         }
510
511         id = vfs_file_id_from_sbuf(conn, &fsp->fsp_name->st);
512
513         if (!file_id_equal(&fsp->file_id, &id)) {
514                 DEBUG(5,("close_remove_share_mode: file %s. Delete on close "
515                          "was set and dev and/or inode does not match\n",
516                          fsp_str_dbg(fsp)));
517                 DEBUG(5,("close_remove_share_mode: file %s. stored file_id %s, "
518                          "stat file_id %s\n",
519                          fsp_str_dbg(fsp),
520                          file_id_string_tos(&fsp->file_id),
521                          file_id_string_tos(&id)));
522                 /*
523                  * Don't save the errno here, we ignore this error
524                  */
525                 goto done;
526         }
527
528         if ((conn->fs_capabilities & FILE_NAMED_STREAMS)
529             && !is_ntfs_stream_smb_fname(fsp->fsp_name)) {
530
531                 status = delete_all_streams(conn, fsp->fsp_name->base_name);
532
533                 if (!NT_STATUS_IS_OK(status)) {
534                         DEBUG(5, ("delete_all_streams failed: %s\n",
535                                   nt_errstr(status)));
536                         goto done;
537                 }
538         }
539
540
541         if (SMB_VFS_UNLINK(conn, fsp->fsp_name) != 0) {
542                 /*
543                  * This call can potentially fail as another smbd may
544                  * have had the file open with delete on close set and
545                  * deleted it when its last reference to this file
546                  * went away. Hence we log this but not at debug level
547                  * zero.
548                  */
549
550                 DEBUG(5,("close_remove_share_mode: file %s. Delete on close "
551                          "was set and unlink failed with error %s\n",
552                          fsp_str_dbg(fsp), strerror(errno)));
553
554                 status = map_nt_error_from_unix(errno);
555         }
556
557         /* As we now have POSIX opens which can unlink
558          * with other open files we may have taken
559          * this code path with more than one share mode
560          * entry - ensure we only delete once by resetting
561          * the delete on close flag. JRA.
562          */
563
564         fsp->delete_on_close = false;
565         set_delete_on_close_lck(fsp, lck, false, NULL, NULL);
566
567  done:
568
569         if (changed_user) {
570                 /* unbecome user. */
571                 pop_sec_ctx();
572         }
573
574         TALLOC_FREE(lck);
575
576         if (delete_file) {
577                 /*
578                  * Do the notification after we released the share
579                  * mode lock. Inside notify_fname we take out another
580                  * tdb lock. With ctdb also accessing our databases,
581                  * this can lead to deadlocks. Putting this notify
582                  * after the TALLOC_FREE(lck) above we avoid locking
583                  * two records simultaneously. Notifies are async and
584                  * informational only, so calling the notify_fname
585                  * without holding the share mode lock should not do
586                  * any harm.
587                  */
588                 notify_fname(conn, NOTIFY_ACTION_REMOVED,
589                              FILE_NOTIFY_CHANGE_FILE_NAME,
590                              fsp->fsp_name->base_name);
591         }
592
593         return status;
594 }
595
596 void set_close_write_time(struct files_struct *fsp, struct timespec ts)
597 {
598         DEBUG(6,("close_write_time: %s" , time_to_asc(convert_timespec_to_time_t(ts))));
599
600         if (null_timespec(ts)) {
601                 return;
602         }
603         fsp->write_time_forced = false;
604         fsp->update_write_time_on_close = true;
605         fsp->close_write_time = ts;
606 }
607
608 static NTSTATUS update_write_time_on_close(struct files_struct *fsp)
609 {
610         struct smb_file_time ft;
611         NTSTATUS status;
612         struct share_mode_lock *lck = NULL;
613
614         ZERO_STRUCT(ft);
615
616         if (!fsp->update_write_time_on_close) {
617                 return NT_STATUS_OK;
618         }
619
620         if (null_timespec(fsp->close_write_time)) {
621                 fsp->close_write_time = timespec_current();
622         }
623
624         /* Ensure we have a valid stat struct for the source. */
625         status = vfs_stat_fsp(fsp);
626         if (!NT_STATUS_IS_OK(status)) {
627                 return status;
628         }
629
630         if (!VALID_STAT(fsp->fsp_name->st)) {
631                 /* if it doesn't seem to be a real file */
632                 return NT_STATUS_OK;
633         }
634
635         /*
636          * get_existing_share_mode_lock() isn't really the right
637          * call here, as we're being called after
638          * close_remove_share_mode() inside close_normal_file()
639          * so it's quite normal to not have an existing share
640          * mode here. However, get_share_mode_lock() doesn't
641          * work because that will create a new share mode if
642          * one doesn't exist - so stick with this call (just
643          * ignore any error we get if the share mode doesn't
644          * exist.
645          */
646
647         lck = get_existing_share_mode_lock(talloc_tos(), fsp->file_id);
648         if (lck) {
649                 /* On close if we're changing the real file time we
650                  * must update it in the open file db too. */
651                 (void)set_write_time(fsp->file_id, fsp->close_write_time);
652
653                 /* Close write times overwrite sticky write times
654                    so we must replace any sticky write time here. */
655                 if (!null_timespec(lck->data->changed_write_time)) {
656                         (void)set_sticky_write_time(fsp->file_id, fsp->close_write_time);
657                 }
658                 TALLOC_FREE(lck);
659         }
660
661         ft.mtime = fsp->close_write_time;
662         /* As this is a close based update, we are not directly changing the
663            file attributes from a client call, but indirectly from a write. */
664         status = smb_set_file_time(fsp->conn, fsp, fsp->fsp_name, &ft, false);
665         if (!NT_STATUS_IS_OK(status)) {
666                 DEBUG(10,("update_write_time_on_close: smb_set_file_time "
667                         "on file %s returned %s\n",
668                         fsp_str_dbg(fsp),
669                         nt_errstr(status)));
670                 return status;
671         }
672
673         return status;
674 }
675
676 static NTSTATUS ntstatus_keeperror(NTSTATUS s1, NTSTATUS s2)
677 {
678         if (!NT_STATUS_IS_OK(s1)) {
679                 return s1;
680         }
681         return s2;
682 }
683
684 /****************************************************************************
685  Close a file.
686
687  close_type can be NORMAL_CLOSE=0,SHUTDOWN_CLOSE,ERROR_CLOSE.
688  printing and magic scripts are only run on normal close.
689  delete on close is done on normal and shutdown close.
690 ****************************************************************************/
691
692 static NTSTATUS close_normal_file(struct smb_request *req, files_struct *fsp,
693                                   enum file_close_type close_type)
694 {
695         NTSTATUS status = NT_STATUS_OK;
696         NTSTATUS tmp;
697         connection_struct *conn = fsp->conn;
698         int ret;
699
700         /*
701          * If we're finishing async io on a close we can get a write
702          * error here, we must remember this.
703          */
704         ret = wait_for_aio_completion(fsp);
705         if (ret) {
706                 status = ntstatus_keeperror(
707                         status, map_nt_error_from_unix(ret));
708         }
709
710         /*
711          * If we're flushing on a close we can get a write
712          * error here, we must remember this.
713          */
714
715         tmp = close_filestruct(fsp);
716         status = ntstatus_keeperror(status, tmp);
717
718         if (fsp->print_file) {
719                 /* FIXME: return spool errors */
720                 print_spool_end(fsp, close_type);
721                 file_free(req, fsp);
722                 return NT_STATUS_OK;
723         }
724
725         /* Remove the oplock before potentially deleting the file. */
726         if(fsp->oplock_type) {
727                 release_file_oplock(fsp);
728         }
729
730         /* If this is an old DOS or FCB open and we have multiple opens on
731            the same handle we only have one share mode. Ensure we only remove
732            the share mode on the last close. */
733
734         if (fsp->fh->ref_count == 1) {
735                 /* Should we return on error here... ? */
736                 tmp = close_remove_share_mode(fsp, close_type);
737                 status = ntstatus_keeperror(status, tmp);
738         }
739
740         locking_close_file(conn->sconn->msg_ctx, fsp, close_type);
741
742         tmp = fd_close(fsp);
743         status = ntstatus_keeperror(status, tmp);
744
745         /* check for magic scripts */
746         if (close_type == NORMAL_CLOSE) {
747                 tmp = check_magic(fsp);
748                 status = ntstatus_keeperror(status, tmp);
749         }
750
751         /*
752          * Ensure pending modtime is set after close.
753          */
754
755         tmp = update_write_time_on_close(fsp);
756         if (NT_STATUS_EQUAL(tmp, NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
757                 /* Someone renamed the file or a parent directory containing
758                  * this file. We can't do anything about this, we don't have
759                  * an "update timestamp by fd" call in POSIX. Eat the error. */
760
761                 tmp = NT_STATUS_OK;
762         }
763
764         status = ntstatus_keeperror(status, tmp);
765
766         DEBUG(2,("%s closed file %s (numopen=%d) %s\n",
767                 conn->session_info->unix_info->unix_name, fsp_str_dbg(fsp),
768                 conn->num_files_open - 1,
769                 nt_errstr(status) ));
770
771         file_free(req, fsp);
772         return status;
773 }
774 /****************************************************************************
775  Static function used by reply_rmdir to delete an entire directory
776  tree recursively. Return True on ok, False on fail.
777 ****************************************************************************/
778
779 static bool recursive_rmdir(TALLOC_CTX *ctx,
780                         connection_struct *conn,
781                         struct smb_filename *smb_dname)
782 {
783         const char *dname = NULL;
784         char *talloced = NULL;
785         bool ret = True;
786         long offset = 0;
787         SMB_STRUCT_STAT st;
788         struct smb_Dir *dir_hnd;
789
790         SMB_ASSERT(!is_ntfs_stream_smb_fname(smb_dname));
791
792         dir_hnd = OpenDir(talloc_tos(), conn, smb_dname->base_name, NULL, 0);
793         if(dir_hnd == NULL)
794                 return False;
795
796         while((dname = ReadDirName(dir_hnd, &offset, &st, &talloced))) {
797                 struct smb_filename *smb_dname_full = NULL;
798                 char *fullname = NULL;
799                 bool do_break = true;
800                 NTSTATUS status;
801
802                 if (ISDOT(dname) || ISDOTDOT(dname)) {
803                         TALLOC_FREE(talloced);
804                         continue;
805                 }
806
807                 if (!is_visible_file(conn, smb_dname->base_name, dname, &st,
808                                      false)) {
809                         TALLOC_FREE(talloced);
810                         continue;
811                 }
812
813                 /* Construct the full name. */
814                 fullname = talloc_asprintf(ctx,
815                                 "%s/%s",
816                                 smb_dname->base_name,
817                                 dname);
818                 if (!fullname) {
819                         errno = ENOMEM;
820                         goto err_break;
821                 }
822
823                 status = create_synthetic_smb_fname(talloc_tos(), fullname,
824                                                     NULL, NULL,
825                                                     &smb_dname_full);
826                 if (!NT_STATUS_IS_OK(status)) {
827                         goto err_break;
828                 }
829
830                 if(SMB_VFS_LSTAT(conn, smb_dname_full) != 0) {
831                         goto err_break;
832                 }
833
834                 if(smb_dname_full->st.st_ex_mode & S_IFDIR) {
835                         if(!recursive_rmdir(ctx, conn, smb_dname_full)) {
836                                 goto err_break;
837                         }
838                         if(SMB_VFS_RMDIR(conn,
839                                          smb_dname_full->base_name) != 0) {
840                                 goto err_break;
841                         }
842                 } else if(SMB_VFS_UNLINK(conn, smb_dname_full) != 0) {
843                         goto err_break;
844                 }
845
846                 /* Successful iteration. */
847                 do_break = false;
848
849          err_break:
850                 TALLOC_FREE(smb_dname_full);
851                 TALLOC_FREE(fullname);
852                 TALLOC_FREE(talloced);
853                 if (do_break) {
854                         ret = false;
855                         break;
856                 }
857         }
858         TALLOC_FREE(dir_hnd);
859         return ret;
860 }
861
862 /****************************************************************************
863  The internals of the rmdir code - called elsewhere.
864 ****************************************************************************/
865
866 static NTSTATUS rmdir_internals(TALLOC_CTX *ctx, files_struct *fsp)
867 {
868         connection_struct *conn = fsp->conn;
869         struct smb_filename *smb_dname = fsp->fsp_name;
870         int ret;
871
872         SMB_ASSERT(!is_ntfs_stream_smb_fname(smb_dname));
873
874         /* Might be a symlink. */
875         if(SMB_VFS_LSTAT(conn, smb_dname) != 0) {
876                 return map_nt_error_from_unix(errno);
877         }
878
879         if (S_ISLNK(smb_dname->st.st_ex_mode)) {
880                 /* Is what it points to a directory ? */
881                 if(SMB_VFS_STAT(conn, smb_dname) != 0) {
882                         return map_nt_error_from_unix(errno);
883                 }
884                 if (!(S_ISDIR(smb_dname->st.st_ex_mode))) {
885                         return NT_STATUS_NOT_A_DIRECTORY;
886                 }
887                 ret = SMB_VFS_UNLINK(conn, smb_dname);
888         } else {
889                 ret = SMB_VFS_RMDIR(conn, smb_dname->base_name);
890         }
891         if (ret == 0) {
892                 notify_fname(conn, NOTIFY_ACTION_REMOVED,
893                              FILE_NOTIFY_CHANGE_DIR_NAME,
894                              smb_dname->base_name);
895                 return NT_STATUS_OK;
896         }
897
898         if(((errno == ENOTEMPTY)||(errno == EEXIST)) && *lp_veto_files(SNUM(conn))) {
899                 /*
900                  * Check to see if the only thing in this directory are
901                  * vetoed files/directories. If so then delete them and
902                  * retry. If we fail to delete any of them (and we *don't*
903                  * do a recursive delete) then fail the rmdir.
904                  */
905                 SMB_STRUCT_STAT st;
906                 const char *dname = NULL;
907                 char *talloced = NULL;
908                 long dirpos = 0;
909                 struct smb_Dir *dir_hnd = OpenDir(talloc_tos(), conn,
910                                                   smb_dname->base_name, NULL,
911                                                   0);
912
913                 if(dir_hnd == NULL) {
914                         errno = ENOTEMPTY;
915                         goto err;
916                 }
917
918                 while ((dname = ReadDirName(dir_hnd, &dirpos, &st,
919                                             &talloced)) != NULL) {
920                         if((strcmp(dname, ".") == 0) || (strcmp(dname, "..")==0)) {
921                                 TALLOC_FREE(talloced);
922                                 continue;
923                         }
924                         if (!is_visible_file(conn, smb_dname->base_name, dname,
925                                              &st, false)) {
926                                 TALLOC_FREE(talloced);
927                                 continue;
928                         }
929                         if(!IS_VETO_PATH(conn, dname)) {
930                                 TALLOC_FREE(dir_hnd);
931                                 TALLOC_FREE(talloced);
932                                 errno = ENOTEMPTY;
933                                 goto err;
934                         }
935                         TALLOC_FREE(talloced);
936                 }
937
938                 /* We only have veto files/directories.
939                  * Are we allowed to delete them ? */
940
941                 if(!lp_recursive_veto_delete(SNUM(conn))) {
942                         TALLOC_FREE(dir_hnd);
943                         errno = ENOTEMPTY;
944                         goto err;
945                 }
946
947                 /* Do a recursive delete. */
948                 RewindDir(dir_hnd,&dirpos);
949                 while ((dname = ReadDirName(dir_hnd, &dirpos, &st,
950                                             &talloced)) != NULL) {
951                         struct smb_filename *smb_dname_full = NULL;
952                         char *fullname = NULL;
953                         bool do_break = true;
954                         NTSTATUS status;
955
956                         if (ISDOT(dname) || ISDOTDOT(dname)) {
957                                 TALLOC_FREE(talloced);
958                                 continue;
959                         }
960                         if (!is_visible_file(conn, smb_dname->base_name, dname,
961                                              &st, false)) {
962                                 TALLOC_FREE(talloced);
963                                 continue;
964                         }
965
966                         fullname = talloc_asprintf(ctx,
967                                         "%s/%s",
968                                         smb_dname->base_name,
969                                         dname);
970
971                         if(!fullname) {
972                                 errno = ENOMEM;
973                                 goto err_break;
974                         }
975
976                         status = create_synthetic_smb_fname(talloc_tos(),
977                                                             fullname, NULL,
978                                                             NULL,
979                                                             &smb_dname_full);
980                         if (!NT_STATUS_IS_OK(status)) {
981                                 errno = map_errno_from_nt_status(status);
982                                 goto err_break;
983                         }
984
985                         if(SMB_VFS_LSTAT(conn, smb_dname_full) != 0) {
986                                 goto err_break;
987                         }
988                         if(smb_dname_full->st.st_ex_mode & S_IFDIR) {
989                                 if(!recursive_rmdir(ctx, conn,
990                                                     smb_dname_full)) {
991                                         goto err_break;
992                                 }
993                                 if(SMB_VFS_RMDIR(conn,
994                                         smb_dname_full->base_name) != 0) {
995                                         goto err_break;
996                                 }
997                         } else if(SMB_VFS_UNLINK(conn, smb_dname_full) != 0) {
998                                 goto err_break;
999                         }
1000
1001                         /* Successful iteration. */
1002                         do_break = false;
1003
1004                  err_break:
1005                         TALLOC_FREE(fullname);
1006                         TALLOC_FREE(smb_dname_full);
1007                         TALLOC_FREE(talloced);
1008                         if (do_break)
1009                                 break;
1010                 }
1011                 TALLOC_FREE(dir_hnd);
1012                 /* Retry the rmdir */
1013                 ret = SMB_VFS_RMDIR(conn, smb_dname->base_name);
1014         }
1015
1016   err:
1017
1018         if (ret != 0) {
1019                 DEBUG(3,("rmdir_internals: couldn't remove directory %s : "
1020                          "%s\n", smb_fname_str_dbg(smb_dname),
1021                          strerror(errno)));
1022                 return map_nt_error_from_unix(errno);
1023         }
1024
1025         notify_fname(conn, NOTIFY_ACTION_REMOVED,
1026                      FILE_NOTIFY_CHANGE_DIR_NAME,
1027                      smb_dname->base_name);
1028
1029         return NT_STATUS_OK;
1030 }
1031
1032 /****************************************************************************
1033  Close a directory opened by an NT SMB call. 
1034 ****************************************************************************/
1035   
1036 static NTSTATUS close_directory(struct smb_request *req, files_struct *fsp,
1037                                 enum file_close_type close_type)
1038 {
1039         struct share_mode_lock *lck = NULL;
1040         bool delete_dir = False;
1041         NTSTATUS status = NT_STATUS_OK;
1042         NTSTATUS status1 = NT_STATUS_OK;
1043         const struct security_token *del_nt_token = NULL;
1044         const struct security_unix_token *del_token = NULL;
1045
1046         /*
1047          * NT can set delete_on_close of the last open
1048          * reference to a directory also.
1049          */
1050
1051         lck = get_existing_share_mode_lock(talloc_tos(), fsp->file_id);
1052         if (lck == NULL) {
1053                 DEBUG(0, ("close_directory: Could not get share mode lock for "
1054                           "%s\n", fsp_str_dbg(fsp)));
1055                 status = NT_STATUS_INVALID_PARAMETER;
1056                 goto out;
1057         }
1058
1059         if (!del_share_mode(lck, fsp)) {
1060                 DEBUG(0, ("close_directory: Could not delete share entry for "
1061                           "%s\n", fsp_str_dbg(fsp)));
1062         }
1063
1064         if (fsp->initial_delete_on_close) {
1065                 bool became_user = False;
1066
1067                 /* Initial delete on close was set - for
1068                  * directories we don't care if anyone else
1069                  * wrote a real delete on close. */
1070
1071                 if (get_current_vuid(fsp->conn) != fsp->vuid) {
1072                         become_user(fsp->conn, fsp->vuid);
1073                         became_user = True;
1074                 }
1075                 send_stat_cache_delete_message(fsp->conn->sconn->msg_ctx,
1076                                                fsp->fsp_name->base_name);
1077                 set_delete_on_close_lck(fsp, lck, true,
1078                                 get_current_nttok(fsp->conn),
1079                                 get_current_utok(fsp->conn));
1080                 fsp->delete_on_close = true;
1081                 if (became_user) {
1082                         unbecome_user();
1083                 }
1084         }
1085
1086         delete_dir = get_delete_on_close_token(lck, fsp->name_hash,
1087                                         &del_nt_token, &del_token);
1088
1089         if (delete_dir) {
1090                 int i;
1091                 /* See if others still have the dir open. If this is the
1092                  * case, then don't delete. If all opens are POSIX delete now. */
1093                 for (i=0; i<lck->data->num_share_modes; i++) {
1094                         struct share_mode_entry *e = &lck->data->share_modes[i];
1095                         if (is_valid_share_mode_entry(e) &&
1096                                         e->name_hash == fsp->name_hash) {
1097                                 if (fsp->posix_open && (e->flags & SHARE_MODE_FLAG_POSIX_OPEN)) {
1098                                         continue;
1099                                 }
1100                                 if (share_mode_stale_pid(lck->data, i)) {
1101                                         continue;
1102                                 }
1103                                 delete_dir = False;
1104                                 break;
1105                         }
1106                 }
1107         }
1108
1109         if ((close_type == NORMAL_CLOSE || close_type == SHUTDOWN_CLOSE) &&
1110                                 delete_dir) {
1111         
1112                 /* Become the user who requested the delete. */
1113
1114                 if (!push_sec_ctx()) {
1115                         smb_panic("close_directory: failed to push sec_ctx.\n");
1116                 }
1117
1118                 set_sec_ctx(del_token->uid,
1119                                 del_token->gid,
1120                                 del_token->ngroups,
1121                                 del_token->groups,
1122                                 del_nt_token);
1123
1124                 TALLOC_FREE(lck);
1125
1126                 if ((fsp->conn->fs_capabilities & FILE_NAMED_STREAMS)
1127                     && !is_ntfs_stream_smb_fname(fsp->fsp_name)) {
1128
1129                         status = delete_all_streams(fsp->conn, fsp->fsp_name->base_name);
1130                         if (!NT_STATUS_IS_OK(status)) {
1131                                 DEBUG(5, ("delete_all_streams failed: %s\n",
1132                                           nt_errstr(status)));
1133                                 goto out;
1134                         }
1135                 }
1136
1137                 status = rmdir_internals(talloc_tos(), fsp);
1138
1139                 DEBUG(5,("close_directory: %s. Delete on close was set - "
1140                          "deleting directory returned %s.\n",
1141                          fsp_str_dbg(fsp), nt_errstr(status)));
1142
1143                 /* unbecome user. */
1144                 pop_sec_ctx();
1145
1146                 /*
1147                  * Ensure we remove any change notify requests that would
1148                  * now fail as the directory has been deleted.
1149                  */
1150
1151                 if(NT_STATUS_IS_OK(status)) {
1152                         remove_pending_change_notify_requests_by_fid(fsp, NT_STATUS_DELETE_PENDING);
1153                 }
1154         } else {
1155                 TALLOC_FREE(lck);
1156                 remove_pending_change_notify_requests_by_fid(
1157                         fsp, NT_STATUS_OK);
1158         }
1159
1160         status1 = fd_close(fsp);
1161
1162         if (!NT_STATUS_IS_OK(status1)) {
1163                 DEBUG(0, ("Could not close dir! fname=%s, fd=%d, err=%d=%s\n",
1164                           fsp_str_dbg(fsp), fsp->fh->fd, errno,
1165                           strerror(errno)));
1166         }
1167
1168         /*
1169          * Do the code common to files and directories.
1170          */
1171         close_filestruct(fsp);
1172         file_free(req, fsp);
1173
1174  out:
1175         TALLOC_FREE(lck);
1176         if (NT_STATUS_IS_OK(status) && !NT_STATUS_IS_OK(status1)) {
1177                 status = status1;
1178         }
1179         return status;
1180 }
1181
1182 /****************************************************************************
1183  Close a files_struct.
1184 ****************************************************************************/
1185   
1186 NTSTATUS close_file(struct smb_request *req, files_struct *fsp,
1187                     enum file_close_type close_type)
1188 {
1189         NTSTATUS status;
1190         struct files_struct *base_fsp = fsp->base_fsp;
1191
1192         if(fsp->is_directory) {
1193                 status = close_directory(req, fsp, close_type);
1194         } else if (fsp->fake_file_handle != NULL) {
1195                 status = close_fake_file(req, fsp);
1196         } else {
1197                 status = close_normal_file(req, fsp, close_type);
1198         }
1199
1200         if ((base_fsp != NULL) && (close_type != SHUTDOWN_CLOSE)) {
1201
1202                 /*
1203                  * fsp was a stream, the base fsp can't be a stream as well
1204                  *
1205                  * For SHUTDOWN_CLOSE this is not possible here, because
1206                  * SHUTDOWN_CLOSE only happens from files.c which walks the
1207                  * complete list of files. If we mess with more than one fsp
1208                  * those loops will become confused.
1209                  */
1210
1211                 SMB_ASSERT(base_fsp->base_fsp == NULL);
1212                 close_file(req, base_fsp, close_type);
1213         }
1214
1215         return status;
1216 }
1217
1218 /****************************************************************************
1219  Deal with an (authorized) message to close a file given the share mode
1220  entry.
1221 ****************************************************************************/
1222
1223 void msg_close_file(struct messaging_context *msg_ctx,
1224                         void *private_data,
1225                         uint32_t msg_type,
1226                         struct server_id server_id,
1227                         DATA_BLOB *data)
1228 {
1229         files_struct *fsp = NULL;
1230         struct share_mode_entry e;
1231         struct smbd_server_connection *sconn =
1232                 talloc_get_type_abort(private_data,
1233                 struct smbd_server_connection);
1234
1235         message_to_share_mode_entry(&e, (char *)data->data);
1236
1237         if(DEBUGLVL(10)) {
1238                 char *sm_str = share_mode_str(NULL, 0, &e);
1239                 if (!sm_str) {
1240                         smb_panic("talloc failed");
1241                 }
1242                 DEBUG(10,("msg_close_file: got request to close share mode "
1243                         "entry %s\n", sm_str));
1244                 TALLOC_FREE(sm_str);
1245         }
1246
1247         fsp = file_find_dif(sconn, e.id, e.share_file_id);
1248         if (!fsp) {
1249                 DEBUG(10,("msg_close_file: failed to find file.\n"));
1250                 return;
1251         }
1252         close_file(NULL, fsp, NORMAL_CLOSE);
1253 }