smbd: Use share_mode_forall_entries() in has_other_nonposix_opens_fn()
[Samba.git] / source3 / smbd / close.c
blob5b29d3477327b09581b3371930f27fc5153d2cdf
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 "lib/util/server_id.h"
25 #include "printing.h"
26 #include "smbd/smbd.h"
27 #include "smbd/globals.h"
28 #include "smbd/scavenger.h"
29 #include "fake_file.h"
30 #include "transfer_file.h"
31 #include "auth.h"
32 #include "messages.h"
33 #include "../librpc/gen_ndr/open_files.h"
35 /****************************************************************************
36 Run a file if it is a magic script.
37 ****************************************************************************/
39 static NTSTATUS check_magic(struct files_struct *fsp)
41 int ret;
42 const char *magic_output = NULL;
43 SMB_STRUCT_STAT st;
44 int tmp_fd, outfd;
45 TALLOC_CTX *ctx = NULL;
46 const char *p;
47 struct connection_struct *conn = fsp->conn;
48 char *fname = NULL;
49 NTSTATUS status;
51 if (!*lp_magic_script(talloc_tos(), SNUM(conn))) {
52 return NT_STATUS_OK;
55 DEBUG(5,("checking magic for %s\n", fsp_str_dbg(fsp)));
57 ctx = talloc_stackframe();
59 fname = fsp->fsp_name->base_name;
61 if (!(p = strrchr_m(fname,'/'))) {
62 p = fname;
63 } else {
64 p++;
67 if (!strequal(lp_magic_script(talloc_tos(), SNUM(conn)),p)) {
68 status = NT_STATUS_OK;
69 goto out;
72 if (*lp_magic_output(talloc_tos(), SNUM(conn))) {
73 magic_output = lp_magic_output(talloc_tos(), SNUM(conn));
74 } else {
75 magic_output = talloc_asprintf(ctx,
76 "%s.out",
77 fname);
79 if (!magic_output) {
80 status = NT_STATUS_NO_MEMORY;
81 goto out;
84 /* Ensure we don't depend on user's PATH. */
85 p = talloc_asprintf(ctx, "./%s", fname);
86 if (!p) {
87 status = NT_STATUS_NO_MEMORY;
88 goto out;
91 if (chmod(fname, 0755) == -1) {
92 status = map_nt_error_from_unix(errno);
93 goto out;
95 ret = smbrun(p, &tmp_fd, NULL);
96 DEBUG(3,("Invoking magic command %s gave %d\n",
97 p,ret));
99 unlink(fname);
100 if (ret != 0 || tmp_fd == -1) {
101 if (tmp_fd != -1) {
102 close(tmp_fd);
104 status = NT_STATUS_UNSUCCESSFUL;
105 goto out;
107 outfd = open(magic_output, O_CREAT|O_EXCL|O_RDWR, 0600);
108 if (outfd == -1) {
109 int err = errno;
110 close(tmp_fd);
111 status = map_nt_error_from_unix(err);
112 goto out;
115 if (sys_fstat(tmp_fd, &st, false) == -1) {
116 int err = errno;
117 close(tmp_fd);
118 close(outfd);
119 status = map_nt_error_from_unix(err);
120 goto out;
123 if (transfer_file(tmp_fd,outfd,(off_t)st.st_ex_size) == (off_t)-1) {
124 int err = errno;
125 close(tmp_fd);
126 close(outfd);
127 status = map_nt_error_from_unix(err);
128 goto out;
130 close(tmp_fd);
131 if (close(outfd) == -1) {
132 status = map_nt_error_from_unix(errno);
133 goto out;
136 status = NT_STATUS_OK;
138 out:
139 TALLOC_FREE(ctx);
140 return status;
143 /****************************************************************************
144 Common code to close a file or a directory.
145 ****************************************************************************/
147 static NTSTATUS close_filestruct(files_struct *fsp)
149 NTSTATUS status = NT_STATUS_OK;
151 if (fsp->fh->fd != -1) {
152 if(flush_write_cache(fsp, SAMBA_CLOSE_FLUSH) == -1) {
153 status = map_nt_error_from_unix(errno);
155 delete_write_cache(fsp);
158 return status;
161 /****************************************************************************
162 Delete all streams
163 ****************************************************************************/
165 NTSTATUS delete_all_streams(connection_struct *conn,
166 const struct smb_filename *smb_fname)
168 struct stream_struct *stream_info = NULL;
169 unsigned int i;
170 unsigned int num_streams = 0;
171 TALLOC_CTX *frame = talloc_stackframe();
172 NTSTATUS status;
174 status = vfs_streaminfo(conn, NULL, smb_fname, talloc_tos(),
175 &num_streams, &stream_info);
177 if (NT_STATUS_EQUAL(status, NT_STATUS_NOT_IMPLEMENTED)) {
178 DEBUG(10, ("no streams around\n"));
179 TALLOC_FREE(frame);
180 return NT_STATUS_OK;
183 if (!NT_STATUS_IS_OK(status)) {
184 DEBUG(10, ("vfs_streaminfo failed: %s\n",
185 nt_errstr(status)));
186 goto fail;
189 DEBUG(10, ("delete_all_streams found %d streams\n",
190 num_streams));
192 if (num_streams == 0) {
193 TALLOC_FREE(frame);
194 return NT_STATUS_OK;
197 for (i=0; i<num_streams; i++) {
198 int res;
199 struct smb_filename *smb_fname_stream;
201 if (strequal(stream_info[i].name, "::$DATA")) {
202 continue;
205 smb_fname_stream = synthetic_smb_fname(talloc_tos(),
206 smb_fname->base_name,
207 stream_info[i].name,
208 NULL,
209 (smb_fname->flags &
210 ~SMB_FILENAME_POSIX_PATH));
212 if (smb_fname_stream == NULL) {
213 DEBUG(0, ("talloc_aprintf failed\n"));
214 status = NT_STATUS_NO_MEMORY;
215 goto fail;
218 res = SMB_VFS_UNLINK(conn, smb_fname_stream);
220 if (res == -1) {
221 status = map_nt_error_from_unix(errno);
222 DEBUG(10, ("Could not delete stream %s: %s\n",
223 smb_fname_str_dbg(smb_fname_stream),
224 strerror(errno)));
225 TALLOC_FREE(smb_fname_stream);
226 break;
228 TALLOC_FREE(smb_fname_stream);
231 fail:
232 TALLOC_FREE(frame);
233 return status;
236 struct has_other_nonposix_opens_state {
237 files_struct *fsp;
238 bool found_another;
241 static bool has_other_nonposix_opens_fn(
242 struct share_mode_entry *e,
243 bool *modified,
244 void *private_data)
246 struct has_other_nonposix_opens_state *state = private_data;
247 struct files_struct *fsp = state->fsp;
249 if (e->name_hash != fsp->name_hash) {
250 return false;
252 if ((fsp->posix_flags & FSP_POSIX_FLAGS_OPEN) &&
253 (e->flags & SHARE_MODE_FLAG_POSIX_OPEN)) {
254 return false;
256 if (e->share_file_id == fsp->fh->gen_id) {
257 struct server_id self = messaging_server_id(
258 fsp->conn->sconn->msg_ctx);
259 if (server_id_equal(&self, &e->pid)) {
260 return false;
263 if (share_entry_stale_pid(e)) {
264 return false;
267 state->found_another = true;
268 return true;
271 bool has_other_nonposix_opens(struct share_mode_lock *lck,
272 struct files_struct *fsp)
274 struct has_other_nonposix_opens_state state = { .fsp = fsp };
275 bool ok;
277 ok = share_mode_forall_entries(
278 lck, has_other_nonposix_opens_fn, &state);
279 if (!ok) {
280 return false;
282 return state.found_another;
285 /****************************************************************************
286 Deal with removing a share mode on last close.
287 ****************************************************************************/
289 static NTSTATUS close_remove_share_mode(files_struct *fsp,
290 enum file_close_type close_type)
292 connection_struct *conn = fsp->conn;
293 bool delete_file = false;
294 bool changed_user = false;
295 struct share_mode_lock *lck = NULL;
296 NTSTATUS status = NT_STATUS_OK;
297 NTSTATUS tmp_status;
298 struct file_id id;
299 const struct security_unix_token *del_token = NULL;
300 const struct security_token *del_nt_token = NULL;
301 bool got_tokens = false;
302 bool normal_close;
304 /* Ensure any pending write time updates are done. */
305 if (fsp->update_write_time_event) {
306 fsp_flush_write_time_update(fsp);
310 * Lock the share entries, and determine if we should delete
311 * on close. If so delete whilst the lock is still in effect.
312 * This prevents race conditions with the file being created. JRA.
315 lck = get_existing_share_mode_lock(talloc_tos(), fsp->file_id);
316 if (lck == NULL) {
317 DEBUG(0, ("close_remove_share_mode: Could not get share mode "
318 "lock for file %s\n", fsp_str_dbg(fsp)));
319 return NT_STATUS_INVALID_PARAMETER;
322 /* Remove the oplock before potentially deleting the file. */
323 if(fsp->oplock_type) {
324 remove_oplock(fsp);
327 if (fsp->write_time_forced) {
328 DEBUG(10,("close_remove_share_mode: write time forced "
329 "for file %s\n",
330 fsp_str_dbg(fsp)));
331 set_close_write_time(fsp, lck->data->changed_write_time);
332 } else if (fsp->update_write_time_on_close) {
333 /* Someone had a pending write. */
334 if (null_timespec(fsp->close_write_time)) {
335 DEBUG(10,("close_remove_share_mode: update to current time "
336 "for file %s\n",
337 fsp_str_dbg(fsp)));
338 /* Update to current time due to "normal" write. */
339 set_close_write_time(fsp, timespec_current());
340 } else {
341 DEBUG(10,("close_remove_share_mode: write time pending "
342 "for file %s\n",
343 fsp_str_dbg(fsp)));
344 /* Update to time set on close call. */
345 set_close_write_time(fsp, fsp->close_write_time);
349 if (fsp->initial_delete_on_close &&
350 !is_delete_on_close_set(lck, fsp->name_hash)) {
351 bool became_user = False;
353 /* Initial delete on close was set and no one else
354 * wrote a real delete on close. */
356 if (get_current_vuid(conn) != fsp->vuid) {
357 become_user_without_service(conn, fsp->vuid);
358 became_user = True;
360 fsp->delete_on_close = true;
361 set_delete_on_close_lck(fsp, lck,
362 get_current_nttok(conn),
363 get_current_utok(conn));
364 if (became_user) {
365 unbecome_user_without_service();
369 delete_file = is_delete_on_close_set(lck, fsp->name_hash) &&
370 !has_other_nonposix_opens(lck, fsp);
373 * NT can set delete_on_close of the last open
374 * reference to a file.
377 normal_close = (close_type == NORMAL_CLOSE || close_type == SHUTDOWN_CLOSE);
379 if (!normal_close || !delete_file) {
380 status = NT_STATUS_OK;
381 goto done;
385 * Ok, we have to delete the file
388 DEBUG(5,("close_remove_share_mode: file %s. Delete on close was set "
389 "- deleting file.\n", fsp_str_dbg(fsp)));
392 * Don't try to update the write time when we delete the file
394 fsp->update_write_time_on_close = false;
396 got_tokens = get_delete_on_close_token(lck, fsp->name_hash,
397 &del_nt_token, &del_token);
398 SMB_ASSERT(got_tokens);
400 if (!unix_token_equal(del_token, get_current_utok(conn))) {
401 /* Become the user who requested the delete. */
403 DEBUG(5,("close_remove_share_mode: file %s. "
404 "Change user to uid %u\n",
405 fsp_str_dbg(fsp),
406 (unsigned int)del_token->uid));
408 if (!push_sec_ctx()) {
409 smb_panic("close_remove_share_mode: file %s. failed to push "
410 "sec_ctx.\n");
413 set_sec_ctx(del_token->uid,
414 del_token->gid,
415 del_token->ngroups,
416 del_token->groups,
417 del_nt_token);
419 changed_user = true;
422 /* We can only delete the file if the name we have is still valid and
423 hasn't been renamed. */
425 tmp_status = vfs_stat_fsp(fsp);
426 if (!NT_STATUS_IS_OK(tmp_status)) {
427 DEBUG(5,("close_remove_share_mode: file %s. Delete on close "
428 "was set and stat failed with error %s\n",
429 fsp_str_dbg(fsp), nt_errstr(tmp_status)));
431 * Don't save the errno here, we ignore this error
433 goto done;
436 id = vfs_file_id_from_sbuf(conn, &fsp->fsp_name->st);
438 if (!file_id_equal(&fsp->file_id, &id)) {
439 struct file_id_buf ftmp1, ftmp2;
440 DEBUG(5,("close_remove_share_mode: file %s. Delete on close "
441 "was set and dev and/or inode does not match\n",
442 fsp_str_dbg(fsp)));
443 DEBUG(5,("close_remove_share_mode: file %s. stored file_id %s, "
444 "stat file_id %s\n",
445 fsp_str_dbg(fsp),
446 file_id_str_buf(fsp->file_id, &ftmp1),
447 file_id_str_buf(id, &ftmp2)));
449 * Don't save the errno here, we ignore this error
451 goto done;
454 if ((conn->fs_capabilities & FILE_NAMED_STREAMS)
455 && !is_ntfs_stream_smb_fname(fsp->fsp_name)) {
457 status = delete_all_streams(conn, fsp->fsp_name);
459 if (!NT_STATUS_IS_OK(status)) {
460 DEBUG(5, ("delete_all_streams failed: %s\n",
461 nt_errstr(status)));
462 goto done;
466 if (fsp->kernel_share_modes_taken) {
467 int ret_flock;
470 * A file system sharemode could block the unlink;
471 * remove filesystem sharemodes first.
473 ret_flock = SMB_VFS_KERNEL_FLOCK(fsp, 0, 0);
474 if (ret_flock == -1) {
475 DBG_INFO("removing kernel flock for %s failed: %s\n",
476 fsp_str_dbg(fsp), strerror(errno));
479 fsp->kernel_share_modes_taken = false;
483 if (SMB_VFS_UNLINK(conn, fsp->fsp_name) != 0) {
485 * This call can potentially fail as another smbd may
486 * have had the file open with delete on close set and
487 * deleted it when its last reference to this file
488 * went away. Hence we log this but not at debug level
489 * zero.
492 DEBUG(5,("close_remove_share_mode: file %s. Delete on close "
493 "was set and unlink failed with error %s\n",
494 fsp_str_dbg(fsp), strerror(errno)));
496 status = map_nt_error_from_unix(errno);
499 /* As we now have POSIX opens which can unlink
500 * with other open files we may have taken
501 * this code path with more than one share mode
502 * entry - ensure we only delete once by resetting
503 * the delete on close flag. JRA.
506 fsp->delete_on_close = false;
507 reset_delete_on_close_lck(fsp, lck);
509 done:
511 if (changed_user) {
512 /* unbecome user. */
513 pop_sec_ctx();
516 if (fsp->kernel_share_modes_taken) {
517 int ret_flock;
519 /* remove filesystem sharemodes */
520 ret_flock = SMB_VFS_KERNEL_FLOCK(fsp, 0, 0);
521 if (ret_flock == -1) {
522 DEBUG(2, ("close_remove_share_mode: removing kernel "
523 "flock for %s failed: %s\n",
524 fsp_str_dbg(fsp), strerror(errno)));
528 if (!del_share_mode(lck, fsp)) {
529 DEBUG(0, ("close_remove_share_mode: Could not delete share "
530 "entry for file %s\n", fsp_str_dbg(fsp)));
533 TALLOC_FREE(lck);
535 if (delete_file) {
537 * Do the notification after we released the share
538 * mode lock. Inside notify_fname we take out another
539 * tdb lock. With ctdb also accessing our databases,
540 * this can lead to deadlocks. Putting this notify
541 * after the TALLOC_FREE(lck) above we avoid locking
542 * two records simultaneously. Notifies are async and
543 * informational only, so calling the notify_fname
544 * without holding the share mode lock should not do
545 * any harm.
547 notify_fname(conn, NOTIFY_ACTION_REMOVED,
548 FILE_NOTIFY_CHANGE_FILE_NAME,
549 fsp->fsp_name->base_name);
552 return status;
555 void set_close_write_time(struct files_struct *fsp, struct timespec ts)
557 DEBUG(6,("close_write_time: %s" , time_to_asc(convert_timespec_to_time_t(ts))));
559 if (null_timespec(ts)) {
560 return;
562 fsp->write_time_forced = false;
563 fsp->update_write_time_on_close = true;
564 fsp->close_write_time = ts;
567 static NTSTATUS update_write_time_on_close(struct files_struct *fsp)
569 struct smb_file_time ft;
570 NTSTATUS status;
571 struct share_mode_lock *lck = NULL;
573 ZERO_STRUCT(ft);
575 if (!fsp->update_write_time_on_close) {
576 return NT_STATUS_OK;
579 if (null_timespec(fsp->close_write_time)) {
580 fsp->close_write_time = timespec_current();
583 /* Ensure we have a valid stat struct for the source. */
584 status = vfs_stat_fsp(fsp);
585 if (!NT_STATUS_IS_OK(status)) {
586 return status;
589 if (!VALID_STAT(fsp->fsp_name->st)) {
590 /* if it doesn't seem to be a real file */
591 return NT_STATUS_OK;
595 * get_existing_share_mode_lock() isn't really the right
596 * call here, as we're being called after
597 * close_remove_share_mode() inside close_normal_file()
598 * so it's quite normal to not have an existing share
599 * mode here. However, get_share_mode_lock() doesn't
600 * work because that will create a new share mode if
601 * one doesn't exist - so stick with this call (just
602 * ignore any error we get if the share mode doesn't
603 * exist.
606 lck = get_existing_share_mode_lock(talloc_tos(), fsp->file_id);
607 if (lck) {
608 /* On close if we're changing the real file time we
609 * must update it in the open file db too. */
610 (void)set_write_time(fsp->file_id, fsp->close_write_time);
612 /* Close write times overwrite sticky write times
613 so we must replace any sticky write time here. */
614 if (!null_timespec(lck->data->changed_write_time)) {
615 (void)set_sticky_write_time(fsp->file_id, fsp->close_write_time);
617 TALLOC_FREE(lck);
620 ft.mtime = fsp->close_write_time;
621 /* As this is a close based update, we are not directly changing the
622 file attributes from a client call, but indirectly from a write. */
623 status = smb_set_file_time(fsp->conn, fsp, fsp->fsp_name, &ft, false);
624 if (!NT_STATUS_IS_OK(status)) {
625 DEBUG(10,("update_write_time_on_close: smb_set_file_time "
626 "on file %s returned %s\n",
627 fsp_str_dbg(fsp),
628 nt_errstr(status)));
629 return status;
632 return status;
635 static NTSTATUS ntstatus_keeperror(NTSTATUS s1, NTSTATUS s2)
637 if (!NT_STATUS_IS_OK(s1)) {
638 return s1;
640 return s2;
643 /****************************************************************************
644 Close a file.
646 close_type can be NORMAL_CLOSE=0,SHUTDOWN_CLOSE,ERROR_CLOSE.
647 printing and magic scripts are only run on normal close.
648 delete on close is done on normal and shutdown close.
649 ****************************************************************************/
651 static NTSTATUS close_normal_file(struct smb_request *req, files_struct *fsp,
652 enum file_close_type close_type)
654 NTSTATUS status = NT_STATUS_OK;
655 NTSTATUS tmp;
656 connection_struct *conn = fsp->conn;
657 bool is_durable = false;
659 if (fsp->num_aio_requests != 0) {
661 if (close_type != SHUTDOWN_CLOSE) {
663 * reply_close and the smb2 close must have
664 * taken care of this. No other callers of
665 * close_file should ever have created async
666 * I/O.
668 * We need to panic here because if we close()
669 * the fd while we have outstanding async I/O
670 * requests, in the worst case we could end up
671 * writing to the wrong file.
673 DEBUG(0, ("fsp->num_aio_requests=%u\n",
674 fsp->num_aio_requests));
675 smb_panic("can not close with outstanding aio "
676 "requests");
680 * For shutdown close, just drop the async requests
681 * including a potential close request pending for
682 * this fsp. Drop the close request first, the
683 * destructor for the aio_requests would execute it.
685 TALLOC_FREE(fsp->deferred_close);
687 while (fsp->num_aio_requests != 0) {
689 * The destructor of the req will remove
690 * itself from the fsp.
691 * Don't use TALLOC_FREE here, this will overwrite
692 * what the destructor just wrote into
693 * aio_requests[0].
695 talloc_free(fsp->aio_requests[0]);
699 while (talloc_array_length(fsp->blocked_smb1_lock_reqs) != 0) {
700 smbd_smb1_brl_finish_by_req(
701 fsp->blocked_smb1_lock_reqs[0],
702 NT_STATUS_RANGE_NOT_LOCKED);
706 * If we're flushing on a close we can get a write
707 * error here, we must remember this.
710 tmp = close_filestruct(fsp);
711 status = ntstatus_keeperror(status, tmp);
713 if (NT_STATUS_IS_OK(status) && fsp->op != NULL) {
714 is_durable = fsp->op->global->durable;
717 if (close_type != SHUTDOWN_CLOSE) {
718 is_durable = false;
721 if (is_durable) {
722 DATA_BLOB new_cookie = data_blob_null;
724 tmp = SMB_VFS_DURABLE_DISCONNECT(fsp,
725 fsp->op->global->backend_cookie,
726 fsp->op,
727 &new_cookie);
728 if (NT_STATUS_IS_OK(tmp)) {
729 struct timeval tv;
730 NTTIME now;
732 if (req != NULL) {
733 tv = req->request_time;
734 } else {
735 tv = timeval_current();
737 now = timeval_to_nttime(&tv);
739 data_blob_free(&fsp->op->global->backend_cookie);
740 fsp->op->global->backend_cookie = new_cookie;
742 fsp->op->compat = NULL;
743 tmp = smbXsrv_open_close(fsp->op, now);
744 if (!NT_STATUS_IS_OK(tmp)) {
745 DEBUG(1, ("Failed to update smbXsrv_open "
746 "record when disconnecting durable "
747 "handle for file %s: %s - "
748 "proceeding with normal close\n",
749 fsp_str_dbg(fsp), nt_errstr(tmp)));
751 scavenger_schedule_disconnected(fsp);
752 } else {
753 DEBUG(1, ("Failed to disconnect durable handle for "
754 "file %s: %s - proceeding with normal "
755 "close\n", fsp_str_dbg(fsp), nt_errstr(tmp)));
757 if (!NT_STATUS_IS_OK(tmp)) {
758 is_durable = false;
762 if (is_durable) {
764 * This is the case where we successfully disconnected
765 * a durable handle and closed the underlying file.
766 * In all other cases, we proceed with a genuine close.
768 DEBUG(10, ("%s disconnected durable handle for file %s\n",
769 conn->session_info->unix_info->unix_name,
770 fsp_str_dbg(fsp)));
771 file_free(req, fsp);
772 return NT_STATUS_OK;
775 if (fsp->op != NULL) {
777 * Make sure the handle is not marked as durable anymore
779 fsp->op->global->durable = false;
782 if (fsp->print_file) {
783 /* FIXME: return spool errors */
784 print_spool_end(fsp, close_type);
785 file_free(req, fsp);
786 return NT_STATUS_OK;
789 /* If this is an old DOS or FCB open and we have multiple opens on
790 the same handle we only have one share mode. Ensure we only remove
791 the share mode on the last close. */
793 if (fsp->fh->ref_count == 1) {
794 /* Should we return on error here... ? */
795 tmp = close_remove_share_mode(fsp, close_type);
796 status = ntstatus_keeperror(status, tmp);
799 locking_close_file(fsp, close_type);
801 tmp = fd_close(fsp);
802 status = ntstatus_keeperror(status, tmp);
804 /* check for magic scripts */
805 if (close_type == NORMAL_CLOSE) {
806 tmp = check_magic(fsp);
807 status = ntstatus_keeperror(status, tmp);
811 * Ensure pending modtime is set after close.
814 tmp = update_write_time_on_close(fsp);
815 if (NT_STATUS_EQUAL(tmp, NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
816 /* Someone renamed the file or a parent directory containing
817 * this file. We can't do anything about this, we don't have
818 * an "update timestamp by fd" call in POSIX. Eat the error. */
820 tmp = NT_STATUS_OK;
823 status = ntstatus_keeperror(status, tmp);
825 DEBUG(2,("%s closed file %s (numopen=%d) %s\n",
826 conn->session_info->unix_info->unix_name, fsp_str_dbg(fsp),
827 conn->num_files_open - 1,
828 nt_errstr(status) ));
830 file_free(req, fsp);
831 return status;
833 /****************************************************************************
834 Function used by reply_rmdir to delete an entire directory
835 tree recursively. Return True on ok, False on fail.
836 ****************************************************************************/
838 bool recursive_rmdir(TALLOC_CTX *ctx,
839 connection_struct *conn,
840 struct smb_filename *smb_dname)
842 const char *dname = NULL;
843 char *talloced = NULL;
844 bool ret = True;
845 long offset = 0;
846 SMB_STRUCT_STAT st;
847 struct smb_Dir *dir_hnd;
849 SMB_ASSERT(!is_ntfs_stream_smb_fname(smb_dname));
851 dir_hnd = OpenDir(talloc_tos(), conn, smb_dname, NULL, 0);
852 if(dir_hnd == NULL)
853 return False;
855 while((dname = ReadDirName(dir_hnd, &offset, &st, &talloced))) {
856 struct smb_filename *smb_dname_full = NULL;
857 char *fullname = NULL;
858 bool do_break = true;
860 if (ISDOT(dname) || ISDOTDOT(dname)) {
861 TALLOC_FREE(talloced);
862 continue;
865 if (!is_visible_file(conn, smb_dname->base_name, dname, &st,
866 false)) {
867 TALLOC_FREE(talloced);
868 continue;
871 /* Construct the full name. */
872 fullname = talloc_asprintf(ctx,
873 "%s/%s",
874 smb_dname->base_name,
875 dname);
876 if (!fullname) {
877 errno = ENOMEM;
878 goto err_break;
881 smb_dname_full = synthetic_smb_fname(talloc_tos(),
882 fullname,
883 NULL,
884 NULL,
885 smb_dname->flags);
886 if (smb_dname_full == NULL) {
887 errno = ENOMEM;
888 goto err_break;
891 if(SMB_VFS_LSTAT(conn, smb_dname_full) != 0) {
892 goto err_break;
895 if(smb_dname_full->st.st_ex_mode & S_IFDIR) {
896 if(!recursive_rmdir(ctx, conn, smb_dname_full)) {
897 goto err_break;
899 if(SMB_VFS_RMDIR(conn, smb_dname_full) != 0) {
900 goto err_break;
902 } else if(SMB_VFS_UNLINK(conn, smb_dname_full) != 0) {
903 goto err_break;
906 /* Successful iteration. */
907 do_break = false;
909 err_break:
910 TALLOC_FREE(smb_dname_full);
911 TALLOC_FREE(fullname);
912 TALLOC_FREE(talloced);
913 if (do_break) {
914 ret = false;
915 break;
918 TALLOC_FREE(dir_hnd);
919 return ret;
922 /****************************************************************************
923 The internals of the rmdir code - called elsewhere.
924 ****************************************************************************/
926 static NTSTATUS rmdir_internals(TALLOC_CTX *ctx, files_struct *fsp)
928 connection_struct *conn = fsp->conn;
929 struct smb_filename *smb_dname = fsp->fsp_name;
930 int ret;
932 SMB_ASSERT(!is_ntfs_stream_smb_fname(smb_dname));
934 /* Might be a symlink. */
935 if(SMB_VFS_LSTAT(conn, smb_dname) != 0) {
936 return map_nt_error_from_unix(errno);
939 if (S_ISLNK(smb_dname->st.st_ex_mode)) {
940 /* Is what it points to a directory ? */
941 if(SMB_VFS_STAT(conn, smb_dname) != 0) {
942 return map_nt_error_from_unix(errno);
944 if (!(S_ISDIR(smb_dname->st.st_ex_mode))) {
945 return NT_STATUS_NOT_A_DIRECTORY;
947 ret = SMB_VFS_UNLINK(conn, smb_dname);
948 } else {
949 ret = SMB_VFS_RMDIR(conn, smb_dname);
951 if (ret == 0) {
952 notify_fname(conn, NOTIFY_ACTION_REMOVED,
953 FILE_NOTIFY_CHANGE_DIR_NAME,
954 smb_dname->base_name);
955 return NT_STATUS_OK;
958 if(((errno == ENOTEMPTY)||(errno == EEXIST)) && *lp_veto_files(talloc_tos(), SNUM(conn))) {
960 * Check to see if the only thing in this directory are
961 * vetoed files/directories. If so then delete them and
962 * retry. If we fail to delete any of them (and we *don't*
963 * do a recursive delete) then fail the rmdir.
965 SMB_STRUCT_STAT st;
966 const char *dname = NULL;
967 char *talloced = NULL;
968 long dirpos = 0;
969 struct smb_Dir *dir_hnd = OpenDir(talloc_tos(), conn,
970 smb_dname, NULL,
973 if(dir_hnd == NULL) {
974 errno = ENOTEMPTY;
975 goto err;
978 while ((dname = ReadDirName(dir_hnd, &dirpos, &st,
979 &talloced)) != NULL) {
980 if((strcmp(dname, ".") == 0) || (strcmp(dname, "..")==0)) {
981 TALLOC_FREE(talloced);
982 continue;
984 if (!is_visible_file(conn, smb_dname->base_name, dname,
985 &st, false)) {
986 TALLOC_FREE(talloced);
987 continue;
989 if(!IS_VETO_PATH(conn, dname)) {
990 TALLOC_FREE(dir_hnd);
991 TALLOC_FREE(talloced);
992 errno = ENOTEMPTY;
993 goto err;
995 TALLOC_FREE(talloced);
998 /* We only have veto files/directories.
999 * Are we allowed to delete them ? */
1001 if(!lp_delete_veto_files(SNUM(conn))) {
1002 TALLOC_FREE(dir_hnd);
1003 errno = ENOTEMPTY;
1004 goto err;
1007 /* Do a recursive delete. */
1008 RewindDir(dir_hnd,&dirpos);
1009 while ((dname = ReadDirName(dir_hnd, &dirpos, &st,
1010 &talloced)) != NULL) {
1011 struct smb_filename *smb_dname_full = NULL;
1012 char *fullname = NULL;
1013 bool do_break = true;
1015 if (ISDOT(dname) || ISDOTDOT(dname)) {
1016 TALLOC_FREE(talloced);
1017 continue;
1019 if (!is_visible_file(conn, smb_dname->base_name, dname,
1020 &st, false)) {
1021 TALLOC_FREE(talloced);
1022 continue;
1025 fullname = talloc_asprintf(ctx,
1026 "%s/%s",
1027 smb_dname->base_name,
1028 dname);
1030 if(!fullname) {
1031 errno = ENOMEM;
1032 goto err_break;
1035 smb_dname_full = synthetic_smb_fname(talloc_tos(),
1036 fullname,
1037 NULL,
1038 NULL,
1039 smb_dname->flags);
1040 if (smb_dname_full == NULL) {
1041 errno = ENOMEM;
1042 goto err_break;
1045 if(SMB_VFS_LSTAT(conn, smb_dname_full) != 0) {
1046 goto err_break;
1048 if(smb_dname_full->st.st_ex_mode & S_IFDIR) {
1049 if(!recursive_rmdir(ctx, conn,
1050 smb_dname_full)) {
1051 goto err_break;
1053 if(SMB_VFS_RMDIR(conn,
1054 smb_dname_full) != 0) {
1055 goto err_break;
1057 } else if(SMB_VFS_UNLINK(conn, smb_dname_full) != 0) {
1058 goto err_break;
1061 /* Successful iteration. */
1062 do_break = false;
1064 err_break:
1065 TALLOC_FREE(fullname);
1066 TALLOC_FREE(smb_dname_full);
1067 TALLOC_FREE(talloced);
1068 if (do_break)
1069 break;
1071 TALLOC_FREE(dir_hnd);
1072 /* Retry the rmdir */
1073 ret = SMB_VFS_RMDIR(conn, smb_dname);
1076 err:
1078 if (ret != 0) {
1079 DEBUG(3,("rmdir_internals: couldn't remove directory %s : "
1080 "%s\n", smb_fname_str_dbg(smb_dname),
1081 strerror(errno)));
1082 return map_nt_error_from_unix(errno);
1085 notify_fname(conn, NOTIFY_ACTION_REMOVED,
1086 FILE_NOTIFY_CHANGE_DIR_NAME,
1087 smb_dname->base_name);
1089 return NT_STATUS_OK;
1092 /****************************************************************************
1093 Close a directory opened by an NT SMB call.
1094 ****************************************************************************/
1096 static NTSTATUS close_directory(struct smb_request *req, files_struct *fsp,
1097 enum file_close_type close_type)
1099 struct share_mode_lock *lck = NULL;
1100 bool delete_dir = False;
1101 NTSTATUS status = NT_STATUS_OK;
1102 NTSTATUS status1 = NT_STATUS_OK;
1103 const struct security_token *del_nt_token = NULL;
1104 const struct security_unix_token *del_token = NULL;
1105 NTSTATUS notify_status;
1107 if (fsp->conn->sconn->using_smb2) {
1108 notify_status = STATUS_NOTIFY_CLEANUP;
1109 } else {
1110 notify_status = NT_STATUS_OK;
1113 if (fsp->num_aio_requests != 0) {
1114 if (close_type != SHUTDOWN_CLOSE) {
1116 * We panic here because if we close() the fd while we
1117 * have outstanding async I/O requests, an async IO
1118 * request might use the fd. For directories the fd is
1119 * read-only, so this is not as bad as with files, but
1120 * still, better safe then sorry.
1122 DBG_ERR("fsp->num_aio_requests=%u\n",
1123 fsp->num_aio_requests);
1124 smb_panic("close with outstanding aio requests");
1125 return NT_STATUS_INTERNAL_ERROR;
1128 while (fsp->num_aio_requests != 0) {
1130 * The destructor of the req will remove itself from the
1131 * fsp. Don't use TALLOC_FREE here, this will overwrite
1132 * what the destructor just wrote into aio_requests[0].
1134 talloc_free(fsp->aio_requests[0]);
1139 * NT can set delete_on_close of the last open
1140 * reference to a directory also.
1143 lck = get_existing_share_mode_lock(talloc_tos(), fsp->file_id);
1144 if (lck == NULL) {
1145 DEBUG(0, ("close_directory: Could not get share mode lock for "
1146 "%s\n", fsp_str_dbg(fsp)));
1147 close_filestruct(fsp);
1148 file_free(req, fsp);
1149 return NT_STATUS_INVALID_PARAMETER;
1152 if (fsp->initial_delete_on_close) {
1153 bool became_user = False;
1155 /* Initial delete on close was set - for
1156 * directories we don't care if anyone else
1157 * wrote a real delete on close. */
1159 if (get_current_vuid(fsp->conn) != fsp->vuid) {
1160 become_user_without_service(fsp->conn, fsp->vuid);
1161 became_user = True;
1163 send_stat_cache_delete_message(fsp->conn->sconn->msg_ctx,
1164 fsp->fsp_name->base_name);
1165 set_delete_on_close_lck(fsp, lck,
1166 get_current_nttok(fsp->conn),
1167 get_current_utok(fsp->conn));
1168 fsp->delete_on_close = true;
1169 if (became_user) {
1170 unbecome_user_without_service();
1174 delete_dir = get_delete_on_close_token(
1175 lck, fsp->name_hash, &del_nt_token, &del_token) &&
1176 !has_other_nonposix_opens(lck, fsp);
1178 if ((close_type == NORMAL_CLOSE || close_type == SHUTDOWN_CLOSE) &&
1179 delete_dir) {
1181 /* Become the user who requested the delete. */
1183 if (!push_sec_ctx()) {
1184 smb_panic("close_directory: failed to push sec_ctx.\n");
1187 set_sec_ctx(del_token->uid,
1188 del_token->gid,
1189 del_token->ngroups,
1190 del_token->groups,
1191 del_nt_token);
1193 if (!del_share_mode(lck, fsp)) {
1194 DEBUG(0, ("close_directory: Could not delete share entry for "
1195 "%s\n", fsp_str_dbg(fsp)));
1198 TALLOC_FREE(lck);
1200 if ((fsp->conn->fs_capabilities & FILE_NAMED_STREAMS)
1201 && !is_ntfs_stream_smb_fname(fsp->fsp_name)) {
1203 status = delete_all_streams(fsp->conn, fsp->fsp_name);
1204 if (!NT_STATUS_IS_OK(status)) {
1205 DEBUG(5, ("delete_all_streams failed: %s\n",
1206 nt_errstr(status)));
1207 close_filestruct(fsp);
1208 file_free(req, fsp);
1209 return status;
1213 status = rmdir_internals(talloc_tos(), fsp);
1215 DEBUG(5,("close_directory: %s. Delete on close was set - "
1216 "deleting directory returned %s.\n",
1217 fsp_str_dbg(fsp), nt_errstr(status)));
1219 /* unbecome user. */
1220 pop_sec_ctx();
1223 * Ensure we remove any change notify requests that would
1224 * now fail as the directory has been deleted.
1227 if (NT_STATUS_IS_OK(status)) {
1228 notify_status = NT_STATUS_DELETE_PENDING;
1230 } else {
1231 if (!del_share_mode(lck, fsp)) {
1232 DEBUG(0, ("close_directory: Could not delete share entry for "
1233 "%s\n", fsp_str_dbg(fsp)));
1236 TALLOC_FREE(lck);
1239 remove_pending_change_notify_requests_by_fid(fsp, notify_status);
1241 status1 = fd_close(fsp);
1243 if (!NT_STATUS_IS_OK(status1)) {
1244 DEBUG(0, ("Could not close dir! fname=%s, fd=%d, err=%d=%s\n",
1245 fsp_str_dbg(fsp), fsp->fh->fd, errno,
1246 strerror(errno)));
1250 * Do the code common to files and directories.
1252 close_filestruct(fsp);
1253 file_free(req, fsp);
1255 if (NT_STATUS_IS_OK(status) && !NT_STATUS_IS_OK(status1)) {
1256 status = status1;
1258 return status;
1261 /****************************************************************************
1262 Close a files_struct.
1263 ****************************************************************************/
1265 NTSTATUS close_file(struct smb_request *req, files_struct *fsp,
1266 enum file_close_type close_type)
1268 NTSTATUS status;
1269 struct files_struct *base_fsp = fsp->base_fsp;
1271 if(fsp->is_directory) {
1272 status = close_directory(req, fsp, close_type);
1273 } else if (fsp->fake_file_handle != NULL) {
1274 status = close_fake_file(req, fsp);
1275 } else {
1276 status = close_normal_file(req, fsp, close_type);
1279 if ((base_fsp != NULL) && (close_type != SHUTDOWN_CLOSE)) {
1282 * fsp was a stream, the base fsp can't be a stream as well
1284 * For SHUTDOWN_CLOSE this is not possible here, because
1285 * SHUTDOWN_CLOSE only happens from files.c which walks the
1286 * complete list of files. If we mess with more than one fsp
1287 * those loops will become confused.
1290 SMB_ASSERT(base_fsp->base_fsp == NULL);
1291 close_file(req, base_fsp, close_type);
1294 return status;
1297 /****************************************************************************
1298 Deal with an (authorized) message to close a file given the share mode
1299 entry.
1300 ****************************************************************************/
1302 void msg_close_file(struct messaging_context *msg_ctx,
1303 void *private_data,
1304 uint32_t msg_type,
1305 struct server_id server_id,
1306 DATA_BLOB *data)
1308 files_struct *fsp = NULL;
1309 struct file_id id;
1310 struct share_mode_entry e;
1311 struct smbd_server_connection *sconn =
1312 talloc_get_type_abort(private_data,
1313 struct smbd_server_connection);
1315 message_to_share_mode_entry(&id, &e, (char *)data->data);
1317 if(DEBUGLVL(10)) {
1318 char *sm_str = share_mode_str(NULL, 0, &id, &e);
1319 if (!sm_str) {
1320 smb_panic("talloc failed");
1322 DEBUG(10,("msg_close_file: got request to close share mode "
1323 "entry %s\n", sm_str));
1324 TALLOC_FREE(sm_str);
1327 fsp = file_find_dif(sconn, id, e.share_file_id);
1328 if (!fsp) {
1329 DEBUG(10,("msg_close_file: failed to find file.\n"));
1330 return;
1332 close_file(NULL, fsp, NORMAL_CLOSE);