2 Unix SMB/CIFS implementation.
3 file opening and share modes
4 Copyright (C) Andrew Tridgell 1992-1998
5 Copyright (C) Jeremy Allison 2001-2004
6 Copyright (C) Volker Lendecke 2005
7 Copyright (C) Ralph Boehme 2017
9 This program is free software; you can redistribute it and/or modify
10 it under the terms of the GNU General Public License as published by
11 the Free Software Foundation; either version 3 of the License, or
12 (at your option) any later version.
14 This program is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 GNU General Public License for more details.
19 You should have received a copy of the GNU General Public License
20 along with this program. If not, see <http://www.gnu.org/licenses/>.
24 #include "smb1_utils.h"
25 #include "system/filesys.h"
26 #include "lib/util/server_id.h"
28 #include "locking/share_mode_lock.h"
29 #include "smbd/smbd.h"
30 #include "smbd/globals.h"
31 #include "fake_file.h"
32 #include "../libcli/security/security.h"
33 #include "../librpc/gen_ndr/ndr_security.h"
34 #include "../librpc/gen_ndr/ndr_open_files.h"
35 #include "../librpc/gen_ndr/idmap.h"
36 #include "../librpc/gen_ndr/ioctl.h"
37 #include "passdb/lookup_sid.h"
41 #include "source3/lib/dbwrap/dbwrap_watch.h"
42 #include "locking/leases_db.h"
43 #include "librpc/gen_ndr/ndr_leases_db.h"
44 #include "lib/util/time_basic.h"
46 extern const struct generic_mapping file_generic_mapping;
48 struct deferred_open_record {
49 struct smbXsrv_connection *xconn;
55 * Timer for async opens, needed because they don't use a watch on
56 * a locking.tdb record. This is currently only used for real async
57 * opens and just terminates smbd if the async open times out.
59 struct tevent_timer *te;
62 * For the samba kernel oplock case we use both a timeout and
63 * a watch on locking.tdb. This way in case it's smbd holding
64 * the kernel oplock we get directly notified for the retry
65 * once the kernel oplock is properly broken. Store the req
66 * here so that it can be timely discarded once the timer
69 struct tevent_req *watch_req;
72 /****************************************************************************
73 If the requester wanted DELETE_ACCESS and was rejected because
74 the file ACL didn't include DELETE_ACCESS, see if the parent ACL
76 ****************************************************************************/
78 static bool parent_override_delete(connection_struct *conn,
79 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_sd(
100 struct connection_struct *conn,
101 struct files_struct *dirfsp,
102 const struct smb_filename *smb_fname,
103 struct security_descriptor *sd,
105 uint32_t access_mask)
107 uint32_t rejected_share_access;
108 uint32_t rejected_mask = access_mask;
109 uint32_t do_not_check_mask = 0;
112 rejected_share_access = access_mask & ~(conn->share_access);
114 if (rejected_share_access) {
115 DBG_DEBUG("rejected share access 0x%x on %s (0x%x)\n",
116 (unsigned int)access_mask,
117 smb_fname_str_dbg(smb_fname),
118 (unsigned int)rejected_share_access);
119 return NT_STATUS_ACCESS_DENIED;
122 if (!use_privs && get_current_uid(conn) == (uid_t)0) {
123 /* I'm sorry sir, I didn't know you were root... */
124 DBG_DEBUG("root override on %s. Granting 0x%x\n",
125 smb_fname_str_dbg(smb_fname),
126 (unsigned int)access_mask);
130 if ((access_mask & DELETE_ACCESS) &&
131 !lp_acl_check_permissions(SNUM(conn)))
133 DBG_DEBUG("Not checking ACL on DELETE_ACCESS on file %s. "
135 smb_fname_str_dbg(smb_fname),
136 (unsigned int)access_mask);
140 if (access_mask == DELETE_ACCESS &&
141 VALID_STAT(smb_fname->st) &&
142 S_ISLNK(smb_fname->st.st_ex_mode))
144 /* We can always delete a symlink. */
145 DBG_DEBUG("Not checking ACL on DELETE_ACCESS on symlink %s.\n",
146 smb_fname_str_dbg(smb_fname));
155 * If we can access the path to this file, by
156 * default we have FILE_READ_ATTRIBUTES from the
157 * containing directory. See the section:
158 * "Algorithm to Check Access to an Existing File"
161 * se_file_access_check() also takes care of
162 * owner WRITE_DAC and READ_CONTROL.
164 do_not_check_mask = FILE_READ_ATTRIBUTES;
167 * Samba 3.6 and earlier granted execute access even
168 * if the ACL did not contain execute rights.
169 * Samba 4.0 is more correct and checks it.
170 * The compatibilty mode allows one to skip this check
171 * to smoothen upgrades.
173 if (lp_acl_allow_execute_always(SNUM(conn))) {
174 do_not_check_mask |= FILE_EXECUTE;
177 status = se_file_access_check(sd,
178 get_current_nttok(conn),
180 (access_mask & ~do_not_check_mask),
183 DBG_DEBUG("File [%s] requesting [0x%x] returning [0x%x] (%s)\n",
184 smb_fname_str_dbg(smb_fname),
185 (unsigned int)access_mask,
186 (unsigned int)rejected_mask,
189 if (!NT_STATUS_IS_OK(status)) {
190 if (DEBUGLEVEL >= 10) {
191 DBG_DEBUG("acl for %s is:\n",
192 smb_fname_str_dbg(smb_fname));
193 NDR_PRINT_DEBUG(security_descriptor, sd);
199 if (NT_STATUS_IS_OK(status) ||
200 !NT_STATUS_EQUAL(status, NT_STATUS_ACCESS_DENIED))
205 /* Here we know status == NT_STATUS_ACCESS_DENIED. */
209 if ((access_mask & FILE_WRITE_ATTRIBUTES) &&
210 (rejected_mask & FILE_WRITE_ATTRIBUTES) &&
211 !lp_store_dos_attributes(SNUM(conn)) &&
212 (lp_map_readonly(SNUM(conn)) ||
213 lp_map_archive(SNUM(conn)) ||
214 lp_map_hidden(SNUM(conn)) ||
215 lp_map_system(SNUM(conn))))
217 rejected_mask &= ~FILE_WRITE_ATTRIBUTES;
219 DBG_DEBUG("overrode FILE_WRITE_ATTRIBUTES on file %s\n",
220 smb_fname_str_dbg(smb_fname));
223 if (parent_override_delete(conn,
230 * Were we trying to do an open for delete and didn't get DELETE
231 * access. Check if the directory allows DELETE_CHILD.
233 * http://blogs.msdn.com/oldnewthing/archive/2004/06/04/148426.aspx
237 rejected_mask &= ~DELETE_ACCESS;
239 DBG_DEBUG("Overrode DELETE_ACCESS on file %s\n",
240 smb_fname_str_dbg(smb_fname));
243 if (rejected_mask != 0) {
244 return NT_STATUS_ACCESS_DENIED;
249 NTSTATUS smbd_check_access_rights_fsp(struct files_struct *dirfsp,
250 struct files_struct *fsp,
252 uint32_t access_mask)
254 struct security_descriptor *sd = NULL;
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 * verison 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;
280 status = SMB_VFS_FGET_NT_ACL(fsp,
286 if (!NT_STATUS_IS_OK(status)) {
287 DBG_DEBUG("Could not get acl on %s: %s\n",
293 return smbd_check_access_rights_sd(fsp->conn,
302 * Given an fsp that represents a parent directory,
303 * check if the requested access can be granted.
305 NTSTATUS check_parent_access_fsp(struct files_struct *fsp,
306 uint32_t access_mask)
309 struct security_descriptor *parent_sd = NULL;
310 uint32_t access_granted = 0;
311 struct share_mode_lock *lck = NULL;
313 bool delete_on_close_set;
314 TALLOC_CTX *frame = talloc_stackframe();
316 if (get_current_uid(fsp->conn) == (uid_t)0) {
317 /* I'm sorry sir, I didn't know you were root... */
318 DBG_DEBUG("root override on %s. Granting 0x%x\n",
320 (unsigned int)access_mask);
321 status = NT_STATUS_OK;
325 status = SMB_VFS_FGET_NT_ACL(fsp,
330 if (!NT_STATUS_IS_OK(status)) {
331 DBG_INFO("SMB_VFS_FGET_NT_ACL failed for "
332 "%s with error %s\n",
339 * If we can access the path to this file, by
340 * default we have FILE_READ_ATTRIBUTES from the
341 * containing directory. See the section:
342 * "Algorithm to Check Access to an Existing File"
345 * se_file_access_check() also takes care of
346 * owner WRITE_DAC and READ_CONTROL.
348 status = se_file_access_check(parent_sd,
349 get_current_nttok(fsp->conn),
351 (access_mask & ~FILE_READ_ATTRIBUTES),
353 if(!NT_STATUS_IS_OK(status)) {
354 DBG_INFO("access check "
355 "on directory %s for mask 0x%x returned (0x%x) %s\n",
363 if (!(access_mask & (SEC_DIR_ADD_FILE | SEC_DIR_ADD_SUBDIR))) {
364 status = NT_STATUS_OK;
367 if (!lp_check_parent_directory_delete_on_close(SNUM(fsp->conn))) {
368 status = NT_STATUS_OK;
372 /* Check if the directory has delete-on-close set */
373 status = file_name_hash(fsp->conn,
374 fsp->fsp_name->base_name,
376 if (!NT_STATUS_IS_OK(status)) {
381 * Don't take a lock here. We just need a snapshot
382 * of the current state of delete on close and this is
383 * called in a codepath where we may already have a lock
384 * (and we explicitly can't hold 2 locks at the same time
385 * as that may deadlock).
387 lck = fetch_share_mode_unlocked(frame, fsp->file_id);
389 status = NT_STATUS_OK;
393 delete_on_close_set = is_delete_on_close_set(lck, name_hash);
394 if (delete_on_close_set) {
395 status = NT_STATUS_DELETE_PENDING;
399 status = NT_STATUS_OK;
406 /****************************************************************************
407 Ensure when opening a base file for a stream open that we have permissions
408 to do so given the access mask on the base file.
409 ****************************************************************************/
411 static NTSTATUS check_base_file_access(struct files_struct *fsp,
412 uint32_t access_mask)
416 status = smbd_calculate_access_mask_fsp(fsp->conn->cwd_fsp,
421 if (!NT_STATUS_IS_OK(status)) {
422 DEBUG(10, ("smbd_calculate_access_mask "
423 "on file %s returned %s\n",
429 if (access_mask & (FILE_WRITE_DATA|FILE_APPEND_DATA)) {
431 if (!CAN_WRITE(fsp->conn)) {
432 return NT_STATUS_ACCESS_DENIED;
434 dosattrs = fdos_mode(fsp);
435 if (IS_DOS_READONLY(dosattrs)) {
436 return NT_STATUS_ACCESS_DENIED;
440 return smbd_check_access_rights_fsp(fsp->conn->cwd_fsp,
446 /****************************************************************************
447 Handle differing symlink errno's
448 ****************************************************************************/
450 static NTSTATUS link_errno_convert(int err)
452 #if defined(ENOTSUP) && defined(OSF1)
453 /* handle special Tru64 errno */
454 if (err == ENOTSUP) {
459 /* fix broken NetBSD errno */
464 /* fix broken FreeBSD errno */
469 return NT_STATUS_STOPPED_ON_SYMLINK;
471 return map_nt_error_from_unix(err);
474 static NTSTATUS non_widelink_open(const struct files_struct *dirfsp,
476 struct smb_filename *smb_fname,
479 unsigned int link_depth);
481 /****************************************************************************
482 Follow a symlink in userspace.
483 ****************************************************************************/
485 static NTSTATUS process_symlink_open(const struct files_struct *dirfsp,
487 struct smb_filename *smb_fname,
490 unsigned int link_depth)
492 struct connection_struct *conn = dirfsp->conn;
493 const char *conn_rootdir = NULL;
494 struct smb_filename conn_rootdir_fname = { 0 };
495 char *link_target = NULL;
497 struct smb_filename *oldwd_fname = NULL;
498 size_t rootdir_len = 0;
499 struct smb_filename *resolved_fname = NULL;
500 char *resolved_name = NULL;
501 bool matched = false;
502 struct smb_filename *full_fname = NULL;
505 conn_rootdir = SMB_VFS_CONNECTPATH(conn, smb_fname);
506 if (conn_rootdir == NULL) {
507 return NT_STATUS_NO_MEMORY;
510 * With shadow_copy2 conn_rootdir can be talloc_freed
511 * whilst we use it in this function. We must take a copy.
513 conn_rootdir_fname.base_name = talloc_strdup(talloc_tos(),
515 if (conn_rootdir_fname.base_name == NULL) {
516 return NT_STATUS_NO_MEMORY;
520 * Ensure we don't get stuck in a symlink loop.
523 if (link_depth >= 20) {
524 status = NT_STATUS_STOPPED_ON_SYMLINK;
528 /* Allocate space for the link target. */
529 link_target = talloc_array(talloc_tos(), char, PATH_MAX);
530 if (link_target == NULL) {
531 status = NT_STATUS_NO_MEMORY;
536 * Read the link target. We do this just to verify that smb_fname indeed
537 * points at a symbolic link and return NT_STATUS_NOT_A_DIRECTORY
538 * and failure in case smb_fname is NOT a symlink.
540 * The caller needs this piece of information to distinguish two cases
541 * where open() fails with errno=ENOTDIR, cf the comment in
542 * non_widelink_open().
544 * We rely on SMB_VFS_REALPATH() to resolve the path including the
545 * symlink. Once we have SMB_VFS_STATX() or something similar in our VFS
546 * we may want to use that instead of SMB_VFS_READLINKAT().
548 link_len = SMB_VFS_READLINKAT(conn,
553 if (link_len == -1) {
554 status = NT_STATUS_INVALID_PARAMETER;
558 full_fname = full_path_from_dirfsp_atname(
559 talloc_tos(), dirfsp, smb_fname);
560 if (full_fname == NULL) {
561 status = NT_STATUS_NO_MEMORY;
565 /* Convert to an absolute path. */
566 resolved_fname = SMB_VFS_REALPATH(conn, talloc_tos(), full_fname);
567 if (resolved_fname == NULL) {
568 status = map_nt_error_from_unix(errno);
571 resolved_name = resolved_fname->base_name;
574 * We know conn_rootdir starts with '/' and
575 * does not end in '/'. FIXME ! Should we
578 rootdir_len = strlen(conn_rootdir_fname.base_name);
580 matched = (strncmp(conn_rootdir_fname.base_name,
584 status = NT_STATUS_STOPPED_ON_SYMLINK;
589 * Turn into a path relative to the share root.
591 if (resolved_name[rootdir_len] == '\0') {
592 /* Link to the root of the share. */
593 TALLOC_FREE(smb_fname->base_name);
594 smb_fname->base_name = talloc_strdup(smb_fname, ".");
595 } else if (resolved_name[rootdir_len] == '/') {
596 TALLOC_FREE(smb_fname->base_name);
597 smb_fname->base_name = talloc_strdup(smb_fname,
598 &resolved_name[rootdir_len+1]);
600 status = NT_STATUS_STOPPED_ON_SYMLINK;
604 if (smb_fname->base_name == NULL) {
605 status = NT_STATUS_NO_MEMORY;
609 oldwd_fname = vfs_GetWd(talloc_tos(), dirfsp->conn);
610 if (oldwd_fname == NULL) {
611 status = map_nt_error_from_unix(errno);
615 /* Ensure we operate from the root of the share. */
616 if (vfs_ChDir(conn, &conn_rootdir_fname) == -1) {
617 status = map_nt_error_from_unix(errno);
622 * And do it all again... As smb_fname is not relative to the passed in
623 * dirfsp anymore, we pass conn->cwd_fsp as dirfsp to
624 * non_widelink_open() to trigger the chdir(parentdir) logic.
626 status = non_widelink_open(conn->cwd_fsp,
635 TALLOC_FREE(resolved_fname);
636 TALLOC_FREE(link_target);
637 TALLOC_FREE(conn_rootdir_fname.base_name);
638 if (oldwd_fname != NULL) {
639 int ret = vfs_ChDir(conn, oldwd_fname);
641 smb_panic("unable to get back to old directory\n");
643 TALLOC_FREE(oldwd_fname);
649 /****************************************************************************
651 ****************************************************************************/
653 static NTSTATUS non_widelink_open(const struct files_struct *dirfsp,
655 struct smb_filename *smb_fname,
658 unsigned int link_depth)
660 struct connection_struct *conn = fsp->conn;
661 NTSTATUS saved_status;
662 NTSTATUS status = NT_STATUS_OK;
664 struct smb_filename *orig_fsp_name = fsp->fsp_name;
665 struct smb_filename *orig_base_fsp_name = NULL;
666 struct smb_filename *smb_fname_rel = NULL;
667 struct smb_filename *oldwd_fname = NULL;
668 struct smb_filename *parent_dir_fname = NULL;
669 bool have_opath = false;
676 if (dirfsp == conn->cwd_fsp) {
677 if (fsp->fsp_flags.is_directory) {
678 parent_dir_fname = cp_smb_filename(talloc_tos(), smb_fname);
679 if (parent_dir_fname == NULL) {
680 status = NT_STATUS_NO_MEMORY;
684 smb_fname_rel = synthetic_smb_fname(parent_dir_fname,
686 smb_fname->stream_name,
690 if (smb_fname_rel == NULL) {
691 status = NT_STATUS_NO_MEMORY;
695 status = SMB_VFS_PARENT_PATHNAME(fsp->conn,
700 if (!NT_STATUS_IS_OK(status)) {
705 if (!ISDOT(parent_dir_fname->base_name)) {
706 oldwd_fname = vfs_GetWd(talloc_tos(), conn);
707 if (oldwd_fname == NULL) {
708 status = map_nt_error_from_unix(errno);
712 /* Pin parent directory in place. */
713 if (vfs_ChDir(conn, parent_dir_fname) == -1) {
714 status = map_nt_error_from_unix(errno);
719 /* Ensure the relative path is below the share. */
720 status = check_reduced_name(conn, parent_dir_fname, smb_fname_rel);
721 if (!NT_STATUS_IS_OK(status)) {
725 /* Setup fsp->fsp_name to be relative to cwd */
726 fsp->fsp_name = smb_fname_rel;
728 /* Also setup base_fsp to be relative to the new cwd */
729 if (fsp->base_fsp != NULL) {
730 struct smb_filename *base_smb_fname_rel = NULL;
732 /* Check the invarient is true. */
733 SMB_ASSERT(fsp->base_fsp->fsp_name->fsp ==
736 base_smb_fname_rel = synthetic_smb_fname(
738 smb_fname_rel->base_name,
742 smb_fname_rel->flags);
743 if (base_smb_fname_rel == NULL) {
744 status = NT_STATUS_NO_MEMORY;
748 base_smb_fname_rel->fsp = fsp->base_fsp;
750 orig_base_fsp_name = fsp->base_fsp->fsp_name;
751 fsp->base_fsp->fsp_name = base_smb_fname_rel;
754 * We should have preserved the invarient
755 * fsp->base_fsp->fsp_name->fsp == fsp->base_fsp.
757 SMB_ASSERT(fsp->base_fsp->fsp_name->fsp ==
762 * fsp->fsp_name is unchanged as it is already correctly
763 * relative to conn->cwd.
765 smb_fname_rel = smb_fname;
770 fd = SMB_VFS_OPENAT(conn,
777 status = link_errno_convert(errno);
782 ret = SMB_VFS_FSTAT(fsp, &fsp->fsp_name->st);
784 status = map_nt_error_from_unix(errno);
787 orig_fsp_name->st = fsp->fsp_name->st;
790 if (!is_ntfs_stream_smb_fname(fsp->fsp_name) &&
791 fsp->fsp_flags.is_pathref &&
795 * Opening with O_PATH and O_NOFOLLOW opens a handle on the
796 * symlink. In follow symlink=yes mode we must avoid this and
797 * instead should open a handle on the symlink target.
799 * Check for this case by doing an fstat, forcing
800 * process_symlink_open() codepath down below by setting fd=-1
803 if (S_ISLNK(fsp->fsp_name->st.st_ex_mode)) {
804 ret = SMB_VFS_CLOSE(fsp);
805 SMB_ASSERT(ret == 0);
809 status = NT_STATUS_STOPPED_ON_SYMLINK;
814 (NT_STATUS_EQUAL(status, NT_STATUS_STOPPED_ON_SYMLINK) ||
815 NT_STATUS_EQUAL(status, NT_STATUS_NOT_A_DIRECTORY)))
818 * Trying to open a symlink to a directory with O_NOFOLLOW and
819 * O_DIRECTORY can return either of ELOOP and ENOTDIR. So
820 * ENOTDIR really means: might be a symlink, but we're not sure.
821 * In this case, we just assume there's a symlink. If we were
822 * wrong, process_symlink_open() will return EINVAL. We check
823 * this below, and fall back to returning the initial
826 * BUG: https://bugzilla.samba.org/show_bug.cgi?id=12860
828 saved_status = status;
830 if (fsp->fsp_name->flags & SMB_FILENAME_POSIX_PATH) {
831 /* Never follow symlinks on posix open. */
834 if (!lp_follow_symlinks(SNUM(conn))) {
835 /* Explicitly no symlinks. */
839 fsp->fsp_name = orig_fsp_name;
842 * We may have a symlink. Follow in userspace
843 * to ensure it's under the share definition.
845 status = process_symlink_open(dirfsp,
851 if (NT_STATUS_EQUAL(status, NT_STATUS_INVALID_PARAMETER) &&
852 NT_STATUS_EQUAL(saved_status, NT_STATUS_NOT_A_DIRECTORY))
854 status = saved_status;
859 fsp->fsp_name = orig_fsp_name;
860 if (fsp->base_fsp != NULL) {
861 /* Save off the temporary name. */
862 struct smb_filename *base_smb_fname_rel =
863 fsp->base_fsp->fsp_name;
864 /* It no longer has an associated fsp. */
865 base_smb_fname_rel->fsp = NULL;
867 /* Replace the original name. */
868 fsp->base_fsp->fsp_name = orig_base_fsp_name;
870 * We should have preserved the invarient
871 * fsp->base_fsp->fsp_name->fsp == fsp->base_fsp.
873 SMB_ASSERT(fsp->base_fsp->fsp_name->fsp == fsp->base_fsp);
874 TALLOC_FREE(base_smb_fname_rel);
876 TALLOC_FREE(parent_dir_fname);
878 if (oldwd_fname != NULL) {
879 ret = vfs_ChDir(conn, oldwd_fname);
881 smb_panic("unable to get back to old directory\n");
883 TALLOC_FREE(oldwd_fname);
888 /****************************************************************************
889 fd support routines - attempt to do a dos_open.
890 ****************************************************************************/
892 NTSTATUS fd_openat(const struct files_struct *dirfsp,
893 struct smb_filename *smb_fname,
898 struct connection_struct *conn = fsp->conn;
899 NTSTATUS status = NT_STATUS_OK;
902 * Never follow symlinks on a POSIX client. The
903 * client should be doing this.
906 if ((fsp->posix_flags & FSP_POSIX_FLAGS_OPEN) || !lp_follow_symlinks(SNUM(conn))) {
911 * Only follow symlinks within a share
914 status = non_widelink_open(dirfsp, fsp, smb_fname, flags, mode, 0);
915 if (!NT_STATUS_IS_OK(status)) {
916 if (NT_STATUS_EQUAL(status, NT_STATUS_TOO_MANY_OPENED_FILES)) {
917 static time_t last_warned = 0L;
919 if (time((time_t *) NULL) > last_warned) {
920 DEBUG(0,("Too many open files, unable "
921 "to open more! smbd's max "
923 lp_max_open_files()));
924 last_warned = time((time_t *) NULL);
928 DBG_DEBUG("name %s, flags = 0%o mode = 0%o, fd = %d. %s\n",
929 smb_fname_str_dbg(smb_fname), flags, (int)mode,
930 fsp_get_pathref_fd(fsp), nt_errstr(status));
934 DBG_DEBUG("name %s, flags = 0%o mode = 0%o, fd = %d\n",
935 smb_fname_str_dbg(smb_fname), flags, (int)mode,
936 fsp_get_pathref_fd(fsp));
941 /****************************************************************************
942 Close the file associated with a fsp.
943 ****************************************************************************/
945 NTSTATUS fd_close(files_struct *fsp)
949 if (fsp == fsp->conn->cwd_fsp) {
956 if (fsp_get_pathref_fd(fsp) == -1) {
958 * Either a directory where the dptr_CloseDir() already closed
959 * the fd or a stat open.
963 if (fh_get_refcount(fsp->fh) > 1) {
964 return NT_STATUS_OK; /* Shared handle. Only close last reference. */
967 ret = SMB_VFS_CLOSE(fsp);
970 return map_nt_error_from_unix(errno);
975 /****************************************************************************
976 Change the ownership of a file to that of the parent directory.
977 Do this by fd if possible.
978 ****************************************************************************/
980 static void change_file_owner_to_parent_fsp(struct files_struct *parent_fsp,
981 struct files_struct *fsp)
985 if (parent_fsp->fsp_name->st.st_ex_uid == fsp->fsp_name->st.st_ex_uid) {
986 /* Already this uid - no need to change. */
987 DBG_DEBUG("file %s is already owned by uid %u\n",
989 (unsigned int)fsp->fsp_name->st.st_ex_uid);
994 ret = SMB_VFS_FCHOWN(fsp,
995 parent_fsp->fsp_name->st.st_ex_uid,
999 DBG_ERR("failed to fchown "
1000 "file %s to parent directory uid %u. Error "
1003 (unsigned int)parent_fsp->fsp_name->st.st_ex_uid,
1006 DBG_DEBUG("changed new file %s to "
1007 "parent directory uid %u.\n",
1009 (unsigned int)parent_fsp->fsp_name->st.st_ex_uid);
1010 /* Ensure the uid entry is updated. */
1011 fsp->fsp_name->st.st_ex_uid =
1012 parent_fsp->fsp_name->st.st_ex_uid;
1016 static NTSTATUS change_dir_owner_to_parent_fsp(struct files_struct *parent_fsp,
1017 struct files_struct *fsp)
1022 if (parent_fsp->fsp_name->st.st_ex_uid == fsp->fsp_name->st.st_ex_uid) {
1023 /* Already this uid - no need to change. */
1024 DBG_DEBUG("directory %s is already owned by uid %u\n",
1026 (unsigned int)fsp->fsp_name->st.st_ex_uid);
1027 return NT_STATUS_OK;
1031 ret = SMB_VFS_FCHOWN(fsp,
1032 parent_fsp->fsp_name->st.st_ex_uid,
1036 status = map_nt_error_from_unix(errno);
1037 DBG_ERR("failed to chown "
1038 "directory %s to parent directory uid %u. "
1041 (unsigned int)parent_fsp->fsp_name->st.st_ex_uid,
1046 DBG_DEBUG("changed ownership of new "
1047 "directory %s to parent directory uid %u.\n",
1049 (unsigned int)parent_fsp->fsp_name->st.st_ex_uid);
1051 /* Ensure the uid entry is updated. */
1052 fsp->fsp_name->st.st_ex_uid = parent_fsp->fsp_name->st.st_ex_uid;
1054 return NT_STATUS_OK;
1057 /****************************************************************************
1058 Open a file - returning a guaranteed ATOMIC indication of if the
1059 file was created or not.
1060 ****************************************************************************/
1062 static NTSTATUS fd_open_atomic(files_struct *fsp,
1067 NTSTATUS status = NT_STATUS_UNSUCCESSFUL;
1068 NTSTATUS retry_status;
1069 bool file_existed = VALID_STAT(fsp->fsp_name->st);
1072 if (!(flags & O_CREAT)) {
1074 * We're not creating the file, just pass through.
1076 status = fd_openat(fsp->conn->cwd_fsp, fsp->fsp_name, fsp, flags, mode);
1077 *file_created = false;
1081 if (flags & O_EXCL) {
1083 * Fail if already exists, just pass through.
1085 status = fd_openat(fsp->conn->cwd_fsp, fsp->fsp_name, fsp, flags, mode);
1088 * Here we've opened with O_CREAT|O_EXCL. If that went
1089 * NT_STATUS_OK, we *know* we created this file.
1091 *file_created = NT_STATUS_IS_OK(status);
1097 * Now it gets tricky. We have O_CREAT, but not O_EXCL.
1098 * To know absolutely if we created the file or not,
1099 * we can never call O_CREAT without O_EXCL. So if
1100 * we think the file existed, try without O_CREAT|O_EXCL.
1101 * If we think the file didn't exist, try with
1104 * The big problem here is dangling symlinks. Opening
1105 * without O_NOFOLLOW means both bad symlink
1106 * and missing path return -1, ENOENT from open(). As POSIX
1107 * is pathname based it's not possible to tell
1108 * the difference between these two cases in a
1109 * non-racy way, so change to try only two attempts before
1112 * We don't have this problem for the O_NOFOLLOW
1113 * case as it just returns NT_STATUS_OBJECT_PATH_NOT_FOUND
1114 * mapped from the ELOOP POSIX error.
1118 curr_flags = flags & ~(O_CREAT);
1119 retry_status = NT_STATUS_OBJECT_NAME_NOT_FOUND;
1121 curr_flags = flags | O_EXCL;
1122 retry_status = NT_STATUS_OBJECT_NAME_COLLISION;
1125 status = fd_openat(fsp->conn->cwd_fsp, fsp->fsp_name, fsp, curr_flags, mode);
1126 if (NT_STATUS_IS_OK(status)) {
1127 *file_created = !file_existed;
1128 return NT_STATUS_OK;
1130 if (NT_STATUS_EQUAL(status, retry_status)) {
1132 file_existed = !file_existed;
1134 DBG_DEBUG("File %s %s. Retry.\n",
1136 file_existed ? "existed" : "did not exist");
1139 curr_flags = flags & ~(O_CREAT);
1141 curr_flags = flags | O_EXCL;
1144 status = fd_openat(fsp->conn->cwd_fsp, fsp->fsp_name, fsp, curr_flags, mode);
1147 *file_created = (NT_STATUS_IS_OK(status) && !file_existed);
1151 static NTSTATUS reopen_from_procfd(struct files_struct *fsp,
1155 struct smb_filename proc_fname;
1156 const char *p = NULL;
1163 if (!fsp->fsp_flags.have_proc_fds) {
1164 return NT_STATUS_MORE_PROCESSING_REQUIRED;
1167 old_fd = fsp_get_pathref_fd(fsp);
1169 return NT_STATUS_MORE_PROCESSING_REQUIRED;
1172 if (!fsp->fsp_flags.is_pathref) {
1173 DBG_ERR("[%s] is not a pathref\n",
1176 smb_panic("Not a pathref");
1178 return NT_STATUS_INVALID_HANDLE;
1181 p = sys_proc_fd_path(old_fd, buf, sizeof(buf));
1183 return NT_STATUS_NO_MEMORY;
1186 proc_fname = (struct smb_filename) {
1187 .base_name = discard_const_p(char, p),
1190 fsp->fsp_flags.is_pathref = false;
1192 new_fd = SMB_VFS_OPENAT(fsp->conn,
1199 status = map_nt_error_from_unix(errno);
1201 fsp_set_fd(fsp, -1);
1205 ret = SMB_VFS_CLOSE(fsp);
1206 fsp_set_fd(fsp, -1);
1208 return map_nt_error_from_unix(errno);
1211 fsp_set_fd(fsp, new_fd);
1212 return NT_STATUS_OK;
1215 static NTSTATUS reopen_from_fsp(struct files_struct *fsp,
1218 bool *p_file_created)
1220 bool __unused_file_created = false;
1223 if (p_file_created == NULL) {
1224 p_file_created = &__unused_file_created;
1228 * TODO: should we move this to the VFS layer?
1229 * SMB_VFS_REOPEN_FSP()?
1232 status = reopen_from_procfd(fsp,
1235 if (NT_STATUS_EQUAL(status, NT_STATUS_MORE_PROCESSING_REQUIRED)) {
1237 * Close the existing pathref fd and set the fsp flag
1238 * is_pathref to false so we get a "normal" fd this
1241 status = fd_close(fsp);
1242 if (!NT_STATUS_IS_OK(status)) {
1246 fsp->fsp_flags.is_pathref = false;
1248 status = fd_open_atomic(fsp,
1257 /****************************************************************************
1259 ****************************************************************************/
1261 static NTSTATUS open_file(files_struct *fsp,
1262 struct smb_request *req,
1263 struct smb_filename *parent_dir,
1266 uint32_t access_mask, /* client requested access mask. */
1267 uint32_t open_access_mask, /* what we're actually using in the open. */
1268 uint32_t private_flags,
1269 bool *p_file_created)
1271 connection_struct *conn = fsp->conn;
1272 struct smb_filename *smb_fname = fsp->fsp_name;
1273 NTSTATUS status = NT_STATUS_OK;
1274 int accmode = (flags & O_ACCMODE);
1275 int local_flags = flags;
1276 bool file_existed = VALID_STAT(fsp->fsp_name->st);
1277 uint32_t need_fd_mask =
1283 WRITE_OWNER_ACCESS |
1284 SEC_FLAG_SYSTEM_SECURITY |
1285 READ_CONTROL_ACCESS;
1286 bool creating = !file_existed && (flags & O_CREAT);
1287 bool truncating = (flags & O_TRUNC);
1288 bool open_fd = false;
1291 * Catch early an attempt to open an existing
1292 * directory as a file.
1294 if (file_existed && S_ISDIR(fsp->fsp_name->st.st_ex_mode)) {
1295 return NT_STATUS_FILE_IS_A_DIRECTORY;
1298 /* Check permissions */
1301 * This code was changed after seeing a client open request
1302 * containing the open mode of (DENY_WRITE/read-only) with
1303 * the 'create if not exist' bit set. The previous code
1304 * would fail to open the file read only on a read-only share
1305 * as it was checking the flags parameter directly against O_RDONLY,
1306 * this was failing as the flags parameter was set to O_RDONLY|O_CREAT.
1310 if (!CAN_WRITE(conn)) {
1311 /* It's a read-only share - fail if we wanted to write. */
1312 if(accmode != O_RDONLY || (flags & O_TRUNC) || (flags & O_APPEND)) {
1313 DEBUG(3,("Permission denied opening %s\n",
1314 smb_fname_str_dbg(smb_fname)));
1315 return NT_STATUS_ACCESS_DENIED;
1317 if (flags & O_CREAT) {
1318 /* We don't want to write - but we must make sure that
1319 O_CREAT doesn't create the file if we have write
1320 access into the directory.
1322 flags &= ~(O_CREAT|O_EXCL);
1323 local_flags &= ~(O_CREAT|O_EXCL);
1328 * This little piece of insanity is inspired by the
1329 * fact that an NT client can open a file for O_RDONLY,
1330 * but set the create disposition to FILE_EXISTS_TRUNCATE.
1331 * If the client *can* write to the file, then it expects to
1332 * truncate the file, even though it is opening for readonly.
1333 * Quicken uses this stupid trick in backup file creation...
1334 * Thanks *greatly* to "David W. Chapman Jr." <dwcjr@inethouston.net>
1335 * for helping track this one down. It didn't bite us in 2.0.x
1336 * as we always opened files read-write in that release. JRA.
1339 if ((accmode == O_RDONLY) && ((flags & O_TRUNC) == O_TRUNC)) {
1340 DEBUG(10,("open_file: truncate requested on read-only open "
1341 "for file %s\n", smb_fname_str_dbg(smb_fname)));
1342 local_flags = (flags & ~O_ACCMODE)|O_RDWR;
1345 if ((open_access_mask & need_fd_mask) || creating || truncating) {
1353 #if defined(O_NONBLOCK) && defined(S_ISFIFO)
1355 * We would block on opening a FIFO with no one else on the
1356 * other end. Do what we used to do and add O_NONBLOCK to the
1360 if (file_existed && S_ISFIFO(smb_fname->st.st_ex_mode)) {
1361 local_flags &= ~O_TRUNC; /* Can't truncate a FIFO. */
1362 local_flags |= O_NONBLOCK;
1367 /* Don't create files with Microsoft wildcard characters. */
1368 if (fsp->base_fsp) {
1370 * wildcard characters are allowed in stream names
1371 * only test the basefilename
1373 wild = fsp->base_fsp->fsp_name->base_name;
1375 wild = smb_fname->base_name;
1377 if ((local_flags & O_CREAT) && !file_existed &&
1378 !(fsp->posix_flags & FSP_POSIX_FLAGS_PATHNAMES) &&
1379 ms_has_wild(wild)) {
1380 return NT_STATUS_OBJECT_NAME_INVALID;
1383 /* Can we access this file ? */
1384 if (!fsp->base_fsp) {
1385 /* Only do this check on non-stream open. */
1387 status = smbd_check_access_rights_fsp(
1393 if (!NT_STATUS_IS_OK(status)) {
1394 DBG_DEBUG("smbd_check_access_rights_fsp"
1395 " on file %s returned %s\n",
1400 if (!NT_STATUS_IS_OK(status) &&
1401 !NT_STATUS_EQUAL(status,
1402 NT_STATUS_OBJECT_NAME_NOT_FOUND))
1407 if (NT_STATUS_EQUAL(status,
1408 NT_STATUS_OBJECT_NAME_NOT_FOUND))
1410 DEBUG(10, ("open_file: "
1411 "file %s vanished since we "
1412 "checked for existence.\n",
1413 smb_fname_str_dbg(smb_fname)));
1414 file_existed = false;
1415 SET_STAT_INVALID(fsp->fsp_name->st);
1419 if (!file_existed) {
1420 if (!(local_flags & O_CREAT)) {
1421 /* File didn't exist and no O_CREAT. */
1422 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
1425 status = check_parent_access_fsp(
1428 if (!NT_STATUS_IS_OK(status)) {
1429 DBG_DEBUG("check_parent_access_fsp on "
1430 "directory %s for file %s "
1432 smb_fname_str_dbg(parent_dir),
1433 smb_fname_str_dbg(smb_fname),
1441 * Actually do the open - if O_TRUNC is needed handle it
1442 * below under the share mode lock.
1444 status = reopen_from_fsp(fsp,
1445 local_flags & ~O_TRUNC,
1448 if (NT_STATUS_EQUAL(status, NT_STATUS_STOPPED_ON_SYMLINK)) {
1450 * POSIX client that hit a symlink. We don't want to
1451 * return NT_STATUS_STOPPED_ON_SYMLINK to avoid handling
1452 * this special error code in all callers, so we map
1453 * this to NT_STATUS_OBJECT_PATH_NOT_FOUND. Historically
1454 * the lower level functions returned status code mapped
1455 * from errno by map_nt_error_from_unix() where ELOOP is
1456 * mapped to NT_STATUS_OBJECT_PATH_NOT_FOUND.
1458 status = NT_STATUS_OBJECT_PATH_NOT_FOUND;
1460 if (!NT_STATUS_IS_OK(status)) {
1461 DEBUG(3,("Error opening file %s (%s) (local_flags=%d) "
1462 "(flags=%d)\n", smb_fname_str_dbg(smb_fname),
1463 nt_errstr(status),local_flags,flags));
1467 if (local_flags & O_NONBLOCK) {
1469 * GPFS can return ETIMEDOUT for pread on
1470 * nonblocking file descriptors when files
1471 * migrated to tape need to be recalled. I
1472 * could imagine this happens elsewhere
1473 * too. With blocking file descriptors this
1476 ret = vfs_set_blocking(fsp, true);
1478 status = map_nt_error_from_unix(errno);
1479 DBG_WARNING("Could not set fd to blocking: "
1480 "%s\n", strerror(errno));
1486 if (*p_file_created) {
1487 /* We created this file. */
1489 bool need_re_stat = false;
1490 /* Do all inheritance work after we've
1491 done a successful fstat call and filled
1492 in the stat struct in fsp->fsp_name. */
1494 /* Inherit the ACL if required */
1495 if (lp_inherit_permissions(SNUM(conn))) {
1496 inherit_access_posix_acl(conn,
1500 need_re_stat = true;
1503 /* Change the owner if required. */
1504 if (lp_inherit_owner(SNUM(conn)) != INHERIT_OWNER_NO) {
1505 change_file_owner_to_parent_fsp(parent_dir->fsp,
1507 need_re_stat = true;
1511 ret = SMB_VFS_FSTAT(fsp, &smb_fname->st);
1513 * If we have an fd, this stat should succeed.
1516 status = map_nt_error_from_unix(errno);
1517 DBG_ERR("Error doing fstat on open "
1519 smb_fname_str_dbg(smb_fname),
1526 notify_fname(conn, NOTIFY_ACTION_ADDED,
1527 FILE_NOTIFY_CHANGE_FILE_NAME,
1528 smb_fname->base_name);
1531 if (!file_existed) {
1532 /* File must exist for a stat open. */
1533 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
1536 if (S_ISLNK(smb_fname->st.st_ex_mode) &&
1537 !(fsp->posix_flags & FSP_POSIX_FLAGS_OPEN))
1540 * Don't allow stat opens on symlinks directly unless
1541 * it's a POSIX open.
1543 return NT_STATUS_OBJECT_PATH_NOT_FOUND;
1546 if (!fsp->fsp_flags.is_pathref) {
1548 * There is only one legit case where end up here:
1549 * openat_pathref_fsp() failed to open a symlink, so the
1550 * fsp was created by fsp_new() which doesn't set
1551 * is_pathref. Other then that, we should always have a
1552 * pathref fsp at this point. The subsequent checks
1555 if (!(smb_fname->flags & SMB_FILENAME_POSIX_PATH)) {
1556 DBG_ERR("[%s] is not a POSIX pathname\n",
1557 smb_fname_str_dbg(smb_fname));
1558 return NT_STATUS_INTERNAL_ERROR;
1560 if (!S_ISLNK(smb_fname->st.st_ex_mode)) {
1561 DBG_ERR("[%s] is not a symlink\n",
1562 smb_fname_str_dbg(smb_fname));
1563 return NT_STATUS_INTERNAL_ERROR;
1565 if (fsp_get_pathref_fd(fsp) != -1) {
1566 DBG_ERR("fd for [%s] is not -1: fd [%d]\n",
1567 smb_fname_str_dbg(smb_fname),
1568 fsp_get_pathref_fd(fsp));
1569 return NT_STATUS_INTERNAL_ERROR;
1573 status = smbd_check_access_rights_fsp(parent_dir->fsp,
1578 if (NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND) &&
1579 (fsp->posix_flags & FSP_POSIX_FLAGS_OPEN) &&
1580 S_ISLNK(smb_fname->st.st_ex_mode)) {
1581 /* This is a POSIX stat open for delete
1582 * or rename on a symlink that points
1583 * nowhere. Allow. */
1584 DEBUG(10,("open_file: allowing POSIX "
1585 "open on bad symlink %s\n",
1586 smb_fname_str_dbg(smb_fname)));
1587 status = NT_STATUS_OK;
1590 if (!NT_STATUS_IS_OK(status)) {
1591 DBG_DEBUG("smbd_check_access_rights_fsp on file "
1599 fsp->file_id = vfs_file_id_from_sbuf(conn, &smb_fname->st);
1600 fsp->vuid = req ? req->vuid : UID_FIELD_INVALID;
1601 fsp->file_pid = req ? req->smbpid : 0;
1602 fsp->fsp_flags.can_lock = true;
1603 fsp->fsp_flags.can_read = ((access_mask & FILE_READ_DATA) != 0);
1604 fsp->fsp_flags.can_write =
1606 ((access_mask & (FILE_WRITE_DATA | FILE_APPEND_DATA)) != 0);
1607 fsp->print_file = NULL;
1608 fsp->fsp_flags.modified = false;
1609 fsp->sent_oplock_break = NO_BREAK_SENT;
1610 fsp->fsp_flags.is_directory = false;
1611 if (conn->aio_write_behind_list &&
1612 is_in_path(smb_fname->base_name, conn->aio_write_behind_list,
1613 conn->case_sensitive)) {
1614 fsp->fsp_flags.aio_write_behind = true;
1617 DEBUG(2,("%s opened file %s read=%s write=%s (numopen=%d)\n",
1618 conn->session_info->unix_info->unix_name,
1619 smb_fname_str_dbg(smb_fname),
1620 BOOLSTR(fsp->fsp_flags.can_read),
1621 BOOLSTR(fsp->fsp_flags.can_write),
1622 conn->num_files_open));
1624 return NT_STATUS_OK;
1627 static bool mask_conflict(
1628 uint32_t new_access,
1629 uint32_t existing_access,
1630 uint32_t access_mask,
1631 uint32_t new_sharemode,
1632 uint32_t existing_sharemode,
1633 uint32_t sharemode_mask)
1635 bool want_access = (new_access & access_mask);
1636 bool allow_existing = (existing_sharemode & sharemode_mask);
1637 bool have_access = (existing_access & access_mask);
1638 bool allow_new = (new_sharemode & sharemode_mask);
1640 if (want_access && !allow_existing) {
1641 DBG_DEBUG("Access request 0x%"PRIx32"/0x%"PRIx32" conflicts "
1642 "with existing sharemode 0x%"PRIx32"/0x%"PRIx32"\n",
1649 if (have_access && !allow_new) {
1650 DBG_DEBUG("Sharemode request 0x%"PRIx32"/0x%"PRIx32" conflicts "
1651 "with existing access 0x%"PRIx32"/0x%"PRIx32"\n",
1661 /****************************************************************************
1662 Check if we can open a file with a share mode.
1663 Returns True if conflict, False if not.
1664 ****************************************************************************/
1666 static const uint32_t conflicting_access =
1673 static bool share_conflict(uint32_t e_access_mask,
1674 uint32_t e_share_access,
1675 uint32_t access_mask,
1676 uint32_t share_access)
1680 DBG_DEBUG("existing access_mask = 0x%"PRIx32", "
1681 "existing share access = 0x%"PRIx32", "
1682 "access_mask = 0x%"PRIx32", "
1683 "share_access = 0x%"PRIx32"\n",
1689 if ((e_access_mask & conflicting_access) == 0) {
1690 DBG_DEBUG("No conflict due to "
1691 "existing access_mask = 0x%"PRIx32"\n",
1695 if ((access_mask & conflicting_access) == 0) {
1696 DBG_DEBUG("No conflict due to access_mask = 0x%"PRIx32"\n",
1701 conflict = mask_conflict(
1702 access_mask, e_access_mask, FILE_WRITE_DATA | FILE_APPEND_DATA,
1703 share_access, e_share_access, FILE_SHARE_WRITE);
1704 conflict |= mask_conflict(
1705 access_mask, e_access_mask, FILE_READ_DATA | FILE_EXECUTE,
1706 share_access, e_share_access, FILE_SHARE_READ);
1707 conflict |= mask_conflict(
1708 access_mask, e_access_mask, DELETE_ACCESS,
1709 share_access, e_share_access, FILE_SHARE_DELETE);
1711 DBG_DEBUG("conflict=%s\n", conflict ? "true" : "false");
1715 #if defined(DEVELOPER)
1717 struct validate_my_share_entries_state {
1718 struct smbd_server_connection *sconn;
1720 struct server_id self;
1723 static bool validate_my_share_entries_fn(
1724 struct share_mode_entry *e,
1728 struct validate_my_share_entries_state *state = private_data;
1731 if (!server_id_equal(&state->self, &e->pid)) {
1735 if (e->op_mid == 0) {
1736 /* INTERNAL_OPEN_ONLY */
1740 fsp = file_find_dif(state->sconn, state->fid, e->share_file_id);
1742 DBG_ERR("PANIC : %s\n",
1743 share_mode_str(talloc_tos(), 0, &state->fid, e));
1744 smb_panic("validate_my_share_entries: Cannot match a "
1745 "share entry with an open file\n");
1748 if (((uint16_t)fsp->oplock_type) != e->op_type) {
1757 DBG_ERR("validate_my_share_entries: PANIC : %s\n",
1758 share_mode_str(talloc_tos(), 0, &state->fid, e));
1759 str = talloc_asprintf(talloc_tos(),
1760 "validate_my_share_entries: "
1761 "file %s, oplock_type = 0x%x, op_type = 0x%x\n",
1762 fsp->fsp_name->base_name,
1763 (unsigned int)fsp->oplock_type,
1764 (unsigned int)e->op_type);
1773 * Allowed access mask for stat opens relevant to oplocks
1775 bool is_oplock_stat_open(uint32_t access_mask)
1777 const uint32_t stat_open_bits =
1778 (SYNCHRONIZE_ACCESS|
1779 FILE_READ_ATTRIBUTES|
1780 FILE_WRITE_ATTRIBUTES);
1782 return (((access_mask & stat_open_bits) != 0) &&
1783 ((access_mask & ~stat_open_bits) == 0));
1787 * Allowed access mask for stat opens relevant to leases
1789 bool is_lease_stat_open(uint32_t access_mask)
1791 const uint32_t stat_open_bits =
1792 (SYNCHRONIZE_ACCESS|
1793 FILE_READ_ATTRIBUTES|
1794 FILE_WRITE_ATTRIBUTES|
1795 READ_CONTROL_ACCESS);
1797 return (((access_mask & stat_open_bits) != 0) &&
1798 ((access_mask & ~stat_open_bits) == 0));
1801 struct has_delete_on_close_state {
1805 static bool has_delete_on_close_fn(
1806 struct share_mode_entry *e,
1810 struct has_delete_on_close_state *state = private_data;
1811 state->ret = !share_entry_stale_pid(e);
1815 static bool has_delete_on_close(struct share_mode_lock *lck,
1818 struct has_delete_on_close_state state = { .ret = false };
1821 if (!is_delete_on_close_set(lck, name_hash)) {
1825 ok= share_mode_forall_entries(lck, has_delete_on_close_fn, &state);
1827 DBG_DEBUG("share_mode_forall_entries failed\n");
1833 static void share_mode_flags_restrict(
1834 struct share_mode_lock *lck,
1835 uint32_t access_mask,
1836 uint32_t share_mode,
1837 uint32_t lease_type)
1839 uint32_t existing_access_mask, existing_share_mode;
1840 uint32_t existing_lease_type;
1842 share_mode_flags_get(
1844 &existing_access_mask,
1845 &existing_share_mode,
1846 &existing_lease_type);
1848 existing_access_mask |= access_mask;
1849 if (access_mask & conflicting_access) {
1850 existing_share_mode &= share_mode;
1852 existing_lease_type |= lease_type;
1854 share_mode_flags_set(
1856 existing_access_mask,
1857 existing_share_mode,
1858 existing_lease_type,
1862 /****************************************************************************
1863 Deal with share modes
1864 Invariant: Share mode must be locked on entry and exit.
1865 Returns -1 on error, or number of share modes on success (may be zero).
1866 ****************************************************************************/
1868 struct open_mode_check_state {
1870 uint32_t access_mask;
1871 uint32_t share_access;
1872 uint32_t lease_type;
1875 static bool open_mode_check_fn(
1876 struct share_mode_entry *e,
1880 struct open_mode_check_state *state = private_data;
1881 bool disconnected, stale;
1882 uint32_t access_mask, share_access, lease_type;
1884 disconnected = server_id_is_disconnected(&e->pid);
1889 access_mask = state->access_mask | e->access_mask;
1890 share_access = state->share_access;
1891 if (e->access_mask & conflicting_access) {
1892 share_access &= e->share_access;
1894 lease_type = state->lease_type | get_lease_type(e, state->fid);
1896 if ((access_mask == state->access_mask) &&
1897 (share_access == state->share_access) &&
1898 (lease_type == state->lease_type)) {
1902 stale = share_entry_stale_pid(e);
1907 state->access_mask = access_mask;
1908 state->share_access = share_access;
1909 state->lease_type = lease_type;
1914 static NTSTATUS open_mode_check(connection_struct *conn,
1916 struct share_mode_lock *lck,
1917 uint32_t access_mask,
1918 uint32_t share_access)
1920 struct open_mode_check_state state;
1922 bool modified = false;
1924 if (is_oplock_stat_open(access_mask)) {
1925 /* Stat open that doesn't trigger oplock breaks or share mode
1926 * checks... ! JRA. */
1927 return NT_STATUS_OK;
1931 * Check if the share modes will give us access.
1934 #if defined(DEVELOPER)
1936 struct validate_my_share_entries_state validate_state = {
1937 .sconn = conn->sconn,
1939 .self = messaging_server_id(conn->sconn->msg_ctx),
1941 ok = share_mode_forall_entries(
1942 lck, validate_my_share_entries_fn, &validate_state);
1947 share_mode_flags_get(
1948 lck, &state.access_mask, &state.share_access, NULL);
1950 conflict = share_conflict(
1956 DBG_DEBUG("No conflict due to share_mode_flags access\n");
1957 return NT_STATUS_OK;
1960 state = (struct open_mode_check_state) {
1962 .share_access = (FILE_SHARE_READ|
1968 * Walk the share mode array to recalculate d->flags
1971 ok = share_mode_forall_entries(lck, open_mode_check_fn, &state);
1973 DBG_DEBUG("share_mode_forall_entries failed\n");
1974 return NT_STATUS_INTERNAL_ERROR;
1977 share_mode_flags_set(
1985 * We only end up here if we had a sharing violation
1986 * from d->flags and have recalculated it.
1988 return NT_STATUS_SHARING_VIOLATION;
1991 conflict = share_conflict(
1997 DBG_DEBUG("No conflict due to share_mode_flags access\n");
1998 return NT_STATUS_OK;
2001 return NT_STATUS_SHARING_VIOLATION;
2005 * Send a break message to the oplock holder and delay the open for
2009 NTSTATUS send_break_message(struct messaging_context *msg_ctx,
2010 const struct file_id *id,
2011 const struct share_mode_entry *exclusive,
2014 struct oplock_break_message msg = {
2016 .share_file_id = exclusive->share_file_id,
2017 .break_to = break_to,
2019 enum ndr_err_code ndr_err;
2024 struct server_id_buf buf;
2025 DBG_DEBUG("Sending break message to %s\n",
2026 server_id_str_buf(exclusive->pid, &buf));
2027 NDR_PRINT_DEBUG(oplock_break_message, &msg);
2030 ndr_err = ndr_push_struct_blob(
2034 (ndr_push_flags_fn_t)ndr_push_oplock_break_message);
2035 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
2036 DBG_WARNING("ndr_push_oplock_break_message failed: %s\n",
2037 ndr_errstr(ndr_err));
2038 return ndr_map_error2ntstatus(ndr_err);
2041 status = messaging_send(
2042 msg_ctx, exclusive->pid, MSG_SMB_BREAK_REQUEST, &blob);
2043 TALLOC_FREE(blob.data);
2044 if (!NT_STATUS_IS_OK(status)) {
2045 DEBUG(3, ("Could not send oplock break message: %s\n",
2046 nt_errstr(status)));
2052 struct validate_oplock_types_state {
2058 uint32_t num_non_stat_opens;
2061 static bool validate_oplock_types_fn(
2062 struct share_mode_entry *e,
2066 struct validate_oplock_types_state *state = private_data;
2068 if (e->op_mid == 0) {
2069 /* INTERNAL_OPEN_ONLY */
2073 if (e->op_type == NO_OPLOCK && is_oplock_stat_open(e->access_mask)) {
2075 * We ignore stat opens in the table - they always
2076 * have NO_OPLOCK and never get or cause breaks. JRA.
2081 state->num_non_stat_opens += 1;
2083 if (BATCH_OPLOCK_TYPE(e->op_type)) {
2084 /* batch - can only be one. */
2085 if (share_entry_stale_pid(e)) {
2086 DBG_DEBUG("Found stale batch oplock\n");
2089 if (state->ex_or_batch ||
2093 DBG_ERR("Bad batch oplock entry\n");
2094 state->valid = false;
2097 state->batch = true;
2100 if (EXCLUSIVE_OPLOCK_TYPE(e->op_type)) {
2101 if (share_entry_stale_pid(e)) {
2102 DBG_DEBUG("Found stale duplicate oplock\n");
2105 /* Exclusive or batch - can only be one. */
2106 if (state->ex_or_batch ||
2109 DBG_ERR("Bad exclusive or batch oplock entry\n");
2110 state->valid = false;
2113 state->ex_or_batch = true;
2116 if (LEVEL_II_OPLOCK_TYPE(e->op_type)) {
2117 if (state->batch || state->ex_or_batch) {
2118 if (share_entry_stale_pid(e)) {
2119 DBG_DEBUG("Found stale LevelII oplock\n");
2122 DBG_DEBUG("Bad levelII oplock entry\n");
2123 state->valid = false;
2126 state->level2 = true;
2129 if (e->op_type == NO_OPLOCK) {
2130 if (state->batch || state->ex_or_batch) {
2131 if (share_entry_stale_pid(e)) {
2132 DBG_DEBUG("Found stale NO_OPLOCK entry\n");
2135 DBG_ERR("Bad no oplock entry\n");
2136 state->valid = false;
2139 state->no_oplock = true;
2146 * Do internal consistency checks on the share mode for a file.
2149 static bool validate_oplock_types(struct share_mode_lock *lck)
2151 struct validate_oplock_types_state state = { .valid = true };
2154 ok = share_mode_forall_entries(lck, validate_oplock_types_fn, &state);
2156 DBG_DEBUG("share_mode_forall_entries failed\n");
2160 DBG_DEBUG("Got invalid oplock configuration\n");
2164 if ((state.batch || state.ex_or_batch) &&
2165 (state.num_non_stat_opens != 1)) {
2166 DBG_WARNING("got batch (%d) or ex (%d) non-exclusively "
2169 (int)state.ex_or_batch,
2170 state.num_non_stat_opens);
2177 static bool is_same_lease(const files_struct *fsp,
2178 const struct share_mode_entry *e,
2179 const struct smb2_lease *lease)
2181 if (e->op_type != LEASE_OPLOCK) {
2184 if (lease == NULL) {
2188 return smb2_lease_equal(fsp_client_guid(fsp),
2194 static bool file_has_brlocks(files_struct *fsp)
2196 struct byte_range_lock *br_lck;
2198 br_lck = brl_get_locks_readonly(fsp);
2202 return (brl_num_locks(br_lck) > 0);
2205 struct fsp_lease *find_fsp_lease(struct files_struct *new_fsp,
2206 const struct smb2_lease_key *key,
2207 uint32_t current_state,
2208 uint16_t lease_version,
2209 uint16_t lease_epoch)
2211 struct files_struct *fsp;
2214 * TODO: Measure how expensive this loop is with thousands of open
2218 for (fsp = file_find_di_first(new_fsp->conn->sconn, new_fsp->file_id, true);
2220 fsp = file_find_di_next(fsp, true)) {
2222 if (fsp == new_fsp) {
2225 if (fsp->oplock_type != LEASE_OPLOCK) {
2228 if (smb2_lease_key_equal(&fsp->lease->lease.lease_key, key)) {
2229 fsp->lease->ref_count += 1;
2234 /* Not found - must be leased in another smbd. */
2235 new_fsp->lease = talloc_zero(new_fsp->conn->sconn, struct fsp_lease);
2236 if (new_fsp->lease == NULL) {
2239 new_fsp->lease->ref_count = 1;
2240 new_fsp->lease->sconn = new_fsp->conn->sconn;
2241 new_fsp->lease->lease.lease_key = *key;
2242 new_fsp->lease->lease.lease_state = current_state;
2244 * We internally treat all leases as V2 and update
2245 * the epoch, but when sending breaks it matters if
2246 * the requesting lease was v1 or v2.
2248 new_fsp->lease->lease.lease_version = lease_version;
2249 new_fsp->lease->lease.lease_epoch = lease_epoch;
2250 return new_fsp->lease;
2253 static NTSTATUS try_lease_upgrade(struct files_struct *fsp,
2254 struct share_mode_lock *lck,
2255 const struct GUID *client_guid,
2256 const struct smb2_lease *lease,
2260 uint32_t current_state, breaking_to_requested, breaking_to_required;
2262 uint16_t lease_version, epoch;
2263 uint32_t existing, requested;
2266 status = leases_db_get(
2272 &breaking_to_requested,
2273 &breaking_to_required,
2276 if (!NT_STATUS_IS_OK(status)) {
2280 fsp->lease = find_fsp_lease(
2286 if (fsp->lease == NULL) {
2287 DEBUG(1, ("Did not find existing lease for file %s\n",
2289 return NT_STATUS_NO_MEMORY;
2293 * Upgrade only if the requested lease is a strict upgrade.
2295 existing = current_state;
2296 requested = lease->lease_state;
2299 * Tricky: This test makes sure that "requested" is a
2300 * strict bitwise superset of "existing".
2302 do_upgrade = ((existing & requested) == existing);
2305 * Upgrade only if there's a change.
2307 do_upgrade &= (granted != existing);
2310 * Upgrade only if other leases don't prevent what was asked
2313 do_upgrade &= (granted == requested);
2316 * only upgrade if we are not in breaking state
2318 do_upgrade &= !breaking;
2320 DEBUG(10, ("existing=%"PRIu32", requested=%"PRIu32", "
2321 "granted=%"PRIu32", do_upgrade=%d\n",
2322 existing, requested, granted, (int)do_upgrade));
2325 NTSTATUS set_status;
2327 current_state = granted;
2330 set_status = leases_db_set(
2335 breaking_to_requested,
2336 breaking_to_required,
2340 if (!NT_STATUS_IS_OK(set_status)) {
2341 DBG_DEBUG("leases_db_set failed: %s\n",
2342 nt_errstr(set_status));
2347 fsp_lease_update(fsp);
2349 return NT_STATUS_OK;
2352 static NTSTATUS grant_new_fsp_lease(struct files_struct *fsp,
2353 struct share_mode_lock *lck,
2354 const struct GUID *client_guid,
2355 const struct smb2_lease *lease,
2360 fsp->lease = talloc_zero(fsp->conn->sconn, struct fsp_lease);
2361 if (fsp->lease == NULL) {
2362 return NT_STATUS_INSUFFICIENT_RESOURCES;
2364 fsp->lease->ref_count = 1;
2365 fsp->lease->sconn = fsp->conn->sconn;
2366 fsp->lease->lease.lease_version = lease->lease_version;
2367 fsp->lease->lease.lease_key = lease->lease_key;
2368 fsp->lease->lease.lease_state = granted;
2369 fsp->lease->lease.lease_epoch = lease->lease_epoch + 1;
2371 status = leases_db_add(client_guid,
2374 fsp->lease->lease.lease_state,
2375 fsp->lease->lease.lease_version,
2376 fsp->lease->lease.lease_epoch,
2377 fsp->conn->connectpath,
2378 fsp->fsp_name->base_name,
2379 fsp->fsp_name->stream_name);
2380 if (!NT_STATUS_IS_OK(status)) {
2381 DEBUG(10, ("%s: leases_db_add failed: %s\n", __func__,
2382 nt_errstr(status)));
2383 TALLOC_FREE(fsp->lease);
2384 return NT_STATUS_INSUFFICIENT_RESOURCES;
2388 * We used to set lck->data->modified=true here without
2389 * actually modifying lck->data, triggering a needless
2390 * writeback of lck->data.
2392 * Apart from that writeback, setting modified=true has the
2393 * effect of triggering all waiters for this file to
2394 * retry. This only makes sense if any blocking condition
2395 * (i.e. waiting for a lease to be downgraded or removed) is
2396 * gone. This routine here only adds a lease, so it will never
2397 * free up resources that blocked waiters can now claim. So
2398 * that second effect also does not matter in this
2399 * routine. Thus setting lck->data->modified=true does not
2400 * need to be done here.
2403 return NT_STATUS_OK;
2406 static NTSTATUS grant_fsp_lease(struct files_struct *fsp,
2407 struct share_mode_lock *lck,
2408 const struct smb2_lease *lease,
2411 const struct GUID *client_guid = fsp_client_guid(fsp);
2414 status = try_lease_upgrade(fsp, lck, client_guid, lease, granted);
2416 if (NT_STATUS_EQUAL(status, NT_STATUS_NOT_FOUND)) {
2417 status = grant_new_fsp_lease(
2418 fsp, lck, client_guid, lease, granted);
2424 static int map_lease_type_to_oplock(uint32_t lease_type)
2426 int result = NO_OPLOCK;
2428 switch (lease_type) {
2429 case SMB2_LEASE_READ|SMB2_LEASE_WRITE|SMB2_LEASE_HANDLE:
2430 result = BATCH_OPLOCK|EXCLUSIVE_OPLOCK;
2432 case SMB2_LEASE_READ|SMB2_LEASE_WRITE:
2433 result = EXCLUSIVE_OPLOCK;
2435 case SMB2_LEASE_READ|SMB2_LEASE_HANDLE:
2436 case SMB2_LEASE_READ:
2437 result = LEVEL_II_OPLOCK;
2444 struct delay_for_oplock_state {
2445 struct files_struct *fsp;
2446 const struct smb2_lease *lease;
2447 bool will_overwrite;
2448 uint32_t delay_mask;
2449 bool first_open_attempt;
2450 bool got_handle_lease;
2452 bool have_other_lease;
2456 static bool delay_for_oplock_fn(
2457 struct share_mode_entry *e,
2461 struct delay_for_oplock_state *state = private_data;
2462 struct files_struct *fsp = state->fsp;
2463 const struct smb2_lease *lease = state->lease;
2464 bool e_is_lease = (e->op_type == LEASE_OPLOCK);
2465 uint32_t e_lease_type = get_lease_type(e, fsp->file_id);
2467 bool lease_is_breaking = false;
2472 if (lease != NULL) {
2473 bool our_lease = is_same_lease(fsp, e, lease);
2475 DBG_DEBUG("Ignoring our own lease\n");
2480 status = leases_db_get(
2484 NULL, /* current_state */
2486 NULL, /* breaking_to_requested */
2487 NULL, /* breaking_to_required */
2488 NULL, /* lease_version */
2492 * leases_db_get() can return NT_STATUS_NOT_FOUND
2493 * if the share_mode_entry e is stale and the
2494 * lease record was already removed. In this case return
2495 * false so the traverse continues.
2498 if (NT_STATUS_EQUAL(status, NT_STATUS_NOT_FOUND) &&
2499 share_entry_stale_pid(e))
2501 struct GUID_txt_buf guid_strbuf;
2502 struct file_id_buf file_id_strbuf;
2503 DBG_DEBUG("leases_db_get for client_guid [%s] "
2504 "lease_key [%"PRIu64"/%"PRIu64"] "
2505 "file_id [%s] failed for stale "
2506 "share_mode_entry\n",
2507 GUID_buf_string(&e->client_guid, &guid_strbuf),
2508 e->lease_key.data[0],
2509 e->lease_key.data[1],
2510 file_id_str_buf(fsp->file_id, &file_id_strbuf));
2513 if (!NT_STATUS_IS_OK(status)) {
2514 struct GUID_txt_buf guid_strbuf;
2515 struct file_id_buf file_id_strbuf;
2516 DBG_ERR("leases_db_get for client_guid [%s] "
2517 "lease_key [%"PRIu64"/%"PRIu64"] "
2518 "file_id [%s] failed: %s\n",
2519 GUID_buf_string(&e->client_guid, &guid_strbuf),
2520 e->lease_key.data[0],
2521 e->lease_key.data[1],
2522 file_id_str_buf(fsp->file_id, &file_id_strbuf),
2524 smb_panic("leases_db_get() failed");
2528 if (!state->got_handle_lease &&
2529 ((e_lease_type & SMB2_LEASE_HANDLE) != 0) &&
2530 !share_entry_stale_pid(e)) {
2531 state->got_handle_lease = true;
2534 if (!state->got_oplock &&
2535 (e->op_type != LEASE_OPLOCK) &&
2536 !share_entry_stale_pid(e)) {
2537 state->got_oplock = true;
2540 if (!state->have_other_lease &&
2541 !is_same_lease(fsp, e, lease) &&
2542 !share_entry_stale_pid(e)) {
2543 state->have_other_lease = true;
2546 if (e_is_lease && is_lease_stat_open(fsp->access_mask)) {
2550 break_to = e_lease_type & ~state->delay_mask;
2552 if (state->will_overwrite) {
2553 break_to &= ~(SMB2_LEASE_HANDLE|SMB2_LEASE_READ);
2556 DBG_DEBUG("e_lease_type %u, will_overwrite: %u\n",
2557 (unsigned)e_lease_type,
2558 (unsigned)state->will_overwrite);
2560 if ((e_lease_type & ~break_to) == 0) {
2561 if (lease_is_breaking) {
2562 state->delay = true;
2567 if (share_entry_stale_pid(e)) {
2571 if (state->will_overwrite) {
2573 * If we break anyway break to NONE directly.
2574 * Otherwise vfs_set_filelen() will trigger the
2577 break_to &= ~(SMB2_LEASE_READ|SMB2_LEASE_WRITE);
2582 * Oplocks only support breaking to R or NONE.
2584 break_to &= ~(SMB2_LEASE_HANDLE|SMB2_LEASE_WRITE);
2587 DBG_DEBUG("breaking from %d to %d\n",
2591 fsp->conn->sconn->msg_ctx, &fsp->file_id, e, break_to);
2592 if (e_lease_type & state->delay_mask) {
2593 state->delay = true;
2595 if (lease_is_breaking && !state->first_open_attempt) {
2596 state->delay = true;
2602 static NTSTATUS delay_for_oplock(files_struct *fsp,
2604 const struct smb2_lease *lease,
2605 struct share_mode_lock *lck,
2606 bool have_sharing_violation,
2607 uint32_t create_disposition,
2608 bool first_open_attempt)
2610 struct delay_for_oplock_state state = {
2613 .first_open_attempt = first_open_attempt,
2619 if (is_oplock_stat_open(fsp->access_mask)) {
2623 state.delay_mask = have_sharing_violation ?
2624 SMB2_LEASE_HANDLE : SMB2_LEASE_WRITE;
2626 switch (create_disposition) {
2627 case FILE_SUPERSEDE:
2628 case FILE_OVERWRITE:
2629 case FILE_OVERWRITE_IF:
2630 state.will_overwrite = true;
2633 state.will_overwrite = false;
2637 ok = share_mode_forall_entries(lck, delay_for_oplock_fn, &state);
2639 return NT_STATUS_INTERNAL_ERROR;
2643 return NT_STATUS_RETRY;
2647 if (have_sharing_violation) {
2648 return NT_STATUS_SHARING_VIOLATION;
2651 if (oplock_request == LEASE_OPLOCK) {
2652 if (lease == NULL) {
2654 * The SMB2 layer should have checked this
2656 return NT_STATUS_INTERNAL_ERROR;
2659 granted = lease->lease_state;
2661 if (lp_kernel_oplocks(SNUM(fsp->conn))) {
2662 DEBUG(10, ("No lease granted because kernel oplocks are enabled\n"));
2663 granted = SMB2_LEASE_NONE;
2665 if ((granted & (SMB2_LEASE_READ|SMB2_LEASE_WRITE)) == 0) {
2666 DEBUG(10, ("No read or write lease requested\n"));
2667 granted = SMB2_LEASE_NONE;
2669 if (granted == SMB2_LEASE_WRITE) {
2670 DEBUG(10, ("pure write lease requested\n"));
2671 granted = SMB2_LEASE_NONE;
2673 if (granted == (SMB2_LEASE_WRITE|SMB2_LEASE_HANDLE)) {
2674 DEBUG(10, ("write and handle lease requested\n"));
2675 granted = SMB2_LEASE_NONE;
2678 granted = map_oplock_to_lease_type(
2679 oplock_request & ~SAMBA_PRIVATE_OPLOCK_MASK);
2682 if (lp_locking(fsp->conn->params) && file_has_brlocks(fsp)) {
2683 DBG_DEBUG("file %s has byte range locks\n",
2685 granted &= ~SMB2_LEASE_READ;
2688 if (state.have_other_lease) {
2690 * Can grant only one writer
2692 granted &= ~SMB2_LEASE_WRITE;
2695 if ((granted & SMB2_LEASE_READ) && !(granted & SMB2_LEASE_WRITE)) {
2697 (global_client_caps & CAP_LEVEL_II_OPLOCKS) &&
2698 lp_level2_oplocks(SNUM(fsp->conn));
2700 if (!allow_level2) {
2701 granted = SMB2_LEASE_NONE;
2705 if (oplock_request == LEASE_OPLOCK) {
2706 if (state.got_oplock) {
2707 granted &= ~SMB2_LEASE_HANDLE;
2710 fsp->oplock_type = LEASE_OPLOCK;
2712 status = grant_fsp_lease(fsp, lck, lease, granted);
2713 if (!NT_STATUS_IS_OK(status)) {
2718 DBG_DEBUG("lease_state=%d\n", fsp->lease->lease.lease_state);
2720 if (state.got_handle_lease) {
2721 granted = SMB2_LEASE_NONE;
2724 fsp->oplock_type = map_lease_type_to_oplock(granted);
2726 status = set_file_oplock(fsp);
2727 if (!NT_STATUS_IS_OK(status)) {
2729 * Could not get the kernel oplock
2731 fsp->oplock_type = NO_OPLOCK;
2735 if (granted & SMB2_LEASE_READ) {
2736 uint32_t acc, sh, ls;
2737 share_mode_flags_get(lck, &acc, &sh, &ls);
2738 ls |= SHARE_MODE_LEASE_READ;
2739 share_mode_flags_set(lck, acc, sh, ls, NULL);
2742 DBG_DEBUG("oplock type 0x%x on file %s\n",
2743 fsp->oplock_type, fsp_str_dbg(fsp));
2745 return NT_STATUS_OK;
2748 static NTSTATUS handle_share_mode_lease(
2750 struct share_mode_lock *lck,
2751 uint32_t create_disposition,
2752 uint32_t access_mask,
2753 uint32_t share_access,
2755 const struct smb2_lease *lease,
2756 bool first_open_attempt)
2758 bool sharing_violation = false;
2761 status = open_mode_check(
2762 fsp->conn, fsp->file_id, lck, access_mask, share_access);
2763 if (NT_STATUS_EQUAL(status, NT_STATUS_SHARING_VIOLATION)) {
2764 sharing_violation = true;
2765 status = NT_STATUS_OK; /* handled later */
2768 if (!NT_STATUS_IS_OK(status)) {
2772 if (oplock_request == INTERNAL_OPEN_ONLY) {
2773 if (sharing_violation) {
2774 DBG_DEBUG("Sharing violation for internal open\n");
2775 return NT_STATUS_SHARING_VIOLATION;
2779 * Internal opens never do oplocks or leases. We don't
2780 * need to go through delay_for_oplock().
2782 fsp->oplock_type = NO_OPLOCK;
2784 return NT_STATUS_OK;
2787 status = delay_for_oplock(
2794 first_open_attempt);
2795 if (!NT_STATUS_IS_OK(status)) {
2799 return NT_STATUS_OK;
2802 static bool request_timed_out(struct smb_request *req, struct timeval timeout)
2804 struct timeval now, end_time;
2806 end_time = timeval_sum(&req->request_time, &timeout);
2807 return (timeval_compare(&end_time, &now) < 0);
2810 struct defer_open_state {
2811 struct smbXsrv_connection *xconn;
2815 static void defer_open_done(struct tevent_req *req);
2818 * Defer an open and watch a locking.tdb record
2820 * This defers an open that gets rescheduled once the locking.tdb record watch
2821 * is triggered by a change to the record.
2823 * It is used to defer opens that triggered an oplock break and for the SMB1
2824 * sharing violation delay.
2826 static void defer_open(struct share_mode_lock *lck,
2827 struct timeval timeout,
2828 struct smb_request *req,
2831 struct deferred_open_record *open_rec = NULL;
2832 struct timeval abs_timeout;
2833 struct defer_open_state *watch_state;
2834 struct tevent_req *watch_req;
2835 struct timeval_buf tvbuf1, tvbuf2;
2836 struct file_id_buf fbuf;
2839 abs_timeout = timeval_sum(&req->request_time, &timeout);
2841 DBG_DEBUG("request time [%s] timeout [%s] mid [%" PRIu64 "] "
2843 timeval_str_buf(&req->request_time, false, true, &tvbuf1),
2844 timeval_str_buf(&abs_timeout, false, true, &tvbuf2),
2846 file_id_str_buf(id, &fbuf));
2848 open_rec = talloc_zero(NULL, struct deferred_open_record);
2849 if (open_rec == NULL) {
2851 exit_server("talloc failed");
2854 watch_state = talloc(open_rec, struct defer_open_state);
2855 if (watch_state == NULL) {
2856 exit_server("talloc failed");
2858 watch_state->xconn = req->xconn;
2859 watch_state->mid = req->mid;
2861 DBG_DEBUG("defering mid %" PRIu64 "\n", req->mid);
2863 watch_req = share_mode_watch_send(
2867 (struct server_id){0});
2868 if (watch_req == NULL) {
2869 exit_server("Could not watch share mode record");
2871 tevent_req_set_callback(watch_req, defer_open_done, watch_state);
2873 ok = tevent_req_set_endtime(watch_req, req->sconn->ev_ctx, abs_timeout);
2875 exit_server("tevent_req_set_endtime failed");
2878 ok = push_deferred_open_message_smb(req, timeout, id, open_rec);
2881 exit_server("push_deferred_open_message_smb failed");
2885 static void defer_open_done(struct tevent_req *req)
2887 struct defer_open_state *state = tevent_req_callback_data(
2888 req, struct defer_open_state);
2892 status = share_mode_watch_recv(req, NULL, NULL);
2894 if (!NT_STATUS_IS_OK(status)) {
2895 DEBUG(5, ("dbwrap_watched_watch_recv returned %s\n",
2896 nt_errstr(status)));
2898 * Even if it failed, retry anyway. TODO: We need a way to
2899 * tell a re-scheduled open about that error.
2903 DEBUG(10, ("scheduling mid %llu\n", (unsigned long long)state->mid));
2905 ret = schedule_deferred_open_message_smb(state->xconn, state->mid);
2911 * Actually attempt the kernel oplock polling open.
2914 static void poll_open_fn(struct tevent_context *ev,
2915 struct tevent_timer *te,
2916 struct timeval current_time,
2919 struct deferred_open_record *open_rec = talloc_get_type_abort(
2920 private_data, struct deferred_open_record);
2923 TALLOC_FREE(open_rec->watch_req);
2925 ok = schedule_deferred_open_message_smb(
2926 open_rec->xconn, open_rec->mid);
2928 exit_server("schedule_deferred_open_message_smb failed");
2930 DBG_DEBUG("timer fired. Retrying open !\n");
2933 static void poll_open_done(struct tevent_req *subreq);
2936 * Reschedule an open for 1 second from now, if not timed out.
2938 static bool setup_poll_open(
2939 struct smb_request *req,
2940 struct share_mode_lock *lck,
2942 struct timeval max_timeout,
2943 struct timeval interval)
2946 struct deferred_open_record *open_rec = NULL;
2947 struct timeval endtime, next_interval;
2948 struct file_id_buf ftmp;
2950 if (request_timed_out(req, max_timeout)) {
2954 open_rec = talloc_zero(NULL, struct deferred_open_record);
2955 if (open_rec == NULL) {
2956 DBG_WARNING("talloc failed\n");
2959 open_rec->xconn = req->xconn;
2960 open_rec->mid = req->mid;
2963 * Make sure open_rec->te does not come later than the
2964 * request's maximum endtime.
2967 endtime = timeval_sum(&req->request_time, &max_timeout);
2968 next_interval = timeval_current_ofs(interval.tv_sec, interval.tv_usec);
2969 next_interval = timeval_min(&endtime, &next_interval);
2971 open_rec->te = tevent_add_timer(
2977 if (open_rec->te == NULL) {
2978 DBG_WARNING("tevent_add_timer failed\n");
2979 TALLOC_FREE(open_rec);
2984 open_rec->watch_req = share_mode_watch_send(
2988 (struct server_id) {0});
2989 if (open_rec->watch_req == NULL) {
2990 DBG_WARNING("share_mode_watch_send failed\n");
2991 TALLOC_FREE(open_rec);
2994 tevent_req_set_callback(
2995 open_rec->watch_req, poll_open_done, open_rec);
2998 ok = push_deferred_open_message_smb(req, max_timeout, id, open_rec);
3000 DBG_WARNING("push_deferred_open_message_smb failed\n");
3001 TALLOC_FREE(open_rec);
3005 DBG_DEBUG("poll request time [%s] mid [%" PRIu64 "] file_id [%s]\n",
3006 timeval_string(talloc_tos(), &req->request_time, false),
3008 file_id_str_buf(id, &ftmp));
3013 static void poll_open_done(struct tevent_req *subreq)
3015 struct deferred_open_record *open_rec = tevent_req_callback_data(
3016 subreq, struct deferred_open_record);
3020 status = share_mode_watch_recv(subreq, NULL, NULL);
3021 TALLOC_FREE(subreq);
3022 open_rec->watch_req = NULL;
3023 TALLOC_FREE(open_rec->te);
3025 DBG_DEBUG("dbwrap_watched_watch_recv returned %s\n",
3028 ok = schedule_deferred_open_message_smb(
3029 open_rec->xconn, open_rec->mid);
3031 exit_server("schedule_deferred_open_message_smb failed");
3035 bool defer_smb1_sharing_violation(struct smb_request *req)
3040 if (!lp_defer_sharing_violations()) {
3045 * Try every 200msec up to (by default) one second. To be
3046 * precise, according to behaviour note <247> in [MS-CIFS],
3047 * the server tries 5 times. But up to one second should be
3051 timeout_usecs = lp_parm_int(
3055 SHARING_VIOLATION_USEC_WAIT);
3057 ok = setup_poll_open(
3060 (struct file_id) {0},
3061 (struct timeval) { .tv_usec = timeout_usecs },
3062 (struct timeval) { .tv_usec = 200000 });
3066 /****************************************************************************
3067 On overwrite open ensure that the attributes match.
3068 ****************************************************************************/
3070 static bool open_match_attributes(connection_struct *conn,
3071 uint32_t old_dos_attr,
3072 uint32_t new_dos_attr,
3073 mode_t new_unx_mode,
3074 mode_t *returned_unx_mode)
3076 uint32_t noarch_old_dos_attr, noarch_new_dos_attr;
3078 noarch_old_dos_attr = (old_dos_attr & ~FILE_ATTRIBUTE_ARCHIVE);
3079 noarch_new_dos_attr = (new_dos_attr & ~FILE_ATTRIBUTE_ARCHIVE);
3081 if((noarch_old_dos_attr == 0 && noarch_new_dos_attr != 0) ||
3082 (noarch_old_dos_attr != 0 && ((noarch_old_dos_attr & noarch_new_dos_attr) == noarch_old_dos_attr))) {
3083 *returned_unx_mode = new_unx_mode;
3085 *returned_unx_mode = (mode_t)0;
3088 DEBUG(10,("open_match_attributes: old_dos_attr = 0x%x, "
3089 "new_dos_attr = 0x%x "
3090 "returned_unx_mode = 0%o\n",
3091 (unsigned int)old_dos_attr,
3092 (unsigned int)new_dos_attr,
3093 (unsigned int)*returned_unx_mode ));
3095 /* If we're mapping SYSTEM and HIDDEN ensure they match. */
3096 if (lp_map_system(SNUM(conn)) || lp_store_dos_attributes(SNUM(conn))) {
3097 if ((old_dos_attr & FILE_ATTRIBUTE_SYSTEM) &&
3098 !(new_dos_attr & FILE_ATTRIBUTE_SYSTEM)) {
3102 if (lp_map_hidden(SNUM(conn)) || lp_store_dos_attributes(SNUM(conn))) {
3103 if ((old_dos_attr & FILE_ATTRIBUTE_HIDDEN) &&
3104 !(new_dos_attr & FILE_ATTRIBUTE_HIDDEN)) {
3111 static void schedule_defer_open(struct share_mode_lock *lck,
3113 struct smb_request *req)
3115 /* This is a relative time, added to the absolute
3116 request_time value to get the absolute timeout time.
3117 Note that if this is the second or greater time we enter
3118 this codepath for this particular request mid then
3119 request_time is left as the absolute time of the *first*
3120 time this request mid was processed. This is what allows
3121 the request to eventually time out. */
3123 struct timeval timeout;
3125 /* Normally the smbd we asked should respond within
3126 * OPLOCK_BREAK_TIMEOUT seconds regardless of whether
3127 * the client did, give twice the timeout as a safety
3128 * measure here in case the other smbd is stuck
3129 * somewhere else. */
3131 timeout = timeval_set(OPLOCK_BREAK_TIMEOUT*2, 0);
3133 if (request_timed_out(req, timeout)) {
3137 defer_open(lck, timeout, req, id);
3140 /****************************************************************************
3141 Reschedule an open call that went asynchronous.
3142 ****************************************************************************/
3144 static void schedule_async_open_timer(struct tevent_context *ev,
3145 struct tevent_timer *te,
3146 struct timeval current_time,
3149 exit_server("async open timeout");
3152 static void schedule_async_open(struct smb_request *req)
3154 struct deferred_open_record *open_rec = NULL;
3155 struct timeval timeout = timeval_set(20, 0);
3158 if (request_timed_out(req, timeout)) {
3162 open_rec = talloc_zero(NULL, struct deferred_open_record);
3163 if (open_rec == NULL) {
3164 exit_server("deferred_open_record_create failed");
3166 open_rec->async_open = true;
3168 ok = push_deferred_open_message_smb(
3169 req, timeout, (struct file_id){0}, open_rec);
3171 exit_server("push_deferred_open_message_smb failed");
3174 open_rec->te = tevent_add_timer(req->sconn->ev_ctx,
3176 timeval_current_ofs(20, 0),
3177 schedule_async_open_timer,
3179 if (open_rec->te == NULL) {
3180 exit_server("tevent_add_timer failed");
3184 /****************************************************************************
3185 Work out what access_mask to use from what the client sent us.
3186 ****************************************************************************/
3188 static NTSTATUS smbd_calculate_maximum_allowed_access_fsp(
3189 struct files_struct *dirfsp,
3190 struct files_struct *fsp,
3192 uint32_t *p_access_mask)
3194 struct security_descriptor *sd = NULL;
3195 uint32_t access_granted = 0;
3198 /* Cope with symlinks */
3199 if (fsp == NULL || fsp_get_pathref_fd(fsp) == -1) {
3200 *p_access_mask = FILE_GENERIC_ALL;
3201 return NT_STATUS_OK;
3204 /* Cope with fake/printer fsp's. */
3205 if (fsp->fake_file_handle != NULL || fsp->print_file != NULL) {
3206 *p_access_mask = FILE_GENERIC_ALL;
3207 return NT_STATUS_OK;
3210 if (!use_privs && (get_current_uid(fsp->conn) == (uid_t)0)) {
3211 *p_access_mask |= FILE_GENERIC_ALL;
3212 return NT_STATUS_OK;
3215 status = SMB_VFS_FGET_NT_ACL(fsp,
3222 if (NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
3224 * File did not exist
3226 *p_access_mask = FILE_GENERIC_ALL;
3227 return NT_STATUS_OK;
3229 if (!NT_STATUS_IS_OK(status)) {
3230 DBG_ERR("Could not get acl on file %s: %s\n",
3237 * If we can access the path to this file, by
3238 * default we have FILE_READ_ATTRIBUTES from the
3239 * containing directory. See the section:
3240 * "Algorithm to Check Access to an Existing File"
3243 * se_file_access_check()
3244 * also takes care of owner WRITE_DAC and READ_CONTROL.
3246 status = se_file_access_check(sd,
3247 get_current_nttok(fsp->conn),
3249 (*p_access_mask & ~FILE_READ_ATTRIBUTES),
3254 if (!NT_STATUS_IS_OK(status)) {
3255 DBG_ERR("Status %s on file %s: "
3256 "when calculating maximum access\n",
3262 *p_access_mask = (access_granted | FILE_READ_ATTRIBUTES);
3264 if (!(access_granted & DELETE_ACCESS)) {
3265 if (can_delete_file_in_directory(fsp->conn,
3268 *p_access_mask |= DELETE_ACCESS;
3272 return NT_STATUS_OK;
3275 NTSTATUS smbd_calculate_access_mask_fsp(struct files_struct *dirfsp,
3276 struct files_struct *fsp,
3278 uint32_t access_mask,
3279 uint32_t *access_mask_out)
3282 uint32_t orig_access_mask = access_mask;
3283 uint32_t rejected_share_access;
3285 if (access_mask & SEC_MASK_INVALID) {
3286 DBG_DEBUG("access_mask [%8x] contains invalid bits\n",
3288 return NT_STATUS_ACCESS_DENIED;
3292 * Convert GENERIC bits to specific bits.
3295 se_map_generic(&access_mask, &file_generic_mapping);
3297 /* Calculate MAXIMUM_ALLOWED_ACCESS if requested. */
3298 if (access_mask & MAXIMUM_ALLOWED_ACCESS) {
3300 status = smbd_calculate_maximum_allowed_access_fsp(
3306 if (!NT_STATUS_IS_OK(status)) {
3310 access_mask &= fsp->conn->share_access;
3313 rejected_share_access = access_mask & ~(fsp->conn->share_access);
3315 if (rejected_share_access) {
3316 DBG_ERR("Access denied on file %s: "
3317 "rejected by share access mask[0x%08X] "
3318 "orig[0x%08X] mapped[0x%08X] reject[0x%08X]\n",
3320 fsp->conn->share_access,
3321 orig_access_mask, access_mask,
3322 rejected_share_access);
3323 return NT_STATUS_ACCESS_DENIED;
3326 *access_mask_out = access_mask;
3327 return NT_STATUS_OK;
3330 /****************************************************************************
3331 Remove the deferred open entry under lock.
3332 ****************************************************************************/
3334 /****************************************************************************
3335 Return true if this is a state pointer to an asynchronous create.
3336 ****************************************************************************/
3338 bool is_deferred_open_async(const struct deferred_open_record *rec)
3340 return rec->async_open;
3343 static bool clear_ads(uint32_t create_disposition)
3347 switch (create_disposition) {
3348 case FILE_SUPERSEDE:
3349 case FILE_OVERWRITE_IF:
3350 case FILE_OVERWRITE:
3359 static int disposition_to_open_flags(uint32_t create_disposition)
3364 * Currently we're using FILE_SUPERSEDE as the same as
3365 * FILE_OVERWRITE_IF but they really are
3366 * different. FILE_SUPERSEDE deletes an existing file
3367 * (requiring delete access) then recreates it.
3370 switch (create_disposition) {
3371 case FILE_SUPERSEDE:
3372 case FILE_OVERWRITE_IF:
3374 * If file exists replace/overwrite. If file doesn't
3377 ret = O_CREAT|O_TRUNC;
3382 * If file exists open. If file doesn't exist error.
3387 case FILE_OVERWRITE:
3389 * If file exists overwrite. If file doesn't exist
3397 * If file exists error. If file doesn't exist create.
3399 ret = O_CREAT|O_EXCL;
3404 * If file exists open. If file doesn't exist create.
3412 static int calculate_open_access_flags(uint32_t access_mask,
3413 uint32_t private_flags)
3415 bool need_write, need_read;
3418 * Note that we ignore the append flag as append does not
3419 * mean the same thing under DOS and Unix.
3422 need_write = (access_mask & (FILE_WRITE_DATA | FILE_APPEND_DATA));
3427 /* DENY_DOS opens are always underlying read-write on the
3428 file handle, no matter what the requested access mask
3432 ((private_flags & NTCREATEX_FLAG_DENY_DOS) ||
3433 access_mask & (FILE_READ_ATTRIBUTES|FILE_READ_DATA|
3434 FILE_READ_EA|FILE_EXECUTE));
3442 /****************************************************************************
3443 Open a file with a share mode. Passed in an already created files_struct *.
3444 ****************************************************************************/
3446 static NTSTATUS open_file_ntcreate(connection_struct *conn,
3447 struct smb_request *req,
3448 uint32_t access_mask, /* access bits (FILE_READ_DATA etc.) */
3449 uint32_t share_access, /* share constants (FILE_SHARE_READ etc) */
3450 uint32_t create_disposition, /* FILE_OPEN_IF etc. */
3451 uint32_t create_options, /* options such as delete on close. */
3452 uint32_t new_dos_attributes, /* attributes used for new file. */
3453 int oplock_request, /* internal Samba oplock codes. */
3454 const struct smb2_lease *lease,
3455 /* Information (FILE_EXISTS etc.) */
3456 uint32_t private_flags, /* Samba specific flags. */
3457 struct smb_filename *parent_dir_fname, /* parent. */
3458 struct smb_filename *smb_fname_atname, /* atname relative to parent. */
3462 struct smb_filename *smb_fname = fsp->fsp_name;
3465 bool file_existed = VALID_STAT(smb_fname->st);
3466 bool def_acl = False;
3467 bool posix_open = False;
3468 bool new_file_created = False;
3469 bool first_open_attempt = true;
3470 NTSTATUS fsp_open = NT_STATUS_ACCESS_DENIED;
3471 mode_t new_unx_mode = (mode_t)0;
3472 mode_t unx_mode = (mode_t)0;
3474 uint32_t existing_dos_attributes = 0;
3475 struct share_mode_lock *lck = NULL;
3476 uint32_t open_access_mask = access_mask;
3478 SMB_STRUCT_STAT saved_stat = smb_fname->st;
3479 struct timespec old_write_time;
3480 bool setup_poll = false;
3483 if (conn->printer) {
3485 * Printers are handled completely differently.
3486 * Most of the passed parameters are ignored.
3490 *pinfo = FILE_WAS_CREATED;
3493 DEBUG(10, ("open_file_ntcreate: printer open fname=%s\n",
3494 smb_fname_str_dbg(smb_fname)));
3497 DEBUG(0,("open_file_ntcreate: printer open without "
3498 "an SMB request!\n"));
3499 return NT_STATUS_INTERNAL_ERROR;
3502 return print_spool_open(fsp, smb_fname->base_name,
3506 if (new_dos_attributes & FILE_FLAG_POSIX_SEMANTICS) {
3508 unx_mode = (mode_t)(new_dos_attributes & ~FILE_FLAG_POSIX_SEMANTICS);
3509 new_dos_attributes = 0;
3511 /* Windows allows a new file to be created and
3512 silently removes a FILE_ATTRIBUTE_DIRECTORY
3513 sent by the client. Do the same. */
3515 new_dos_attributes &= ~FILE_ATTRIBUTE_DIRECTORY;
3517 /* We add FILE_ATTRIBUTE_ARCHIVE to this as this mode is only used if the file is
3519 unx_mode = unix_mode(conn, new_dos_attributes | FILE_ATTRIBUTE_ARCHIVE,
3520 smb_fname, parent_dir_fname);
3523 DEBUG(10, ("open_file_ntcreate: fname=%s, dos_attrs=0x%x "
3524 "access_mask=0x%x share_access=0x%x "
3525 "create_disposition = 0x%x create_options=0x%x "
3526 "unix mode=0%o oplock_request=%d private_flags = 0x%x\n",
3527 smb_fname_str_dbg(smb_fname), new_dos_attributes,
3528 access_mask, share_access, create_disposition,
3529 create_options, (unsigned int)unx_mode, oplock_request,
3530 (unsigned int)private_flags));
3533 /* Ensure req == NULL means INTERNAL_OPEN_ONLY */
3534 SMB_ASSERT(oplock_request == INTERNAL_OPEN_ONLY);
3536 /* And req != NULL means no INTERNAL_OPEN_ONLY */
3537 SMB_ASSERT(((oplock_request & INTERNAL_OPEN_ONLY) == 0));
3541 * Only non-internal opens can be deferred at all
3545 struct deferred_open_record *open_rec;
3546 if (get_deferred_open_message_state(req, NULL, &open_rec)) {
3548 /* If it was an async create retry, the file
3551 if (is_deferred_open_async(open_rec)) {
3552 SET_STAT_INVALID(smb_fname->st);
3553 file_existed = false;
3556 /* Ensure we don't reprocess this message. */
3557 remove_deferred_open_message_smb(req->xconn, req->mid);
3559 first_open_attempt = false;
3564 new_dos_attributes &= SAMBA_ATTRIBUTES_MASK;
3567 * Only use stored DOS attributes for checks
3568 * against requested attributes (below via
3569 * open_match_attributes()), cf bug #11992
3570 * for details. -slow
3574 status = SMB_VFS_FGET_DOS_ATTRIBUTES(conn, smb_fname->fsp, &attr);
3575 if (NT_STATUS_IS_OK(status)) {
3576 existing_dos_attributes = attr;
3581 /* ignore any oplock requests if oplocks are disabled */
3582 if (!lp_oplocks(SNUM(conn)) ||
3583 IS_VETO_OPLOCK_PATH(conn, smb_fname->base_name)) {
3584 /* Mask off everything except the private Samba bits. */
3585 oplock_request &= SAMBA_PRIVATE_OPLOCK_MASK;
3588 /* this is for OS/2 long file names - say we don't support them */
3589 if (req != NULL && !req->posix_pathnames &&
3590 strstr(smb_fname->base_name,".+,;=[].")) {
3591 /* OS/2 Workplace shell fix may be main code stream in a later
3593 DEBUG(5,("open_file_ntcreate: OS/2 long filenames are not "
3595 if (use_nt_status()) {
3596 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3598 return NT_STATUS_DOS(ERRDOS, ERRcannotopen);
3601 switch( create_disposition ) {
3603 /* If file exists open. If file doesn't exist error. */
3604 if (!file_existed) {
3605 DEBUG(5,("open_file_ntcreate: FILE_OPEN "
3606 "requested for file %s and file "
3608 smb_fname_str_dbg(smb_fname)));
3609 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3613 case FILE_OVERWRITE:
3614 /* If file exists overwrite. If file doesn't exist
3616 if (!file_existed) {
3617 DEBUG(5,("open_file_ntcreate: FILE_OVERWRITE "
3618 "requested for file %s and file "
3620 smb_fname_str_dbg(smb_fname) ));
3621 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3626 /* If file exists error. If file doesn't exist
3629 DEBUG(5,("open_file_ntcreate: FILE_CREATE "
3630 "requested for file %s and file "
3631 "already exists.\n",
3632 smb_fname_str_dbg(smb_fname)));
3633 if (S_ISDIR(smb_fname->st.st_ex_mode)) {
3634 return NT_STATUS_FILE_IS_A_DIRECTORY;
3636 return NT_STATUS_OBJECT_NAME_COLLISION;
3640 case FILE_SUPERSEDE:
3641 case FILE_OVERWRITE_IF:
3645 return NT_STATUS_INVALID_PARAMETER;
3648 flags2 = disposition_to_open_flags(create_disposition);
3650 /* We only care about matching attributes on file exists and
3653 if (!posix_open && file_existed &&
3654 ((create_disposition == FILE_OVERWRITE) ||
3655 (create_disposition == FILE_OVERWRITE_IF))) {
3656 if (!open_match_attributes(conn, existing_dos_attributes,
3658 unx_mode, &new_unx_mode)) {
3659 DEBUG(5,("open_file_ntcreate: attributes mismatch "
3660 "for file %s (%x %x) (0%o, 0%o)\n",
3661 smb_fname_str_dbg(smb_fname),
3662 existing_dos_attributes,
3664 (unsigned int)smb_fname->st.st_ex_mode,
3665 (unsigned int)unx_mode ));
3666 return NT_STATUS_ACCESS_DENIED;
3670 status = smbd_calculate_access_mask_fsp(parent_dir_fname->fsp,
3675 if (!NT_STATUS_IS_OK(status)) {
3676 DBG_DEBUG("smbd_calculate_access_mask_fsp "
3677 "on file %s returned %s\n",
3678 smb_fname_str_dbg(smb_fname),
3683 open_access_mask = access_mask;
3685 if (flags2 & O_TRUNC) {
3686 open_access_mask |= FILE_WRITE_DATA; /* This will cause oplock breaks. */
3691 * stat opens on existing files don't get oplocks.
3692 * They can get leases.
3694 * Note that we check for stat open on the *open_access_mask*,
3695 * i.e. the access mask we actually used to do the open,
3696 * not the one the client asked for (which is in
3697 * fsp->access_mask). This is due to the fact that
3698 * FILE_OVERWRITE and FILE_OVERWRITE_IF add in O_TRUNC,
3699 * which adds FILE_WRITE_DATA to open_access_mask.
3701 if (is_oplock_stat_open(open_access_mask) && lease == NULL) {
3702 oplock_request = NO_OPLOCK;
3706 DEBUG(10, ("open_file_ntcreate: fname=%s, after mapping "
3707 "access_mask=0x%x\n", smb_fname_str_dbg(smb_fname),
3711 * Note that we ignore the append flag as append does not
3712 * mean the same thing under DOS and Unix.
3715 flags = calculate_open_access_flags(access_mask, private_flags);
3718 * Currently we only look at FILE_WRITE_THROUGH for create options.
3722 if ((create_options & FILE_WRITE_THROUGH) && lp_strict_sync(SNUM(conn))) {
3727 if (posix_open && (access_mask & FILE_APPEND_DATA)) {
3731 if (!posix_open && !CAN_WRITE(conn)) {
3733 * We should really return a permission denied error if either
3734 * O_CREAT or O_TRUNC are set, but for compatibility with
3735 * older versions of Samba we just AND them out.
3737 flags2 &= ~(O_CREAT|O_TRUNC);
3741 * With kernel oplocks the open breaking an oplock
3742 * blocks until the oplock holder has given up the
3743 * oplock or closed the file. We prevent this by always
3744 * trying to open the file with O_NONBLOCK (see "man
3747 * If a process that doesn't use the smbd open files
3748 * database or communication methods holds a kernel
3749 * oplock we must periodically poll for available open
3752 flags2 |= O_NONBLOCK;
3755 * Ensure we can't write on a read-only share or file.
3758 if (flags != O_RDONLY && file_existed &&
3759 (!CAN_WRITE(conn) || IS_DOS_READONLY(existing_dos_attributes))) {
3760 DEBUG(5,("open_file_ntcreate: write access requested for "
3761 "file %s on read only %s\n",
3762 smb_fname_str_dbg(smb_fname),
3763 !CAN_WRITE(conn) ? "share" : "file" ));
3764 return NT_STATUS_ACCESS_DENIED;
3767 if (VALID_STAT(smb_fname->st)) {
3769 * Only try and create a file id before open
3770 * for an existing file. For a file being created
3771 * this won't do anything useful until the file
3772 * exists and has a valid stat struct.
3774 fsp->file_id = vfs_file_id_from_sbuf(conn, &smb_fname->st);
3776 fh_set_private_options(fsp->fh, private_flags);
3777 fsp->access_mask = open_access_mask; /* We change this to the
3778 * requested access_mask after
3779 * the open is done. */
3781 fsp->posix_flags |= FSP_POSIX_FLAGS_ALL;
3784 if ((create_options & FILE_DELETE_ON_CLOSE) &&
3785 (flags2 & O_CREAT) &&
3787 /* Delete on close semantics for new files. */
3788 status = can_set_delete_on_close(fsp,
3789 new_dos_attributes);
3790 if (!NT_STATUS_IS_OK(status)) {
3797 * Ensure we pay attention to default ACLs on directories if required.
3800 if ((flags2 & O_CREAT) && lp_inherit_acls(SNUM(conn)) &&
3801 (def_acl = directory_has_default_acl_fsp(parent_dir_fname->fsp)))
3803 unx_mode = (0777 & lp_create_mask(SNUM(conn)));
3806 DEBUG(4,("calling open_file with flags=0x%X flags2=0x%X mode=0%o, "
3807 "access_mask = 0x%x, open_access_mask = 0x%x\n",
3808 (unsigned int)flags, (unsigned int)flags2,
3809 (unsigned int)unx_mode, (unsigned int)access_mask,
3810 (unsigned int)open_access_mask));
3812 fsp_open = open_file(fsp,
3821 if (NT_STATUS_EQUAL(fsp_open, NT_STATUS_NETWORK_BUSY)) {
3822 if (file_existed && S_ISFIFO(fsp->fsp_name->st.st_ex_mode)) {
3823 DEBUG(10, ("FIFO busy\n"));
3824 return NT_STATUS_NETWORK_BUSY;
3827 DEBUG(10, ("Internal open busy\n"));
3828 return NT_STATUS_NETWORK_BUSY;
3831 * This handles the kernel oplock case:
3833 * the file has an active kernel oplock and the open() returned
3834 * EWOULDBLOCK/EAGAIN which maps to NETWORK_BUSY.
3836 * "Samba locking.tdb oplocks" are handled below after acquiring
3837 * the sharemode lock with get_share_mode_lock().
3842 if (NT_STATUS_EQUAL(fsp_open, NT_STATUS_RETRY)) {
3844 * EINTR from the open(2) syscall. Just setup a retry
3845 * in a bit. We can't use the sys_write() tight retry
3846 * loop here, as we might have to actually deal with
3847 * lease-break signals to avoid a deadlock.
3854 * From here on we assume this is an oplock break triggered
3857 lck = get_existing_share_mode_lock(talloc_tos(), fsp->file_id);
3859 if ((lck != NULL) && !validate_oplock_types(lck)) {
3860 smb_panic("validate_oplock_types failed");
3864 * Retry once a second. If there's a share_mode_lock
3865 * around, also wait for it in case it was smbd
3866 * holding that kernel oplock that can quickly tell us
3867 * the oplock got removed.
3874 timeval_set(OPLOCK_BREAK_TIMEOUT*2, 0),
3879 return NT_STATUS_SHARING_VIOLATION;
3882 if (!NT_STATUS_IS_OK(fsp_open)) {
3883 bool wait_for_aio = NT_STATUS_EQUAL(
3884 fsp_open, NT_STATUS_MORE_PROCESSING_REQUIRED);
3886 schedule_async_open(req);
3891 if (new_file_created) {
3893 * As we atomically create using O_CREAT|O_EXCL,
3894 * then if new_file_created is true, then
3895 * file_existed *MUST* have been false (even
3896 * if the file was previously detected as being
3899 file_existed = false;
3902 if (file_existed && !check_same_dev_ino(&saved_stat, &smb_fname->st)) {
3904 * The file did exist, but some other (local or NFS)
3905 * process either renamed/unlinked and re-created the
3906 * file with different dev/ino after we walked the path,
3907 * but before we did the open. We could retry the
3908 * open but it's a rare enough case it's easier to
3909 * just fail the open to prevent creating any problems
3910 * in the open file db having the wrong dev/ino key.
3913 DBG_WARNING("file %s - dev/ino mismatch. "
3914 "Old (dev=%ju, ino=%ju). "
3915 "New (dev=%ju, ino=%ju). Failing open "
3916 "with NT_STATUS_ACCESS_DENIED.\n",
3917 smb_fname_str_dbg(smb_fname),
3918 (uintmax_t)saved_stat.st_ex_dev,
3919 (uintmax_t)saved_stat.st_ex_ino,
3920 (uintmax_t)smb_fname->st.st_ex_dev,
3921 (uintmax_t)smb_fname->st.st_ex_ino);
3922 return NT_STATUS_ACCESS_DENIED;
3925 old_write_time = smb_fname->st.st_ex_mtime;
3928 * Deal with the race condition where two smbd's detect the
3929 * file doesn't exist and do the create at the same time. One
3930 * of them will win and set a share mode, the other (ie. this
3931 * one) should check if the requested share mode for this
3932 * create is allowed.
3936 * Now the file exists and fsp is successfully opened,
3937 * fsp->dev and fsp->inode are valid and should replace the
3938 * dev=0,inode=0 from a non existent file. Spotted by
3939 * Nadav Danieli <nadavd@exanet.com>. JRA.
3942 lck = get_share_mode_lock(talloc_tos(), fsp->file_id,
3944 smb_fname, &old_write_time);
3947 DEBUG(0, ("open_file_ntcreate: Could not get share "
3948 "mode lock for %s\n",
3949 smb_fname_str_dbg(smb_fname)));
3951 return NT_STATUS_SHARING_VIOLATION;
3954 /* Get the types we need to examine. */
3955 if (!validate_oplock_types(lck)) {
3956 smb_panic("validate_oplock_types failed");
3959 if (has_delete_on_close(lck, fsp->name_hash)) {
3962 return NT_STATUS_DELETE_PENDING;
3965 status = handle_share_mode_lease(
3973 first_open_attempt);
3975 if (NT_STATUS_EQUAL(status, NT_STATUS_RETRY)) {
3976 schedule_defer_open(lck, fsp->file_id, req);
3979 return NT_STATUS_SHARING_VIOLATION;
3982 if (!NT_STATUS_IS_OK(status)) {
3988 share_mode_flags_restrict(lck, access_mask, share_access, 0);
3990 ok = set_share_mode(
3993 get_current_uid(fsp->conn),
3999 if (fsp->oplock_type == LEASE_OPLOCK) {
4000 status = remove_lease_if_stale(
4002 fsp_client_guid(fsp),
4003 &fsp->lease->lease.lease_key);
4004 if (!NT_STATUS_IS_OK(status)) {
4005 DBG_WARNING("remove_lease_if_stale "
4012 return NT_STATUS_NO_MEMORY;
4015 /* Should we atomically (to the client at least) truncate ? */
4016 if ((!new_file_created) &&
4017 (flags2 & O_TRUNC) &&
4018 (S_ISREG(fsp->fsp_name->st.st_ex_mode))) {
4021 ret = SMB_VFS_FTRUNCATE(fsp, 0);
4023 status = map_nt_error_from_unix(errno);
4024 del_share_mode(lck, fsp);
4029 notify_fname(fsp->conn, NOTIFY_ACTION_MODIFIED,
4030 FILE_NOTIFY_CHANGE_SIZE
4031 | FILE_NOTIFY_CHANGE_ATTRIBUTES,
4032 fsp->fsp_name->base_name);
4036 * We have the share entry *locked*.....
4039 /* Delete streams if create_disposition requires it */
4040 if (!new_file_created && clear_ads(create_disposition) &&
4041 !is_ntfs_stream_smb_fname(smb_fname)) {
4042 status = delete_all_streams(conn, smb_fname);
4043 if (!NT_STATUS_IS_OK(status)) {
4044 del_share_mode(lck, fsp);
4051 if (!fsp->fsp_flags.is_pathref &&
4052 fsp_get_io_fd(fsp) != -1 &&
4053 lp_kernel_share_modes(SNUM(conn)))
4057 * Beware: streams implementing VFS modules may
4058 * implement streams in a way that fsp will have the
4059 * basefile open in the fsp fd, so lacking a distinct
4060 * fd for the stream kernel_flock will apply on the
4061 * basefile which is wrong. The actual check is
4062 * deferred to the VFS module implementing the
4063 * kernel_flock call.
4065 ret_flock = SMB_VFS_KERNEL_FLOCK(fsp, share_access, access_mask);
4066 if(ret_flock == -1 ){
4068 del_share_mode(lck, fsp);
4072 return NT_STATUS_SHARING_VIOLATION;
4075 fsp->fsp_flags.kernel_share_modes_taken = true;
4079 * At this point onwards, we can guarantee that the share entry
4080 * is locked, whether we created the file or not, and that the
4081 * deny mode is compatible with all current opens.
4085 * According to Samba4, SEC_FILE_READ_ATTRIBUTE is always granted,
4086 * but we don't have to store this - just ignore it on access check.
4088 if (conn->sconn->using_smb2) {
4090 * SMB2 doesn't return it (according to Microsoft tests).
4091 * Test Case: TestSuite_ScenarioNo009GrantedAccessTestS0
4092 * File created with access = 0x7 (Read, Write, Delete)
4093 * Query Info on file returns 0x87 (Read, Write, Delete, Read Attributes)
4095 fsp->access_mask = access_mask;
4097 /* But SMB1 does. */
4098 fsp->access_mask = access_mask | FILE_READ_ATTRIBUTES;
4101 if (new_file_created) {
4102 info = FILE_WAS_CREATED;
4104 if (flags2 & O_TRUNC) {
4105 info = FILE_WAS_OVERWRITTEN;
4107 info = FILE_WAS_OPENED;
4115 /* Handle strange delete on close create semantics. */
4116 if (create_options & FILE_DELETE_ON_CLOSE) {
4117 if (!new_file_created) {
4118 status = can_set_delete_on_close(fsp,
4119 existing_dos_attributes);
4121 if (!NT_STATUS_IS_OK(status)) {
4122 /* Remember to delete the mode we just added. */
4123 del_share_mode(lck, fsp);
4129 /* Note that here we set the *initial* delete on close flag,
4130 not the regular one. The magic gets handled in close. */
4131 fsp->fsp_flags.initial_delete_on_close = true;
4135 * If we created a file and it's not a stream, this is the point where
4136 * we set the itime (aka invented time) that get's stored in the DOS
4137 * attribute xattr. The value is going to be either what the filesystem
4138 * provided or a copy of the creation date.
4140 * Either way, we turn the itime into a File-ID, unless the filesystem
4141 * provided one (unlikely).
4143 if (info == FILE_WAS_CREATED && !is_named_stream(smb_fname)) {
4144 smb_fname->st.st_ex_iflags &= ~ST_EX_IFLAG_CALCULATED_ITIME;
4146 if (lp_store_dos_attributes(SNUM(conn)) &&
4147 smb_fname->st.st_ex_iflags & ST_EX_IFLAG_CALCULATED_FILE_ID)
4151 file_id = make_file_id_from_itime(&smb_fname->st);
4152 update_stat_ex_file_id(&smb_fname->st, file_id);
4156 if (info != FILE_WAS_OPENED) {
4157 /* Overwritten files should be initially set as archive */
4158 if ((info == FILE_WAS_OVERWRITTEN && lp_map_archive(SNUM(conn))) ||
4159 lp_store_dos_attributes(SNUM(conn))) {
4160 (void)fdos_mode(fsp);
4162 if (file_set_dosmode(conn, smb_fname,
4163 new_dos_attributes | FILE_ATTRIBUTE_ARCHIVE,
4164 parent_dir_fname, true) == 0) {
4165 unx_mode = smb_fname->st.st_ex_mode;
4171 /* Determine sparse flag. */
4173 /* POSIX opens are sparse by default. */
4174 fsp->fsp_flags.is_sparse = true;
4176 fsp->fsp_flags.is_sparse =
4177 (existing_dos_attributes & FILE_ATTRIBUTE_SPARSE);
4181 * Take care of inherited ACLs on created files - if default ACL not
4185 if (!posix_open && new_file_created && !def_acl) {
4186 if (unx_mode != smb_fname->st.st_ex_mode) {
4187 int ret = SMB_VFS_FCHMOD(fsp, unx_mode);
4189 DBG_INFO("failed to reset "
4190 "attributes of file %s to 0%o\n",
4191 smb_fname_str_dbg(smb_fname),
4192 (unsigned int)unx_mode);
4196 } else if (new_unx_mode) {
4198 * We only get here in the case of:
4200 * a). Not a POSIX open.
4201 * b). File already existed.
4202 * c). File was overwritten.
4203 * d). Requested DOS attributes didn't match
4204 * the DOS attributes on the existing file.
4206 * In that case new_unx_mode has been set
4207 * equal to the calculated mode (including
4208 * possible inheritance of the mode from the
4209 * containing directory).
4211 * Note this mode was calculated with the
4212 * DOS attribute FILE_ATTRIBUTE_ARCHIVE added,
4213 * so the mode change here is suitable for
4214 * an overwritten file.
4217 if (new_unx_mode != smb_fname->st.st_ex_mode) {
4218 int ret = SMB_VFS_FCHMOD(fsp, new_unx_mode);
4220 DBG_INFO("failed to reset "
4221 "attributes of file %s to 0%o\n",
4222 smb_fname_str_dbg(smb_fname),
4223 (unsigned int)new_unx_mode);
4230 * Deal with other opens having a modified write time.
4232 struct timespec write_time = get_share_mode_write_time(lck);
4234 if (!is_omit_timespec(&write_time)) {
4235 update_stat_ex_mtime(&fsp->fsp_name->st, write_time);
4241 return NT_STATUS_OK;
4244 static NTSTATUS mkdir_internal(connection_struct *conn,
4245 struct smb_filename *parent_dir_fname, /* parent. */
4246 struct smb_filename *smb_fname_atname, /* atname relative to parent. */
4247 struct smb_filename *smb_dname, /* full pathname from root of share. */
4248 uint32_t file_attributes,
4249 struct files_struct *fsp)
4251 const struct loadparm_substitution *lp_sub =
4252 loadparm_s3_global_substitution();
4255 bool posix_open = false;
4256 bool need_re_stat = false;
4257 uint32_t access_mask = SEC_DIR_ADD_SUBDIR;
4260 if (!CAN_WRITE(conn) || (access_mask & ~(conn->share_access))) {
4261 DEBUG(5,("mkdir_internal: failing share access "
4262 "%s\n", lp_servicename(talloc_tos(), lp_sub, SNUM(conn))));
4263 return NT_STATUS_ACCESS_DENIED;
4266 if (file_attributes & FILE_FLAG_POSIX_SEMANTICS) {
4268 mode = (mode_t)(file_attributes & ~FILE_FLAG_POSIX_SEMANTICS);
4270 mode = unix_mode(conn,
4271 FILE_ATTRIBUTE_DIRECTORY,
4276 status = check_parent_access_fsp(parent_dir_fname->fsp, access_mask);
4277 if(!NT_STATUS_IS_OK(status)) {
4278 DBG_INFO("check_parent_access_fsp "
4279 "on directory %s for path %s returned %s\n",
4280 smb_fname_str_dbg(parent_dir_fname),
4281 smb_dname->base_name,
4286 if (lp_inherit_acls(SNUM(conn))) {
4287 if (directory_has_default_acl_fsp(parent_dir_fname->fsp)) {
4288 mode = (0777 & lp_directory_mask(SNUM(conn)));
4292 ret = SMB_VFS_MKDIRAT(conn,
4293 parent_dir_fname->fsp,
4297 return map_nt_error_from_unix(errno);
4301 * Make this a pathref fsp for now. open_directory() will reopen as a
4304 fsp->fsp_flags.is_pathref = true;
4306 status = fd_openat(conn->cwd_fsp, smb_dname, fsp, O_RDONLY | O_DIRECTORY, 0);
4307 if (!NT_STATUS_IS_OK(status)) {
4311 /* Ensure we're checking for a symlink here.... */
4312 /* We don't want to get caught by a symlink racer. */
4314 if (SMB_VFS_FSTAT(fsp, &smb_dname->st) == -1) {
4315 DEBUG(2, ("Could not stat directory '%s' just created: %s\n",
4316 smb_fname_str_dbg(smb_dname), strerror(errno)));
4317 return map_nt_error_from_unix(errno);
4320 if (!S_ISDIR(smb_dname->st.st_ex_mode)) {
4321 DEBUG(0, ("Directory '%s' just created is not a directory !\n",
4322 smb_fname_str_dbg(smb_dname)));
4323 return NT_STATUS_NOT_A_DIRECTORY;
4326 smb_dname->st.st_ex_iflags &= ~ST_EX_IFLAG_CALCULATED_ITIME;
4328 if (lp_store_dos_attributes(SNUM(conn))) {
4329 if (smb_dname->st.st_ex_iflags & ST_EX_IFLAG_CALCULATED_FILE_ID)
4333 file_id = make_file_id_from_itime(&smb_dname->st);
4334 update_stat_ex_file_id(&smb_dname->st, file_id);
4338 file_set_dosmode(conn, smb_dname,
4339 file_attributes | FILE_ATTRIBUTE_DIRECTORY,
4340 parent_dir_fname, true);
4344 if (lp_inherit_permissions(SNUM(conn))) {
4345 inherit_access_posix_acl(conn, parent_dir_fname,
4347 need_re_stat = true;
4352 * Check if high bits should have been set,
4353 * then (if bits are missing): add them.
4354 * Consider bits automagically set by UNIX, i.e. SGID bit from parent
4357 if ((mode & ~(S_IRWXU|S_IRWXG|S_IRWXO)) &&
4358 (mode & ~smb_dname->st.st_ex_mode)) {
4360 (smb_dname->st.st_ex_mode |
4361 (mode & ~smb_dname->st.st_ex_mode)));
4362 need_re_stat = true;
4366 /* Change the owner if required. */
4367 if (lp_inherit_owner(SNUM(conn)) != INHERIT_OWNER_NO) {
4368 change_dir_owner_to_parent_fsp(parent_dir_fname->fsp,
4370 need_re_stat = true;
4374 if (SMB_VFS_FSTAT(fsp, &smb_dname->st) == -1) {
4375 DEBUG(2, ("Could not stat directory '%s' just created: %s\n",
4376 smb_fname_str_dbg(smb_dname), strerror(errno)));
4377 return map_nt_error_from_unix(errno);
4381 notify_fname(conn, NOTIFY_ACTION_ADDED, FILE_NOTIFY_CHANGE_DIR_NAME,
4382 smb_dname->base_name);
4384 return NT_STATUS_OK;
4387 /****************************************************************************
4388 Open a directory from an NT SMB call.
4389 ****************************************************************************/
4391 static NTSTATUS open_directory(connection_struct *conn,
4392 struct smb_request *req,
4393 uint32_t access_mask,
4394 uint32_t share_access,
4395 uint32_t create_disposition,
4396 uint32_t create_options,
4397 uint32_t file_attributes,
4398 struct smb_filename *parent_dir_fname,
4399 struct smb_filename *smb_fname_atname,
4401 struct files_struct *fsp)
4403 struct smb_filename *smb_dname = fsp->fsp_name;
4404 bool dir_existed = VALID_STAT(smb_dname->st);
4405 struct share_mode_lock *lck = NULL;
4407 struct timespec mtimespec;
4411 if (is_ntfs_stream_smb_fname(smb_dname)) {
4412 DEBUG(2, ("open_directory: %s is a stream name!\n",
4413 smb_fname_str_dbg(smb_dname)));
4414 return NT_STATUS_NOT_A_DIRECTORY;
4417 if (!(file_attributes & FILE_FLAG_POSIX_SEMANTICS)) {
4418 /* Ensure we have a directory attribute. */
4419 file_attributes |= FILE_ATTRIBUTE_DIRECTORY;
4422 DBG_INFO("opening directory %s, access_mask = 0x%"PRIx32", "
4423 "share_access = 0x%"PRIx32" create_options = 0x%"PRIx32", "
4424 "create_disposition = 0x%"PRIx32", "
4425 "file_attributes = 0x%"PRIx32"\n",
4426 smb_fname_str_dbg(smb_dname),
4433 status = smbd_calculate_access_mask_fsp(parent_dir_fname->fsp,
4438 if (!NT_STATUS_IS_OK(status)) {
4439 DBG_DEBUG("smbd_calculate_access_mask_fsp "
4440 "on file %s returned %s\n",
4441 smb_fname_str_dbg(smb_dname),
4446 if ((access_mask & SEC_FLAG_SYSTEM_SECURITY) &&
4447 !security_token_has_privilege(get_current_nttok(conn),
4448 SEC_PRIV_SECURITY)) {
4449 DEBUG(10, ("open_directory: open on %s "
4450 "failed - SEC_FLAG_SYSTEM_SECURITY denied.\n",
4451 smb_fname_str_dbg(smb_dname)));
4452 return NT_STATUS_PRIVILEGE_NOT_HELD;
4455 switch( create_disposition ) {
4459 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
4462 info = FILE_WAS_OPENED;
4467 /* If directory exists error. If directory doesn't
4471 status = NT_STATUS_OBJECT_NAME_COLLISION;
4472 DEBUG(2, ("open_directory: unable to create "
4473 "%s. Error was %s\n",
4474 smb_fname_str_dbg(smb_dname),
4475 nt_errstr(status)));
4479 status = mkdir_internal(conn,
4486 if (!NT_STATUS_IS_OK(status)) {
4487 DEBUG(2, ("open_directory: unable to create "
4488 "%s. Error was %s\n",
4489 smb_fname_str_dbg(smb_dname),
4490 nt_errstr(status)));
4494 info = FILE_WAS_CREATED;
4499 * If directory exists open. If directory doesn't
4504 status = NT_STATUS_OK;
4505 info = FILE_WAS_OPENED;
4507 status = mkdir_internal(conn,
4514 if (NT_STATUS_IS_OK(status)) {
4515 info = FILE_WAS_CREATED;
4517 /* Cope with create race. */
4518 if (!NT_STATUS_EQUAL(status,
4519 NT_STATUS_OBJECT_NAME_COLLISION)) {
4520 DEBUG(2, ("open_directory: unable to create "
4521 "%s. Error was %s\n",
4522 smb_fname_str_dbg(smb_dname),
4523 nt_errstr(status)));
4528 * If mkdir_internal() returned
4529 * NT_STATUS_OBJECT_NAME_COLLISION
4530 * we still must lstat the path.
4533 if (SMB_VFS_LSTAT(conn, smb_dname)
4535 DEBUG(2, ("Could not stat "
4536 "directory '%s' just "
4541 return map_nt_error_from_unix(
4545 info = FILE_WAS_OPENED;
4551 case FILE_SUPERSEDE:
4552 case FILE_OVERWRITE:
4553 case FILE_OVERWRITE_IF:
4555 DEBUG(5,("open_directory: invalid create_disposition "
4556 "0x%x for directory %s\n",
4557 (unsigned int)create_disposition,
4558 smb_fname_str_dbg(smb_dname)));
4559 return NT_STATUS_INVALID_PARAMETER;
4562 if(!S_ISDIR(smb_dname->st.st_ex_mode)) {
4563 DEBUG(5,("open_directory: %s is not a directory !\n",
4564 smb_fname_str_dbg(smb_dname)));
4565 return NT_STATUS_NOT_A_DIRECTORY;
4569 * Setup the files_struct for it.
4572 fsp->file_id = vfs_file_id_from_sbuf(conn, &smb_dname->st);
4573 fsp->vuid = req ? req->vuid : UID_FIELD_INVALID;
4574 fsp->file_pid = req ? req->smbpid : 0;
4575 fsp->fsp_flags.can_lock = false;
4576 fsp->fsp_flags.can_read = false;
4577 fsp->fsp_flags.can_write = false;
4579 fh_set_private_options(fsp->fh, 0);
4581 * According to Samba4, SEC_FILE_READ_ATTRIBUTE is always granted,
4583 fsp->access_mask = access_mask | FILE_READ_ATTRIBUTES;
4584 fsp->print_file = NULL;
4585 fsp->fsp_flags.modified = false;
4586 fsp->oplock_type = NO_OPLOCK;
4587 fsp->sent_oplock_break = NO_BREAK_SENT;
4588 fsp->fsp_flags.is_directory = true;
4589 if (file_attributes & FILE_FLAG_POSIX_SEMANTICS) {
4590 fsp->posix_flags |= FSP_POSIX_FLAGS_ALL;
4593 /* Don't store old timestamps for directory
4594 handles in the internal database. We don't
4595 update them in there if new objects
4596 are created in the directory. Currently
4597 we only update timestamps on file writes.
4600 mtimespec = make_omit_timespec();
4602 status = reopen_from_fsp(fsp, O_RDONLY|O_DIRECTORY, 0, NULL);
4603 if (!NT_STATUS_IS_OK(status)) {
4604 DBG_INFO("Could not open fd for%s (%s)\n",
4605 smb_fname_str_dbg(smb_dname),
4610 status = vfs_stat_fsp(fsp);
4611 if (!NT_STATUS_IS_OK(status)) {
4616 if(!S_ISDIR(fsp->fsp_name->st.st_ex_mode)) {
4617 DEBUG(5,("open_directory: %s is not a directory !\n",
4618 smb_fname_str_dbg(smb_dname)));
4620 return NT_STATUS_NOT_A_DIRECTORY;
4623 /* Ensure there was no race condition. We need to check
4624 * dev/inode but not permissions, as these can change
4626 if (!check_same_dev_ino(&smb_dname->st, &fsp->fsp_name->st)) {
4627 DEBUG(5,("open_directory: stat struct differs for "
4629 smb_fname_str_dbg(smb_dname)));
4631 return NT_STATUS_ACCESS_DENIED;
4634 if (info == FILE_WAS_OPENED) {
4635 status = smbd_check_access_rights_fsp(parent_dir_fname->fsp,
4639 if (!NT_STATUS_IS_OK(status)) {
4640 DBG_DEBUG("smbd_check_access_rights_fsp on "
4641 "file %s failed with %s\n",
4649 lck = get_share_mode_lock(talloc_tos(), fsp->file_id,
4650 conn->connectpath, smb_dname,
4654 DEBUG(0, ("open_directory: Could not get share mode lock for "
4655 "%s\n", smb_fname_str_dbg(smb_dname)));
4657 return NT_STATUS_SHARING_VIOLATION;
4660 if (has_delete_on_close(lck, fsp->name_hash)) {
4663 return NT_STATUS_DELETE_PENDING;
4666 status = open_mode_check(conn, fsp->file_id, lck,
4667 access_mask, share_access);
4669 if (!NT_STATUS_IS_OK(status)) {
4675 share_mode_flags_restrict(lck, access_mask, share_access, 0);
4677 ok = set_share_mode(
4680 get_current_uid(conn),
4688 return NT_STATUS_NO_MEMORY;
4691 /* For directories the delete on close bit at open time seems
4692 always to be honored on close... See test 19 in Samba4 BASE-DELETE. */
4693 if (create_options & FILE_DELETE_ON_CLOSE) {
4694 status = can_set_delete_on_close(fsp, 0);
4695 if (!NT_STATUS_IS_OK(status) && !NT_STATUS_EQUAL(status, NT_STATUS_DIRECTORY_NOT_EMPTY)) {
4696 del_share_mode(lck, fsp);
4702 if (NT_STATUS_IS_OK(status)) {
4703 /* Note that here we set the *initial* delete on close flag,
4704 not the regular one. The magic gets handled in close. */
4705 fsp->fsp_flags.initial_delete_on_close = true;
4711 * Deal with other opens having a modified write time. Is this
4712 * possible for directories?
4714 struct timespec write_time = get_share_mode_write_time(lck);
4716 if (!is_omit_timespec(&write_time)) {
4717 update_stat_ex_mtime(&fsp->fsp_name->st, write_time);
4727 return NT_STATUS_OK;
4730 NTSTATUS create_directory(connection_struct *conn, struct smb_request *req,
4731 struct smb_filename *smb_dname)
4736 status = SMB_VFS_CREATE_FILE(
4739 smb_dname, /* fname */
4740 FILE_READ_ATTRIBUTES, /* access_mask */
4741 FILE_SHARE_NONE, /* share_access */
4742 FILE_CREATE, /* create_disposition*/
4743 FILE_DIRECTORY_FILE, /* create_options */
4744 FILE_ATTRIBUTE_DIRECTORY, /* file_attributes */
4745 0, /* oplock_request */
4747 0, /* allocation_size */
4748 0, /* private_flags */
4753 NULL, NULL); /* create context */
4755 if (NT_STATUS_IS_OK(status)) {
4756 close_file(req, fsp, NORMAL_CLOSE);
4762 /****************************************************************************
4763 Receive notification that one of our open files has been renamed by another
4765 ****************************************************************************/
4767 void msg_file_was_renamed(struct messaging_context *msg_ctx,
4770 struct server_id src,
4773 struct file_rename_message *msg = NULL;
4774 enum ndr_err_code ndr_err;
4776 struct smb_filename *smb_fname = NULL;
4777 struct smbd_server_connection *sconn =
4778 talloc_get_type_abort(private_data,
4779 struct smbd_server_connection);
4781 msg = talloc(talloc_tos(), struct file_rename_message);
4783 DBG_WARNING("talloc failed\n");
4787 ndr_err = ndr_pull_struct_blob_all(
4791 (ndr_pull_flags_fn_t)ndr_pull_file_rename_message);
4792 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
4793 DBG_DEBUG("ndr_pull_oplock_break_message failed: %s\n",
4794 ndr_errstr(ndr_err));
4797 if (DEBUGLEVEL >= 10) {
4798 struct server_id_buf buf;
4799 DBG_DEBUG("Got rename message from %s\n",
4800 server_id_str_buf(src, &buf));
4801 NDR_PRINT_DEBUG(file_rename_message, msg);
4804 /* stream_name must always be NULL if there is no stream. */
4805 if ((msg->stream_name != NULL) && (msg->stream_name[0] == '\0')) {
4806 msg->stream_name = NULL;
4809 smb_fname = synthetic_smb_fname(msg,
4815 if (smb_fname == NULL) {
4816 DBG_DEBUG("synthetic_smb_fname failed\n");
4820 fsp = file_find_dif(sconn, msg->id, msg->share_file_id);
4822 DBG_DEBUG("fsp not found\n");
4826 if (strcmp(fsp->conn->connectpath, msg->servicepath) == 0) {
4828 DBG_DEBUG("renaming file %s from %s -> %s\n",
4831 smb_fname_str_dbg(smb_fname));
4832 status = fsp_set_smb_fname(fsp, smb_fname);
4833 if (!NT_STATUS_IS_OK(status)) {
4834 DBG_DEBUG("fsp_set_smb_fname failed: %s\n",
4840 * Now we have the complete path we can work out if
4841 * this is actually within this share and adjust
4842 * newname accordingly.
4844 DBG_DEBUG("share mismatch (sharepath %s not sharepath %s) "
4845 "%s from %s -> %s\n",
4846 fsp->conn->connectpath,
4850 smb_fname_str_dbg(smb_fname));
4857 * If a main file is opened for delete, all streams need to be checked for
4858 * !FILE_SHARE_DELETE. Do this by opening with DELETE_ACCESS.
4859 * If that works, delete them all by setting the delete on close and close.
4862 static NTSTATUS open_streams_for_delete(connection_struct *conn,
4863 const struct smb_filename *smb_fname)
4865 struct stream_struct *stream_info = NULL;
4866 files_struct **streams = NULL;
4868 unsigned int i, num_streams = 0;
4869 TALLOC_CTX *frame = talloc_stackframe();
4870 const struct smb_filename *pathref = NULL;
4873 if (smb_fname->fsp == NULL) {
4874 struct smb_filename *tmp = NULL;
4875 status = synthetic_pathref(frame,
4877 smb_fname->base_name,
4883 if (!NT_STATUS_IS_OK(status)) {
4884 if (NT_STATUS_EQUAL(status, NT_STATUS_NOT_IMPLEMENTED)
4885 || NT_STATUS_EQUAL(status,
4886 NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
4887 DBG_DEBUG("no streams around\n");
4889 return NT_STATUS_OK;
4891 DBG_DEBUG("synthetic_pathref failed: %s\n",
4897 pathref = smb_fname;
4899 status = vfs_fstreaminfo(pathref->fsp, talloc_tos(),
4900 &num_streams, &stream_info);
4902 if (NT_STATUS_EQUAL(status, NT_STATUS_NOT_IMPLEMENTED)
4903 || NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
4904 DEBUG(10, ("no streams around\n"));
4906 return NT_STATUS_OK;
4909 if (!NT_STATUS_IS_OK(status)) {
4910 DEBUG(10, ("vfs_fstreaminfo failed: %s\n",
4911 nt_errstr(status)));
4915 DEBUG(10, ("open_streams_for_delete found %d streams\n",
4918 if (num_streams == 0) {
4920 return NT_STATUS_OK;
4923 streams = talloc_array(talloc_tos(), files_struct *, num_streams);
4924 if (streams == NULL) {
4925 DEBUG(0, ("talloc failed\n"));
4926 status = NT_STATUS_NO_MEMORY;
4930 for (i=0; i<num_streams; i++) {
4931 struct smb_filename *smb_fname_cp;
4933 if (strequal(stream_info[i].name, "::$DATA")) {
4938 smb_fname_cp = synthetic_smb_fname(talloc_tos(),
4939 smb_fname->base_name,
4940 stream_info[i].name,
4944 ~SMB_FILENAME_POSIX_PATH));
4945 if (smb_fname_cp == NULL) {
4946 status = NT_STATUS_NO_MEMORY;
4950 if (SMB_VFS_STAT(conn, smb_fname_cp) == -1) {
4951 DEBUG(10, ("Unable to stat stream: %s\n",
4952 smb_fname_str_dbg(smb_fname_cp)));
4955 status = openat_pathref_fsp(conn->cwd_fsp, smb_fname_cp);
4956 if (!NT_STATUS_IS_OK(status)) {
4957 DBG_DEBUG("Unable to open stream [%s]: %s\n",
4958 smb_fname_str_dbg(smb_fname_cp),
4960 TALLOC_FREE(smb_fname_cp);
4964 status = SMB_VFS_CREATE_FILE(
4967 smb_fname_cp, /* fname */
4968 DELETE_ACCESS, /* access_mask */
4969 (FILE_SHARE_READ | /* share_access */
4970 FILE_SHARE_WRITE | FILE_SHARE_DELETE),
4971 FILE_OPEN, /* create_disposition*/
4972 0, /* create_options */
4973 FILE_ATTRIBUTE_NORMAL, /* file_attributes */
4974 0, /* oplock_request */
4976 0, /* allocation_size */
4977 0, /* private_flags */
4980 &streams[i], /* result */
4982 NULL, NULL); /* create context */
4984 if (!NT_STATUS_IS_OK(status)) {
4985 DEBUG(10, ("Could not open stream %s: %s\n",
4986 smb_fname_str_dbg(smb_fname_cp),
4987 nt_errstr(status)));
4989 TALLOC_FREE(smb_fname_cp);
4992 TALLOC_FREE(smb_fname_cp);
4996 * don't touch the variable "status" beyond this point :-)
4999 for (j = i-1 ; j >= 0; j--) {
5000 if (streams[j] == NULL) {
5004 DEBUG(10, ("Closing stream # %d, %s\n", j,
5005 fsp_str_dbg(streams[j])));
5006 close_file(NULL, streams[j], NORMAL_CLOSE);
5014 /*********************************************************************
5015 Create a default ACL by inheriting from the parent. If no inheritance
5016 from the parent available, don't set anything. This will leave the actual
5017 permissions the new file or directory already got from the filesystem
5018 as the NT ACL when read.
5019 *********************************************************************/
5021 static NTSTATUS inherit_new_acl(struct smb_filename *parent_dir_fname,
5024 TALLOC_CTX *frame = talloc_stackframe();
5025 struct security_descriptor *parent_desc = NULL;
5026 NTSTATUS status = NT_STATUS_OK;
5027 struct security_descriptor *psd = NULL;
5028 const struct dom_sid *owner_sid = NULL;
5029 const struct dom_sid *group_sid = NULL;
5030 uint32_t security_info_sent = (SECINFO_OWNER | SECINFO_GROUP | SECINFO_DACL);
5031 struct security_token *token = fsp->conn->session_info->security_token;
5032 bool inherit_owner =
5033 (lp_inherit_owner(SNUM(fsp->conn)) == INHERIT_OWNER_WINDOWS_AND_UNIX);
5034 bool inheritable_components = false;
5035 bool try_builtin_administrators = false;
5036 const struct dom_sid *BA_U_sid = NULL;
5037 const struct dom_sid *BA_G_sid = NULL;
5038 bool try_system = false;
5039 const struct dom_sid *SY_U_sid = NULL;
5040 const struct dom_sid *SY_G_sid = NULL;
5044 status = SMB_VFS_FGET_NT_ACL(parent_dir_fname->fsp,
5045 (SECINFO_OWNER | SECINFO_GROUP | SECINFO_DACL),
5048 if (!NT_STATUS_IS_OK(status)) {
5053 inheritable_components = sd_has_inheritable_components(parent_desc,
5054 fsp->fsp_flags.is_directory);
5056 if (!inheritable_components && !inherit_owner) {
5058 /* Nothing to inherit and not setting owner. */
5059 return NT_STATUS_OK;
5062 /* Create an inherited descriptor from the parent. */
5064 if (DEBUGLEVEL >= 10) {
5065 DEBUG(10,("inherit_new_acl: parent acl for %s is:\n",
5066 fsp_str_dbg(fsp) ));
5067 NDR_PRINT_DEBUG(security_descriptor, parent_desc);
5070 /* Inherit from parent descriptor if "inherit owner" set. */
5071 if (inherit_owner) {
5072 owner_sid = parent_desc->owner_sid;
5073 group_sid = parent_desc->group_sid;
5076 if (owner_sid == NULL) {
5077 if (security_token_has_builtin_administrators(token)) {
5078 try_builtin_administrators = true;
5079 } else if (security_token_is_system(token)) {
5080 try_builtin_administrators = true;
5085 if (group_sid == NULL &&
5086 token->num_sids == PRIMARY_GROUP_SID_INDEX)
5088 if (security_token_is_system(token)) {
5089 try_builtin_administrators = true;
5094 if (try_builtin_administrators) {
5098 ok = sids_to_unixids(&global_sid_Builtin_Administrators, 1, &ids);
5102 BA_U_sid = &global_sid_Builtin_Administrators;
5103 BA_G_sid = &global_sid_Builtin_Administrators;
5106 BA_U_sid = &global_sid_Builtin_Administrators;
5109 BA_G_sid = &global_sid_Builtin_Administrators;
5121 ok = sids_to_unixids(&global_sid_System, 1, &ids);
5125 SY_U_sid = &global_sid_System;
5126 SY_G_sid = &global_sid_System;
5129 SY_U_sid = &global_sid_System;
5132 SY_G_sid = &global_sid_System;
5140 if (owner_sid == NULL) {
5141 owner_sid = BA_U_sid;
5144 if (owner_sid == NULL) {
5145 owner_sid = SY_U_sid;
5148 if (group_sid == NULL) {
5149 group_sid = SY_G_sid;
5152 if (try_system && group_sid == NULL) {
5153 group_sid = BA_G_sid;
5156 if (owner_sid == NULL) {
5157 owner_sid = &token->sids[PRIMARY_USER_SID_INDEX];
5159 if (group_sid == NULL) {
5160 if (token->num_sids == PRIMARY_GROUP_SID_INDEX) {
5161 group_sid = &token->sids[PRIMARY_USER_SID_INDEX];
5163 group_sid = &token->sids[PRIMARY_GROUP_SID_INDEX];
5167 status = se_create_child_secdesc(frame,
5173 fsp->fsp_flags.is_directory);
5174 if (!NT_STATUS_IS_OK(status)) {
5179 /* If inheritable_components == false,
5180 se_create_child_secdesc()
5181 creates a security descriptor with a NULL dacl
5182 entry, but with SEC_DESC_DACL_PRESENT. We need
5183 to remove that flag. */
5185 if (!inheritable_components) {
5186 security_info_sent &= ~SECINFO_DACL;
5187 psd->type &= ~SEC_DESC_DACL_PRESENT;
5190 if (DEBUGLEVEL >= 10) {
5191 DEBUG(10,("inherit_new_acl: child acl for %s is:\n",
5192 fsp_str_dbg(fsp) ));
5193 NDR_PRINT_DEBUG(security_descriptor, psd);
5196 if (inherit_owner) {
5197 /* We need to be root to force this. */
5200 status = SMB_VFS_FSET_NT_ACL(fsp,
5203 if (inherit_owner) {
5211 * If we already have a lease, it must match the new file id. [MS-SMB2]
5212 * 3.3.5.9.8 speaks about INVALID_PARAMETER if an already used lease key is
5213 * used for a different file name.
5216 struct lease_match_state {
5217 /* Input parameters. */
5218 TALLOC_CTX *mem_ctx;
5219 const char *servicepath;
5220 const struct smb_filename *fname;
5223 /* Return parameters. */
5224 uint32_t num_file_ids;
5225 struct file_id *ids;
5226 NTSTATUS match_status;
5229 /*************************************************************
5230 File doesn't exist but this lease key+guid is already in use.
5232 This is only allowable in the dynamic share case where the
5233 service path must be different.
5235 There is a small race condition here in the multi-connection
5236 case where a client sends two create calls on different connections,
5237 where the file doesn't exist and one smbd creates the leases_db
5238 entry first, but this will get fixed by the multichannel cleanup
5239 when all identical client_guids get handled by a single smbd.
5240 **************************************************************/
5242 static void lease_match_parser_new_file(
5244 const struct leases_db_file *files,
5245 struct lease_match_state *state)
5249 for (i = 0; i < num_files; i++) {
5250 const struct leases_db_file *f = &files[i];
5251 if (strequal(state->servicepath, f->servicepath)) {
5252 state->match_status = NT_STATUS_INVALID_PARAMETER;
5257 /* Dynamic share case. Break leases on all other files. */
5258 state->match_status = leases_db_copy_file_ids(state->mem_ctx,
5262 if (!NT_STATUS_IS_OK(state->match_status)) {
5266 state->num_file_ids = num_files;
5267 state->match_status = NT_STATUS_OPLOCK_NOT_GRANTED;
5271 static void lease_match_parser(
5273 const struct leases_db_file *files,
5276 struct lease_match_state *state =
5277 (struct lease_match_state *)private_data;
5280 if (!state->file_existed) {
5282 * Deal with name mismatch or
5283 * possible dynamic share case separately
5284 * to make code clearer.
5286 lease_match_parser_new_file(num_files,
5293 state->match_status = NT_STATUS_OK;
5295 for (i = 0; i < num_files; i++) {
5296 const struct leases_db_file *f = &files[i];
5298 /* Everything should be the same. */
5299 if (!file_id_equal(&state->id, &f->id)) {
5300 /* This should catch all dynamic share cases. */
5301 state->match_status = NT_STATUS_OPLOCK_NOT_GRANTED;
5304 if (!strequal(f->servicepath, state->servicepath)) {
5305 state->match_status = NT_STATUS_INVALID_PARAMETER;
5308 if (!strequal(f->base_name, state->fname->base_name)) {
5309 state->match_status = NT_STATUS_INVALID_PARAMETER;
5312 if (!strequal(f->stream_name, state->fname->stream_name)) {
5313 state->match_status = NT_STATUS_INVALID_PARAMETER;
5318 if (NT_STATUS_IS_OK(state->match_status)) {
5320 * Common case - just opening another handle on a
5321 * file on a non-dynamic share.
5326 if (NT_STATUS_EQUAL(state->match_status, NT_STATUS_INVALID_PARAMETER)) {
5327 /* Mismatched path. Error back to client. */
5332 * File id mismatch. Dynamic share case NT_STATUS_OPLOCK_NOT_GRANTED.
5333 * Don't allow leases.
5336 state->match_status = leases_db_copy_file_ids(state->mem_ctx,
5340 if (!NT_STATUS_IS_OK(state->match_status)) {
5344 state->num_file_ids = num_files;
5345 state->match_status = NT_STATUS_OPLOCK_NOT_GRANTED;
5349 struct lease_match_break_state {
5350 struct messaging_context *msg_ctx;
5351 const struct smb2_lease_key *lease_key;
5359 static bool lease_match_break_fn(
5360 struct share_mode_entry *e,
5363 struct lease_match_break_state *state = private_data;
5365 uint32_t e_lease_type;
5368 stale = share_entry_stale_pid(e);
5373 equal = smb2_lease_key_equal(&e->lease_key, state->lease_key);
5378 status = leases_db_get(
5382 NULL, /* current_state */
5383 NULL, /* breaking */
5384 NULL, /* breaking_to_requested */
5385 NULL, /* breaking_to_required */
5386 &state->version, /* lease_version */
5387 &state->epoch); /* epoch */
5388 if (NT_STATUS_IS_OK(status)) {
5389 state->found_lease = true;
5391 DBG_WARNING("Could not find version/epoch: %s\n",
5395 e_lease_type = get_lease_type(e, state->id);
5396 if (e_lease_type == SMB2_LEASE_NONE) {
5399 send_break_message(state->msg_ctx, &state->id, e, SMB2_LEASE_NONE);
5402 * Windows 7 and 8 lease clients are broken in that they will
5403 * not respond to lease break requests whilst waiting for an
5404 * outstanding open request on that lease handle on the same
5405 * TCP connection, due to holding an internal inode lock.
5407 * This means we can't reschedule ourselves here, but must
5408 * return from the create.
5412 * Send the breaks and then return SMB2_LEASE_NONE in the
5413 * lease handle to cause them to acknowledge the lease
5414 * break. Consultation with Microsoft engineering confirmed
5415 * this approach is safe.
5421 static NTSTATUS lease_match(connection_struct *conn,
5422 struct smb_request *req,
5423 const struct smb2_lease_key *lease_key,
5424 const char *servicepath,
5425 const struct smb_filename *fname,
5426 uint16_t *p_version,
5429 struct smbd_server_connection *sconn = req->sconn;
5430 TALLOC_CTX *tos = talloc_tos();
5431 struct lease_match_state state = {
5433 .servicepath = servicepath,
5435 .match_status = NT_STATUS_OK
5440 state.file_existed = VALID_STAT(fname->st);
5441 if (state.file_existed) {
5442 state.id = vfs_file_id_from_sbuf(conn, &fname->st);
5445 status = leases_db_parse(&sconn->client->global->client_guid,
5446 lease_key, lease_match_parser, &state);
5447 if (!NT_STATUS_IS_OK(status)) {
5449 * Not found or error means okay: We can make the lease pass
5451 return NT_STATUS_OK;
5453 if (!NT_STATUS_EQUAL(state.match_status, NT_STATUS_OPLOCK_NOT_GRANTED)) {
5455 * Anything but NT_STATUS_OPLOCK_NOT_GRANTED, let the caller
5458 return state.match_status;
5461 /* We have to break all existing leases. */
5462 for (i = 0; i < state.num_file_ids; i++) {
5463 struct lease_match_break_state break_state = {
5464 .msg_ctx = conn->sconn->msg_ctx,
5465 .lease_key = lease_key,
5467 struct share_mode_lock *lck;
5470 if (file_id_equal(&state.ids[i], &state.id)) {
5471 /* Don't need to break our own file. */
5475 break_state.id = state.ids[i];
5477 lck = get_existing_share_mode_lock(
5478 talloc_tos(), break_state.id);
5480 /* Race condition - file already closed. */
5484 ok = share_mode_forall_leases(
5485 lck, lease_match_break_fn, &break_state);
5487 DBG_DEBUG("share_mode_forall_leases failed\n");
5493 if (break_state.found_lease) {
5494 *p_version = break_state.version;
5495 *p_epoch = break_state.epoch;
5499 * Ensure we don't grant anything more so we
5502 return NT_STATUS_OPLOCK_NOT_GRANTED;
5506 * Wrapper around open_file_ntcreate and open_directory
5509 static NTSTATUS create_file_unixpath(connection_struct *conn,
5510 struct smb_request *req,
5511 struct smb_filename *smb_fname,
5512 uint32_t access_mask,
5513 uint32_t share_access,
5514 uint32_t create_disposition,
5515 uint32_t create_options,
5516 uint32_t file_attributes,
5517 uint32_t oplock_request,
5518 const struct smb2_lease *lease,
5519 uint64_t allocation_size,
5520 uint32_t private_flags,
5521 struct security_descriptor *sd,
5522 struct ea_list *ea_list,
5524 files_struct **result,
5527 struct smb2_lease none_lease;
5528 int info = FILE_WAS_OPENED;
5529 files_struct *base_fsp = NULL;
5530 files_struct *fsp = NULL;
5533 struct smb_filename *parent_dir_fname = NULL;
5534 struct smb_filename *smb_fname_atname = NULL;
5536 DBG_DEBUG("create_file_unixpath: access_mask = 0x%x "
5537 "file_attributes = 0x%x, share_access = 0x%x, "
5538 "create_disposition = 0x%x create_options = 0x%x "
5539 "oplock_request = 0x%x private_flags = 0x%x "
5540 "ea_list = %p, sd = %p, "
5542 (unsigned int)access_mask,
5543 (unsigned int)file_attributes,
5544 (unsigned int)share_access,
5545 (unsigned int)create_disposition,
5546 (unsigned int)create_options,
5547 (unsigned int)oplock_request,
5548 (unsigned int)private_flags,
5549 ea_list, sd, smb_fname_str_dbg(smb_fname));
5551 if (create_options & FILE_OPEN_BY_FILE_ID) {
5552 status = NT_STATUS_NOT_SUPPORTED;
5556 if (create_options & NTCREATEX_OPTIONS_INVALID_PARAM_MASK) {
5557 status = NT_STATUS_INVALID_PARAMETER;
5562 oplock_request |= INTERNAL_OPEN_ONLY;
5565 if (lease != NULL) {
5566 uint16_t epoch = lease->lease_epoch;
5567 uint16_t version = lease->lease_version;
5570 DBG_WARNING("Got lease on internal open\n");
5571 status = NT_STATUS_INTERNAL_ERROR;
5575 status = lease_match(conn,
5582 if (NT_STATUS_EQUAL(status, NT_STATUS_OPLOCK_NOT_GRANTED)) {
5583 /* Dynamic share file. No leases and update epoch... */
5584 none_lease = *lease;
5585 none_lease.lease_state = SMB2_LEASE_NONE;
5586 none_lease.lease_epoch = epoch;
5587 none_lease.lease_version = version;
5588 lease = &none_lease;
5589 } else if (!NT_STATUS_IS_OK(status)) {
5594 if ((conn->fs_capabilities & FILE_NAMED_STREAMS)
5595 && (access_mask & DELETE_ACCESS)
5596 && !is_ntfs_stream_smb_fname(smb_fname)) {
5598 * We can't open a file with DELETE access if any of the
5599 * streams is open without FILE_SHARE_DELETE
5601 status = open_streams_for_delete(conn, smb_fname);
5603 if (!NT_STATUS_IS_OK(status)) {
5608 if (access_mask & SEC_FLAG_SYSTEM_SECURITY) {
5611 ok = security_token_has_privilege(get_current_nttok(conn),
5614 DBG_DEBUG("open on %s failed - "
5615 "SEC_FLAG_SYSTEM_SECURITY denied.\n",
5616 smb_fname_str_dbg(smb_fname));
5617 status = NT_STATUS_PRIVILEGE_NOT_HELD;
5621 if (conn->sconn->using_smb2 &&
5622 (access_mask == SEC_FLAG_SYSTEM_SECURITY))
5625 * No other bits set. Windows SMB2 refuses this.
5626 * See smbtorture3 SMB2-SACL test.
5628 * Note this is an SMB2-only behavior,
5629 * smbtorture3 SMB1-SYSTEM-SECURITY already tests
5630 * that SMB1 allows this.
5632 status = NT_STATUS_ACCESS_DENIED;
5638 * Files or directories can't be opened DELETE_ON_CLOSE without
5640 * BUG: https://bugzilla.samba.org/show_bug.cgi?id=13358
5642 if (create_options & FILE_DELETE_ON_CLOSE) {
5643 if ((access_mask & DELETE_ACCESS) == 0) {
5644 status = NT_STATUS_INVALID_PARAMETER;
5649 if ((conn->fs_capabilities & FILE_NAMED_STREAMS)
5650 && is_ntfs_stream_smb_fname(smb_fname))
5652 uint32_t base_create_disposition;
5653 struct smb_filename *smb_fname_base = NULL;
5654 uint32_t base_privflags;
5656 if (create_options & FILE_DIRECTORY_FILE) {
5657 status = NT_STATUS_NOT_A_DIRECTORY;
5661 switch (create_disposition) {
5663 base_create_disposition = FILE_OPEN;
5666 base_create_disposition = FILE_OPEN_IF;
5670 /* Create an smb_filename with stream_name == NULL. */
5671 smb_fname_base = synthetic_smb_fname(talloc_tos(),
5672 smb_fname->base_name,
5677 if (smb_fname_base == NULL) {
5678 status = NT_STATUS_NO_MEMORY;
5683 * We may be creating the basefile as part of creating the
5684 * stream, so it's legal if the basefile doesn't exist at this
5685 * point, the create_file_unixpath() below will create it. But
5686 * if the basefile exists we want a handle so we can fstat() it.
5689 ret = vfs_stat(conn, smb_fname_base);
5690 if (ret == -1 && errno != ENOENT) {
5691 status = map_nt_error_from_unix(errno);
5692 TALLOC_FREE(smb_fname_base);
5696 status = openat_pathref_fsp(conn->cwd_fsp,
5698 if (!NT_STATUS_IS_OK(status)) {
5699 DBG_ERR("open_smb_fname_fsp [%s] failed: %s\n",
5700 smb_fname_str_dbg(smb_fname_base),
5702 TALLOC_FREE(smb_fname_base);
5707 * https://bugzilla.samba.org/show_bug.cgi?id=10229
5708 * We need to check if the requested access mask
5709 * could be used to open the underlying file (if
5710 * it existed), as we're passing in zero for the
5711 * access mask to the base filename.
5713 status = check_base_file_access(smb_fname_base->fsp,
5716 if (!NT_STATUS_IS_OK(status)) {
5717 DEBUG(10, ("Permission check "
5718 "for base %s failed: "
5719 "%s\n", smb_fname->base_name,
5720 nt_errstr(status)));
5721 TALLOC_FREE(smb_fname_base);
5726 base_privflags = NTCREATEX_FLAG_STREAM_BASEOPEN;
5728 /* Open the base file. */
5729 status = create_file_unixpath(conn,
5735 | FILE_SHARE_DELETE,
5736 base_create_disposition,
5747 TALLOC_FREE(smb_fname_base);
5749 if (!NT_STATUS_IS_OK(status)) {
5750 DEBUG(10, ("create_file_unixpath for base %s failed: "
5751 "%s\n", smb_fname->base_name,
5752 nt_errstr(status)));
5758 * Now either reuse smb_fname->fsp or allocate a new fsp if
5759 * smb_fname->fsp is NULL. The latter will be the case when processing a
5760 * request to create a file that doesn't exist.
5762 if (smb_fname->fsp != NULL) {
5763 bool need_fsp_unlink = true;
5766 * This is really subtle. If someone passes in an smb_fname
5767 * where smb_fname actually is taken from fsp->fsp_name, then
5768 * the lifetime of these objects is meant to be the same.
5770 * This is commonly the case from an SMB1 path-based call,
5771 * (call_trans2qfilepathinfo) where we use the pathref fsp
5772 * (smb_fname->fsp) as the handle. In this case we must not
5773 * unlink smb_fname->fsp from it's owner.
5775 * The asserts below:
5777 * SMB_ASSERT(fsp->fsp_name->fsp != NULL);
5778 * SMB_ASSERT(fsp->fsp_name->fsp == fsp);
5780 * ensure the required invarients are met.
5782 if (smb_fname->fsp->fsp_name == smb_fname) {
5783 need_fsp_unlink = false;
5786 fsp = smb_fname->fsp;
5788 if (need_fsp_unlink) {
5790 * Unlink the fsp from the smb_fname so the fsp is not
5791 * autoclosed by the smb_fname pathref fsp talloc
5794 smb_fname_fsp_unlink(smb_fname);
5797 status = fsp_bind_smb(fsp, req);
5798 if (!NT_STATUS_IS_OK(status)) {
5802 if (fsp->base_fsp != NULL) {
5803 struct files_struct *tmp_base_fsp = fsp->base_fsp;
5805 fsp_set_base_fsp(fsp, NULL);
5807 fd_close(tmp_base_fsp);
5808 file_free(NULL, tmp_base_fsp);
5814 status = file_new(req, conn, &fsp);
5815 if(!NT_STATUS_IS_OK(status)) {
5819 status = fsp_set_smb_fname(fsp, smb_fname);
5820 if (!NT_STATUS_IS_OK(status)) {
5825 SMB_ASSERT(fsp->fsp_name->fsp != NULL);
5826 SMB_ASSERT(fsp->fsp_name->fsp == fsp);
5830 * We're opening the stream element of a
5831 * base_fsp we already opened. Set up the
5834 fsp_set_base_fsp(fsp, base_fsp);
5838 * Get a pathref on the parent. We can re-use this
5839 * for multiple calls to check parent ACLs etc. to
5840 * avoid pathname calls.
5842 status = parent_pathref(talloc_tos(),
5847 if (!NT_STATUS_IS_OK(status)) {
5852 * If it's a request for a directory open, deal with it separately.
5855 if (create_options & FILE_DIRECTORY_FILE) {
5857 if (create_options & FILE_NON_DIRECTORY_FILE) {
5858 status = NT_STATUS_INVALID_PARAMETER;
5862 /* Can't open a temp directory. IFS kit test. */
5863 if (!(file_attributes & FILE_FLAG_POSIX_SEMANTICS) &&
5864 (file_attributes & FILE_ATTRIBUTE_TEMPORARY)) {
5865 status = NT_STATUS_INVALID_PARAMETER;
5870 * We will get a create directory here if the Win32
5871 * app specified a security descriptor in the
5872 * CreateDirectory() call.
5876 status = open_directory(conn,
5890 * Ordinary file case.
5893 if (allocation_size) {
5894 fsp->initial_allocation_size = smb_roundup(fsp->conn,
5898 status = open_file_ntcreate(conn,
5912 if (NT_STATUS_EQUAL(status, NT_STATUS_FILE_IS_A_DIRECTORY)) {
5914 /* A stream open never opens a directory */
5917 status = NT_STATUS_FILE_IS_A_DIRECTORY;
5922 * Fail the open if it was explicitly a non-directory
5926 if (create_options & FILE_NON_DIRECTORY_FILE) {
5927 status = NT_STATUS_FILE_IS_A_DIRECTORY;
5932 status = open_directory(conn,
5946 if (!NT_STATUS_IS_OK(status)) {
5950 fsp->fsp_flags.is_fsa = true;
5952 if ((ea_list != NULL) &&
5953 ((info == FILE_WAS_CREATED) || (info == FILE_WAS_OVERWRITTEN))) {
5954 status = set_ea(conn, fsp, ea_list);
5955 if (!NT_STATUS_IS_OK(status)) {
5960 if (!fsp->fsp_flags.is_directory &&
5961 S_ISDIR(fsp->fsp_name->st.st_ex_mode))
5963 status = NT_STATUS_ACCESS_DENIED;
5967 /* Save the requested allocation size. */
5968 if ((info == FILE_WAS_CREATED) || (info == FILE_WAS_OVERWRITTEN)) {
5969 if ((allocation_size > (uint64_t)fsp->fsp_name->st.st_ex_size)
5970 && !(fsp->fsp_flags.is_directory))
5972 fsp->initial_allocation_size = smb_roundup(
5973 fsp->conn, allocation_size);
5974 if (vfs_allocate_file_space(
5975 fsp, fsp->initial_allocation_size) == -1) {
5976 status = NT_STATUS_DISK_FULL;
5980 fsp->initial_allocation_size = smb_roundup(
5981 fsp->conn, (uint64_t)fsp->fsp_name->st.st_ex_size);
5984 fsp->initial_allocation_size = 0;
5987 if ((info == FILE_WAS_CREATED) && lp_nt_acl_support(SNUM(conn)) &&
5988 fsp->base_fsp == NULL) {
5991 * According to the MS documentation, the only time the security
5992 * descriptor is applied to the opened file is iff we *created* the
5993 * file; an existing file stays the same.
5995 * Also, it seems (from observation) that you can open the file with
5996 * any access mask but you can still write the sd. We need to override
5997 * the granted access before we call set_sd
5998 * Patch for bug #2242 from Tom Lackemann <cessnatomny@yahoo.com>.
6001 uint32_t sec_info_sent;
6002 uint32_t saved_access_mask = fsp->access_mask;
6004 sec_info_sent = get_sec_info(sd);
6006 fsp->access_mask = FILE_GENERIC_ALL;
6008 if (sec_info_sent & (SECINFO_OWNER|
6012 status = set_sd(fsp, sd, sec_info_sent);
6015 fsp->access_mask = saved_access_mask;
6017 if (!NT_STATUS_IS_OK(status)) {
6020 } else if (lp_inherit_acls(SNUM(conn))) {
6021 /* Inherit from parent. Errors here are not fatal. */
6022 status = inherit_new_acl(parent_dir_fname, fsp);
6023 if (!NT_STATUS_IS_OK(status)) {
6024 DEBUG(10,("inherit_new_acl: failed for %s with %s\n",
6026 nt_errstr(status) ));
6031 if ((conn->fs_capabilities & FILE_FILE_COMPRESSION)
6032 && (create_options & FILE_NO_COMPRESSION)
6033 && (info == FILE_WAS_CREATED)) {
6034 status = SMB_VFS_SET_COMPRESSION(conn, fsp, fsp,
6035 COMPRESSION_FORMAT_NONE);
6036 if (!NT_STATUS_IS_OK(status)) {
6037 DEBUG(1, ("failed to disable compression: %s\n",
6038 nt_errstr(status)));
6042 DEBUG(10, ("create_file_unixpath: info=%d\n", info));
6045 if (pinfo != NULL) {
6049 smb_fname->st = fsp->fsp_name->st;
6051 TALLOC_FREE(parent_dir_fname);
6053 return NT_STATUS_OK;
6056 DEBUG(10, ("create_file_unixpath: %s\n", nt_errstr(status)));
6060 * The close_file below will close
6064 close_file(req, fsp, ERROR_CLOSE);
6067 if (base_fsp != NULL) {
6068 close_file(req, base_fsp, ERROR_CLOSE);
6072 TALLOC_FREE(parent_dir_fname);
6077 NTSTATUS create_file_default(connection_struct *conn,
6078 struct smb_request *req,
6079 struct smb_filename *smb_fname,
6080 uint32_t access_mask,
6081 uint32_t share_access,
6082 uint32_t create_disposition,
6083 uint32_t create_options,
6084 uint32_t file_attributes,
6085 uint32_t oplock_request,
6086 const struct smb2_lease *lease,
6087 uint64_t allocation_size,
6088 uint32_t private_flags,
6089 struct security_descriptor *sd,
6090 struct ea_list *ea_list,
6091 files_struct **result,
6093 const struct smb2_create_blobs *in_context_blobs,
6094 struct smb2_create_blobs *out_context_blobs)
6096 int info = FILE_WAS_OPENED;
6097 files_struct *fsp = NULL;
6099 bool stream_name = false;
6100 struct smb2_create_blob *posx = NULL;
6102 DBG_DEBUG("create_file: access_mask = 0x%x "
6103 "file_attributes = 0x%x, share_access = 0x%x, "
6104 "create_disposition = 0x%x create_options = 0x%x "
6105 "oplock_request = 0x%x "
6106 "private_flags = 0x%x "
6107 "ea_list = %p, sd = %p, "
6109 (unsigned int)access_mask,
6110 (unsigned int)file_attributes,
6111 (unsigned int)share_access,
6112 (unsigned int)create_disposition,
6113 (unsigned int)create_options,
6114 (unsigned int)oplock_request,
6115 (unsigned int)private_flags,
6118 smb_fname_str_dbg(smb_fname));
6122 * Remember the absolute time of the original request
6123 * with this mid. We'll use it later to see if this
6126 get_deferred_open_message_state(req, &req->request_time, NULL);
6130 * Check to see if this is a mac fork of some kind.
6133 stream_name = is_ntfs_stream_smb_fname(smb_fname);
6135 enum FAKE_FILE_TYPE fake_file_type;
6137 fake_file_type = is_fake_file(smb_fname);
6139 if (req != NULL && fake_file_type != FAKE_FILE_TYPE_NONE) {
6142 * Here we go! support for changing the disk quotas
6145 * We need to fake up to open this MAGIC QUOTA file
6146 * and return a valid FID.
6148 * w2k close this file directly after openening xp
6149 * also tries a QUERY_FILE_INFO on the file and then
6152 status = open_fake_file(req, conn, req->vuid,
6153 fake_file_type, smb_fname,
6155 if (!NT_STATUS_IS_OK(status)) {
6159 ZERO_STRUCT(smb_fname->st);
6163 if (!(conn->fs_capabilities & FILE_NAMED_STREAMS)) {
6164 status = NT_STATUS_OBJECT_NAME_NOT_FOUND;
6169 if (is_ntfs_default_stream_smb_fname(smb_fname)) {
6171 smb_fname->stream_name = NULL;
6172 /* We have to handle this error here. */
6173 if (create_options & FILE_DIRECTORY_FILE) {
6174 status = NT_STATUS_NOT_A_DIRECTORY;
6177 ret = vfs_stat(conn, smb_fname);
6178 if (ret == 0 && VALID_STAT_OF_DIR(smb_fname->st)) {
6179 status = NT_STATUS_FILE_IS_A_DIRECTORY;
6184 posx = smb2_create_blob_find(
6185 in_context_blobs, SMB2_CREATE_TAG_POSIX);
6187 uint32_t wire_mode_bits = 0;
6188 mode_t mode_bits = 0;
6189 SMB_STRUCT_STAT sbuf = { 0 };
6190 enum perm_type ptype =
6191 (create_options & FILE_DIRECTORY_FILE) ?
6192 PERM_NEW_DIR : PERM_NEW_FILE;
6194 if (posx->data.length != 4) {
6195 status = NT_STATUS_INVALID_PARAMETER;
6199 wire_mode_bits = IVAL(posx->data.data, 0);
6200 status = unix_perms_from_wire(
6201 conn, &sbuf, wire_mode_bits, ptype, &mode_bits);
6202 if (!NT_STATUS_IS_OK(status)) {
6206 * Remove type info from mode, leaving only the
6207 * permissions and setuid/gid bits.
6209 mode_bits &= ~S_IFMT;
6211 file_attributes = (FILE_FLAG_POSIX_SEMANTICS | mode_bits);
6214 status = create_file_unixpath(conn,
6230 if (!NT_STATUS_IS_OK(status)) {
6235 DEBUG(10, ("create_file: info=%d\n", info));
6238 if (pinfo != NULL) {
6241 return NT_STATUS_OK;
6244 DEBUG(10, ("create_file: %s\n", nt_errstr(status)));
6247 close_file(req, fsp, ERROR_CLOSE);