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 "system/filesys.h"
25 #include "lib/util/server_id.h"
27 #include "locking/share_mode_lock.h"
28 #include "smbd/smbd.h"
29 #include "smbd/globals.h"
30 #include "fake_file.h"
31 #include "../libcli/security/security.h"
32 #include "../librpc/gen_ndr/ndr_security.h"
33 #include "../librpc/gen_ndr/ndr_open_files.h"
34 #include "../librpc/gen_ndr/idmap.h"
35 #include "../librpc/gen_ndr/ioctl.h"
36 #include "passdb/lookup_sid.h"
40 #include "source3/lib/dbwrap/dbwrap_watch.h"
41 #include "locking/leases_db.h"
42 #include "librpc/gen_ndr/ndr_leases_db.h"
43 #include "lib/util/time_basic.h"
44 #include "source3/smbd/dir.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 struct files_struct *dirfsp,
80 const struct smb_filename *smb_fname,
82 uint32_t rejected_mask)
84 if ((access_mask & DELETE_ACCESS) &&
85 (rejected_mask & DELETE_ACCESS) &&
86 can_delete_file_in_directory(conn,
95 /****************************************************************************
96 Check if we have open rights.
97 ****************************************************************************/
99 static NTSTATUS smbd_check_access_rights_fname(
100 struct connection_struct *conn,
101 const struct smb_filename *smb_fname,
103 uint32_t access_mask,
104 uint32_t do_not_check_mask)
106 uint32_t rejected_share_access;
107 uint32_t effective_access;
109 rejected_share_access = access_mask & ~(conn->share_access);
111 if (rejected_share_access) {
112 DBG_DEBUG("rejected share access 0x%"PRIx32" on "
113 "%s (0x%"PRIx32")\n",
115 smb_fname_str_dbg(smb_fname),
116 rejected_share_access);
117 return NT_STATUS_ACCESS_DENIED;
120 effective_access = access_mask & ~do_not_check_mask;
121 if (effective_access == 0) {
122 DBG_DEBUG("do_not_check_mask override on %s. Granting 0x%x for free.\n",
123 smb_fname_str_dbg(smb_fname),
124 (unsigned int)access_mask);
128 if (!use_privs && get_current_uid(conn) == (uid_t)0) {
129 /* I'm sorry sir, I didn't know you were root... */
130 DBG_DEBUG("root override on %s. Granting 0x%x\n",
131 smb_fname_str_dbg(smb_fname),
132 (unsigned int)access_mask);
136 if ((access_mask & DELETE_ACCESS) &&
137 !lp_acl_check_permissions(SNUM(conn)))
139 DBG_DEBUG("Not checking ACL on DELETE_ACCESS on file %s. "
140 "Granting 0x%"PRIx32"\n",
141 smb_fname_str_dbg(smb_fname),
146 if (access_mask == DELETE_ACCESS &&
147 VALID_STAT(smb_fname->st) &&
148 S_ISLNK(smb_fname->st.st_ex_mode))
150 /* We can always delete a symlink. */
151 DBG_DEBUG("Not checking ACL on DELETE_ACCESS on symlink %s.\n",
152 smb_fname_str_dbg(smb_fname));
156 return NT_STATUS_MORE_PROCESSING_REQUIRED;
159 static NTSTATUS smbd_check_access_rights_sd(
160 struct connection_struct *conn,
161 struct files_struct *dirfsp,
162 const struct smb_filename *smb_fname,
163 struct security_descriptor *sd,
165 uint32_t access_mask,
166 uint32_t do_not_check_mask)
168 uint32_t rejected_mask = access_mask;
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%"PRIx32"] "
182 "returning [0x%"PRIx32"] (%s)\n",
183 smb_fname_str_dbg(smb_fname),
188 if (!NT_STATUS_IS_OK(status)) {
189 if (DEBUGLEVEL >= 10) {
190 DBG_DEBUG("acl for %s is:\n",
191 smb_fname_str_dbg(smb_fname));
192 NDR_PRINT_DEBUG(security_descriptor, sd);
198 if (NT_STATUS_IS_OK(status) ||
199 !NT_STATUS_EQUAL(status, NT_STATUS_ACCESS_DENIED))
204 /* Here we know status == NT_STATUS_ACCESS_DENIED. */
208 if ((access_mask & FILE_WRITE_ATTRIBUTES) &&
209 (rejected_mask & FILE_WRITE_ATTRIBUTES) &&
210 !lp_store_dos_attributes(SNUM(conn)) &&
211 (lp_map_readonly(SNUM(conn)) ||
212 lp_map_archive(SNUM(conn)) ||
213 lp_map_hidden(SNUM(conn)) ||
214 lp_map_system(SNUM(conn))))
216 rejected_mask &= ~FILE_WRITE_ATTRIBUTES;
218 DBG_DEBUG("overrode FILE_WRITE_ATTRIBUTES on file %s\n",
219 smb_fname_str_dbg(smb_fname));
222 if (parent_override_delete(conn,
229 * Were we trying to do an open for delete and didn't get DELETE
230 * access. Check if the directory allows DELETE_CHILD.
232 * http://blogs.msdn.com/oldnewthing/archive/2004/06/04/148426.aspx
236 rejected_mask &= ~DELETE_ACCESS;
238 DBG_DEBUG("Overrode DELETE_ACCESS on file %s\n",
239 smb_fname_str_dbg(smb_fname));
242 if (rejected_mask != 0) {
243 return NT_STATUS_ACCESS_DENIED;
248 NTSTATUS smbd_check_access_rights_fsp(struct files_struct *dirfsp,
249 struct files_struct *fsp,
251 uint32_t access_mask)
253 struct security_descriptor *sd = NULL;
254 uint32_t do_not_check_mask = 0;
257 /* Cope with fake/printer fsp's. */
258 if (fsp->fake_file_handle != NULL || fsp->print_file != NULL) {
259 if ((fsp->access_mask & access_mask) != access_mask) {
260 return NT_STATUS_ACCESS_DENIED;
265 if (fsp_get_pathref_fd(fsp) == -1) {
267 * This is a POSIX open on a symlink. For the pathname
268 * version of this function we used to return the st_mode
269 * bits turned into an NT ACL. For a symlink the mode bits
270 * are always rwxrwxrwx which means the pathname version always
271 * returned NT_STATUS_OK for a symlink. For the handle reference
272 * to a symlink use the handle access bits.
274 if ((fsp->access_mask & access_mask) != access_mask) {
275 return NT_STATUS_ACCESS_DENIED;
281 * If we can access the path to this file, by
282 * default we have FILE_READ_ATTRIBUTES from the
283 * containing directory. See the section:
284 * "Algorithm to Check Access to an Existing File"
287 * se_file_access_check() also takes care of
288 * owner WRITE_DAC and READ_CONTROL.
290 do_not_check_mask = FILE_READ_ATTRIBUTES;
293 * Samba 3.6 and earlier granted execute access even
294 * if the ACL did not contain execute rights.
295 * Samba 4.0 is more correct and checks it.
296 * The compatibility mode allows one to skip this check
297 * to smoothen upgrades.
299 if (lp_acl_allow_execute_always(SNUM(fsp->conn))) {
300 do_not_check_mask |= FILE_EXECUTE;
303 status = smbd_check_access_rights_fname(fsp->conn,
308 if (!NT_STATUS_EQUAL(status, NT_STATUS_MORE_PROCESSING_REQUIRED)) {
312 status = SMB_VFS_FGET_NT_ACL(metadata_fsp(fsp),
318 if (!NT_STATUS_IS_OK(status)) {
319 DBG_DEBUG("Could not get acl on %s: %s\n",
325 return smbd_check_access_rights_sd(fsp->conn,
335 * Given an fsp that represents a parent directory,
336 * check if the requested access can be granted.
338 NTSTATUS check_parent_access_fsp(struct files_struct *fsp,
339 uint32_t access_mask)
342 struct security_descriptor *parent_sd = NULL;
343 uint32_t access_granted = 0;
344 struct share_mode_lock *lck = NULL;
346 bool delete_on_close_set;
347 TALLOC_CTX *frame = talloc_stackframe();
349 if (get_current_uid(fsp->conn) == (uid_t)0) {
350 /* I'm sorry sir, I didn't know you were root... */
351 DBG_DEBUG("root override on %s. Granting 0x%x\n",
353 (unsigned int)access_mask);
354 status = NT_STATUS_OK;
358 status = SMB_VFS_FGET_NT_ACL(fsp,
363 if (!NT_STATUS_IS_OK(status)) {
364 DBG_INFO("SMB_VFS_FGET_NT_ACL failed for "
365 "%s with error %s\n",
372 * If we can access the path to this file, by
373 * default we have FILE_READ_ATTRIBUTES from the
374 * containing directory. See the section:
375 * "Algorithm to Check Access to an Existing File"
378 * se_file_access_check() also takes care of
379 * owner WRITE_DAC and READ_CONTROL.
381 status = se_file_access_check(parent_sd,
382 get_current_nttok(fsp->conn),
384 (access_mask & ~FILE_READ_ATTRIBUTES),
386 if(!NT_STATUS_IS_OK(status)) {
387 DBG_INFO("access check "
388 "on directory %s for mask 0x%x returned (0x%x) %s\n",
396 if (!(access_mask & (SEC_DIR_ADD_FILE | SEC_DIR_ADD_SUBDIR))) {
397 status = NT_STATUS_OK;
400 if (!lp_check_parent_directory_delete_on_close(SNUM(fsp->conn))) {
401 status = NT_STATUS_OK;
405 /* Check if the directory has delete-on-close set */
406 status = file_name_hash(fsp->conn,
407 fsp->fsp_name->base_name,
409 if (!NT_STATUS_IS_OK(status)) {
414 * Don't take a lock here. We just need a snapshot
415 * of the current state of delete on close and this is
416 * called in a codepath where we may already have a lock
417 * (and we explicitly can't hold 2 locks at the same time
418 * as that may deadlock).
420 lck = fetch_share_mode_unlocked(frame, fsp->file_id);
422 status = NT_STATUS_OK;
426 delete_on_close_set = is_delete_on_close_set(lck, name_hash);
427 if (delete_on_close_set) {
428 status = NT_STATUS_DELETE_PENDING;
432 status = NT_STATUS_OK;
439 /****************************************************************************
440 Ensure when opening a base file for a stream open that we have permissions
441 to do so given the access mask on the base file.
442 ****************************************************************************/
444 static NTSTATUS check_base_file_access(struct files_struct *fsp,
445 uint32_t access_mask)
449 status = smbd_calculate_access_mask_fsp(fsp->conn->cwd_fsp,
454 if (!NT_STATUS_IS_OK(status)) {
455 DEBUG(10, ("smbd_calculate_access_mask "
456 "on file %s returned %s\n",
462 if (access_mask & (FILE_WRITE_DATA|FILE_APPEND_DATA)) {
464 if (!CAN_WRITE(fsp->conn)) {
465 return NT_STATUS_ACCESS_DENIED;
467 dosattrs = fdos_mode(fsp);
468 if (dosattrs & FILE_ATTRIBUTE_READONLY) {
469 return NT_STATUS_ACCESS_DENIED;
473 return smbd_check_access_rights_fsp(fsp->conn->cwd_fsp,
479 static NTSTATUS chdir_below_conn(
481 connection_struct *conn,
482 const char *connectpath,
483 size_t connectpath_len,
484 struct smb_filename *dir_fname,
485 struct smb_filename **_oldwd_fname)
487 struct smb_filename *oldwd_fname = NULL;
488 struct smb_filename *smb_fname_dot = NULL;
489 struct smb_filename *real_fname = NULL;
490 const char *relative = NULL;
495 if (!ISDOT(dir_fname->base_name)) {
497 oldwd_fname = vfs_GetWd(talloc_tos(), conn);
498 if (oldwd_fname == NULL) {
499 status = map_nt_error_from_unix(errno);
503 /* Pin parent directory in place. */
504 ret = vfs_ChDir(conn, dir_fname);
506 status = map_nt_error_from_unix(errno);
507 DBG_DEBUG("chdir to %s failed: %s\n",
508 dir_fname->base_name,
514 smb_fname_dot = synthetic_smb_fname(
521 if (smb_fname_dot == NULL) {
522 status = NT_STATUS_NO_MEMORY;
526 real_fname = SMB_VFS_REALPATH(conn, talloc_tos(), smb_fname_dot);
527 if (real_fname == NULL) {
528 status = map_nt_error_from_unix(errno);
529 DBG_DEBUG("realpath in %s failed: %s\n",
530 dir_fname->base_name,
534 TALLOC_FREE(smb_fname_dot);
536 ok = subdir_of(connectpath,
538 real_fname->base_name,
541 TALLOC_FREE(real_fname);
542 *_oldwd_fname = oldwd_fname;
546 DBG_NOTICE("Bad access attempt: %s is a symlink "
547 "outside the share path\n"
549 "resolved_name=%s\n",
550 dir_fname->base_name,
552 real_fname->base_name);
553 TALLOC_FREE(real_fname);
555 status = NT_STATUS_OBJECT_NAME_NOT_FOUND;
558 if (oldwd_fname != NULL) {
559 ret = vfs_ChDir(conn, oldwd_fname);
560 SMB_ASSERT(ret == 0);
561 TALLOC_FREE(oldwd_fname);
568 * Get the symlink target of dirfsp/symlink_name, making sure the
569 * target is below connection_path.
572 static NTSTATUS symlink_target_below_conn(
574 const char *connection_path,
575 struct files_struct *fsp,
576 struct files_struct *dirfsp,
577 struct smb_filename *symlink_name,
581 char *absolute = NULL;
584 if (fsp_get_pathref_fd(fsp) != -1) {
586 * fsp is an O_PATH open, Linux does a "freadlink"
587 * with an empty name argument to readlinkat
589 status = readlink_talloc(talloc_tos(), fsp, NULL, &target);
591 status = readlink_talloc(
592 talloc_tos(), dirfsp, symlink_name, &target);
595 status = safe_symlink_target_path(talloc_tos(),
597 dirfsp->fsp_name->base_name,
601 if (!NT_STATUS_IS_OK(status)) {
602 DBG_DEBUG("safe_symlink_target_path() failed: %s\n",
607 if (absolute[0] == '\0') {
609 * special case symlink to share root: "." is our
610 * share root filename
612 TALLOC_FREE(absolute);
613 absolute = talloc_strdup(talloc_tos(), ".");
614 if (absolute == NULL) {
615 return NT_STATUS_NO_MEMORY;
623 /****************************************************************************
625 ****************************************************************************/
627 static NTSTATUS non_widelink_open(const struct files_struct *dirfsp,
629 struct smb_filename *smb_fname,
630 const struct vfs_open_how *_how)
632 struct connection_struct *conn = fsp->conn;
633 const char *connpath = SMB_VFS_CONNECTPATH(conn, dirfsp, smb_fname);
635 NTSTATUS status = NT_STATUS_OK;
637 char *orig_smb_fname_base = smb_fname->base_name;
638 struct smb_filename *orig_fsp_name = fsp->fsp_name;
639 struct smb_filename *smb_fname_rel = NULL;
640 struct smb_filename *oldwd_fname = NULL;
641 struct smb_filename *parent_dir_fname = NULL;
642 struct vfs_open_how how = *_how;
644 size_t link_depth = 0;
647 SMB_ASSERT(!fsp_is_alternate_stream(fsp));
649 if (connpath == NULL) {
651 * This can happen with shadow_copy2 if the snapshot
654 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
656 connpath_len = strlen(connpath);
659 if (smb_fname->base_name[0] == '/') {
660 int cmp = strcmp(connpath, smb_fname->base_name);
662 smb_fname->base_name = talloc_strdup(smb_fname, "");
663 if (smb_fname->base_name == NULL) {
664 status = NT_STATUS_NO_MEMORY;
670 if (dirfsp == conn->cwd_fsp) {
672 status = SMB_VFS_PARENT_PATHNAME(fsp->conn,
677 if (!NT_STATUS_IS_OK(status)) {
681 status = chdir_below_conn(
688 if (!NT_STATUS_IS_OK(status)) {
692 /* Setup fsp->fsp_name to be relative to cwd */
693 fsp->fsp_name = smb_fname_rel;
696 * fsp->fsp_name is unchanged as it is already correctly
697 * relative to conn->cwd.
699 smb_fname_rel = smb_fname;
704 * Assert nobody can step in with a symlink on the
705 * path, there is no path anymore and we'll use
706 * O_NOFOLLOW to open.
708 char *slash = strchr_m(smb_fname_rel->base_name, '/');
709 SMB_ASSERT(slash == NULL);
712 how.flags |= O_NOFOLLOW;
714 fd = SMB_VFS_OPENAT(conn,
719 fsp_set_fd(fsp, fd); /* This preserves errno */
722 status = map_nt_error_from_unix(errno);
724 if (errno == ENOENT) {
729 * ENOENT makes it worthless retrying with a
730 * stat, we know for sure the file does not
731 * exist. For everything else we want to know
734 ret = SMB_VFS_FSTATAT(
739 AT_SYMLINK_NOFOLLOW);
743 * Keep the original error. Otherwise we would
744 * mask for example EROFS for open(O_CREAT),
745 * turning it into ENOENT.
750 ret = SMB_VFS_FSTAT(fsp, &fsp->fsp_name->st);
754 status = map_nt_error_from_unix(errno);
755 DBG_DEBUG("fstat[at](%s) failed: %s\n",
756 smb_fname_str_dbg(smb_fname),
761 fsp->fsp_flags.is_directory = S_ISDIR(fsp->fsp_name->st.st_ex_mode);
762 orig_fsp_name->st = fsp->fsp_name->st;
764 if (!S_ISLNK(fsp->fsp_name->st.st_ex_mode)) {
769 * Found a symlink to follow in user space
772 if (fsp->fsp_name->flags & SMB_FILENAME_POSIX_PATH) {
773 /* Never follow symlinks on posix open. */
774 status = NT_STATUS_STOPPED_ON_SYMLINK;
777 if (!lp_follow_symlinks(SNUM(conn))) {
778 /* Explicitly no symlinks. */
779 status = NT_STATUS_STOPPED_ON_SYMLINK;
784 if (link_depth >= 40) {
785 status = NT_STATUS_STOPPED_ON_SYMLINK;
789 fsp->fsp_name = orig_fsp_name;
791 status = symlink_target_below_conn(
795 discard_const_p(files_struct, dirfsp),
799 if (!NT_STATUS_IS_OK(status)) {
800 DBG_DEBUG("symlink_target_below_conn() failed: %s\n",
806 * Close what openat(O_PATH) potentially left behind
810 if (smb_fname->base_name != orig_smb_fname_base) {
811 TALLOC_FREE(smb_fname->base_name);
813 smb_fname->base_name = target;
815 if (oldwd_fname != NULL) {
816 ret = vfs_ChDir(conn, oldwd_fname);
818 smb_panic("unable to get back to old directory\n");
820 TALLOC_FREE(oldwd_fname);
824 * And do it all again... As smb_fname is not relative to the passed in
825 * dirfsp anymore, we pass conn->cwd_fsp as dirfsp to
826 * non_widelink_open() to trigger the chdir(parentdir) logic.
828 dirfsp = conn->cwd_fsp;
833 fsp->fsp_name = orig_fsp_name;
834 smb_fname->base_name = orig_smb_fname_base;
836 TALLOC_FREE(parent_dir_fname);
838 if (!NT_STATUS_IS_OK(status)) {
842 if (oldwd_fname != NULL) {
843 ret = vfs_ChDir(conn, oldwd_fname);
845 smb_panic("unable to get back to old directory\n");
847 TALLOC_FREE(oldwd_fname);
852 /****************************************************************************
853 fd support routines - attempt to do a dos_open.
854 ****************************************************************************/
856 NTSTATUS fd_openat(const struct files_struct *dirfsp,
857 struct smb_filename *smb_fname,
859 const struct vfs_open_how *_how)
861 struct vfs_open_how how = *_how;
862 struct connection_struct *conn = fsp->conn;
863 NTSTATUS status = NT_STATUS_OK;
864 bool fsp_is_stream = fsp_is_alternate_stream(fsp);
865 bool smb_fname_is_stream = is_named_stream(smb_fname);
867 SMB_ASSERT(fsp_is_stream == smb_fname_is_stream);
870 * Never follow symlinks on a POSIX client. The
871 * client should be doing this.
874 if ((fsp->posix_flags & FSP_POSIX_FLAGS_OPEN) || !lp_follow_symlinks(SNUM(conn))) {
875 how.flags |= O_NOFOLLOW;
883 NULL, /* stream open is relative to fsp->base_fsp */
888 status = map_nt_error_from_unix(errno);
893 status = vfs_stat_fsp(fsp);
894 if (!NT_STATUS_IS_OK(status)) {
895 DBG_DEBUG("vfs_stat_fsp failed: %s\n",
905 * Only follow symlinks within a share
908 status = non_widelink_open(dirfsp, fsp, smb_fname, &how);
909 if (!NT_STATUS_IS_OK(status)) {
910 if (NT_STATUS_EQUAL(status, NT_STATUS_TOO_MANY_OPENED_FILES)) {
911 static time_t last_warned = 0L;
913 if (time((time_t *) NULL) > last_warned) {
914 DEBUG(0,("Too many open files, unable "
915 "to open more! smbd's max "
917 lp_max_open_files()));
918 last_warned = time((time_t *) NULL);
922 DBG_DEBUG("name %s, flags = 0%o mode = 0%o, fd = %d. %s\n",
923 smb_fname_str_dbg(smb_fname),
926 fsp_get_pathref_fd(fsp),
931 DBG_DEBUG("name %s, flags = 0%o mode = 0%o, fd = %d\n",
932 smb_fname_str_dbg(smb_fname),
935 fsp_get_pathref_fd(fsp));
940 /****************************************************************************
941 Close the file associated with a fsp.
942 ****************************************************************************/
944 NTSTATUS fd_close(files_struct *fsp)
949 if (fsp == fsp->conn->cwd_fsp) {
953 if (fsp->fsp_flags.fstat_before_close) {
954 status = vfs_stat_fsp(fsp);
955 if (!NT_STATUS_IS_OK(status)) {
957 * If this is a stream and delete-on-close was set, the
958 * backing object (an xattr from streams_xattr) might
959 * already be deleted so fstat() fails with
960 * NT_STATUS_NOT_FOUND. So if fsp refers to a stream we
961 * ignore the error and only bail for normal files where
962 * an fstat() should still work. NB. We cannot use
963 * fsp_is_alternate_stream(fsp) for this as the base_fsp
964 * has already been closed at this point and so the value
965 * fsp_is_alternate_stream() checks for is already NULL.
967 if (fsp->fsp_name->stream_name == NULL) {
976 if (fsp_get_pathref_fd(fsp) == -1) {
978 * Either a directory where the dptr_CloseDir() already closed
979 * the fd or a stat open.
983 if (fh_get_refcount(fsp->fh) > 1) {
984 return NT_STATUS_OK; /* Shared handle. Only close last reference. */
987 ret = SMB_VFS_CLOSE(fsp);
990 return map_nt_error_from_unix(errno);
995 /****************************************************************************
996 Change the ownership of a file to that of the parent directory.
997 Do this by fd if possible.
998 ****************************************************************************/
1000 static void change_file_owner_to_parent_fsp(struct files_struct *parent_fsp,
1001 struct files_struct *fsp)
1005 if (parent_fsp->fsp_name->st.st_ex_uid == fsp->fsp_name->st.st_ex_uid) {
1006 /* Already this uid - no need to change. */
1007 DBG_DEBUG("file %s is already owned by uid %u\n",
1009 (unsigned int)fsp->fsp_name->st.st_ex_uid);
1013 set_effective_capability(DAC_OVERRIDE_CAPABILITY);
1014 ret = SMB_VFS_FCHOWN(fsp,
1015 parent_fsp->fsp_name->st.st_ex_uid,
1017 drop_effective_capability(DAC_OVERRIDE_CAPABILITY);
1019 DBG_ERR("failed to fchown "
1020 "file %s to parent directory uid %u. Error "
1023 (unsigned int)parent_fsp->fsp_name->st.st_ex_uid,
1026 DBG_DEBUG("changed new file %s to "
1027 "parent directory uid %u.\n",
1029 (unsigned int)parent_fsp->fsp_name->st.st_ex_uid);
1030 /* Ensure the uid entry is updated. */
1031 fsp->fsp_name->st.st_ex_uid =
1032 parent_fsp->fsp_name->st.st_ex_uid;
1036 static NTSTATUS change_dir_owner_to_parent_fsp(struct files_struct *parent_fsp,
1037 struct files_struct *fsp)
1042 if (parent_fsp->fsp_name->st.st_ex_uid == fsp->fsp_name->st.st_ex_uid) {
1043 /* Already this uid - no need to change. */
1044 DBG_DEBUG("directory %s is already owned by uid %u\n",
1046 (unsigned int)fsp->fsp_name->st.st_ex_uid);
1047 return NT_STATUS_OK;
1050 set_effective_capability(DAC_OVERRIDE_CAPABILITY);
1051 ret = SMB_VFS_FCHOWN(fsp,
1052 parent_fsp->fsp_name->st.st_ex_uid,
1054 drop_effective_capability(DAC_OVERRIDE_CAPABILITY);
1056 status = map_nt_error_from_unix(errno);
1057 DBG_ERR("failed to chown "
1058 "directory %s to parent directory uid %u. "
1061 (unsigned int)parent_fsp->fsp_name->st.st_ex_uid,
1066 DBG_DEBUG("changed ownership of new "
1067 "directory %s to parent directory uid %u.\n",
1069 (unsigned int)parent_fsp->fsp_name->st.st_ex_uid);
1071 /* Ensure the uid entry is updated. */
1072 fsp->fsp_name->st.st_ex_uid = parent_fsp->fsp_name->st.st_ex_uid;
1074 return NT_STATUS_OK;
1077 /****************************************************************************
1078 Open a file - returning a guaranteed ATOMIC indication of if the
1079 file was created or not.
1080 ****************************************************************************/
1082 static NTSTATUS fd_open_atomic(struct files_struct *dirfsp,
1083 struct smb_filename *smb_fname,
1085 const struct vfs_open_how *_how,
1088 struct vfs_open_how how = *_how;
1089 NTSTATUS status = NT_STATUS_UNSUCCESSFUL;
1090 NTSTATUS retry_status;
1091 bool file_existed = VALID_STAT(smb_fname->st);
1093 if (!(how.flags & O_CREAT)) {
1095 * We're not creating the file, just pass through.
1097 status = fd_openat(dirfsp, smb_fname, fsp, &how);
1098 *file_created = false;
1102 if (how.flags & O_EXCL) {
1104 * Fail if already exists, just pass through.
1106 status = fd_openat(dirfsp, smb_fname, fsp, &how);
1109 * Here we've opened with O_CREAT|O_EXCL. If that went
1110 * NT_STATUS_OK, we *know* we created this file.
1112 *file_created = NT_STATUS_IS_OK(status);
1118 * Now it gets tricky. We have O_CREAT, but not O_EXCL.
1119 * To know absolutely if we created the file or not,
1120 * we can never call O_CREAT without O_EXCL. So if
1121 * we think the file existed, try without O_CREAT|O_EXCL.
1122 * If we think the file didn't exist, try with
1125 * The big problem here is dangling symlinks. Opening
1126 * without O_NOFOLLOW means both bad symlink
1127 * and missing path return -1, ENOENT from open(). As POSIX
1128 * is pathname based it's not possible to tell
1129 * the difference between these two cases in a
1130 * non-racy way, so change to try only two attempts before
1133 * We don't have this problem for the O_NOFOLLOW
1134 * case as it just returns NT_STATUS_OBJECT_PATH_NOT_FOUND
1135 * mapped from the ELOOP POSIX error.
1139 how.flags = _how->flags & ~(O_CREAT);
1140 retry_status = NT_STATUS_OBJECT_NAME_NOT_FOUND;
1142 how.flags = _how->flags | O_EXCL;
1143 retry_status = NT_STATUS_OBJECT_NAME_COLLISION;
1146 status = fd_openat(dirfsp, smb_fname, fsp, &how);
1147 if (NT_STATUS_IS_OK(status)) {
1148 *file_created = !file_existed;
1149 return NT_STATUS_OK;
1151 if (NT_STATUS_EQUAL(status, retry_status)) {
1153 file_existed = !file_existed;
1155 DBG_DEBUG("File %s %s. Retry.\n",
1157 file_existed ? "existed" : "did not exist");
1160 how.flags = _how->flags & ~(O_CREAT);
1162 how.flags = _how->flags | O_EXCL;
1165 status = fd_openat(dirfsp, smb_fname, fsp, &how);
1168 *file_created = (NT_STATUS_IS_OK(status) && !file_existed);
1172 static NTSTATUS reopen_from_fsp(struct files_struct *dirfsp,
1173 struct smb_filename *smb_fname,
1174 struct files_struct *fsp,
1175 const struct vfs_open_how *how,
1176 bool *p_file_created)
1181 if (fsp->fsp_flags.have_proc_fds &&
1182 ((old_fd = fsp_get_pathref_fd(fsp)) != -1)) {
1184 struct sys_proc_fd_path_buf buf;
1185 struct smb_filename proc_fname = (struct smb_filename){
1186 .base_name = sys_proc_fd_path(old_fd, &buf),
1188 mode_t mode = fsp->fsp_name->st.st_ex_mode;
1191 SMB_ASSERT(fsp->fsp_flags.is_pathref);
1193 if (S_ISLNK(mode)) {
1194 return NT_STATUS_STOPPED_ON_SYMLINK;
1196 if (!(S_ISREG(mode) || S_ISDIR(mode))) {
1197 return NT_STATUS_IO_REPARSE_TAG_NOT_HANDLED;
1200 fsp->fsp_flags.is_pathref = false;
1202 new_fd = SMB_VFS_OPENAT(fsp->conn,
1208 status = map_nt_error_from_unix(errno);
1213 status = fd_close(fsp);
1214 if (!NT_STATUS_IS_OK(status)) {
1218 fsp_set_fd(fsp, new_fd);
1219 return NT_STATUS_OK;
1223 * Close the existing pathref fd and set the fsp flag
1224 * is_pathref to false so we get a "normal" fd this time.
1226 status = fd_close(fsp);
1227 if (!NT_STATUS_IS_OK(status)) {
1231 fsp->fsp_flags.is_pathref = false;
1233 status = fd_open_atomic(dirfsp, smb_fname, fsp, how, p_file_created);
1237 /****************************************************************************
1239 ****************************************************************************/
1241 static NTSTATUS open_file(
1242 struct smb_request *req,
1243 struct files_struct *dirfsp,
1244 struct smb_filename *smb_fname_atname,
1246 const struct vfs_open_how *_how,
1247 uint32_t access_mask, /* client requested access mask. */
1248 uint32_t open_access_mask, /* what we're actually using in the open. */
1249 uint32_t private_flags,
1250 bool *p_file_created)
1252 connection_struct *conn = fsp->conn;
1253 struct smb_filename *smb_fname = fsp->fsp_name;
1254 struct vfs_open_how how = *_how;
1255 NTSTATUS status = NT_STATUS_OK;
1256 bool file_existed = VALID_STAT(fsp->fsp_name->st);
1257 const uint32_t need_fd_mask =
1262 SEC_FLAG_SYSTEM_SECURITY;
1263 bool creating = !file_existed && (how.flags & O_CREAT);
1264 bool open_fd = false;
1265 bool posix_open = (fsp->posix_flags & FSP_POSIX_FLAGS_OPEN);
1268 * Catch early an attempt to open an existing
1269 * directory as a file.
1271 if (file_existed && S_ISDIR(fsp->fsp_name->st.st_ex_mode)) {
1272 return NT_STATUS_FILE_IS_A_DIRECTORY;
1276 * This little piece of insanity is inspired by the
1277 * fact that an NT client can open a file for O_RDONLY,
1278 * but set the create disposition to FILE_EXISTS_TRUNCATE.
1279 * If the client *can* write to the file, then it expects to
1280 * truncate the file, even though it is opening for readonly.
1281 * Quicken uses this stupid trick in backup file creation...
1282 * Thanks *greatly* to "David W. Chapman Jr." <dwcjr@inethouston.net>
1283 * for helping track this one down. It didn't bite us in 2.0.x
1284 * as we always opened files read-write in that release. JRA.
1287 if (((how.flags & O_ACCMODE) == O_RDONLY) && (how.flags & O_TRUNC)) {
1288 DBG_DEBUG("truncate requested on read-only open for file %s\n",
1289 smb_fname_str_dbg(smb_fname));
1290 how.flags = (how.flags & ~O_ACCMODE) | O_RDWR;
1293 /* Check permissions */
1296 * This code was changed after seeing a client open request
1297 * containing the open mode of (DENY_WRITE/read-only) with
1298 * the 'create if not exist' bit set. The previous code
1299 * would fail to open the file read only on a read-only share
1300 * as it was checking the flags parameter directly against O_RDONLY,
1301 * this was failing as the flags parameter was set to O_RDONLY|O_CREAT.
1305 if (!CAN_WRITE(conn)) {
1306 /* It's a read-only share - fail if we wanted to write. */
1307 if ((how.flags & O_ACCMODE) != O_RDONLY ||
1308 (how.flags & O_TRUNC) || (how.flags & O_APPEND)) {
1309 DEBUG(3,("Permission denied opening %s\n",
1310 smb_fname_str_dbg(smb_fname)));
1311 return NT_STATUS_ACCESS_DENIED;
1314 * We don't want to write - but we must make sure that
1315 * O_CREAT doesn't create the file if we have write
1316 * access into the directory.
1318 how.flags &= ~(O_CREAT | O_EXCL);
1321 if ((open_access_mask & need_fd_mask) || creating ||
1322 (how.flags & O_TRUNC)) {
1329 #if defined(O_NONBLOCK) && defined(S_ISFIFO)
1331 * We would block on opening a FIFO with no one else on the
1332 * other end. Do what we used to do and add O_NONBLOCK to the
1336 if (file_existed && S_ISFIFO(smb_fname->st.st_ex_mode)) {
1337 how.flags |= O_NONBLOCK;
1342 const char *wild = smb_fname->base_name;
1344 * Don't open files with Microsoft wildcard characters.
1346 if (fsp_is_alternate_stream(fsp)) {
1348 * wildcard characters are allowed in stream
1349 * names only test the basefilename
1351 wild = fsp->base_fsp->fsp_name->base_name;
1354 if (ms_has_wild(wild)) {
1355 return NT_STATUS_OBJECT_NAME_INVALID;
1359 /* Can we access this file ? */
1360 if (!fsp_is_alternate_stream(fsp)) {
1361 /* Only do this check on non-stream open. */
1363 status = smbd_check_access_rights_fsp(
1369 if (!NT_STATUS_IS_OK(status)) {
1370 DBG_DEBUG("smbd_check_access_rights_fsp"
1371 " on file %s returned %s\n",
1376 if (!NT_STATUS_IS_OK(status) &&
1377 !NT_STATUS_EQUAL(status,
1378 NT_STATUS_OBJECT_NAME_NOT_FOUND))
1383 if (NT_STATUS_EQUAL(status,
1384 NT_STATUS_OBJECT_NAME_NOT_FOUND))
1386 DEBUG(10, ("open_file: "
1387 "file %s vanished since we "
1388 "checked for existence.\n",
1389 smb_fname_str_dbg(smb_fname)));
1390 file_existed = false;
1391 SET_STAT_INVALID(fsp->fsp_name->st);
1395 if (!file_existed) {
1396 if (!(how.flags & O_CREAT)) {
1397 /* File didn't exist and no O_CREAT. */
1398 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
1401 status = check_parent_access_fsp(
1404 if (!NT_STATUS_IS_OK(status)) {
1405 DBG_DEBUG("check_parent_access_fsp on "
1406 "directory %s for file %s "
1410 smb_fname_str_dbg(smb_fname),
1418 * Actually do the open - if O_TRUNC is needed handle it
1419 * below under the share mode lock.
1421 how.flags &= ~O_TRUNC;
1422 status = reopen_from_fsp(dirfsp,
1427 if (NT_STATUS_EQUAL(status, NT_STATUS_STOPPED_ON_SYMLINK)) {
1429 * Non-O_PATH reopen that hit a race
1430 * condition: Someone has put a symlink where
1431 * we used to have a file. Can't happen with
1432 * O_PATH and reopening from /proc/self/fd/ or
1435 status = NT_STATUS_OBJECT_NAME_NOT_FOUND;
1437 if (!NT_STATUS_IS_OK(status)) {
1438 DBG_NOTICE("Error opening file %s (%s) (in_flags=%d) "
1440 smb_fname_str_dbg(smb_fname),
1447 if (how.flags & O_NONBLOCK) {
1449 * GPFS can return ETIMEDOUT for pread on
1450 * nonblocking file descriptors when files
1451 * migrated to tape need to be recalled. I
1452 * could imagine this happens elsewhere
1453 * too. With blocking file descriptors this
1456 ret = vfs_set_blocking(fsp, true);
1458 status = map_nt_error_from_unix(errno);
1459 DBG_WARNING("Could not set fd to blocking: "
1460 "%s\n", strerror(errno));
1466 if (*p_file_created) {
1467 /* We created this file. */
1469 bool need_re_stat = false;
1470 /* Do all inheritance work after we've
1471 done a successful fstat call and filled
1472 in the stat struct in fsp->fsp_name. */
1474 /* Inherit the ACL if required */
1475 if (lp_inherit_permissions(SNUM(conn))) {
1476 inherit_access_posix_acl(conn,
1480 need_re_stat = true;
1483 /* Change the owner if required. */
1484 if (lp_inherit_owner(SNUM(conn)) != INHERIT_OWNER_NO) {
1485 change_file_owner_to_parent_fsp(dirfsp, fsp);
1486 need_re_stat = true;
1490 status = vfs_stat_fsp(fsp);
1492 * If we have an fd, this stat should succeed.
1494 if (!NT_STATUS_IS_OK(status)) {
1495 DBG_ERR("Error doing fstat on open "
1497 smb_fname_str_dbg(smb_fname),
1504 notify_fname(conn, NOTIFY_ACTION_ADDED,
1505 FILE_NOTIFY_CHANGE_FILE_NAME,
1506 smb_fname->base_name);
1509 if (!file_existed) {
1510 /* File must exist for a stat open. */
1511 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
1514 if (S_ISLNK(smb_fname->st.st_ex_mode) &&
1518 * Don't allow stat opens on symlinks directly unless
1519 * it's a POSIX open. Match the return code from
1520 * openat_pathref_fsp().
1522 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
1525 if (!fsp->fsp_flags.is_pathref) {
1527 * There is only one legit case where end up here:
1528 * openat_pathref_fsp() failed to open a symlink, so the
1529 * fsp was created by fsp_new() which doesn't set
1530 * is_pathref. Other than that, we should always have a
1531 * pathref fsp at this point. The subsequent checks
1534 if (!(smb_fname->flags & SMB_FILENAME_POSIX_PATH)) {
1535 DBG_ERR("[%s] is not a POSIX pathname\n",
1536 smb_fname_str_dbg(smb_fname));
1537 return NT_STATUS_INTERNAL_ERROR;
1539 if (!S_ISLNK(smb_fname->st.st_ex_mode)) {
1540 DBG_ERR("[%s] is not a symlink\n",
1541 smb_fname_str_dbg(smb_fname));
1542 return NT_STATUS_INTERNAL_ERROR;
1544 if (fsp_get_pathref_fd(fsp) != -1) {
1545 DBG_ERR("fd for [%s] is not -1: fd [%d]\n",
1546 smb_fname_str_dbg(smb_fname),
1547 fsp_get_pathref_fd(fsp));
1548 return NT_STATUS_INTERNAL_ERROR;
1553 * Access to streams is checked by checking the basefile and
1554 * that has already been checked by check_base_file_access()
1555 * in create_file_unixpath().
1557 if (!fsp_is_alternate_stream(fsp)) {
1558 status = smbd_check_access_rights_fsp(dirfsp,
1563 if (NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND) &&
1565 S_ISLNK(smb_fname->st.st_ex_mode)) {
1566 /* This is a POSIX stat open for delete
1567 * or rename on a symlink that points
1568 * nowhere. Allow. */
1569 DEBUG(10,("open_file: allowing POSIX "
1570 "open on bad symlink %s\n",
1571 smb_fname_str_dbg(smb_fname)));
1572 status = NT_STATUS_OK;
1575 if (!NT_STATUS_IS_OK(status)) {
1576 DBG_DEBUG("smbd_check_access_rights_fsp on file "
1585 fsp->file_id = vfs_file_id_from_sbuf(conn, &smb_fname->st);
1586 fsp->vuid = req ? req->vuid : UID_FIELD_INVALID;
1587 fsp->file_pid = req ? req->smbpid : 0;
1588 fsp->fsp_flags.can_lock = true;
1589 fsp->fsp_flags.can_read = ((access_mask & FILE_READ_DATA) != 0);
1590 fsp->fsp_flags.can_write =
1592 ((access_mask & (FILE_WRITE_DATA | FILE_APPEND_DATA)) != 0);
1593 if (fsp->fsp_name->twrp != 0) {
1594 fsp->fsp_flags.can_write = false;
1596 fsp->print_file = NULL;
1597 fsp->fsp_flags.modified = false;
1598 fsp->sent_oplock_break = NO_BREAK_SENT;
1599 fsp->fsp_flags.is_directory = false;
1600 if (is_in_path(smb_fname->base_name,
1601 conn->aio_write_behind_list,
1602 posix_open ? true : conn->case_sensitive)) {
1603 fsp->fsp_flags.aio_write_behind = true;
1606 DEBUG(2,("%s opened file %s read=%s write=%s (numopen=%d)\n",
1607 conn->session_info->unix_info->unix_name,
1608 smb_fname_str_dbg(smb_fname),
1609 BOOLSTR(fsp->fsp_flags.can_read),
1610 BOOLSTR(fsp->fsp_flags.can_write),
1611 conn->num_files_open));
1613 return NT_STATUS_OK;
1616 static bool mask_conflict(
1617 uint32_t new_access,
1618 uint32_t existing_access,
1619 uint32_t access_mask,
1620 uint32_t new_sharemode,
1621 uint32_t existing_sharemode,
1622 uint32_t sharemode_mask)
1624 bool want_access = (new_access & access_mask);
1625 bool allow_existing = (existing_sharemode & sharemode_mask);
1626 bool have_access = (existing_access & access_mask);
1627 bool allow_new = (new_sharemode & sharemode_mask);
1629 if (want_access && !allow_existing) {
1630 DBG_DEBUG("Access request 0x%"PRIx32"/0x%"PRIx32" conflicts "
1631 "with existing sharemode 0x%"PRIx32"/0x%"PRIx32"\n",
1638 if (have_access && !allow_new) {
1639 DBG_DEBUG("Sharemode request 0x%"PRIx32"/0x%"PRIx32" conflicts "
1640 "with existing access 0x%"PRIx32"/0x%"PRIx32"\n",
1650 /****************************************************************************
1651 Check if we can open a file with a share mode.
1652 Returns True if conflict, False if not.
1653 ****************************************************************************/
1655 static const uint32_t conflicting_access =
1662 static bool share_conflict(uint32_t e_access_mask,
1663 uint32_t e_share_access,
1664 uint32_t access_mask,
1665 uint32_t share_access)
1669 DBG_DEBUG("existing access_mask = 0x%"PRIx32", "
1670 "existing share access = 0x%"PRIx32", "
1671 "access_mask = 0x%"PRIx32", "
1672 "share_access = 0x%"PRIx32"\n",
1678 if ((e_access_mask & conflicting_access) == 0) {
1679 DBG_DEBUG("No conflict due to "
1680 "existing access_mask = 0x%"PRIx32"\n",
1684 if ((access_mask & conflicting_access) == 0) {
1685 DBG_DEBUG("No conflict due to access_mask = 0x%"PRIx32"\n",
1690 conflict = mask_conflict(
1691 access_mask, e_access_mask, FILE_WRITE_DATA | FILE_APPEND_DATA,
1692 share_access, e_share_access, FILE_SHARE_WRITE);
1693 conflict |= mask_conflict(
1694 access_mask, e_access_mask, FILE_READ_DATA | FILE_EXECUTE,
1695 share_access, e_share_access, FILE_SHARE_READ);
1696 conflict |= mask_conflict(
1697 access_mask, e_access_mask, DELETE_ACCESS,
1698 share_access, e_share_access, FILE_SHARE_DELETE);
1700 DBG_DEBUG("conflict=%s\n", conflict ? "true" : "false");
1704 #if defined(DEVELOPER)
1706 struct validate_my_share_entries_state {
1707 struct smbd_server_connection *sconn;
1709 struct server_id self;
1712 static bool validate_my_share_entries_fn(
1713 struct share_mode_entry *e,
1717 struct validate_my_share_entries_state *state = private_data;
1720 if (!server_id_equal(&state->self, &e->pid)) {
1724 if (e->op_mid == 0) {
1725 /* INTERNAL_OPEN_ONLY */
1729 fsp = file_find_dif(state->sconn, state->fid, e->share_file_id);
1731 DBG_ERR("PANIC : %s\n",
1732 share_mode_str(talloc_tos(), 0, &state->fid, e));
1733 smb_panic("validate_my_share_entries: Cannot match a "
1734 "share entry with an open file\n");
1737 if (((uint16_t)fsp->oplock_type) != e->op_type) {
1746 DBG_ERR("validate_my_share_entries: PANIC : %s\n",
1747 share_mode_str(talloc_tos(), 0, &state->fid, e));
1748 str = talloc_asprintf(talloc_tos(),
1749 "validate_my_share_entries: "
1750 "file %s, oplock_type = 0x%x, op_type = 0x%x\n",
1751 fsp->fsp_name->base_name,
1752 (unsigned int)fsp->oplock_type,
1753 (unsigned int)e->op_type);
1762 * Allowed access mask for stat opens relevant to oplocks
1764 bool is_oplock_stat_open(uint32_t access_mask)
1766 const uint32_t stat_open_bits =
1767 (SYNCHRONIZE_ACCESS|
1768 FILE_READ_ATTRIBUTES|
1769 FILE_WRITE_ATTRIBUTES);
1771 return (((access_mask & stat_open_bits) != 0) &&
1772 ((access_mask & ~stat_open_bits) == 0));
1776 * Allowed access mask for stat opens relevant to leases
1778 bool is_lease_stat_open(uint32_t access_mask)
1780 const uint32_t stat_open_bits =
1781 (SYNCHRONIZE_ACCESS|
1782 FILE_READ_ATTRIBUTES|
1783 FILE_WRITE_ATTRIBUTES|
1784 READ_CONTROL_ACCESS);
1786 return (((access_mask & stat_open_bits) != 0) &&
1787 ((access_mask & ~stat_open_bits) == 0));
1790 struct has_delete_on_close_state {
1794 static bool has_delete_on_close_fn(
1795 struct share_mode_entry *e,
1799 struct has_delete_on_close_state *state = private_data;
1800 state->ret = !share_entry_stale_pid(e);
1804 static bool has_delete_on_close(struct share_mode_lock *lck,
1807 struct has_delete_on_close_state state = { .ret = false };
1810 if (!is_delete_on_close_set(lck, name_hash)) {
1814 ok= share_mode_forall_entries(lck, has_delete_on_close_fn, &state);
1816 DBG_DEBUG("share_mode_forall_entries failed\n");
1822 static void share_mode_flags_restrict(
1823 struct share_mode_lock *lck,
1824 uint32_t access_mask,
1825 uint32_t share_mode,
1826 uint32_t lease_type)
1828 uint32_t existing_access_mask, existing_share_mode;
1829 uint32_t existing_lease_type;
1831 share_mode_flags_get(
1833 &existing_access_mask,
1834 &existing_share_mode,
1835 &existing_lease_type);
1837 existing_access_mask |= access_mask;
1838 if (access_mask & conflicting_access) {
1839 existing_share_mode &= share_mode;
1841 existing_lease_type |= lease_type;
1843 share_mode_flags_set(
1845 existing_access_mask,
1846 existing_share_mode,
1847 existing_lease_type,
1851 /****************************************************************************
1852 Deal with share modes
1853 Invariant: Share mode must be locked on entry and exit.
1854 Returns -1 on error, or number of share modes on success (may be zero).
1855 ****************************************************************************/
1857 struct open_mode_check_state {
1859 uint32_t access_mask;
1860 uint32_t share_access;
1861 uint32_t lease_type;
1864 static bool open_mode_check_fn(
1865 struct share_mode_entry *e,
1869 struct open_mode_check_state *state = private_data;
1870 bool disconnected, stale;
1871 uint32_t access_mask, share_access, lease_type;
1873 disconnected = server_id_is_disconnected(&e->pid);
1878 access_mask = state->access_mask | e->access_mask;
1879 share_access = state->share_access;
1880 if (e->access_mask & conflicting_access) {
1881 share_access &= e->share_access;
1883 lease_type = state->lease_type | get_lease_type(e, state->fid);
1885 if ((access_mask == state->access_mask) &&
1886 (share_access == state->share_access) &&
1887 (lease_type == state->lease_type)) {
1891 stale = share_entry_stale_pid(e);
1896 state->access_mask = access_mask;
1897 state->share_access = share_access;
1898 state->lease_type = lease_type;
1903 static NTSTATUS open_mode_check(connection_struct *conn,
1905 struct share_mode_lock *lck,
1906 uint32_t access_mask,
1907 uint32_t share_access)
1909 struct open_mode_check_state state;
1911 bool modified = false;
1913 if (is_oplock_stat_open(access_mask)) {
1914 /* Stat open that doesn't trigger oplock breaks or share mode
1915 * checks... ! JRA. */
1916 return NT_STATUS_OK;
1920 * Check if the share modes will give us access.
1923 #if defined(DEVELOPER)
1925 struct validate_my_share_entries_state validate_state = {
1926 .sconn = conn->sconn,
1928 .self = messaging_server_id(conn->sconn->msg_ctx),
1930 ok = share_mode_forall_entries(
1931 lck, validate_my_share_entries_fn, &validate_state);
1936 share_mode_flags_get(
1937 lck, &state.access_mask, &state.share_access, NULL);
1939 conflict = share_conflict(
1945 DBG_DEBUG("No conflict due to share_mode_flags access\n");
1946 return NT_STATUS_OK;
1949 state = (struct open_mode_check_state) {
1951 .share_access = (FILE_SHARE_READ|
1957 * Walk the share mode array to recalculate d->flags
1960 ok = share_mode_forall_entries(lck, open_mode_check_fn, &state);
1962 DBG_DEBUG("share_mode_forall_entries failed\n");
1963 return NT_STATUS_INTERNAL_ERROR;
1966 share_mode_flags_set(
1974 * We only end up here if we had a sharing violation
1975 * from d->flags and have recalculated it.
1977 return NT_STATUS_SHARING_VIOLATION;
1980 conflict = share_conflict(
1986 DBG_DEBUG("No conflict due to share_mode_flags access\n");
1987 return NT_STATUS_OK;
1990 return NT_STATUS_SHARING_VIOLATION;
1994 * Send a break message to the oplock holder and delay the open for
1998 NTSTATUS send_break_message(struct messaging_context *msg_ctx,
1999 const struct file_id *id,
2000 const struct share_mode_entry *exclusive,
2003 struct oplock_break_message msg = {
2005 .share_file_id = exclusive->share_file_id,
2006 .break_to = break_to,
2008 enum ndr_err_code ndr_err;
2013 struct server_id_buf buf;
2014 DBG_DEBUG("Sending break message to %s\n",
2015 server_id_str_buf(exclusive->pid, &buf));
2016 NDR_PRINT_DEBUG(oplock_break_message, &msg);
2019 ndr_err = ndr_push_struct_blob(
2023 (ndr_push_flags_fn_t)ndr_push_oplock_break_message);
2024 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
2025 DBG_WARNING("ndr_push_oplock_break_message failed: %s\n",
2026 ndr_errstr(ndr_err));
2027 return ndr_map_error2ntstatus(ndr_err);
2030 status = messaging_send(
2031 msg_ctx, exclusive->pid, MSG_SMB_BREAK_REQUEST, &blob);
2032 TALLOC_FREE(blob.data);
2033 if (!NT_STATUS_IS_OK(status)) {
2034 DEBUG(3, ("Could not send oplock break message: %s\n",
2035 nt_errstr(status)));
2041 struct validate_oplock_types_state {
2047 uint32_t num_non_stat_opens;
2050 static bool validate_oplock_types_fn(
2051 struct share_mode_entry *e,
2055 struct validate_oplock_types_state *state = private_data;
2057 if (e->op_mid == 0) {
2058 /* INTERNAL_OPEN_ONLY */
2062 if (e->op_type == NO_OPLOCK && is_oplock_stat_open(e->access_mask)) {
2064 * We ignore stat opens in the table - they always
2065 * have NO_OPLOCK and never get or cause breaks. JRA.
2070 state->num_non_stat_opens += 1;
2072 if (BATCH_OPLOCK_TYPE(e->op_type)) {
2073 /* batch - can only be one. */
2074 if (share_entry_stale_pid(e)) {
2075 DBG_DEBUG("Found stale batch oplock\n");
2078 if (state->ex_or_batch ||
2082 DBG_ERR("Bad batch oplock entry\n");
2083 state->valid = false;
2086 state->batch = true;
2089 if (EXCLUSIVE_OPLOCK_TYPE(e->op_type)) {
2090 if (share_entry_stale_pid(e)) {
2091 DBG_DEBUG("Found stale duplicate oplock\n");
2094 /* Exclusive or batch - can only be one. */
2095 if (state->ex_or_batch ||
2098 DBG_ERR("Bad exclusive or batch oplock entry\n");
2099 state->valid = false;
2102 state->ex_or_batch = true;
2105 if (LEVEL_II_OPLOCK_TYPE(e->op_type)) {
2106 if (state->batch || state->ex_or_batch) {
2107 if (share_entry_stale_pid(e)) {
2108 DBG_DEBUG("Found stale LevelII oplock\n");
2111 DBG_DEBUG("Bad levelII oplock entry\n");
2112 state->valid = false;
2115 state->level2 = true;
2118 if (e->op_type == NO_OPLOCK) {
2119 if (state->batch || state->ex_or_batch) {
2120 if (share_entry_stale_pid(e)) {
2121 DBG_DEBUG("Found stale NO_OPLOCK entry\n");
2124 DBG_ERR("Bad no oplock entry\n");
2125 state->valid = false;
2128 state->no_oplock = true;
2135 * Do internal consistency checks on the share mode for a file.
2138 static bool validate_oplock_types(struct share_mode_lock *lck)
2140 struct validate_oplock_types_state state = { .valid = true };
2141 static bool skip_validation;
2145 if (skip_validation) {
2149 validate = lp_parm_bool(-1, "smbd", "validate_oplock_types", false);
2151 DBG_DEBUG("smbd:validate_oplock_types not set to yes\n");
2152 skip_validation = true;
2156 ok = share_mode_forall_entries(lck, validate_oplock_types_fn, &state);
2158 DBG_DEBUG("share_mode_forall_entries failed\n");
2162 DBG_DEBUG("Got invalid oplock configuration\n");
2166 if ((state.batch || state.ex_or_batch) &&
2167 (state.num_non_stat_opens != 1)) {
2168 DBG_WARNING("got batch (%d) or ex (%d) non-exclusively "
2171 (int)state.ex_or_batch,
2172 state.num_non_stat_opens);
2179 static bool is_same_lease(const files_struct *fsp,
2180 const struct share_mode_entry *e,
2181 const struct smb2_lease *lease)
2183 if (e->op_type != LEASE_OPLOCK) {
2186 if (lease == NULL) {
2190 return smb2_lease_equal(fsp_client_guid(fsp),
2196 static bool file_has_brlocks(files_struct *fsp)
2198 struct byte_range_lock *br_lck;
2200 br_lck = brl_get_locks_readonly(fsp);
2204 return (brl_num_locks(br_lck) > 0);
2207 struct fsp_lease *find_fsp_lease(struct files_struct *new_fsp,
2208 const struct smb2_lease_key *key,
2209 uint32_t current_state,
2210 uint16_t lease_version,
2211 uint16_t lease_epoch)
2213 struct files_struct *fsp;
2216 * TODO: Measure how expensive this loop is with thousands of open
2220 for (fsp = file_find_di_first(new_fsp->conn->sconn, new_fsp->file_id, true);
2222 fsp = file_find_di_next(fsp, true)) {
2224 if (fsp == new_fsp) {
2227 if (fsp->oplock_type != LEASE_OPLOCK) {
2230 if (smb2_lease_key_equal(&fsp->lease->lease.lease_key, key)) {
2231 fsp->lease->ref_count += 1;
2236 /* Not found - must be leased in another smbd. */
2237 new_fsp->lease = talloc_zero(new_fsp->conn->sconn, struct fsp_lease);
2238 if (new_fsp->lease == NULL) {
2241 new_fsp->lease->ref_count = 1;
2242 new_fsp->lease->sconn = new_fsp->conn->sconn;
2243 new_fsp->lease->lease.lease_key = *key;
2244 new_fsp->lease->lease.lease_state = current_state;
2246 * We internally treat all leases as V2 and update
2247 * the epoch, but when sending breaks it matters if
2248 * the requesting lease was v1 or v2.
2250 new_fsp->lease->lease.lease_version = lease_version;
2251 new_fsp->lease->lease.lease_epoch = lease_epoch;
2252 return new_fsp->lease;
2255 static NTSTATUS try_lease_upgrade(struct files_struct *fsp,
2256 struct share_mode_lock *lck,
2257 const struct GUID *client_guid,
2258 const struct smb2_lease *lease,
2262 uint32_t current_state, breaking_to_requested, breaking_to_required;
2264 uint16_t lease_version, epoch;
2265 uint32_t existing, requested;
2268 status = leases_db_get(
2274 &breaking_to_requested,
2275 &breaking_to_required,
2278 if (!NT_STATUS_IS_OK(status)) {
2282 fsp->lease = find_fsp_lease(
2288 if (fsp->lease == NULL) {
2289 DEBUG(1, ("Did not find existing lease for file %s\n",
2291 return NT_STATUS_NO_MEMORY;
2295 * Upgrade only if the requested lease is a strict upgrade.
2297 existing = current_state;
2298 requested = lease->lease_state;
2301 * Tricky: This test makes sure that "requested" is a
2302 * strict bitwise superset of "existing".
2304 do_upgrade = ((existing & requested) == existing);
2307 * Upgrade only if there's a change.
2309 do_upgrade &= (granted != existing);
2312 * Upgrade only if other leases don't prevent what was asked
2315 do_upgrade &= (granted == requested);
2318 * only upgrade if we are not in breaking state
2320 do_upgrade &= !breaking;
2322 DEBUG(10, ("existing=%"PRIu32", requested=%"PRIu32", "
2323 "granted=%"PRIu32", do_upgrade=%d\n",
2324 existing, requested, granted, (int)do_upgrade));
2327 NTSTATUS set_status;
2329 current_state = granted;
2332 set_status = leases_db_set(
2337 breaking_to_requested,
2338 breaking_to_required,
2342 if (!NT_STATUS_IS_OK(set_status)) {
2343 DBG_DEBUG("leases_db_set failed: %s\n",
2344 nt_errstr(set_status));
2349 fsp_lease_update(fsp);
2351 return NT_STATUS_OK;
2354 static NTSTATUS grant_new_fsp_lease(struct files_struct *fsp,
2355 struct share_mode_lock *lck,
2356 const struct GUID *client_guid,
2357 const struct smb2_lease *lease,
2362 fsp->lease = talloc_zero(fsp->conn->sconn, struct fsp_lease);
2363 if (fsp->lease == NULL) {
2364 return NT_STATUS_INSUFFICIENT_RESOURCES;
2366 fsp->lease->ref_count = 1;
2367 fsp->lease->sconn = fsp->conn->sconn;
2368 fsp->lease->lease.lease_version = lease->lease_version;
2369 fsp->lease->lease.lease_key = lease->lease_key;
2370 fsp->lease->lease.lease_state = granted;
2371 fsp->lease->lease.lease_epoch = lease->lease_epoch + 1;
2373 status = leases_db_add(client_guid,
2376 fsp->lease->lease.lease_state,
2377 fsp->lease->lease.lease_version,
2378 fsp->lease->lease.lease_epoch,
2379 fsp->conn->connectpath,
2380 fsp->fsp_name->base_name,
2381 fsp->fsp_name->stream_name);
2382 if (!NT_STATUS_IS_OK(status)) {
2383 DEBUG(10, ("%s: leases_db_add failed: %s\n", __func__,
2384 nt_errstr(status)));
2385 TALLOC_FREE(fsp->lease);
2386 return NT_STATUS_INSUFFICIENT_RESOURCES;
2390 * We used to set lck->data->modified=true here without
2391 * actually modifying lck->data, triggering a needless
2392 * writeback of lck->data.
2394 * Apart from that writeback, setting modified=true has the
2395 * effect of triggering all waiters for this file to
2396 * retry. This only makes sense if any blocking condition
2397 * (i.e. waiting for a lease to be downgraded or removed) is
2398 * gone. This routine here only adds a lease, so it will never
2399 * free up resources that blocked waiters can now claim. So
2400 * that second effect also does not matter in this
2401 * routine. Thus setting lck->data->modified=true does not
2402 * need to be done here.
2405 return NT_STATUS_OK;
2408 static NTSTATUS grant_fsp_lease(struct files_struct *fsp,
2409 struct share_mode_lock *lck,
2410 const struct smb2_lease *lease,
2413 const struct GUID *client_guid = fsp_client_guid(fsp);
2416 status = try_lease_upgrade(fsp, lck, client_guid, lease, granted);
2418 if (NT_STATUS_EQUAL(status, NT_STATUS_NOT_FOUND)) {
2419 status = grant_new_fsp_lease(
2420 fsp, lck, client_guid, lease, granted);
2426 static int map_lease_type_to_oplock(uint32_t lease_type)
2428 int result = NO_OPLOCK;
2430 switch (lease_type) {
2431 case SMB2_LEASE_READ|SMB2_LEASE_WRITE|SMB2_LEASE_HANDLE:
2432 result = BATCH_OPLOCK|EXCLUSIVE_OPLOCK;
2434 case SMB2_LEASE_READ|SMB2_LEASE_WRITE:
2435 result = EXCLUSIVE_OPLOCK;
2437 case SMB2_LEASE_READ|SMB2_LEASE_HANDLE:
2438 case SMB2_LEASE_READ:
2439 result = LEVEL_II_OPLOCK;
2446 struct delay_for_oplock_state {
2447 struct files_struct *fsp;
2448 const struct smb2_lease *lease;
2449 bool will_overwrite;
2450 uint32_t delay_mask;
2451 bool first_open_attempt;
2452 bool got_handle_lease;
2454 bool have_other_lease;
2455 uint32_t total_lease_types;
2459 static bool delay_for_oplock_fn(
2460 struct share_mode_entry *e,
2464 struct delay_for_oplock_state *state = private_data;
2465 struct files_struct *fsp = state->fsp;
2466 const struct smb2_lease *lease = state->lease;
2467 bool e_is_lease = (e->op_type == LEASE_OPLOCK);
2468 uint32_t e_lease_type = SMB2_LEASE_NONE;
2470 bool lease_is_breaking = false;
2475 if (lease != NULL) {
2476 bool our_lease = is_same_lease(fsp, e, lease);
2478 DBG_DEBUG("Ignoring our own lease\n");
2483 status = leases_db_get(
2487 &e_lease_type, /* current_state */
2489 NULL, /* breaking_to_requested */
2490 NULL, /* breaking_to_required */
2491 NULL, /* lease_version */
2495 * leases_db_get() can return NT_STATUS_NOT_FOUND
2496 * if the share_mode_entry e is stale and the
2497 * lease record was already removed. In this case return
2498 * false so the traverse continues.
2501 if (NT_STATUS_EQUAL(status, NT_STATUS_NOT_FOUND) &&
2502 share_entry_stale_pid(e))
2504 struct GUID_txt_buf guid_strbuf;
2505 struct file_id_buf file_id_strbuf;
2506 DBG_DEBUG("leases_db_get for client_guid [%s] "
2507 "lease_key [%"PRIu64"/%"PRIu64"] "
2508 "file_id [%s] failed for stale "
2509 "share_mode_entry\n",
2510 GUID_buf_string(&e->client_guid, &guid_strbuf),
2511 e->lease_key.data[0],
2512 e->lease_key.data[1],
2513 file_id_str_buf(fsp->file_id, &file_id_strbuf));
2516 if (!NT_STATUS_IS_OK(status)) {
2517 struct GUID_txt_buf guid_strbuf;
2518 struct file_id_buf file_id_strbuf;
2519 DBG_ERR("leases_db_get for client_guid [%s] "
2520 "lease_key [%"PRIu64"/%"PRIu64"] "
2521 "file_id [%s] failed: %s\n",
2522 GUID_buf_string(&e->client_guid, &guid_strbuf),
2523 e->lease_key.data[0],
2524 e->lease_key.data[1],
2525 file_id_str_buf(fsp->file_id, &file_id_strbuf),
2527 smb_panic("leases_db_get() failed");
2530 e_lease_type = get_lease_type(e, fsp->file_id);
2533 if (((e_lease_type & ~state->total_lease_types) != 0) &&
2534 !share_entry_stale_pid(e))
2536 state->total_lease_types |= e_lease_type;
2539 if (!state->got_handle_lease &&
2540 ((e_lease_type & SMB2_LEASE_HANDLE) != 0) &&
2541 !share_entry_stale_pid(e)) {
2542 state->got_handle_lease = true;
2545 if (!state->got_oplock &&
2546 (e->op_type != LEASE_OPLOCK) &&
2547 !share_entry_stale_pid(e)) {
2548 state->got_oplock = true;
2551 if (!state->have_other_lease &&
2552 !is_same_lease(fsp, e, lease) &&
2553 !share_entry_stale_pid(e)) {
2554 state->have_other_lease = true;
2557 if (e_is_lease && is_lease_stat_open(fsp->access_mask)) {
2561 break_to = e_lease_type & ~state->delay_mask;
2563 if (state->will_overwrite) {
2564 break_to &= ~(SMB2_LEASE_HANDLE|SMB2_LEASE_READ);
2567 DBG_DEBUG("e_lease_type %u, will_overwrite: %u\n",
2568 (unsigned)e_lease_type,
2569 (unsigned)state->will_overwrite);
2571 if ((e_lease_type & ~break_to) == 0) {
2572 if (lease_is_breaking) {
2573 state->delay = true;
2578 if (share_entry_stale_pid(e)) {
2582 if (state->will_overwrite) {
2584 * If we break anyway break to NONE directly.
2585 * Otherwise vfs_set_filelen() will trigger the
2588 break_to &= ~(SMB2_LEASE_READ|SMB2_LEASE_WRITE);
2593 * Oplocks only support breaking to R or NONE.
2595 break_to &= ~(SMB2_LEASE_HANDLE|SMB2_LEASE_WRITE);
2598 DBG_DEBUG("breaking from %d to %d\n",
2602 fsp->conn->sconn->msg_ctx, &fsp->file_id, e, break_to);
2603 if (e_lease_type & state->delay_mask) {
2604 state->delay = true;
2606 if (lease_is_breaking && !state->first_open_attempt) {
2607 state->delay = true;
2613 static NTSTATUS delay_for_oplock(files_struct *fsp,
2615 const struct smb2_lease *lease,
2616 struct share_mode_lock *lck,
2617 bool have_sharing_violation,
2618 uint32_t create_disposition,
2619 bool first_open_attempt,
2623 struct delay_for_oplock_state state = {
2626 .first_open_attempt = first_open_attempt,
2633 *poplock_type = NO_OPLOCK;
2636 if (fsp->fsp_flags.is_directory) {
2638 * No directory leases yet
2640 SMB_ASSERT(oplock_request == NO_OPLOCK);
2641 if (have_sharing_violation) {
2642 return NT_STATUS_SHARING_VIOLATION;
2644 return NT_STATUS_OK;
2647 if (oplock_request == LEASE_OPLOCK) {
2648 if (lease == NULL) {
2650 * The SMB2 layer should have checked this
2652 return NT_STATUS_INTERNAL_ERROR;
2655 requested = lease->lease_state;
2657 requested = map_oplock_to_lease_type(
2658 oplock_request & ~SAMBA_PRIVATE_OPLOCK_MASK);
2661 share_mode_flags_get(lck, NULL, NULL, &state.total_lease_types);
2663 if (is_oplock_stat_open(fsp->access_mask)) {
2667 state.delay_mask = have_sharing_violation ?
2668 SMB2_LEASE_HANDLE : SMB2_LEASE_WRITE;
2670 switch (create_disposition) {
2671 case FILE_SUPERSEDE:
2672 case FILE_OVERWRITE:
2673 case FILE_OVERWRITE_IF:
2674 state.will_overwrite = true;
2677 state.will_overwrite = false;
2681 state.total_lease_types = SMB2_LEASE_NONE;
2682 ok = share_mode_forall_entries(lck, delay_for_oplock_fn, &state);
2684 return NT_STATUS_INTERNAL_ERROR;
2688 return NT_STATUS_RETRY;
2692 if (have_sharing_violation) {
2693 return NT_STATUS_SHARING_VIOLATION;
2696 granted = requested;
2698 if (oplock_request == LEASE_OPLOCK) {
2699 if (lp_kernel_oplocks(SNUM(fsp->conn))) {
2700 DEBUG(10, ("No lease granted because kernel oplocks are enabled\n"));
2701 granted = SMB2_LEASE_NONE;
2703 if ((granted & (SMB2_LEASE_READ|SMB2_LEASE_WRITE)) == 0) {
2704 DEBUG(10, ("No read or write lease requested\n"));
2705 granted = SMB2_LEASE_NONE;
2707 if (granted == SMB2_LEASE_WRITE) {
2708 DEBUG(10, ("pure write lease requested\n"));
2709 granted = SMB2_LEASE_NONE;
2711 if (granted == (SMB2_LEASE_WRITE|SMB2_LEASE_HANDLE)) {
2712 DEBUG(10, ("write and handle lease requested\n"));
2713 granted = SMB2_LEASE_NONE;
2717 if (lp_locking(fsp->conn->params) && file_has_brlocks(fsp)) {
2718 DBG_DEBUG("file %s has byte range locks\n",
2720 granted &= ~SMB2_LEASE_READ;
2723 if (state.have_other_lease) {
2725 * Can grant only one writer
2727 granted &= ~SMB2_LEASE_WRITE;
2730 if ((granted & SMB2_LEASE_READ) && !(granted & SMB2_LEASE_WRITE)) {
2732 (global_client_caps & CAP_LEVEL_II_OPLOCKS) &&
2733 lp_level2_oplocks(SNUM(fsp->conn));
2735 if (!allow_level2) {
2736 granted = SMB2_LEASE_NONE;
2740 if (oplock_request == LEASE_OPLOCK) {
2741 if (state.got_oplock) {
2742 granted &= ~SMB2_LEASE_HANDLE;
2745 oplock_type = LEASE_OPLOCK;
2747 if (state.got_handle_lease) {
2748 granted = SMB2_LEASE_NONE;
2752 * Reflect possible downgrades from:
2753 * - map_lease_type_to_oplock() => "RH" to just LEVEL_II
2755 oplock_type = map_lease_type_to_oplock(granted);
2756 granted = map_oplock_to_lease_type(oplock_type);
2759 state.total_lease_types |= granted;
2762 uint32_t acc, sh, ls;
2763 share_mode_flags_get(lck, &acc, &sh, &ls);
2764 ls = state.total_lease_types;
2765 share_mode_flags_set(lck, acc, sh, ls, NULL);
2768 DBG_DEBUG("oplock type 0x%x granted (%s%s%s)(0x%x), on file %s, "
2769 "requested 0x%x (%s%s%s)(0x%x) => total (%s%s%s)(0x%x)\n",
2771 granted & SMB2_LEASE_READ ? "R":"",
2772 granted & SMB2_LEASE_WRITE ? "W":"",
2773 granted & SMB2_LEASE_HANDLE ? "H":"",
2777 requested & SMB2_LEASE_READ ? "R":"",
2778 requested & SMB2_LEASE_WRITE ? "W":"",
2779 requested & SMB2_LEASE_HANDLE ? "H":"",
2781 state.total_lease_types & SMB2_LEASE_READ ? "R":"",
2782 state.total_lease_types & SMB2_LEASE_WRITE ? "W":"",
2783 state.total_lease_types & SMB2_LEASE_HANDLE ? "H":"",
2784 state.total_lease_types);
2786 *poplock_type = oplock_type;
2787 *pgranted = granted;
2788 return NT_STATUS_OK;
2791 static NTSTATUS handle_share_mode_lease(
2793 struct share_mode_lock *lck,
2794 uint32_t create_disposition,
2795 uint32_t access_mask,
2796 uint32_t share_access,
2798 const struct smb2_lease *lease,
2799 bool first_open_attempt,
2803 bool sharing_violation = false;
2806 *poplock_type = NO_OPLOCK;
2809 status = open_mode_check(
2810 fsp->conn, fsp->file_id, lck, access_mask, share_access);
2811 if (NT_STATUS_EQUAL(status, NT_STATUS_SHARING_VIOLATION)) {
2812 sharing_violation = true;
2813 status = NT_STATUS_OK; /* handled later */
2816 if (!NT_STATUS_IS_OK(status)) {
2820 if (oplock_request == INTERNAL_OPEN_ONLY) {
2821 if (sharing_violation) {
2822 DBG_DEBUG("Sharing violation for internal open\n");
2823 return NT_STATUS_SHARING_VIOLATION;
2827 * Internal opens never do oplocks or leases. We don't
2828 * need to go through delay_for_oplock().
2830 return NT_STATUS_OK;
2833 status = delay_for_oplock(
2843 if (!NT_STATUS_IS_OK(status)) {
2847 return NT_STATUS_OK;
2850 static bool request_timed_out(struct smb_request *req, struct timeval timeout)
2852 struct timeval now, end_time;
2854 end_time = timeval_sum(&req->request_time, &timeout);
2855 return (timeval_compare(&end_time, &now) < 0);
2858 struct defer_open_state {
2859 struct smbXsrv_connection *xconn;
2863 static void defer_open_done(struct tevent_req *req);
2866 * Defer an open and watch a locking.tdb record
2868 * This defers an open that gets rescheduled once the locking.tdb record watch
2869 * is triggered by a change to the record.
2871 * It is used to defer opens that triggered an oplock break and for the SMB1
2872 * sharing violation delay.
2874 static void defer_open(struct share_mode_lock *lck,
2875 struct timeval timeout,
2876 struct smb_request *req,
2879 struct deferred_open_record *open_rec = NULL;
2880 struct timeval abs_timeout;
2881 struct defer_open_state *watch_state;
2882 struct tevent_req *watch_req;
2883 struct timeval_buf tvbuf1, tvbuf2;
2884 struct file_id_buf fbuf;
2887 abs_timeout = timeval_sum(&req->request_time, &timeout);
2889 DBG_DEBUG("request time [%s] timeout [%s] mid [%" PRIu64 "] "
2891 timeval_str_buf(&req->request_time, false, true, &tvbuf1),
2892 timeval_str_buf(&abs_timeout, false, true, &tvbuf2),
2894 file_id_str_buf(id, &fbuf));
2896 open_rec = talloc_zero(NULL, struct deferred_open_record);
2897 if (open_rec == NULL) {
2899 exit_server("talloc failed");
2902 watch_state = talloc(open_rec, struct defer_open_state);
2903 if (watch_state == NULL) {
2904 exit_server("talloc failed");
2906 watch_state->xconn = req->xconn;
2907 watch_state->mid = req->mid;
2909 DBG_DEBUG("deferring mid %" PRIu64 "\n", req->mid);
2911 watch_req = share_mode_watch_send(
2915 (struct server_id){0});
2916 if (watch_req == NULL) {
2917 exit_server("Could not watch share mode record");
2919 tevent_req_set_callback(watch_req, defer_open_done, watch_state);
2921 ok = tevent_req_set_endtime(watch_req, req->sconn->ev_ctx, abs_timeout);
2923 exit_server("tevent_req_set_endtime failed");
2926 ok = push_deferred_open_message_smb(req, timeout, id, open_rec);
2929 exit_server("push_deferred_open_message_smb failed");
2933 static void defer_open_done(struct tevent_req *req)
2935 struct defer_open_state *state = tevent_req_callback_data(
2936 req, struct defer_open_state);
2940 status = share_mode_watch_recv(req, NULL, NULL);
2942 if (!NT_STATUS_IS_OK(status)) {
2943 DEBUG(5, ("dbwrap_watched_watch_recv returned %s\n",
2944 nt_errstr(status)));
2946 * Even if it failed, retry anyway. TODO: We need a way to
2947 * tell a re-scheduled open about that error.
2951 DEBUG(10, ("scheduling mid %llu\n", (unsigned long long)state->mid));
2953 ret = schedule_deferred_open_message_smb(state->xconn, state->mid);
2959 * Actually attempt the kernel oplock polling open.
2962 static void poll_open_fn(struct tevent_context *ev,
2963 struct tevent_timer *te,
2964 struct timeval current_time,
2967 struct deferred_open_record *open_rec = talloc_get_type_abort(
2968 private_data, struct deferred_open_record);
2971 TALLOC_FREE(open_rec->watch_req);
2973 ok = schedule_deferred_open_message_smb(
2974 open_rec->xconn, open_rec->mid);
2976 exit_server("schedule_deferred_open_message_smb failed");
2978 DBG_DEBUG("timer fired. Retrying open !\n");
2981 static void poll_open_done(struct tevent_req *subreq);
2983 struct poll_open_setup_watcher_state {
2984 TALLOC_CTX *mem_ctx;
2985 struct tevent_context *ev_ctx;
2986 struct tevent_req *watch_req;
2989 static void poll_open_setup_watcher_fn(struct share_mode_lock *lck,
2992 struct poll_open_setup_watcher_state *state =
2993 (struct poll_open_setup_watcher_state *)private_data;
2995 if (!validate_oplock_types(lck)) {
2996 smb_panic("validate_oplock_types failed");
2999 state->watch_req = share_mode_watch_send(
3003 (struct server_id) {0});
3004 if (state->watch_req == NULL) {
3005 DBG_WARNING("share_mode_watch_send failed\n");
3011 * Reschedule an open for 1 second from now, if not timed out.
3013 static bool setup_poll_open(
3014 struct smb_request *req,
3015 const struct file_id *id,
3016 struct timeval max_timeout,
3017 struct timeval interval)
3019 static struct file_id zero_id = {};
3021 struct deferred_open_record *open_rec = NULL;
3022 struct timeval endtime, next_interval;
3023 struct file_id_buf ftmp;
3025 if (request_timed_out(req, max_timeout)) {
3029 open_rec = talloc_zero(NULL, struct deferred_open_record);
3030 if (open_rec == NULL) {
3031 DBG_WARNING("talloc failed\n");
3034 open_rec->xconn = req->xconn;
3035 open_rec->mid = req->mid;
3038 * Make sure open_rec->te does not come later than the
3039 * request's maximum endtime.
3042 endtime = timeval_sum(&req->request_time, &max_timeout);
3043 next_interval = timeval_current_ofs(interval.tv_sec, interval.tv_usec);
3044 next_interval = timeval_min(&endtime, &next_interval);
3046 open_rec->te = tevent_add_timer(
3052 if (open_rec->te == NULL) {
3053 DBG_WARNING("tevent_add_timer failed\n");
3054 TALLOC_FREE(open_rec);
3059 struct poll_open_setup_watcher_state wstate = {
3060 .mem_ctx = open_rec,
3061 .ev_ctx = req->sconn->ev_ctx,
3065 status = share_mode_do_locked_vfs_denied(*id,
3066 poll_open_setup_watcher_fn,
3068 if (NT_STATUS_IS_OK(status)) {
3069 if (wstate.watch_req == NULL) {
3070 DBG_WARNING("share_mode_watch_send failed\n");
3071 TALLOC_FREE(open_rec);
3074 open_rec->watch_req = wstate.watch_req;
3075 tevent_req_set_callback(open_rec->watch_req,
3078 } else if (!NT_STATUS_EQUAL(status, NT_STATUS_NOT_FOUND)) {
3079 DBG_WARNING("share_mode_do_locked_vfs_denied failed - %s\n",
3081 TALLOC_FREE(open_rec);
3088 ok = push_deferred_open_message_smb(req, max_timeout, *id, open_rec);
3090 DBG_WARNING("push_deferred_open_message_smb failed\n");
3091 TALLOC_FREE(open_rec);
3095 DBG_DEBUG("poll request time [%s] mid [%" PRIu64 "] file_id [%s]\n",
3096 timeval_string(talloc_tos(), &req->request_time, false),
3098 file_id_str_buf(*id, &ftmp));
3103 static void poll_open_done(struct tevent_req *subreq)
3105 struct deferred_open_record *open_rec = tevent_req_callback_data(
3106 subreq, struct deferred_open_record);
3110 status = share_mode_watch_recv(subreq, NULL, NULL);
3111 TALLOC_FREE(subreq);
3112 open_rec->watch_req = NULL;
3113 TALLOC_FREE(open_rec->te);
3115 DBG_DEBUG("dbwrap_watched_watch_recv returned %s\n",
3118 ok = schedule_deferred_open_message_smb(
3119 open_rec->xconn, open_rec->mid);
3121 exit_server("schedule_deferred_open_message_smb failed");
3125 bool defer_smb1_sharing_violation(struct smb_request *req)
3130 if (!lp_defer_sharing_violations()) {
3135 * Try every 200msec up to (by default) one second. To be
3136 * precise, according to behaviour note <247> in [MS-CIFS],
3137 * the server tries 5 times. But up to one second should be
3141 timeout_usecs = lp_parm_int(
3145 SHARING_VIOLATION_USEC_WAIT);
3147 ok = setup_poll_open(
3150 (struct timeval) { .tv_usec = timeout_usecs },
3151 (struct timeval) { .tv_usec = 200000 });
3155 /****************************************************************************
3156 On overwrite open ensure that the attributes match.
3157 ****************************************************************************/
3159 static bool open_match_attributes(connection_struct *conn,
3160 uint32_t old_dos_attr,
3161 uint32_t new_dos_attr,
3162 mode_t new_unx_mode,
3163 mode_t *returned_unx_mode)
3165 uint32_t noarch_old_dos_attr, noarch_new_dos_attr;
3167 noarch_old_dos_attr = (old_dos_attr & ~FILE_ATTRIBUTE_ARCHIVE);
3168 noarch_new_dos_attr = (new_dos_attr & ~FILE_ATTRIBUTE_ARCHIVE);
3170 if((noarch_old_dos_attr == 0 && noarch_new_dos_attr != 0) ||
3171 (noarch_old_dos_attr != 0 && ((noarch_old_dos_attr & noarch_new_dos_attr) == noarch_old_dos_attr))) {
3172 *returned_unx_mode = new_unx_mode;
3174 *returned_unx_mode = (mode_t)0;
3177 DEBUG(10,("open_match_attributes: old_dos_attr = 0x%x, "
3178 "new_dos_attr = 0x%x "
3179 "returned_unx_mode = 0%o\n",
3180 (unsigned int)old_dos_attr,
3181 (unsigned int)new_dos_attr,
3182 (unsigned int)*returned_unx_mode ));
3184 /* If we're mapping SYSTEM and HIDDEN ensure they match. */
3185 if (lp_map_system(SNUM(conn)) || lp_store_dos_attributes(SNUM(conn))) {
3186 if ((old_dos_attr & FILE_ATTRIBUTE_SYSTEM) &&
3187 !(new_dos_attr & FILE_ATTRIBUTE_SYSTEM)) {
3191 if (lp_map_hidden(SNUM(conn)) || lp_store_dos_attributes(SNUM(conn))) {
3192 if ((old_dos_attr & FILE_ATTRIBUTE_HIDDEN) &&
3193 !(new_dos_attr & FILE_ATTRIBUTE_HIDDEN)) {
3200 static void schedule_defer_open(struct share_mode_lock *lck,
3202 struct smb_request *req)
3204 /* This is a relative time, added to the absolute
3205 request_time value to get the absolute timeout time.
3206 Note that if this is the second or greater time we enter
3207 this codepath for this particular request mid then
3208 request_time is left as the absolute time of the *first*
3209 time this request mid was processed. This is what allows
3210 the request to eventually time out. */
3212 struct timeval timeout;
3214 /* Normally the smbd we asked should respond within
3215 * OPLOCK_BREAK_TIMEOUT seconds regardless of whether
3216 * the client did, give twice the timeout as a safety
3217 * measure here in case the other smbd is stuck
3218 * somewhere else. */
3220 timeout = timeval_set(OPLOCK_BREAK_TIMEOUT*2, 0);
3222 if (request_timed_out(req, timeout)) {
3226 defer_open(lck, timeout, req, id);
3229 /****************************************************************************
3230 Reschedule an open call that went asynchronous.
3231 ****************************************************************************/
3233 static void schedule_async_open_timer(struct tevent_context *ev,
3234 struct tevent_timer *te,
3235 struct timeval current_time,
3238 exit_server("async open timeout");
3241 static void schedule_async_open(struct smb_request *req)
3243 struct deferred_open_record *open_rec = NULL;
3244 struct timeval timeout = timeval_set(20, 0);
3247 if (request_timed_out(req, timeout)) {
3251 open_rec = talloc_zero(NULL, struct deferred_open_record);
3252 if (open_rec == NULL) {
3253 exit_server("deferred_open_record_create failed");
3255 open_rec->async_open = true;
3257 ok = push_deferred_open_message_smb(
3258 req, timeout, (struct file_id){0}, open_rec);
3260 exit_server("push_deferred_open_message_smb failed");
3263 open_rec->te = tevent_add_timer(req->sconn->ev_ctx,
3265 timeval_current_ofs(20, 0),
3266 schedule_async_open_timer,
3268 if (open_rec->te == NULL) {
3269 exit_server("tevent_add_timer failed");
3273 static NTSTATUS check_and_store_share_mode(
3274 struct files_struct *fsp,
3275 struct smb_request *req,
3276 struct share_mode_lock *lck,
3277 uint32_t create_disposition,
3278 uint32_t access_mask,
3279 uint32_t share_access,
3281 const struct smb2_lease *lease,
3282 bool first_open_attempt)
3285 int oplock_type = NO_OPLOCK;
3286 uint32_t granted_lease = 0;
3287 const struct smb2_lease_key *lease_key = NULL;
3288 bool delete_on_close;
3291 /* Get the types we need to examine. */
3292 if (!validate_oplock_types(lck)) {
3293 smb_panic("validate_oplock_types failed");
3296 delete_on_close = has_delete_on_close(lck, fsp->name_hash);
3297 if (delete_on_close) {
3298 return NT_STATUS_DELETE_PENDING;
3301 status = handle_share_mode_lease(fsp,
3311 if (NT_STATUS_EQUAL(status, NT_STATUS_RETRY)) {
3312 schedule_defer_open(lck, fsp->file_id, req);
3313 return NT_STATUS_SHARING_VIOLATION;
3315 if (!NT_STATUS_IS_OK(status)) {
3319 if (oplock_type == LEASE_OPLOCK) {
3320 lease_key = &lease->lease_key;
3323 share_mode_flags_restrict(lck, access_mask, share_access, 0);
3325 ok = set_share_mode(lck,
3327 get_current_uid(fsp->conn),
3334 return NT_STATUS_NO_MEMORY;
3337 if (oplock_type == LEASE_OPLOCK) {
3338 status = grant_fsp_lease(fsp, lck, lease, granted_lease);
3339 if (!NT_STATUS_IS_OK(status)) {
3340 del_share_mode(lck, fsp);
3344 DBG_DEBUG("lease_state=%d\n", fsp->lease->lease.lease_state);
3347 fsp->oplock_type = oplock_type;
3349 return NT_STATUS_OK;
3352 /****************************************************************************
3353 Work out what access_mask to use from what the client sent us.
3354 ****************************************************************************/
3356 static NTSTATUS smbd_calculate_maximum_allowed_access_fsp(
3357 struct files_struct *dirfsp,
3358 struct files_struct *fsp,
3360 uint32_t *p_access_mask)
3362 struct security_descriptor *sd = NULL;
3363 uint32_t access_granted = 0;
3367 /* Cope with symlinks */
3368 if (fsp == NULL || fsp_get_pathref_fd(fsp) == -1) {
3369 *p_access_mask = FILE_GENERIC_ALL;
3370 return NT_STATUS_OK;
3373 /* Cope with fake/printer fsp's. */
3374 if (fsp->fake_file_handle != NULL || fsp->print_file != NULL) {
3375 *p_access_mask = FILE_GENERIC_ALL;
3376 return NT_STATUS_OK;
3379 if (!use_privs && (get_current_uid(fsp->conn) == (uid_t)0)) {
3380 *p_access_mask |= FILE_GENERIC_ALL;
3381 return NT_STATUS_OK;
3384 status = SMB_VFS_FGET_NT_ACL(metadata_fsp(fsp),
3391 if (NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
3393 * File did not exist
3395 *p_access_mask = FILE_GENERIC_ALL;
3396 return NT_STATUS_OK;
3398 if (!NT_STATUS_IS_OK(status)) {
3399 DBG_ERR("Could not get acl on file %s: %s\n",
3406 * If we can access the path to this file, by
3407 * default we have FILE_READ_ATTRIBUTES from the
3408 * containing directory. See the section:
3409 * "Algorithm to Check Access to an Existing File"
3412 * se_file_access_check()
3413 * also takes care of owner WRITE_DAC and READ_CONTROL.
3415 status = se_file_access_check(sd,
3416 get_current_nttok(fsp->conn),
3418 (*p_access_mask & ~FILE_READ_ATTRIBUTES),
3423 if (!NT_STATUS_IS_OK(status)) {
3424 DBG_ERR("Status %s on file %s: "
3425 "when calculating maximum access\n",
3431 *p_access_mask = (access_granted | FILE_READ_ATTRIBUTES);
3433 if (!(access_granted & DELETE_ACCESS)) {
3434 if (can_delete_file_in_directory(fsp->conn,
3437 *p_access_mask |= DELETE_ACCESS;
3441 dosattrs = fdos_mode(fsp);
3442 if ((dosattrs & FILE_ATTRIBUTE_READONLY) || !CAN_WRITE(fsp->conn)) {
3443 *p_access_mask &= ~(FILE_GENERIC_WRITE | DELETE_ACCESS);
3446 return NT_STATUS_OK;
3449 NTSTATUS smbd_calculate_access_mask_fsp(struct files_struct *dirfsp,
3450 struct files_struct *fsp,
3452 uint32_t access_mask,
3453 uint32_t *access_mask_out)
3456 uint32_t orig_access_mask = access_mask;
3457 uint32_t rejected_share_access;
3459 if (access_mask & SEC_MASK_INVALID) {
3460 DBG_DEBUG("access_mask [%8x] contains invalid bits\n",
3462 return NT_STATUS_ACCESS_DENIED;
3466 * Convert GENERIC bits to specific bits.
3469 se_map_generic(&access_mask, &file_generic_mapping);
3471 /* Calculate MAXIMUM_ALLOWED_ACCESS if requested. */
3472 if (access_mask & MAXIMUM_ALLOWED_ACCESS) {
3474 status = smbd_calculate_maximum_allowed_access_fsp(
3480 if (!NT_STATUS_IS_OK(status)) {
3484 access_mask &= fsp->conn->share_access;
3487 rejected_share_access = access_mask & ~(fsp->conn->share_access);
3489 if (rejected_share_access) {
3490 DBG_INFO("Access denied on file %s: "
3491 "rejected by share access mask[0x%08X] "
3492 "orig[0x%08X] mapped[0x%08X] reject[0x%08X]\n",
3494 fsp->conn->share_access,
3495 orig_access_mask, access_mask,
3496 rejected_share_access);
3497 return NT_STATUS_ACCESS_DENIED;
3500 *access_mask_out = access_mask;
3501 return NT_STATUS_OK;
3504 /****************************************************************************
3505 Remove the deferred open entry under lock.
3506 ****************************************************************************/
3508 /****************************************************************************
3509 Return true if this is a state pointer to an asynchronous create.
3510 ****************************************************************************/
3512 bool is_deferred_open_async(const struct deferred_open_record *rec)
3514 return rec->async_open;
3517 static bool clear_ads(uint32_t create_disposition)
3521 switch (create_disposition) {
3522 case FILE_SUPERSEDE:
3523 case FILE_OVERWRITE_IF:
3524 case FILE_OVERWRITE:
3533 static int disposition_to_open_flags(uint32_t create_disposition)
3538 * Currently we're using FILE_SUPERSEDE as the same as
3539 * FILE_OVERWRITE_IF but they really are
3540 * different. FILE_SUPERSEDE deletes an existing file
3541 * (requiring delete access) then recreates it.
3544 switch (create_disposition) {
3545 case FILE_SUPERSEDE:
3546 case FILE_OVERWRITE_IF:
3548 * If file exists replace/overwrite. If file doesn't
3551 ret = O_CREAT|O_TRUNC;
3556 * If file exists open. If file doesn't exist error.
3561 case FILE_OVERWRITE:
3563 * If file exists overwrite. If file doesn't exist
3571 * If file exists error. If file doesn't exist create.
3573 ret = O_CREAT|O_EXCL;
3578 * If file exists open. If file doesn't exist create.
3586 static int calculate_open_access_flags(uint32_t access_mask,
3587 uint32_t private_flags,
3590 bool need_write, need_read;
3593 * Note that we ignore the append flag as append does not
3594 * mean the same thing under DOS and Unix.
3599 * Pave over the user requested mode and force O_RDONLY for the
3600 * file handle. Windows allows opening a VSS file with O_RDWR,
3601 * even though actual writes on the handle will fail.
3606 need_write = (access_mask & (FILE_WRITE_DATA | FILE_APPEND_DATA));
3611 /* DENY_DOS opens are always underlying read-write on the
3612 file handle, no matter what the requested access mask
3616 ((private_flags & NTCREATEX_FLAG_DENY_DOS) ||
3617 access_mask & (FILE_READ_ATTRIBUTES|FILE_READ_DATA|
3618 FILE_READ_EA|FILE_EXECUTE));
3626 struct open_ntcreate_lock_state {
3627 struct share_mode_entry_prepare_state prepare_state;
3628 struct files_struct *fsp;
3629 const char *object_type;
3630 struct smb_request *req;
3631 uint32_t create_disposition;
3632 uint32_t access_mask;
3633 uint32_t share_access;
3635 const struct smb2_lease *lease;
3636 bool first_open_attempt;
3639 struct timespec write_time;
3640 share_mode_entry_prepare_unlock_fn_t cleanup_fn;
3643 static void open_ntcreate_lock_add_entry(struct share_mode_lock *lck,
3647 struct open_ntcreate_lock_state *state =
3648 (struct open_ntcreate_lock_state *)private_data;
3651 * By default drop the g_lock again if we leave the
3654 *keep_locked = false;
3656 state->status = check_and_store_share_mode(state->fsp,
3659 state->create_disposition,
3661 state->share_access,
3662 state->oplock_request,
3664 state->first_open_attempt);
3665 if (!NT_STATUS_IS_OK(state->status)) {
3669 state->write_time = get_share_mode_write_time(lck);
3672 * keep the g_lock while existing the tdb chainlock,
3673 * we we're asked to, which mean we'll keep
3674 * the share_mode_lock during object creation,
3675 * or setting delete on close.
3677 *keep_locked = state->keep_locked;
3680 static void open_ntcreate_lock_cleanup_oplock(struct share_mode_lock *lck,
3683 struct open_ntcreate_lock_state *state =
3684 (struct open_ntcreate_lock_state *)private_data;
3687 ok = remove_share_oplock(lck, state->fsp);
3689 DBG_ERR("Could not remove oplock for %s %s\n",
3690 state->object_type, fsp_str_dbg(state->fsp));
3694 static void open_ntcreate_lock_cleanup_entry(struct share_mode_lock *lck,
3697 struct open_ntcreate_lock_state *state =
3698 (struct open_ntcreate_lock_state *)private_data;
3701 ok = del_share_mode(lck, state->fsp);
3703 DBG_ERR("Could not delete share entry for %s %s\n",
3704 state->object_type, fsp_str_dbg(state->fsp));
3708 static void possibly_set_archive(struct connection_struct *conn,
3709 struct files_struct *fsp,
3710 struct smb_filename *smb_fname,
3711 struct smb_filename *parent_dir_fname,
3716 bool set_archive = false;
3719 if (info == FILE_WAS_OPENED) {
3723 /* Overwritten files should be initially set as archive */
3724 if ((info == FILE_WAS_OVERWRITTEN && lp_map_archive(SNUM(conn)))) {
3726 } else if (lp_store_dos_attributes(SNUM(conn))) {
3733 ret = file_set_dosmode(conn,
3735 dosattrs | FILE_ATTRIBUTE_ARCHIVE,
3741 *unx_mode = smb_fname->st.st_ex_mode;
3744 /****************************************************************************
3745 Open a file with a share mode. Passed in an already created files_struct *.
3746 ****************************************************************************/
3748 static NTSTATUS open_file_ntcreate(connection_struct *conn,
3749 struct smb_request *req,
3750 uint32_t access_mask, /* access bits (FILE_READ_DATA etc.) */
3751 uint32_t share_access, /* share constants (FILE_SHARE_READ etc) */
3752 uint32_t create_disposition, /* FILE_OPEN_IF etc. */
3753 uint32_t create_options, /* options such as delete on close. */
3754 uint32_t new_dos_attributes, /* attributes used for new file. */
3755 int oplock_request, /* internal Samba oplock codes. */
3756 const struct smb2_lease *lease,
3757 /* Information (FILE_EXISTS etc.) */
3758 uint32_t private_flags, /* Samba specific flags. */
3759 struct smb_filename *parent_dir_fname, /* parent. */
3760 struct smb_filename *smb_fname_atname, /* atname relative to parent. */
3764 struct smb_filename *smb_fname = fsp->fsp_name;
3766 bool file_existed = VALID_STAT(smb_fname->st);
3767 bool def_acl = False;
3768 bool posix_open = False;
3769 bool new_file_created = False;
3770 bool first_open_attempt = true;
3771 bool is_twrp = (smb_fname_atname->twrp != 0);
3772 NTSTATUS fsp_open = NT_STATUS_ACCESS_DENIED;
3773 mode_t new_unx_mode = (mode_t)0;
3774 mode_t unx_mode = (mode_t)0;
3776 uint32_t existing_dos_attributes = 0;
3777 struct open_ntcreate_lock_state lck_state = {};
3778 bool keep_locked = false;
3779 uint32_t open_access_mask = access_mask;
3781 SMB_STRUCT_STAT saved_stat = smb_fname->st;
3782 struct timespec old_write_time;
3783 bool setup_poll = false;
3786 if (conn->printer) {
3788 * Printers are handled completely differently.
3789 * Most of the passed parameters are ignored.
3793 *pinfo = FILE_WAS_CREATED;
3796 DBG_DEBUG("printer open fname=%s\n",
3797 smb_fname_str_dbg(smb_fname));
3800 DBG_ERR("printer open without an SMB request!\n");
3801 return NT_STATUS_INTERNAL_ERROR;
3804 return print_spool_open(fsp, smb_fname->base_name,
3808 if (new_dos_attributes & FILE_FLAG_POSIX_SEMANTICS) {
3810 unx_mode = (mode_t)(new_dos_attributes & ~FILE_FLAG_POSIX_SEMANTICS);
3811 new_dos_attributes = 0;
3813 /* Windows allows a new file to be created and
3814 silently removes a FILE_ATTRIBUTE_DIRECTORY
3815 sent by the client. Do the same. */
3817 new_dos_attributes &= ~FILE_ATTRIBUTE_DIRECTORY;
3819 /* We add FILE_ATTRIBUTE_ARCHIVE to this as this mode is only used if the file is
3821 unx_mode = unix_mode(
3823 new_dos_attributes | FILE_ATTRIBUTE_ARCHIVE,
3825 parent_dir_fname->fsp);
3828 DEBUG(10, ("open_file_ntcreate: fname=%s, dos_attrs=0x%x "
3829 "access_mask=0x%x share_access=0x%x "
3830 "create_disposition = 0x%x create_options=0x%x "
3831 "unix mode=0%o oplock_request=%d private_flags = 0x%x\n",
3832 smb_fname_str_dbg(smb_fname), new_dos_attributes,
3833 access_mask, share_access, create_disposition,
3834 create_options, (unsigned int)unx_mode, oplock_request,
3835 (unsigned int)private_flags));
3838 /* Ensure req == NULL means INTERNAL_OPEN_ONLY */
3839 SMB_ASSERT(oplock_request == INTERNAL_OPEN_ONLY);
3841 /* And req != NULL means no INTERNAL_OPEN_ONLY */
3842 SMB_ASSERT(((oplock_request & INTERNAL_OPEN_ONLY) == 0));
3846 * Only non-internal opens can be deferred at all
3850 struct deferred_open_record *open_rec;
3851 if (get_deferred_open_message_state(req, NULL, &open_rec)) {
3853 /* If it was an async create retry, the file
3856 if (is_deferred_open_async(open_rec)) {
3857 SET_STAT_INVALID(smb_fname->st);
3858 file_existed = false;
3861 /* Ensure we don't reprocess this message. */
3862 remove_deferred_open_message_smb(req->xconn, req->mid);
3864 first_open_attempt = false;
3869 new_dos_attributes &= SAMBA_ATTRIBUTES_MASK;
3872 * Only use stored DOS attributes for checks
3873 * against requested attributes (below via
3874 * open_match_attributes()), cf bug #11992
3875 * for details. -slow
3879 status = SMB_VFS_FGET_DOS_ATTRIBUTES(
3881 metadata_fsp(smb_fname->fsp),
3883 if (NT_STATUS_IS_OK(status)) {
3884 existing_dos_attributes = attr;
3889 /* ignore any oplock requests if oplocks are disabled */
3890 if (!lp_oplocks(SNUM(conn)) ||
3891 IS_VETO_OPLOCK_PATH(conn, smb_fname->base_name)) {
3892 /* Mask off everything except the private Samba bits. */
3893 oplock_request &= SAMBA_PRIVATE_OPLOCK_MASK;
3896 /* this is for OS/2 long file names - say we don't support them */
3897 if (req != NULL && !req->posix_pathnames &&
3898 strstr(smb_fname->base_name,".+,;=[].")) {
3899 /* OS/2 Workplace shell fix may be main code stream in a later
3901 DEBUG(5,("open_file_ntcreate: OS/2 long filenames are not "
3903 if (use_nt_status()) {
3904 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3906 return NT_STATUS_DOS(ERRDOS, ERRcannotopen);
3909 switch( create_disposition ) {
3911 /* If file exists open. If file doesn't exist error. */
3912 if (!file_existed) {
3913 DEBUG(5,("open_file_ntcreate: FILE_OPEN "
3914 "requested for file %s and file "
3916 smb_fname_str_dbg(smb_fname)));
3917 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3921 case FILE_OVERWRITE:
3922 /* If file exists overwrite. If file doesn't exist
3924 if (!file_existed) {
3925 DEBUG(5,("open_file_ntcreate: FILE_OVERWRITE "
3926 "requested for file %s and file "
3928 smb_fname_str_dbg(smb_fname) ));
3929 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3932 return NT_STATUS_MEDIA_WRITE_PROTECTED;
3937 /* If file exists error. If file doesn't exist
3940 DEBUG(5,("open_file_ntcreate: FILE_CREATE "
3941 "requested for file %s and file "
3942 "already exists.\n",
3943 smb_fname_str_dbg(smb_fname)));
3944 if (S_ISDIR(smb_fname->st.st_ex_mode)) {
3945 return NT_STATUS_FILE_IS_A_DIRECTORY;
3947 return NT_STATUS_OBJECT_NAME_COLLISION;
3950 return NT_STATUS_MEDIA_WRITE_PROTECTED;
3954 case FILE_SUPERSEDE:
3955 case FILE_OVERWRITE_IF:
3957 return NT_STATUS_MEDIA_WRITE_PROTECTED;
3962 if (!file_existed) {
3963 return NT_STATUS_MEDIA_WRITE_PROTECTED;
3965 create_disposition = FILE_OPEN;
3969 return NT_STATUS_INVALID_PARAMETER;
3972 flags = disposition_to_open_flags(create_disposition);
3974 /* We only care about matching attributes on file exists and
3977 if (!posix_open && file_existed &&
3978 ((create_disposition == FILE_OVERWRITE) ||
3979 (create_disposition == FILE_OVERWRITE_IF))) {
3980 if (!open_match_attributes(conn, existing_dos_attributes,
3982 unx_mode, &new_unx_mode)) {
3983 DEBUG(5,("open_file_ntcreate: attributes mismatch "
3984 "for file %s (%x %x) (0%o, 0%o)\n",
3985 smb_fname_str_dbg(smb_fname),
3986 existing_dos_attributes,
3988 (unsigned int)smb_fname->st.st_ex_mode,
3989 (unsigned int)unx_mode ));
3990 return NT_STATUS_ACCESS_DENIED;
3994 status = smbd_calculate_access_mask_fsp(parent_dir_fname->fsp,
3999 if (!NT_STATUS_IS_OK(status)) {
4000 DBG_DEBUG("smbd_calculate_access_mask_fsp "
4001 "on file %s returned %s\n",
4002 smb_fname_str_dbg(smb_fname),
4007 open_access_mask = access_mask;
4009 if (flags & O_TRUNC) {
4010 open_access_mask |= FILE_WRITE_DATA; /* This will cause oplock breaks. */
4015 * stat opens on existing files don't get oplocks.
4016 * They can get leases.
4018 * Note that we check for stat open on the *open_access_mask*,
4019 * i.e. the access mask we actually used to do the open,
4020 * not the one the client asked for (which is in
4021 * fsp->access_mask). This is due to the fact that
4022 * FILE_OVERWRITE and FILE_OVERWRITE_IF add in O_TRUNC,
4023 * which adds FILE_WRITE_DATA to open_access_mask.
4025 if (is_oplock_stat_open(open_access_mask) && lease == NULL) {
4026 oplock_request = NO_OPLOCK;
4030 DEBUG(10, ("open_file_ntcreate: fname=%s, after mapping "
4031 "access_mask=0x%x\n", smb_fname_str_dbg(smb_fname),
4035 * Note that we ignore the append flag as append does not
4036 * mean the same thing under DOS and Unix.
4039 flags |= calculate_open_access_flags(access_mask,
4044 * Currently we only look at FILE_WRITE_THROUGH for create options.
4048 if ((create_options & FILE_WRITE_THROUGH) && lp_strict_sync(SNUM(conn))) {
4053 if (posix_open && (access_mask & FILE_APPEND_DATA)) {
4057 if (!posix_open && !CAN_WRITE(conn)) {
4059 * We should really return a permission denied error if either
4060 * O_CREAT or O_TRUNC are set, but for compatibility with
4061 * older versions of Samba we just AND them out.
4063 flags &= ~(O_CREAT | O_TRUNC);
4067 * With kernel oplocks the open breaking an oplock
4068 * blocks until the oplock holder has given up the
4069 * oplock or closed the file. We prevent this by always
4070 * trying to open the file with O_NONBLOCK (see "man
4073 * If a process that doesn't use the smbd open files
4074 * database or communication methods holds a kernel
4075 * oplock we must periodically poll for available open
4078 flags |= O_NONBLOCK;
4081 * Ensure we can't write on a read-only share or file.
4084 if (((flags & O_ACCMODE) != O_RDONLY) && file_existed &&
4085 (!CAN_WRITE(conn) ||
4086 (existing_dos_attributes & FILE_ATTRIBUTE_READONLY))) {
4087 DEBUG(5,("open_file_ntcreate: write access requested for "
4088 "file %s on read only %s\n",
4089 smb_fname_str_dbg(smb_fname),
4090 !CAN_WRITE(conn) ? "share" : "file" ));
4091 return NT_STATUS_ACCESS_DENIED;
4094 if (VALID_STAT(smb_fname->st)) {
4096 * Only try and create a file id before open
4097 * for an existing file. For a file being created
4098 * this won't do anything useful until the file
4099 * exists and has a valid stat struct.
4101 fsp->file_id = vfs_file_id_from_sbuf(conn, &smb_fname->st);
4103 fh_set_private_options(fsp->fh, private_flags);
4104 fsp->access_mask = open_access_mask; /* We change this to the
4105 * requested access_mask after
4106 * the open is done. */
4108 fsp->posix_flags |= FSP_POSIX_FLAGS_ALL;
4111 if ((create_options & FILE_DELETE_ON_CLOSE) && (flags & O_CREAT) &&
4113 /* Delete on close semantics for new files. */
4114 status = can_set_delete_on_close(fsp,
4115 new_dos_attributes);
4116 if (!NT_STATUS_IS_OK(status)) {
4123 * Ensure we pay attention to default ACLs on directories if required.
4126 if ((flags & O_CREAT) && lp_inherit_acls(SNUM(conn)) &&
4127 (def_acl = directory_has_default_acl_fsp(parent_dir_fname->fsp))) {
4128 unx_mode = (0777 & lp_create_mask(SNUM(conn)));
4132 ("calling open_file with flags=0x%X mode=0%o, "
4133 "access_mask = 0x%x, open_access_mask = 0x%x\n",
4134 (unsigned int)flags,
4135 (unsigned int)unx_mode,
4136 (unsigned int)access_mask,
4137 (unsigned int)open_access_mask));
4140 struct vfs_open_how how = {
4145 if (create_options & FILE_OPEN_FOR_BACKUP_INTENT) {
4146 how.resolve |= VFS_OPEN_HOW_WITH_BACKUP_INTENT;
4149 fsp_open = open_file(req,
4150 parent_dir_fname->fsp,
4159 if (NT_STATUS_EQUAL(fsp_open, NT_STATUS_NETWORK_BUSY)) {
4160 if (file_existed && S_ISFIFO(fsp->fsp_name->st.st_ex_mode)) {
4161 DEBUG(10, ("FIFO busy\n"));
4162 return NT_STATUS_NETWORK_BUSY;
4165 DEBUG(10, ("Internal open busy\n"));
4166 return NT_STATUS_NETWORK_BUSY;
4169 * This handles the kernel oplock case:
4171 * the file has an active kernel oplock and the open() returned
4172 * EWOULDBLOCK/EAGAIN which maps to NETWORK_BUSY.
4174 * "Samba locking.tdb oplocks" are handled below after acquiring
4175 * the sharemode lock with get_share_mode_lock().
4180 if (NT_STATUS_EQUAL(fsp_open, NT_STATUS_RETRY)) {
4182 * EINTR from the open(2) syscall. Just setup a retry
4183 * in a bit. We can't use the sys_write() tight retry
4184 * loop here, as we might have to actually deal with
4185 * lease-break signals to avoid a deadlock.
4192 * Retry once a second. If there's a share_mode_lock
4193 * around, also wait for it in case it was smbd
4194 * holding that kernel oplock that can quickly tell us
4195 * the oplock got removed.
4201 timeval_set(OPLOCK_BREAK_TIMEOUT*2, 0),
4204 return NT_STATUS_SHARING_VIOLATION;
4207 if (!NT_STATUS_IS_OK(fsp_open)) {
4208 bool wait_for_aio = NT_STATUS_EQUAL(
4209 fsp_open, NT_STATUS_MORE_PROCESSING_REQUIRED);
4211 schedule_async_open(req);
4216 if (new_file_created) {
4218 * As we atomically create using O_CREAT|O_EXCL,
4219 * then if new_file_created is true, then
4220 * file_existed *MUST* have been false (even
4221 * if the file was previously detected as being
4224 file_existed = false;
4227 if (file_existed && !check_same_dev_ino(&saved_stat, &smb_fname->st)) {
4229 * The file did exist, but some other (local or NFS)
4230 * process either renamed/unlinked and re-created the
4231 * file with different dev/ino after we walked the path,
4232 * but before we did the open. We could retry the
4233 * open but it's a rare enough case it's easier to
4234 * just fail the open to prevent creating any problems
4235 * in the open file db having the wrong dev/ino key.
4238 DBG_WARNING("file %s - dev/ino mismatch. "
4239 "Old (dev=%ju, ino=%ju). "
4240 "New (dev=%ju, ino=%ju). Failing open "
4241 "with NT_STATUS_ACCESS_DENIED.\n",
4242 smb_fname_str_dbg(smb_fname),
4243 (uintmax_t)saved_stat.st_ex_dev,
4244 (uintmax_t)saved_stat.st_ex_ino,
4245 (uintmax_t)smb_fname->st.st_ex_dev,
4246 (uintmax_t)smb_fname->st.st_ex_ino);
4247 return NT_STATUS_ACCESS_DENIED;
4250 old_write_time = smb_fname->st.st_ex_mtime;
4253 * Deal with the race condition where two smbd's detect the
4254 * file doesn't exist and do the create at the same time. One
4255 * of them will win and set a share mode, the other (ie. this
4256 * one) should check if the requested share mode for this
4257 * create is allowed.
4261 * Now the file exists and fsp is successfully opened,
4262 * fsp->dev and fsp->inode are valid and should replace the
4263 * dev=0,inode=0 from a non existent file. Spotted by
4264 * Nadav Danieli <nadavd@exanet.com>. JRA.
4267 if (new_file_created) {
4268 info = FILE_WAS_CREATED;
4270 if (flags & O_TRUNC) {
4271 info = FILE_WAS_OVERWRITTEN;
4273 info = FILE_WAS_OPENED;
4278 * If we created a new file, overwrite an existing one
4279 * or going to delete it later, we should keep
4280 * the share_mode_lock (g_lock) until we call
4281 * share_mode_entry_prepare_unlock()
4283 if (info != FILE_WAS_OPENED) {
4285 } else if (create_options & FILE_DELETE_ON_CLOSE) {
4289 lck_state = (struct open_ntcreate_lock_state) {
4291 .object_type = "file",
4293 .create_disposition = create_disposition,
4294 .access_mask = access_mask,
4295 .share_access = share_access,
4296 .oplock_request = oplock_request,
4298 .first_open_attempt = first_open_attempt,
4299 .keep_locked = keep_locked,
4302 status = share_mode_entry_prepare_lock_add(&lck_state.prepare_state,
4307 open_ntcreate_lock_add_entry,
4309 if (!NT_STATUS_IS_OK(status)) {
4310 DBG_ERR("share_mode_entry_prepare_lock_add() failed for %s - %s\n",
4311 smb_fname_str_dbg(smb_fname), nt_errstr(status));
4316 status = lck_state.status;
4317 if (!NT_STATUS_IS_OK(status)) {
4323 * From here we need to use 'goto unlock;' instead of return !!!
4326 if (fsp->oplock_type != NO_OPLOCK && fsp->oplock_type != LEASE_OPLOCK) {
4328 * Now ask for kernel oplocks
4329 * and cleanup on failure.
4331 status = set_file_oplock(fsp);
4332 if (!NT_STATUS_IS_OK(status)) {
4334 * Could not get the kernel oplock
4336 lck_state.cleanup_fn =
4337 open_ntcreate_lock_cleanup_oplock;
4338 fsp->oplock_type = NO_OPLOCK;
4342 /* Should we atomically (to the client at least) truncate ? */
4343 if ((!new_file_created) && (flags & O_TRUNC) &&
4344 (S_ISREG(fsp->fsp_name->st.st_ex_mode))) {
4347 ret = SMB_VFS_FTRUNCATE(fsp, 0);
4349 status = map_nt_error_from_unix(errno);
4350 lck_state.cleanup_fn =
4351 open_ntcreate_lock_cleanup_entry;
4354 notify_fname(fsp->conn, NOTIFY_ACTION_MODIFIED,
4355 FILE_NOTIFY_CHANGE_SIZE
4356 | FILE_NOTIFY_CHANGE_ATTRIBUTES,
4357 fsp->fsp_name->base_name);
4361 * We have the share entry *locked*.....
4364 /* Delete streams if create_disposition requires it */
4365 if (!new_file_created &&
4366 clear_ads(create_disposition) &&
4367 !fsp_is_alternate_stream(fsp)) {
4368 status = delete_all_streams(conn, smb_fname);
4369 if (!NT_STATUS_IS_OK(status)) {
4370 lck_state.cleanup_fn =
4371 open_ntcreate_lock_cleanup_entry;
4376 if (!fsp->fsp_flags.is_pathref &&
4377 fsp_get_io_fd(fsp) != -1 &&
4378 lp_kernel_share_modes(SNUM(conn)))
4382 * Beware: streams implementing VFS modules may
4383 * implement streams in a way that fsp will have the
4384 * basefile open in the fsp fd, so lacking a distinct
4385 * fd for the stream the file-system sharemode will
4386 * apply on the basefile which is wrong. The actual
4387 * check is deferred to the VFS module implementing
4388 * the file-system sharemode call.
4390 ret = SMB_VFS_FILESYSTEM_SHAREMODE(fsp,
4394 status = NT_STATUS_SHARING_VIOLATION;
4395 lck_state.cleanup_fn =
4396 open_ntcreate_lock_cleanup_entry;
4400 fsp->fsp_flags.kernel_share_modes_taken = true;
4404 * At this point onwards, we can guarantee that the share entry
4405 * is locked, whether we created the file or not, and that the
4406 * deny mode is compatible with all current opens.
4410 * According to Samba4, SEC_FILE_READ_ATTRIBUTE is always granted,
4411 * but we don't have to store this - just ignore it on access check.
4413 if (conn->sconn->using_smb2) {
4415 * SMB2 doesn't return it (according to Microsoft tests).
4416 * Test Case: TestSuite_ScenarioNo009GrantedAccessTestS0
4417 * File created with access = 0x7 (Read, Write, Delete)
4418 * Query Info on file returns 0x87 (Read, Write, Delete, Read Attributes)
4420 fsp->access_mask = access_mask;
4422 /* But SMB1 does. */
4423 fsp->access_mask = access_mask | FILE_READ_ATTRIBUTES;
4430 /* Handle strange delete on close create semantics. */
4431 if (create_options & FILE_DELETE_ON_CLOSE) {
4432 if (!new_file_created) {
4433 status = can_set_delete_on_close(fsp,
4434 existing_dos_attributes);
4436 if (!NT_STATUS_IS_OK(status)) {
4437 /* Remember to delete the mode we just added. */
4438 lck_state.cleanup_fn =
4439 open_ntcreate_lock_cleanup_entry;
4443 /* Note that here we set the *initial* delete on close flag,
4444 not the regular one. The magic gets handled in close. */
4445 fsp->fsp_flags.initial_delete_on_close = true;
4448 possibly_set_archive(conn,
4454 &smb_fname->st.st_ex_mode);
4456 /* Determine sparse flag. */
4458 /* POSIX opens are sparse by default. */
4459 fsp->fsp_flags.is_sparse = true;
4461 fsp->fsp_flags.is_sparse =
4462 (existing_dos_attributes & FILE_ATTRIBUTE_SPARSE);
4466 * Take care of inherited ACLs on created files - if default ACL not
4470 if (!posix_open && new_file_created && !def_acl) {
4471 if (unx_mode != smb_fname->st.st_ex_mode) {
4472 int ret = SMB_VFS_FCHMOD(fsp, unx_mode);
4474 DBG_INFO("failed to reset "
4475 "attributes of file %s to 0%o\n",
4476 smb_fname_str_dbg(smb_fname),
4477 (unsigned int)unx_mode);
4481 } else if (new_unx_mode) {
4483 * We only get here in the case of:
4485 * a). Not a POSIX open.
4486 * b). File already existed.
4487 * c). File was overwritten.
4488 * d). Requested DOS attributes didn't match
4489 * the DOS attributes on the existing file.
4491 * In that case new_unx_mode has been set
4492 * equal to the calculated mode (including
4493 * possible inheritance of the mode from the
4494 * containing directory).
4496 * Note this mode was calculated with the
4497 * DOS attribute FILE_ATTRIBUTE_ARCHIVE added,
4498 * so the mode change here is suitable for
4499 * an overwritten file.
4502 if (new_unx_mode != smb_fname->st.st_ex_mode) {
4503 int ret = SMB_VFS_FCHMOD(fsp, new_unx_mode);
4505 DBG_INFO("failed to reset "
4506 "attributes of file %s to 0%o\n",
4507 smb_fname_str_dbg(smb_fname),
4508 (unsigned int)new_unx_mode);
4514 * Deal with other opens having a modified write time.
4516 if (fsp_getinfo_ask_sharemode(fsp) &&
4517 !is_omit_timespec(&lck_state.write_time))
4519 update_stat_ex_mtime(&fsp->fsp_name->st, lck_state.write_time);
4522 status = NT_STATUS_OK;
4525 ulstatus = share_mode_entry_prepare_unlock(&lck_state.prepare_state,
4526 lck_state.cleanup_fn,
4528 if (!NT_STATUS_IS_OK(ulstatus)) {
4529 DBG_ERR("share_mode_entry_prepare_unlock() failed for %s - %s\n",
4530 smb_fname_str_dbg(smb_fname), nt_errstr(ulstatus));
4531 smb_panic("share_mode_entry_prepare_unlock() failed!");
4534 if (!NT_STATUS_IS_OK(status)) {
4539 return NT_STATUS_OK;
4542 static NTSTATUS mkdir_internal(connection_struct *conn,
4543 struct smb_filename *parent_dir_fname, /* parent. */
4544 struct smb_filename *smb_fname_atname, /* atname relative to parent. */
4545 struct smb_filename *smb_dname, /* full pathname from root of share. */
4546 uint32_t file_attributes,
4547 struct files_struct *fsp)
4549 const struct loadparm_substitution *lp_sub =
4550 loadparm_s3_global_substitution();
4553 bool posix_open = false;
4554 bool need_re_stat = false;
4555 uint32_t access_mask = SEC_DIR_ADD_SUBDIR;
4556 struct vfs_open_how how = { .flags = O_RDONLY|O_DIRECTORY, };
4559 if (!CAN_WRITE(conn) || (access_mask & ~(conn->share_access))) {
4560 DEBUG(5,("mkdir_internal: failing share access "
4561 "%s\n", lp_servicename(talloc_tos(), lp_sub, SNUM(conn))));
4562 return NT_STATUS_ACCESS_DENIED;
4565 if (file_attributes & FILE_FLAG_POSIX_SEMANTICS) {
4567 mode = (mode_t)(file_attributes & ~FILE_FLAG_POSIX_SEMANTICS);
4569 mode = unix_mode(conn,
4570 FILE_ATTRIBUTE_DIRECTORY,
4572 parent_dir_fname->fsp);
4575 status = check_parent_access_fsp(parent_dir_fname->fsp, access_mask);
4576 if(!NT_STATUS_IS_OK(status)) {
4577 DBG_INFO("check_parent_access_fsp "
4578 "on directory %s for path %s returned %s\n",
4579 smb_fname_str_dbg(parent_dir_fname),
4580 smb_dname->base_name,
4585 if (lp_inherit_acls(SNUM(conn))) {
4586 if (directory_has_default_acl_fsp(parent_dir_fname->fsp)) {
4587 mode = (0777 & lp_directory_mask(SNUM(conn)));
4591 ret = SMB_VFS_MKDIRAT(conn,
4592 parent_dir_fname->fsp,
4596 return map_nt_error_from_unix(errno);
4600 * Make this a pathref fsp for now. open_directory() will reopen as a
4603 fsp->fsp_flags.is_pathref = true;
4605 status = fd_openat(parent_dir_fname->fsp, smb_fname_atname, fsp, &how);
4606 if (!NT_STATUS_IS_OK(status)) {
4610 /* Ensure we're checking for a symlink here.... */
4611 /* We don't want to get caught by a symlink racer. */
4613 status = vfs_stat_fsp(fsp);
4614 if (!NT_STATUS_IS_OK(status)) {
4615 DEBUG(2, ("Could not stat directory '%s' just created: %s\n",
4616 smb_fname_str_dbg(smb_dname), nt_errstr(status)));
4620 if (!S_ISDIR(smb_dname->st.st_ex_mode)) {
4621 DEBUG(0, ("Directory '%s' just created is not a directory !\n",
4622 smb_fname_str_dbg(smb_dname)));
4623 return NT_STATUS_NOT_A_DIRECTORY;
4626 if (lp_store_dos_attributes(SNUM(conn))) {
4627 file_set_dosmode(conn,
4629 file_attributes | FILE_ATTRIBUTE_DIRECTORY,
4634 if (lp_inherit_permissions(SNUM(conn))) {
4635 inherit_access_posix_acl(conn, parent_dir_fname->fsp,
4637 need_re_stat = true;
4642 * Check if high bits should have been set,
4643 * then (if bits are missing): add them.
4644 * Consider bits automagically set by UNIX, i.e. SGID bit from parent
4647 if ((mode & ~(S_IRWXU|S_IRWXG|S_IRWXO)) &&
4648 (mode & ~smb_dname->st.st_ex_mode)) {
4650 (smb_dname->st.st_ex_mode |
4651 (mode & ~smb_dname->st.st_ex_mode)));
4652 need_re_stat = true;
4656 /* Change the owner if required. */
4657 if (lp_inherit_owner(SNUM(conn)) != INHERIT_OWNER_NO) {
4658 change_dir_owner_to_parent_fsp(parent_dir_fname->fsp,
4660 need_re_stat = true;
4664 status = vfs_stat_fsp(fsp);
4665 if (!NT_STATUS_IS_OK(status)) {
4666 DEBUG(2, ("Could not stat directory '%s' just created: %s\n",
4667 smb_fname_str_dbg(smb_dname), nt_errstr(status)));
4672 notify_fname(conn, NOTIFY_ACTION_ADDED, FILE_NOTIFY_CHANGE_DIR_NAME,
4673 smb_dname->base_name);
4675 return NT_STATUS_OK;
4678 /****************************************************************************
4679 Open a directory from an NT SMB call.
4680 ****************************************************************************/
4682 static NTSTATUS open_directory(connection_struct *conn,
4683 struct smb_request *req,
4684 uint32_t access_mask,
4685 uint32_t share_access,
4686 uint32_t create_disposition,
4687 uint32_t create_options,
4688 uint32_t file_attributes,
4689 struct smb_filename *parent_dir_fname,
4690 struct smb_filename *smb_fname_atname,
4692 struct files_struct *fsp)
4694 struct smb_filename *smb_dname = fsp->fsp_name;
4695 bool dir_existed = VALID_STAT(smb_dname->st);
4696 struct open_ntcreate_lock_state lck_state = {};
4697 bool keep_locked = false;
4699 struct timespec mtimespec;
4701 uint32_t need_fd_access;
4704 if (is_ntfs_stream_smb_fname(smb_dname)) {
4705 DEBUG(2, ("open_directory: %s is a stream name!\n",
4706 smb_fname_str_dbg(smb_dname)));
4707 return NT_STATUS_NOT_A_DIRECTORY;
4710 if (!(file_attributes & FILE_FLAG_POSIX_SEMANTICS)) {
4711 /* Ensure we have a directory attribute. */
4712 file_attributes |= FILE_ATTRIBUTE_DIRECTORY;
4715 DBG_INFO("opening directory %s, access_mask = 0x%"PRIx32", "
4716 "share_access = 0x%"PRIx32" create_options = 0x%"PRIx32", "
4717 "create_disposition = 0x%"PRIx32", "
4718 "file_attributes = 0x%"PRIx32"\n",
4719 smb_fname_str_dbg(smb_dname),
4726 status = smbd_calculate_access_mask_fsp(parent_dir_fname->fsp,
4731 if (!NT_STATUS_IS_OK(status)) {
4732 DBG_DEBUG("smbd_calculate_access_mask_fsp "
4733 "on file %s returned %s\n",
4734 smb_fname_str_dbg(smb_dname),
4739 if ((access_mask & SEC_FLAG_SYSTEM_SECURITY) &&
4740 !security_token_has_privilege(get_current_nttok(conn),
4741 SEC_PRIV_SECURITY)) {
4742 DEBUG(10, ("open_directory: open on %s "
4743 "failed - SEC_FLAG_SYSTEM_SECURITY denied.\n",
4744 smb_fname_str_dbg(smb_dname)));
4745 return NT_STATUS_PRIVILEGE_NOT_HELD;
4748 switch( create_disposition ) {
4752 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
4755 info = FILE_WAS_OPENED;
4760 /* If directory exists error. If directory doesn't
4764 status = NT_STATUS_OBJECT_NAME_COLLISION;
4765 DEBUG(2, ("open_directory: unable to create "
4766 "%s. Error was %s\n",
4767 smb_fname_str_dbg(smb_dname),
4768 nt_errstr(status)));
4772 if (smb_fname_atname->twrp != 0) {
4773 return NT_STATUS_MEDIA_WRITE_PROTECTED;
4776 status = mkdir_internal(conn,
4783 if (!NT_STATUS_IS_OK(status)) {
4784 DEBUG(2, ("open_directory: unable to create "
4785 "%s. Error was %s\n",
4786 smb_fname_str_dbg(smb_dname),
4787 nt_errstr(status)));
4791 info = FILE_WAS_CREATED;
4796 * If directory exists open. If directory doesn't
4801 status = NT_STATUS_OK;
4802 info = FILE_WAS_OPENED;
4804 if (smb_fname_atname->twrp != 0) {
4805 return NT_STATUS_MEDIA_WRITE_PROTECTED;
4807 status = mkdir_internal(conn,
4814 if (NT_STATUS_IS_OK(status)) {
4815 info = FILE_WAS_CREATED;
4818 /* Cope with create race. */
4819 if (!NT_STATUS_EQUAL(status,
4820 NT_STATUS_OBJECT_NAME_COLLISION)) {
4821 DEBUG(2, ("open_directory: unable to create "
4822 "%s. Error was %s\n",
4823 smb_fname_str_dbg(smb_dname),
4824 nt_errstr(status)));
4829 * If mkdir_internal() returned
4830 * NT_STATUS_OBJECT_NAME_COLLISION
4831 * we still must lstat the path.
4833 ret = SMB_VFS_FSTATAT(
4835 parent_dir_fname->fsp,
4838 AT_SYMLINK_NOFOLLOW);
4840 DEBUG(2, ("Could not stat "
4841 "directory '%s' just "
4846 return map_nt_error_from_unix(
4850 info = FILE_WAS_OPENED;
4856 case FILE_SUPERSEDE:
4857 case FILE_OVERWRITE:
4858 case FILE_OVERWRITE_IF:
4860 DEBUG(5,("open_directory: invalid create_disposition "
4861 "0x%x for directory %s\n",
4862 (unsigned int)create_disposition,
4863 smb_fname_str_dbg(smb_dname)));
4864 return NT_STATUS_INVALID_PARAMETER;
4867 if(!S_ISDIR(smb_dname->st.st_ex_mode)) {
4868 DEBUG(5,("open_directory: %s is not a directory !\n",
4869 smb_fname_str_dbg(smb_dname)));
4870 return NT_STATUS_NOT_A_DIRECTORY;
4874 * Setup the files_struct for it.
4877 fsp->file_id = vfs_file_id_from_sbuf(conn, &smb_dname->st);
4878 fsp->vuid = req ? req->vuid : UID_FIELD_INVALID;
4879 fsp->file_pid = req ? req->smbpid : 0;
4880 fsp->fsp_flags.can_lock = false;
4881 fsp->fsp_flags.can_read = false;
4882 fsp->fsp_flags.can_write = false;
4884 fh_set_private_options(fsp->fh, 0);
4886 * According to Samba4, SEC_FILE_READ_ATTRIBUTE is always granted,
4888 fsp->access_mask = access_mask | FILE_READ_ATTRIBUTES;
4889 fsp->print_file = NULL;
4890 fsp->fsp_flags.modified = false;
4891 fsp->oplock_type = NO_OPLOCK;
4892 fsp->sent_oplock_break = NO_BREAK_SENT;
4893 fsp->fsp_flags.is_directory = true;
4894 if (file_attributes & FILE_FLAG_POSIX_SEMANTICS) {
4895 fsp->posix_flags |= FSP_POSIX_FLAGS_ALL;
4898 /* Don't store old timestamps for directory
4899 handles in the internal database. We don't
4900 update them in there if new objects
4901 are created in the directory. Currently
4902 we only update timestamps on file writes.
4905 mtimespec = make_omit_timespec();
4908 * Obviously for FILE_LIST_DIRECTORY we need to reopen to get an fd
4909 * usable for reading a directory. SMB2_FLUSH may be called on
4910 * directories opened with FILE_ADD_FILE and FILE_ADD_SUBDIRECTORY so
4911 * for those we need to reopen as well.
4914 FILE_LIST_DIRECTORY |
4916 FILE_ADD_SUBDIRECTORY;
4918 if (access_mask & need_fd_access) {
4919 struct vfs_open_how how = {
4920 .flags = O_RDONLY | O_DIRECTORY,
4924 status = reopen_from_fsp(fsp->conn->cwd_fsp,
4929 if (!NT_STATUS_IS_OK(status)) {
4930 DBG_INFO("Could not open fd for [%s]: %s\n",
4931 smb_fname_str_dbg(smb_dname),
4937 status = vfs_stat_fsp(fsp);
4938 if (!NT_STATUS_IS_OK(status)) {
4943 if(!S_ISDIR(fsp->fsp_name->st.st_ex_mode)) {
4944 DEBUG(5,("open_directory: %s is not a directory !\n",
4945 smb_fname_str_dbg(smb_dname)));
4947 return NT_STATUS_NOT_A_DIRECTORY;
4950 /* Ensure there was no race condition. We need to check
4951 * dev/inode but not permissions, as these can change
4953 if (!check_same_dev_ino(&smb_dname->st, &fsp->fsp_name->st)) {
4954 DEBUG(5,("open_directory: stat struct differs for "
4956 smb_fname_str_dbg(smb_dname)));
4958 return NT_STATUS_ACCESS_DENIED;
4961 if (info == FILE_WAS_OPENED) {
4962 status = smbd_check_access_rights_fsp(parent_dir_fname->fsp,
4966 if (!NT_STATUS_IS_OK(status)) {
4967 DBG_DEBUG("smbd_check_access_rights_fsp on "
4968 "file %s failed with %s\n",
4977 * If we created a new directory or going to delete it later,
4978 * we should keep * the share_mode_lock (g_lock) until we call
4979 * share_mode_entry_prepare_unlock()
4981 if (info != FILE_WAS_OPENED) {
4983 } else if (create_options & FILE_DELETE_ON_CLOSE) {
4987 lck_state = (struct open_ntcreate_lock_state) {
4989 .object_type = "directory",
4991 .create_disposition = create_disposition,
4992 .access_mask = access_mask,
4993 .share_access = share_access,
4994 .oplock_request = NO_OPLOCK,
4996 .first_open_attempt = true,
4997 .keep_locked = keep_locked,
5000 status = share_mode_entry_prepare_lock_add(&lck_state.prepare_state,
5005 open_ntcreate_lock_add_entry,
5007 if (!NT_STATUS_IS_OK(status)) {
5008 DBG_ERR("share_mode_entry_prepare_lock_add() failed for %s - %s\n",
5009 smb_fname_str_dbg(smb_dname), nt_errstr(status));
5014 status = lck_state.status;
5015 if (!NT_STATUS_IS_OK(status)) {
5021 * From here we need to use 'goto unlock;' instead of return !!!
5024 /* For directories the delete on close bit at open time seems
5025 always to be honored on close... See test 19 in Samba4 BASE-DELETE. */
5026 if (create_options & FILE_DELETE_ON_CLOSE) {
5027 status = can_set_delete_on_close(fsp, 0);
5028 if (!NT_STATUS_IS_OK(status) && !NT_STATUS_EQUAL(status, NT_STATUS_DIRECTORY_NOT_EMPTY)) {
5029 lck_state.cleanup_fn =
5030 open_ntcreate_lock_cleanup_entry;
5034 if (NT_STATUS_IS_OK(status)) {
5035 /* Note that here we set the *initial* delete on close flag,
5036 not the regular one. The magic gets handled in close. */
5037 fsp->fsp_flags.initial_delete_on_close = true;
5042 * Deal with other opens having a modified write time.
5044 if (!is_omit_timespec(&lck_state.write_time)) {
5045 update_stat_ex_mtime(&fsp->fsp_name->st, lck_state.write_time);
5052 status = NT_STATUS_OK;
5055 ulstatus = share_mode_entry_prepare_unlock(&lck_state.prepare_state,
5056 lck_state.cleanup_fn,
5058 if (!NT_STATUS_IS_OK(ulstatus)) {
5059 DBG_ERR("share_mode_entry_prepare_unlock() failed for %s - %s\n",
5060 smb_fname_str_dbg(smb_dname), nt_errstr(ulstatus));
5061 smb_panic("share_mode_entry_prepare_unlock() failed!");
5064 if (!NT_STATUS_IS_OK(status)) {
5069 return NT_STATUS_OK;
5072 NTSTATUS create_directory(connection_struct *conn,
5073 struct smb_request *req,
5074 struct files_struct *dirfsp,
5075 struct smb_filename *smb_dname)
5080 status = SMB_VFS_CREATE_FILE(
5083 dirfsp, /* dirfsp */
5084 smb_dname, /* fname */
5085 FILE_READ_ATTRIBUTES, /* access_mask */
5086 FILE_SHARE_NONE, /* share_access */
5087 FILE_CREATE, /* create_disposition*/
5088 FILE_DIRECTORY_FILE, /* create_options */
5089 FILE_ATTRIBUTE_DIRECTORY, /* file_attributes */
5090 0, /* oplock_request */
5092 0, /* allocation_size */
5093 0, /* private_flags */
5098 NULL, NULL); /* create context */
5100 if (NT_STATUS_IS_OK(status)) {
5101 close_file_free(req, &fsp, NORMAL_CLOSE);
5107 /****************************************************************************
5108 Receive notification that one of our open files has been renamed by another
5110 ****************************************************************************/
5112 void msg_file_was_renamed(struct messaging_context *msg_ctx,
5115 struct server_id src,
5118 struct file_rename_message *msg = NULL;
5119 enum ndr_err_code ndr_err;
5121 struct smb_filename *smb_fname = NULL;
5122 struct smbd_server_connection *sconn =
5123 talloc_get_type_abort(private_data,
5124 struct smbd_server_connection);
5126 msg = talloc(talloc_tos(), struct file_rename_message);
5128 DBG_WARNING("talloc failed\n");
5132 ndr_err = ndr_pull_struct_blob_all(
5136 (ndr_pull_flags_fn_t)ndr_pull_file_rename_message);
5137 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
5138 DBG_DEBUG("ndr_pull_oplock_break_message failed: %s\n",
5139 ndr_errstr(ndr_err));
5142 if (DEBUGLEVEL >= 10) {
5143 struct server_id_buf buf;
5144 DBG_DEBUG("Got rename message from %s\n",
5145 server_id_str_buf(src, &buf));
5146 NDR_PRINT_DEBUG(file_rename_message, msg);
5149 /* stream_name must always be NULL if there is no stream. */
5150 if ((msg->stream_name != NULL) && (msg->stream_name[0] == '\0')) {
5151 msg->stream_name = NULL;
5154 smb_fname = synthetic_smb_fname(msg,
5160 if (smb_fname == NULL) {
5161 DBG_DEBUG("synthetic_smb_fname failed\n");
5165 fsp = file_find_dif(sconn, msg->id, msg->share_file_id);
5167 DBG_DEBUG("fsp not found\n");
5171 if (strcmp(fsp->conn->connectpath, msg->servicepath) == 0) {
5172 SMB_STRUCT_STAT fsp_orig_sbuf;
5174 DBG_DEBUG("renaming file %s from %s -> %s\n",
5177 smb_fname_str_dbg(smb_fname));
5180 * The incoming smb_fname here has an
5181 * invalid stat struct from synthetic_smb_fname()
5183 * Preserve the existing stat from the
5184 * open fsp after fsp_set_smb_fname()
5185 * overwrites with the invalid stat.
5187 * (We could just copy this into
5188 * smb_fname->st, but keep this code
5189 * identical to the fix in rename_open_files()
5192 * We will do an fstat before returning
5193 * any of this metadata to the client anyway.
5195 fsp_orig_sbuf = fsp->fsp_name->st;
5196 status = fsp_set_smb_fname(fsp, smb_fname);
5197 if (!NT_STATUS_IS_OK(status)) {
5198 DBG_DEBUG("fsp_set_smb_fname failed: %s\n",
5201 fsp->fsp_name->st = fsp_orig_sbuf;
5205 * Now we have the complete path we can work out if
5206 * this is actually within this share and adjust
5207 * newname accordingly.
5209 DBG_DEBUG("share mismatch (sharepath %s not sharepath %s) "
5210 "%s from %s -> %s\n",
5211 fsp->conn->connectpath,
5215 smb_fname_str_dbg(smb_fname));
5222 * If a main file is opened for delete, all streams need to be checked for
5223 * !FILE_SHARE_DELETE. Do this by opening with DELETE_ACCESS.
5224 * If that works, delete them all by setting the delete on close and close.
5227 static NTSTATUS open_streams_for_delete(connection_struct *conn,
5228 const struct smb_filename *smb_fname)
5230 struct stream_struct *stream_info = NULL;
5231 files_struct **streams = NULL;
5233 unsigned int i, num_streams = 0;
5234 TALLOC_CTX *frame = talloc_stackframe();
5235 const struct smb_filename *pathref = NULL;
5238 if (smb_fname->fsp == NULL) {
5239 struct smb_filename *tmp = NULL;
5240 status = synthetic_pathref(frame,
5242 smb_fname->base_name,
5248 if (!NT_STATUS_IS_OK(status)) {
5249 if (NT_STATUS_EQUAL(status, NT_STATUS_NOT_IMPLEMENTED)
5250 || NT_STATUS_EQUAL(status,
5251 NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
5252 DBG_DEBUG("no streams around\n");
5254 return NT_STATUS_OK;
5256 DBG_DEBUG("synthetic_pathref failed: %s\n",
5262 pathref = smb_fname;
5264 status = vfs_fstreaminfo(pathref->fsp, talloc_tos(),
5265 &num_streams, &stream_info);
5267 if (NT_STATUS_EQUAL(status, NT_STATUS_NOT_IMPLEMENTED)
5268 || NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
5269 DEBUG(10, ("no streams around\n"));
5271 return NT_STATUS_OK;
5274 if (!NT_STATUS_IS_OK(status)) {
5275 DEBUG(10, ("vfs_fstreaminfo failed: %s\n",
5276 nt_errstr(status)));
5280 DEBUG(10, ("open_streams_for_delete found %d streams\n",
5283 if (num_streams == 0) {
5285 return NT_STATUS_OK;
5288 streams = talloc_array(talloc_tos(), files_struct *, num_streams);
5289 if (streams == NULL) {
5290 DEBUG(0, ("talloc failed\n"));
5291 status = NT_STATUS_NO_MEMORY;
5295 for (i=0; i<num_streams; i++) {
5296 struct smb_filename *smb_fname_cp;
5298 if (strequal(stream_info[i].name, "::$DATA")) {
5303 smb_fname_cp = synthetic_smb_fname(talloc_tos(),
5304 smb_fname->base_name,
5305 stream_info[i].name,
5309 ~SMB_FILENAME_POSIX_PATH));
5310 if (smb_fname_cp == NULL) {
5311 status = NT_STATUS_NO_MEMORY;
5315 status = openat_pathref_fsp(conn->cwd_fsp, smb_fname_cp);
5316 if (!NT_STATUS_IS_OK(status)) {
5317 DBG_DEBUG("Unable to open stream [%s]: %s\n",
5318 smb_fname_str_dbg(smb_fname_cp),
5320 TALLOC_FREE(smb_fname_cp);
5324 status = SMB_VFS_CREATE_FILE(
5328 smb_fname_cp, /* fname */
5329 DELETE_ACCESS, /* access_mask */
5330 (FILE_SHARE_READ | /* share_access */
5331 FILE_SHARE_WRITE | FILE_SHARE_DELETE),
5332 FILE_OPEN, /* create_disposition*/
5333 0, /* create_options */
5334 FILE_ATTRIBUTE_NORMAL, /* file_attributes */
5335 0, /* oplock_request */
5337 0, /* allocation_size */
5338 0, /* private_flags */
5341 &streams[i], /* result */
5343 NULL, NULL); /* create context */
5345 if (!NT_STATUS_IS_OK(status)) {
5346 DEBUG(10, ("Could not open stream %s: %s\n",
5347 smb_fname_str_dbg(smb_fname_cp),
5348 nt_errstr(status)));
5350 TALLOC_FREE(smb_fname_cp);
5353 TALLOC_FREE(smb_fname_cp);
5357 * don't touch the variable "status" beyond this point :-)
5360 for (j = i-1 ; j >= 0; j--) {
5361 if (streams[j] == NULL) {
5365 DEBUG(10, ("Closing stream # %d, %s\n", j,
5366 fsp_str_dbg(streams[j])));
5367 close_file_free(NULL, &streams[j], NORMAL_CLOSE);
5375 /*********************************************************************
5376 Create a default ACL by inheriting from the parent. If no inheritance
5377 from the parent available, don't set anything. This will leave the actual
5378 permissions the new file or directory already got from the filesystem
5379 as the NT ACL when read.
5380 *********************************************************************/
5382 static NTSTATUS inherit_new_acl(files_struct *dirfsp, files_struct *fsp)
5384 TALLOC_CTX *frame = talloc_stackframe();
5385 struct security_descriptor *parent_desc = NULL;
5386 NTSTATUS status = NT_STATUS_OK;
5387 struct security_descriptor *psd = NULL;
5388 const struct dom_sid *owner_sid = NULL;
5389 const struct dom_sid *group_sid = NULL;
5390 uint32_t security_info_sent = (SECINFO_OWNER | SECINFO_GROUP | SECINFO_DACL);
5391 struct security_token *token = fsp->conn->session_info->security_token;
5392 bool inherit_owner =
5393 (lp_inherit_owner(SNUM(fsp->conn)) == INHERIT_OWNER_WINDOWS_AND_UNIX);
5394 bool inheritable_components = false;
5395 bool try_builtin_administrators = false;
5396 const struct dom_sid *BA_U_sid = NULL;
5397 const struct dom_sid *BA_G_sid = NULL;
5398 bool try_system = false;
5399 const struct dom_sid *SY_U_sid = NULL;
5400 const struct dom_sid *SY_G_sid = NULL;
5404 status = SMB_VFS_FGET_NT_ACL(dirfsp,
5405 (SECINFO_OWNER | SECINFO_GROUP | SECINFO_DACL),
5408 if (!NT_STATUS_IS_OK(status)) {
5413 inheritable_components = sd_has_inheritable_components(parent_desc,
5414 fsp->fsp_flags.is_directory);
5416 if (!inheritable_components && !inherit_owner) {
5418 /* Nothing to inherit and not setting owner. */
5419 return NT_STATUS_OK;
5422 /* Create an inherited descriptor from the parent. */
5424 if (DEBUGLEVEL >= 10) {
5425 DEBUG(10,("inherit_new_acl: parent acl for %s is:\n",
5426 fsp_str_dbg(fsp) ));
5427 NDR_PRINT_DEBUG(security_descriptor, parent_desc);
5430 /* Inherit from parent descriptor if "inherit owner" set. */
5431 if (inherit_owner) {
5432 owner_sid = parent_desc->owner_sid;
5433 group_sid = parent_desc->group_sid;
5436 if (owner_sid == NULL) {
5437 if (security_token_has_builtin_administrators(token)) {
5438 try_builtin_administrators = true;
5439 } else if (security_token_is_system(token)) {
5440 try_builtin_administrators = true;
5445 if (group_sid == NULL &&
5446 token->num_sids == PRIMARY_GROUP_SID_INDEX)
5448 if (security_token_is_system(token)) {
5449 try_builtin_administrators = true;
5454 if (try_builtin_administrators) {
5455 struct unixid ids = { .id = 0 };
5457 ok = sids_to_unixids(&global_sid_Builtin_Administrators, 1, &ids);
5461 BA_U_sid = &global_sid_Builtin_Administrators;
5462 BA_G_sid = &global_sid_Builtin_Administrators;
5465 BA_U_sid = &global_sid_Builtin_Administrators;
5468 BA_G_sid = &global_sid_Builtin_Administrators;
5477 struct unixid ids = { .id = 0 };
5479 ok = sids_to_unixids(&global_sid_System, 1, &ids);
5483 SY_U_sid = &global_sid_System;
5484 SY_G_sid = &global_sid_System;
5487 SY_U_sid = &global_sid_System;
5490 SY_G_sid = &global_sid_System;
5498 if (owner_sid == NULL) {
5499 owner_sid = BA_U_sid;
5502 if (owner_sid == NULL) {
5503 owner_sid = SY_U_sid;
5506 if (group_sid == NULL) {
5507 group_sid = SY_G_sid;
5510 if (try_system && group_sid == NULL) {
5511 group_sid = BA_G_sid;
5514 if (owner_sid == NULL) {
5515 owner_sid = &token->sids[PRIMARY_USER_SID_INDEX];
5517 if (group_sid == NULL) {
5518 if (token->num_sids == PRIMARY_GROUP_SID_INDEX) {
5519 group_sid = &token->sids[PRIMARY_USER_SID_INDEX];
5521 group_sid = &token->sids[PRIMARY_GROUP_SID_INDEX];
5525 status = se_create_child_secdesc(frame,
5531 fsp->fsp_flags.is_directory);
5532 if (!NT_STATUS_IS_OK(status)) {
5537 /* If inheritable_components == false,
5538 se_create_child_secdesc()
5539 creates a security descriptor with a NULL dacl
5540 entry, but with SEC_DESC_DACL_PRESENT. We need
5541 to remove that flag. */
5543 if (!inheritable_components) {
5544 security_info_sent &= ~SECINFO_DACL;
5545 psd->type &= ~SEC_DESC_DACL_PRESENT;
5548 if (DEBUGLEVEL >= 10) {
5549 DEBUG(10,("inherit_new_acl: child acl for %s is:\n",
5550 fsp_str_dbg(fsp) ));
5551 NDR_PRINT_DEBUG(security_descriptor, psd);
5554 if (inherit_owner) {
5555 /* We need to be root to force this. */
5556 set_effective_capability(DAC_OVERRIDE_CAPABILITY);
5558 status = SMB_VFS_FSET_NT_ACL(metadata_fsp(fsp),
5561 if (inherit_owner) {
5562 drop_effective_capability(DAC_OVERRIDE_CAPABILITY);
5569 * If we already have a lease, it must match the new file id. [MS-SMB2]
5570 * 3.3.5.9.8 speaks about INVALID_PARAMETER if an already used lease key is
5571 * used for a different file name.
5574 struct lease_match_state {
5575 /* Input parameters. */
5576 TALLOC_CTX *mem_ctx;
5577 const char *servicepath;
5578 const struct smb_filename *fname;
5581 /* Return parameters. */
5582 uint32_t num_file_ids;
5583 struct file_id *ids;
5584 NTSTATUS match_status;
5587 /*************************************************************
5588 File doesn't exist but this lease key+guid is already in use.
5590 This is only allowable in the dynamic share case where the
5591 service path must be different.
5593 There is a small race condition here in the multi-connection
5594 case where a client sends two create calls on different connections,
5595 where the file doesn't exist and one smbd creates the leases_db
5596 entry first, but this will get fixed by the multichannel cleanup
5597 when all identical client_guids get handled by a single smbd.
5598 **************************************************************/
5600 static void lease_match_parser_new_file(
5602 const struct leases_db_file *files,
5603 struct lease_match_state *state)
5607 for (i = 0; i < num_files; i++) {
5608 const struct leases_db_file *f = &files[i];
5609 if (strequal(state->servicepath, f->servicepath)) {
5610 state->match_status = NT_STATUS_INVALID_PARAMETER;
5615 /* Dynamic share case. Break leases on all other files. */
5616 state->match_status = leases_db_copy_file_ids(state->mem_ctx,
5620 if (!NT_STATUS_IS_OK(state->match_status)) {
5624 state->num_file_ids = num_files;
5625 state->match_status = NT_STATUS_OPLOCK_NOT_GRANTED;
5629 static void lease_match_parser(
5631 const struct leases_db_file *files,
5634 struct lease_match_state *state =
5635 (struct lease_match_state *)private_data;
5638 if (!state->file_existed) {
5640 * Deal with name mismatch or
5641 * possible dynamic share case separately
5642 * to make code clearer.
5644 lease_match_parser_new_file(num_files,
5651 state->match_status = NT_STATUS_OK;
5653 for (i = 0; i < num_files; i++) {
5654 const struct leases_db_file *f = &files[i];
5656 /* Everything should be the same. */
5657 if (!file_id_equal(&state->id, &f->id)) {
5659 * The client asked for a lease on a
5660 * file that doesn't match the file_id
5663 * Maybe this is a dynamic share, i.e.
5664 * a share where the servicepath is
5665 * different for different users (e.g.
5666 * the [HOMES] share.
5668 * If the servicepath is different, but the requested
5669 * file name + stream name is the same then this is
5670 * a dynamic share, the client is using the same share
5671 * name and doesn't know that the underlying servicepath
5672 * is different. It was expecting a lease on the
5673 * same file. Return NT_STATUS_OPLOCK_NOT_GRANTED
5676 * Otherwise the client has messed up, or is
5677 * testing our error codes, so return
5678 * NT_STATUS_INVALID_PARAMETER.
5680 if (!strequal(f->servicepath, state->servicepath) &&
5681 strequal(f->base_name, state->fname->base_name) &&
5682 strequal(f->stream_name, state->fname->stream_name))
5685 * Name is the same but servicepath is
5686 * different, dynamic share. Break leases.
5688 state->match_status =
5689 NT_STATUS_OPLOCK_NOT_GRANTED;
5691 state->match_status =
5692 NT_STATUS_INVALID_PARAMETER;
5696 if (!strequal(f->servicepath, state->servicepath)) {
5697 state->match_status = NT_STATUS_INVALID_PARAMETER;
5700 if (!strequal(f->base_name, state->fname->base_name)) {
5701 state->match_status = NT_STATUS_INVALID_PARAMETER;
5704 if (!strequal(f->stream_name, state->fname->stream_name)) {
5705 state->match_status = NT_STATUS_INVALID_PARAMETER;
5710 if (NT_STATUS_IS_OK(state->match_status)) {
5712 * Common case - just opening another handle on a
5713 * file on a non-dynamic share.
5718 if (NT_STATUS_EQUAL(state->match_status, NT_STATUS_INVALID_PARAMETER)) {
5719 /* Mismatched path. Error back to client. */
5724 * File id mismatch. Dynamic share case NT_STATUS_OPLOCK_NOT_GRANTED.
5725 * Don't allow leases.
5728 state->match_status = leases_db_copy_file_ids(state->mem_ctx,
5732 if (!NT_STATUS_IS_OK(state->match_status)) {
5736 state->num_file_ids = num_files;
5737 state->match_status = NT_STATUS_OPLOCK_NOT_GRANTED;
5741 struct lease_match_break_state {
5742 struct messaging_context *msg_ctx;
5743 const struct smb2_lease_key *lease_key;
5751 static bool lease_match_break_fn(
5752 struct share_mode_entry *e,
5755 struct lease_match_break_state *state = private_data;
5757 uint32_t e_lease_type = SMB2_LEASE_NONE;
5760 stale = share_entry_stale_pid(e);
5765 equal = smb2_lease_key_equal(&e->lease_key, state->lease_key);
5770 status = leases_db_get(
5774 &e_lease_type, /* current_state */
5775 NULL, /* breaking */
5776 NULL, /* breaking_to_requested */
5777 NULL, /* breaking_to_required */
5778 &state->version, /* lease_version */
5779 &state->epoch); /* epoch */
5780 if (NT_STATUS_IS_OK(status)) {
5781 state->found_lease = true;
5783 DBG_WARNING("Could not find version/epoch: %s\n",
5788 if (e_lease_type == SMB2_LEASE_NONE) {
5791 send_break_message(state->msg_ctx, &state->id, e, SMB2_LEASE_NONE);
5794 * Windows 7 and 8 lease clients are broken in that they will
5795 * not respond to lease break requests whilst waiting for an
5796 * outstanding open request on that lease handle on the same
5797 * TCP connection, due to holding an internal inode lock.
5799 * This means we can't reschedule ourselves here, but must
5800 * return from the create.
5804 * Send the breaks and then return SMB2_LEASE_NONE in the
5805 * lease handle to cause them to acknowledge the lease
5806 * break. Consultation with Microsoft engineering confirmed
5807 * this approach is safe.
5813 static void lease_match_fid_fn(struct share_mode_lock *lck,
5818 ok = share_mode_forall_leases(lck, lease_match_break_fn, private_data);
5820 DBG_DEBUG("share_mode_forall_leases failed\n");
5824 static NTSTATUS lease_match(connection_struct *conn,
5825 struct smb_request *req,
5826 const struct smb2_lease_key *lease_key,
5827 const char *servicepath,
5828 const struct smb_filename *fname,
5829 uint16_t *p_version,
5832 struct smbd_server_connection *sconn = req->sconn;
5833 TALLOC_CTX *tos = talloc_tos();
5834 struct lease_match_state state = {
5836 .servicepath = servicepath,
5838 .match_status = NT_STATUS_OK
5843 state.file_existed = VALID_STAT(fname->st);
5844 if (state.file_existed) {
5845 state.id = vfs_file_id_from_sbuf(conn, &fname->st);
5848 status = leases_db_parse(&sconn->client->global->client_guid,
5849 lease_key, lease_match_parser, &state);
5850 if (!NT_STATUS_IS_OK(status)) {
5852 * Not found or error means okay: We can make the lease pass
5854 return NT_STATUS_OK;
5856 if (!NT_STATUS_EQUAL(state.match_status, NT_STATUS_OPLOCK_NOT_GRANTED)) {
5858 * Anything but NT_STATUS_OPLOCK_NOT_GRANTED, let the caller
5861 return state.match_status;
5864 /* We have to break all existing leases. */
5865 for (i = 0; i < state.num_file_ids; i++) {
5866 struct lease_match_break_state break_state = {
5867 .msg_ctx = conn->sconn->msg_ctx,
5868 .lease_key = lease_key,
5871 if (file_id_equal(&state.ids[i], &state.id)) {
5872 /* Don't need to break our own file. */
5876 break_state.id = state.ids[i];
5878 status = share_mode_do_locked_vfs_denied(break_state.id,
5881 if (!NT_STATUS_IS_OK(status)) {
5882 /* Race condition - file already closed. */
5886 if (break_state.found_lease) {
5887 *p_version = break_state.version;
5888 *p_epoch = break_state.epoch;
5892 * Ensure we don't grant anything more so we
5895 return NT_STATUS_OPLOCK_NOT_GRANTED;
5899 * Wrapper around open_file_ntcreate and open_directory
5902 static NTSTATUS create_file_unixpath(connection_struct *conn,
5903 struct smb_request *req,
5904 struct files_struct *dirfsp,
5905 struct smb_filename *smb_fname,
5906 uint32_t access_mask,
5907 uint32_t share_access,
5908 uint32_t create_disposition,
5909 uint32_t create_options,
5910 uint32_t file_attributes,
5911 uint32_t oplock_request,
5912 const struct smb2_lease *lease,
5913 uint64_t allocation_size,
5914 uint32_t private_flags,
5915 struct security_descriptor *sd,
5916 struct ea_list *ea_list,
5918 files_struct **result,
5921 struct smb2_lease none_lease;
5922 int info = FILE_WAS_OPENED;
5923 files_struct *base_fsp = NULL;
5924 files_struct *fsp = NULL;
5925 bool free_fsp_on_error = false;
5928 struct smb_filename *parent_dir_fname = NULL;
5929 struct smb_filename *smb_fname_atname = NULL;
5931 DBG_DEBUG("access_mask = 0x%"PRIx32" "
5932 "file_attributes = 0x%"PRIx32" "
5933 "share_access = 0x%"PRIx32" "
5934 "create_disposition = 0x%"PRIx32" "
5935 "create_options = 0x%"PRIx32" "
5936 "oplock_request = 0x%"PRIx32" "
5937 "private_flags = 0x%"PRIx32" "
5950 smb_fname_str_dbg(smb_fname));
5952 if (create_options & FILE_OPEN_BY_FILE_ID) {
5953 status = NT_STATUS_NOT_SUPPORTED;
5957 if (create_options & NTCREATEX_OPTIONS_INVALID_PARAM_MASK) {
5958 status = NT_STATUS_INVALID_PARAMETER;
5962 if (!(create_options & FILE_OPEN_REPARSE_POINT) &&
5963 (smb_fname->fsp != NULL) && /* new files don't have an fsp */
5964 VALID_STAT(smb_fname->fsp->fsp_name->st))
5966 mode_t type = (smb_fname->fsp->fsp_name->st.st_ex_mode &
5976 * We should never get this far with a symlink
5977 * "as such". Report as not existing.
5979 status = NT_STATUS_OBJECT_NAME_NOT_FOUND;
5982 status = NT_STATUS_IO_REPARSE_TAG_NOT_HANDLED;
5988 oplock_request |= INTERNAL_OPEN_ONLY;
5991 if (lease != NULL) {
5992 uint16_t epoch = lease->lease_epoch;
5993 uint16_t version = lease->lease_version;
5996 DBG_WARNING("Got lease on internal open\n");
5997 status = NT_STATUS_INTERNAL_ERROR;
6001 status = lease_match(conn,
6008 if (NT_STATUS_EQUAL(status, NT_STATUS_OPLOCK_NOT_GRANTED)) {
6009 /* Dynamic share file. No leases and update epoch... */
6010 none_lease = *lease;
6011 none_lease.lease_state = SMB2_LEASE_NONE;
6012 none_lease.lease_epoch = epoch;
6013 none_lease.lease_version = version;
6014 lease = &none_lease;
6015 } else if (!NT_STATUS_IS_OK(status)) {
6020 if ((conn->fs_capabilities & FILE_NAMED_STREAMS)
6021 && (access_mask & DELETE_ACCESS)
6022 && !is_named_stream(smb_fname)) {
6024 * We can't open a file with DELETE access if any of the
6025 * streams is open without FILE_SHARE_DELETE
6027 status = open_streams_for_delete(conn, smb_fname);
6029 if (!NT_STATUS_IS_OK(status)) {
6034 if (access_mask & SEC_FLAG_SYSTEM_SECURITY) {
6037 ok = security_token_has_privilege(get_current_nttok(conn),
6040 DBG_DEBUG("open on %s failed - "
6041 "SEC_FLAG_SYSTEM_SECURITY denied.\n",
6042 smb_fname_str_dbg(smb_fname));
6043 status = NT_STATUS_PRIVILEGE_NOT_HELD;
6047 if (conn->sconn->using_smb2 &&
6048 (access_mask == SEC_FLAG_SYSTEM_SECURITY))
6051 * No other bits set. Windows SMB2 refuses this.
6052 * See smbtorture3 SMB2-SACL test.
6054 * Note this is an SMB2-only behavior,
6055 * smbtorture3 SMB1-SYSTEM-SECURITY already tests
6056 * that SMB1 allows this.
6058 status = NT_STATUS_ACCESS_DENIED;
6064 * Files or directories can't be opened DELETE_ON_CLOSE without
6066 * BUG: https://bugzilla.samba.org/show_bug.cgi?id=13358
6068 if ((create_options & FILE_DELETE_ON_CLOSE) &&
6069 ((access_mask & DELETE_ACCESS) == 0)) {
6070 status = NT_STATUS_INVALID_PARAMETER;
6074 if ((conn->fs_capabilities & FILE_NAMED_STREAMS)
6075 && is_named_stream(smb_fname))
6077 uint32_t base_create_disposition;
6078 struct smb_filename *smb_fname_base = NULL;
6079 uint32_t base_privflags;
6081 if (create_options & FILE_DIRECTORY_FILE) {
6082 DBG_DEBUG("Can't open a stream as directory\n");
6083 status = NT_STATUS_NOT_A_DIRECTORY;
6087 switch (create_disposition) {
6089 base_create_disposition = FILE_OPEN;
6092 base_create_disposition = FILE_OPEN_IF;
6096 smb_fname_base = cp_smb_filename_nostream(
6097 talloc_tos(), smb_fname);
6099 if (smb_fname_base == NULL) {
6100 status = NT_STATUS_NO_MEMORY;
6105 * We may be creating the basefile as part of creating the
6106 * stream, so it's legal if the basefile doesn't exist at this
6107 * point, the create_file_unixpath() below will create it. But
6108 * if the basefile exists we want a handle so we can fstat() it.
6111 ret = vfs_stat(conn, smb_fname_base);
6112 if (ret == -1 && errno != ENOENT) {
6113 status = map_nt_error_from_unix(errno);
6114 TALLOC_FREE(smb_fname_base);
6118 status = openat_pathref_fsp(conn->cwd_fsp,
6120 if (!NT_STATUS_IS_OK(status)) {
6121 DBG_ERR("open_smb_fname_fsp [%s] failed: %s\n",
6122 smb_fname_str_dbg(smb_fname_base),
6124 TALLOC_FREE(smb_fname_base);
6129 * https://bugzilla.samba.org/show_bug.cgi?id=10229
6130 * We need to check if the requested access mask
6131 * could be used to open the underlying file (if
6132 * it existed), as we're passing in zero for the
6133 * access mask to the base filename.
6135 status = check_base_file_access(smb_fname_base->fsp,
6138 if (!NT_STATUS_IS_OK(status)) {
6139 DEBUG(10, ("Permission check "
6140 "for base %s failed: "
6141 "%s\n", smb_fname->base_name,
6142 nt_errstr(status)));
6143 TALLOC_FREE(smb_fname_base);
6148 base_privflags = NTCREATEX_FLAG_STREAM_BASEOPEN;
6150 /* Open the base file. */
6151 status = create_file_unixpath(conn,
6158 | FILE_SHARE_DELETE,
6159 base_create_disposition,
6170 TALLOC_FREE(smb_fname_base);
6172 if (!NT_STATUS_IS_OK(status)) {
6173 DEBUG(10, ("create_file_unixpath for base %s failed: "
6174 "%s\n", smb_fname->base_name,
6175 nt_errstr(status)));
6180 if (smb_fname->fsp != NULL) {
6182 fsp = smb_fname->fsp;
6185 * We're about to use smb_fname->fsp for the fresh open.
6187 * Every fsp passed in via smb_fname->fsp already
6188 * holds a fsp->fsp_name. If it is already this
6189 * fsp->fsp_name that we got passed in as our input
6190 * argument smb_fname, these two are assumed to have
6191 * the same lifetime: Every fsp hangs of "conn", and
6192 * fsp->fsp_name is its talloc child.
6195 if (smb_fname != smb_fname->fsp->fsp_name) {
6197 * "smb_fname" is temporary in this case, but
6198 * the destructor of smb_fname would also tear
6199 * down the fsp we're about to use. Unlink
6200 * them from each other.
6202 smb_fname_fsp_unlink(smb_fname);
6207 free_fsp_on_error = true;
6210 status = fsp_bind_smb(fsp, req);
6211 if (!NT_STATUS_IS_OK(status)) {
6215 if (fsp_is_alternate_stream(fsp)) {
6216 struct files_struct *tmp_base_fsp = fsp->base_fsp;
6218 fsp_set_base_fsp(fsp, NULL);
6220 fd_close(tmp_base_fsp);
6221 file_free(NULL, tmp_base_fsp);
6225 * No fsp passed in that we can use, create one
6227 status = file_new(req, conn, &fsp);
6228 if(!NT_STATUS_IS_OK(status)) {
6231 free_fsp_on_error = true;
6233 status = fsp_set_smb_fname(fsp, smb_fname);
6234 if (!NT_STATUS_IS_OK(status)) {
6239 SMB_ASSERT(fsp->fsp_name->fsp != NULL);
6240 SMB_ASSERT(fsp->fsp_name->fsp == fsp);
6244 * We're opening the stream element of a
6245 * base_fsp we already opened. Set up the
6248 fsp_set_base_fsp(fsp, base_fsp);
6251 if (dirfsp != NULL) {
6252 status = SMB_VFS_PARENT_PATHNAME(
6258 if (!NT_STATUS_IS_OK(status)) {
6263 * Get a pathref on the parent. We can re-use this for
6264 * multiple calls to check parent ACLs etc. to avoid
6267 status = parent_pathref(talloc_tos(),
6272 if (!NT_STATUS_IS_OK(status)) {
6276 dirfsp = parent_dir_fname->fsp;
6277 status = fsp_set_smb_fname(dirfsp, parent_dir_fname);
6278 if (!NT_STATUS_IS_OK(status)) {
6284 * If it's a request for a directory open, deal with it separately.
6287 if (create_options & FILE_DIRECTORY_FILE) {
6289 if (create_options & FILE_NON_DIRECTORY_FILE) {
6290 status = NT_STATUS_INVALID_PARAMETER;
6294 /* Can't open a temp directory. IFS kit test. */
6295 if (!(file_attributes & FILE_FLAG_POSIX_SEMANTICS) &&
6296 (file_attributes & FILE_ATTRIBUTE_TEMPORARY)) {
6297 status = NT_STATUS_INVALID_PARAMETER;
6302 * We will get a create directory here if the Win32
6303 * app specified a security descriptor in the
6304 * CreateDirectory() call.
6308 status = open_directory(conn,
6322 * Ordinary file case.
6325 if (allocation_size) {
6326 fsp->initial_allocation_size = smb_roundup(fsp->conn,
6330 status = open_file_ntcreate(conn,
6344 if (NT_STATUS_EQUAL(status, NT_STATUS_FILE_IS_A_DIRECTORY)) {
6346 /* A stream open never opens a directory */
6349 status = NT_STATUS_FILE_IS_A_DIRECTORY;
6354 * Fail the open if it was explicitly a non-directory
6358 if (create_options & FILE_NON_DIRECTORY_FILE) {
6359 status = NT_STATUS_FILE_IS_A_DIRECTORY;
6364 status = open_directory(conn,
6378 if (!NT_STATUS_IS_OK(status)) {
6382 fsp->fsp_flags.is_fsa = true;
6384 if ((ea_list != NULL) &&
6385 ((info == FILE_WAS_CREATED) || (info == FILE_WAS_OVERWRITTEN))) {
6386 status = set_ea(conn, fsp, ea_list);
6387 if (!NT_STATUS_IS_OK(status)) {
6392 if (!fsp->fsp_flags.is_directory &&
6393 S_ISDIR(fsp->fsp_name->st.st_ex_mode))
6395 status = NT_STATUS_ACCESS_DENIED;
6399 /* Save the requested allocation size. */
6400 if ((info == FILE_WAS_CREATED) || (info == FILE_WAS_OVERWRITTEN)) {
6401 if ((allocation_size > (uint64_t)fsp->fsp_name->st.st_ex_size)
6402 && !(fsp->fsp_flags.is_directory))
6404 fsp->initial_allocation_size = smb_roundup(
6405 fsp->conn, allocation_size);
6406 if (vfs_allocate_file_space(
6407 fsp, fsp->initial_allocation_size) == -1) {
6408 status = NT_STATUS_DISK_FULL;
6412 fsp->initial_allocation_size = smb_roundup(
6413 fsp->conn, (uint64_t)fsp->fsp_name->st.st_ex_size);
6416 fsp->initial_allocation_size = 0;
6419 if ((info == FILE_WAS_CREATED) &&
6420 lp_nt_acl_support(SNUM(conn)) &&
6421 !fsp_is_alternate_stream(fsp)) {
6424 * According to the MS documentation, the only time the security
6425 * descriptor is applied to the opened file is iff we *created* the
6426 * file; an existing file stays the same.
6428 * Also, it seems (from observation) that you can open the file with
6429 * any access mask but you can still write the sd. We need to override
6430 * the granted access before we call set_sd
6431 * Patch for bug #2242 from Tom Lackemann <cessnatomny@yahoo.com>.
6434 uint32_t sec_info_sent;
6435 uint32_t saved_access_mask = fsp->access_mask;
6437 sec_info_sent = get_sec_info(sd);
6439 fsp->access_mask = FILE_GENERIC_ALL;
6441 if (sec_info_sent & (SECINFO_OWNER|
6445 status = set_sd(fsp, sd, sec_info_sent);
6448 fsp->access_mask = saved_access_mask;
6450 if (!NT_STATUS_IS_OK(status)) {
6453 } else if (lp_inherit_acls(SNUM(conn))) {
6454 /* Inherit from parent. Errors here are not fatal. */
6455 status = inherit_new_acl(dirfsp, fsp);
6456 if (!NT_STATUS_IS_OK(status)) {
6457 DEBUG(10,("inherit_new_acl: failed for %s with %s\n",
6459 nt_errstr(status) ));
6464 if ((conn->fs_capabilities & FILE_FILE_COMPRESSION)
6465 && (create_options & FILE_NO_COMPRESSION)
6466 && (info == FILE_WAS_CREATED)) {
6467 status = SMB_VFS_SET_COMPRESSION(conn, fsp, fsp,
6468 COMPRESSION_FORMAT_NONE);
6469 if (!NT_STATUS_IS_OK(status)) {
6470 DEBUG(1, ("failed to disable compression: %s\n",
6471 nt_errstr(status)));
6475 DEBUG(10, ("create_file_unixpath: info=%d\n", info));
6478 if (pinfo != NULL) {
6482 smb_fname->st = fsp->fsp_name->st;
6484 TALLOC_FREE(parent_dir_fname);
6486 return NT_STATUS_OK;
6489 DEBUG(10, ("create_file_unixpath: %s\n", nt_errstr(status)));
6493 * The close_file below will close
6497 close_file_smb(req, fsp, ERROR_CLOSE);
6498 if (free_fsp_on_error) {
6499 file_free(req, fsp);
6503 if (base_fsp != NULL) {
6504 close_file_free(req, &base_fsp, ERROR_CLOSE);
6507 TALLOC_FREE(parent_dir_fname);
6512 NTSTATUS create_file_default(connection_struct *conn,
6513 struct smb_request *req,
6514 struct files_struct *dirfsp,
6515 struct smb_filename *smb_fname,
6516 uint32_t access_mask,
6517 uint32_t share_access,
6518 uint32_t create_disposition,
6519 uint32_t create_options,
6520 uint32_t file_attributes,
6521 uint32_t oplock_request,
6522 const struct smb2_lease *lease,
6523 uint64_t allocation_size,
6524 uint32_t private_flags,
6525 struct security_descriptor *sd,
6526 struct ea_list *ea_list,
6527 files_struct **result,
6529 const struct smb2_create_blobs *in_context_blobs,
6530 struct smb2_create_blobs *out_context_blobs)
6532 int info = FILE_WAS_OPENED;
6533 files_struct *fsp = NULL;
6535 bool stream_name = false;
6536 struct smb2_create_blob *posx = NULL;
6538 DBG_DEBUG("access_mask = 0x%" PRIu32
6539 " file_attributes = 0x%" PRIu32
6540 " share_access = 0x%" PRIu32
6541 " create_disposition = 0x%" PRIu32
6542 " create_options = 0x%" PRIu32
6543 " oplock_request = 0x%" PRIu32
6544 " private_flags = 0x%" PRIu32
6545 " ea_list = %p, sd = %p, fname = %s\n",
6555 smb_fname_str_dbg(smb_fname));
6559 * Remember the absolute time of the original request
6560 * with this mid. We'll use it later to see if this
6563 get_deferred_open_message_state(req, &req->request_time, NULL);
6567 * Check to see if this is a mac fork of some kind.
6570 stream_name = is_ntfs_stream_smb_fname(smb_fname);
6572 enum FAKE_FILE_TYPE fake_file_type;
6574 fake_file_type = is_fake_file(smb_fname);
6576 if (req != NULL && fake_file_type != FAKE_FILE_TYPE_NONE) {
6579 * Here we go! support for changing the disk quotas
6582 * We need to fake up to open this MAGIC QUOTA file
6583 * and return a valid FID.
6585 * w2k close this file directly after opening xp
6586 * also tries a QUERY_FILE_INFO on the file and then
6589 status = open_fake_file(req, conn, req->vuid,
6590 fake_file_type, smb_fname,
6592 if (!NT_STATUS_IS_OK(status)) {
6596 ZERO_STRUCT(smb_fname->st);
6600 if (!(conn->fs_capabilities & FILE_NAMED_STREAMS)) {
6601 status = NT_STATUS_OBJECT_NAME_INVALID;
6606 if (is_ntfs_default_stream_smb_fname(smb_fname)) {
6608 /* We have to handle this error here. */
6609 if (create_options & FILE_DIRECTORY_FILE) {
6610 status = NT_STATUS_NOT_A_DIRECTORY;
6613 ret = vfs_stat(conn, smb_fname);
6614 if (ret == 0 && VALID_STAT_OF_DIR(smb_fname->st)) {
6615 status = NT_STATUS_FILE_IS_A_DIRECTORY;
6620 posx = smb2_create_blob_find(
6621 in_context_blobs, SMB2_CREATE_TAG_POSIX);
6623 uint32_t wire_mode_bits = 0;
6624 mode_t mode_bits = 0;
6625 SMB_STRUCT_STAT sbuf = { 0 };
6626 enum perm_type ptype =
6627 (create_options & FILE_DIRECTORY_FILE) ?
6628 PERM_NEW_DIR : PERM_NEW_FILE;
6630 if (posx->data.length != 4) {
6631 status = NT_STATUS_INVALID_PARAMETER;
6635 wire_mode_bits = IVAL(posx->data.data, 0);
6636 status = unix_perms_from_wire(
6637 conn, &sbuf, wire_mode_bits, ptype, &mode_bits);
6638 if (!NT_STATUS_IS_OK(status)) {
6642 * Remove type info from mode, leaving only the
6643 * permissions and setuid/gid bits.
6645 mode_bits &= ~S_IFMT;
6647 file_attributes = (FILE_FLAG_POSIX_SEMANTICS | mode_bits);
6650 status = create_file_unixpath(conn,
6667 if (!NT_STATUS_IS_OK(status)) {
6672 DEBUG(10, ("create_file: info=%d\n", info));
6675 if (pinfo != NULL) {
6678 return NT_STATUS_OK;
6681 DEBUG(10, ("create_file: %s\n", nt_errstr(status)));
6684 close_file_free(req, &fsp, ERROR_CLOSE);