s3: Slightly simplify close_remove_share_mode
[Samba/id10ts.git] / source3 / smbd / close.c
blobe2d7c2c7a7b2ac4230c836ec9d629ee3d177ee0c
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
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.
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.
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/>.
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"
33 /****************************************************************************
34 Run a file if it is a magic script.
35 ****************************************************************************/
37 static NTSTATUS check_magic(struct files_struct *fsp)
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;
49 if (!*lp_magicscript(SNUM(conn))) {
50 return NT_STATUS_OK;
53 DEBUG(5,("checking magic for %s\n", fsp_str_dbg(fsp)));
55 ctx = talloc_stackframe();
57 fname = fsp->fsp_name->base_name;
59 if (!(p = strrchr_m(fname,'/'))) {
60 p = fname;
61 } else {
62 p++;
65 if (!strequal(lp_magicscript(SNUM(conn)),p)) {
66 status = NT_STATUS_OK;
67 goto out;
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);
77 if (!magic_output) {
78 status = NT_STATUS_NO_MEMORY;
79 goto out;
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;
89 if (chmod(fname, 0755) == -1) {
90 status = map_nt_error_from_unix(errno);
91 goto out;
93 ret = smbrun(p,&tmp_fd);
94 DEBUG(3,("Invoking magic command %s gave %d\n",
95 p,ret));
97 unlink(fname);
98 if (ret != 0 || tmp_fd == -1) {
99 if (tmp_fd != -1) {
100 close(tmp_fd);
102 status = NT_STATUS_UNSUCCESSFUL;
103 goto out;
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;
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;
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;
128 close(tmp_fd);
129 if (close(outfd) == -1) {
130 status = map_nt_error_from_unix(errno);
131 goto out;
134 status = NT_STATUS_OK;
136 out:
137 TALLOC_FREE(ctx);
138 return status;
141 /****************************************************************************
142 Common code to close a file or a directory.
143 ****************************************************************************/
145 static NTSTATUS close_filestruct(files_struct *fsp)
147 NTSTATUS status = NT_STATUS_OK;
149 if (fsp->fh->fd != -1) {
150 if(flush_write_cache(fsp, CLOSE_FLUSH) == -1) {
151 status = map_nt_error_from_unix(errno);
153 delete_write_cache(fsp);
156 return status;
159 static int compare_share_mode_times(const void *p1, const void *p2)
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);
166 /****************************************************************************
167 If any deferred opens are waiting on this close, notify them.
168 ****************************************************************************/
170 static void notify_deferred_opens(struct smbd_server_connection *sconn,
171 struct share_mode_lock *lck)
173 struct server_id self = messaging_server_id(sconn->msg_ctx);
174 uint32_t i, num_deferred;
175 struct share_mode_entry *deferred;
177 if (!should_notify_deferred_opens(sconn)) {
178 return;
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];
185 if (!is_deferred_open_entry(e)) {
186 continue;
188 if (share_mode_stale_pid(lck->data, i)) {
189 continue;
191 num_deferred += 1;
193 if (num_deferred == 0) {
194 return;
197 deferred = talloc_array(talloc_tos(), struct share_mode_entry,
198 num_deferred);
199 if (deferred == NULL) {
200 return;
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;
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.
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.
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.
229 qsort(deferred, num_deferred, sizeof(struct share_mode_entry),
230 compare_share_mode_times);
232 for (i=0; i<num_deferred; i++) {
233 struct share_mode_entry *e = &deferred[i];
235 if (procid_equal(&self, &e->pid)) {
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.
242 schedule_deferred_open_message_smb(sconn, e->op_mid);
243 } else {
244 char msg[MSG_SMB_SHARE_MODE_ENTRY_SIZE];
246 share_mode_entry_to_message(msg, e);
248 messaging_send_buf(sconn->msg_ctx, e->pid,
249 MSG_SMB_OPEN_RETRY,
250 (uint8 *)msg,
251 MSG_SMB_SHARE_MODE_ENTRY_SIZE);
254 TALLOC_FREE(deferred);
257 /****************************************************************************
258 Delete all streams
259 ****************************************************************************/
261 NTSTATUS delete_all_streams(connection_struct *conn, const char *fname)
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;
269 status = vfs_streaminfo(conn, NULL, fname, talloc_tos(),
270 &num_streams, &stream_info);
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;
278 if (!NT_STATUS_IS_OK(status)) {
279 DEBUG(10, ("vfs_streaminfo failed: %s\n",
280 nt_errstr(status)));
281 goto fail;
284 DEBUG(10, ("delete_all_streams found %d streams\n",
285 num_streams));
287 if (num_streams == 0) {
288 TALLOC_FREE(frame);
289 return NT_STATUS_OK;
292 for (i=0; i<num_streams; i++) {
293 int res;
294 struct smb_filename *smb_fname_stream = NULL;
296 if (strequal(stream_info[i].name, "::$DATA")) {
297 continue;
300 status = create_synthetic_smb_fname(talloc_tos(), fname,
301 stream_info[i].name, NULL,
302 &smb_fname_stream);
304 if (!NT_STATUS_IS_OK(status)) {
305 DEBUG(0, ("talloc_aprintf failed\n"));
306 goto fail;
309 res = SMB_VFS_UNLINK(conn, smb_fname_stream);
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;
319 TALLOC_FREE(smb_fname_stream);
322 fail:
323 TALLOC_FREE(frame);
324 return status;
327 /****************************************************************************
328 Deal with removing a share mode on last close.
329 ****************************************************************************/
331 static NTSTATUS close_remove_share_mode(files_struct *fsp,
332 enum file_close_type close_type)
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;
345 /* Ensure any pending write time updates are done. */
346 if (fsp->update_write_time_event) {
347 update_write_time_handler(fsp->conn->sconn->ev_ctx,
348 fsp->update_write_time_event,
349 timeval_current(),
350 (void *)fsp);
354 * Lock the share entries, and determine if we should delete
355 * on close. If so delete whilst the lock is still in effect.
356 * This prevents race conditions with the file being created. JRA.
359 lck = get_existing_share_mode_lock(talloc_tos(), fsp->file_id);
360 if (lck == NULL) {
361 DEBUG(0, ("close_remove_share_mode: Could not get share mode "
362 "lock for file %s\n", fsp_str_dbg(fsp)));
363 status = NT_STATUS_INVALID_PARAMETER;
364 goto done;
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);
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)));
395 if (fsp->initial_delete_on_close &&
396 !is_delete_on_close_set(lck, fsp->name_hash)) {
397 bool became_user = False;
399 /* Initial delete on close was set and no one else
400 * wrote a real delete on close. */
402 if (get_current_vuid(conn) != fsp->vuid) {
403 become_user(conn, fsp->vuid);
404 became_user = True;
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();
415 delete_file = is_delete_on_close_set(lck, fsp->name_hash);
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];
425 if (!is_valid_share_mode_entry(e)) {
426 continue;
428 if (e->name_hash != fsp->name_hash) {
429 continue;
431 if (fsp->posix_open
432 && (e->flags & SHARE_MODE_FLAG_POSIX_OPEN)) {
433 continue;
435 if (share_mode_stale_pid(lck->data, i)) {
436 continue;
438 delete_file = False;
439 break;
443 /* Notify any deferred opens waiting on this close. */
444 notify_deferred_opens(conn->sconn, lck);
445 reply_to_oplock_break_requests(fsp);
448 * NT can set delete_on_close of the last open
449 * reference to a file.
452 if (!(close_type == NORMAL_CLOSE || close_type == SHUTDOWN_CLOSE) ||
453 !delete_file) {
454 TALLOC_FREE(lck);
455 return NT_STATUS_OK;
459 * Ok, we have to delete the file
462 DEBUG(5,("close_remove_share_mode: file %s. Delete on close was set "
463 "- deleting file.\n", fsp_str_dbg(fsp)));
466 * Don't try to update the write time when we delete the file
468 fsp->update_write_time_on_close = false;
470 got_tokens = get_delete_on_close_token(lck, fsp->name_hash,
471 &del_nt_token, &del_token);
472 SMB_ASSERT(got_tokens);
474 if (!unix_token_equal(del_token, get_current_utok(conn))) {
475 /* Become the user who requested the delete. */
477 DEBUG(5,("close_remove_share_mode: file %s. "
478 "Change user to uid %u\n",
479 fsp_str_dbg(fsp),
480 (unsigned int)del_token->uid));
482 if (!push_sec_ctx()) {
483 smb_panic("close_remove_share_mode: file %s. failed to push "
484 "sec_ctx.\n");
487 set_sec_ctx(del_token->uid,
488 del_token->gid,
489 del_token->ngroups,
490 del_token->groups,
491 del_nt_token);
493 changed_user = true;
496 /* We can only delete the file if the name we have is still valid and
497 hasn't been renamed. */
499 tmp_status = vfs_stat_fsp(fsp);
500 if (!NT_STATUS_IS_OK(tmp_status)) {
501 DEBUG(5,("close_remove_share_mode: file %s. Delete on close "
502 "was set and stat failed with error %s\n",
503 fsp_str_dbg(fsp), nt_errstr(tmp_status)));
505 * Don't save the errno here, we ignore this error
507 goto done;
510 id = vfs_file_id_from_sbuf(conn, &fsp->fsp_name->st);
512 if (!file_id_equal(&fsp->file_id, &id)) {
513 DEBUG(5,("close_remove_share_mode: file %s. Delete on close "
514 "was set and dev and/or inode does not match\n",
515 fsp_str_dbg(fsp)));
516 DEBUG(5,("close_remove_share_mode: file %s. stored file_id %s, "
517 "stat file_id %s\n",
518 fsp_str_dbg(fsp),
519 file_id_string_tos(&fsp->file_id),
520 file_id_string_tos(&id)));
522 * Don't save the errno here, we ignore this error
524 goto done;
527 if ((conn->fs_capabilities & FILE_NAMED_STREAMS)
528 && !is_ntfs_stream_smb_fname(fsp->fsp_name)) {
530 status = delete_all_streams(conn, fsp->fsp_name->base_name);
532 if (!NT_STATUS_IS_OK(status)) {
533 DEBUG(5, ("delete_all_streams failed: %s\n",
534 nt_errstr(status)));
535 goto done;
540 if (SMB_VFS_UNLINK(conn, fsp->fsp_name) != 0) {
542 * This call can potentially fail as another smbd may
543 * have had the file open with delete on close set and
544 * deleted it when its last reference to this file
545 * went away. Hence we log this but not at debug level
546 * zero.
549 DEBUG(5,("close_remove_share_mode: file %s. Delete on close "
550 "was set and unlink failed with error %s\n",
551 fsp_str_dbg(fsp), strerror(errno)));
553 status = map_nt_error_from_unix(errno);
556 /* As we now have POSIX opens which can unlink
557 * with other open files we may have taken
558 * this code path with more than one share mode
559 * entry - ensure we only delete once by resetting
560 * the delete on close flag. JRA.
563 fsp->delete_on_close = false;
564 set_delete_on_close_lck(fsp, lck, false, NULL, NULL);
566 done:
568 if (changed_user) {
569 /* unbecome user. */
570 pop_sec_ctx();
573 TALLOC_FREE(lck);
575 if (delete_file) {
577 * Do the notification after we released the share
578 * mode lock. Inside notify_fname we take out another
579 * tdb lock. With ctdb also accessing our databases,
580 * this can lead to deadlocks. Putting this notify
581 * after the TALLOC_FREE(lck) above we avoid locking
582 * two records simultaneously. Notifies are async and
583 * informational only, so calling the notify_fname
584 * without holding the share mode lock should not do
585 * any harm.
587 notify_fname(conn, NOTIFY_ACTION_REMOVED,
588 FILE_NOTIFY_CHANGE_FILE_NAME,
589 fsp->fsp_name->base_name);
592 return status;
595 void set_close_write_time(struct files_struct *fsp, struct timespec ts)
597 DEBUG(6,("close_write_time: %s" , time_to_asc(convert_timespec_to_time_t(ts))));
599 if (null_timespec(ts)) {
600 return;
602 fsp->write_time_forced = false;
603 fsp->update_write_time_on_close = true;
604 fsp->close_write_time = ts;
607 static NTSTATUS update_write_time_on_close(struct files_struct *fsp)
609 struct smb_file_time ft;
610 NTSTATUS status;
611 struct share_mode_lock *lck = NULL;
613 ZERO_STRUCT(ft);
615 if (!fsp->update_write_time_on_close) {
616 return NT_STATUS_OK;
619 if (null_timespec(fsp->close_write_time)) {
620 fsp->close_write_time = timespec_current();
623 /* Ensure we have a valid stat struct for the source. */
624 status = vfs_stat_fsp(fsp);
625 if (!NT_STATUS_IS_OK(status)) {
626 return status;
629 if (!VALID_STAT(fsp->fsp_name->st)) {
630 /* if it doesn't seem to be a real file */
631 return NT_STATUS_OK;
635 * get_existing_share_mode_lock() isn't really the right
636 * call here, as we're being called after
637 * close_remove_share_mode() inside close_normal_file()
638 * so it's quite normal to not have an existing share
639 * mode here. However, get_share_mode_lock() doesn't
640 * work because that will create a new share mode if
641 * one doesn't exist - so stick with this call (just
642 * ignore any error we get if the share mode doesn't
643 * exist.
646 lck = get_existing_share_mode_lock(talloc_tos(), fsp->file_id);
647 if (lck) {
648 /* On close if we're changing the real file time we
649 * must update it in the open file db too. */
650 (void)set_write_time(fsp->file_id, fsp->close_write_time);
652 /* Close write times overwrite sticky write times
653 so we must replace any sticky write time here. */
654 if (!null_timespec(lck->data->changed_write_time)) {
655 (void)set_sticky_write_time(fsp->file_id, fsp->close_write_time);
657 TALLOC_FREE(lck);
660 ft.mtime = fsp->close_write_time;
661 /* As this is a close based update, we are not directly changing the
662 file attributes from a client call, but indirectly from a write. */
663 status = smb_set_file_time(fsp->conn, fsp, fsp->fsp_name, &ft, false);
664 if (!NT_STATUS_IS_OK(status)) {
665 DEBUG(10,("update_write_time_on_close: smb_set_file_time "
666 "on file %s returned %s\n",
667 fsp_str_dbg(fsp),
668 nt_errstr(status)));
669 return status;
672 return status;
675 static NTSTATUS ntstatus_keeperror(NTSTATUS s1, NTSTATUS s2)
677 if (!NT_STATUS_IS_OK(s1)) {
678 return s1;
680 return s2;
683 /****************************************************************************
684 Close a file.
686 close_type can be NORMAL_CLOSE=0,SHUTDOWN_CLOSE,ERROR_CLOSE.
687 printing and magic scripts are only run on normal close.
688 delete on close is done on normal and shutdown close.
689 ****************************************************************************/
691 static NTSTATUS close_normal_file(struct smb_request *req, files_struct *fsp,
692 enum file_close_type close_type)
694 NTSTATUS status = NT_STATUS_OK;
695 NTSTATUS tmp;
696 connection_struct *conn = fsp->conn;
697 int ret;
700 * If we're finishing async io on a close we can get a write
701 * error here, we must remember this.
703 ret = wait_for_aio_completion(fsp);
704 if (ret) {
705 status = ntstatus_keeperror(
706 status, map_nt_error_from_unix(ret));
710 * If we're flushing on a close we can get a write
711 * error here, we must remember this.
714 tmp = close_filestruct(fsp);
715 status = ntstatus_keeperror(status, tmp);
717 if (fsp->print_file) {
718 /* FIXME: return spool errors */
719 print_spool_end(fsp, close_type);
720 file_free(req, fsp);
721 return NT_STATUS_OK;
724 /* Remove the oplock before potentially deleting the file. */
725 if(fsp->oplock_type) {
726 release_file_oplock(fsp);
729 /* If this is an old DOS or FCB open and we have multiple opens on
730 the same handle we only have one share mode. Ensure we only remove
731 the share mode on the last close. */
733 if (fsp->fh->ref_count == 1) {
734 /* Should we return on error here... ? */
735 tmp = close_remove_share_mode(fsp, close_type);
736 status = ntstatus_keeperror(status, tmp);
739 locking_close_file(conn->sconn->msg_ctx, fsp, close_type);
741 tmp = fd_close(fsp);
742 status = ntstatus_keeperror(status, tmp);
744 /* check for magic scripts */
745 if (close_type == NORMAL_CLOSE) {
746 tmp = check_magic(fsp);
747 status = ntstatus_keeperror(status, tmp);
751 * Ensure pending modtime is set after close.
754 tmp = update_write_time_on_close(fsp);
755 if (NT_STATUS_EQUAL(tmp, NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
756 /* Someone renamed the file or a parent directory containing
757 * this file. We can't do anything about this, we don't have
758 * an "update timestamp by fd" call in POSIX. Eat the error. */
760 tmp = NT_STATUS_OK;
763 status = ntstatus_keeperror(status, tmp);
765 DEBUG(2,("%s closed file %s (numopen=%d) %s\n",
766 conn->session_info->unix_info->unix_name, fsp_str_dbg(fsp),
767 conn->num_files_open - 1,
768 nt_errstr(status) ));
770 file_free(req, fsp);
771 return status;
773 /****************************************************************************
774 Static function used by reply_rmdir to delete an entire directory
775 tree recursively. Return True on ok, False on fail.
776 ****************************************************************************/
778 static bool recursive_rmdir(TALLOC_CTX *ctx,
779 connection_struct *conn,
780 struct smb_filename *smb_dname)
782 const char *dname = NULL;
783 char *talloced = NULL;
784 bool ret = True;
785 long offset = 0;
786 SMB_STRUCT_STAT st;
787 struct smb_Dir *dir_hnd;
789 SMB_ASSERT(!is_ntfs_stream_smb_fname(smb_dname));
791 dir_hnd = OpenDir(talloc_tos(), conn, smb_dname->base_name, NULL, 0);
792 if(dir_hnd == NULL)
793 return False;
795 while((dname = ReadDirName(dir_hnd, &offset, &st, &talloced))) {
796 struct smb_filename *smb_dname_full = NULL;
797 char *fullname = NULL;
798 bool do_break = true;
799 NTSTATUS status;
801 if (ISDOT(dname) || ISDOTDOT(dname)) {
802 TALLOC_FREE(talloced);
803 continue;
806 if (!is_visible_file(conn, smb_dname->base_name, dname, &st,
807 false)) {
808 TALLOC_FREE(talloced);
809 continue;
812 /* Construct the full name. */
813 fullname = talloc_asprintf(ctx,
814 "%s/%s",
815 smb_dname->base_name,
816 dname);
817 if (!fullname) {
818 errno = ENOMEM;
819 goto err_break;
822 status = create_synthetic_smb_fname(talloc_tos(), fullname,
823 NULL, NULL,
824 &smb_dname_full);
825 if (!NT_STATUS_IS_OK(status)) {
826 goto err_break;
829 if(SMB_VFS_LSTAT(conn, smb_dname_full) != 0) {
830 goto err_break;
833 if(smb_dname_full->st.st_ex_mode & S_IFDIR) {
834 if(!recursive_rmdir(ctx, conn, smb_dname_full)) {
835 goto err_break;
837 if(SMB_VFS_RMDIR(conn,
838 smb_dname_full->base_name) != 0) {
839 goto err_break;
841 } else if(SMB_VFS_UNLINK(conn, smb_dname_full) != 0) {
842 goto err_break;
845 /* Successful iteration. */
846 do_break = false;
848 err_break:
849 TALLOC_FREE(smb_dname_full);
850 TALLOC_FREE(fullname);
851 TALLOC_FREE(talloced);
852 if (do_break) {
853 ret = false;
854 break;
857 TALLOC_FREE(dir_hnd);
858 return ret;
861 /****************************************************************************
862 The internals of the rmdir code - called elsewhere.
863 ****************************************************************************/
865 static NTSTATUS rmdir_internals(TALLOC_CTX *ctx, files_struct *fsp)
867 connection_struct *conn = fsp->conn;
868 struct smb_filename *smb_dname = fsp->fsp_name;
869 int ret;
871 SMB_ASSERT(!is_ntfs_stream_smb_fname(smb_dname));
873 /* Might be a symlink. */
874 if(SMB_VFS_LSTAT(conn, smb_dname) != 0) {
875 return map_nt_error_from_unix(errno);
878 if (S_ISLNK(smb_dname->st.st_ex_mode)) {
879 /* Is what it points to a directory ? */
880 if(SMB_VFS_STAT(conn, smb_dname) != 0) {
881 return map_nt_error_from_unix(errno);
883 if (!(S_ISDIR(smb_dname->st.st_ex_mode))) {
884 return NT_STATUS_NOT_A_DIRECTORY;
886 ret = SMB_VFS_UNLINK(conn, smb_dname);
887 } else {
888 ret = SMB_VFS_RMDIR(conn, smb_dname->base_name);
890 if (ret == 0) {
891 notify_fname(conn, NOTIFY_ACTION_REMOVED,
892 FILE_NOTIFY_CHANGE_DIR_NAME,
893 smb_dname->base_name);
894 return NT_STATUS_OK;
897 if(((errno == ENOTEMPTY)||(errno == EEXIST)) && *lp_veto_files(SNUM(conn))) {
899 * Check to see if the only thing in this directory are
900 * vetoed files/directories. If so then delete them and
901 * retry. If we fail to delete any of them (and we *don't*
902 * do a recursive delete) then fail the rmdir.
904 SMB_STRUCT_STAT st;
905 const char *dname = NULL;
906 char *talloced = NULL;
907 long dirpos = 0;
908 struct smb_Dir *dir_hnd = OpenDir(talloc_tos(), conn,
909 smb_dname->base_name, NULL,
912 if(dir_hnd == NULL) {
913 errno = ENOTEMPTY;
914 goto err;
917 while ((dname = ReadDirName(dir_hnd, &dirpos, &st,
918 &talloced)) != NULL) {
919 if((strcmp(dname, ".") == 0) || (strcmp(dname, "..")==0)) {
920 TALLOC_FREE(talloced);
921 continue;
923 if (!is_visible_file(conn, smb_dname->base_name, dname,
924 &st, false)) {
925 TALLOC_FREE(talloced);
926 continue;
928 if(!IS_VETO_PATH(conn, dname)) {
929 TALLOC_FREE(dir_hnd);
930 TALLOC_FREE(talloced);
931 errno = ENOTEMPTY;
932 goto err;
934 TALLOC_FREE(talloced);
937 /* We only have veto files/directories.
938 * Are we allowed to delete them ? */
940 if(!lp_recursive_veto_delete(SNUM(conn))) {
941 TALLOC_FREE(dir_hnd);
942 errno = ENOTEMPTY;
943 goto err;
946 /* Do a recursive delete. */
947 RewindDir(dir_hnd,&dirpos);
948 while ((dname = ReadDirName(dir_hnd, &dirpos, &st,
949 &talloced)) != NULL) {
950 struct smb_filename *smb_dname_full = NULL;
951 char *fullname = NULL;
952 bool do_break = true;
953 NTSTATUS status;
955 if (ISDOT(dname) || ISDOTDOT(dname)) {
956 TALLOC_FREE(talloced);
957 continue;
959 if (!is_visible_file(conn, smb_dname->base_name, dname,
960 &st, false)) {
961 TALLOC_FREE(talloced);
962 continue;
965 fullname = talloc_asprintf(ctx,
966 "%s/%s",
967 smb_dname->base_name,
968 dname);
970 if(!fullname) {
971 errno = ENOMEM;
972 goto err_break;
975 status = create_synthetic_smb_fname(talloc_tos(),
976 fullname, NULL,
977 NULL,
978 &smb_dname_full);
979 if (!NT_STATUS_IS_OK(status)) {
980 errno = map_errno_from_nt_status(status);
981 goto err_break;
984 if(SMB_VFS_LSTAT(conn, smb_dname_full) != 0) {
985 goto err_break;
987 if(smb_dname_full->st.st_ex_mode & S_IFDIR) {
988 if(!recursive_rmdir(ctx, conn,
989 smb_dname_full)) {
990 goto err_break;
992 if(SMB_VFS_RMDIR(conn,
993 smb_dname_full->base_name) != 0) {
994 goto err_break;
996 } else if(SMB_VFS_UNLINK(conn, smb_dname_full) != 0) {
997 goto err_break;
1000 /* Successful iteration. */
1001 do_break = false;
1003 err_break:
1004 TALLOC_FREE(fullname);
1005 TALLOC_FREE(smb_dname_full);
1006 TALLOC_FREE(talloced);
1007 if (do_break)
1008 break;
1010 TALLOC_FREE(dir_hnd);
1011 /* Retry the rmdir */
1012 ret = SMB_VFS_RMDIR(conn, smb_dname->base_name);
1015 err:
1017 if (ret != 0) {
1018 DEBUG(3,("rmdir_internals: couldn't remove directory %s : "
1019 "%s\n", smb_fname_str_dbg(smb_dname),
1020 strerror(errno)));
1021 return map_nt_error_from_unix(errno);
1024 notify_fname(conn, NOTIFY_ACTION_REMOVED,
1025 FILE_NOTIFY_CHANGE_DIR_NAME,
1026 smb_dname->base_name);
1028 return NT_STATUS_OK;
1031 /****************************************************************************
1032 Close a directory opened by an NT SMB call.
1033 ****************************************************************************/
1035 static NTSTATUS close_directory(struct smb_request *req, files_struct *fsp,
1036 enum file_close_type close_type)
1038 struct share_mode_lock *lck = NULL;
1039 bool delete_dir = False;
1040 NTSTATUS status = NT_STATUS_OK;
1041 NTSTATUS status1 = NT_STATUS_OK;
1042 const struct security_token *del_nt_token = NULL;
1043 const struct security_unix_token *del_token = NULL;
1046 * NT can set delete_on_close of the last open
1047 * reference to a directory also.
1050 lck = get_existing_share_mode_lock(talloc_tos(), fsp->file_id);
1051 if (lck == NULL) {
1052 DEBUG(0, ("close_directory: Could not get share mode lock for "
1053 "%s\n", fsp_str_dbg(fsp)));
1054 status = NT_STATUS_INVALID_PARAMETER;
1055 goto out;
1058 if (!del_share_mode(lck, fsp)) {
1059 DEBUG(0, ("close_directory: Could not delete share entry for "
1060 "%s\n", fsp_str_dbg(fsp)));
1063 if (fsp->initial_delete_on_close) {
1064 bool became_user = False;
1066 /* Initial delete on close was set - for
1067 * directories we don't care if anyone else
1068 * wrote a real delete on close. */
1070 if (get_current_vuid(fsp->conn) != fsp->vuid) {
1071 become_user(fsp->conn, fsp->vuid);
1072 became_user = True;
1074 send_stat_cache_delete_message(fsp->conn->sconn->msg_ctx,
1075 fsp->fsp_name->base_name);
1076 set_delete_on_close_lck(fsp, lck, true,
1077 get_current_nttok(fsp->conn),
1078 get_current_utok(fsp->conn));
1079 fsp->delete_on_close = true;
1080 if (became_user) {
1081 unbecome_user();
1085 delete_dir = get_delete_on_close_token(lck, fsp->name_hash,
1086 &del_nt_token, &del_token);
1088 if (delete_dir) {
1089 int i;
1090 /* See if others still have the dir open. If this is the
1091 * case, then don't delete. If all opens are POSIX delete now. */
1092 for (i=0; i<lck->data->num_share_modes; i++) {
1093 struct share_mode_entry *e = &lck->data->share_modes[i];
1094 if (is_valid_share_mode_entry(e) &&
1095 e->name_hash == fsp->name_hash) {
1096 if (fsp->posix_open && (e->flags & SHARE_MODE_FLAG_POSIX_OPEN)) {
1097 continue;
1099 if (share_mode_stale_pid(lck->data, i)) {
1100 continue;
1102 delete_dir = False;
1103 break;
1108 if ((close_type == NORMAL_CLOSE || close_type == SHUTDOWN_CLOSE) &&
1109 delete_dir) {
1111 /* Become the user who requested the delete. */
1113 if (!push_sec_ctx()) {
1114 smb_panic("close_directory: failed to push sec_ctx.\n");
1117 set_sec_ctx(del_token->uid,
1118 del_token->gid,
1119 del_token->ngroups,
1120 del_token->groups,
1121 del_nt_token);
1123 TALLOC_FREE(lck);
1125 if ((fsp->conn->fs_capabilities & FILE_NAMED_STREAMS)
1126 && !is_ntfs_stream_smb_fname(fsp->fsp_name)) {
1128 status = delete_all_streams(fsp->conn, fsp->fsp_name->base_name);
1129 if (!NT_STATUS_IS_OK(status)) {
1130 DEBUG(5, ("delete_all_streams failed: %s\n",
1131 nt_errstr(status)));
1132 goto out;
1136 status = rmdir_internals(talloc_tos(), fsp);
1138 DEBUG(5,("close_directory: %s. Delete on close was set - "
1139 "deleting directory returned %s.\n",
1140 fsp_str_dbg(fsp), nt_errstr(status)));
1142 /* unbecome user. */
1143 pop_sec_ctx();
1146 * Ensure we remove any change notify requests that would
1147 * now fail as the directory has been deleted.
1150 if(NT_STATUS_IS_OK(status)) {
1151 remove_pending_change_notify_requests_by_fid(fsp, NT_STATUS_DELETE_PENDING);
1153 } else {
1154 TALLOC_FREE(lck);
1155 remove_pending_change_notify_requests_by_fid(
1156 fsp, NT_STATUS_OK);
1159 status1 = fd_close(fsp);
1161 if (!NT_STATUS_IS_OK(status1)) {
1162 DEBUG(0, ("Could not close dir! fname=%s, fd=%d, err=%d=%s\n",
1163 fsp_str_dbg(fsp), fsp->fh->fd, errno,
1164 strerror(errno)));
1168 * Do the code common to files and directories.
1170 close_filestruct(fsp);
1171 file_free(req, fsp);
1173 out:
1174 TALLOC_FREE(lck);
1175 if (NT_STATUS_IS_OK(status) && !NT_STATUS_IS_OK(status1)) {
1176 status = status1;
1178 return status;
1181 /****************************************************************************
1182 Close a files_struct.
1183 ****************************************************************************/
1185 NTSTATUS close_file(struct smb_request *req, files_struct *fsp,
1186 enum file_close_type close_type)
1188 NTSTATUS status;
1189 struct files_struct *base_fsp = fsp->base_fsp;
1191 if(fsp->is_directory) {
1192 status = close_directory(req, fsp, close_type);
1193 } else if (fsp->fake_file_handle != NULL) {
1194 status = close_fake_file(req, fsp);
1195 } else {
1196 status = close_normal_file(req, fsp, close_type);
1199 if ((base_fsp != NULL) && (close_type != SHUTDOWN_CLOSE)) {
1202 * fsp was a stream, the base fsp can't be a stream as well
1204 * For SHUTDOWN_CLOSE this is not possible here, because
1205 * SHUTDOWN_CLOSE only happens from files.c which walks the
1206 * complete list of files. If we mess with more than one fsp
1207 * those loops will become confused.
1210 SMB_ASSERT(base_fsp->base_fsp == NULL);
1211 close_file(req, base_fsp, close_type);
1214 return status;
1217 /****************************************************************************
1218 Deal with an (authorized) message to close a file given the share mode
1219 entry.
1220 ****************************************************************************/
1222 void msg_close_file(struct messaging_context *msg_ctx,
1223 void *private_data,
1224 uint32_t msg_type,
1225 struct server_id server_id,
1226 DATA_BLOB *data)
1228 files_struct *fsp = NULL;
1229 struct share_mode_entry e;
1230 struct smbd_server_connection *sconn =
1231 talloc_get_type_abort(private_data,
1232 struct smbd_server_connection);
1234 message_to_share_mode_entry(&e, (char *)data->data);
1236 if(DEBUGLVL(10)) {
1237 char *sm_str = share_mode_str(NULL, 0, &e);
1238 if (!sm_str) {
1239 smb_panic("talloc failed");
1241 DEBUG(10,("msg_close_file: got request to close share mode "
1242 "entry %s\n", sm_str));
1243 TALLOC_FREE(sm_str);
1246 fsp = file_find_dif(sconn, e.id, e.share_file_id);
1247 if (!fsp) {
1248 DEBUG(10,("msg_close_file: failed to find file.\n"));
1249 return;
1251 close_file(NULL, fsp, NORMAL_CLOSE);