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