Get closer to an accurate model of Windows timestamp changes.
[Samba/fernandojvsilva.git] / source3 / smbd / close.c
blobc1623ce290c3ed272885f24d8817a32a8921709b
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"
24 extern struct current_user current_user;
26 /****************************************************************************
27 Run a file if it is a magic script.
28 ****************************************************************************/
30 static NTSTATUS check_magic(struct files_struct *fsp)
32 int ret;
33 const char *magic_output = NULL;
34 SMB_STRUCT_STAT st;
35 int tmp_fd, outfd;
36 TALLOC_CTX *ctx = NULL;
37 const char *p;
38 struct connection_struct *conn = fsp->conn;
39 char *fname = NULL;
40 NTSTATUS status;
42 if (!*lp_magicscript(SNUM(conn))) {
43 return NT_STATUS_OK;
46 DEBUG(5,("checking magic for %s\n", fsp_str_dbg(fsp)));
48 ctx = talloc_stackframe();
50 fname = fsp->fsp_name->base_name;
52 if (!(p = strrchr_m(fname,'/'))) {
53 p = fname;
54 } else {
55 p++;
58 if (!strequal(lp_magicscript(SNUM(conn)),p)) {
59 status = NT_STATUS_OK;
60 goto out;
63 if (*lp_magicoutput(SNUM(conn))) {
64 magic_output = lp_magicoutput(SNUM(conn));
65 } else {
66 magic_output = talloc_asprintf(ctx,
67 "%s.out",
68 fname);
70 if (!magic_output) {
71 status = NT_STATUS_NO_MEMORY;
72 goto out;
75 /* Ensure we don't depend on user's PATH. */
76 p = talloc_asprintf(ctx, "./%s", fname);
77 if (!p) {
78 status = NT_STATUS_NO_MEMORY;
79 goto out;
82 if (chmod(fname, 0755) == -1) {
83 status = map_nt_error_from_unix(errno);
84 goto out;
86 ret = smbrun(p,&tmp_fd);
87 DEBUG(3,("Invoking magic command %s gave %d\n",
88 p,ret));
90 unlink(fname);
91 if (ret != 0 || tmp_fd == -1) {
92 if (tmp_fd != -1) {
93 close(tmp_fd);
95 status = NT_STATUS_UNSUCCESSFUL;
96 goto out;
98 outfd = open(magic_output, O_CREAT|O_EXCL|O_RDWR, 0600);
99 if (outfd == -1) {
100 int err = errno;
101 close(tmp_fd);
102 status = map_nt_error_from_unix(err);
103 goto out;
106 if (sys_fstat(tmp_fd,&st) == -1) {
107 int err = errno;
108 close(tmp_fd);
109 close(outfd);
110 status = map_nt_error_from_unix(err);
111 goto out;
114 if (transfer_file(tmp_fd,outfd,(SMB_OFF_T)st.st_ex_size) == (SMB_OFF_T)-1) {
115 int err = errno;
116 close(tmp_fd);
117 close(outfd);
118 status = map_nt_error_from_unix(err);
119 goto out;
121 close(tmp_fd);
122 if (close(outfd) == -1) {
123 status = map_nt_error_from_unix(errno);
124 goto out;
127 status = NT_STATUS_OK;
129 out:
130 TALLOC_FREE(ctx);
131 return status;
134 /****************************************************************************
135 Common code to close a file or a directory.
136 ****************************************************************************/
138 static NTSTATUS close_filestruct(files_struct *fsp)
140 NTSTATUS status = NT_STATUS_OK;
142 if (fsp->fh->fd != -1) {
143 if(flush_write_cache(fsp, CLOSE_FLUSH) == -1) {
144 status = map_nt_error_from_unix(errno);
146 delete_write_cache(fsp);
149 return status;
152 /****************************************************************************
153 If any deferred opens are waiting on this close, notify them.
154 ****************************************************************************/
156 static void notify_deferred_opens(struct share_mode_lock *lck)
158 int i;
160 if (!should_notify_deferred_opens()) {
161 return;
164 for (i=0; i<lck->num_share_modes; i++) {
165 struct share_mode_entry *e = &lck->share_modes[i];
167 if (!is_deferred_open_entry(e)) {
168 continue;
171 if (procid_is_me(&e->pid)) {
173 * We need to notify ourself to retry the open. Do
174 * this by finding the queued SMB record, moving it to
175 * the head of the queue and changing the wait time to
176 * zero.
178 schedule_deferred_open_smb_message(e->op_mid);
179 } else {
180 char msg[MSG_SMB_SHARE_MODE_ENTRY_SIZE];
182 share_mode_entry_to_message(msg, e);
184 messaging_send_buf(smbd_messaging_context(),
185 e->pid, MSG_SMB_OPEN_RETRY,
186 (uint8 *)msg,
187 MSG_SMB_SHARE_MODE_ENTRY_SIZE);
192 /****************************************************************************
193 Delete all streams
194 ****************************************************************************/
196 NTSTATUS delete_all_streams(connection_struct *conn, const char *fname)
198 struct stream_struct *stream_info;
199 int i;
200 unsigned int num_streams;
201 TALLOC_CTX *frame = talloc_stackframe();
202 NTSTATUS status;
204 status = SMB_VFS_STREAMINFO(conn, NULL, fname, talloc_tos(),
205 &num_streams, &stream_info);
207 if (NT_STATUS_EQUAL(status, NT_STATUS_NOT_IMPLEMENTED)) {
208 DEBUG(10, ("no streams around\n"));
209 TALLOC_FREE(frame);
210 return NT_STATUS_OK;
213 if (!NT_STATUS_IS_OK(status)) {
214 DEBUG(10, ("SMB_VFS_STREAMINFO failed: %s\n",
215 nt_errstr(status)));
216 goto fail;
219 DEBUG(10, ("delete_all_streams found %d streams\n",
220 num_streams));
222 if (num_streams == 0) {
223 TALLOC_FREE(frame);
224 return NT_STATUS_OK;
227 for (i=0; i<num_streams; i++) {
228 int res;
229 struct smb_filename *smb_fname_stream = NULL;
231 if (strequal(stream_info[i].name, "::$DATA")) {
232 continue;
235 status = create_synthetic_smb_fname(talloc_tos(), fname,
236 stream_info[i].name, NULL,
237 &smb_fname_stream);
239 if (!NT_STATUS_IS_OK(status)) {
240 DEBUG(0, ("talloc_aprintf failed\n"));
241 goto fail;
244 res = SMB_VFS_UNLINK(conn, smb_fname_stream);
246 if (res == -1) {
247 status = map_nt_error_from_unix(errno);
248 DEBUG(10, ("Could not delete stream %s: %s\n",
249 smb_fname_str_dbg(smb_fname_stream),
250 strerror(errno)));
251 TALLOC_FREE(smb_fname_stream);
252 break;
254 TALLOC_FREE(smb_fname_stream);
257 fail:
258 TALLOC_FREE(frame);
259 return status;
262 /****************************************************************************
263 Deal with removing a share mode on last close.
264 ****************************************************************************/
266 static NTSTATUS close_remove_share_mode(files_struct *fsp,
267 enum file_close_type close_type)
269 connection_struct *conn = fsp->conn;
270 bool delete_file = false;
271 bool changed_user = false;
272 struct share_mode_lock *lck = NULL;
273 NTSTATUS status = NT_STATUS_OK;
274 NTSTATUS tmp_status;
275 struct file_id id;
278 * Lock the share entries, and determine if we should delete
279 * on close. If so delete whilst the lock is still in effect.
280 * This prevents race conditions with the file being created. JRA.
283 lck = get_share_mode_lock(talloc_tos(), fsp->file_id, NULL, NULL,
284 NULL);
286 if (lck == NULL) {
287 DEBUG(0, ("close_remove_share_mode: Could not get share mode "
288 "lock for file %s\n", fsp_str_dbg(fsp)));
289 status = NT_STATUS_INVALID_PARAMETER;
290 goto done;
293 if (fsp->write_time_forced) {
294 DEBUG(10,("close_remove_share_mode: write time forced "
295 "for file %s\n",
296 fsp_str_dbg(fsp)));
297 set_close_write_time(lck, fsp, lck->changed_write_time);
298 } else if (fsp->update_write_time_on_close) {
299 DEBUG(10,("close_remove_share_mode: update_write_time_on_close "
300 "set for file %s\n",
301 fsp_str_dbg(fsp)));
302 set_close_write_time(lck, fsp, timespec_current());
305 if (!del_share_mode(lck, fsp)) {
306 DEBUG(0, ("close_remove_share_mode: Could not delete share "
307 "entry for file %s\n",
308 fsp_str_dbg(fsp)));
311 if (fsp->initial_delete_on_close && (lck->delete_token == NULL)) {
312 bool became_user = False;
314 /* Initial delete on close was set and no one else
315 * wrote a real delete on close. */
317 if (current_user.vuid != fsp->vuid) {
318 become_user(conn, fsp->vuid);
319 became_user = True;
321 set_delete_on_close_lck(lck, True, &current_user.ut);
322 if (became_user) {
323 unbecome_user();
327 delete_file = lck->delete_on_close;
329 if (delete_file) {
330 int i;
331 /* See if others still have the file open. If this is the
332 * case, then don't delete. If all opens are POSIX delete now. */
333 for (i=0; i<lck->num_share_modes; i++) {
334 struct share_mode_entry *e = &lck->share_modes[i];
335 if (is_valid_share_mode_entry(e)) {
336 if (fsp->posix_open && (e->flags & SHARE_MODE_FLAG_POSIX_OPEN)) {
337 continue;
339 delete_file = False;
340 break;
345 /* Notify any deferred opens waiting on this close. */
346 notify_deferred_opens(lck);
347 reply_to_oplock_break_requests(fsp);
350 * NT can set delete_on_close of the last open
351 * reference to a file.
354 if (!(close_type == NORMAL_CLOSE || close_type == SHUTDOWN_CLOSE)
355 || !delete_file
356 || (lck->delete_token == NULL)) {
357 TALLOC_FREE(lck);
358 return NT_STATUS_OK;
362 * Ok, we have to delete the file
365 DEBUG(5,("close_remove_share_mode: file %s. Delete on close was set "
366 "- deleting file.\n", fsp_str_dbg(fsp)));
369 * Don't try to update the write time when we delete the file
371 fsp->update_write_time_on_close = false;
373 if (!unix_token_equal(lck->delete_token, &current_user.ut)) {
374 /* Become the user who requested the delete. */
376 DEBUG(5,("close_remove_share_mode: file %s. "
377 "Change user to uid %u\n",
378 fsp_str_dbg(fsp),
379 (unsigned int)lck->delete_token->uid));
381 if (!push_sec_ctx()) {
382 smb_panic("close_remove_share_mode: file %s. failed to push "
383 "sec_ctx.\n");
386 set_sec_ctx(lck->delete_token->uid,
387 lck->delete_token->gid,
388 lck->delete_token->ngroups,
389 lck->delete_token->groups,
390 NULL);
392 changed_user = true;
395 /* We can only delete the file if the name we have is still valid and
396 hasn't been renamed. */
398 tmp_status = vfs_stat_fsp(fsp);
399 if (!NT_STATUS_IS_OK(tmp_status)) {
400 DEBUG(5,("close_remove_share_mode: file %s. Delete on close "
401 "was set and stat failed with error %s\n",
402 fsp_str_dbg(fsp), nt_errstr(tmp_status)));
404 * Don't save the errno here, we ignore this error
406 goto done;
409 id = vfs_file_id_from_sbuf(conn, &fsp->fsp_name->st);
411 if (!file_id_equal(&fsp->file_id, &id)) {
412 DEBUG(5,("close_remove_share_mode: file %s. Delete on close "
413 "was set and dev and/or inode does not match\n",
414 fsp_str_dbg(fsp)));
415 DEBUG(5,("close_remove_share_mode: file %s. stored file_id %s, "
416 "stat file_id %s\n",
417 fsp_str_dbg(fsp),
418 file_id_string_tos(&fsp->file_id),
419 file_id_string_tos(&id)));
421 * Don't save the errno here, we ignore this error
423 goto done;
426 if ((conn->fs_capabilities & FILE_NAMED_STREAMS)
427 && !is_ntfs_stream_smb_fname(fsp->fsp_name)) {
429 status = delete_all_streams(conn, fsp->fsp_name->base_name);
431 if (!NT_STATUS_IS_OK(status)) {
432 DEBUG(5, ("delete_all_streams failed: %s\n",
433 nt_errstr(status)));
434 goto done;
439 if (SMB_VFS_UNLINK(conn, fsp->fsp_name) != 0) {
441 * This call can potentially fail as another smbd may
442 * have had the file open with delete on close set and
443 * deleted it when its last reference to this file
444 * went away. Hence we log this but not at debug level
445 * zero.
448 DEBUG(5,("close_remove_share_mode: file %s. Delete on close "
449 "was set and unlink failed with error %s\n",
450 fsp_str_dbg(fsp), strerror(errno)));
452 status = map_nt_error_from_unix(errno);
455 notify_fname(conn, NOTIFY_ACTION_REMOVED,
456 FILE_NOTIFY_CHANGE_FILE_NAME,
457 fsp->fsp_name->base_name);
459 /* As we now have POSIX opens which can unlink
460 * with other open files we may have taken
461 * this code path with more than one share mode
462 * entry - ensure we only delete once by resetting
463 * the delete on close flag. JRA.
466 set_delete_on_close_lck(lck, False, NULL);
468 done:
470 if (changed_user) {
471 /* unbecome user. */
472 pop_sec_ctx();
475 TALLOC_FREE(lck);
476 return status;
479 void set_close_write_time(struct share_mode_lock *lck,
480 struct files_struct *fsp, struct timespec ts)
482 DEBUG(6,("close_write_time: %s" , time_to_asc(convert_timespec_to_time_t(ts))));
484 if (null_timespec(ts)) {
485 return;
488 * if the write time on close is explict set, then don't
489 * need to fix it up to the value in the locking db
491 fsp->write_time_forced = false;
493 fsp->update_write_time_on_close = true;
494 fsp->close_write_time = ts;
496 /* On close if we're changing the real file time we
497 * must update it in the open file db too. */
498 (void)set_write_time(fsp->file_id, ts);
499 /* If someone has a sticky write time then update it as well. */
500 if (lck && !null_timespec(lck->changed_write_time)) {
501 (void)set_sticky_write_time(fsp->file_id, ts);
505 static NTSTATUS update_write_time_on_close(struct files_struct *fsp)
507 struct smb_file_time ft;
508 NTSTATUS status;
510 ZERO_STRUCT(ft);
512 if (!fsp->update_write_time_on_close) {
513 return NT_STATUS_OK;
516 if (null_timespec(fsp->close_write_time)) {
517 fsp->close_write_time = timespec_current();
520 /* Ensure we have a valid stat struct for the source. */
521 status = vfs_stat_fsp(fsp);
522 if (!NT_STATUS_IS_OK(status)) {
523 return status;
526 if (!VALID_STAT(fsp->fsp_name->st)) {
527 /* if it doesn't seem to be a real file */
528 return NT_STATUS_OK;
531 ft.mtime = fsp->close_write_time;
532 status = smb_set_file_time(fsp->conn, fsp, fsp->fsp_name, &ft, true);
533 if (!NT_STATUS_IS_OK(status)) {
534 return status;
537 return status;
540 static NTSTATUS ntstatus_keeperror(NTSTATUS s1, NTSTATUS s2)
542 if (!NT_STATUS_IS_OK(s1)) {
543 return s1;
545 return s2;
548 /****************************************************************************
549 Close a file.
551 close_type can be NORMAL_CLOSE=0,SHUTDOWN_CLOSE,ERROR_CLOSE.
552 printing and magic scripts are only run on normal close.
553 delete on close is done on normal and shutdown close.
554 ****************************************************************************/
556 static NTSTATUS close_normal_file(struct smb_request *req, files_struct *fsp,
557 enum file_close_type close_type)
559 NTSTATUS status = NT_STATUS_OK;
560 NTSTATUS tmp;
561 connection_struct *conn = fsp->conn;
563 if (fsp->aio_write_behind) {
565 * If we're finishing write behind on a close we can get a write
566 * error here, we must remember this.
568 int ret = wait_for_aio_completion(fsp);
569 if (ret) {
570 status = ntstatus_keeperror(
571 status, map_nt_error_from_unix(ret));
573 } else {
574 cancel_aio_by_fsp(fsp);
578 * If we're flushing on a close we can get a write
579 * error here, we must remember this.
582 tmp = close_filestruct(fsp);
583 status = ntstatus_keeperror(status, tmp);
585 if (fsp->print_file) {
586 print_fsp_end(fsp, close_type);
587 file_free(req, fsp);
588 return NT_STATUS_OK;
591 /* Remove the oplock before potentially deleting the file. */
592 if(fsp->oplock_type) {
593 release_file_oplock(fsp);
596 /* If this is an old DOS or FCB open and we have multiple opens on
597 the same handle we only have one share mode. Ensure we only remove
598 the share mode on the last close. */
600 if (fsp->fh->ref_count == 1) {
601 /* Should we return on error here... ? */
602 tmp = close_remove_share_mode(fsp, close_type);
603 status = ntstatus_keeperror(status, tmp);
606 locking_close_file(smbd_messaging_context(), fsp);
608 tmp = fd_close(fsp);
609 status = ntstatus_keeperror(status, tmp);
611 /* check for magic scripts */
612 if (close_type == NORMAL_CLOSE) {
613 tmp = check_magic(fsp);
614 status = ntstatus_keeperror(status, tmp);
618 * Ensure pending modtime is set after close.
621 tmp = update_write_time_on_close(fsp);
622 if (NT_STATUS_EQUAL(tmp, NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
623 /* Someone renamed the file or a parent directory containing
624 * this file. We can't do anything about this, we don't have
625 * an "update timestamp by fd" call in POSIX. Eat the error. */
627 tmp = NT_STATUS_OK;
630 status = ntstatus_keeperror(status, tmp);
632 DEBUG(2,("%s closed file %s (numopen=%d) %s\n",
633 conn->server_info->unix_name, fsp_str_dbg(fsp),
634 conn->num_files_open - 1,
635 nt_errstr(status) ));
637 file_free(req, fsp);
638 return status;
641 /****************************************************************************
642 Close a directory opened by an NT SMB call.
643 ****************************************************************************/
645 static NTSTATUS close_directory(struct smb_request *req, files_struct *fsp,
646 enum file_close_type close_type)
648 struct share_mode_lock *lck = NULL;
649 bool delete_dir = False;
650 NTSTATUS status = NT_STATUS_OK;
653 * NT can set delete_on_close of the last open
654 * reference to a directory also.
657 lck = get_share_mode_lock(talloc_tos(), fsp->file_id, NULL, NULL,
658 NULL);
660 if (lck == NULL) {
661 DEBUG(0, ("close_directory: Could not get share mode lock for "
662 "%s\n", fsp_str_dbg(fsp)));
663 status = NT_STATUS_INVALID_PARAMETER;
664 goto out;
667 if (!del_share_mode(lck, fsp)) {
668 DEBUG(0, ("close_directory: Could not delete share entry for "
669 "%s\n", fsp_str_dbg(fsp)));
672 if (fsp->initial_delete_on_close) {
673 bool became_user = False;
675 /* Initial delete on close was set - for
676 * directories we don't care if anyone else
677 * wrote a real delete on close. */
679 if (current_user.vuid != fsp->vuid) {
680 become_user(fsp->conn, fsp->vuid);
681 became_user = True;
683 send_stat_cache_delete_message(fsp->fsp_name->base_name);
684 set_delete_on_close_lck(lck, True, &current_user.ut);
685 if (became_user) {
686 unbecome_user();
690 delete_dir = lck->delete_on_close;
692 if (delete_dir) {
693 int i;
694 /* See if others still have the dir open. If this is the
695 * case, then don't delete. If all opens are POSIX delete now. */
696 for (i=0; i<lck->num_share_modes; i++) {
697 struct share_mode_entry *e = &lck->share_modes[i];
698 if (is_valid_share_mode_entry(e)) {
699 if (fsp->posix_open && (e->flags & SHARE_MODE_FLAG_POSIX_OPEN)) {
700 continue;
702 delete_dir = False;
703 break;
708 if ((close_type == NORMAL_CLOSE || close_type == SHUTDOWN_CLOSE) &&
709 delete_dir &&
710 lck->delete_token) {
712 /* Become the user who requested the delete. */
714 if (!push_sec_ctx()) {
715 smb_panic("close_directory: failed to push sec_ctx.\n");
718 set_sec_ctx(lck->delete_token->uid,
719 lck->delete_token->gid,
720 lck->delete_token->ngroups,
721 lck->delete_token->groups,
722 NULL);
724 TALLOC_FREE(lck);
726 status = rmdir_internals(talloc_tos(), fsp->conn,
727 fsp->fsp_name);
729 DEBUG(5,("close_directory: %s. Delete on close was set - "
730 "deleting directory returned %s.\n",
731 fsp_str_dbg(fsp), nt_errstr(status)));
733 /* unbecome user. */
734 pop_sec_ctx();
737 * Ensure we remove any change notify requests that would
738 * now fail as the directory has been deleted.
741 if(NT_STATUS_IS_OK(status)) {
742 remove_pending_change_notify_requests_by_fid(fsp, NT_STATUS_DELETE_PENDING);
744 } else {
745 TALLOC_FREE(lck);
746 remove_pending_change_notify_requests_by_fid(
747 fsp, NT_STATUS_OK);
750 status = fd_close(fsp);
752 if (!NT_STATUS_IS_OK(status)) {
753 DEBUG(0, ("Could not close dir! fname=%s, fd=%d, err=%d=%s\n",
754 fsp_str_dbg(fsp), fsp->fh->fd, errno,
755 strerror(errno)));
758 if (fsp->dptr) {
759 dptr_CloseDir(fsp->dptr);
763 * Do the code common to files and directories.
765 close_filestruct(fsp);
766 file_free(req, fsp);
768 out:
769 TALLOC_FREE(lck);
770 return status;
773 /****************************************************************************
774 Close a files_struct.
775 ****************************************************************************/
777 NTSTATUS close_file(struct smb_request *req, files_struct *fsp,
778 enum file_close_type close_type)
780 NTSTATUS status;
781 struct files_struct *base_fsp = fsp->base_fsp;
783 if(fsp->is_directory) {
784 status = close_directory(req, fsp, close_type);
785 } else if (fsp->fake_file_handle != NULL) {
786 status = close_fake_file(req, fsp);
787 } else {
788 status = close_normal_file(req, fsp, close_type);
791 if ((base_fsp != NULL) && (close_type != SHUTDOWN_CLOSE)) {
794 * fsp was a stream, the base fsp can't be a stream as well
796 * For SHUTDOWN_CLOSE this is not possible here, because
797 * SHUTDOWN_CLOSE only happens from files.c which walks the
798 * complete list of files. If we mess with more than one fsp
799 * those loops will become confused.
802 SMB_ASSERT(base_fsp->base_fsp == NULL);
803 close_file(req, base_fsp, close_type);
806 return status;
809 /****************************************************************************
810 Deal with an (authorized) message to close a file given the share mode
811 entry.
812 ****************************************************************************/
814 void msg_close_file(struct messaging_context *msg_ctx,
815 void *private_data,
816 uint32_t msg_type,
817 struct server_id server_id,
818 DATA_BLOB *data)
820 files_struct *fsp = NULL;
821 struct share_mode_entry e;
823 message_to_share_mode_entry(&e, (char *)data->data);
825 if(DEBUGLVL(10)) {
826 char *sm_str = share_mode_str(NULL, 0, &e);
827 if (!sm_str) {
828 smb_panic("talloc failed");
830 DEBUG(10,("msg_close_file: got request to close share mode "
831 "entry %s\n", sm_str));
832 TALLOC_FREE(sm_str);
835 fsp = file_find_dif(e.id, e.share_file_id);
836 if (!fsp) {
837 DEBUG(10,("msg_close_file: failed to find file.\n"));
838 return;
840 close_file(NULL, fsp, NORMAL_CLOSE);