s4:torture:vfs_fruit: smb2/create context AAPL test
[Samba.git] / source3 / smbd / close.c
blob4fbd442fc33aa3762b25ff50bc261693bd29adfa
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 "smbd/scavenger.h"
28 #include "fake_file.h"
29 #include "transfer_file.h"
30 #include "auth.h"
31 #include "messages.h"
32 #include "../librpc/gen_ndr/open_files.h"
34 /****************************************************************************
35 Run a file if it is a magic script.
36 ****************************************************************************/
38 static NTSTATUS check_magic(struct files_struct *fsp)
40 int ret;
41 const char *magic_output = NULL;
42 SMB_STRUCT_STAT st;
43 int tmp_fd, outfd;
44 TALLOC_CTX *ctx = NULL;
45 const char *p;
46 struct connection_struct *conn = fsp->conn;
47 char *fname = NULL;
48 NTSTATUS status;
50 if (!*lp_magic_script(talloc_tos(), SNUM(conn))) {
51 return NT_STATUS_OK;
54 DEBUG(5,("checking magic for %s\n", fsp_str_dbg(fsp)));
56 ctx = talloc_stackframe();
58 fname = fsp->fsp_name->base_name;
60 if (!(p = strrchr_m(fname,'/'))) {
61 p = fname;
62 } else {
63 p++;
66 if (!strequal(lp_magic_script(talloc_tos(), SNUM(conn)),p)) {
67 status = NT_STATUS_OK;
68 goto out;
71 if (*lp_magic_output(talloc_tos(), SNUM(conn))) {
72 magic_output = lp_magic_output(talloc_tos(), SNUM(conn));
73 } else {
74 magic_output = talloc_asprintf(ctx,
75 "%s.out",
76 fname);
78 if (!magic_output) {
79 status = NT_STATUS_NO_MEMORY;
80 goto out;
83 /* Ensure we don't depend on user's PATH. */
84 p = talloc_asprintf(ctx, "./%s", fname);
85 if (!p) {
86 status = NT_STATUS_NO_MEMORY;
87 goto out;
90 if (chmod(fname, 0755) == -1) {
91 status = map_nt_error_from_unix(errno);
92 goto out;
94 ret = smbrun(p,&tmp_fd);
95 DEBUG(3,("Invoking magic command %s gave %d\n",
96 p,ret));
98 unlink(fname);
99 if (ret != 0 || tmp_fd == -1) {
100 if (tmp_fd != -1) {
101 close(tmp_fd);
103 status = NT_STATUS_UNSUCCESSFUL;
104 goto out;
106 outfd = open(magic_output, O_CREAT|O_EXCL|O_RDWR, 0600);
107 if (outfd == -1) {
108 int err = errno;
109 close(tmp_fd);
110 status = map_nt_error_from_unix(err);
111 goto out;
114 if (sys_fstat(tmp_fd, &st, false) == -1) {
115 int err = errno;
116 close(tmp_fd);
117 close(outfd);
118 status = map_nt_error_from_unix(err);
119 goto out;
122 if (transfer_file(tmp_fd,outfd,(off_t)st.st_ex_size) == (off_t)-1) {
123 int err = errno;
124 close(tmp_fd);
125 close(outfd);
126 status = map_nt_error_from_unix(err);
127 goto out;
129 close(tmp_fd);
130 if (close(outfd) == -1) {
131 status = map_nt_error_from_unix(errno);
132 goto out;
135 status = NT_STATUS_OK;
137 out:
138 TALLOC_FREE(ctx);
139 return status;
142 /****************************************************************************
143 Common code to close a file or a directory.
144 ****************************************************************************/
146 static NTSTATUS close_filestruct(files_struct *fsp)
148 NTSTATUS status = NT_STATUS_OK;
150 if (fsp->fh->fd != -1) {
151 if(flush_write_cache(fsp, SAMBA_CLOSE_FLUSH) == -1) {
152 status = map_nt_error_from_unix(errno);
154 delete_write_cache(fsp);
157 return status;
160 /****************************************************************************
161 Delete all streams
162 ****************************************************************************/
164 NTSTATUS delete_all_streams(connection_struct *conn, const char *fname)
166 struct stream_struct *stream_info = NULL;
167 int i;
168 unsigned int num_streams = 0;
169 TALLOC_CTX *frame = talloc_stackframe();
170 NTSTATUS status;
172 status = vfs_streaminfo(conn, NULL, fname, talloc_tos(),
173 &num_streams, &stream_info);
175 if (NT_STATUS_EQUAL(status, NT_STATUS_NOT_IMPLEMENTED)) {
176 DEBUG(10, ("no streams around\n"));
177 TALLOC_FREE(frame);
178 return NT_STATUS_OK;
181 if (!NT_STATUS_IS_OK(status)) {
182 DEBUG(10, ("vfs_streaminfo failed: %s\n",
183 nt_errstr(status)));
184 goto fail;
187 DEBUG(10, ("delete_all_streams found %d streams\n",
188 num_streams));
190 if (num_streams == 0) {
191 TALLOC_FREE(frame);
192 return NT_STATUS_OK;
195 for (i=0; i<num_streams; i++) {
196 int res;
197 struct smb_filename *smb_fname_stream;
199 if (strequal(stream_info[i].name, "::$DATA")) {
200 continue;
203 smb_fname_stream = synthetic_smb_fname(
204 talloc_tos(), fname, stream_info[i].name, NULL);
206 if (smb_fname_stream == NULL) {
207 DEBUG(0, ("talloc_aprintf failed\n"));
208 status = NT_STATUS_NO_MEMORY;
209 goto fail;
212 res = SMB_VFS_UNLINK(conn, smb_fname_stream);
214 if (res == -1) {
215 status = map_nt_error_from_unix(errno);
216 DEBUG(10, ("Could not delete stream %s: %s\n",
217 smb_fname_str_dbg(smb_fname_stream),
218 strerror(errno)));
219 TALLOC_FREE(smb_fname_stream);
220 break;
222 TALLOC_FREE(smb_fname_stream);
225 fail:
226 TALLOC_FREE(frame);
227 return status;
230 /****************************************************************************
231 Deal with removing a share mode on last close.
232 ****************************************************************************/
234 static NTSTATUS close_remove_share_mode(files_struct *fsp,
235 enum file_close_type close_type)
237 connection_struct *conn = fsp->conn;
238 struct server_id self = messaging_server_id(conn->sconn->msg_ctx);
239 bool delete_file = false;
240 bool changed_user = false;
241 struct share_mode_lock *lck = NULL;
242 NTSTATUS status = NT_STATUS_OK;
243 NTSTATUS tmp_status;
244 struct file_id id;
245 const struct security_unix_token *del_token = NULL;
246 const struct security_token *del_nt_token = NULL;
247 bool got_tokens = false;
248 bool normal_close;
249 int ret_flock;
251 /* Ensure any pending write time updates are done. */
252 if (fsp->update_write_time_event) {
253 update_write_time_handler(fsp->conn->sconn->ev_ctx,
254 fsp->update_write_time_event,
255 timeval_current(),
256 (void *)fsp);
260 * Lock the share entries, and determine if we should delete
261 * on close. If so delete whilst the lock is still in effect.
262 * This prevents race conditions with the file being created. JRA.
265 lck = get_existing_share_mode_lock(talloc_tos(), fsp->file_id);
266 if (lck == NULL) {
267 DEBUG(0, ("close_remove_share_mode: Could not get share mode "
268 "lock for file %s\n", fsp_str_dbg(fsp)));
269 return NT_STATUS_INVALID_PARAMETER;
272 if (fsp->write_time_forced) {
273 DEBUG(10,("close_remove_share_mode: write time forced "
274 "for file %s\n",
275 fsp_str_dbg(fsp)));
276 set_close_write_time(fsp, lck->data->changed_write_time);
277 } else if (fsp->update_write_time_on_close) {
278 /* Someone had a pending write. */
279 if (null_timespec(fsp->close_write_time)) {
280 DEBUG(10,("close_remove_share_mode: update to current time "
281 "for file %s\n",
282 fsp_str_dbg(fsp)));
283 /* Update to current time due to "normal" write. */
284 set_close_write_time(fsp, timespec_current());
285 } else {
286 DEBUG(10,("close_remove_share_mode: write time pending "
287 "for file %s\n",
288 fsp_str_dbg(fsp)));
289 /* Update to time set on close call. */
290 set_close_write_time(fsp, fsp->close_write_time);
294 if (fsp->initial_delete_on_close &&
295 !is_delete_on_close_set(lck, fsp->name_hash)) {
296 bool became_user = False;
298 /* Initial delete on close was set and no one else
299 * wrote a real delete on close. */
301 if (get_current_vuid(conn) != fsp->vuid) {
302 become_user(conn, fsp->vuid);
303 became_user = True;
305 fsp->delete_on_close = true;
306 set_delete_on_close_lck(fsp, lck, True,
307 get_current_nttok(conn),
308 get_current_utok(conn));
309 if (became_user) {
310 unbecome_user();
314 delete_file = is_delete_on_close_set(lck, fsp->name_hash);
316 if (delete_file) {
317 int i;
318 /* See if others still have the file open via this pathname.
319 If this is the case, then don't delete. If all opens are
320 POSIX delete now. */
321 for (i=0; i<lck->data->num_share_modes; i++) {
322 struct share_mode_entry *e = &lck->data->share_modes[i];
324 if (!is_valid_share_mode_entry(e)) {
325 continue;
327 if (e->name_hash != fsp->name_hash) {
328 continue;
330 if (fsp->posix_open
331 && (e->flags & SHARE_MODE_FLAG_POSIX_OPEN)) {
332 continue;
334 if (serverid_equal(&self, &e->pid) &&
335 (e->share_file_id == fsp->fh->gen_id)) {
336 continue;
338 if (share_mode_stale_pid(lck->data, i)) {
339 continue;
341 delete_file = False;
342 break;
347 * NT can set delete_on_close of the last open
348 * reference to a file.
351 normal_close = (close_type == NORMAL_CLOSE || close_type == SHUTDOWN_CLOSE);
353 if (!normal_close || !delete_file) {
354 status = NT_STATUS_OK;
355 goto done;
359 * Ok, we have to delete the file
362 DEBUG(5,("close_remove_share_mode: file %s. Delete on close was set "
363 "- deleting file.\n", fsp_str_dbg(fsp)));
366 * Don't try to update the write time when we delete the file
368 fsp->update_write_time_on_close = false;
370 got_tokens = get_delete_on_close_token(lck, fsp->name_hash,
371 &del_nt_token, &del_token);
372 SMB_ASSERT(got_tokens);
374 if (!unix_token_equal(del_token, get_current_utok(conn))) {
375 /* Become the user who requested the delete. */
377 DEBUG(5,("close_remove_share_mode: file %s. "
378 "Change user to uid %u\n",
379 fsp_str_dbg(fsp),
380 (unsigned int)del_token->uid));
382 if (!push_sec_ctx()) {
383 smb_panic("close_remove_share_mode: file %s. failed to push "
384 "sec_ctx.\n");
387 set_sec_ctx(del_token->uid,
388 del_token->gid,
389 del_token->ngroups,
390 del_token->groups,
391 del_nt_token);
393 changed_user = true;
396 /* We can only delete the file if the name we have is still valid and
397 hasn't been renamed. */
399 tmp_status = vfs_stat_fsp(fsp);
400 if (!NT_STATUS_IS_OK(tmp_status)) {
401 DEBUG(5,("close_remove_share_mode: file %s. Delete on close "
402 "was set and stat failed with error %s\n",
403 fsp_str_dbg(fsp), nt_errstr(tmp_status)));
405 * Don't save the errno here, we ignore this error
407 goto done;
410 id = vfs_file_id_from_sbuf(conn, &fsp->fsp_name->st);
412 if (!file_id_equal(&fsp->file_id, &id)) {
413 DEBUG(5,("close_remove_share_mode: file %s. Delete on close "
414 "was set and dev and/or inode does not match\n",
415 fsp_str_dbg(fsp)));
416 DEBUG(5,("close_remove_share_mode: file %s. stored file_id %s, "
417 "stat file_id %s\n",
418 fsp_str_dbg(fsp),
419 file_id_string_tos(&fsp->file_id),
420 file_id_string_tos(&id)));
422 * Don't save the errno here, we ignore this error
424 goto done;
427 if ((conn->fs_capabilities & FILE_NAMED_STREAMS)
428 && !is_ntfs_stream_smb_fname(fsp->fsp_name)) {
430 status = delete_all_streams(conn, fsp->fsp_name->base_name);
432 if (!NT_STATUS_IS_OK(status)) {
433 DEBUG(5, ("delete_all_streams failed: %s\n",
434 nt_errstr(status)));
435 goto done;
440 if (SMB_VFS_UNLINK(conn, fsp->fsp_name) != 0) {
442 * This call can potentially fail as another smbd may
443 * have had the file open with delete on close set and
444 * deleted it when its last reference to this file
445 * went away. Hence we log this but not at debug level
446 * zero.
449 DEBUG(5,("close_remove_share_mode: file %s. Delete on close "
450 "was set and unlink failed with error %s\n",
451 fsp_str_dbg(fsp), strerror(errno)));
453 status = map_nt_error_from_unix(errno);
456 /* As we now have POSIX opens which can unlink
457 * with other open files we may have taken
458 * this code path with more than one share mode
459 * entry - ensure we only delete once by resetting
460 * the delete on close flag. JRA.
463 fsp->delete_on_close = false;
464 set_delete_on_close_lck(fsp, lck, false, NULL, NULL);
466 done:
468 if (changed_user) {
469 /* unbecome user. */
470 pop_sec_ctx();
473 /* remove filesystem sharemodes */
474 ret_flock = SMB_VFS_KERNEL_FLOCK(fsp, 0, 0);
475 if (ret_flock == -1) {
476 DEBUG(2, ("close_remove_share_mode: removing kernel flock for "
477 "%s failed: %s\n", fsp_str_dbg(fsp),
478 strerror(errno)));
481 if (!del_share_mode(lck, fsp)) {
482 DEBUG(0, ("close_remove_share_mode: Could not delete share "
483 "entry for file %s\n", fsp_str_dbg(fsp)));
486 TALLOC_FREE(lck);
488 if (delete_file) {
490 * Do the notification after we released the share
491 * mode lock. Inside notify_fname we take out another
492 * tdb lock. With ctdb also accessing our databases,
493 * this can lead to deadlocks. Putting this notify
494 * after the TALLOC_FREE(lck) above we avoid locking
495 * two records simultaneously. Notifies are async and
496 * informational only, so calling the notify_fname
497 * without holding the share mode lock should not do
498 * any harm.
500 notify_fname(conn, NOTIFY_ACTION_REMOVED,
501 FILE_NOTIFY_CHANGE_FILE_NAME,
502 fsp->fsp_name->base_name);
505 return status;
508 void set_close_write_time(struct files_struct *fsp, struct timespec ts)
510 DEBUG(6,("close_write_time: %s" , time_to_asc(convert_timespec_to_time_t(ts))));
512 if (null_timespec(ts)) {
513 return;
515 fsp->write_time_forced = false;
516 fsp->update_write_time_on_close = true;
517 fsp->close_write_time = ts;
520 static NTSTATUS update_write_time_on_close(struct files_struct *fsp)
522 struct smb_file_time ft;
523 NTSTATUS status;
524 struct share_mode_lock *lck = NULL;
526 ZERO_STRUCT(ft);
528 if (!fsp->update_write_time_on_close) {
529 return NT_STATUS_OK;
532 if (null_timespec(fsp->close_write_time)) {
533 fsp->close_write_time = timespec_current();
536 /* Ensure we have a valid stat struct for the source. */
537 status = vfs_stat_fsp(fsp);
538 if (!NT_STATUS_IS_OK(status)) {
539 return status;
542 if (!VALID_STAT(fsp->fsp_name->st)) {
543 /* if it doesn't seem to be a real file */
544 return NT_STATUS_OK;
548 * get_existing_share_mode_lock() isn't really the right
549 * call here, as we're being called after
550 * close_remove_share_mode() inside close_normal_file()
551 * so it's quite normal to not have an existing share
552 * mode here. However, get_share_mode_lock() doesn't
553 * work because that will create a new share mode if
554 * one doesn't exist - so stick with this call (just
555 * ignore any error we get if the share mode doesn't
556 * exist.
559 lck = get_existing_share_mode_lock(talloc_tos(), fsp->file_id);
560 if (lck) {
561 /* On close if we're changing the real file time we
562 * must update it in the open file db too. */
563 (void)set_write_time(fsp->file_id, fsp->close_write_time);
565 /* Close write times overwrite sticky write times
566 so we must replace any sticky write time here. */
567 if (!null_timespec(lck->data->changed_write_time)) {
568 (void)set_sticky_write_time(fsp->file_id, fsp->close_write_time);
570 TALLOC_FREE(lck);
573 ft.mtime = fsp->close_write_time;
574 /* As this is a close based update, we are not directly changing the
575 file attributes from a client call, but indirectly from a write. */
576 status = smb_set_file_time(fsp->conn, fsp, fsp->fsp_name, &ft, false);
577 if (!NT_STATUS_IS_OK(status)) {
578 DEBUG(10,("update_write_time_on_close: smb_set_file_time "
579 "on file %s returned %s\n",
580 fsp_str_dbg(fsp),
581 nt_errstr(status)));
582 return status;
585 return status;
588 static NTSTATUS ntstatus_keeperror(NTSTATUS s1, NTSTATUS s2)
590 if (!NT_STATUS_IS_OK(s1)) {
591 return s1;
593 return s2;
596 /****************************************************************************
597 Close a file.
599 close_type can be NORMAL_CLOSE=0,SHUTDOWN_CLOSE,ERROR_CLOSE.
600 printing and magic scripts are only run on normal close.
601 delete on close is done on normal and shutdown close.
602 ****************************************************************************/
604 static NTSTATUS close_normal_file(struct smb_request *req, files_struct *fsp,
605 enum file_close_type close_type)
607 NTSTATUS status = NT_STATUS_OK;
608 NTSTATUS tmp;
609 connection_struct *conn = fsp->conn;
610 bool is_durable = false;
612 if (fsp->num_aio_requests != 0) {
614 if (close_type != SHUTDOWN_CLOSE) {
616 * reply_close and the smb2 close must have
617 * taken care of this. No other callers of
618 * close_file should ever have created async
619 * I/O.
621 * We need to panic here because if we close()
622 * the fd while we have outstanding async I/O
623 * requests, in the worst case we could end up
624 * writing to the wrong file.
626 DEBUG(0, ("fsp->num_aio_requests=%u\n",
627 fsp->num_aio_requests));
628 smb_panic("can not close with outstanding aio "
629 "requests");
633 * For shutdown close, just drop the async requests
634 * including a potential close request pending for
635 * this fsp. Drop the close request first, the
636 * destructor for the aio_requests would execute it.
638 TALLOC_FREE(fsp->deferred_close);
640 while (fsp->num_aio_requests != 0) {
642 * The destructor of the req will remove
643 * itself from the fsp.
644 * Don't use TALLOC_FREE here, this will overwrite
645 * what the destructor just wrote into
646 * aio_requests[0].
648 talloc_free(fsp->aio_requests[0]);
653 * If we're flushing on a close we can get a write
654 * error here, we must remember this.
657 tmp = close_filestruct(fsp);
658 status = ntstatus_keeperror(status, tmp);
660 if (NT_STATUS_IS_OK(status) && fsp->op != NULL) {
661 is_durable = fsp->op->global->durable;
664 if (close_type != SHUTDOWN_CLOSE) {
665 is_durable = false;
668 if (is_durable) {
669 DATA_BLOB new_cookie = data_blob_null;
671 tmp = SMB_VFS_DURABLE_DISCONNECT(fsp,
672 fsp->op->global->backend_cookie,
673 fsp->op,
674 &new_cookie);
675 if (NT_STATUS_IS_OK(tmp)) {
676 struct timeval tv;
677 NTTIME now;
679 if (req != NULL) {
680 tv = req->request_time;
681 } else {
682 tv = timeval_current();
684 now = timeval_to_nttime(&tv);
686 data_blob_free(&fsp->op->global->backend_cookie);
687 fsp->op->global->backend_cookie = new_cookie;
689 fsp->op->compat = NULL;
690 tmp = smbXsrv_open_close(fsp->op, now);
691 if (!NT_STATUS_IS_OK(tmp)) {
692 DEBUG(1, ("Failed to update smbXsrv_open "
693 "record when disconnecting durable "
694 "handle for file %s: %s - "
695 "proceeding with normal close\n",
696 fsp_str_dbg(fsp), nt_errstr(tmp)));
698 scavenger_schedule_disconnected(fsp);
699 } else {
700 DEBUG(1, ("Failed to disconnect durable handle for "
701 "file %s: %s - proceeding with normal "
702 "close\n", fsp_str_dbg(fsp), nt_errstr(tmp)));
704 if (!NT_STATUS_IS_OK(tmp)) {
705 is_durable = false;
709 if (is_durable) {
711 * This is the case where we successfully disconnected
712 * a durable handle and closed the underlying file.
713 * In all other cases, we proceed with a genuine close.
715 DEBUG(10, ("%s disconnected durable handle for file %s\n",
716 conn->session_info->unix_info->unix_name,
717 fsp_str_dbg(fsp)));
718 file_free(req, fsp);
719 return NT_STATUS_OK;
722 if (fsp->op != NULL) {
724 * Make sure the handle is not marked as durable anymore
726 fsp->op->global->durable = false;
729 if (fsp->print_file) {
730 /* FIXME: return spool errors */
731 print_spool_end(fsp, close_type);
732 file_free(req, fsp);
733 return NT_STATUS_OK;
736 /* Remove the oplock before potentially deleting the file. */
737 if(fsp->oplock_type) {
738 remove_oplock(fsp);
741 /* If this is an old DOS or FCB open and we have multiple opens on
742 the same handle we only have one share mode. Ensure we only remove
743 the share mode on the last close. */
745 if (fsp->fh->ref_count == 1) {
746 /* Should we return on error here... ? */
747 tmp = close_remove_share_mode(fsp, close_type);
748 status = ntstatus_keeperror(status, tmp);
751 locking_close_file(conn->sconn->msg_ctx, fsp, close_type);
753 tmp = fd_close(fsp);
754 status = ntstatus_keeperror(status, tmp);
756 /* check for magic scripts */
757 if (close_type == NORMAL_CLOSE) {
758 tmp = check_magic(fsp);
759 status = ntstatus_keeperror(status, tmp);
763 * Ensure pending modtime is set after close.
766 tmp = update_write_time_on_close(fsp);
767 if (NT_STATUS_EQUAL(tmp, NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
768 /* Someone renamed the file or a parent directory containing
769 * this file. We can't do anything about this, we don't have
770 * an "update timestamp by fd" call in POSIX. Eat the error. */
772 tmp = NT_STATUS_OK;
775 status = ntstatus_keeperror(status, tmp);
777 DEBUG(2,("%s closed file %s (numopen=%d) %s\n",
778 conn->session_info->unix_info->unix_name, fsp_str_dbg(fsp),
779 conn->num_files_open - 1,
780 nt_errstr(status) ));
782 file_free(req, fsp);
783 return status;
785 /****************************************************************************
786 Function used by reply_rmdir to delete an entire directory
787 tree recursively. Return True on ok, False on fail.
788 ****************************************************************************/
790 bool recursive_rmdir(TALLOC_CTX *ctx,
791 connection_struct *conn,
792 struct smb_filename *smb_dname)
794 const char *dname = NULL;
795 char *talloced = NULL;
796 bool ret = True;
797 long offset = 0;
798 SMB_STRUCT_STAT st;
799 struct smb_Dir *dir_hnd;
801 SMB_ASSERT(!is_ntfs_stream_smb_fname(smb_dname));
803 dir_hnd = OpenDir(talloc_tos(), conn, smb_dname->base_name, NULL, 0);
804 if(dir_hnd == NULL)
805 return False;
807 while((dname = ReadDirName(dir_hnd, &offset, &st, &talloced))) {
808 struct smb_filename *smb_dname_full = NULL;
809 char *fullname = NULL;
810 bool do_break = true;
812 if (ISDOT(dname) || ISDOTDOT(dname)) {
813 TALLOC_FREE(talloced);
814 continue;
817 if (!is_visible_file(conn, smb_dname->base_name, dname, &st,
818 false)) {
819 TALLOC_FREE(talloced);
820 continue;
823 /* Construct the full name. */
824 fullname = talloc_asprintf(ctx,
825 "%s/%s",
826 smb_dname->base_name,
827 dname);
828 if (!fullname) {
829 errno = ENOMEM;
830 goto err_break;
833 smb_dname_full = synthetic_smb_fname(talloc_tos(), fullname,
834 NULL, NULL);
835 if (smb_dname_full == NULL) {
836 errno = ENOMEM;
837 goto err_break;
840 if(SMB_VFS_LSTAT(conn, smb_dname_full) != 0) {
841 goto err_break;
844 if(smb_dname_full->st.st_ex_mode & S_IFDIR) {
845 if(!recursive_rmdir(ctx, conn, smb_dname_full)) {
846 goto err_break;
848 if(SMB_VFS_RMDIR(conn,
849 smb_dname_full->base_name) != 0) {
850 goto err_break;
852 } else if(SMB_VFS_UNLINK(conn, smb_dname_full) != 0) {
853 goto err_break;
856 /* Successful iteration. */
857 do_break = false;
859 err_break:
860 TALLOC_FREE(smb_dname_full);
861 TALLOC_FREE(fullname);
862 TALLOC_FREE(talloced);
863 if (do_break) {
864 ret = false;
865 break;
868 TALLOC_FREE(dir_hnd);
869 return ret;
872 /****************************************************************************
873 The internals of the rmdir code - called elsewhere.
874 ****************************************************************************/
876 static NTSTATUS rmdir_internals(TALLOC_CTX *ctx, files_struct *fsp)
878 connection_struct *conn = fsp->conn;
879 struct smb_filename *smb_dname = fsp->fsp_name;
880 int ret;
882 SMB_ASSERT(!is_ntfs_stream_smb_fname(smb_dname));
884 /* Might be a symlink. */
885 if(SMB_VFS_LSTAT(conn, smb_dname) != 0) {
886 return map_nt_error_from_unix(errno);
889 if (S_ISLNK(smb_dname->st.st_ex_mode)) {
890 /* Is what it points to a directory ? */
891 if(SMB_VFS_STAT(conn, smb_dname) != 0) {
892 return map_nt_error_from_unix(errno);
894 if (!(S_ISDIR(smb_dname->st.st_ex_mode))) {
895 return NT_STATUS_NOT_A_DIRECTORY;
897 ret = SMB_VFS_UNLINK(conn, smb_dname);
898 } else {
899 ret = SMB_VFS_RMDIR(conn, smb_dname->base_name);
901 if (ret == 0) {
902 notify_fname(conn, NOTIFY_ACTION_REMOVED,
903 FILE_NOTIFY_CHANGE_DIR_NAME,
904 smb_dname->base_name);
905 return NT_STATUS_OK;
908 if(((errno == ENOTEMPTY)||(errno == EEXIST)) && *lp_veto_files(talloc_tos(), SNUM(conn))) {
910 * Check to see if the only thing in this directory are
911 * vetoed files/directories. If so then delete them and
912 * retry. If we fail to delete any of them (and we *don't*
913 * do a recursive delete) then fail the rmdir.
915 SMB_STRUCT_STAT st;
916 const char *dname = NULL;
917 char *talloced = NULL;
918 long dirpos = 0;
919 struct smb_Dir *dir_hnd = OpenDir(talloc_tos(), conn,
920 smb_dname->base_name, NULL,
923 if(dir_hnd == NULL) {
924 errno = ENOTEMPTY;
925 goto err;
928 while ((dname = ReadDirName(dir_hnd, &dirpos, &st,
929 &talloced)) != NULL) {
930 if((strcmp(dname, ".") == 0) || (strcmp(dname, "..")==0)) {
931 TALLOC_FREE(talloced);
932 continue;
934 if (!is_visible_file(conn, smb_dname->base_name, dname,
935 &st, false)) {
936 TALLOC_FREE(talloced);
937 continue;
939 if(!IS_VETO_PATH(conn, dname)) {
940 TALLOC_FREE(dir_hnd);
941 TALLOC_FREE(talloced);
942 errno = ENOTEMPTY;
943 goto err;
945 TALLOC_FREE(talloced);
948 /* We only have veto files/directories.
949 * Are we allowed to delete them ? */
951 if(!lp_delete_veto_files(SNUM(conn))) {
952 TALLOC_FREE(dir_hnd);
953 errno = ENOTEMPTY;
954 goto err;
957 /* Do a recursive delete. */
958 RewindDir(dir_hnd,&dirpos);
959 while ((dname = ReadDirName(dir_hnd, &dirpos, &st,
960 &talloced)) != NULL) {
961 struct smb_filename *smb_dname_full = NULL;
962 char *fullname = NULL;
963 bool do_break = true;
965 if (ISDOT(dname) || ISDOTDOT(dname)) {
966 TALLOC_FREE(talloced);
967 continue;
969 if (!is_visible_file(conn, smb_dname->base_name, dname,
970 &st, false)) {
971 TALLOC_FREE(talloced);
972 continue;
975 fullname = talloc_asprintf(ctx,
976 "%s/%s",
977 smb_dname->base_name,
978 dname);
980 if(!fullname) {
981 errno = ENOMEM;
982 goto err_break;
985 smb_dname_full = synthetic_smb_fname(
986 talloc_tos(), fullname, NULL, NULL);
987 if (smb_dname_full == NULL) {
988 errno = ENOMEM;
989 goto err_break;
992 if(SMB_VFS_LSTAT(conn, smb_dname_full) != 0) {
993 goto err_break;
995 if(smb_dname_full->st.st_ex_mode & S_IFDIR) {
996 if(!recursive_rmdir(ctx, conn,
997 smb_dname_full)) {
998 goto err_break;
1000 if(SMB_VFS_RMDIR(conn,
1001 smb_dname_full->base_name) != 0) {
1002 goto err_break;
1004 } else if(SMB_VFS_UNLINK(conn, smb_dname_full) != 0) {
1005 goto err_break;
1008 /* Successful iteration. */
1009 do_break = false;
1011 err_break:
1012 TALLOC_FREE(fullname);
1013 TALLOC_FREE(smb_dname_full);
1014 TALLOC_FREE(talloced);
1015 if (do_break)
1016 break;
1018 TALLOC_FREE(dir_hnd);
1019 /* Retry the rmdir */
1020 ret = SMB_VFS_RMDIR(conn, smb_dname->base_name);
1023 err:
1025 if (ret != 0) {
1026 DEBUG(3,("rmdir_internals: couldn't remove directory %s : "
1027 "%s\n", smb_fname_str_dbg(smb_dname),
1028 strerror(errno)));
1029 return map_nt_error_from_unix(errno);
1032 notify_fname(conn, NOTIFY_ACTION_REMOVED,
1033 FILE_NOTIFY_CHANGE_DIR_NAME,
1034 smb_dname->base_name);
1036 return NT_STATUS_OK;
1039 /****************************************************************************
1040 Close a directory opened by an NT SMB call.
1041 ****************************************************************************/
1043 static NTSTATUS close_directory(struct smb_request *req, files_struct *fsp,
1044 enum file_close_type close_type)
1046 struct server_id self = messaging_server_id(fsp->conn->sconn->msg_ctx);
1047 struct share_mode_lock *lck = NULL;
1048 bool delete_dir = False;
1049 NTSTATUS status = NT_STATUS_OK;
1050 NTSTATUS status1 = NT_STATUS_OK;
1051 const struct security_token *del_nt_token = NULL;
1052 const struct security_unix_token *del_token = NULL;
1055 * NT can set delete_on_close of the last open
1056 * reference to a directory also.
1059 lck = get_existing_share_mode_lock(talloc_tos(), fsp->file_id);
1060 if (lck == NULL) {
1061 DEBUG(0, ("close_directory: Could not get share mode lock for "
1062 "%s\n", fsp_str_dbg(fsp)));
1063 return NT_STATUS_INVALID_PARAMETER;
1066 if (fsp->initial_delete_on_close) {
1067 bool became_user = False;
1069 /* Initial delete on close was set - for
1070 * directories we don't care if anyone else
1071 * wrote a real delete on close. */
1073 if (get_current_vuid(fsp->conn) != fsp->vuid) {
1074 become_user(fsp->conn, fsp->vuid);
1075 became_user = True;
1077 send_stat_cache_delete_message(fsp->conn->sconn->msg_ctx,
1078 fsp->fsp_name->base_name);
1079 set_delete_on_close_lck(fsp, lck, true,
1080 get_current_nttok(fsp->conn),
1081 get_current_utok(fsp->conn));
1082 fsp->delete_on_close = true;
1083 if (became_user) {
1084 unbecome_user();
1088 delete_dir = get_delete_on_close_token(lck, fsp->name_hash,
1089 &del_nt_token, &del_token);
1091 if (delete_dir) {
1092 int i;
1093 /* See if others still have the dir open. If this is the
1094 * case, then don't delete. If all opens are POSIX delete now. */
1095 for (i=0; i<lck->data->num_share_modes; i++) {
1096 struct share_mode_entry *e = &lck->data->share_modes[i];
1097 if (is_valid_share_mode_entry(e) &&
1098 e->name_hash == fsp->name_hash) {
1099 if (fsp->posix_open && (e->flags & SHARE_MODE_FLAG_POSIX_OPEN)) {
1100 continue;
1102 if (serverid_equal(&self, &e->pid) &&
1103 (e->share_file_id == fsp->fh->gen_id)) {
1104 continue;
1106 if (share_mode_stale_pid(lck->data, i)) {
1107 continue;
1109 delete_dir = False;
1110 break;
1115 if ((close_type == NORMAL_CLOSE || close_type == SHUTDOWN_CLOSE) &&
1116 delete_dir) {
1118 /* Become the user who requested the delete. */
1120 if (!push_sec_ctx()) {
1121 smb_panic("close_directory: failed to push sec_ctx.\n");
1124 set_sec_ctx(del_token->uid,
1125 del_token->gid,
1126 del_token->ngroups,
1127 del_token->groups,
1128 del_nt_token);
1130 if (!del_share_mode(lck, fsp)) {
1131 DEBUG(0, ("close_directory: Could not delete share entry for "
1132 "%s\n", fsp_str_dbg(fsp)));
1135 TALLOC_FREE(lck);
1137 if ((fsp->conn->fs_capabilities & FILE_NAMED_STREAMS)
1138 && !is_ntfs_stream_smb_fname(fsp->fsp_name)) {
1140 status = delete_all_streams(fsp->conn, fsp->fsp_name->base_name);
1141 if (!NT_STATUS_IS_OK(status)) {
1142 DEBUG(5, ("delete_all_streams failed: %s\n",
1143 nt_errstr(status)));
1144 return status;
1148 status = rmdir_internals(talloc_tos(), fsp);
1150 DEBUG(5,("close_directory: %s. Delete on close was set - "
1151 "deleting directory returned %s.\n",
1152 fsp_str_dbg(fsp), nt_errstr(status)));
1154 /* unbecome user. */
1155 pop_sec_ctx();
1158 * Ensure we remove any change notify requests that would
1159 * now fail as the directory has been deleted.
1162 if(NT_STATUS_IS_OK(status)) {
1163 remove_pending_change_notify_requests_by_fid(fsp, NT_STATUS_DELETE_PENDING);
1165 } else {
1166 if (!del_share_mode(lck, fsp)) {
1167 DEBUG(0, ("close_directory: Could not delete share entry for "
1168 "%s\n", fsp_str_dbg(fsp)));
1171 TALLOC_FREE(lck);
1172 remove_pending_change_notify_requests_by_fid(
1173 fsp, NT_STATUS_OK);
1176 status1 = fd_close(fsp);
1178 if (!NT_STATUS_IS_OK(status1)) {
1179 DEBUG(0, ("Could not close dir! fname=%s, fd=%d, err=%d=%s\n",
1180 fsp_str_dbg(fsp), fsp->fh->fd, errno,
1181 strerror(errno)));
1185 * Do the code common to files and directories.
1187 close_filestruct(fsp);
1188 file_free(req, fsp);
1190 if (NT_STATUS_IS_OK(status) && !NT_STATUS_IS_OK(status1)) {
1191 status = status1;
1193 return status;
1196 /****************************************************************************
1197 Close a files_struct.
1198 ****************************************************************************/
1200 NTSTATUS close_file(struct smb_request *req, files_struct *fsp,
1201 enum file_close_type close_type)
1203 NTSTATUS status;
1204 struct files_struct *base_fsp = fsp->base_fsp;
1206 if(fsp->is_directory) {
1207 status = close_directory(req, fsp, close_type);
1208 } else if (fsp->fake_file_handle != NULL) {
1209 status = close_fake_file(req, fsp);
1210 } else {
1211 status = close_normal_file(req, fsp, close_type);
1214 if ((base_fsp != NULL) && (close_type != SHUTDOWN_CLOSE)) {
1217 * fsp was a stream, the base fsp can't be a stream as well
1219 * For SHUTDOWN_CLOSE this is not possible here, because
1220 * SHUTDOWN_CLOSE only happens from files.c which walks the
1221 * complete list of files. If we mess with more than one fsp
1222 * those loops will become confused.
1225 SMB_ASSERT(base_fsp->base_fsp == NULL);
1226 close_file(req, base_fsp, close_type);
1229 return status;
1232 /****************************************************************************
1233 Deal with an (authorized) message to close a file given the share mode
1234 entry.
1235 ****************************************************************************/
1237 void msg_close_file(struct messaging_context *msg_ctx,
1238 void *private_data,
1239 uint32_t msg_type,
1240 struct server_id server_id,
1241 DATA_BLOB *data)
1243 files_struct *fsp = NULL;
1244 struct share_mode_entry e;
1245 struct smbd_server_connection *sconn =
1246 talloc_get_type_abort(private_data,
1247 struct smbd_server_connection);
1249 message_to_share_mode_entry(&e, (char *)data->data);
1251 if(DEBUGLVL(10)) {
1252 char *sm_str = share_mode_str(NULL, 0, &e);
1253 if (!sm_str) {
1254 smb_panic("talloc failed");
1256 DEBUG(10,("msg_close_file: got request to close share mode "
1257 "entry %s\n", sm_str));
1258 TALLOC_FREE(sm_str);
1261 fsp = file_find_dif(sconn, e.id, e.share_file_id);
1262 if (!fsp) {
1263 DEBUG(10,("msg_close_file: failed to find file.\n"));
1264 return;
1266 close_file(NULL, fsp, NORMAL_CLOSE);