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