2 Unix SMB/CIFS implementation.
3 file opening and share modes
4 Copyright (C) Andrew Tridgell 1992-1998
5 Copyright (C) Jeremy Allison 2001-2004
6 Copyright (C) Volker Lendecke 2005
7 Copyright (C) Ralph Boehme 2017
9 This program is free software; you can redistribute it and/or modify
10 it under the terms of the GNU General Public License as published by
11 the Free Software Foundation; either version 3 of the License, or
12 (at your option) any later version.
14 This program is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 GNU General Public License for more details.
19 You should have received a copy of the GNU General Public License
20 along with this program. If not, see <http://www.gnu.org/licenses/>.
24 #include "smb1_utils.h"
25 #include "system/filesys.h"
26 #include "lib/util/server_id.h"
28 #include "locking/share_mode_lock.h"
29 #include "smbd/smbd.h"
30 #include "smbd/globals.h"
31 #include "fake_file.h"
32 #include "../libcli/security/security.h"
33 #include "../librpc/gen_ndr/ndr_security.h"
34 #include "../librpc/gen_ndr/ndr_open_files.h"
35 #include "../librpc/gen_ndr/idmap.h"
36 #include "../librpc/gen_ndr/ioctl.h"
37 #include "passdb/lookup_sid.h"
41 #include "source3/lib/dbwrap/dbwrap_watch.h"
42 #include "locking/leases_db.h"
43 #include "librpc/gen_ndr/ndr_leases_db.h"
44 #include "lib/util/time_basic.h"
46 extern const struct generic_mapping file_generic_mapping;
48 struct deferred_open_record {
49 struct smbXsrv_connection *xconn;
55 * Timer for async opens, needed because they don't use a watch on
56 * a locking.tdb record. This is currently only used for real async
57 * opens and just terminates smbd if the async open times out.
59 struct tevent_timer *te;
62 * For the samba kernel oplock case we use both a timeout and
63 * a watch on locking.tdb. This way in case it's smbd holding
64 * the kernel oplock we get directly notified for the retry
65 * once the kernel oplock is properly broken. Store the req
66 * here so that it can be timely discarded once the timer
69 struct tevent_req *watch_req;
72 /****************************************************************************
73 If the requester wanted DELETE_ACCESS and was rejected because
74 the file ACL didn't include DELETE_ACCESS, see if the parent ACL
76 ****************************************************************************/
78 static bool parent_override_delete(connection_struct *conn,
79 const struct smb_filename *smb_fname,
81 uint32_t rejected_mask)
83 if ((access_mask & DELETE_ACCESS) &&
84 (rejected_mask & DELETE_ACCESS) &&
85 can_delete_file_in_directory(conn,
94 /****************************************************************************
95 Check if we have open rights.
96 ****************************************************************************/
98 static NTSTATUS smbd_check_access_rights_sd(
99 struct connection_struct *conn,
100 const struct smb_filename *smb_fname,
101 struct security_descriptor *sd,
103 uint32_t access_mask)
105 uint32_t rejected_share_access;
106 uint32_t rejected_mask = access_mask;
107 uint32_t do_not_check_mask = 0;
110 rejected_share_access = access_mask & ~(conn->share_access);
112 if (rejected_share_access) {
113 DBG_DEBUG("rejected share access 0x%x on %s (0x%x)\n",
114 (unsigned int)access_mask,
115 smb_fname_str_dbg(smb_fname),
116 (unsigned int)rejected_share_access);
117 return NT_STATUS_ACCESS_DENIED;
120 if (!use_privs && get_current_uid(conn) == (uid_t)0) {
121 /* I'm sorry sir, I didn't know you were root... */
122 DBG_DEBUG("root override on %s. Granting 0x%x\n",
123 smb_fname_str_dbg(smb_fname),
124 (unsigned int)access_mask);
128 if ((access_mask & DELETE_ACCESS) &&
129 !lp_acl_check_permissions(SNUM(conn)))
131 DBG_DEBUG("Not checking ACL on DELETE_ACCESS on file %s. "
133 smb_fname_str_dbg(smb_fname),
134 (unsigned int)access_mask);
138 if (access_mask == DELETE_ACCESS &&
139 VALID_STAT(smb_fname->st) &&
140 S_ISLNK(smb_fname->st.st_ex_mode))
142 /* We can always delete a symlink. */
143 DBG_DEBUG("Not checking ACL on DELETE_ACCESS on symlink %s.\n",
144 smb_fname_str_dbg(smb_fname));
153 * If we can access the path to this file, by
154 * default we have FILE_READ_ATTRIBUTES from the
155 * containing directory. See the section:
156 * "Algorithm to Check Access to an Existing File"
159 * se_file_access_check() also takes care of
160 * owner WRITE_DAC and READ_CONTROL.
162 do_not_check_mask = FILE_READ_ATTRIBUTES;
165 * Samba 3.6 and earlier granted execute access even
166 * if the ACL did not contain execute rights.
167 * Samba 4.0 is more correct and checks it.
168 * The compatibilty mode allows one to skip this check
169 * to smoothen upgrades.
171 if (lp_acl_allow_execute_always(SNUM(conn))) {
172 do_not_check_mask |= FILE_EXECUTE;
175 status = se_file_access_check(sd,
176 get_current_nttok(conn),
178 (access_mask & ~do_not_check_mask),
181 DBG_DEBUG("File [%s] requesting [0x%x] returning [0x%x] (%s)\n",
182 smb_fname_str_dbg(smb_fname),
183 (unsigned int)access_mask,
184 (unsigned int)rejected_mask,
187 if (!NT_STATUS_IS_OK(status)) {
188 if (DEBUGLEVEL >= 10) {
189 DBG_DEBUG("acl for %s is:\n",
190 smb_fname_str_dbg(smb_fname));
191 NDR_PRINT_DEBUG(security_descriptor, sd);
197 if (NT_STATUS_IS_OK(status) ||
198 !NT_STATUS_EQUAL(status, NT_STATUS_ACCESS_DENIED))
203 /* Here we know status == NT_STATUS_ACCESS_DENIED. */
207 if ((access_mask & FILE_WRITE_ATTRIBUTES) &&
208 (rejected_mask & FILE_WRITE_ATTRIBUTES) &&
209 !lp_store_dos_attributes(SNUM(conn)) &&
210 (lp_map_readonly(SNUM(conn)) ||
211 lp_map_archive(SNUM(conn)) ||
212 lp_map_hidden(SNUM(conn)) ||
213 lp_map_system(SNUM(conn))))
215 rejected_mask &= ~FILE_WRITE_ATTRIBUTES;
217 DBG_DEBUG("overrode FILE_WRITE_ATTRIBUTES on file %s\n",
218 smb_fname_str_dbg(smb_fname));
221 if (parent_override_delete(conn,
227 * Were we trying to do an open for delete and didn't get DELETE
228 * access. Check if the directory allows DELETE_CHILD.
230 * http://blogs.msdn.com/oldnewthing/archive/2004/06/04/148426.aspx
234 rejected_mask &= ~DELETE_ACCESS;
236 DBG_DEBUG("Overrode DELETE_ACCESS on file %s\n",
237 smb_fname_str_dbg(smb_fname));
240 if (rejected_mask != 0) {
241 return NT_STATUS_ACCESS_DENIED;
246 NTSTATUS smbd_check_access_rights(struct connection_struct *conn,
247 struct files_struct *dirfsp,
248 const struct smb_filename *smb_fname,
250 uint32_t access_mask)
252 /* Check if we have rights to open. */
254 struct security_descriptor *sd = NULL;
256 status = SMB_VFS_GET_NT_ACL_AT(conn,
265 if (NT_STATUS_EQUAL(status, NT_STATUS_ACCESS_DENIED)) {
266 status = NT_STATUS_OK;
268 if (!NT_STATUS_IS_OK(status)) {
269 DEBUG(10, ("smbd_check_access_rights: Could not get acl "
271 smb_fname_str_dbg(smb_fname),
276 return smbd_check_access_rights_sd(conn,
283 NTSTATUS smbd_check_access_rights_fsp(struct files_struct *fsp,
285 uint32_t access_mask)
287 struct security_descriptor *sd = NULL;
290 /* Cope with fake/printer fsp's. */
291 if (fsp->fake_file_handle != NULL || fsp->print_file != NULL) {
292 if ((fsp->access_mask & access_mask) != access_mask) {
293 return NT_STATUS_ACCESS_DENIED;
298 if (fsp_get_pathref_fd(fsp) == -1) {
300 * This is a POSIX open on a symlink. For the pathname
301 * verison of this function we used to return the st_mode
302 * bits turned into an NT ACL. For a symlink the mode bits
303 * are always rwxrwxrwx which means the pathname version always
304 * returned NT_STATUS_OK for a symlink. For the handle reference
305 * to a symlink use the handle access bits.
307 if ((fsp->access_mask & access_mask) != access_mask) {
308 return NT_STATUS_ACCESS_DENIED;
313 status = SMB_VFS_FGET_NT_ACL(fsp,
319 if (!NT_STATUS_IS_OK(status)) {
320 DBG_DEBUG("Could not get acl on %s: %s\n",
326 return smbd_check_access_rights_sd(fsp->conn,
333 NTSTATUS check_parent_access(struct connection_struct *conn,
334 struct files_struct *dirfsp,
335 struct smb_filename *smb_fname,
336 uint32_t access_mask)
339 struct security_descriptor *parent_sd = NULL;
340 uint32_t access_granted = 0;
341 struct smb_filename *parent_dir = NULL;
342 struct share_mode_lock *lck = NULL;
343 struct file_id id = {0};
345 bool delete_on_close_set;
347 TALLOC_CTX *frame = talloc_stackframe();
350 * NB. When dirfsp != conn->cwd_fsp, we must
351 * change parent_dir to be "." for the name here.
354 SMB_ASSERT(dirfsp == conn->cwd_fsp);
356 status = SMB_VFS_PARENT_PATHNAME(conn,
361 if (!NT_STATUS_IS_OK(status)) {
365 if (get_current_uid(conn) == (uid_t)0) {
366 /* I'm sorry sir, I didn't know you were root... */
367 DEBUG(10,("check_parent_access: root override "
368 "on %s. Granting 0x%x\n",
369 smb_fname_str_dbg(smb_fname),
370 (unsigned int)access_mask ));
371 status = NT_STATUS_OK;
375 status = SMB_VFS_GET_NT_ACL_AT(conn,
382 if (!NT_STATUS_IS_OK(status)) {
383 DBG_INFO("SMB_VFS_GET_NT_ACL_AT failed for "
384 "%s with error %s\n",
385 smb_fname_str_dbg(parent_dir),
391 * If we can access the path to this file, by
392 * default we have FILE_READ_ATTRIBUTES from the
393 * containing directory. See the section:
394 * "Algorithm to Check Access to an Existing File"
397 * se_file_access_check() also takes care of
398 * owner WRITE_DAC and READ_CONTROL.
400 status = se_file_access_check(parent_sd,
401 get_current_nttok(conn),
403 (access_mask & ~FILE_READ_ATTRIBUTES),
405 if(!NT_STATUS_IS_OK(status)) {
406 DEBUG(5,("check_parent_access: access check "
407 "on directory %s for "
408 "path %s for mask 0x%x returned (0x%x) %s\n",
409 smb_fname_str_dbg(parent_dir),
410 smb_fname->base_name,
413 nt_errstr(status) ));
417 if (!(access_mask & (SEC_DIR_ADD_FILE | SEC_DIR_ADD_SUBDIR))) {
418 status = NT_STATUS_OK;
421 if (!lp_check_parent_directory_delete_on_close(SNUM(conn))) {
422 status = NT_STATUS_OK;
426 /* Check if the directory has delete-on-close set */
427 ret = SMB_VFS_STAT(conn, parent_dir);
429 status = map_nt_error_from_unix(errno);
433 id = SMB_VFS_FILE_ID_CREATE(conn, &parent_dir->st);
435 status = file_name_hash(conn, parent_dir->base_name, &name_hash);
436 if (!NT_STATUS_IS_OK(status)) {
441 * Don't take a lock here. We just need a snapshot
442 * of the current state of delete on close and this is
443 * called in a codepath where we may already have a lock
444 * (and we explicitly can't hold 2 locks at the same time
445 * as that may deadlock).
447 lck = fetch_share_mode_unlocked(frame, id);
449 status = NT_STATUS_OK;
453 delete_on_close_set = is_delete_on_close_set(lck, name_hash);
454 if (delete_on_close_set) {
455 status = NT_STATUS_DELETE_PENDING;
459 status = NT_STATUS_OK;
466 /****************************************************************************
467 Ensure when opening a base file for a stream open that we have permissions
468 to do so given the access mask on the base file.
469 ****************************************************************************/
471 static NTSTATUS check_base_file_access(struct connection_struct *conn,
472 struct smb_filename *smb_fname,
473 uint32_t access_mask)
477 status = smbd_calculate_access_mask(conn,
483 if (!NT_STATUS_IS_OK(status)) {
484 DEBUG(10, ("smbd_calculate_access_mask "
485 "on file %s returned %s\n",
486 smb_fname_str_dbg(smb_fname),
491 if (access_mask & (FILE_WRITE_DATA|FILE_APPEND_DATA)) {
493 if (!CAN_WRITE(conn)) {
494 return NT_STATUS_ACCESS_DENIED;
496 dosattrs = fdos_mode(smb_fname->fsp);
497 if (IS_DOS_READONLY(dosattrs)) {
498 return NT_STATUS_ACCESS_DENIED;
502 return smbd_check_access_rights(conn,
509 /****************************************************************************
510 Handle differing symlink errno's
511 ****************************************************************************/
513 static NTSTATUS link_errno_convert(int err)
515 #if defined(ENOTSUP) && defined(OSF1)
516 /* handle special Tru64 errno */
517 if (err == ENOTSUP) {
522 /* fix broken NetBSD errno */
527 /* fix broken FreeBSD errno */
532 return NT_STATUS_STOPPED_ON_SYMLINK;
534 return map_nt_error_from_unix(err);
537 static NTSTATUS non_widelink_open(const struct files_struct *dirfsp,
539 struct smb_filename *smb_fname,
542 unsigned int link_depth);
544 /****************************************************************************
545 Follow a symlink in userspace.
546 ****************************************************************************/
548 static NTSTATUS process_symlink_open(const struct files_struct *dirfsp,
550 struct smb_filename *smb_fname,
553 unsigned int link_depth)
555 struct connection_struct *conn = dirfsp->conn;
556 const char *conn_rootdir = NULL;
557 struct smb_filename conn_rootdir_fname = { 0 };
558 char *link_target = NULL;
560 struct smb_filename *oldwd_fname = NULL;
561 size_t rootdir_len = 0;
562 struct smb_filename *resolved_fname = NULL;
563 char *resolved_name = NULL;
564 bool matched = false;
565 struct smb_filename *full_fname = NULL;
568 conn_rootdir = SMB_VFS_CONNECTPATH(conn, smb_fname);
569 if (conn_rootdir == NULL) {
570 return NT_STATUS_NO_MEMORY;
573 * With shadow_copy2 conn_rootdir can be talloc_freed
574 * whilst we use it in this function. We must take a copy.
576 conn_rootdir_fname.base_name = talloc_strdup(talloc_tos(),
578 if (conn_rootdir_fname.base_name == NULL) {
579 return NT_STATUS_NO_MEMORY;
583 * Ensure we don't get stuck in a symlink loop.
586 if (link_depth >= 20) {
587 status = NT_STATUS_STOPPED_ON_SYMLINK;
591 /* Allocate space for the link target. */
592 link_target = talloc_array(talloc_tos(), char, PATH_MAX);
593 if (link_target == NULL) {
594 status = NT_STATUS_NO_MEMORY;
599 * Read the link target. We do this just to verify that smb_fname indeed
600 * points at a symbolic link and return NT_STATUS_NOT_A_DIRECTORY
601 * and failure in case smb_fname is NOT a symlink.
603 * The caller needs this piece of information to distinguish two cases
604 * where open() fails with errno=ENOTDIR, cf the comment in
605 * non_widelink_open().
607 * We rely on SMB_VFS_REALPATH() to resolve the path including the
608 * symlink. Once we have SMB_VFS_STATX() or something similar in our VFS
609 * we may want to use that instead of SMB_VFS_READLINKAT().
611 link_len = SMB_VFS_READLINKAT(conn,
616 if (link_len == -1) {
617 status = NT_STATUS_INVALID_PARAMETER;
621 full_fname = full_path_from_dirfsp_atname(
622 talloc_tos(), dirfsp, smb_fname);
623 if (full_fname == NULL) {
624 status = NT_STATUS_NO_MEMORY;
628 /* Convert to an absolute path. */
629 resolved_fname = SMB_VFS_REALPATH(conn, talloc_tos(), full_fname);
630 if (resolved_fname == NULL) {
631 status = map_nt_error_from_unix(errno);
634 resolved_name = resolved_fname->base_name;
637 * We know conn_rootdir starts with '/' and
638 * does not end in '/'. FIXME ! Should we
641 rootdir_len = strlen(conn_rootdir_fname.base_name);
643 matched = (strncmp(conn_rootdir_fname.base_name,
647 status = NT_STATUS_STOPPED_ON_SYMLINK;
652 * Turn into a path relative to the share root.
654 if (resolved_name[rootdir_len] == '\0') {
655 /* Link to the root of the share. */
656 TALLOC_FREE(smb_fname->base_name);
657 smb_fname->base_name = talloc_strdup(smb_fname, ".");
658 } else if (resolved_name[rootdir_len] == '/') {
659 TALLOC_FREE(smb_fname->base_name);
660 smb_fname->base_name = talloc_strdup(smb_fname,
661 &resolved_name[rootdir_len+1]);
663 status = NT_STATUS_STOPPED_ON_SYMLINK;
667 if (smb_fname->base_name == NULL) {
668 status = NT_STATUS_NO_MEMORY;
672 oldwd_fname = vfs_GetWd(talloc_tos(), dirfsp->conn);
673 if (oldwd_fname == NULL) {
674 status = map_nt_error_from_unix(errno);
678 /* Ensure we operate from the root of the share. */
679 if (vfs_ChDir(conn, &conn_rootdir_fname) == -1) {
680 status = map_nt_error_from_unix(errno);
685 * And do it all again... As smb_fname is not relative to the passed in
686 * dirfsp anymore, we pass conn->cwd_fsp as dirfsp to
687 * non_widelink_open() to trigger the chdir(parentdir) logic.
689 status = non_widelink_open(conn->cwd_fsp,
698 TALLOC_FREE(resolved_fname);
699 TALLOC_FREE(link_target);
700 TALLOC_FREE(conn_rootdir_fname.base_name);
701 if (oldwd_fname != NULL) {
702 int ret = vfs_ChDir(conn, oldwd_fname);
704 smb_panic("unable to get back to old directory\n");
706 TALLOC_FREE(oldwd_fname);
712 /****************************************************************************
714 ****************************************************************************/
716 static NTSTATUS non_widelink_open(const struct files_struct *dirfsp,
718 struct smb_filename *smb_fname,
721 unsigned int link_depth)
723 struct connection_struct *conn = fsp->conn;
724 NTSTATUS saved_status;
725 NTSTATUS status = NT_STATUS_OK;
727 struct smb_filename *orig_fsp_name = fsp->fsp_name;
728 struct smb_filename *orig_base_fsp_name = NULL;
729 struct smb_filename *smb_fname_rel = NULL;
730 struct smb_filename base_smb_fname_rel;
731 struct smb_filename *oldwd_fname = NULL;
732 struct smb_filename *parent_dir_fname = NULL;
733 bool have_opath = false;
740 if (dirfsp == conn->cwd_fsp) {
741 if (fsp->fsp_flags.is_directory) {
742 parent_dir_fname = cp_smb_filename(talloc_tos(), smb_fname);
743 if (parent_dir_fname == NULL) {
744 status = NT_STATUS_NO_MEMORY;
748 smb_fname_rel = synthetic_smb_fname(parent_dir_fname,
750 smb_fname->stream_name,
754 if (smb_fname_rel == NULL) {
755 status = NT_STATUS_NO_MEMORY;
759 status = SMB_VFS_PARENT_PATHNAME(fsp->conn,
764 if (!NT_STATUS_IS_OK(status)) {
769 oldwd_fname = vfs_GetWd(talloc_tos(), conn);
770 if (oldwd_fname == NULL) {
771 status = map_nt_error_from_unix(errno);
775 /* Pin parent directory in place. */
776 if (vfs_ChDir(conn, parent_dir_fname) == -1) {
777 status = map_nt_error_from_unix(errno);
781 /* Ensure the relative path is below the share. */
782 status = check_reduced_name(conn, parent_dir_fname, smb_fname_rel);
783 if (!NT_STATUS_IS_OK(status)) {
787 /* Setup fsp->fsp_name to be relative to cwd */
788 fsp->fsp_name = smb_fname_rel;
790 /* Also setup base_fsp to be relative to the new cwd */
791 if (fsp->base_fsp != NULL) {
792 base_smb_fname_rel = (struct smb_filename) {
793 .base_name = smb_fname_rel->base_name,
795 orig_base_fsp_name = fsp->base_fsp->fsp_name;
796 fsp->base_fsp->fsp_name = &base_smb_fname_rel;
800 * fsp->fsp_name is unchanged as it is already correctly
801 * relative to conn->cwd.
803 smb_fname_rel = smb_fname;
808 fd = SMB_VFS_OPENAT(conn,
815 status = link_errno_convert(errno);
820 ret = SMB_VFS_FSTAT(fsp, &orig_fsp_name->st);
822 status = map_nt_error_from_unix(errno);
825 fsp->fsp_name->st = orig_fsp_name->st;
828 if (!is_ntfs_stream_smb_fname(fsp->fsp_name) &&
829 fsp->fsp_flags.is_pathref &&
833 * Opening with O_PATH and O_NOFOLLOW opens a handle on the
834 * symlink. In follow symlink=yes mode we must avoid this and
835 * instead should open a handle on the symlink target.
837 * Check for this case by doing an fstat, forcing
838 * process_symlink_open() codepath down below by setting fd=-1
841 if (S_ISLNK(fsp->fsp_name->st.st_ex_mode)) {
842 ret = SMB_VFS_CLOSE(fsp);
843 SMB_ASSERT(ret == 0);
847 status = NT_STATUS_STOPPED_ON_SYMLINK;
852 (NT_STATUS_EQUAL(status, NT_STATUS_STOPPED_ON_SYMLINK) ||
853 NT_STATUS_EQUAL(status, NT_STATUS_NOT_A_DIRECTORY)))
856 * Trying to open a symlink to a directory with O_NOFOLLOW and
857 * O_DIRECTORY can return either of ELOOP and ENOTDIR. So
858 * ENOTDIR really means: might be a symlink, but we're not sure.
859 * In this case, we just assume there's a symlink. If we were
860 * wrong, process_symlink_open() will return EINVAL. We check
861 * this below, and fall back to returning the initial
864 * BUG: https://bugzilla.samba.org/show_bug.cgi?id=12860
866 saved_status = status;
868 if (fsp->fsp_name->flags & SMB_FILENAME_POSIX_PATH) {
869 /* Never follow symlinks on posix open. */
872 if (!lp_follow_symlinks(SNUM(conn))) {
873 /* Explicitly no symlinks. */
877 fsp->fsp_name = orig_fsp_name;
880 * We may have a symlink. Follow in userspace
881 * to ensure it's under the share definition.
883 status = process_symlink_open(dirfsp,
889 if (NT_STATUS_EQUAL(status, NT_STATUS_INVALID_PARAMETER) &&
890 NT_STATUS_EQUAL(saved_status, NT_STATUS_NOT_A_DIRECTORY))
892 status = saved_status;
897 fsp->fsp_name = orig_fsp_name;
898 if (fsp->base_fsp != NULL) {
899 fsp->base_fsp->fsp_name = orig_base_fsp_name;
901 TALLOC_FREE(parent_dir_fname);
903 if (oldwd_fname != NULL) {
904 ret = vfs_ChDir(conn, oldwd_fname);
906 smb_panic("unable to get back to old directory\n");
908 TALLOC_FREE(oldwd_fname);
913 /****************************************************************************
914 fd support routines - attempt to do a dos_open.
915 ****************************************************************************/
917 NTSTATUS fd_openat(const struct files_struct *dirfsp,
918 struct smb_filename *smb_fname,
923 struct connection_struct *conn = fsp->conn;
924 NTSTATUS status = NT_STATUS_OK;
927 * Never follow symlinks on a POSIX client. The
928 * client should be doing this.
931 if ((fsp->posix_flags & FSP_POSIX_FLAGS_OPEN) || !lp_follow_symlinks(SNUM(conn))) {
936 * Only follow symlinks within a share
939 status = non_widelink_open(dirfsp, fsp, smb_fname, flags, mode, 0);
940 if (!NT_STATUS_IS_OK(status)) {
941 if (NT_STATUS_EQUAL(status, NT_STATUS_TOO_MANY_OPENED_FILES)) {
942 static time_t last_warned = 0L;
944 if (time((time_t *) NULL) > last_warned) {
945 DEBUG(0,("Too many open files, unable "
946 "to open more! smbd's max "
948 lp_max_open_files()));
949 last_warned = time((time_t *) NULL);
953 DBG_DEBUG("name %s, flags = 0%o mode = 0%o, fd = %d. %s\n",
954 smb_fname_str_dbg(smb_fname), flags, (int)mode,
955 fsp_get_pathref_fd(fsp), nt_errstr(status));
959 DBG_DEBUG("name %s, flags = 0%o mode = 0%o, fd = %d\n",
960 smb_fname_str_dbg(smb_fname), flags, (int)mode,
961 fsp_get_pathref_fd(fsp));
966 /****************************************************************************
967 Close the file associated with a fsp.
968 ****************************************************************************/
970 NTSTATUS fd_close(files_struct *fsp)
974 if (fsp == fsp->conn->cwd_fsp) {
981 if (fsp_get_pathref_fd(fsp) == -1) {
983 * Either a directory where the dptr_CloseDir() already closed
984 * the fd or a stat open.
988 if (fh_get_refcount(fsp->fh) > 1) {
989 return NT_STATUS_OK; /* Shared handle. Only close last reference. */
992 ret = SMB_VFS_CLOSE(fsp);
995 return map_nt_error_from_unix(errno);
1000 /****************************************************************************
1001 Change the ownership of a file to that of the parent directory.
1002 Do this by fd if possible.
1003 ****************************************************************************/
1005 void change_file_owner_to_parent(connection_struct *conn,
1006 struct smb_filename *smb_fname_parent,
1011 ret = SMB_VFS_STAT(conn, smb_fname_parent);
1013 DEBUG(0,("change_file_owner_to_parent: failed to stat parent "
1014 "directory %s. Error was %s\n",
1015 smb_fname_str_dbg(smb_fname_parent),
1017 TALLOC_FREE(smb_fname_parent);
1021 if (smb_fname_parent->st.st_ex_uid == fsp->fsp_name->st.st_ex_uid) {
1022 /* Already this uid - no need to change. */
1023 DEBUG(10,("change_file_owner_to_parent: file %s "
1024 "is already owned by uid %d\n",
1026 (int)fsp->fsp_name->st.st_ex_uid ));
1027 TALLOC_FREE(smb_fname_parent);
1032 ret = SMB_VFS_FCHOWN(fsp, smb_fname_parent->st.st_ex_uid, (gid_t)-1);
1035 DEBUG(0,("change_file_owner_to_parent: failed to fchown "
1036 "file %s to parent directory uid %u. Error "
1037 "was %s\n", fsp_str_dbg(fsp),
1038 (unsigned int)smb_fname_parent->st.st_ex_uid,
1041 DEBUG(10,("change_file_owner_to_parent: changed new file %s to "
1042 "parent directory uid %u.\n", fsp_str_dbg(fsp),
1043 (unsigned int)smb_fname_parent->st.st_ex_uid));
1044 /* Ensure the uid entry is updated. */
1045 fsp->fsp_name->st.st_ex_uid = smb_fname_parent->st.st_ex_uid;
1049 static NTSTATUS change_dir_owner_to_parent(connection_struct *conn,
1050 struct smb_filename *smb_fname_parent,
1051 struct smb_filename *smb_dname,
1052 SMB_STRUCT_STAT *psbuf)
1056 ret = SMB_VFS_STAT(conn, smb_fname_parent);
1058 DEBUG(0,("change_dir_owner_to_parent: failed to stat parent "
1059 "directory %s. Error was %s\n",
1060 smb_fname_str_dbg(smb_fname_parent),
1062 return map_nt_error_from_unix(errno);
1065 if (smb_fname_parent->st.st_ex_uid == smb_dname->st.st_ex_uid) {
1066 /* Already this uid - no need to change. */
1067 DEBUG(10,("change_dir_owner_to_parent: directory %s "
1068 "is already owned by uid %d\n",
1069 smb_dname->base_name,
1070 (int)smb_dname->st.st_ex_uid ));
1071 return NT_STATUS_OK;
1075 ret = SMB_VFS_FCHOWN(smb_dname->fsp,
1076 smb_fname_parent->st.st_ex_uid,
1080 DEBUG(10,("change_dir_owner_to_parent: failed to chown "
1081 "directory %s to parent directory uid %u. "
1083 smb_dname->base_name,
1084 (unsigned int)smb_fname_parent->st.st_ex_uid,
1086 return map_nt_error_from_unix(errno);
1089 DBG_DEBUG("changed ownership of new "
1090 "directory %s to parent directory uid %u.\n",
1091 smb_dname->base_name,
1092 (unsigned int)smb_fname_parent->st.st_ex_uid);
1094 /* Ensure the uid entry is updated. */
1095 psbuf->st_ex_uid = smb_fname_parent->st.st_ex_uid;
1097 return NT_STATUS_OK;
1100 /****************************************************************************
1101 Open a file - returning a guaranteed ATOMIC indication of if the
1102 file was created or not.
1103 ****************************************************************************/
1105 static NTSTATUS fd_open_atomic(files_struct *fsp,
1110 NTSTATUS status = NT_STATUS_UNSUCCESSFUL;
1111 NTSTATUS retry_status;
1112 bool file_existed = VALID_STAT(fsp->fsp_name->st);
1115 if (!(flags & O_CREAT)) {
1117 * We're not creating the file, just pass through.
1119 status = fd_openat(fsp->conn->cwd_fsp, fsp->fsp_name, fsp, flags, mode);
1120 *file_created = false;
1124 if (flags & O_EXCL) {
1126 * Fail if already exists, just pass through.
1128 status = fd_openat(fsp->conn->cwd_fsp, fsp->fsp_name, fsp, flags, mode);
1131 * Here we've opened with O_CREAT|O_EXCL. If that went
1132 * NT_STATUS_OK, we *know* we created this file.
1134 *file_created = NT_STATUS_IS_OK(status);
1140 * Now it gets tricky. We have O_CREAT, but not O_EXCL.
1141 * To know absolutely if we created the file or not,
1142 * we can never call O_CREAT without O_EXCL. So if
1143 * we think the file existed, try without O_CREAT|O_EXCL.
1144 * If we think the file didn't exist, try with
1147 * The big problem here is dangling symlinks. Opening
1148 * without O_NOFOLLOW means both bad symlink
1149 * and missing path return -1, ENOENT from open(). As POSIX
1150 * is pathname based it's not possible to tell
1151 * the difference between these two cases in a
1152 * non-racy way, so change to try only two attempts before
1155 * We don't have this problem for the O_NOFOLLOW
1156 * case as it just returns NT_STATUS_OBJECT_PATH_NOT_FOUND
1157 * mapped from the ELOOP POSIX error.
1161 curr_flags = flags & ~(O_CREAT);
1162 retry_status = NT_STATUS_OBJECT_NAME_NOT_FOUND;
1164 curr_flags = flags | O_EXCL;
1165 retry_status = NT_STATUS_OBJECT_NAME_COLLISION;
1168 status = fd_openat(fsp->conn->cwd_fsp, fsp->fsp_name, fsp, curr_flags, mode);
1169 if (NT_STATUS_IS_OK(status)) {
1170 *file_created = !file_existed;
1171 return NT_STATUS_OK;
1173 if (NT_STATUS_EQUAL(status, retry_status)) {
1175 file_existed = !file_existed;
1177 DBG_DEBUG("File %s %s. Retry.\n",
1179 file_existed ? "existed" : "did not exist");
1182 curr_flags = flags & ~(O_CREAT);
1184 curr_flags = flags | O_EXCL;
1187 status = fd_openat(fsp->conn->cwd_fsp, fsp->fsp_name, fsp, curr_flags, mode);
1190 *file_created = (NT_STATUS_IS_OK(status) && !file_existed);
1194 static NTSTATUS reopen_from_procfd(struct files_struct *fsp,
1198 struct smb_filename proc_fname;
1199 const char *p = NULL;
1206 if (!fsp->fsp_flags.have_proc_fds) {
1207 return NT_STATUS_MORE_PROCESSING_REQUIRED;
1210 old_fd = fsp_get_pathref_fd(fsp);
1212 return NT_STATUS_MORE_PROCESSING_REQUIRED;
1215 if (!fsp->fsp_flags.is_pathref) {
1216 DBG_ERR("[%s] is not a pathref\n",
1219 smb_panic("Not a pathref");
1221 return NT_STATUS_INVALID_HANDLE;
1224 p = sys_proc_fd_path(old_fd, buf, sizeof(buf));
1226 return NT_STATUS_NO_MEMORY;
1229 proc_fname = (struct smb_filename) {
1230 .base_name = discard_const_p(char, p),
1233 fsp->fsp_flags.is_pathref = false;
1235 new_fd = SMB_VFS_OPENAT(fsp->conn,
1242 status = map_nt_error_from_unix(errno);
1244 fsp_set_fd(fsp, -1);
1248 ret = SMB_VFS_CLOSE(fsp);
1249 fsp_set_fd(fsp, -1);
1251 return map_nt_error_from_unix(errno);
1254 fsp_set_fd(fsp, new_fd);
1255 return NT_STATUS_OK;
1258 static NTSTATUS reopen_from_fsp(struct files_struct *fsp,
1261 bool *p_file_created)
1263 bool __unused_file_created = false;
1266 if (p_file_created == NULL) {
1267 p_file_created = &__unused_file_created;
1271 * TODO: should we move this to the VFS layer?
1272 * SMB_VFS_REOPEN_FSP()?
1275 status = reopen_from_procfd(fsp,
1278 if (NT_STATUS_EQUAL(status, NT_STATUS_MORE_PROCESSING_REQUIRED)) {
1280 * Close the existing pathref fd and set the fsp flag
1281 * is_pathref to false so we get a "normal" fd this
1284 status = fd_close(fsp);
1285 if (!NT_STATUS_IS_OK(status)) {
1289 fsp->fsp_flags.is_pathref = false;
1291 status = fd_open_atomic(fsp,
1300 /****************************************************************************
1302 ****************************************************************************/
1304 static NTSTATUS open_file(files_struct *fsp,
1305 struct smb_request *req,
1306 struct smb_filename *parent_dir,
1309 uint32_t access_mask, /* client requested access mask. */
1310 uint32_t open_access_mask, /* what we're actually using in the open. */
1311 uint32_t private_flags,
1312 bool *p_file_created)
1314 connection_struct *conn = fsp->conn;
1315 struct smb_filename *smb_fname = fsp->fsp_name;
1316 NTSTATUS status = NT_STATUS_OK;
1317 int accmode = (flags & O_ACCMODE);
1318 int local_flags = flags;
1319 bool file_existed = VALID_STAT(fsp->fsp_name->st);
1320 uint32_t need_fd_mask =
1326 WRITE_OWNER_ACCESS |
1327 SEC_FLAG_SYSTEM_SECURITY |
1328 READ_CONTROL_ACCESS;
1329 bool creating = !file_existed && (flags & O_CREAT);
1330 bool truncating = (flags & O_TRUNC);
1331 bool open_fd = false;
1334 * Catch early an attempt to open an existing
1335 * directory as a file.
1337 if (file_existed && S_ISDIR(fsp->fsp_name->st.st_ex_mode)) {
1338 return NT_STATUS_FILE_IS_A_DIRECTORY;
1341 /* Check permissions */
1344 * This code was changed after seeing a client open request
1345 * containing the open mode of (DENY_WRITE/read-only) with
1346 * the 'create if not exist' bit set. The previous code
1347 * would fail to open the file read only on a read-only share
1348 * as it was checking the flags parameter directly against O_RDONLY,
1349 * this was failing as the flags parameter was set to O_RDONLY|O_CREAT.
1353 if (!CAN_WRITE(conn)) {
1354 /* It's a read-only share - fail if we wanted to write. */
1355 if(accmode != O_RDONLY || (flags & O_TRUNC) || (flags & O_APPEND)) {
1356 DEBUG(3,("Permission denied opening %s\n",
1357 smb_fname_str_dbg(smb_fname)));
1358 return NT_STATUS_ACCESS_DENIED;
1360 if (flags & O_CREAT) {
1361 /* We don't want to write - but we must make sure that
1362 O_CREAT doesn't create the file if we have write
1363 access into the directory.
1365 flags &= ~(O_CREAT|O_EXCL);
1366 local_flags &= ~(O_CREAT|O_EXCL);
1371 * This little piece of insanity is inspired by the
1372 * fact that an NT client can open a file for O_RDONLY,
1373 * but set the create disposition to FILE_EXISTS_TRUNCATE.
1374 * If the client *can* write to the file, then it expects to
1375 * truncate the file, even though it is opening for readonly.
1376 * Quicken uses this stupid trick in backup file creation...
1377 * Thanks *greatly* to "David W. Chapman Jr." <dwcjr@inethouston.net>
1378 * for helping track this one down. It didn't bite us in 2.0.x
1379 * as we always opened files read-write in that release. JRA.
1382 if ((accmode == O_RDONLY) && ((flags & O_TRUNC) == O_TRUNC)) {
1383 DEBUG(10,("open_file: truncate requested on read-only open "
1384 "for file %s\n", smb_fname_str_dbg(smb_fname)));
1385 local_flags = (flags & ~O_ACCMODE)|O_RDWR;
1388 if ((open_access_mask & need_fd_mask) || creating || truncating) {
1396 #if defined(O_NONBLOCK) && defined(S_ISFIFO)
1398 * We would block on opening a FIFO with no one else on the
1399 * other end. Do what we used to do and add O_NONBLOCK to the
1403 if (file_existed && S_ISFIFO(smb_fname->st.st_ex_mode)) {
1404 local_flags &= ~O_TRUNC; /* Can't truncate a FIFO. */
1405 local_flags |= O_NONBLOCK;
1410 /* Don't create files with Microsoft wildcard characters. */
1411 if (fsp->base_fsp) {
1413 * wildcard characters are allowed in stream names
1414 * only test the basefilename
1416 wild = fsp->base_fsp->fsp_name->base_name;
1418 wild = smb_fname->base_name;
1420 if ((local_flags & O_CREAT) && !file_existed &&
1421 !(fsp->posix_flags & FSP_POSIX_FLAGS_PATHNAMES) &&
1422 ms_has_wild(wild)) {
1423 return NT_STATUS_OBJECT_NAME_INVALID;
1426 /* Can we access this file ? */
1427 if (!fsp->base_fsp) {
1428 /* Only do this check on non-stream open. */
1430 status = smbd_check_access_rights(conn,
1436 if (!NT_STATUS_IS_OK(status)) {
1437 DEBUG(10, ("open_file: "
1438 "smbd_check_access_rights "
1439 "on file %s returned %s\n",
1440 smb_fname_str_dbg(smb_fname),
1441 nt_errstr(status)));
1444 if (!NT_STATUS_IS_OK(status) &&
1445 !NT_STATUS_EQUAL(status,
1446 NT_STATUS_OBJECT_NAME_NOT_FOUND))
1451 if (NT_STATUS_EQUAL(status,
1452 NT_STATUS_OBJECT_NAME_NOT_FOUND))
1454 DEBUG(10, ("open_file: "
1455 "file %s vanished since we "
1456 "checked for existence.\n",
1457 smb_fname_str_dbg(smb_fname)));
1458 file_existed = false;
1459 SET_STAT_INVALID(fsp->fsp_name->st);
1463 if (!file_existed) {
1464 if (!(local_flags & O_CREAT)) {
1465 /* File didn't exist and no O_CREAT. */
1466 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
1469 status = check_parent_access(conn,
1473 if (!NT_STATUS_IS_OK(status)) {
1474 DEBUG(10, ("open_file: "
1475 "check_parent_access on "
1476 "file %s returned %s\n",
1477 smb_fname_str_dbg(smb_fname),
1478 nt_errstr(status) ));
1485 * Actually do the open - if O_TRUNC is needed handle it
1486 * below under the share mode lock.
1488 status = reopen_from_fsp(fsp,
1489 local_flags & ~O_TRUNC,
1492 if (NT_STATUS_EQUAL(status, NT_STATUS_STOPPED_ON_SYMLINK)) {
1494 * POSIX client that hit a symlink. We don't want to
1495 * return NT_STATUS_STOPPED_ON_SYMLINK to avoid handling
1496 * this special error code in all callers, so we map
1497 * this to NT_STATUS_OBJECT_PATH_NOT_FOUND. Historically
1498 * the lower level functions returned status code mapped
1499 * from errno by map_nt_error_from_unix() where ELOOP is
1500 * mapped to NT_STATUS_OBJECT_PATH_NOT_FOUND.
1502 status = NT_STATUS_OBJECT_PATH_NOT_FOUND;
1504 if (!NT_STATUS_IS_OK(status)) {
1505 DEBUG(3,("Error opening file %s (%s) (local_flags=%d) "
1506 "(flags=%d)\n", smb_fname_str_dbg(smb_fname),
1507 nt_errstr(status),local_flags,flags));
1511 if (local_flags & O_NONBLOCK) {
1513 * GPFS can return ETIMEDOUT for pread on
1514 * nonblocking file descriptors when files
1515 * migrated to tape need to be recalled. I
1516 * could imagine this happens elsewhere
1517 * too. With blocking file descriptors this
1520 ret = vfs_set_blocking(fsp, true);
1522 status = map_nt_error_from_unix(errno);
1523 DBG_WARNING("Could not set fd to blocking: "
1524 "%s\n", strerror(errno));
1530 if (*p_file_created) {
1531 /* We created this file. */
1533 bool need_re_stat = false;
1534 /* Do all inheritance work after we've
1535 done a successful fstat call and filled
1536 in the stat struct in fsp->fsp_name. */
1538 /* Inherit the ACL if required */
1539 if (lp_inherit_permissions(SNUM(conn))) {
1540 inherit_access_posix_acl(conn,
1544 need_re_stat = true;
1547 /* Change the owner if required. */
1548 if (lp_inherit_owner(SNUM(conn)) != INHERIT_OWNER_NO) {
1549 change_file_owner_to_parent(conn,
1552 need_re_stat = true;
1556 ret = SMB_VFS_FSTAT(fsp, &smb_fname->st);
1558 * If we have an fd, this stat should succeed.
1561 status = map_nt_error_from_unix(errno);
1562 DBG_ERR("Error doing fstat on open "
1564 smb_fname_str_dbg(smb_fname),
1571 notify_fname(conn, NOTIFY_ACTION_ADDED,
1572 FILE_NOTIFY_CHANGE_FILE_NAME,
1573 smb_fname->base_name);
1576 if (!file_existed) {
1577 /* File must exist for a stat open. */
1578 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
1581 if (S_ISLNK(smb_fname->st.st_ex_mode) &&
1582 !(fsp->posix_flags & FSP_POSIX_FLAGS_OPEN))
1585 * Don't allow stat opens on symlinks directly unless
1586 * it's a POSIX open.
1588 return NT_STATUS_OBJECT_PATH_NOT_FOUND;
1591 if (!fsp->fsp_flags.is_pathref) {
1593 * There is only one legit case where end up here:
1594 * openat_pathref_fsp() failed to open a symlink, so the
1595 * fsp was created by fsp_new() which doesn't set
1596 * is_pathref. Other then that, we should always have a
1597 * pathref fsp at this point. The subsequent checks
1600 if (!(smb_fname->flags & SMB_FILENAME_POSIX_PATH)) {
1601 DBG_ERR("[%s] is not a POSIX pathname\n",
1602 smb_fname_str_dbg(smb_fname));
1603 return NT_STATUS_INTERNAL_ERROR;
1605 if (!S_ISLNK(smb_fname->st.st_ex_mode)) {
1606 DBG_ERR("[%s] is not a symlink\n",
1607 smb_fname_str_dbg(smb_fname));
1608 return NT_STATUS_INTERNAL_ERROR;
1610 if (fsp_get_pathref_fd(fsp) != -1) {
1611 DBG_ERR("fd for [%s] is not -1: fd [%d]\n",
1612 smb_fname_str_dbg(smb_fname),
1613 fsp_get_pathref_fd(fsp));
1614 return NT_STATUS_INTERNAL_ERROR;
1618 status = smbd_check_access_rights(conn,
1624 if (NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND) &&
1625 (fsp->posix_flags & FSP_POSIX_FLAGS_OPEN) &&
1626 S_ISLNK(smb_fname->st.st_ex_mode)) {
1627 /* This is a POSIX stat open for delete
1628 * or rename on a symlink that points
1629 * nowhere. Allow. */
1630 DEBUG(10,("open_file: allowing POSIX "
1631 "open on bad symlink %s\n",
1632 smb_fname_str_dbg(smb_fname)));
1633 status = NT_STATUS_OK;
1636 if (!NT_STATUS_IS_OK(status)) {
1637 DEBUG(10,("open_file: "
1638 "smbd_check_access_rights on file "
1640 smb_fname_str_dbg(smb_fname),
1641 nt_errstr(status) ));
1646 fsp->file_id = vfs_file_id_from_sbuf(conn, &smb_fname->st);
1647 fsp->vuid = req ? req->vuid : UID_FIELD_INVALID;
1648 fsp->file_pid = req ? req->smbpid : 0;
1649 fsp->fsp_flags.can_lock = true;
1650 fsp->fsp_flags.can_read = ((access_mask & FILE_READ_DATA) != 0);
1651 fsp->fsp_flags.can_write =
1653 ((access_mask & (FILE_WRITE_DATA | FILE_APPEND_DATA)) != 0);
1654 fsp->print_file = NULL;
1655 fsp->fsp_flags.modified = false;
1656 fsp->sent_oplock_break = NO_BREAK_SENT;
1657 fsp->fsp_flags.is_directory = false;
1658 if (conn->aio_write_behind_list &&
1659 is_in_path(smb_fname->base_name, conn->aio_write_behind_list,
1660 conn->case_sensitive)) {
1661 fsp->fsp_flags.aio_write_behind = true;
1664 DEBUG(2,("%s opened file %s read=%s write=%s (numopen=%d)\n",
1665 conn->session_info->unix_info->unix_name,
1666 smb_fname_str_dbg(smb_fname),
1667 BOOLSTR(fsp->fsp_flags.can_read),
1668 BOOLSTR(fsp->fsp_flags.can_write),
1669 conn->num_files_open));
1671 return NT_STATUS_OK;
1674 static bool mask_conflict(
1675 uint32_t new_access,
1676 uint32_t existing_access,
1677 uint32_t access_mask,
1678 uint32_t new_sharemode,
1679 uint32_t existing_sharemode,
1680 uint32_t sharemode_mask)
1682 bool want_access = (new_access & access_mask);
1683 bool allow_existing = (existing_sharemode & sharemode_mask);
1684 bool have_access = (existing_access & access_mask);
1685 bool allow_new = (new_sharemode & sharemode_mask);
1687 if (want_access && !allow_existing) {
1688 DBG_DEBUG("Access request 0x%"PRIx32"/0x%"PRIx32" conflicts "
1689 "with existing sharemode 0x%"PRIx32"/0x%"PRIx32"\n",
1696 if (have_access && !allow_new) {
1697 DBG_DEBUG("Sharemode request 0x%"PRIx32"/0x%"PRIx32" conflicts "
1698 "with existing access 0x%"PRIx32"/0x%"PRIx32"\n",
1708 /****************************************************************************
1709 Check if we can open a file with a share mode.
1710 Returns True if conflict, False if not.
1711 ****************************************************************************/
1713 static const uint32_t conflicting_access =
1720 static bool share_conflict(uint32_t e_access_mask,
1721 uint32_t e_share_access,
1722 uint32_t access_mask,
1723 uint32_t share_access)
1727 DBG_DEBUG("existing access_mask = 0x%"PRIx32", "
1728 "existing share access = 0x%"PRIx32", "
1729 "access_mask = 0x%"PRIx32", "
1730 "share_access = 0x%"PRIx32"\n",
1736 if ((e_access_mask & conflicting_access) == 0) {
1737 DBG_DEBUG("No conflict due to "
1738 "existing access_mask = 0x%"PRIx32"\n",
1742 if ((access_mask & conflicting_access) == 0) {
1743 DBG_DEBUG("No conflict due to access_mask = 0x%"PRIx32"\n",
1748 conflict = mask_conflict(
1749 access_mask, e_access_mask, FILE_WRITE_DATA | FILE_APPEND_DATA,
1750 share_access, e_share_access, FILE_SHARE_WRITE);
1751 conflict |= mask_conflict(
1752 access_mask, e_access_mask, FILE_READ_DATA | FILE_EXECUTE,
1753 share_access, e_share_access, FILE_SHARE_READ);
1754 conflict |= mask_conflict(
1755 access_mask, e_access_mask, DELETE_ACCESS,
1756 share_access, e_share_access, FILE_SHARE_DELETE);
1758 DBG_DEBUG("conflict=%s\n", conflict ? "true" : "false");
1762 #if defined(DEVELOPER)
1764 struct validate_my_share_entries_state {
1765 struct smbd_server_connection *sconn;
1767 struct server_id self;
1770 static bool validate_my_share_entries_fn(
1771 struct share_mode_entry *e,
1775 struct validate_my_share_entries_state *state = private_data;
1778 if (!server_id_equal(&state->self, &e->pid)) {
1782 if (e->op_mid == 0) {
1783 /* INTERNAL_OPEN_ONLY */
1787 fsp = file_find_dif(state->sconn, state->fid, e->share_file_id);
1789 DBG_ERR("PANIC : %s\n",
1790 share_mode_str(talloc_tos(), 0, &state->fid, e));
1791 smb_panic("validate_my_share_entries: Cannot match a "
1792 "share entry with an open file\n");
1795 if (((uint16_t)fsp->oplock_type) != e->op_type) {
1804 DBG_ERR("validate_my_share_entries: PANIC : %s\n",
1805 share_mode_str(talloc_tos(), 0, &state->fid, e));
1806 str = talloc_asprintf(talloc_tos(),
1807 "validate_my_share_entries: "
1808 "file %s, oplock_type = 0x%x, op_type = 0x%x\n",
1809 fsp->fsp_name->base_name,
1810 (unsigned int)fsp->oplock_type,
1811 (unsigned int)e->op_type);
1820 * Allowed access mask for stat opens relevant to oplocks
1822 bool is_oplock_stat_open(uint32_t access_mask)
1824 const uint32_t stat_open_bits =
1825 (SYNCHRONIZE_ACCESS|
1826 FILE_READ_ATTRIBUTES|
1827 FILE_WRITE_ATTRIBUTES);
1829 return (((access_mask & stat_open_bits) != 0) &&
1830 ((access_mask & ~stat_open_bits) == 0));
1834 * Allowed access mask for stat opens relevant to leases
1836 bool is_lease_stat_open(uint32_t access_mask)
1838 const uint32_t stat_open_bits =
1839 (SYNCHRONIZE_ACCESS|
1840 FILE_READ_ATTRIBUTES|
1841 FILE_WRITE_ATTRIBUTES|
1842 READ_CONTROL_ACCESS);
1844 return (((access_mask & stat_open_bits) != 0) &&
1845 ((access_mask & ~stat_open_bits) == 0));
1848 struct has_delete_on_close_state {
1852 static bool has_delete_on_close_fn(
1853 struct share_mode_entry *e,
1857 struct has_delete_on_close_state *state = private_data;
1858 state->ret = !share_entry_stale_pid(e);
1862 static bool has_delete_on_close(struct share_mode_lock *lck,
1865 struct has_delete_on_close_state state = { .ret = false };
1868 if (!is_delete_on_close_set(lck, name_hash)) {
1872 ok= share_mode_forall_entries(lck, has_delete_on_close_fn, &state);
1874 DBG_DEBUG("share_mode_forall_entries failed\n");
1880 static void share_mode_flags_restrict(
1881 struct share_mode_lock *lck,
1882 uint32_t access_mask,
1883 uint32_t share_mode,
1884 uint32_t lease_type)
1886 uint32_t existing_access_mask, existing_share_mode;
1887 uint32_t existing_lease_type;
1889 share_mode_flags_get(
1891 &existing_access_mask,
1892 &existing_share_mode,
1893 &existing_lease_type);
1895 existing_access_mask |= access_mask;
1896 if (access_mask & conflicting_access) {
1897 existing_share_mode &= share_mode;
1899 existing_lease_type |= lease_type;
1901 share_mode_flags_set(
1903 existing_access_mask,
1904 existing_share_mode,
1905 existing_lease_type,
1909 /****************************************************************************
1910 Deal with share modes
1911 Invariant: Share mode must be locked on entry and exit.
1912 Returns -1 on error, or number of share modes on success (may be zero).
1913 ****************************************************************************/
1915 struct open_mode_check_state {
1917 uint32_t access_mask;
1918 uint32_t share_access;
1919 uint32_t lease_type;
1922 static bool open_mode_check_fn(
1923 struct share_mode_entry *e,
1927 struct open_mode_check_state *state = private_data;
1928 bool disconnected, stale;
1929 uint32_t access_mask, share_access, lease_type;
1931 disconnected = server_id_is_disconnected(&e->pid);
1936 access_mask = state->access_mask | e->access_mask;
1937 share_access = state->share_access;
1938 if (e->access_mask & conflicting_access) {
1939 share_access &= e->share_access;
1941 lease_type = state->lease_type | get_lease_type(e, state->fid);
1943 if ((access_mask == state->access_mask) &&
1944 (share_access == state->share_access) &&
1945 (lease_type == state->lease_type)) {
1949 stale = share_entry_stale_pid(e);
1954 state->access_mask = access_mask;
1955 state->share_access = share_access;
1956 state->lease_type = lease_type;
1961 static NTSTATUS open_mode_check(connection_struct *conn,
1963 struct share_mode_lock *lck,
1964 uint32_t access_mask,
1965 uint32_t share_access)
1967 struct open_mode_check_state state;
1969 bool modified = false;
1971 if (is_oplock_stat_open(access_mask)) {
1972 /* Stat open that doesn't trigger oplock breaks or share mode
1973 * checks... ! JRA. */
1974 return NT_STATUS_OK;
1978 * Check if the share modes will give us access.
1981 #if defined(DEVELOPER)
1983 struct validate_my_share_entries_state validate_state = {
1984 .sconn = conn->sconn,
1986 .self = messaging_server_id(conn->sconn->msg_ctx),
1988 ok = share_mode_forall_entries(
1989 lck, validate_my_share_entries_fn, &validate_state);
1994 share_mode_flags_get(
1995 lck, &state.access_mask, &state.share_access, NULL);
1997 conflict = share_conflict(
2003 DBG_DEBUG("No conflict due to share_mode_flags access\n");
2004 return NT_STATUS_OK;
2007 state = (struct open_mode_check_state) {
2009 .share_access = (FILE_SHARE_READ|
2015 * Walk the share mode array to recalculate d->flags
2018 ok = share_mode_forall_entries(lck, open_mode_check_fn, &state);
2020 DBG_DEBUG("share_mode_forall_entries failed\n");
2021 return NT_STATUS_INTERNAL_ERROR;
2024 share_mode_flags_set(
2032 * We only end up here if we had a sharing violation
2033 * from d->flags and have recalculated it.
2035 return NT_STATUS_SHARING_VIOLATION;
2038 conflict = share_conflict(
2044 DBG_DEBUG("No conflict due to share_mode_flags access\n");
2045 return NT_STATUS_OK;
2048 return NT_STATUS_SHARING_VIOLATION;
2052 * Send a break message to the oplock holder and delay the open for
2056 NTSTATUS send_break_message(struct messaging_context *msg_ctx,
2057 const struct file_id *id,
2058 const struct share_mode_entry *exclusive,
2061 struct oplock_break_message msg = {
2063 .share_file_id = exclusive->share_file_id,
2064 .break_to = break_to,
2066 enum ndr_err_code ndr_err;
2071 struct server_id_buf buf;
2072 DBG_DEBUG("Sending break message to %s\n",
2073 server_id_str_buf(exclusive->pid, &buf));
2074 NDR_PRINT_DEBUG(oplock_break_message, &msg);
2077 ndr_err = ndr_push_struct_blob(
2081 (ndr_push_flags_fn_t)ndr_push_oplock_break_message);
2082 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
2083 DBG_WARNING("ndr_push_oplock_break_message failed: %s\n",
2084 ndr_errstr(ndr_err));
2085 return ndr_map_error2ntstatus(ndr_err);
2088 status = messaging_send(
2089 msg_ctx, exclusive->pid, MSG_SMB_BREAK_REQUEST, &blob);
2090 TALLOC_FREE(blob.data);
2091 if (!NT_STATUS_IS_OK(status)) {
2092 DEBUG(3, ("Could not send oplock break message: %s\n",
2093 nt_errstr(status)));
2099 struct validate_oplock_types_state {
2105 uint32_t num_non_stat_opens;
2108 static bool validate_oplock_types_fn(
2109 struct share_mode_entry *e,
2113 struct validate_oplock_types_state *state = private_data;
2115 if (e->op_mid == 0) {
2116 /* INTERNAL_OPEN_ONLY */
2120 if (e->op_type == NO_OPLOCK && is_oplock_stat_open(e->access_mask)) {
2122 * We ignore stat opens in the table - they always
2123 * have NO_OPLOCK and never get or cause breaks. JRA.
2128 state->num_non_stat_opens += 1;
2130 if (BATCH_OPLOCK_TYPE(e->op_type)) {
2131 /* batch - can only be one. */
2132 if (share_entry_stale_pid(e)) {
2133 DBG_DEBUG("Found stale batch oplock\n");
2136 if (state->ex_or_batch ||
2140 DBG_ERR("Bad batch oplock entry\n");
2141 state->valid = false;
2144 state->batch = true;
2147 if (EXCLUSIVE_OPLOCK_TYPE(e->op_type)) {
2148 if (share_entry_stale_pid(e)) {
2149 DBG_DEBUG("Found stale duplicate oplock\n");
2152 /* Exclusive or batch - can only be one. */
2153 if (state->ex_or_batch ||
2156 DBG_ERR("Bad exclusive or batch oplock entry\n");
2157 state->valid = false;
2160 state->ex_or_batch = true;
2163 if (LEVEL_II_OPLOCK_TYPE(e->op_type)) {
2164 if (state->batch || state->ex_or_batch) {
2165 if (share_entry_stale_pid(e)) {
2166 DBG_DEBUG("Found stale LevelII oplock\n");
2169 DBG_DEBUG("Bad levelII oplock entry\n");
2170 state->valid = false;
2173 state->level2 = true;
2176 if (e->op_type == NO_OPLOCK) {
2177 if (state->batch || state->ex_or_batch) {
2178 if (share_entry_stale_pid(e)) {
2179 DBG_DEBUG("Found stale NO_OPLOCK entry\n");
2182 DBG_ERR("Bad no oplock entry\n");
2183 state->valid = false;
2186 state->no_oplock = true;
2193 * Do internal consistency checks on the share mode for a file.
2196 static bool validate_oplock_types(struct share_mode_lock *lck)
2198 struct validate_oplock_types_state state = { .valid = true };
2201 ok = share_mode_forall_entries(lck, validate_oplock_types_fn, &state);
2203 DBG_DEBUG("share_mode_forall_entries failed\n");
2207 DBG_DEBUG("Got invalid oplock configuration\n");
2211 if ((state.batch || state.ex_or_batch) &&
2212 (state.num_non_stat_opens != 1)) {
2213 DBG_WARNING("got batch (%d) or ex (%d) non-exclusively "
2216 (int)state.ex_or_batch,
2217 state.num_non_stat_opens);
2224 static bool is_same_lease(const files_struct *fsp,
2225 const struct share_mode_entry *e,
2226 const struct smb2_lease *lease)
2228 if (e->op_type != LEASE_OPLOCK) {
2231 if (lease == NULL) {
2235 return smb2_lease_equal(fsp_client_guid(fsp),
2241 static bool file_has_brlocks(files_struct *fsp)
2243 struct byte_range_lock *br_lck;
2245 br_lck = brl_get_locks_readonly(fsp);
2249 return (brl_num_locks(br_lck) > 0);
2252 struct fsp_lease *find_fsp_lease(struct files_struct *new_fsp,
2253 const struct smb2_lease_key *key,
2254 uint32_t current_state,
2255 uint16_t lease_version,
2256 uint16_t lease_epoch)
2258 struct files_struct *fsp;
2261 * TODO: Measure how expensive this loop is with thousands of open
2265 for (fsp = file_find_di_first(new_fsp->conn->sconn, new_fsp->file_id, true);
2267 fsp = file_find_di_next(fsp, true)) {
2269 if (fsp == new_fsp) {
2272 if (fsp->oplock_type != LEASE_OPLOCK) {
2275 if (smb2_lease_key_equal(&fsp->lease->lease.lease_key, key)) {
2276 fsp->lease->ref_count += 1;
2281 /* Not found - must be leased in another smbd. */
2282 new_fsp->lease = talloc_zero(new_fsp->conn->sconn, struct fsp_lease);
2283 if (new_fsp->lease == NULL) {
2286 new_fsp->lease->ref_count = 1;
2287 new_fsp->lease->sconn = new_fsp->conn->sconn;
2288 new_fsp->lease->lease.lease_key = *key;
2289 new_fsp->lease->lease.lease_state = current_state;
2291 * We internally treat all leases as V2 and update
2292 * the epoch, but when sending breaks it matters if
2293 * the requesting lease was v1 or v2.
2295 new_fsp->lease->lease.lease_version = lease_version;
2296 new_fsp->lease->lease.lease_epoch = lease_epoch;
2297 return new_fsp->lease;
2300 static NTSTATUS try_lease_upgrade(struct files_struct *fsp,
2301 struct share_mode_lock *lck,
2302 const struct GUID *client_guid,
2303 const struct smb2_lease *lease,
2307 uint32_t current_state, breaking_to_requested, breaking_to_required;
2309 uint16_t lease_version, epoch;
2310 uint32_t existing, requested;
2313 status = leases_db_get(
2319 &breaking_to_requested,
2320 &breaking_to_required,
2323 if (!NT_STATUS_IS_OK(status)) {
2327 fsp->lease = find_fsp_lease(
2333 if (fsp->lease == NULL) {
2334 DEBUG(1, ("Did not find existing lease for file %s\n",
2336 return NT_STATUS_NO_MEMORY;
2340 * Upgrade only if the requested lease is a strict upgrade.
2342 existing = current_state;
2343 requested = lease->lease_state;
2346 * Tricky: This test makes sure that "requested" is a
2347 * strict bitwise superset of "existing".
2349 do_upgrade = ((existing & requested) == existing);
2352 * Upgrade only if there's a change.
2354 do_upgrade &= (granted != existing);
2357 * Upgrade only if other leases don't prevent what was asked
2360 do_upgrade &= (granted == requested);
2363 * only upgrade if we are not in breaking state
2365 do_upgrade &= !breaking;
2367 DEBUG(10, ("existing=%"PRIu32", requested=%"PRIu32", "
2368 "granted=%"PRIu32", do_upgrade=%d\n",
2369 existing, requested, granted, (int)do_upgrade));
2372 NTSTATUS set_status;
2374 current_state = granted;
2377 set_status = leases_db_set(
2382 breaking_to_requested,
2383 breaking_to_required,
2387 if (!NT_STATUS_IS_OK(set_status)) {
2388 DBG_DEBUG("leases_db_set failed: %s\n",
2389 nt_errstr(set_status));
2394 fsp_lease_update(fsp);
2396 return NT_STATUS_OK;
2399 static NTSTATUS grant_new_fsp_lease(struct files_struct *fsp,
2400 struct share_mode_lock *lck,
2401 const struct GUID *client_guid,
2402 const struct smb2_lease *lease,
2407 fsp->lease = talloc_zero(fsp->conn->sconn, struct fsp_lease);
2408 if (fsp->lease == NULL) {
2409 return NT_STATUS_INSUFFICIENT_RESOURCES;
2411 fsp->lease->ref_count = 1;
2412 fsp->lease->sconn = fsp->conn->sconn;
2413 fsp->lease->lease.lease_version = lease->lease_version;
2414 fsp->lease->lease.lease_key = lease->lease_key;
2415 fsp->lease->lease.lease_state = granted;
2416 fsp->lease->lease.lease_epoch = lease->lease_epoch + 1;
2418 status = leases_db_add(client_guid,
2421 fsp->lease->lease.lease_state,
2422 fsp->lease->lease.lease_version,
2423 fsp->lease->lease.lease_epoch,
2424 fsp->conn->connectpath,
2425 fsp->fsp_name->base_name,
2426 fsp->fsp_name->stream_name);
2427 if (!NT_STATUS_IS_OK(status)) {
2428 DEBUG(10, ("%s: leases_db_add failed: %s\n", __func__,
2429 nt_errstr(status)));
2430 TALLOC_FREE(fsp->lease);
2431 return NT_STATUS_INSUFFICIENT_RESOURCES;
2435 * We used to set lck->data->modified=true here without
2436 * actually modifying lck->data, triggering a needless
2437 * writeback of lck->data.
2439 * Apart from that writeback, setting modified=true has the
2440 * effect of triggering all waiters for this file to
2441 * retry. This only makes sense if any blocking condition
2442 * (i.e. waiting for a lease to be downgraded or removed) is
2443 * gone. This routine here only adds a lease, so it will never
2444 * free up resources that blocked waiters can now claim. So
2445 * that second effect also does not matter in this
2446 * routine. Thus setting lck->data->modified=true does not
2447 * need to be done here.
2450 return NT_STATUS_OK;
2453 static NTSTATUS grant_fsp_lease(struct files_struct *fsp,
2454 struct share_mode_lock *lck,
2455 const struct smb2_lease *lease,
2458 const struct GUID *client_guid = fsp_client_guid(fsp);
2461 status = try_lease_upgrade(fsp, lck, client_guid, lease, granted);
2463 if (NT_STATUS_EQUAL(status, NT_STATUS_NOT_FOUND)) {
2464 status = grant_new_fsp_lease(
2465 fsp, lck, client_guid, lease, granted);
2471 static int map_lease_type_to_oplock(uint32_t lease_type)
2473 int result = NO_OPLOCK;
2475 switch (lease_type) {
2476 case SMB2_LEASE_READ|SMB2_LEASE_WRITE|SMB2_LEASE_HANDLE:
2477 result = BATCH_OPLOCK|EXCLUSIVE_OPLOCK;
2479 case SMB2_LEASE_READ|SMB2_LEASE_WRITE:
2480 result = EXCLUSIVE_OPLOCK;
2482 case SMB2_LEASE_READ|SMB2_LEASE_HANDLE:
2483 case SMB2_LEASE_READ:
2484 result = LEVEL_II_OPLOCK;
2491 struct delay_for_oplock_state {
2492 struct files_struct *fsp;
2493 const struct smb2_lease *lease;
2494 bool will_overwrite;
2495 uint32_t delay_mask;
2496 bool first_open_attempt;
2497 bool got_handle_lease;
2499 bool have_other_lease;
2503 static bool delay_for_oplock_fn(
2504 struct share_mode_entry *e,
2508 struct delay_for_oplock_state *state = private_data;
2509 struct files_struct *fsp = state->fsp;
2510 const struct smb2_lease *lease = state->lease;
2511 bool e_is_lease = (e->op_type == LEASE_OPLOCK);
2512 uint32_t e_lease_type = get_lease_type(e, fsp->file_id);
2514 bool lease_is_breaking = false;
2519 if (lease != NULL) {
2520 bool our_lease = is_same_lease(fsp, e, lease);
2522 DBG_DEBUG("Ignoring our own lease\n");
2527 status = leases_db_get(
2531 NULL, /* current_state */
2533 NULL, /* breaking_to_requested */
2534 NULL, /* breaking_to_required */
2535 NULL, /* lease_version */
2539 * leases_db_get() can return NT_STATUS_NOT_FOUND
2540 * if the share_mode_entry e is stale and the
2541 * lease record was already removed. In this case return
2542 * false so the traverse continues.
2545 if (NT_STATUS_EQUAL(status, NT_STATUS_NOT_FOUND) &&
2546 share_entry_stale_pid(e))
2548 struct GUID_txt_buf guid_strbuf;
2549 struct file_id_buf file_id_strbuf;
2550 DBG_DEBUG("leases_db_get for client_guid [%s] "
2551 "lease_key [%"PRIu64"/%"PRIu64"] "
2552 "file_id [%s] failed for stale "
2553 "share_mode_entry\n",
2554 GUID_buf_string(&e->client_guid, &guid_strbuf),
2555 e->lease_key.data[0],
2556 e->lease_key.data[1],
2557 file_id_str_buf(fsp->file_id, &file_id_strbuf));
2560 if (!NT_STATUS_IS_OK(status)) {
2561 struct GUID_txt_buf guid_strbuf;
2562 struct file_id_buf file_id_strbuf;
2563 DBG_ERR("leases_db_get for client_guid [%s] "
2564 "lease_key [%"PRIu64"/%"PRIu64"] "
2565 "file_id [%s] failed: %s\n",
2566 GUID_buf_string(&e->client_guid, &guid_strbuf),
2567 e->lease_key.data[0],
2568 e->lease_key.data[1],
2569 file_id_str_buf(fsp->file_id, &file_id_strbuf),
2571 smb_panic("leases_db_get() failed");
2575 if (!state->got_handle_lease &&
2576 ((e_lease_type & SMB2_LEASE_HANDLE) != 0) &&
2577 !share_entry_stale_pid(e)) {
2578 state->got_handle_lease = true;
2581 if (!state->got_oplock &&
2582 (e->op_type != LEASE_OPLOCK) &&
2583 !share_entry_stale_pid(e)) {
2584 state->got_oplock = true;
2587 if (!state->have_other_lease &&
2588 !is_same_lease(fsp, e, lease) &&
2589 !share_entry_stale_pid(e)) {
2590 state->have_other_lease = true;
2593 if (e_is_lease && is_lease_stat_open(fsp->access_mask)) {
2597 break_to = e_lease_type & ~state->delay_mask;
2599 if (state->will_overwrite) {
2600 break_to &= ~(SMB2_LEASE_HANDLE|SMB2_LEASE_READ);
2603 DBG_DEBUG("e_lease_type %u, will_overwrite: %u\n",
2604 (unsigned)e_lease_type,
2605 (unsigned)state->will_overwrite);
2607 if ((e_lease_type & ~break_to) == 0) {
2608 if (lease_is_breaking) {
2609 state->delay = true;
2614 if (share_entry_stale_pid(e)) {
2618 if (state->will_overwrite) {
2620 * If we break anyway break to NONE directly.
2621 * Otherwise vfs_set_filelen() will trigger the
2624 break_to &= ~(SMB2_LEASE_READ|SMB2_LEASE_WRITE);
2629 * Oplocks only support breaking to R or NONE.
2631 break_to &= ~(SMB2_LEASE_HANDLE|SMB2_LEASE_WRITE);
2634 DBG_DEBUG("breaking from %d to %d\n",
2638 fsp->conn->sconn->msg_ctx, &fsp->file_id, e, break_to);
2639 if (e_lease_type & state->delay_mask) {
2640 state->delay = true;
2642 if (lease_is_breaking && !state->first_open_attempt) {
2643 state->delay = true;
2649 static NTSTATUS delay_for_oplock(files_struct *fsp,
2651 const struct smb2_lease *lease,
2652 struct share_mode_lock *lck,
2653 bool have_sharing_violation,
2654 uint32_t create_disposition,
2655 bool first_open_attempt)
2657 struct delay_for_oplock_state state = {
2660 .first_open_attempt = first_open_attempt,
2666 if (is_oplock_stat_open(fsp->access_mask)) {
2670 state.delay_mask = have_sharing_violation ?
2671 SMB2_LEASE_HANDLE : SMB2_LEASE_WRITE;
2673 switch (create_disposition) {
2674 case FILE_SUPERSEDE:
2675 case FILE_OVERWRITE:
2676 case FILE_OVERWRITE_IF:
2677 state.will_overwrite = true;
2680 state.will_overwrite = false;
2684 ok = share_mode_forall_entries(lck, delay_for_oplock_fn, &state);
2686 return NT_STATUS_INTERNAL_ERROR;
2690 return NT_STATUS_RETRY;
2694 if (have_sharing_violation) {
2695 return NT_STATUS_SHARING_VIOLATION;
2698 if (oplock_request == LEASE_OPLOCK) {
2699 if (lease == NULL) {
2701 * The SMB2 layer should have checked this
2703 return NT_STATUS_INTERNAL_ERROR;
2706 granted = lease->lease_state;
2708 if (lp_kernel_oplocks(SNUM(fsp->conn))) {
2709 DEBUG(10, ("No lease granted because kernel oplocks are enabled\n"));
2710 granted = SMB2_LEASE_NONE;
2712 if ((granted & (SMB2_LEASE_READ|SMB2_LEASE_WRITE)) == 0) {
2713 DEBUG(10, ("No read or write lease requested\n"));
2714 granted = SMB2_LEASE_NONE;
2716 if (granted == SMB2_LEASE_WRITE) {
2717 DEBUG(10, ("pure write lease requested\n"));
2718 granted = SMB2_LEASE_NONE;
2720 if (granted == (SMB2_LEASE_WRITE|SMB2_LEASE_HANDLE)) {
2721 DEBUG(10, ("write and handle lease requested\n"));
2722 granted = SMB2_LEASE_NONE;
2725 granted = map_oplock_to_lease_type(
2726 oplock_request & ~SAMBA_PRIVATE_OPLOCK_MASK);
2729 if (lp_locking(fsp->conn->params) && file_has_brlocks(fsp)) {
2730 DBG_DEBUG("file %s has byte range locks\n",
2732 granted &= ~SMB2_LEASE_READ;
2735 if (state.have_other_lease) {
2737 * Can grant only one writer
2739 granted &= ~SMB2_LEASE_WRITE;
2742 if ((granted & SMB2_LEASE_READ) && !(granted & SMB2_LEASE_WRITE)) {
2744 (global_client_caps & CAP_LEVEL_II_OPLOCKS) &&
2745 lp_level2_oplocks(SNUM(fsp->conn));
2747 if (!allow_level2) {
2748 granted = SMB2_LEASE_NONE;
2752 if (oplock_request == LEASE_OPLOCK) {
2753 if (state.got_oplock) {
2754 granted &= ~SMB2_LEASE_HANDLE;
2757 fsp->oplock_type = LEASE_OPLOCK;
2759 status = grant_fsp_lease(fsp, lck, lease, granted);
2760 if (!NT_STATUS_IS_OK(status)) {
2765 DBG_DEBUG("lease_state=%d\n", fsp->lease->lease.lease_state);
2767 if (state.got_handle_lease) {
2768 granted = SMB2_LEASE_NONE;
2771 fsp->oplock_type = map_lease_type_to_oplock(granted);
2773 status = set_file_oplock(fsp);
2774 if (!NT_STATUS_IS_OK(status)) {
2776 * Could not get the kernel oplock
2778 fsp->oplock_type = NO_OPLOCK;
2782 if (granted & SMB2_LEASE_READ) {
2783 uint32_t acc, sh, ls;
2784 share_mode_flags_get(lck, &acc, &sh, &ls);
2785 ls |= SHARE_MODE_LEASE_READ;
2786 share_mode_flags_set(lck, acc, sh, ls, NULL);
2789 DBG_DEBUG("oplock type 0x%x on file %s\n",
2790 fsp->oplock_type, fsp_str_dbg(fsp));
2792 return NT_STATUS_OK;
2795 static NTSTATUS handle_share_mode_lease(
2797 struct share_mode_lock *lck,
2798 uint32_t create_disposition,
2799 uint32_t access_mask,
2800 uint32_t share_access,
2802 const struct smb2_lease *lease,
2803 bool first_open_attempt)
2805 bool sharing_violation = false;
2808 status = open_mode_check(
2809 fsp->conn, fsp->file_id, lck, access_mask, share_access);
2810 if (NT_STATUS_EQUAL(status, NT_STATUS_SHARING_VIOLATION)) {
2811 sharing_violation = true;
2812 status = NT_STATUS_OK; /* handled later */
2815 if (!NT_STATUS_IS_OK(status)) {
2819 if (oplock_request == INTERNAL_OPEN_ONLY) {
2820 if (sharing_violation) {
2821 DBG_DEBUG("Sharing violation for internal open\n");
2822 return NT_STATUS_SHARING_VIOLATION;
2826 * Internal opens never do oplocks or leases. We don't
2827 * need to go through delay_for_oplock().
2829 fsp->oplock_type = NO_OPLOCK;
2831 return NT_STATUS_OK;
2834 status = delay_for_oplock(
2841 first_open_attempt);
2842 if (!NT_STATUS_IS_OK(status)) {
2846 return NT_STATUS_OK;
2849 static bool request_timed_out(struct smb_request *req, struct timeval timeout)
2851 struct timeval now, end_time;
2853 end_time = timeval_sum(&req->request_time, &timeout);
2854 return (timeval_compare(&end_time, &now) < 0);
2857 struct defer_open_state {
2858 struct smbXsrv_connection *xconn;
2862 static void defer_open_done(struct tevent_req *req);
2865 * Defer an open and watch a locking.tdb record
2867 * This defers an open that gets rescheduled once the locking.tdb record watch
2868 * is triggered by a change to the record.
2870 * It is used to defer opens that triggered an oplock break and for the SMB1
2871 * sharing violation delay.
2873 static void defer_open(struct share_mode_lock *lck,
2874 struct timeval timeout,
2875 struct smb_request *req,
2878 struct deferred_open_record *open_rec = NULL;
2879 struct timeval abs_timeout;
2880 struct defer_open_state *watch_state;
2881 struct tevent_req *watch_req;
2882 struct timeval_buf tvbuf1, tvbuf2;
2883 struct file_id_buf fbuf;
2886 abs_timeout = timeval_sum(&req->request_time, &timeout);
2888 DBG_DEBUG("request time [%s] timeout [%s] mid [%" PRIu64 "] "
2890 timeval_str_buf(&req->request_time, false, true, &tvbuf1),
2891 timeval_str_buf(&abs_timeout, false, true, &tvbuf2),
2893 file_id_str_buf(id, &fbuf));
2895 open_rec = talloc_zero(NULL, struct deferred_open_record);
2896 if (open_rec == NULL) {
2898 exit_server("talloc failed");
2901 watch_state = talloc(open_rec, struct defer_open_state);
2902 if (watch_state == NULL) {
2903 exit_server("talloc failed");
2905 watch_state->xconn = req->xconn;
2906 watch_state->mid = req->mid;
2908 DBG_DEBUG("defering mid %" PRIu64 "\n", req->mid);
2910 watch_req = share_mode_watch_send(
2914 (struct server_id){0});
2915 if (watch_req == NULL) {
2916 exit_server("Could not watch share mode record");
2918 tevent_req_set_callback(watch_req, defer_open_done, watch_state);
2920 ok = tevent_req_set_endtime(watch_req, req->sconn->ev_ctx, abs_timeout);
2922 exit_server("tevent_req_set_endtime failed");
2925 ok = push_deferred_open_message_smb(req, timeout, id, open_rec);
2928 exit_server("push_deferred_open_message_smb failed");
2932 static void defer_open_done(struct tevent_req *req)
2934 struct defer_open_state *state = tevent_req_callback_data(
2935 req, struct defer_open_state);
2939 status = share_mode_watch_recv(req, NULL, NULL);
2941 if (!NT_STATUS_IS_OK(status)) {
2942 DEBUG(5, ("dbwrap_watched_watch_recv returned %s\n",
2943 nt_errstr(status)));
2945 * Even if it failed, retry anyway. TODO: We need a way to
2946 * tell a re-scheduled open about that error.
2950 DEBUG(10, ("scheduling mid %llu\n", (unsigned long long)state->mid));
2952 ret = schedule_deferred_open_message_smb(state->xconn, state->mid);
2958 * Actually attempt the kernel oplock polling open.
2961 static void poll_open_fn(struct tevent_context *ev,
2962 struct tevent_timer *te,
2963 struct timeval current_time,
2966 struct deferred_open_record *open_rec = talloc_get_type_abort(
2967 private_data, struct deferred_open_record);
2970 TALLOC_FREE(open_rec->watch_req);
2972 ok = schedule_deferred_open_message_smb(
2973 open_rec->xconn, open_rec->mid);
2975 exit_server("schedule_deferred_open_message_smb failed");
2977 DBG_DEBUG("timer fired. Retrying open !\n");
2980 static void poll_open_done(struct tevent_req *subreq);
2983 * Reschedule an open for 1 second from now, if not timed out.
2985 static bool setup_poll_open(
2986 struct smb_request *req,
2987 struct share_mode_lock *lck,
2989 struct timeval max_timeout,
2990 struct timeval interval)
2993 struct deferred_open_record *open_rec = NULL;
2994 struct timeval endtime, next_interval;
2995 struct file_id_buf ftmp;
2997 if (request_timed_out(req, max_timeout)) {
3001 open_rec = talloc_zero(NULL, struct deferred_open_record);
3002 if (open_rec == NULL) {
3003 DBG_WARNING("talloc failed\n");
3006 open_rec->xconn = req->xconn;
3007 open_rec->mid = req->mid;
3010 * Make sure open_rec->te does not come later than the
3011 * request's maximum endtime.
3014 endtime = timeval_sum(&req->request_time, &max_timeout);
3015 next_interval = timeval_current_ofs(interval.tv_sec, interval.tv_usec);
3016 next_interval = timeval_min(&endtime, &next_interval);
3018 open_rec->te = tevent_add_timer(
3024 if (open_rec->te == NULL) {
3025 DBG_WARNING("tevent_add_timer failed\n");
3026 TALLOC_FREE(open_rec);
3031 open_rec->watch_req = share_mode_watch_send(
3035 (struct server_id) {0});
3036 if (open_rec->watch_req == NULL) {
3037 DBG_WARNING("share_mode_watch_send failed\n");
3038 TALLOC_FREE(open_rec);
3041 tevent_req_set_callback(
3042 open_rec->watch_req, poll_open_done, open_rec);
3045 ok = push_deferred_open_message_smb(req, max_timeout, id, open_rec);
3047 DBG_WARNING("push_deferred_open_message_smb failed\n");
3048 TALLOC_FREE(open_rec);
3052 DBG_DEBUG("poll request time [%s] mid [%" PRIu64 "] file_id [%s]\n",
3053 timeval_string(talloc_tos(), &req->request_time, false),
3055 file_id_str_buf(id, &ftmp));
3060 static void poll_open_done(struct tevent_req *subreq)
3062 struct deferred_open_record *open_rec = tevent_req_callback_data(
3063 subreq, struct deferred_open_record);
3067 status = share_mode_watch_recv(subreq, NULL, NULL);
3068 TALLOC_FREE(subreq);
3069 open_rec->watch_req = NULL;
3070 TALLOC_FREE(open_rec->te);
3072 DBG_DEBUG("dbwrap_watched_watch_recv returned %s\n",
3075 ok = schedule_deferred_open_message_smb(
3076 open_rec->xconn, open_rec->mid);
3078 exit_server("schedule_deferred_open_message_smb failed");
3082 bool defer_smb1_sharing_violation(struct smb_request *req)
3087 if (!lp_defer_sharing_violations()) {
3092 * Try every 200msec up to (by default) one second. To be
3093 * precise, according to behaviour note <247> in [MS-CIFS],
3094 * the server tries 5 times. But up to one second should be
3098 timeout_usecs = lp_parm_int(
3102 SHARING_VIOLATION_USEC_WAIT);
3104 ok = setup_poll_open(
3107 (struct file_id) {0},
3108 (struct timeval) { .tv_usec = timeout_usecs },
3109 (struct timeval) { .tv_usec = 200000 });
3113 /****************************************************************************
3114 On overwrite open ensure that the attributes match.
3115 ****************************************************************************/
3117 static bool open_match_attributes(connection_struct *conn,
3118 uint32_t old_dos_attr,
3119 uint32_t new_dos_attr,
3120 mode_t new_unx_mode,
3121 mode_t *returned_unx_mode)
3123 uint32_t noarch_old_dos_attr, noarch_new_dos_attr;
3125 noarch_old_dos_attr = (old_dos_attr & ~FILE_ATTRIBUTE_ARCHIVE);
3126 noarch_new_dos_attr = (new_dos_attr & ~FILE_ATTRIBUTE_ARCHIVE);
3128 if((noarch_old_dos_attr == 0 && noarch_new_dos_attr != 0) ||
3129 (noarch_old_dos_attr != 0 && ((noarch_old_dos_attr & noarch_new_dos_attr) == noarch_old_dos_attr))) {
3130 *returned_unx_mode = new_unx_mode;
3132 *returned_unx_mode = (mode_t)0;
3135 DEBUG(10,("open_match_attributes: old_dos_attr = 0x%x, "
3136 "new_dos_attr = 0x%x "
3137 "returned_unx_mode = 0%o\n",
3138 (unsigned int)old_dos_attr,
3139 (unsigned int)new_dos_attr,
3140 (unsigned int)*returned_unx_mode ));
3142 /* If we're mapping SYSTEM and HIDDEN ensure they match. */
3143 if (lp_map_system(SNUM(conn)) || lp_store_dos_attributes(SNUM(conn))) {
3144 if ((old_dos_attr & FILE_ATTRIBUTE_SYSTEM) &&
3145 !(new_dos_attr & FILE_ATTRIBUTE_SYSTEM)) {
3149 if (lp_map_hidden(SNUM(conn)) || lp_store_dos_attributes(SNUM(conn))) {
3150 if ((old_dos_attr & FILE_ATTRIBUTE_HIDDEN) &&
3151 !(new_dos_attr & FILE_ATTRIBUTE_HIDDEN)) {
3158 static void schedule_defer_open(struct share_mode_lock *lck,
3160 struct smb_request *req)
3162 /* This is a relative time, added to the absolute
3163 request_time value to get the absolute timeout time.
3164 Note that if this is the second or greater time we enter
3165 this codepath for this particular request mid then
3166 request_time is left as the absolute time of the *first*
3167 time this request mid was processed. This is what allows
3168 the request to eventually time out. */
3170 struct timeval timeout;
3172 /* Normally the smbd we asked should respond within
3173 * OPLOCK_BREAK_TIMEOUT seconds regardless of whether
3174 * the client did, give twice the timeout as a safety
3175 * measure here in case the other smbd is stuck
3176 * somewhere else. */
3178 timeout = timeval_set(OPLOCK_BREAK_TIMEOUT*2, 0);
3180 if (request_timed_out(req, timeout)) {
3184 defer_open(lck, timeout, req, id);
3187 /****************************************************************************
3188 Reschedule an open call that went asynchronous.
3189 ****************************************************************************/
3191 static void schedule_async_open_timer(struct tevent_context *ev,
3192 struct tevent_timer *te,
3193 struct timeval current_time,
3196 exit_server("async open timeout");
3199 static void schedule_async_open(struct smb_request *req)
3201 struct deferred_open_record *open_rec = NULL;
3202 struct timeval timeout = timeval_set(20, 0);
3205 if (request_timed_out(req, timeout)) {
3209 open_rec = talloc_zero(NULL, struct deferred_open_record);
3210 if (open_rec == NULL) {
3211 exit_server("deferred_open_record_create failed");
3213 open_rec->async_open = true;
3215 ok = push_deferred_open_message_smb(
3216 req, timeout, (struct file_id){0}, open_rec);
3218 exit_server("push_deferred_open_message_smb failed");
3221 open_rec->te = tevent_add_timer(req->sconn->ev_ctx,
3223 timeval_current_ofs(20, 0),
3224 schedule_async_open_timer,
3226 if (open_rec->te == NULL) {
3227 exit_server("tevent_add_timer failed");
3231 /****************************************************************************
3232 Work out what access_mask to use from what the client sent us.
3233 ****************************************************************************/
3235 static NTSTATUS smbd_calculate_maximum_allowed_access(
3236 connection_struct *conn,
3237 struct files_struct *dirfsp,
3238 const struct smb_filename *smb_fname,
3240 uint32_t *p_access_mask)
3242 struct security_descriptor *sd;
3243 uint32_t access_granted;
3246 SMB_ASSERT(dirfsp == conn->cwd_fsp);
3248 if (!use_privs && (get_current_uid(conn) == (uid_t)0)) {
3249 *p_access_mask |= FILE_GENERIC_ALL;
3250 return NT_STATUS_OK;
3253 status = SMB_VFS_GET_NT_ACL_AT(conn,
3262 if (NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
3264 * File did not exist
3266 *p_access_mask = FILE_GENERIC_ALL;
3267 return NT_STATUS_OK;
3269 if (!NT_STATUS_IS_OK(status)) {
3270 DEBUG(10,("Could not get acl on file %s: %s\n",
3271 smb_fname_str_dbg(smb_fname),
3272 nt_errstr(status)));
3273 return NT_STATUS_ACCESS_DENIED;
3277 * If we can access the path to this file, by
3278 * default we have FILE_READ_ATTRIBUTES from the
3279 * containing directory. See the section:
3280 * "Algorithm to Check Access to an Existing File"
3283 * se_file_access_check()
3284 * also takes care of owner WRITE_DAC and READ_CONTROL.
3286 status = se_file_access_check(sd,
3287 get_current_nttok(conn),
3289 (*p_access_mask & ~FILE_READ_ATTRIBUTES),
3294 if (!NT_STATUS_IS_OK(status)) {
3295 DEBUG(10, ("Access denied on file %s: "
3296 "when calculating maximum access\n",
3297 smb_fname_str_dbg(smb_fname)));
3298 return NT_STATUS_ACCESS_DENIED;
3300 *p_access_mask = (access_granted | FILE_READ_ATTRIBUTES);
3302 if (!(access_granted & DELETE_ACCESS)) {
3303 if (can_delete_file_in_directory(conn,
3307 *p_access_mask |= DELETE_ACCESS;
3311 return NT_STATUS_OK;
3314 NTSTATUS smbd_calculate_access_mask(connection_struct *conn,
3315 struct files_struct *dirfsp,
3316 const struct smb_filename *smb_fname,
3318 uint32_t access_mask,
3319 uint32_t *access_mask_out)
3322 uint32_t orig_access_mask = access_mask;
3323 uint32_t rejected_share_access;
3325 SMB_ASSERT(dirfsp == conn->cwd_fsp);
3327 if (access_mask & SEC_MASK_INVALID) {
3328 DBG_DEBUG("access_mask [%8x] contains invalid bits\n",
3330 return NT_STATUS_ACCESS_DENIED;
3334 * Convert GENERIC bits to specific bits.
3337 se_map_generic(&access_mask, &file_generic_mapping);
3339 /* Calculate MAXIMUM_ALLOWED_ACCESS if requested. */
3340 if (access_mask & MAXIMUM_ALLOWED_ACCESS) {
3342 status = smbd_calculate_maximum_allowed_access(conn,
3348 if (!NT_STATUS_IS_OK(status)) {
3352 access_mask &= conn->share_access;
3355 rejected_share_access = access_mask & ~(conn->share_access);
3357 if (rejected_share_access) {
3358 DEBUG(10, ("smbd_calculate_access_mask: Access denied on "
3359 "file %s: rejected by share access mask[0x%08X] "
3360 "orig[0x%08X] mapped[0x%08X] reject[0x%08X]\n",
3361 smb_fname_str_dbg(smb_fname),
3363 orig_access_mask, access_mask,
3364 rejected_share_access));
3365 return NT_STATUS_ACCESS_DENIED;
3368 *access_mask_out = access_mask;
3369 return NT_STATUS_OK;
3372 /****************************************************************************
3373 Remove the deferred open entry under lock.
3374 ****************************************************************************/
3376 /****************************************************************************
3377 Return true if this is a state pointer to an asynchronous create.
3378 ****************************************************************************/
3380 bool is_deferred_open_async(const struct deferred_open_record *rec)
3382 return rec->async_open;
3385 static bool clear_ads(uint32_t create_disposition)
3389 switch (create_disposition) {
3390 case FILE_SUPERSEDE:
3391 case FILE_OVERWRITE_IF:
3392 case FILE_OVERWRITE:
3401 static int disposition_to_open_flags(uint32_t create_disposition)
3406 * Currently we're using FILE_SUPERSEDE as the same as
3407 * FILE_OVERWRITE_IF but they really are
3408 * different. FILE_SUPERSEDE deletes an existing file
3409 * (requiring delete access) then recreates it.
3412 switch (create_disposition) {
3413 case FILE_SUPERSEDE:
3414 case FILE_OVERWRITE_IF:
3416 * If file exists replace/overwrite. If file doesn't
3419 ret = O_CREAT|O_TRUNC;
3424 * If file exists open. If file doesn't exist error.
3429 case FILE_OVERWRITE:
3431 * If file exists overwrite. If file doesn't exist
3439 * If file exists error. If file doesn't exist create.
3441 ret = O_CREAT|O_EXCL;
3446 * If file exists open. If file doesn't exist create.
3454 static int calculate_open_access_flags(uint32_t access_mask,
3455 uint32_t private_flags)
3457 bool need_write, need_read;
3460 * Note that we ignore the append flag as append does not
3461 * mean the same thing under DOS and Unix.
3464 need_write = (access_mask & (FILE_WRITE_DATA | FILE_APPEND_DATA));
3469 /* DENY_DOS opens are always underlying read-write on the
3470 file handle, no matter what the requested access mask
3474 ((private_flags & NTCREATEX_FLAG_DENY_DOS) ||
3475 access_mask & (FILE_READ_ATTRIBUTES|FILE_READ_DATA|
3476 FILE_READ_EA|FILE_EXECUTE));
3484 /****************************************************************************
3485 Open a file with a share mode. Passed in an already created files_struct *.
3486 ****************************************************************************/
3488 static NTSTATUS open_file_ntcreate(connection_struct *conn,
3489 struct smb_request *req,
3490 uint32_t access_mask, /* access bits (FILE_READ_DATA etc.) */
3491 uint32_t share_access, /* share constants (FILE_SHARE_READ etc) */
3492 uint32_t create_disposition, /* FILE_OPEN_IF etc. */
3493 uint32_t create_options, /* options such as delete on close. */
3494 uint32_t new_dos_attributes, /* attributes used for new file. */
3495 int oplock_request, /* internal Samba oplock codes. */
3496 const struct smb2_lease *lease,
3497 /* Information (FILE_EXISTS etc.) */
3498 uint32_t private_flags, /* Samba specific flags. */
3502 struct smb_filename *smb_fname = fsp->fsp_name;
3505 bool file_existed = VALID_STAT(smb_fname->st);
3506 bool def_acl = False;
3507 bool posix_open = False;
3508 bool new_file_created = False;
3509 bool first_open_attempt = true;
3510 NTSTATUS fsp_open = NT_STATUS_ACCESS_DENIED;
3511 mode_t new_unx_mode = (mode_t)0;
3512 mode_t unx_mode = (mode_t)0;
3514 uint32_t existing_dos_attributes = 0;
3515 struct share_mode_lock *lck = NULL;
3516 uint32_t open_access_mask = access_mask;
3518 struct smb_filename *parent_dir_fname = NULL;
3519 SMB_STRUCT_STAT saved_stat = smb_fname->st;
3520 struct timespec old_write_time;
3521 bool setup_poll = false;
3524 if (conn->printer) {
3526 * Printers are handled completely differently.
3527 * Most of the passed parameters are ignored.
3531 *pinfo = FILE_WAS_CREATED;
3534 DEBUG(10, ("open_file_ntcreate: printer open fname=%s\n",
3535 smb_fname_str_dbg(smb_fname)));
3538 DEBUG(0,("open_file_ntcreate: printer open without "
3539 "an SMB request!\n"));
3540 return NT_STATUS_INTERNAL_ERROR;
3543 return print_spool_open(fsp, smb_fname->base_name,
3547 status = SMB_VFS_PARENT_PATHNAME(conn,
3552 if (!NT_STATUS_IS_OK(status)) {
3556 if (new_dos_attributes & FILE_FLAG_POSIX_SEMANTICS) {
3558 unx_mode = (mode_t)(new_dos_attributes & ~FILE_FLAG_POSIX_SEMANTICS);
3559 new_dos_attributes = 0;
3561 /* Windows allows a new file to be created and
3562 silently removes a FILE_ATTRIBUTE_DIRECTORY
3563 sent by the client. Do the same. */
3565 new_dos_attributes &= ~FILE_ATTRIBUTE_DIRECTORY;
3567 /* We add FILE_ATTRIBUTE_ARCHIVE to this as this mode is only used if the file is
3569 unx_mode = unix_mode(conn, new_dos_attributes | FILE_ATTRIBUTE_ARCHIVE,
3570 smb_fname, parent_dir_fname);
3573 DEBUG(10, ("open_file_ntcreate: fname=%s, dos_attrs=0x%x "
3574 "access_mask=0x%x share_access=0x%x "
3575 "create_disposition = 0x%x create_options=0x%x "
3576 "unix mode=0%o oplock_request=%d private_flags = 0x%x\n",
3577 smb_fname_str_dbg(smb_fname), new_dos_attributes,
3578 access_mask, share_access, create_disposition,
3579 create_options, (unsigned int)unx_mode, oplock_request,
3580 (unsigned int)private_flags));
3583 /* Ensure req == NULL means INTERNAL_OPEN_ONLY */
3584 SMB_ASSERT(oplock_request == INTERNAL_OPEN_ONLY);
3586 /* And req != NULL means no INTERNAL_OPEN_ONLY */
3587 SMB_ASSERT(((oplock_request & INTERNAL_OPEN_ONLY) == 0));
3591 * Only non-internal opens can be deferred at all
3595 struct deferred_open_record *open_rec;
3596 if (get_deferred_open_message_state(req, NULL, &open_rec)) {
3598 /* If it was an async create retry, the file
3601 if (is_deferred_open_async(open_rec)) {
3602 SET_STAT_INVALID(smb_fname->st);
3603 file_existed = false;
3606 /* Ensure we don't reprocess this message. */
3607 remove_deferred_open_message_smb(req->xconn, req->mid);
3609 first_open_attempt = false;
3614 new_dos_attributes &= SAMBA_ATTRIBUTES_MASK;
3617 * Only use stored DOS attributes for checks
3618 * against requested attributes (below via
3619 * open_match_attributes()), cf bug #11992
3620 * for details. -slow
3624 status = SMB_VFS_FGET_DOS_ATTRIBUTES(conn, smb_fname->fsp, &attr);
3625 if (NT_STATUS_IS_OK(status)) {
3626 existing_dos_attributes = attr;
3631 /* ignore any oplock requests if oplocks are disabled */
3632 if (!lp_oplocks(SNUM(conn)) ||
3633 IS_VETO_OPLOCK_PATH(conn, smb_fname->base_name)) {
3634 /* Mask off everything except the private Samba bits. */
3635 oplock_request &= SAMBA_PRIVATE_OPLOCK_MASK;
3638 /* this is for OS/2 long file names - say we don't support them */
3639 if (req != NULL && !req->posix_pathnames &&
3640 strstr(smb_fname->base_name,".+,;=[].")) {
3641 /* OS/2 Workplace shell fix may be main code stream in a later
3643 DEBUG(5,("open_file_ntcreate: OS/2 long filenames are not "
3645 if (use_nt_status()) {
3646 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3648 return NT_STATUS_DOS(ERRDOS, ERRcannotopen);
3651 switch( create_disposition ) {
3653 /* If file exists open. If file doesn't exist error. */
3654 if (!file_existed) {
3655 DEBUG(5,("open_file_ntcreate: FILE_OPEN "
3656 "requested for file %s and file "
3658 smb_fname_str_dbg(smb_fname)));
3659 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3663 case FILE_OVERWRITE:
3664 /* If file exists overwrite. If file doesn't exist
3666 if (!file_existed) {
3667 DEBUG(5,("open_file_ntcreate: FILE_OVERWRITE "
3668 "requested for file %s and file "
3670 smb_fname_str_dbg(smb_fname) ));
3671 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3676 /* If file exists error. If file doesn't exist
3679 DEBUG(5,("open_file_ntcreate: FILE_CREATE "
3680 "requested for file %s and file "
3681 "already exists.\n",
3682 smb_fname_str_dbg(smb_fname)));
3683 if (S_ISDIR(smb_fname->st.st_ex_mode)) {
3684 return NT_STATUS_FILE_IS_A_DIRECTORY;
3686 return NT_STATUS_OBJECT_NAME_COLLISION;
3691 case FILE_SUPERSEDE:
3692 case FILE_OVERWRITE_IF:
3696 return NT_STATUS_INVALID_PARAMETER;
3699 flags2 = disposition_to_open_flags(create_disposition);
3701 /* We only care about matching attributes on file exists and
3704 if (!posix_open && file_existed &&
3705 ((create_disposition == FILE_OVERWRITE) ||
3706 (create_disposition == FILE_OVERWRITE_IF))) {
3707 if (!open_match_attributes(conn, existing_dos_attributes,
3709 unx_mode, &new_unx_mode)) {
3710 DEBUG(5,("open_file_ntcreate: attributes mismatch "
3711 "for file %s (%x %x) (0%o, 0%o)\n",
3712 smb_fname_str_dbg(smb_fname),
3713 existing_dos_attributes,
3715 (unsigned int)smb_fname->st.st_ex_mode,
3716 (unsigned int)unx_mode ));
3717 return NT_STATUS_ACCESS_DENIED;
3721 status = smbd_calculate_access_mask(conn,
3727 if (!NT_STATUS_IS_OK(status)) {
3728 DEBUG(10, ("open_file_ntcreate: smbd_calculate_access_mask "
3729 "on file %s returned %s\n",
3730 smb_fname_str_dbg(smb_fname), nt_errstr(status)));
3734 open_access_mask = access_mask;
3736 if (flags2 & O_TRUNC) {
3737 open_access_mask |= FILE_WRITE_DATA; /* This will cause oplock breaks. */
3742 * stat opens on existing files don't get oplocks.
3743 * They can get leases.
3745 * Note that we check for stat open on the *open_access_mask*,
3746 * i.e. the access mask we actually used to do the open,
3747 * not the one the client asked for (which is in
3748 * fsp->access_mask). This is due to the fact that
3749 * FILE_OVERWRITE and FILE_OVERWRITE_IF add in O_TRUNC,
3750 * which adds FILE_WRITE_DATA to open_access_mask.
3752 if (is_oplock_stat_open(open_access_mask) && lease == NULL) {
3753 oplock_request = NO_OPLOCK;
3757 DEBUG(10, ("open_file_ntcreate: fname=%s, after mapping "
3758 "access_mask=0x%x\n", smb_fname_str_dbg(smb_fname),
3762 * Note that we ignore the append flag as append does not
3763 * mean the same thing under DOS and Unix.
3766 flags = calculate_open_access_flags(access_mask, private_flags);
3769 * Currently we only look at FILE_WRITE_THROUGH for create options.
3773 if ((create_options & FILE_WRITE_THROUGH) && lp_strict_sync(SNUM(conn))) {
3778 if (posix_open && (access_mask & FILE_APPEND_DATA)) {
3782 if (!posix_open && !CAN_WRITE(conn)) {
3784 * We should really return a permission denied error if either
3785 * O_CREAT or O_TRUNC are set, but for compatibility with
3786 * older versions of Samba we just AND them out.
3788 flags2 &= ~(O_CREAT|O_TRUNC);
3792 * With kernel oplocks the open breaking an oplock
3793 * blocks until the oplock holder has given up the
3794 * oplock or closed the file. We prevent this by always
3795 * trying to open the file with O_NONBLOCK (see "man
3798 * If a process that doesn't use the smbd open files
3799 * database or communication methods holds a kernel
3800 * oplock we must periodically poll for available open
3803 flags2 |= O_NONBLOCK;
3806 * Ensure we can't write on a read-only share or file.
3809 if (flags != O_RDONLY && file_existed &&
3810 (!CAN_WRITE(conn) || IS_DOS_READONLY(existing_dos_attributes))) {
3811 DEBUG(5,("open_file_ntcreate: write access requested for "
3812 "file %s on read only %s\n",
3813 smb_fname_str_dbg(smb_fname),
3814 !CAN_WRITE(conn) ? "share" : "file" ));
3815 return NT_STATUS_ACCESS_DENIED;
3818 if (VALID_STAT(smb_fname->st)) {
3820 * Only try and create a file id before open
3821 * for an existing file. For a file being created
3822 * this won't do anything useful until the file
3823 * exists and has a valid stat struct.
3825 fsp->file_id = vfs_file_id_from_sbuf(conn, &smb_fname->st);
3827 fh_set_private_options(fsp->fh, private_flags);
3828 fsp->access_mask = open_access_mask; /* We change this to the
3829 * requested access_mask after
3830 * the open is done. */
3832 fsp->posix_flags |= FSP_POSIX_FLAGS_ALL;
3835 if ((create_options & FILE_DELETE_ON_CLOSE) &&
3836 (flags2 & O_CREAT) &&
3838 /* Delete on close semantics for new files. */
3839 status = can_set_delete_on_close(fsp,
3840 new_dos_attributes);
3841 if (!NT_STATUS_IS_OK(status)) {
3848 * Ensure we pay attention to default ACLs on directories if required.
3851 if ((flags2 & O_CREAT) && lp_inherit_acls(SNUM(conn)) &&
3852 (def_acl = directory_has_default_acl(conn,
3856 unx_mode = (0777 & lp_create_mask(SNUM(conn)));
3859 DEBUG(4,("calling open_file with flags=0x%X flags2=0x%X mode=0%o, "
3860 "access_mask = 0x%x, open_access_mask = 0x%x\n",
3861 (unsigned int)flags, (unsigned int)flags2,
3862 (unsigned int)unx_mode, (unsigned int)access_mask,
3863 (unsigned int)open_access_mask));
3865 fsp_open = open_file(fsp,
3874 if (NT_STATUS_EQUAL(fsp_open, NT_STATUS_NETWORK_BUSY)) {
3875 if (file_existed && S_ISFIFO(fsp->fsp_name->st.st_ex_mode)) {
3876 DEBUG(10, ("FIFO busy\n"));
3877 return NT_STATUS_NETWORK_BUSY;
3880 DEBUG(10, ("Internal open busy\n"));
3881 return NT_STATUS_NETWORK_BUSY;
3884 * This handles the kernel oplock case:
3886 * the file has an active kernel oplock and the open() returned
3887 * EWOULDBLOCK/EAGAIN which maps to NETWORK_BUSY.
3889 * "Samba locking.tdb oplocks" are handled below after acquiring
3890 * the sharemode lock with get_share_mode_lock().
3895 if (NT_STATUS_EQUAL(fsp_open, NT_STATUS_RETRY)) {
3897 * EINTR from the open(2) syscall. Just setup a retry
3898 * in a bit. We can't use the sys_write() tight retry
3899 * loop here, as we might have to actually deal with
3900 * lease-break signals to avoid a deadlock.
3907 * From here on we assume this is an oplock break triggered
3910 lck = get_existing_share_mode_lock(talloc_tos(), fsp->file_id);
3912 if ((lck != NULL) && !validate_oplock_types(lck)) {
3913 smb_panic("validate_oplock_types failed");
3917 * Retry once a second. If there's a share_mode_lock
3918 * around, also wait for it in case it was smbd
3919 * holding that kernel oplock that can quickly tell us
3920 * the oplock got removed.
3927 timeval_set(OPLOCK_BREAK_TIMEOUT*2, 0),
3932 return NT_STATUS_SHARING_VIOLATION;
3935 if (!NT_STATUS_IS_OK(fsp_open)) {
3936 bool wait_for_aio = NT_STATUS_EQUAL(
3937 fsp_open, NT_STATUS_MORE_PROCESSING_REQUIRED);
3939 schedule_async_open(req);
3944 if (new_file_created) {
3946 * As we atomically create using O_CREAT|O_EXCL,
3947 * then if new_file_created is true, then
3948 * file_existed *MUST* have been false (even
3949 * if the file was previously detected as being
3952 file_existed = false;
3955 if (file_existed && !check_same_dev_ino(&saved_stat, &smb_fname->st)) {
3957 * The file did exist, but some other (local or NFS)
3958 * process either renamed/unlinked and re-created the
3959 * file with different dev/ino after we walked the path,
3960 * but before we did the open. We could retry the
3961 * open but it's a rare enough case it's easier to
3962 * just fail the open to prevent creating any problems
3963 * in the open file db having the wrong dev/ino key.
3966 DBG_WARNING("file %s - dev/ino mismatch. "
3967 "Old (dev=%ju, ino=%ju). "
3968 "New (dev=%ju, ino=%ju). Failing open "
3969 "with NT_STATUS_ACCESS_DENIED.\n",
3970 smb_fname_str_dbg(smb_fname),
3971 (uintmax_t)saved_stat.st_ex_dev,
3972 (uintmax_t)saved_stat.st_ex_ino,
3973 (uintmax_t)smb_fname->st.st_ex_dev,
3974 (uintmax_t)smb_fname->st.st_ex_ino);
3975 return NT_STATUS_ACCESS_DENIED;
3978 old_write_time = smb_fname->st.st_ex_mtime;
3981 * Deal with the race condition where two smbd's detect the
3982 * file doesn't exist and do the create at the same time. One
3983 * of them will win and set a share mode, the other (ie. this
3984 * one) should check if the requested share mode for this
3985 * create is allowed.
3989 * Now the file exists and fsp is successfully opened,
3990 * fsp->dev and fsp->inode are valid and should replace the
3991 * dev=0,inode=0 from a non existent file. Spotted by
3992 * Nadav Danieli <nadavd@exanet.com>. JRA.
3995 lck = get_share_mode_lock(talloc_tos(), fsp->file_id,
3997 smb_fname, &old_write_time);
4000 DEBUG(0, ("open_file_ntcreate: Could not get share "
4001 "mode lock for %s\n",
4002 smb_fname_str_dbg(smb_fname)));
4004 return NT_STATUS_SHARING_VIOLATION;
4007 /* Get the types we need to examine. */
4008 if (!validate_oplock_types(lck)) {
4009 smb_panic("validate_oplock_types failed");
4012 if (has_delete_on_close(lck, fsp->name_hash)) {
4015 return NT_STATUS_DELETE_PENDING;
4018 status = handle_share_mode_lease(
4026 first_open_attempt);
4028 if (NT_STATUS_EQUAL(status, NT_STATUS_RETRY)) {
4029 schedule_defer_open(lck, fsp->file_id, req);
4032 return NT_STATUS_SHARING_VIOLATION;
4035 if (!NT_STATUS_IS_OK(status)) {
4041 share_mode_flags_restrict(lck, access_mask, share_access, 0);
4043 ok = set_share_mode(
4046 get_current_uid(fsp->conn),
4052 if (fsp->oplock_type == LEASE_OPLOCK) {
4053 status = remove_lease_if_stale(
4055 fsp_client_guid(fsp),
4056 &fsp->lease->lease.lease_key);
4057 if (!NT_STATUS_IS_OK(status)) {
4058 DBG_WARNING("remove_lease_if_stale "
4065 return NT_STATUS_NO_MEMORY;
4068 /* Should we atomically (to the client at least) truncate ? */
4069 if ((!new_file_created) &&
4070 (flags2 & O_TRUNC) &&
4071 (S_ISREG(fsp->fsp_name->st.st_ex_mode))) {
4074 ret = SMB_VFS_FTRUNCATE(fsp, 0);
4076 status = map_nt_error_from_unix(errno);
4077 del_share_mode(lck, fsp);
4082 notify_fname(fsp->conn, NOTIFY_ACTION_MODIFIED,
4083 FILE_NOTIFY_CHANGE_SIZE
4084 | FILE_NOTIFY_CHANGE_ATTRIBUTES,
4085 fsp->fsp_name->base_name);
4089 * We have the share entry *locked*.....
4092 /* Delete streams if create_disposition requires it */
4093 if (!new_file_created && clear_ads(create_disposition) &&
4094 !is_ntfs_stream_smb_fname(smb_fname)) {
4095 status = delete_all_streams(conn, smb_fname);
4096 if (!NT_STATUS_IS_OK(status)) {
4097 del_share_mode(lck, fsp);
4104 if (!fsp->fsp_flags.is_pathref &&
4105 fsp_get_io_fd(fsp) != -1 &&
4106 lp_kernel_share_modes(SNUM(conn)))
4110 * Beware: streams implementing VFS modules may
4111 * implement streams in a way that fsp will have the
4112 * basefile open in the fsp fd, so lacking a distinct
4113 * fd for the stream kernel_flock will apply on the
4114 * basefile which is wrong. The actual check is
4115 * deferred to the VFS module implementing the
4116 * kernel_flock call.
4118 ret_flock = SMB_VFS_KERNEL_FLOCK(fsp, share_access, access_mask);
4119 if(ret_flock == -1 ){
4121 del_share_mode(lck, fsp);
4125 return NT_STATUS_SHARING_VIOLATION;
4128 fsp->fsp_flags.kernel_share_modes_taken = true;
4132 * At this point onwards, we can guarantee that the share entry
4133 * is locked, whether we created the file or not, and that the
4134 * deny mode is compatible with all current opens.
4138 * According to Samba4, SEC_FILE_READ_ATTRIBUTE is always granted,
4139 * but we don't have to store this - just ignore it on access check.
4141 if (conn->sconn->using_smb2) {
4143 * SMB2 doesn't return it (according to Microsoft tests).
4144 * Test Case: TestSuite_ScenarioNo009GrantedAccessTestS0
4145 * File created with access = 0x7 (Read, Write, Delete)
4146 * Query Info on file returns 0x87 (Read, Write, Delete, Read Attributes)
4148 fsp->access_mask = access_mask;
4150 /* But SMB1 does. */
4151 fsp->access_mask = access_mask | FILE_READ_ATTRIBUTES;
4154 if (new_file_created) {
4155 info = FILE_WAS_CREATED;
4157 if (flags2 & O_TRUNC) {
4158 info = FILE_WAS_OVERWRITTEN;
4160 info = FILE_WAS_OPENED;
4168 /* Handle strange delete on close create semantics. */
4169 if (create_options & FILE_DELETE_ON_CLOSE) {
4170 if (!new_file_created) {
4171 status = can_set_delete_on_close(fsp,
4172 existing_dos_attributes);
4174 if (!NT_STATUS_IS_OK(status)) {
4175 /* Remember to delete the mode we just added. */
4176 del_share_mode(lck, fsp);
4182 /* Note that here we set the *initial* delete on close flag,
4183 not the regular one. The magic gets handled in close. */
4184 fsp->fsp_flags.initial_delete_on_close = true;
4188 * If we created a file and it's not a stream, this is the point where
4189 * we set the itime (aka invented time) that get's stored in the DOS
4190 * attribute xattr. The value is going to be either what the filesystem
4191 * provided or a copy of the creation date.
4193 * Either way, we turn the itime into a File-ID, unless the filesystem
4194 * provided one (unlikely).
4196 if (info == FILE_WAS_CREATED && !is_named_stream(smb_fname)) {
4197 smb_fname->st.st_ex_iflags &= ~ST_EX_IFLAG_CALCULATED_ITIME;
4199 if (lp_store_dos_attributes(SNUM(conn)) &&
4200 smb_fname->st.st_ex_iflags & ST_EX_IFLAG_CALCULATED_FILE_ID)
4204 file_id = make_file_id_from_itime(&smb_fname->st);
4205 update_stat_ex_file_id(&smb_fname->st, file_id);
4209 if (info != FILE_WAS_OPENED) {
4210 /* Overwritten files should be initially set as archive */
4211 if ((info == FILE_WAS_OVERWRITTEN && lp_map_archive(SNUM(conn))) ||
4212 lp_store_dos_attributes(SNUM(conn))) {
4213 (void)fdos_mode(fsp);
4215 if (file_set_dosmode(conn, smb_fname,
4216 new_dos_attributes | FILE_ATTRIBUTE_ARCHIVE,
4217 parent_dir_fname, true) == 0) {
4218 unx_mode = smb_fname->st.st_ex_mode;
4224 /* Determine sparse flag. */
4226 /* POSIX opens are sparse by default. */
4227 fsp->fsp_flags.is_sparse = true;
4229 fsp->fsp_flags.is_sparse =
4230 (existing_dos_attributes & FILE_ATTRIBUTE_SPARSE);
4234 * Take care of inherited ACLs on created files - if default ACL not
4238 if (!posix_open && new_file_created && !def_acl) {
4239 if (unx_mode != smb_fname->st.st_ex_mode) {
4240 int ret = SMB_VFS_FCHMOD(fsp, unx_mode);
4242 DBG_INFO("failed to reset "
4243 "attributes of file %s to 0%o\n",
4244 smb_fname_str_dbg(smb_fname),
4245 (unsigned int)unx_mode);
4249 } else if (new_unx_mode) {
4251 * We only get here in the case of:
4253 * a). Not a POSIX open.
4254 * b). File already existed.
4255 * c). File was overwritten.
4256 * d). Requested DOS attributes didn't match
4257 * the DOS attributes on the existing file.
4259 * In that case new_unx_mode has been set
4260 * equal to the calculated mode (including
4261 * possible inheritance of the mode from the
4262 * containing directory).
4264 * Note this mode was calculated with the
4265 * DOS attribute FILE_ATTRIBUTE_ARCHIVE added,
4266 * so the mode change here is suitable for
4267 * an overwritten file.
4270 if (new_unx_mode != smb_fname->st.st_ex_mode) {
4271 int ret = SMB_VFS_FCHMOD(fsp, new_unx_mode);
4273 DBG_INFO("failed to reset "
4274 "attributes of file %s to 0%o\n",
4275 smb_fname_str_dbg(smb_fname),
4276 (unsigned int)new_unx_mode);
4283 * Deal with other opens having a modified write time.
4285 struct timespec write_time = get_share_mode_write_time(lck);
4287 if (!is_omit_timespec(&write_time)) {
4288 update_stat_ex_mtime(&fsp->fsp_name->st, write_time);
4294 return NT_STATUS_OK;
4297 static NTSTATUS mkdir_internal(connection_struct *conn,
4298 struct smb_filename *smb_dname,
4299 uint32_t file_attributes,
4300 struct files_struct *fsp)
4302 const struct loadparm_substitution *lp_sub =
4303 loadparm_s3_global_substitution();
4305 struct smb_filename *parent_dir_fname = NULL;
4306 struct smb_filename *base_name = NULL;
4308 bool posix_open = false;
4309 bool need_re_stat = false;
4310 uint32_t access_mask = SEC_DIR_ADD_SUBDIR;
4313 if (!CAN_WRITE(conn) || (access_mask & ~(conn->share_access))) {
4314 DEBUG(5,("mkdir_internal: failing share access "
4315 "%s\n", lp_servicename(talloc_tos(), lp_sub, SNUM(conn))));
4316 return NT_STATUS_ACCESS_DENIED;
4319 status = parent_pathref(talloc_tos(),
4324 if (!NT_STATUS_IS_OK(status)) {
4328 if (file_attributes & FILE_FLAG_POSIX_SEMANTICS) {
4330 mode = (mode_t)(file_attributes & ~FILE_FLAG_POSIX_SEMANTICS);
4332 mode = unix_mode(conn,
4333 FILE_ATTRIBUTE_DIRECTORY,
4338 status = check_parent_access(conn,
4342 if(!NT_STATUS_IS_OK(status)) {
4343 DEBUG(5,("mkdir_internal: check_parent_access "
4344 "on directory %s for path %s returned %s\n",
4345 smb_fname_str_dbg(parent_dir_fname),
4346 smb_dname->base_name,
4347 nt_errstr(status) ));
4348 TALLOC_FREE(parent_dir_fname);
4352 if (lp_inherit_acls(SNUM(conn))) {
4353 if (directory_has_default_acl(conn,
4355 parent_dir_fname)) {
4356 mode = (0777 & lp_directory_mask(SNUM(conn)));
4360 ret = SMB_VFS_MKDIRAT(conn,
4361 parent_dir_fname->fsp,
4365 TALLOC_FREE(parent_dir_fname);
4366 return map_nt_error_from_unix(errno);
4370 * Make this a pathref fsp for now. open_directory() will reopen as a
4373 fsp->fsp_flags.is_pathref = true;
4375 status = fd_openat(conn->cwd_fsp, smb_dname, fsp, O_RDONLY | O_DIRECTORY, 0);
4376 if (!NT_STATUS_IS_OK(status)) {
4377 TALLOC_FREE(parent_dir_fname);
4381 /* Ensure we're checking for a symlink here.... */
4382 /* We don't want to get caught by a symlink racer. */
4384 if (SMB_VFS_FSTAT(fsp, &smb_dname->st) == -1) {
4385 DEBUG(2, ("Could not stat directory '%s' just created: %s\n",
4386 smb_fname_str_dbg(smb_dname), strerror(errno)));
4387 TALLOC_FREE(parent_dir_fname);
4388 return map_nt_error_from_unix(errno);
4391 if (!S_ISDIR(smb_dname->st.st_ex_mode)) {
4392 DEBUG(0, ("Directory '%s' just created is not a directory !\n",
4393 smb_fname_str_dbg(smb_dname)));
4394 TALLOC_FREE(parent_dir_fname);
4395 return NT_STATUS_NOT_A_DIRECTORY;
4398 smb_dname->st.st_ex_iflags &= ~ST_EX_IFLAG_CALCULATED_ITIME;
4400 if (lp_store_dos_attributes(SNUM(conn))) {
4401 if (smb_dname->st.st_ex_iflags & ST_EX_IFLAG_CALCULATED_FILE_ID)
4405 file_id = make_file_id_from_itime(&smb_dname->st);
4406 update_stat_ex_file_id(&smb_dname->st, file_id);
4410 file_set_dosmode(conn, smb_dname,
4411 file_attributes | FILE_ATTRIBUTE_DIRECTORY,
4412 parent_dir_fname, true);
4416 if (lp_inherit_permissions(SNUM(conn))) {
4417 inherit_access_posix_acl(conn, parent_dir_fname,
4419 need_re_stat = true;
4424 * Check if high bits should have been set,
4425 * then (if bits are missing): add them.
4426 * Consider bits automagically set by UNIX, i.e. SGID bit from parent
4429 if ((mode & ~(S_IRWXU|S_IRWXG|S_IRWXO)) &&
4430 (mode & ~smb_dname->st.st_ex_mode)) {
4432 (smb_dname->st.st_ex_mode |
4433 (mode & ~smb_dname->st.st_ex_mode)));
4434 need_re_stat = true;
4438 /* Change the owner if required. */
4439 if (lp_inherit_owner(SNUM(conn)) != INHERIT_OWNER_NO) {
4440 change_dir_owner_to_parent(conn, parent_dir_fname,
4443 need_re_stat = true;
4446 TALLOC_FREE(parent_dir_fname);
4449 if (SMB_VFS_FSTAT(fsp, &smb_dname->st) == -1) {
4450 DEBUG(2, ("Could not stat directory '%s' just created: %s\n",
4451 smb_fname_str_dbg(smb_dname), strerror(errno)));
4452 return map_nt_error_from_unix(errno);
4456 notify_fname(conn, NOTIFY_ACTION_ADDED, FILE_NOTIFY_CHANGE_DIR_NAME,
4457 smb_dname->base_name);
4459 return NT_STATUS_OK;
4462 /****************************************************************************
4463 Open a directory from an NT SMB call.
4464 ****************************************************************************/
4466 static NTSTATUS open_directory(connection_struct *conn,
4467 struct smb_request *req,
4468 uint32_t access_mask,
4469 uint32_t share_access,
4470 uint32_t create_disposition,
4471 uint32_t create_options,
4472 uint32_t file_attributes,
4474 struct files_struct *fsp)
4476 struct smb_filename *smb_dname = fsp->fsp_name;
4477 bool dir_existed = VALID_STAT(smb_dname->st);
4478 struct share_mode_lock *lck = NULL;
4480 struct timespec mtimespec;
4485 if (is_ntfs_stream_smb_fname(smb_dname)) {
4486 DEBUG(2, ("open_directory: %s is a stream name!\n",
4487 smb_fname_str_dbg(smb_dname)));
4488 return NT_STATUS_NOT_A_DIRECTORY;
4491 if (!(file_attributes & FILE_FLAG_POSIX_SEMANTICS)) {
4492 /* Ensure we have a directory attribute. */
4493 file_attributes |= FILE_ATTRIBUTE_DIRECTORY;
4496 DBG_INFO("opening directory %s, access_mask = 0x%"PRIx32", "
4497 "share_access = 0x%"PRIx32" create_options = 0x%"PRIx32", "
4498 "create_disposition = 0x%"PRIx32", "
4499 "file_attributes = 0x%"PRIx32"\n",
4500 smb_fname_str_dbg(smb_dname),
4507 status = smbd_calculate_access_mask(conn,
4513 if (!NT_STATUS_IS_OK(status)) {
4514 DEBUG(10, ("open_directory: smbd_calculate_access_mask "
4515 "on file %s returned %s\n",
4516 smb_fname_str_dbg(smb_dname),
4517 nt_errstr(status)));
4521 if ((access_mask & SEC_FLAG_SYSTEM_SECURITY) &&
4522 !security_token_has_privilege(get_current_nttok(conn),
4523 SEC_PRIV_SECURITY)) {
4524 DEBUG(10, ("open_directory: open on %s "
4525 "failed - SEC_FLAG_SYSTEM_SECURITY denied.\n",
4526 smb_fname_str_dbg(smb_dname)));
4527 return NT_STATUS_PRIVILEGE_NOT_HELD;
4530 switch( create_disposition ) {
4534 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
4537 info = FILE_WAS_OPENED;
4542 /* If directory exists error. If directory doesn't
4546 status = NT_STATUS_OBJECT_NAME_COLLISION;
4547 DEBUG(2, ("open_directory: unable to create "
4548 "%s. Error was %s\n",
4549 smb_fname_str_dbg(smb_dname),
4550 nt_errstr(status)));
4554 status = mkdir_internal(conn,
4559 if (!NT_STATUS_IS_OK(status)) {
4560 DEBUG(2, ("open_directory: unable to create "
4561 "%s. Error was %s\n",
4562 smb_fname_str_dbg(smb_dname),
4563 nt_errstr(status)));
4567 info = FILE_WAS_CREATED;
4572 * If directory exists open. If directory doesn't
4577 status = NT_STATUS_OK;
4578 info = FILE_WAS_OPENED;
4580 status = mkdir_internal(conn,
4585 if (NT_STATUS_IS_OK(status)) {
4586 info = FILE_WAS_CREATED;
4588 /* Cope with create race. */
4589 if (!NT_STATUS_EQUAL(status,
4590 NT_STATUS_OBJECT_NAME_COLLISION)) {
4591 DEBUG(2, ("open_directory: unable to create "
4592 "%s. Error was %s\n",
4593 smb_fname_str_dbg(smb_dname),
4594 nt_errstr(status)));
4599 * If mkdir_internal() returned
4600 * NT_STATUS_OBJECT_NAME_COLLISION
4601 * we still must lstat the path.
4604 if (SMB_VFS_LSTAT(conn, smb_dname)
4606 DEBUG(2, ("Could not stat "
4607 "directory '%s' just "
4612 return map_nt_error_from_unix(
4616 info = FILE_WAS_OPENED;
4622 case FILE_SUPERSEDE:
4623 case FILE_OVERWRITE:
4624 case FILE_OVERWRITE_IF:
4626 DEBUG(5,("open_directory: invalid create_disposition "
4627 "0x%x for directory %s\n",
4628 (unsigned int)create_disposition,
4629 smb_fname_str_dbg(smb_dname)));
4630 return NT_STATUS_INVALID_PARAMETER;
4633 if(!S_ISDIR(smb_dname->st.st_ex_mode)) {
4634 DEBUG(5,("open_directory: %s is not a directory !\n",
4635 smb_fname_str_dbg(smb_dname)));
4636 return NT_STATUS_NOT_A_DIRECTORY;
4640 * Setup the files_struct for it.
4643 fsp->file_id = vfs_file_id_from_sbuf(conn, &smb_dname->st);
4644 fsp->vuid = req ? req->vuid : UID_FIELD_INVALID;
4645 fsp->file_pid = req ? req->smbpid : 0;
4646 fsp->fsp_flags.can_lock = false;
4647 fsp->fsp_flags.can_read = false;
4648 fsp->fsp_flags.can_write = false;
4650 fh_set_private_options(fsp->fh, 0);
4652 * According to Samba4, SEC_FILE_READ_ATTRIBUTE is always granted,
4654 fsp->access_mask = access_mask | FILE_READ_ATTRIBUTES;
4655 fsp->print_file = NULL;
4656 fsp->fsp_flags.modified = false;
4657 fsp->oplock_type = NO_OPLOCK;
4658 fsp->sent_oplock_break = NO_BREAK_SENT;
4659 fsp->fsp_flags.is_directory = true;
4660 if (file_attributes & FILE_FLAG_POSIX_SEMANTICS) {
4661 fsp->posix_flags |= FSP_POSIX_FLAGS_ALL;
4664 /* Don't store old timestamps for directory
4665 handles in the internal database. We don't
4666 update them in there if new objects
4667 are created in the directory. Currently
4668 we only update timestamps on file writes.
4671 mtimespec = make_omit_timespec();
4673 /* POSIX allows us to open a directory with O_RDONLY. */
4676 flags |= O_DIRECTORY;
4679 status = reopen_from_fsp(fsp, flags, 0, NULL);
4680 if (!NT_STATUS_IS_OK(status)) {
4681 DBG_INFO("Could not open fd for%s (%s)\n",
4682 smb_fname_str_dbg(smb_dname),
4687 status = vfs_stat_fsp(fsp);
4688 if (!NT_STATUS_IS_OK(status)) {
4693 if(!S_ISDIR(fsp->fsp_name->st.st_ex_mode)) {
4694 DEBUG(5,("open_directory: %s is not a directory !\n",
4695 smb_fname_str_dbg(smb_dname)));
4697 return NT_STATUS_NOT_A_DIRECTORY;
4700 /* Ensure there was no race condition. We need to check
4701 * dev/inode but not permissions, as these can change
4703 if (!check_same_dev_ino(&smb_dname->st, &fsp->fsp_name->st)) {
4704 DEBUG(5,("open_directory: stat struct differs for "
4706 smb_fname_str_dbg(smb_dname)));
4708 return NT_STATUS_ACCESS_DENIED;
4711 if (info == FILE_WAS_OPENED) {
4712 status = smbd_check_access_rights(conn,
4717 if (!NT_STATUS_IS_OK(status)) {
4718 DEBUG(10, ("open_directory: smbd_check_access_rights on "
4719 "file %s failed with %s\n",
4720 smb_fname_str_dbg(smb_dname),
4721 nt_errstr(status)));
4727 lck = get_share_mode_lock(talloc_tos(), fsp->file_id,
4728 conn->connectpath, smb_dname,
4732 DEBUG(0, ("open_directory: Could not get share mode lock for "
4733 "%s\n", smb_fname_str_dbg(smb_dname)));
4735 return NT_STATUS_SHARING_VIOLATION;
4738 if (has_delete_on_close(lck, fsp->name_hash)) {
4741 return NT_STATUS_DELETE_PENDING;
4744 status = open_mode_check(conn, fsp->file_id, lck,
4745 access_mask, share_access);
4747 if (!NT_STATUS_IS_OK(status)) {
4753 share_mode_flags_restrict(lck, access_mask, share_access, 0);
4755 ok = set_share_mode(
4758 get_current_uid(conn),
4766 return NT_STATUS_NO_MEMORY;
4769 /* For directories the delete on close bit at open time seems
4770 always to be honored on close... See test 19 in Samba4 BASE-DELETE. */
4771 if (create_options & FILE_DELETE_ON_CLOSE) {
4772 status = can_set_delete_on_close(fsp, 0);
4773 if (!NT_STATUS_IS_OK(status) && !NT_STATUS_EQUAL(status, NT_STATUS_DIRECTORY_NOT_EMPTY)) {
4774 del_share_mode(lck, fsp);
4780 if (NT_STATUS_IS_OK(status)) {
4781 /* Note that here we set the *initial* delete on close flag,
4782 not the regular one. The magic gets handled in close. */
4783 fsp->fsp_flags.initial_delete_on_close = true;
4789 * Deal with other opens having a modified write time. Is this
4790 * possible for directories?
4792 struct timespec write_time = get_share_mode_write_time(lck);
4794 if (!is_omit_timespec(&write_time)) {
4795 update_stat_ex_mtime(&fsp->fsp_name->st, write_time);
4805 return NT_STATUS_OK;
4808 NTSTATUS create_directory(connection_struct *conn, struct smb_request *req,
4809 struct smb_filename *smb_dname)
4814 status = SMB_VFS_CREATE_FILE(
4817 smb_dname, /* fname */
4818 FILE_READ_ATTRIBUTES, /* access_mask */
4819 FILE_SHARE_NONE, /* share_access */
4820 FILE_CREATE, /* create_disposition*/
4821 FILE_DIRECTORY_FILE, /* create_options */
4822 FILE_ATTRIBUTE_DIRECTORY, /* file_attributes */
4823 0, /* oplock_request */
4825 0, /* allocation_size */
4826 0, /* private_flags */
4831 NULL, NULL); /* create context */
4833 if (NT_STATUS_IS_OK(status)) {
4834 close_file(req, fsp, NORMAL_CLOSE);
4840 /****************************************************************************
4841 Receive notification that one of our open files has been renamed by another
4843 ****************************************************************************/
4845 void msg_file_was_renamed(struct messaging_context *msg_ctx,
4848 struct server_id src,
4851 struct file_rename_message *msg = NULL;
4852 enum ndr_err_code ndr_err;
4854 struct smb_filename *smb_fname = NULL;
4855 struct smbd_server_connection *sconn =
4856 talloc_get_type_abort(private_data,
4857 struct smbd_server_connection);
4859 msg = talloc(talloc_tos(), struct file_rename_message);
4861 DBG_WARNING("talloc failed\n");
4865 ndr_err = ndr_pull_struct_blob_all(
4869 (ndr_pull_flags_fn_t)ndr_pull_file_rename_message);
4870 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
4871 DBG_DEBUG("ndr_pull_oplock_break_message failed: %s\n",
4872 ndr_errstr(ndr_err));
4875 if (DEBUGLEVEL >= 10) {
4876 struct server_id_buf buf;
4877 DBG_DEBUG("Got rename message from %s\n",
4878 server_id_str_buf(src, &buf));
4879 NDR_PRINT_DEBUG(file_rename_message, msg);
4882 /* stream_name must always be NULL if there is no stream. */
4883 if ((msg->stream_name != NULL) && (msg->stream_name[0] == '\0')) {
4884 msg->stream_name = NULL;
4887 smb_fname = synthetic_smb_fname(msg,
4893 if (smb_fname == NULL) {
4894 DBG_DEBUG("synthetic_smb_fname failed\n");
4898 fsp = file_find_dif(sconn, msg->id, msg->share_file_id);
4900 DBG_DEBUG("fsp not found\n");
4904 if (strcmp(fsp->conn->connectpath, msg->servicepath) == 0) {
4906 DBG_DEBUG("renaming file %s from %s -> %s\n",
4909 smb_fname_str_dbg(smb_fname));
4910 status = fsp_set_smb_fname(fsp, smb_fname);
4911 if (!NT_STATUS_IS_OK(status)) {
4912 DBG_DEBUG("fsp_set_smb_fname failed: %s\n",
4918 * Now we have the complete path we can work out if
4919 * this is actually within this share and adjust
4920 * newname accordingly.
4922 DBG_DEBUG("share mismatch (sharepath %s not sharepath %s) "
4923 "%s from %s -> %s\n",
4924 fsp->conn->connectpath,
4928 smb_fname_str_dbg(smb_fname));
4935 * If a main file is opened for delete, all streams need to be checked for
4936 * !FILE_SHARE_DELETE. Do this by opening with DELETE_ACCESS.
4937 * If that works, delete them all by setting the delete on close and close.
4940 static NTSTATUS open_streams_for_delete(connection_struct *conn,
4941 const struct smb_filename *smb_fname)
4943 struct stream_struct *stream_info = NULL;
4944 files_struct **streams = NULL;
4946 unsigned int i, num_streams = 0;
4947 TALLOC_CTX *frame = talloc_stackframe();
4948 const struct smb_filename *pathref = NULL;
4951 if (smb_fname->fsp == NULL) {
4952 struct smb_filename *tmp = NULL;
4953 status = synthetic_pathref(frame,
4955 smb_fname->base_name,
4961 if (!NT_STATUS_IS_OK(status)) {
4962 if (NT_STATUS_EQUAL(status, NT_STATUS_NOT_IMPLEMENTED)
4963 || NT_STATUS_EQUAL(status,
4964 NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
4965 DBG_DEBUG("no streams around\n");
4967 return NT_STATUS_OK;
4969 DBG_DEBUG("synthetic_pathref failed: %s\n",
4975 pathref = smb_fname;
4977 status = vfs_fstreaminfo(pathref->fsp, talloc_tos(),
4978 &num_streams, &stream_info);
4980 if (NT_STATUS_EQUAL(status, NT_STATUS_NOT_IMPLEMENTED)
4981 || NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
4982 DEBUG(10, ("no streams around\n"));
4984 return NT_STATUS_OK;
4987 if (!NT_STATUS_IS_OK(status)) {
4988 DEBUG(10, ("vfs_fstreaminfo failed: %s\n",
4989 nt_errstr(status)));
4993 DEBUG(10, ("open_streams_for_delete found %d streams\n",
4996 if (num_streams == 0) {
4998 return NT_STATUS_OK;
5001 streams = talloc_array(talloc_tos(), files_struct *, num_streams);
5002 if (streams == NULL) {
5003 DEBUG(0, ("talloc failed\n"));
5004 status = NT_STATUS_NO_MEMORY;
5008 for (i=0; i<num_streams; i++) {
5009 struct smb_filename *smb_fname_cp;
5011 if (strequal(stream_info[i].name, "::$DATA")) {
5016 smb_fname_cp = synthetic_smb_fname(talloc_tos(),
5017 smb_fname->base_name,
5018 stream_info[i].name,
5022 ~SMB_FILENAME_POSIX_PATH));
5023 if (smb_fname_cp == NULL) {
5024 status = NT_STATUS_NO_MEMORY;
5028 if (SMB_VFS_STAT(conn, smb_fname_cp) == -1) {
5029 DEBUG(10, ("Unable to stat stream: %s\n",
5030 smb_fname_str_dbg(smb_fname_cp)));
5033 status = openat_pathref_fsp(conn->cwd_fsp, smb_fname_cp);
5034 if (!NT_STATUS_IS_OK(status)) {
5035 DBG_DEBUG("Unable to open stream [%s]: %s\n",
5036 smb_fname_str_dbg(smb_fname_cp),
5038 TALLOC_FREE(smb_fname_cp);
5042 status = SMB_VFS_CREATE_FILE(
5045 smb_fname_cp, /* fname */
5046 DELETE_ACCESS, /* access_mask */
5047 (FILE_SHARE_READ | /* share_access */
5048 FILE_SHARE_WRITE | FILE_SHARE_DELETE),
5049 FILE_OPEN, /* create_disposition*/
5050 0, /* create_options */
5051 FILE_ATTRIBUTE_NORMAL, /* file_attributes */
5052 0, /* oplock_request */
5054 0, /* allocation_size */
5055 0, /* private_flags */
5058 &streams[i], /* result */
5060 NULL, NULL); /* create context */
5062 if (!NT_STATUS_IS_OK(status)) {
5063 DEBUG(10, ("Could not open stream %s: %s\n",
5064 smb_fname_str_dbg(smb_fname_cp),
5065 nt_errstr(status)));
5067 TALLOC_FREE(smb_fname_cp);
5070 TALLOC_FREE(smb_fname_cp);
5074 * don't touch the variable "status" beyond this point :-)
5077 for (j = i-1 ; j >= 0; j--) {
5078 if (streams[j] == NULL) {
5082 DEBUG(10, ("Closing stream # %d, %s\n", j,
5083 fsp_str_dbg(streams[j])));
5084 close_file(NULL, streams[j], NORMAL_CLOSE);
5092 /*********************************************************************
5093 Create a default ACL by inheriting from the parent. If no inheritance
5094 from the parent available, don't set anything. This will leave the actual
5095 permissions the new file or directory already got from the filesystem
5096 as the NT ACL when read.
5097 *********************************************************************/
5099 static NTSTATUS inherit_new_acl(files_struct *fsp)
5101 TALLOC_CTX *frame = talloc_stackframe();
5102 struct security_descriptor *parent_desc = NULL;
5103 NTSTATUS status = NT_STATUS_OK;
5104 struct security_descriptor *psd = NULL;
5105 const struct dom_sid *owner_sid = NULL;
5106 const struct dom_sid *group_sid = NULL;
5107 uint32_t security_info_sent = (SECINFO_OWNER | SECINFO_GROUP | SECINFO_DACL);
5108 struct security_token *token = fsp->conn->session_info->security_token;
5109 bool inherit_owner =
5110 (lp_inherit_owner(SNUM(fsp->conn)) == INHERIT_OWNER_WINDOWS_AND_UNIX);
5111 bool inheritable_components = false;
5112 bool try_builtin_administrators = false;
5113 const struct dom_sid *BA_U_sid = NULL;
5114 const struct dom_sid *BA_G_sid = NULL;
5115 bool try_system = false;
5116 const struct dom_sid *SY_U_sid = NULL;
5117 const struct dom_sid *SY_G_sid = NULL;
5119 struct smb_filename *parent_dir = NULL;
5122 status = SMB_VFS_PARENT_PATHNAME(fsp->conn,
5127 if (!NT_STATUS_IS_OK(status)) {
5132 status = SMB_VFS_GET_NT_ACL_AT(fsp->conn,
5135 (SECINFO_OWNER | SECINFO_GROUP | SECINFO_DACL),
5138 if (!NT_STATUS_IS_OK(status)) {
5143 inheritable_components = sd_has_inheritable_components(parent_desc,
5144 fsp->fsp_flags.is_directory);
5146 if (!inheritable_components && !inherit_owner) {
5148 /* Nothing to inherit and not setting owner. */
5149 return NT_STATUS_OK;
5152 /* Create an inherited descriptor from the parent. */
5154 if (DEBUGLEVEL >= 10) {
5155 DEBUG(10,("inherit_new_acl: parent acl for %s is:\n",
5156 fsp_str_dbg(fsp) ));
5157 NDR_PRINT_DEBUG(security_descriptor, parent_desc);
5160 /* Inherit from parent descriptor if "inherit owner" set. */
5161 if (inherit_owner) {
5162 owner_sid = parent_desc->owner_sid;
5163 group_sid = parent_desc->group_sid;
5166 if (owner_sid == NULL) {
5167 if (security_token_has_builtin_administrators(token)) {
5168 try_builtin_administrators = true;
5169 } else if (security_token_is_system(token)) {
5170 try_builtin_administrators = true;
5175 if (group_sid == NULL &&
5176 token->num_sids == PRIMARY_GROUP_SID_INDEX)
5178 if (security_token_is_system(token)) {
5179 try_builtin_administrators = true;
5184 if (try_builtin_administrators) {
5188 ok = sids_to_unixids(&global_sid_Builtin_Administrators, 1, &ids);
5192 BA_U_sid = &global_sid_Builtin_Administrators;
5193 BA_G_sid = &global_sid_Builtin_Administrators;
5196 BA_U_sid = &global_sid_Builtin_Administrators;
5199 BA_G_sid = &global_sid_Builtin_Administrators;
5211 ok = sids_to_unixids(&global_sid_System, 1, &ids);
5215 SY_U_sid = &global_sid_System;
5216 SY_G_sid = &global_sid_System;
5219 SY_U_sid = &global_sid_System;
5222 SY_G_sid = &global_sid_System;
5230 if (owner_sid == NULL) {
5231 owner_sid = BA_U_sid;
5234 if (owner_sid == NULL) {
5235 owner_sid = SY_U_sid;
5238 if (group_sid == NULL) {
5239 group_sid = SY_G_sid;
5242 if (try_system && group_sid == NULL) {
5243 group_sid = BA_G_sid;
5246 if (owner_sid == NULL) {
5247 owner_sid = &token->sids[PRIMARY_USER_SID_INDEX];
5249 if (group_sid == NULL) {
5250 if (token->num_sids == PRIMARY_GROUP_SID_INDEX) {
5251 group_sid = &token->sids[PRIMARY_USER_SID_INDEX];
5253 group_sid = &token->sids[PRIMARY_GROUP_SID_INDEX];
5257 status = se_create_child_secdesc(frame,
5263 fsp->fsp_flags.is_directory);
5264 if (!NT_STATUS_IS_OK(status)) {
5269 /* If inheritable_components == false,
5270 se_create_child_secdesc()
5271 creates a security descriptor with a NULL dacl
5272 entry, but with SEC_DESC_DACL_PRESENT. We need
5273 to remove that flag. */
5275 if (!inheritable_components) {
5276 security_info_sent &= ~SECINFO_DACL;
5277 psd->type &= ~SEC_DESC_DACL_PRESENT;
5280 if (DEBUGLEVEL >= 10) {
5281 DEBUG(10,("inherit_new_acl: child acl for %s is:\n",
5282 fsp_str_dbg(fsp) ));
5283 NDR_PRINT_DEBUG(security_descriptor, psd);
5286 if (inherit_owner) {
5287 /* We need to be root to force this. */
5290 status = SMB_VFS_FSET_NT_ACL(fsp,
5293 if (inherit_owner) {
5301 * If we already have a lease, it must match the new file id. [MS-SMB2]
5302 * 3.3.5.9.8 speaks about INVALID_PARAMETER if an already used lease key is
5303 * used for a different file name.
5306 struct lease_match_state {
5307 /* Input parameters. */
5308 TALLOC_CTX *mem_ctx;
5309 const char *servicepath;
5310 const struct smb_filename *fname;
5313 /* Return parameters. */
5314 uint32_t num_file_ids;
5315 struct file_id *ids;
5316 NTSTATUS match_status;
5319 /*************************************************************
5320 File doesn't exist but this lease key+guid is already in use.
5322 This is only allowable in the dynamic share case where the
5323 service path must be different.
5325 There is a small race condition here in the multi-connection
5326 case where a client sends two create calls on different connections,
5327 where the file doesn't exist and one smbd creates the leases_db
5328 entry first, but this will get fixed by the multichannel cleanup
5329 when all identical client_guids get handled by a single smbd.
5330 **************************************************************/
5332 static void lease_match_parser_new_file(
5334 const struct leases_db_file *files,
5335 struct lease_match_state *state)
5339 for (i = 0; i < num_files; i++) {
5340 const struct leases_db_file *f = &files[i];
5341 if (strequal(state->servicepath, f->servicepath)) {
5342 state->match_status = NT_STATUS_INVALID_PARAMETER;
5347 /* Dynamic share case. Break leases on all other files. */
5348 state->match_status = leases_db_copy_file_ids(state->mem_ctx,
5352 if (!NT_STATUS_IS_OK(state->match_status)) {
5356 state->num_file_ids = num_files;
5357 state->match_status = NT_STATUS_OPLOCK_NOT_GRANTED;
5361 static void lease_match_parser(
5363 const struct leases_db_file *files,
5366 struct lease_match_state *state =
5367 (struct lease_match_state *)private_data;
5370 if (!state->file_existed) {
5372 * Deal with name mismatch or
5373 * possible dynamic share case separately
5374 * to make code clearer.
5376 lease_match_parser_new_file(num_files,
5383 state->match_status = NT_STATUS_OK;
5385 for (i = 0; i < num_files; i++) {
5386 const struct leases_db_file *f = &files[i];
5388 /* Everything should be the same. */
5389 if (!file_id_equal(&state->id, &f->id)) {
5390 /* This should catch all dynamic share cases. */
5391 state->match_status = NT_STATUS_OPLOCK_NOT_GRANTED;
5394 if (!strequal(f->servicepath, state->servicepath)) {
5395 state->match_status = NT_STATUS_INVALID_PARAMETER;
5398 if (!strequal(f->base_name, state->fname->base_name)) {
5399 state->match_status = NT_STATUS_INVALID_PARAMETER;
5402 if (!strequal(f->stream_name, state->fname->stream_name)) {
5403 state->match_status = NT_STATUS_INVALID_PARAMETER;
5408 if (NT_STATUS_IS_OK(state->match_status)) {
5410 * Common case - just opening another handle on a
5411 * file on a non-dynamic share.
5416 if (NT_STATUS_EQUAL(state->match_status, NT_STATUS_INVALID_PARAMETER)) {
5417 /* Mismatched path. Error back to client. */
5422 * File id mismatch. Dynamic share case NT_STATUS_OPLOCK_NOT_GRANTED.
5423 * Don't allow leases.
5426 state->match_status = leases_db_copy_file_ids(state->mem_ctx,
5430 if (!NT_STATUS_IS_OK(state->match_status)) {
5434 state->num_file_ids = num_files;
5435 state->match_status = NT_STATUS_OPLOCK_NOT_GRANTED;
5439 struct lease_match_break_state {
5440 struct messaging_context *msg_ctx;
5441 const struct smb2_lease_key *lease_key;
5449 static bool lease_match_break_fn(
5450 struct share_mode_entry *e,
5453 struct lease_match_break_state *state = private_data;
5455 uint32_t e_lease_type;
5458 stale = share_entry_stale_pid(e);
5463 equal = smb2_lease_key_equal(&e->lease_key, state->lease_key);
5468 status = leases_db_get(
5472 NULL, /* current_state */
5473 NULL, /* breaking */
5474 NULL, /* breaking_to_requested */
5475 NULL, /* breaking_to_required */
5476 &state->version, /* lease_version */
5477 &state->epoch); /* epoch */
5478 if (NT_STATUS_IS_OK(status)) {
5479 state->found_lease = true;
5481 DBG_WARNING("Could not find version/epoch: %s\n",
5485 e_lease_type = get_lease_type(e, state->id);
5486 if (e_lease_type == SMB2_LEASE_NONE) {
5489 send_break_message(state->msg_ctx, &state->id, e, SMB2_LEASE_NONE);
5492 * Windows 7 and 8 lease clients are broken in that they will
5493 * not respond to lease break requests whilst waiting for an
5494 * outstanding open request on that lease handle on the same
5495 * TCP connection, due to holding an internal inode lock.
5497 * This means we can't reschedule ourselves here, but must
5498 * return from the create.
5502 * Send the breaks and then return SMB2_LEASE_NONE in the
5503 * lease handle to cause them to acknowledge the lease
5504 * break. Consultation with Microsoft engineering confirmed
5505 * this approach is safe.
5511 static NTSTATUS lease_match(connection_struct *conn,
5512 struct smb_request *req,
5513 const struct smb2_lease_key *lease_key,
5514 const char *servicepath,
5515 const struct smb_filename *fname,
5516 uint16_t *p_version,
5519 struct smbd_server_connection *sconn = req->sconn;
5520 TALLOC_CTX *tos = talloc_tos();
5521 struct lease_match_state state = {
5523 .servicepath = servicepath,
5525 .match_status = NT_STATUS_OK
5530 state.file_existed = VALID_STAT(fname->st);
5531 if (state.file_existed) {
5532 state.id = vfs_file_id_from_sbuf(conn, &fname->st);
5535 status = leases_db_parse(&sconn->client->global->client_guid,
5536 lease_key, lease_match_parser, &state);
5537 if (!NT_STATUS_IS_OK(status)) {
5539 * Not found or error means okay: We can make the lease pass
5541 return NT_STATUS_OK;
5543 if (!NT_STATUS_EQUAL(state.match_status, NT_STATUS_OPLOCK_NOT_GRANTED)) {
5545 * Anything but NT_STATUS_OPLOCK_NOT_GRANTED, let the caller
5548 return state.match_status;
5551 /* We have to break all existing leases. */
5552 for (i = 0; i < state.num_file_ids; i++) {
5553 struct lease_match_break_state break_state = {
5554 .msg_ctx = conn->sconn->msg_ctx,
5555 .lease_key = lease_key,
5557 struct share_mode_lock *lck;
5560 if (file_id_equal(&state.ids[i], &state.id)) {
5561 /* Don't need to break our own file. */
5565 break_state.id = state.ids[i];
5567 lck = get_existing_share_mode_lock(
5568 talloc_tos(), break_state.id);
5570 /* Race condition - file already closed. */
5574 ok = share_mode_forall_leases(
5575 lck, lease_match_break_fn, &break_state);
5577 DBG_DEBUG("share_mode_forall_leases failed\n");
5583 if (break_state.found_lease) {
5584 *p_version = break_state.version;
5585 *p_epoch = break_state.epoch;
5589 * Ensure we don't grant anything more so we
5592 return NT_STATUS_OPLOCK_NOT_GRANTED;
5596 * Wrapper around open_file_ntcreate and open_directory
5599 static NTSTATUS create_file_unixpath(connection_struct *conn,
5600 struct smb_request *req,
5601 struct smb_filename *smb_fname,
5602 uint32_t access_mask,
5603 uint32_t share_access,
5604 uint32_t create_disposition,
5605 uint32_t create_options,
5606 uint32_t file_attributes,
5607 uint32_t oplock_request,
5608 const struct smb2_lease *lease,
5609 uint64_t allocation_size,
5610 uint32_t private_flags,
5611 struct security_descriptor *sd,
5612 struct ea_list *ea_list,
5614 files_struct **result,
5617 struct smb2_lease none_lease;
5618 int info = FILE_WAS_OPENED;
5619 files_struct *base_fsp = NULL;
5620 files_struct *fsp = NULL;
5624 DBG_DEBUG("create_file_unixpath: access_mask = 0x%x "
5625 "file_attributes = 0x%x, share_access = 0x%x, "
5626 "create_disposition = 0x%x create_options = 0x%x "
5627 "oplock_request = 0x%x private_flags = 0x%x "
5628 "ea_list = %p, sd = %p, "
5630 (unsigned int)access_mask,
5631 (unsigned int)file_attributes,
5632 (unsigned int)share_access,
5633 (unsigned int)create_disposition,
5634 (unsigned int)create_options,
5635 (unsigned int)oplock_request,
5636 (unsigned int)private_flags,
5637 ea_list, sd, smb_fname_str_dbg(smb_fname));
5639 if (create_options & FILE_OPEN_BY_FILE_ID) {
5640 status = NT_STATUS_NOT_SUPPORTED;
5644 if (create_options & NTCREATEX_OPTIONS_INVALID_PARAM_MASK) {
5645 status = NT_STATUS_INVALID_PARAMETER;
5650 oplock_request |= INTERNAL_OPEN_ONLY;
5653 if (lease != NULL) {
5654 uint16_t epoch = lease->lease_epoch;
5655 uint16_t version = lease->lease_version;
5658 DBG_WARNING("Got lease on internal open\n");
5659 status = NT_STATUS_INTERNAL_ERROR;
5663 status = lease_match(conn,
5670 if (NT_STATUS_EQUAL(status, NT_STATUS_OPLOCK_NOT_GRANTED)) {
5671 /* Dynamic share file. No leases and update epoch... */
5672 none_lease = *lease;
5673 none_lease.lease_state = SMB2_LEASE_NONE;
5674 none_lease.lease_epoch = epoch;
5675 none_lease.lease_version = version;
5676 lease = &none_lease;
5677 } else if (!NT_STATUS_IS_OK(status)) {
5682 if ((conn->fs_capabilities & FILE_NAMED_STREAMS)
5683 && (access_mask & DELETE_ACCESS)
5684 && !is_ntfs_stream_smb_fname(smb_fname)) {
5686 * We can't open a file with DELETE access if any of the
5687 * streams is open without FILE_SHARE_DELETE
5689 status = open_streams_for_delete(conn, smb_fname);
5691 if (!NT_STATUS_IS_OK(status)) {
5696 if (access_mask & SEC_FLAG_SYSTEM_SECURITY) {
5699 ok = security_token_has_privilege(get_current_nttok(conn),
5702 DBG_DEBUG("open on %s failed - "
5703 "SEC_FLAG_SYSTEM_SECURITY denied.\n",
5704 smb_fname_str_dbg(smb_fname));
5705 status = NT_STATUS_PRIVILEGE_NOT_HELD;
5709 if (conn->sconn->using_smb2 &&
5710 (access_mask == SEC_FLAG_SYSTEM_SECURITY))
5713 * No other bits set. Windows SMB2 refuses this.
5714 * See smbtorture3 SMB2-SACL test.
5716 * Note this is an SMB2-only behavior,
5717 * smbtorture3 SMB1-SYSTEM-SECURITY already tests
5718 * that SMB1 allows this.
5720 status = NT_STATUS_ACCESS_DENIED;
5726 * Files or directories can't be opened DELETE_ON_CLOSE without
5728 * BUG: https://bugzilla.samba.org/show_bug.cgi?id=13358
5730 if (create_options & FILE_DELETE_ON_CLOSE) {
5731 if ((access_mask & DELETE_ACCESS) == 0) {
5732 status = NT_STATUS_INVALID_PARAMETER;
5737 if ((conn->fs_capabilities & FILE_NAMED_STREAMS)
5738 && is_ntfs_stream_smb_fname(smb_fname))
5740 uint32_t base_create_disposition;
5741 struct smb_filename *smb_fname_base = NULL;
5742 uint32_t base_privflags;
5744 if (create_options & FILE_DIRECTORY_FILE) {
5745 status = NT_STATUS_NOT_A_DIRECTORY;
5749 switch (create_disposition) {
5751 base_create_disposition = FILE_OPEN;
5754 base_create_disposition = FILE_OPEN_IF;
5758 /* Create an smb_filename with stream_name == NULL. */
5759 smb_fname_base = synthetic_smb_fname(talloc_tos(),
5760 smb_fname->base_name,
5765 if (smb_fname_base == NULL) {
5766 status = NT_STATUS_NO_MEMORY;
5771 * We may be creating the basefile as part of creating the
5772 * stream, so it's legal if the basefile doesn't exist at this
5773 * point, the create_file_unixpath() below will create it. But
5774 * if the basefile exists we want a handle so we can fstat() it.
5777 ret = vfs_stat(conn, smb_fname_base);
5778 if (ret == -1 && errno != ENOENT) {
5779 status = map_nt_error_from_unix(errno);
5780 TALLOC_FREE(smb_fname_base);
5784 status = openat_pathref_fsp(conn->cwd_fsp,
5786 if (!NT_STATUS_IS_OK(status)) {
5787 DBG_ERR("open_smb_fname_fsp [%s] failed: %s\n",
5788 smb_fname_str_dbg(smb_fname_base),
5790 TALLOC_FREE(smb_fname_base);
5795 * https://bugzilla.samba.org/show_bug.cgi?id=10229
5796 * We need to check if the requested access mask
5797 * could be used to open the underlying file (if
5798 * it existed), as we're passing in zero for the
5799 * access mask to the base filename.
5801 status = check_base_file_access(conn,
5805 if (!NT_STATUS_IS_OK(status)) {
5806 DEBUG(10, ("Permission check "
5807 "for base %s failed: "
5808 "%s\n", smb_fname->base_name,
5809 nt_errstr(status)));
5810 TALLOC_FREE(smb_fname_base);
5815 base_privflags = NTCREATEX_FLAG_STREAM_BASEOPEN;
5817 /* Open the base file. */
5818 status = create_file_unixpath(conn,
5824 | FILE_SHARE_DELETE,
5825 base_create_disposition,
5836 TALLOC_FREE(smb_fname_base);
5838 if (!NT_STATUS_IS_OK(status)) {
5839 DEBUG(10, ("create_file_unixpath for base %s failed: "
5840 "%s\n", smb_fname->base_name,
5841 nt_errstr(status)));
5847 * Now either reuse smb_fname->fsp or allocate a new fsp if
5848 * smb_fname->fsp is NULL. The latter will be the case when processing a
5849 * request to create a file that doesn't exist.
5851 if (smb_fname->fsp != NULL) {
5852 bool need_fsp_unlink = true;
5855 * This is really subtle. If someone passes in an smb_fname
5856 * where smb_fname actually is taken from fsp->fsp_name, then
5857 * the lifetime of these objects is meant to be the same.
5859 * This is commonly the case from an SMB1 path-based call,
5860 * (call_trans2qfilepathinfo) where we use the pathref fsp
5861 * (smb_fname->fsp) as the handle. In this case we must not
5862 * unlink smb_fname->fsp from it's owner.
5864 * The asserts below:
5866 * SMB_ASSERT(fsp->fsp_name->fsp != NULL);
5867 * SMB_ASSERT(fsp->fsp_name->fsp == fsp);
5869 * ensure the required invarients are met.
5871 if (smb_fname->fsp->fsp_name == smb_fname) {
5872 need_fsp_unlink = false;
5875 fsp = smb_fname->fsp;
5877 if (need_fsp_unlink) {
5879 * Unlink the fsp from the smb_fname so the fsp is not
5880 * autoclosed by the smb_fname pathref fsp talloc
5883 smb_fname_fsp_unlink(smb_fname);
5886 status = fsp_bind_smb(fsp, req);
5887 if (!NT_STATUS_IS_OK(status)) {
5891 if (fsp->base_fsp != NULL) {
5892 struct files_struct *tmp_base_fsp = fsp->base_fsp;
5894 fsp_set_base_fsp(fsp, NULL);
5896 fd_close(tmp_base_fsp);
5897 file_free(NULL, tmp_base_fsp);
5903 status = file_new(req, conn, &fsp);
5904 if(!NT_STATUS_IS_OK(status)) {
5908 status = fsp_set_smb_fname(fsp, smb_fname);
5909 if (!NT_STATUS_IS_OK(status)) {
5914 SMB_ASSERT(fsp->fsp_name->fsp != NULL);
5915 SMB_ASSERT(fsp->fsp_name->fsp == fsp);
5919 * We're opening the stream element of a
5920 * base_fsp we already opened. Set up the
5923 fsp_set_base_fsp(fsp, base_fsp);
5927 * If it's a request for a directory open, deal with it separately.
5930 if (create_options & FILE_DIRECTORY_FILE) {
5932 if (create_options & FILE_NON_DIRECTORY_FILE) {
5933 status = NT_STATUS_INVALID_PARAMETER;
5937 /* Can't open a temp directory. IFS kit test. */
5938 if (!(file_attributes & FILE_FLAG_POSIX_SEMANTICS) &&
5939 (file_attributes & FILE_ATTRIBUTE_TEMPORARY)) {
5940 status = NT_STATUS_INVALID_PARAMETER;
5945 * We will get a create directory here if the Win32
5946 * app specified a security descriptor in the
5947 * CreateDirectory() call.
5951 status = open_directory(conn,
5963 * Ordinary file case.
5966 if (allocation_size) {
5967 fsp->initial_allocation_size = smb_roundup(fsp->conn,
5971 status = open_file_ntcreate(conn,
5983 if (NT_STATUS_EQUAL(status, NT_STATUS_FILE_IS_A_DIRECTORY)) {
5985 /* A stream open never opens a directory */
5988 status = NT_STATUS_FILE_IS_A_DIRECTORY;
5993 * Fail the open if it was explicitly a non-directory
5997 if (create_options & FILE_NON_DIRECTORY_FILE) {
5998 status = NT_STATUS_FILE_IS_A_DIRECTORY;
6003 status = open_directory(conn,
6015 if (!NT_STATUS_IS_OK(status)) {
6019 fsp->fsp_flags.is_fsa = true;
6021 if ((ea_list != NULL) &&
6022 ((info == FILE_WAS_CREATED) || (info == FILE_WAS_OVERWRITTEN))) {
6023 status = set_ea(conn, fsp, ea_list);
6024 if (!NT_STATUS_IS_OK(status)) {
6029 if (!fsp->fsp_flags.is_directory &&
6030 S_ISDIR(fsp->fsp_name->st.st_ex_mode))
6032 status = NT_STATUS_ACCESS_DENIED;
6036 /* Save the requested allocation size. */
6037 if ((info == FILE_WAS_CREATED) || (info == FILE_WAS_OVERWRITTEN)) {
6038 if ((allocation_size > (uint64_t)fsp->fsp_name->st.st_ex_size)
6039 && !(fsp->fsp_flags.is_directory))
6041 fsp->initial_allocation_size = smb_roundup(
6042 fsp->conn, allocation_size);
6043 if (vfs_allocate_file_space(
6044 fsp, fsp->initial_allocation_size) == -1) {
6045 status = NT_STATUS_DISK_FULL;
6049 fsp->initial_allocation_size = smb_roundup(
6050 fsp->conn, (uint64_t)fsp->fsp_name->st.st_ex_size);
6053 fsp->initial_allocation_size = 0;
6056 if ((info == FILE_WAS_CREATED) && lp_nt_acl_support(SNUM(conn)) &&
6057 fsp->base_fsp == NULL) {
6060 * According to the MS documentation, the only time the security
6061 * descriptor is applied to the opened file is iff we *created* the
6062 * file; an existing file stays the same.
6064 * Also, it seems (from observation) that you can open the file with
6065 * any access mask but you can still write the sd. We need to override
6066 * the granted access before we call set_sd
6067 * Patch for bug #2242 from Tom Lackemann <cessnatomny@yahoo.com>.
6070 uint32_t sec_info_sent;
6071 uint32_t saved_access_mask = fsp->access_mask;
6073 sec_info_sent = get_sec_info(sd);
6075 fsp->access_mask = FILE_GENERIC_ALL;
6077 if (sec_info_sent & (SECINFO_OWNER|
6081 status = set_sd(fsp, sd, sec_info_sent);
6084 fsp->access_mask = saved_access_mask;
6086 if (!NT_STATUS_IS_OK(status)) {
6089 } else if (lp_inherit_acls(SNUM(conn))) {
6090 /* Inherit from parent. Errors here are not fatal. */
6091 status = inherit_new_acl(fsp);
6092 if (!NT_STATUS_IS_OK(status)) {
6093 DEBUG(10,("inherit_new_acl: failed for %s with %s\n",
6095 nt_errstr(status) ));
6100 if ((conn->fs_capabilities & FILE_FILE_COMPRESSION)
6101 && (create_options & FILE_NO_COMPRESSION)
6102 && (info == FILE_WAS_CREATED)) {
6103 status = SMB_VFS_SET_COMPRESSION(conn, fsp, fsp,
6104 COMPRESSION_FORMAT_NONE);
6105 if (!NT_STATUS_IS_OK(status)) {
6106 DEBUG(1, ("failed to disable compression: %s\n",
6107 nt_errstr(status)));
6111 DEBUG(10, ("create_file_unixpath: info=%d\n", info));
6114 if (pinfo != NULL) {
6118 smb_fname->st = fsp->fsp_name->st;
6120 return NT_STATUS_OK;
6123 DEBUG(10, ("create_file_unixpath: %s\n", nt_errstr(status)));
6127 * The close_file below will close
6131 close_file(req, fsp, ERROR_CLOSE);
6134 if (base_fsp != NULL) {
6135 close_file(req, base_fsp, ERROR_CLOSE);
6141 NTSTATUS create_file_default(connection_struct *conn,
6142 struct smb_request *req,
6143 struct smb_filename *smb_fname,
6144 uint32_t access_mask,
6145 uint32_t share_access,
6146 uint32_t create_disposition,
6147 uint32_t create_options,
6148 uint32_t file_attributes,
6149 uint32_t oplock_request,
6150 const struct smb2_lease *lease,
6151 uint64_t allocation_size,
6152 uint32_t private_flags,
6153 struct security_descriptor *sd,
6154 struct ea_list *ea_list,
6155 files_struct **result,
6157 const struct smb2_create_blobs *in_context_blobs,
6158 struct smb2_create_blobs *out_context_blobs)
6160 int info = FILE_WAS_OPENED;
6161 files_struct *fsp = NULL;
6163 bool stream_name = false;
6164 struct smb2_create_blob *posx = NULL;
6166 DBG_DEBUG("create_file: access_mask = 0x%x "
6167 "file_attributes = 0x%x, share_access = 0x%x, "
6168 "create_disposition = 0x%x create_options = 0x%x "
6169 "oplock_request = 0x%x "
6170 "private_flags = 0x%x "
6171 "ea_list = %p, sd = %p, "
6173 (unsigned int)access_mask,
6174 (unsigned int)file_attributes,
6175 (unsigned int)share_access,
6176 (unsigned int)create_disposition,
6177 (unsigned int)create_options,
6178 (unsigned int)oplock_request,
6179 (unsigned int)private_flags,
6182 smb_fname_str_dbg(smb_fname));
6186 * Remember the absolute time of the original request
6187 * with this mid. We'll use it later to see if this
6190 get_deferred_open_message_state(req, &req->request_time, NULL);
6194 * Check to see if this is a mac fork of some kind.
6197 stream_name = is_ntfs_stream_smb_fname(smb_fname);
6199 enum FAKE_FILE_TYPE fake_file_type;
6201 fake_file_type = is_fake_file(smb_fname);
6203 if (req != NULL && fake_file_type != FAKE_FILE_TYPE_NONE) {
6206 * Here we go! support for changing the disk quotas
6209 * We need to fake up to open this MAGIC QUOTA file
6210 * and return a valid FID.
6212 * w2k close this file directly after openening xp
6213 * also tries a QUERY_FILE_INFO on the file and then
6216 status = open_fake_file(req, conn, req->vuid,
6217 fake_file_type, smb_fname,
6219 if (!NT_STATUS_IS_OK(status)) {
6223 ZERO_STRUCT(smb_fname->st);
6227 if (!(conn->fs_capabilities & FILE_NAMED_STREAMS)) {
6228 status = NT_STATUS_OBJECT_NAME_NOT_FOUND;
6233 if (is_ntfs_default_stream_smb_fname(smb_fname)) {
6235 smb_fname->stream_name = NULL;
6236 /* We have to handle this error here. */
6237 if (create_options & FILE_DIRECTORY_FILE) {
6238 status = NT_STATUS_NOT_A_DIRECTORY;
6241 ret = vfs_stat(conn, smb_fname);
6242 if (ret == 0 && VALID_STAT_OF_DIR(smb_fname->st)) {
6243 status = NT_STATUS_FILE_IS_A_DIRECTORY;
6248 posx = smb2_create_blob_find(
6249 in_context_blobs, SMB2_CREATE_TAG_POSIX);
6251 uint32_t wire_mode_bits = 0;
6252 mode_t mode_bits = 0;
6253 SMB_STRUCT_STAT sbuf = { 0 };
6254 enum perm_type ptype =
6255 (create_options & FILE_DIRECTORY_FILE) ?
6256 PERM_NEW_DIR : PERM_NEW_FILE;
6258 if (posx->data.length != 4) {
6259 status = NT_STATUS_INVALID_PARAMETER;
6263 wire_mode_bits = IVAL(posx->data.data, 0);
6264 status = unix_perms_from_wire(
6265 conn, &sbuf, wire_mode_bits, ptype, &mode_bits);
6266 if (!NT_STATUS_IS_OK(status)) {
6270 * Remove type info from mode, leaving only the
6271 * permissions and setuid/gid bits.
6273 mode_bits &= ~S_IFMT;
6275 file_attributes = (FILE_FLAG_POSIX_SEMANTICS | mode_bits);
6278 status = create_file_unixpath(conn,
6294 if (!NT_STATUS_IS_OK(status)) {
6299 DEBUG(10, ("create_file: info=%d\n", info));
6302 if (pinfo != NULL) {
6305 return NT_STATUS_OK;
6308 DEBUG(10, ("create_file: %s\n", nt_errstr(status)));
6311 close_file(req, fsp, ERROR_CLOSE);