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 "smbd/smbd.h"
29 #include "smbd/globals.h"
30 #include "fake_file.h"
31 #include "../libcli/security/security.h"
32 #include "../librpc/gen_ndr/ndr_security.h"
33 #include "../librpc/gen_ndr/ndr_open_files.h"
34 #include "../librpc/gen_ndr/idmap.h"
35 #include "../librpc/gen_ndr/ioctl.h"
36 #include "passdb/lookup_sid.h"
40 #include "source3/lib/dbwrap/dbwrap_watch.h"
41 #include "locking/leases_db.h"
42 #include "librpc/gen_ndr/ndr_leases_db.h"
43 #include "lib/util/time_basic.h"
45 extern const struct generic_mapping file_generic_mapping;
47 struct deferred_open_record {
48 struct smbXsrv_connection *xconn;
54 * Timer for async opens, needed because they don't use a watch on
55 * a locking.tdb record. This is currently only used for real async
56 * opens and just terminates smbd if the async open times out.
58 struct tevent_timer *te;
61 * For the samba kernel oplock case we use both a timeout and
62 * a watch on locking.tdb. This way in case it's smbd holding
63 * the kernel oplock we get directly notified for the retry
64 * once the kernel oplock is properly broken. Store the req
65 * here so that it can be timely discarded once the timer
68 struct tevent_req *watch_req;
71 /****************************************************************************
72 If the requester wanted DELETE_ACCESS and was rejected because
73 the file ACL didn't include DELETE_ACCESS, see if the parent ACL
75 ****************************************************************************/
77 static bool parent_override_delete(connection_struct *conn,
78 const struct smb_filename *smb_fname,
80 uint32_t rejected_mask)
82 if ((access_mask & DELETE_ACCESS) &&
83 (rejected_mask & DELETE_ACCESS) &&
84 can_delete_file_in_directory(conn,
93 /****************************************************************************
94 Check if we have open rights.
95 ****************************************************************************/
97 NTSTATUS smbd_check_access_rights(struct connection_struct *conn,
98 struct files_struct *dirfsp,
99 const struct smb_filename *smb_fname,
101 uint32_t access_mask)
103 /* Check if we have rights to open. */
105 struct security_descriptor *sd = NULL;
106 uint32_t rejected_share_access;
107 uint32_t rejected_mask = access_mask;
108 uint32_t do_not_check_mask = 0;
110 SMB_ASSERT(dirfsp == conn->cwd_fsp);
112 rejected_share_access = access_mask & ~(conn->share_access);
114 if (rejected_share_access) {
115 DEBUG(10, ("smbd_check_access_rights: rejected share access 0x%x "
117 (unsigned int)access_mask,
118 smb_fname_str_dbg(smb_fname),
119 (unsigned int)rejected_share_access ));
120 return NT_STATUS_ACCESS_DENIED;
123 if (!use_privs && get_current_uid(conn) == (uid_t)0) {
124 /* I'm sorry sir, I didn't know you were root... */
125 DEBUG(10,("smbd_check_access_rights: root override "
126 "on %s. Granting 0x%x\n",
127 smb_fname_str_dbg(smb_fname),
128 (unsigned int)access_mask ));
132 if ((access_mask & DELETE_ACCESS) && !lp_acl_check_permissions(SNUM(conn))) {
133 DEBUG(10,("smbd_check_access_rights: not checking ACL "
134 "on DELETE_ACCESS on file %s. Granting 0x%x\n",
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)) {
143 /* We can always delete a symlink. */
144 DEBUG(10,("smbd_check_access_rights: not checking ACL "
145 "on DELETE_ACCESS on symlink %s.\n",
146 smb_fname_str_dbg(smb_fname) ));
150 status = SMB_VFS_GET_NT_ACL_AT(conn,
159 if (!NT_STATUS_IS_OK(status)) {
160 DEBUG(10, ("smbd_check_access_rights: Could not get acl "
162 smb_fname_str_dbg(smb_fname),
165 if (NT_STATUS_EQUAL(status, NT_STATUS_ACCESS_DENIED)) {
173 * If we can access the path to this file, by
174 * default we have FILE_READ_ATTRIBUTES from the
175 * containing directory. See the section:
176 * "Algorithm to Check Access to an Existing File"
179 * se_file_access_check() also takes care of
180 * owner WRITE_DAC and READ_CONTROL.
182 do_not_check_mask = FILE_READ_ATTRIBUTES;
185 * Samba 3.6 and earlier granted execute access even
186 * if the ACL did not contain execute rights.
187 * Samba 4.0 is more correct and checks it.
188 * The compatibilty mode allows one to skip this check
189 * to smoothen upgrades.
191 if (lp_acl_allow_execute_always(SNUM(conn))) {
192 do_not_check_mask |= FILE_EXECUTE;
195 status = se_file_access_check(sd,
196 get_current_nttok(conn),
198 (access_mask & ~do_not_check_mask),
201 DEBUG(10,("smbd_check_access_rights: file %s requesting "
202 "0x%x returning 0x%x (%s)\n",
203 smb_fname_str_dbg(smb_fname),
204 (unsigned int)access_mask,
205 (unsigned int)rejected_mask,
206 nt_errstr(status) ));
208 if (!NT_STATUS_IS_OK(status)) {
209 if (DEBUGLEVEL >= 10) {
210 DEBUG(10,("smbd_check_access_rights: acl for %s is:\n",
211 smb_fname_str_dbg(smb_fname) ));
212 NDR_PRINT_DEBUG(security_descriptor, sd);
218 if (NT_STATUS_IS_OK(status) ||
219 !NT_STATUS_EQUAL(status, NT_STATUS_ACCESS_DENIED)) {
223 /* Here we know status == NT_STATUS_ACCESS_DENIED. */
227 if ((access_mask & FILE_WRITE_ATTRIBUTES) &&
228 (rejected_mask & FILE_WRITE_ATTRIBUTES) &&
229 !lp_store_dos_attributes(SNUM(conn)) &&
230 (lp_map_readonly(SNUM(conn)) ||
231 lp_map_archive(SNUM(conn)) ||
232 lp_map_hidden(SNUM(conn)) ||
233 lp_map_system(SNUM(conn)))) {
234 rejected_mask &= ~FILE_WRITE_ATTRIBUTES;
236 DEBUG(10,("smbd_check_access_rights: "
238 "FILE_WRITE_ATTRIBUTES "
240 smb_fname_str_dbg(smb_fname)));
243 if (parent_override_delete(conn,
247 /* Were we trying to do an open
248 * for delete and didn't get DELETE
249 * access (only) ? Check if the
250 * directory allows DELETE_CHILD.
252 * http://blogs.msdn.com/oldnewthing/archive/2004/06/04/148426.aspx
255 rejected_mask &= ~DELETE_ACCESS;
257 DEBUG(10,("smbd_check_access_rights: "
261 smb_fname_str_dbg(smb_fname)));
264 if (rejected_mask != 0) {
265 return NT_STATUS_ACCESS_DENIED;
270 NTSTATUS check_parent_access(struct connection_struct *conn,
271 struct files_struct *dirfsp,
272 struct smb_filename *smb_fname,
273 uint32_t access_mask)
276 struct security_descriptor *parent_sd = NULL;
277 uint32_t access_granted = 0;
278 struct smb_filename *parent_dir = NULL;
279 struct share_mode_lock *lck = NULL;
280 struct file_id id = {0};
282 bool delete_on_close_set;
284 TALLOC_CTX *frame = talloc_stackframe();
288 * NB. When dirfsp != conn->cwd_fsp, we must
289 * change parent_dir to be "." for the name here.
292 SMB_ASSERT(dirfsp == conn->cwd_fsp);
294 ok = parent_smb_fname(frame, smb_fname, &parent_dir, NULL);
296 status = NT_STATUS_NO_MEMORY;
300 if (get_current_uid(conn) == (uid_t)0) {
301 /* I'm sorry sir, I didn't know you were root... */
302 DEBUG(10,("check_parent_access: root override "
303 "on %s. Granting 0x%x\n",
304 smb_fname_str_dbg(smb_fname),
305 (unsigned int)access_mask ));
306 status = NT_STATUS_OK;
310 status = SMB_VFS_GET_NT_ACL_AT(conn,
317 if (!NT_STATUS_IS_OK(status)) {
318 DBG_INFO("SMB_VFS_GET_NT_ACL_AT failed for "
319 "%s with error %s\n",
320 smb_fname_str_dbg(parent_dir),
326 * If we can access the path to this file, by
327 * default we have FILE_READ_ATTRIBUTES from the
328 * containing directory. See the section:
329 * "Algorithm to Check Access to an Existing File"
332 * se_file_access_check() also takes care of
333 * owner WRITE_DAC and READ_CONTROL.
335 status = se_file_access_check(parent_sd,
336 get_current_nttok(conn),
338 (access_mask & ~FILE_READ_ATTRIBUTES),
340 if(!NT_STATUS_IS_OK(status)) {
341 DEBUG(5,("check_parent_access: access check "
342 "on directory %s for "
343 "path %s for mask 0x%x returned (0x%x) %s\n",
344 smb_fname_str_dbg(parent_dir),
345 smb_fname->base_name,
348 nt_errstr(status) ));
352 if (!(access_mask & (SEC_DIR_ADD_FILE | SEC_DIR_ADD_SUBDIR))) {
353 status = NT_STATUS_OK;
356 if (!lp_check_parent_directory_delete_on_close(SNUM(conn))) {
357 status = NT_STATUS_OK;
361 /* Check if the directory has delete-on-close set */
362 ret = SMB_VFS_STAT(conn, parent_dir);
364 status = map_nt_error_from_unix(errno);
368 id = SMB_VFS_FILE_ID_CREATE(conn, &parent_dir->st);
370 status = file_name_hash(conn, parent_dir->base_name, &name_hash);
371 if (!NT_STATUS_IS_OK(status)) {
375 lck = get_existing_share_mode_lock(frame, id);
377 status = NT_STATUS_OK;
381 delete_on_close_set = is_delete_on_close_set(lck, name_hash);
382 if (delete_on_close_set) {
383 status = NT_STATUS_DELETE_PENDING;
387 status = NT_STATUS_OK;
394 /****************************************************************************
395 Ensure when opening a base file for a stream open that we have permissions
396 to do so given the access mask on the base file.
397 ****************************************************************************/
399 static NTSTATUS check_base_file_access(struct connection_struct *conn,
400 struct smb_filename *smb_fname,
401 uint32_t access_mask)
405 status = smbd_calculate_access_mask(conn,
411 if (!NT_STATUS_IS_OK(status)) {
412 DEBUG(10, ("smbd_calculate_access_mask "
413 "on file %s returned %s\n",
414 smb_fname_str_dbg(smb_fname),
419 if (access_mask & (FILE_WRITE_DATA|FILE_APPEND_DATA)) {
421 if (!CAN_WRITE(conn)) {
422 return NT_STATUS_ACCESS_DENIED;
424 dosattrs = dos_mode(conn, smb_fname);
425 if (IS_DOS_READONLY(dosattrs)) {
426 return NT_STATUS_ACCESS_DENIED;
430 return smbd_check_access_rights(conn,
437 /****************************************************************************
438 Handle differing symlink errno's
439 ****************************************************************************/
441 static int link_errno_convert(int err)
443 #if defined(ENOTSUP) && defined(OSF1)
444 /* handle special Tru64 errno */
445 if (err == ENOTSUP) {
450 /* fix broken NetBSD errno */
455 /* fix broken FreeBSD errno */
462 static int non_widelink_open(files_struct *fsp,
463 struct smb_filename *smb_fname,
466 unsigned int link_depth);
468 /****************************************************************************
469 Follow a symlink in userspace.
470 ****************************************************************************/
472 static int process_symlink_open(struct connection_struct *conn,
474 struct smb_filename *smb_fname,
477 unsigned int link_depth)
479 const char *conn_rootdir = NULL;
480 struct smb_filename conn_rootdir_fname;
482 char *link_target = NULL;
484 struct smb_filename *oldwd_fname = NULL;
485 size_t rootdir_len = 0;
486 struct smb_filename *resolved_fname = NULL;
487 char *resolved_name = NULL;
488 bool matched = false;
491 conn_rootdir = SMB_VFS_CONNECTPATH(conn, smb_fname);
492 if (conn_rootdir == NULL) {
496 conn_rootdir_fname = (struct smb_filename) {
497 .base_name = discard_const_p(char, conn_rootdir),
501 * Ensure we don't get stuck in a symlink loop.
504 if (link_depth >= 20) {
509 /* Allocate space for the link target. */
510 link_target = talloc_array(talloc_tos(), char, PATH_MAX);
511 if (link_target == NULL) {
517 * Read the link target. We do this just to verify that smb_fname indeed
518 * points at a symbolic link and return the SMB_VFS_READLINKAT() errno
519 * and failure in case smb_fname is NOT a symlink.
521 * The caller needs this piece of information to distinguish two cases
522 * where open() fails with errno=ENOTDIR, cf the comment in
523 * non_widelink_open().
525 * We rely on SMB_VFS_REALPATH() to resolve the path including the
526 * symlink. Once we have SMB_VFS_STATX() or something similar in our VFS
527 * we may want to use that instead of SMB_VFS_READLINKAT().
529 link_len = SMB_VFS_READLINKAT(conn,
534 if (link_len == -1) {
538 /* Convert to an absolute path. */
539 resolved_fname = SMB_VFS_REALPATH(conn, talloc_tos(), smb_fname);
540 if (resolved_fname == NULL) {
543 resolved_name = resolved_fname->base_name;
546 * We know conn_rootdir starts with '/' and
547 * does not end in '/'. FIXME ! Should we
550 rootdir_len = strlen(conn_rootdir_fname.base_name);
552 matched = (strncmp(conn_rootdir_fname.base_name,
561 * Turn into a path relative to the share root.
563 if (resolved_name[rootdir_len] == '\0') {
564 /* Link to the root of the share. */
565 TALLOC_FREE(smb_fname->base_name);
566 smb_fname->base_name = talloc_strdup(smb_fname, ".");
567 } else if (resolved_name[rootdir_len] == '/') {
568 TALLOC_FREE(smb_fname->base_name);
569 smb_fname->base_name = talloc_strdup(smb_fname,
570 &resolved_name[rootdir_len+1]);
576 if (smb_fname->base_name == NULL) {
581 oldwd_fname = vfs_GetWd(talloc_tos(), conn);
582 if (oldwd_fname == NULL) {
586 /* Ensure we operate from the root of the share. */
587 if (vfs_ChDir(conn, &conn_rootdir_fname) == -1) {
591 /* And do it all again.. */
592 fd = non_widelink_open(fsp,
603 TALLOC_FREE(resolved_fname);
604 TALLOC_FREE(link_target);
605 if (oldwd_fname != NULL) {
606 int ret = vfs_ChDir(conn, oldwd_fname);
608 smb_panic("unable to get back to old directory\n");
610 TALLOC_FREE(oldwd_fname);
612 if (saved_errno != 0) {
618 /****************************************************************************
620 ****************************************************************************/
622 static int non_widelink_open(files_struct *fsp,
623 struct smb_filename *smb_fname,
626 unsigned int link_depth)
628 struct connection_struct *conn = fsp->conn;
631 struct smb_filename *tmp_fsp_name = fsp->fsp_name;
632 struct smb_filename *smb_fname_rel = NULL;
634 struct smb_filename *oldwd_fname = NULL;
635 struct smb_filename *parent_dir_fname = NULL;
636 struct files_struct *cwdfsp = NULL;
639 if (fsp->fsp_flags.is_directory) {
640 parent_dir_fname = cp_smb_filename(talloc_tos(), smb_fname);
641 if (parent_dir_fname == NULL) {
646 smb_fname_rel = synthetic_smb_fname(parent_dir_fname,
648 smb_fname->stream_name,
652 if (smb_fname_rel == NULL) {
657 ok = parent_smb_fname(talloc_tos(),
667 oldwd_fname = vfs_GetWd(talloc_tos(), conn);
668 if (oldwd_fname == NULL) {
672 /* Pin parent directory in place. */
673 if (vfs_ChDir(conn, parent_dir_fname) == -1) {
677 /* Ensure the relative path is below the share. */
678 status = check_reduced_name(conn, parent_dir_fname, smb_fname_rel);
679 if (!NT_STATUS_IS_OK(status)) {
680 saved_errno = map_errno_from_nt_status(status);
684 status = vfs_at_fspcwd(talloc_tos(),
687 if (!NT_STATUS_IS_OK(status)) {
688 saved_errno = map_errno_from_nt_status(status);
694 fsp->fsp_name = smb_fname_rel;
696 fd = SMB_VFS_OPENAT(conn,
703 fsp->fsp_name = tmp_fsp_name;
706 saved_errno = link_errno_convert(errno);
708 * Trying to open a symlink to a directory with O_NOFOLLOW and
709 * O_DIRECTORY can return either of ELOOP and ENOTDIR. So
710 * ENOTDIR really means: might be a symlink, but we're not sure.
711 * In this case, we just assume there's a symlink. If we were
712 * wrong, process_symlink_open() will return EINVAL. We check
713 * this below, and fall back to returning the initial
716 * BUG: https://bugzilla.samba.org/show_bug.cgi?id=12860
718 if (saved_errno == ELOOP || saved_errno == ENOTDIR) {
719 if (fsp->fsp_name->flags & SMB_FILENAME_POSIX_PATH) {
720 /* Never follow symlinks on posix open. */
723 if (!lp_follow_symlinks(SNUM(conn))) {
724 /* Explicitly no symlinks. */
728 * We may have a symlink. Follow in userspace
729 * to ensure it's under the share definition.
731 fd = process_symlink_open(conn,
738 if (saved_errno == ENOTDIR &&
741 * O_DIRECTORY on neither a directory,
742 * nor a symlink. Just return
743 * saved_errno from initial open()
748 link_errno_convert(errno);
755 TALLOC_FREE(parent_dir_fname);
758 if (oldwd_fname != NULL) {
759 int ret = vfs_ChDir(conn, oldwd_fname);
761 smb_panic("unable to get back to old directory\n");
763 TALLOC_FREE(oldwd_fname);
765 if (saved_errno != 0) {
771 /****************************************************************************
772 fd support routines - attempt to do a dos_open.
773 ****************************************************************************/
775 NTSTATUS fd_open(files_struct *fsp,
779 struct connection_struct *conn = fsp->conn;
780 struct smb_filename *smb_fname = fsp->fsp_name;
781 NTSTATUS status = NT_STATUS_OK;
785 * Never follow symlinks on a POSIX client. The
786 * client should be doing this.
789 if ((fsp->posix_flags & FSP_POSIX_FLAGS_OPEN) || !lp_follow_symlinks(SNUM(conn))) {
794 * Only follow symlinks within a share
797 fd = non_widelink_open(fsp, smb_fname, flags, mode, 0);
799 int posix_errno = link_errno_convert(errno);
800 status = map_nt_error_from_unix(posix_errno);
801 if (errno == EMFILE) {
802 static time_t last_warned = 0L;
804 if (time((time_t *) NULL) > last_warned) {
805 DEBUG(0,("Too many open files, unable "
806 "to open more! smbd's max "
808 lp_max_open_files()));
809 last_warned = time((time_t *) NULL);
813 DBG_DEBUG("name %s, flags = 0%o mode = 0%o, fd = %d. %s\n",
814 smb_fname_str_dbg(smb_fname), flags, (int)mode,
815 fd, strerror(errno));
821 DBG_DEBUG("name %s, flags = 0%o mode = 0%o, fd = %d\n",
822 smb_fname_str_dbg(smb_fname), flags, (int)mode, fd);
827 /****************************************************************************
828 Close the file associated with a fsp.
829 ****************************************************************************/
831 NTSTATUS fd_close(files_struct *fsp)
835 if (fsp == fsp->conn->cwd_fsp) {
842 if (fsp->fh->fd == -1) {
844 * Either a directory where the dptr_CloseDir() already closed
845 * the fd or a stat open.
849 if (fsp->fh->ref_count > 1) {
850 return NT_STATUS_OK; /* Shared handle. Only close last reference. */
853 ret = SMB_VFS_CLOSE(fsp);
856 return map_nt_error_from_unix(errno);
861 /****************************************************************************
862 Change the ownership of a file to that of the parent directory.
863 Do this by fd if possible.
864 ****************************************************************************/
866 void change_file_owner_to_parent(connection_struct *conn,
867 struct smb_filename *smb_fname_parent,
872 ret = SMB_VFS_STAT(conn, smb_fname_parent);
874 DEBUG(0,("change_file_owner_to_parent: failed to stat parent "
875 "directory %s. Error was %s\n",
876 smb_fname_str_dbg(smb_fname_parent),
878 TALLOC_FREE(smb_fname_parent);
882 if (smb_fname_parent->st.st_ex_uid == fsp->fsp_name->st.st_ex_uid) {
883 /* Already this uid - no need to change. */
884 DEBUG(10,("change_file_owner_to_parent: file %s "
885 "is already owned by uid %d\n",
887 (int)fsp->fsp_name->st.st_ex_uid ));
888 TALLOC_FREE(smb_fname_parent);
893 ret = SMB_VFS_FCHOWN(fsp, smb_fname_parent->st.st_ex_uid, (gid_t)-1);
896 DEBUG(0,("change_file_owner_to_parent: failed to fchown "
897 "file %s to parent directory uid %u. Error "
898 "was %s\n", fsp_str_dbg(fsp),
899 (unsigned int)smb_fname_parent->st.st_ex_uid,
902 DEBUG(10,("change_file_owner_to_parent: changed new file %s to "
903 "parent directory uid %u.\n", fsp_str_dbg(fsp),
904 (unsigned int)smb_fname_parent->st.st_ex_uid));
905 /* Ensure the uid entry is updated. */
906 fsp->fsp_name->st.st_ex_uid = smb_fname_parent->st.st_ex_uid;
910 static NTSTATUS change_dir_owner_to_parent(connection_struct *conn,
911 struct smb_filename *smb_fname_parent,
912 struct smb_filename *smb_dname,
913 SMB_STRUCT_STAT *psbuf)
915 struct smb_filename *smb_fname_cwd = NULL;
916 struct smb_filename *saved_dir_fname = NULL;
917 TALLOC_CTX *ctx = talloc_tos();
918 NTSTATUS status = NT_STATUS_OK;
921 ret = SMB_VFS_STAT(conn, smb_fname_parent);
923 status = map_nt_error_from_unix(errno);
924 DEBUG(0,("change_dir_owner_to_parent: failed to stat parent "
925 "directory %s. Error was %s\n",
926 smb_fname_str_dbg(smb_fname_parent),
931 /* We've already done an lstat into psbuf, and we know it's a
932 directory. If we can cd into the directory and the dev/ino
933 are the same then we can safely chown without races as
934 we're locking the directory in place by being in it. This
935 should work on any UNIX (thanks tridge :-). JRA.
938 saved_dir_fname = vfs_GetWd(ctx,conn);
939 if (!saved_dir_fname) {
940 status = map_nt_error_from_unix(errno);
941 DEBUG(0,("change_dir_owner_to_parent: failed to get "
942 "current working directory. Error was %s\n",
947 /* Chdir into the new path. */
948 if (vfs_ChDir(conn, smb_dname) == -1) {
949 status = map_nt_error_from_unix(errno);
950 DEBUG(0,("change_dir_owner_to_parent: failed to change "
951 "current working directory to %s. Error "
952 "was %s\n", smb_dname->base_name, strerror(errno) ));
956 smb_fname_cwd = synthetic_smb_fname(ctx,
962 if (smb_fname_cwd == NULL) {
963 status = NT_STATUS_NO_MEMORY;
967 ret = SMB_VFS_STAT(conn, smb_fname_cwd);
969 status = map_nt_error_from_unix(errno);
970 DEBUG(0,("change_dir_owner_to_parent: failed to stat "
971 "directory '.' (%s) Error was %s\n",
972 smb_dname->base_name, strerror(errno)));
976 /* Ensure we're pointing at the same place. */
977 if (smb_fname_cwd->st.st_ex_dev != psbuf->st_ex_dev ||
978 smb_fname_cwd->st.st_ex_ino != psbuf->st_ex_ino) {
979 DEBUG(0,("change_dir_owner_to_parent: "
980 "device/inode on directory %s changed. "
981 "Refusing to chown !\n",
982 smb_dname->base_name ));
983 status = NT_STATUS_ACCESS_DENIED;
987 if (smb_fname_parent->st.st_ex_uid == smb_fname_cwd->st.st_ex_uid) {
988 /* Already this uid - no need to change. */
989 DEBUG(10,("change_dir_owner_to_parent: directory %s "
990 "is already owned by uid %d\n",
991 smb_dname->base_name,
992 (int)smb_fname_cwd->st.st_ex_uid ));
993 status = NT_STATUS_OK;
998 ret = SMB_VFS_LCHOWN(conn,
1000 smb_fname_parent->st.st_ex_uid,
1004 status = map_nt_error_from_unix(errno);
1005 DEBUG(10,("change_dir_owner_to_parent: failed to chown "
1006 "directory %s to parent directory uid %u. "
1008 smb_dname->base_name,
1009 (unsigned int)smb_fname_parent->st.st_ex_uid,
1012 DEBUG(10,("change_dir_owner_to_parent: changed ownership of new "
1013 "directory %s to parent directory uid %u.\n",
1014 smb_dname->base_name,
1015 (unsigned int)smb_fname_parent->st.st_ex_uid ));
1016 /* Ensure the uid entry is updated. */
1017 psbuf->st_ex_uid = smb_fname_parent->st.st_ex_uid;
1021 vfs_ChDir(conn, saved_dir_fname);
1023 TALLOC_FREE(saved_dir_fname);
1024 TALLOC_FREE(smb_fname_cwd);
1028 /****************************************************************************
1029 Open a file - returning a guaranteed ATOMIC indication of if the
1030 file was created or not.
1031 ****************************************************************************/
1033 static NTSTATUS fd_open_atomic(files_struct *fsp,
1038 NTSTATUS status = NT_STATUS_UNSUCCESSFUL;
1039 NTSTATUS retry_status;
1040 bool file_existed = VALID_STAT(fsp->fsp_name->st);
1043 if (!(flags & O_CREAT)) {
1045 * We're not creating the file, just pass through.
1047 status = fd_open(fsp, flags, mode);
1048 *file_created = false;
1052 if (flags & O_EXCL) {
1054 * Fail if already exists, just pass through.
1056 status = fd_open(fsp, flags, mode);
1059 * Here we've opened with O_CREAT|O_EXCL. If that went
1060 * NT_STATUS_OK, we *know* we created this file.
1062 *file_created = NT_STATUS_IS_OK(status);
1068 * Now it gets tricky. We have O_CREAT, but not O_EXCL.
1069 * To know absolutely if we created the file or not,
1070 * we can never call O_CREAT without O_EXCL. So if
1071 * we think the file existed, try without O_CREAT|O_EXCL.
1072 * If we think the file didn't exist, try with
1075 * The big problem here is dangling symlinks. Opening
1076 * without O_NOFOLLOW means both bad symlink
1077 * and missing path return -1, ENOENT from open(). As POSIX
1078 * is pathname based it's not possible to tell
1079 * the difference between these two cases in a
1080 * non-racy way, so change to try only two attempts before
1083 * We don't have this problem for the O_NOFOLLOW
1084 * case as it just returns NT_STATUS_OBJECT_PATH_NOT_FOUND
1085 * mapped from the ELOOP POSIX error.
1089 curr_flags = flags & ~(O_CREAT);
1090 retry_status = NT_STATUS_OBJECT_NAME_NOT_FOUND;
1092 curr_flags = flags | O_EXCL;
1093 retry_status = NT_STATUS_OBJECT_NAME_COLLISION;
1096 status = fd_open(fsp, curr_flags, mode);
1097 if (NT_STATUS_IS_OK(status)) {
1098 *file_created = !file_existed;
1099 return NT_STATUS_OK;
1101 if (NT_STATUS_EQUAL(status, retry_status)) {
1103 file_existed = !file_existed;
1105 DBG_DEBUG("File %s %s. Retry.\n",
1107 file_existed ? "existed" : "did not exist");
1110 curr_flags = flags & ~(O_CREAT);
1112 curr_flags = flags | O_EXCL;
1115 status = fd_open(fsp, curr_flags, mode);
1118 *file_created = (NT_STATUS_IS_OK(status) && !file_existed);
1122 /****************************************************************************
1124 ****************************************************************************/
1126 static NTSTATUS open_file(files_struct *fsp,
1127 struct smb_request *req,
1128 struct smb_filename *parent_dir,
1131 uint32_t access_mask, /* client requested access mask. */
1132 uint32_t open_access_mask, /* what we're actually using in the open. */
1133 bool *p_file_created)
1135 connection_struct *conn = fsp->conn;
1136 struct smb_filename *smb_fname = fsp->fsp_name;
1137 NTSTATUS status = NT_STATUS_OK;
1138 int accmode = (flags & O_ACCMODE);
1139 int local_flags = flags;
1140 bool file_existed = VALID_STAT(fsp->fsp_name->st);
1141 uint32_t need_fd_mask =
1147 WRITE_OWNER_ACCESS |
1148 SEC_FLAG_SYSTEM_SECURITY |
1149 READ_CONTROL_ACCESS;
1150 bool creating = !file_existed && (flags & O_CREAT);
1151 bool truncating = (flags & O_TRUNC);
1152 bool open_fd = false;
1157 /* Check permissions */
1160 * This code was changed after seeing a client open request
1161 * containing the open mode of (DENY_WRITE/read-only) with
1162 * the 'create if not exist' bit set. The previous code
1163 * would fail to open the file read only on a read-only share
1164 * as it was checking the flags parameter directly against O_RDONLY,
1165 * this was failing as the flags parameter was set to O_RDONLY|O_CREAT.
1169 if (!CAN_WRITE(conn)) {
1170 /* It's a read-only share - fail if we wanted to write. */
1171 if(accmode != O_RDONLY || (flags & O_TRUNC) || (flags & O_APPEND)) {
1172 DEBUG(3,("Permission denied opening %s\n",
1173 smb_fname_str_dbg(smb_fname)));
1174 return NT_STATUS_ACCESS_DENIED;
1176 if (flags & O_CREAT) {
1177 /* We don't want to write - but we must make sure that
1178 O_CREAT doesn't create the file if we have write
1179 access into the directory.
1181 flags &= ~(O_CREAT|O_EXCL);
1182 local_flags &= ~(O_CREAT|O_EXCL);
1187 * This little piece of insanity is inspired by the
1188 * fact that an NT client can open a file for O_RDONLY,
1189 * but set the create disposition to FILE_EXISTS_TRUNCATE.
1190 * If the client *can* write to the file, then it expects to
1191 * truncate the file, even though it is opening for readonly.
1192 * Quicken uses this stupid trick in backup file creation...
1193 * Thanks *greatly* to "David W. Chapman Jr." <dwcjr@inethouston.net>
1194 * for helping track this one down. It didn't bite us in 2.0.x
1195 * as we always opened files read-write in that release. JRA.
1198 if ((accmode == O_RDONLY) && ((flags & O_TRUNC) == O_TRUNC)) {
1199 DEBUG(10,("open_file: truncate requested on read-only open "
1200 "for file %s\n", smb_fname_str_dbg(smb_fname)));
1201 local_flags = (flags & ~O_ACCMODE)|O_RDWR;
1204 if ((open_access_mask & need_fd_mask) || creating || truncating) {
1212 #if defined(O_NONBLOCK) && defined(S_ISFIFO)
1214 * We would block on opening a FIFO with no one else on the
1215 * other end. Do what we used to do and add O_NONBLOCK to the
1219 if (file_existed && S_ISFIFO(smb_fname->st.st_ex_mode)) {
1220 local_flags &= ~O_TRUNC; /* Can't truncate a FIFO. */
1221 local_flags |= O_NONBLOCK;
1226 /* Don't create files with Microsoft wildcard characters. */
1227 if (fsp->base_fsp) {
1229 * wildcard characters are allowed in stream names
1230 * only test the basefilename
1232 wild = fsp->base_fsp->fsp_name->base_name;
1234 wild = smb_fname->base_name;
1236 if ((local_flags & O_CREAT) && !file_existed &&
1237 !(fsp->posix_flags & FSP_POSIX_FLAGS_PATHNAMES) &&
1238 ms_has_wild(wild)) {
1239 return NT_STATUS_OBJECT_NAME_INVALID;
1242 /* Can we access this file ? */
1243 if (!fsp->base_fsp) {
1244 /* Only do this check on non-stream open. */
1246 status = smbd_check_access_rights(conn,
1252 if (!NT_STATUS_IS_OK(status)) {
1253 DEBUG(10, ("open_file: "
1254 "smbd_check_access_rights "
1255 "on file %s returned %s\n",
1256 smb_fname_str_dbg(smb_fname),
1257 nt_errstr(status)));
1260 if (!NT_STATUS_IS_OK(status) &&
1261 !NT_STATUS_EQUAL(status,
1262 NT_STATUS_OBJECT_NAME_NOT_FOUND))
1267 if (NT_STATUS_EQUAL(status,
1268 NT_STATUS_OBJECT_NAME_NOT_FOUND))
1270 DEBUG(10, ("open_file: "
1271 "file %s vanished since we "
1272 "checked for existence.\n",
1273 smb_fname_str_dbg(smb_fname)));
1274 file_existed = false;
1275 SET_STAT_INVALID(fsp->fsp_name->st);
1279 if (!file_existed) {
1280 if (!(local_flags & O_CREAT)) {
1281 /* File didn't exist and no O_CREAT. */
1282 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
1285 status = check_parent_access(conn,
1289 if (!NT_STATUS_IS_OK(status)) {
1290 DEBUG(10, ("open_file: "
1291 "check_parent_access on "
1292 "file %s returned %s\n",
1293 smb_fname_str_dbg(smb_fname),
1294 nt_errstr(status) ));
1301 * Actually do the open - if O_TRUNC is needed handle it
1302 * below under the share mode lock.
1304 status = fd_open_atomic(fsp,
1305 local_flags & ~O_TRUNC,
1308 if (!NT_STATUS_IS_OK(status)) {
1309 DEBUG(3,("Error opening file %s (%s) (local_flags=%d) "
1310 "(flags=%d)\n", smb_fname_str_dbg(smb_fname),
1311 nt_errstr(status),local_flags,flags));
1315 if (local_flags & O_NONBLOCK) {
1317 * GPFS can return ETIMEDOUT for pread on
1318 * nonblocking file descriptors when files
1319 * migrated to tape need to be recalled. I
1320 * could imagine this happens elsewhere
1321 * too. With blocking file descriptors this
1324 ret = vfs_set_blocking(fsp, true);
1326 status = map_nt_error_from_unix(errno);
1327 DBG_WARNING("Could not set fd to blocking: "
1328 "%s\n", strerror(errno));
1334 ret = SMB_VFS_FSTAT(fsp, &smb_fname->st);
1336 /* If we have an fd, this stat should succeed. */
1337 DEBUG(0,("Error doing fstat on open file %s "
1339 smb_fname_str_dbg(smb_fname),
1341 status = map_nt_error_from_unix(errno);
1346 if (*p_file_created) {
1347 /* We created this file. */
1349 bool need_re_stat = false;
1350 /* Do all inheritance work after we've
1351 done a successful fstat call and filled
1352 in the stat struct in fsp->fsp_name. */
1354 /* Inherit the ACL if required */
1355 if (lp_inherit_permissions(SNUM(conn))) {
1356 inherit_access_posix_acl(conn,
1360 need_re_stat = true;
1363 /* Change the owner if required. */
1364 if (lp_inherit_owner(SNUM(conn)) != INHERIT_OWNER_NO) {
1365 change_file_owner_to_parent(conn,
1368 need_re_stat = true;
1372 ret = SMB_VFS_FSTAT(fsp, &smb_fname->st);
1373 /* If we have an fd, this stat should succeed. */
1375 DEBUG(0,("Error doing fstat on open file %s "
1377 smb_fname_str_dbg(smb_fname),
1382 notify_fname(conn, NOTIFY_ACTION_ADDED,
1383 FILE_NOTIFY_CHANGE_FILE_NAME,
1384 smb_fname->base_name);
1387 fsp->fh->fd = -1; /* What we used to call a stat open. */
1388 if (!file_existed) {
1389 /* File must exist for a stat open. */
1390 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
1393 status = smbd_check_access_rights(conn,
1399 if (NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND) &&
1400 (fsp->posix_flags & FSP_POSIX_FLAGS_OPEN) &&
1401 S_ISLNK(smb_fname->st.st_ex_mode)) {
1402 /* This is a POSIX stat open for delete
1403 * or rename on a symlink that points
1404 * nowhere. Allow. */
1405 DEBUG(10,("open_file: allowing POSIX "
1406 "open on bad symlink %s\n",
1407 smb_fname_str_dbg(smb_fname)));
1408 status = NT_STATUS_OK;
1411 if (!NT_STATUS_IS_OK(status)) {
1412 DEBUG(10,("open_file: "
1413 "smbd_check_access_rights on file "
1415 smb_fname_str_dbg(smb_fname),
1416 nt_errstr(status) ));
1422 * POSIX allows read-only opens of directories. We don't
1423 * want to do this (we use a different code path for this)
1424 * so catch a directory open and return an EISDIR. JRA.
1427 if(S_ISDIR(smb_fname->st.st_ex_mode)) {
1430 return NT_STATUS_FILE_IS_A_DIRECTORY;
1433 fsp->file_id = vfs_file_id_from_sbuf(conn, &smb_fname->st);
1434 fsp->vuid = req ? req->vuid : UID_FIELD_INVALID;
1435 fsp->file_pid = req ? req->smbpid : 0;
1436 fsp->fsp_flags.can_lock = true;
1437 fsp->fsp_flags.can_read = ((access_mask & FILE_READ_DATA) != 0);
1438 fsp->fsp_flags.can_write =
1440 ((access_mask & (FILE_WRITE_DATA | FILE_APPEND_DATA)) != 0);
1441 fsp->print_file = NULL;
1442 fsp->fsp_flags.modified = false;
1443 fsp->sent_oplock_break = NO_BREAK_SENT;
1444 fsp->fsp_flags.is_directory = false;
1445 if (conn->aio_write_behind_list &&
1446 is_in_path(smb_fname->base_name, conn->aio_write_behind_list,
1447 conn->case_sensitive)) {
1448 fsp->fsp_flags.aio_write_behind = true;
1451 DEBUG(2,("%s opened file %s read=%s write=%s (numopen=%d)\n",
1452 conn->session_info->unix_info->unix_name,
1453 smb_fname_str_dbg(smb_fname),
1454 BOOLSTR(fsp->fsp_flags.can_read),
1455 BOOLSTR(fsp->fsp_flags.can_write),
1456 conn->num_files_open));
1459 return NT_STATUS_OK;
1462 static bool mask_conflict(
1463 uint32_t new_access,
1464 uint32_t existing_access,
1465 uint32_t access_mask,
1466 uint32_t new_sharemode,
1467 uint32_t existing_sharemode,
1468 uint32_t sharemode_mask)
1470 bool want_access = (new_access & access_mask);
1471 bool allow_existing = (existing_sharemode & sharemode_mask);
1472 bool have_access = (existing_access & access_mask);
1473 bool allow_new = (new_sharemode & sharemode_mask);
1475 if (want_access && !allow_existing) {
1476 DBG_DEBUG("Access request 0x%"PRIx32"/0x%"PRIx32" conflicts "
1477 "with existing sharemode 0x%"PRIx32"/0x%"PRIx32"\n",
1484 if (have_access && !allow_new) {
1485 DBG_DEBUG("Sharemode request 0x%"PRIx32"/0x%"PRIx32" conflicts "
1486 "with existing access 0x%"PRIx32"/0x%"PRIx32"\n",
1496 /****************************************************************************
1497 Check if we can open a file with a share mode.
1498 Returns True if conflict, False if not.
1499 ****************************************************************************/
1501 static const uint32_t conflicting_access =
1508 static bool share_conflict(uint32_t e_access_mask,
1509 uint32_t e_share_access,
1510 uint32_t access_mask,
1511 uint32_t share_access)
1515 DBG_DEBUG("existing access_mask = 0x%"PRIx32", "
1516 "existing share access = 0x%"PRIx32", "
1517 "access_mask = 0x%"PRIx32", "
1518 "share_access = 0x%"PRIx32"\n",
1524 if ((e_access_mask & conflicting_access) == 0) {
1525 DBG_DEBUG("No conflict due to "
1526 "existing access_mask = 0x%"PRIx32"\n",
1530 if ((access_mask & conflicting_access) == 0) {
1531 DBG_DEBUG("No conflict due to access_mask = 0x%"PRIx32"\n",
1536 conflict = mask_conflict(
1537 access_mask, e_access_mask, FILE_WRITE_DATA | FILE_APPEND_DATA,
1538 share_access, e_share_access, FILE_SHARE_WRITE);
1539 conflict |= mask_conflict(
1540 access_mask, e_access_mask, FILE_READ_DATA | FILE_EXECUTE,
1541 share_access, e_share_access, FILE_SHARE_READ);
1542 conflict |= mask_conflict(
1543 access_mask, e_access_mask, DELETE_ACCESS,
1544 share_access, e_share_access, FILE_SHARE_DELETE);
1546 DBG_DEBUG("conflict=%s\n", conflict ? "true" : "false");
1550 #if defined(DEVELOPER)
1552 struct validate_my_share_entries_state {
1553 struct smbd_server_connection *sconn;
1555 struct server_id self;
1558 static bool validate_my_share_entries_fn(
1559 struct share_mode_entry *e,
1563 struct validate_my_share_entries_state *state = private_data;
1566 if (!server_id_equal(&state->self, &e->pid)) {
1570 if (e->op_mid == 0) {
1571 /* INTERNAL_OPEN_ONLY */
1575 fsp = file_find_dif(state->sconn, state->fid, e->share_file_id);
1577 DBG_ERR("PANIC : %s\n",
1578 share_mode_str(talloc_tos(), 0, &state->fid, e));
1579 smb_panic("validate_my_share_entries: Cannot match a "
1580 "share entry with an open file\n");
1583 if (((uint16_t)fsp->oplock_type) != e->op_type) {
1592 DBG_ERR("validate_my_share_entries: PANIC : %s\n",
1593 share_mode_str(talloc_tos(), 0, &state->fid, e));
1594 str = talloc_asprintf(talloc_tos(),
1595 "validate_my_share_entries: "
1596 "file %s, oplock_type = 0x%x, op_type = 0x%x\n",
1597 fsp->fsp_name->base_name,
1598 (unsigned int)fsp->oplock_type,
1599 (unsigned int)e->op_type);
1608 * Allowed access mask for stat opens relevant to oplocks
1610 bool is_oplock_stat_open(uint32_t access_mask)
1612 const uint32_t stat_open_bits =
1613 (SYNCHRONIZE_ACCESS|
1614 FILE_READ_ATTRIBUTES|
1615 FILE_WRITE_ATTRIBUTES);
1617 return (((access_mask & stat_open_bits) != 0) &&
1618 ((access_mask & ~stat_open_bits) == 0));
1622 * Allowed access mask for stat opens relevant to leases
1624 bool is_lease_stat_open(uint32_t access_mask)
1626 const uint32_t stat_open_bits =
1627 (SYNCHRONIZE_ACCESS|
1628 FILE_READ_ATTRIBUTES|
1629 FILE_WRITE_ATTRIBUTES|
1630 READ_CONTROL_ACCESS);
1632 return (((access_mask & stat_open_bits) != 0) &&
1633 ((access_mask & ~stat_open_bits) == 0));
1636 struct has_delete_on_close_state {
1640 static bool has_delete_on_close_fn(
1641 struct share_mode_entry *e,
1645 struct has_delete_on_close_state *state = private_data;
1646 state->ret = !share_entry_stale_pid(e);
1650 static bool has_delete_on_close(struct share_mode_lock *lck,
1653 struct has_delete_on_close_state state = { .ret = false };
1656 if (!is_delete_on_close_set(lck, name_hash)) {
1660 ok= share_mode_forall_entries(lck, has_delete_on_close_fn, &state);
1662 DBG_DEBUG("share_mode_forall_entries failed\n");
1668 static void share_mode_flags_get(
1670 uint32_t *access_mask,
1671 uint32_t *share_mode,
1672 uint32_t *lease_type)
1674 if (access_mask != NULL) {
1676 ((flags & SHARE_MODE_ACCESS_READ) ?
1677 FILE_READ_DATA : 0) |
1678 ((flags & SHARE_MODE_ACCESS_WRITE) ?
1679 FILE_WRITE_DATA : 0) |
1680 ((flags & SHARE_MODE_ACCESS_DELETE) ?
1683 if (share_mode != NULL) {
1685 ((flags & SHARE_MODE_SHARE_READ) ?
1686 FILE_SHARE_READ : 0) |
1687 ((flags & SHARE_MODE_SHARE_WRITE) ?
1688 FILE_SHARE_WRITE : 0) |
1689 ((flags & SHARE_MODE_SHARE_DELETE) ?
1690 FILE_SHARE_DELETE : 0);
1692 if (lease_type != NULL) {
1694 ((flags & SHARE_MODE_LEASE_READ) ?
1695 SMB2_LEASE_READ : 0) |
1696 ((flags & SHARE_MODE_LEASE_WRITE) ?
1697 SMB2_LEASE_WRITE : 0) |
1698 ((flags & SHARE_MODE_LEASE_HANDLE) ?
1699 SMB2_LEASE_HANDLE : 0);
1703 static uint16_t share_mode_flags_set(
1705 uint32_t access_mask,
1706 uint32_t share_mode,
1707 uint32_t lease_type)
1709 if (access_mask != UINT32_MAX) {
1710 flags &= ~(SHARE_MODE_ACCESS_READ|
1711 SHARE_MODE_ACCESS_WRITE|
1712 SHARE_MODE_ACCESS_DELETE);
1713 flags |= (access_mask & (FILE_READ_DATA | FILE_EXECUTE)) ?
1714 SHARE_MODE_ACCESS_READ : 0;
1715 flags |= (access_mask & (FILE_WRITE_DATA | FILE_APPEND_DATA)) ?
1716 SHARE_MODE_ACCESS_WRITE : 0;
1717 flags |= (access_mask & (DELETE_ACCESS)) ?
1718 SHARE_MODE_ACCESS_DELETE : 0;
1720 if (share_mode != UINT32_MAX) {
1721 flags &= ~(SHARE_MODE_SHARE_READ|
1722 SHARE_MODE_SHARE_WRITE|
1723 SHARE_MODE_SHARE_DELETE);
1724 flags |= (share_mode & FILE_SHARE_READ) ?
1725 SHARE_MODE_SHARE_READ : 0;
1726 flags |= (share_mode & FILE_SHARE_WRITE) ?
1727 SHARE_MODE_SHARE_WRITE : 0;
1728 flags |= (share_mode & FILE_SHARE_DELETE) ?
1729 SHARE_MODE_SHARE_DELETE : 0;
1731 if (lease_type != UINT32_MAX) {
1732 flags &= ~(SHARE_MODE_LEASE_READ|
1733 SHARE_MODE_LEASE_WRITE|
1734 SHARE_MODE_LEASE_HANDLE);
1735 flags |= (lease_type & SMB2_LEASE_READ) ?
1736 SHARE_MODE_LEASE_READ : 0;
1737 flags |= (lease_type & SMB2_LEASE_WRITE) ?
1738 SHARE_MODE_LEASE_WRITE : 0;
1739 flags |= (lease_type & SMB2_LEASE_HANDLE) ?
1740 SHARE_MODE_LEASE_HANDLE : 0;
1746 static uint16_t share_mode_flags_restrict(
1748 uint32_t access_mask,
1749 uint32_t share_mode,
1750 uint32_t lease_type)
1752 uint32_t existing_access_mask, existing_share_mode;
1753 uint32_t existing_lease_type;
1756 share_mode_flags_get(
1758 &existing_access_mask,
1759 &existing_share_mode,
1760 &existing_lease_type);
1762 existing_access_mask |= access_mask;
1763 if (access_mask & conflicting_access) {
1764 existing_share_mode &= share_mode;
1766 existing_lease_type |= lease_type;
1768 ret = share_mode_flags_set(
1770 existing_access_mask,
1771 existing_share_mode,
1772 existing_lease_type);
1776 /****************************************************************************
1777 Deal with share modes
1778 Invariant: Share mode must be locked on entry and exit.
1779 Returns -1 on error, or number of share modes on success (may be zero).
1780 ****************************************************************************/
1782 struct open_mode_check_state {
1784 uint32_t access_mask;
1785 uint32_t share_access;
1786 uint32_t lease_type;
1789 static bool open_mode_check_fn(
1790 struct share_mode_entry *e,
1794 struct open_mode_check_state *state = private_data;
1795 bool disconnected, stale;
1796 uint32_t access_mask, share_access, lease_type;
1798 disconnected = server_id_is_disconnected(&e->pid);
1803 access_mask = state->access_mask | e->access_mask;
1804 share_access = state->share_access;
1805 if (e->access_mask & conflicting_access) {
1806 share_access &= e->share_access;
1808 lease_type = state->lease_type | get_lease_type(e, state->fid);
1810 if ((access_mask == state->access_mask) &&
1811 (share_access == state->share_access) &&
1812 (lease_type == state->lease_type)) {
1816 stale = share_entry_stale_pid(e);
1821 state->access_mask = access_mask;
1822 state->share_access = share_access;
1823 state->lease_type = lease_type;
1828 static NTSTATUS open_mode_check(connection_struct *conn,
1829 struct share_mode_lock *lck,
1830 uint32_t access_mask,
1831 uint32_t share_access)
1833 struct share_mode_data *d = lck->data;
1834 struct open_mode_check_state state;
1836 bool ok, conflict, have_share_entries;
1838 if (is_oplock_stat_open(access_mask)) {
1839 /* Stat open that doesn't trigger oplock breaks or share mode
1840 * checks... ! JRA. */
1841 return NT_STATUS_OK;
1845 * Check if the share modes will give us access.
1848 #if defined(DEVELOPER)
1850 struct validate_my_share_entries_state validate_state = {
1851 .sconn = conn->sconn,
1853 .self = messaging_server_id(conn->sconn->msg_ctx),
1855 ok = share_mode_forall_entries(
1856 lck, validate_my_share_entries_fn, &validate_state);
1861 have_share_entries = share_mode_have_entries(lck);
1862 if (!have_share_entries) {
1864 * This is a fresh share mode lock where no conflicts
1867 return NT_STATUS_OK;
1870 share_mode_flags_get(
1871 d->flags, &state.access_mask, &state.share_access, NULL);
1873 conflict = share_conflict(
1879 DBG_DEBUG("No conflict due to share_mode_flags access\n");
1880 return NT_STATUS_OK;
1883 state = (struct open_mode_check_state) {
1885 .share_access = (FILE_SHARE_READ|
1891 * Walk the share mode array to recalculate d->flags
1894 ok = share_mode_forall_entries(lck, open_mode_check_fn, &state);
1896 DBG_DEBUG("share_mode_forall_entries failed\n");
1897 return NT_STATUS_INTERNAL_ERROR;
1900 new_flags = share_mode_flags_set(
1901 0, state.access_mask, state.share_access, state.lease_type);
1902 if (new_flags == d->flags) {
1904 * We only end up here if we had a sharing violation
1905 * from d->flags and have recalculated it.
1907 return NT_STATUS_SHARING_VIOLATION;
1910 d->flags = new_flags;
1913 conflict = share_conflict(
1919 DBG_DEBUG("No conflict due to share_mode_flags access\n");
1920 return NT_STATUS_OK;
1923 return NT_STATUS_SHARING_VIOLATION;
1927 * Send a break message to the oplock holder and delay the open for
1931 NTSTATUS send_break_message(struct messaging_context *msg_ctx,
1932 const struct file_id *id,
1933 const struct share_mode_entry *exclusive,
1936 struct oplock_break_message msg = {
1938 .share_file_id = exclusive->share_file_id,
1939 .break_to = break_to,
1941 enum ndr_err_code ndr_err;
1946 struct server_id_buf buf;
1947 DBG_DEBUG("Sending break message to %s\n",
1948 server_id_str_buf(exclusive->pid, &buf));
1949 NDR_PRINT_DEBUG(oplock_break_message, &msg);
1952 ndr_err = ndr_push_struct_blob(
1956 (ndr_push_flags_fn_t)ndr_push_oplock_break_message);
1957 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
1958 DBG_WARNING("ndr_push_oplock_break_message failed: %s\n",
1959 ndr_errstr(ndr_err));
1960 return ndr_map_error2ntstatus(ndr_err);
1963 status = messaging_send(
1964 msg_ctx, exclusive->pid, MSG_SMB_BREAK_REQUEST, &blob);
1965 TALLOC_FREE(blob.data);
1966 if (!NT_STATUS_IS_OK(status)) {
1967 DEBUG(3, ("Could not send oplock break message: %s\n",
1968 nt_errstr(status)));
1974 struct validate_oplock_types_state {
1980 uint32_t num_non_stat_opens;
1983 static bool validate_oplock_types_fn(
1984 struct share_mode_entry *e,
1988 struct validate_oplock_types_state *state = private_data;
1990 if (e->op_mid == 0) {
1991 /* INTERNAL_OPEN_ONLY */
1995 if (e->op_type == NO_OPLOCK && is_oplock_stat_open(e->access_mask)) {
1997 * We ignore stat opens in the table - they always
1998 * have NO_OPLOCK and never get or cause breaks. JRA.
2003 state->num_non_stat_opens += 1;
2005 if (BATCH_OPLOCK_TYPE(e->op_type)) {
2006 /* batch - can only be one. */
2007 if (share_entry_stale_pid(e)) {
2008 DBG_DEBUG("Found stale batch oplock\n");
2011 if (state->ex_or_batch ||
2015 DBG_ERR("Bad batch oplock entry\n");
2016 state->valid = false;
2019 state->batch = true;
2022 if (EXCLUSIVE_OPLOCK_TYPE(e->op_type)) {
2023 if (share_entry_stale_pid(e)) {
2024 DBG_DEBUG("Found stale duplicate oplock\n");
2027 /* Exclusive or batch - can only be one. */
2028 if (state->ex_or_batch ||
2031 DBG_ERR("Bad exclusive or batch oplock entry\n");
2032 state->valid = false;
2035 state->ex_or_batch = true;
2038 if (LEVEL_II_OPLOCK_TYPE(e->op_type)) {
2039 if (state->batch || state->ex_or_batch) {
2040 if (share_entry_stale_pid(e)) {
2041 DBG_DEBUG("Found stale LevelII oplock\n");
2044 DBG_DEBUG("Bad levelII oplock entry\n");
2045 state->valid = false;
2048 state->level2 = true;
2051 if (e->op_type == NO_OPLOCK) {
2052 if (state->batch || state->ex_or_batch) {
2053 if (share_entry_stale_pid(e)) {
2054 DBG_DEBUG("Found stale NO_OPLOCK entry\n");
2057 DBG_ERR("Bad no oplock entry\n");
2058 state->valid = false;
2061 state->no_oplock = true;
2068 * Do internal consistency checks on the share mode for a file.
2071 static bool validate_oplock_types(struct share_mode_lock *lck)
2073 struct validate_oplock_types_state state = { .valid = true };
2076 ok = share_mode_forall_entries(lck, validate_oplock_types_fn, &state);
2078 DBG_DEBUG("share_mode_forall_entries failed\n");
2082 DBG_DEBUG("Got invalid oplock configuration\n");
2086 if ((state.batch || state.ex_or_batch) &&
2087 (state.num_non_stat_opens != 1)) {
2088 DBG_WARNING("got batch (%d) or ex (%d) non-exclusively "
2091 (int)state.ex_or_batch,
2092 state.num_non_stat_opens);
2099 static bool is_same_lease(const files_struct *fsp,
2100 const struct share_mode_entry *e,
2101 const struct smb2_lease *lease)
2103 if (e->op_type != LEASE_OPLOCK) {
2106 if (lease == NULL) {
2110 return smb2_lease_equal(fsp_client_guid(fsp),
2116 static bool file_has_brlocks(files_struct *fsp)
2118 struct byte_range_lock *br_lck;
2120 br_lck = brl_get_locks_readonly(fsp);
2124 return (brl_num_locks(br_lck) > 0);
2127 struct fsp_lease *find_fsp_lease(struct files_struct *new_fsp,
2128 const struct smb2_lease_key *key,
2129 uint32_t current_state,
2130 uint16_t lease_version,
2131 uint16_t lease_epoch)
2133 struct files_struct *fsp;
2136 * TODO: Measure how expensive this loop is with thousands of open
2140 for (fsp = file_find_di_first(new_fsp->conn->sconn, new_fsp->file_id);
2142 fsp = file_find_di_next(fsp)) {
2144 if (fsp == new_fsp) {
2147 if (fsp->oplock_type != LEASE_OPLOCK) {
2150 if (smb2_lease_key_equal(&fsp->lease->lease.lease_key, key)) {
2151 fsp->lease->ref_count += 1;
2156 /* Not found - must be leased in another smbd. */
2157 new_fsp->lease = talloc_zero(new_fsp->conn->sconn, struct fsp_lease);
2158 if (new_fsp->lease == NULL) {
2161 new_fsp->lease->ref_count = 1;
2162 new_fsp->lease->sconn = new_fsp->conn->sconn;
2163 new_fsp->lease->lease.lease_key = *key;
2164 new_fsp->lease->lease.lease_state = current_state;
2166 * We internally treat all leases as V2 and update
2167 * the epoch, but when sending breaks it matters if
2168 * the requesting lease was v1 or v2.
2170 new_fsp->lease->lease.lease_version = lease_version;
2171 new_fsp->lease->lease.lease_epoch = lease_epoch;
2172 return new_fsp->lease;
2175 static NTSTATUS try_lease_upgrade(struct files_struct *fsp,
2176 struct share_mode_lock *lck,
2177 const struct GUID *client_guid,
2178 const struct smb2_lease *lease,
2182 uint32_t current_state, breaking_to_requested, breaking_to_required;
2184 uint16_t lease_version, epoch;
2185 uint32_t existing, requested;
2188 status = leases_db_get(
2194 &breaking_to_requested,
2195 &breaking_to_required,
2198 if (!NT_STATUS_IS_OK(status)) {
2202 fsp->lease = find_fsp_lease(
2208 if (fsp->lease == NULL) {
2209 DEBUG(1, ("Did not find existing lease for file %s\n",
2211 return NT_STATUS_NO_MEMORY;
2215 * Upgrade only if the requested lease is a strict upgrade.
2217 existing = current_state;
2218 requested = lease->lease_state;
2221 * Tricky: This test makes sure that "requested" is a
2222 * strict bitwise superset of "existing".
2224 do_upgrade = ((existing & requested) == existing);
2227 * Upgrade only if there's a change.
2229 do_upgrade &= (granted != existing);
2232 * Upgrade only if other leases don't prevent what was asked
2235 do_upgrade &= (granted == requested);
2238 * only upgrade if we are not in breaking state
2240 do_upgrade &= !breaking;
2242 DEBUG(10, ("existing=%"PRIu32", requested=%"PRIu32", "
2243 "granted=%"PRIu32", do_upgrade=%d\n",
2244 existing, requested, granted, (int)do_upgrade));
2247 NTSTATUS set_status;
2249 current_state = granted;
2252 set_status = leases_db_set(
2257 breaking_to_requested,
2258 breaking_to_required,
2262 if (!NT_STATUS_IS_OK(set_status)) {
2263 DBG_DEBUG("leases_db_set failed: %s\n",
2264 nt_errstr(set_status));
2269 fsp_lease_update(fsp);
2271 return NT_STATUS_OK;
2274 static NTSTATUS grant_new_fsp_lease(struct files_struct *fsp,
2275 struct share_mode_lock *lck,
2276 const struct GUID *client_guid,
2277 const struct smb2_lease *lease,
2280 struct share_mode_data *d = lck->data;
2283 fsp->lease = talloc_zero(fsp->conn->sconn, struct fsp_lease);
2284 if (fsp->lease == NULL) {
2285 return NT_STATUS_INSUFFICIENT_RESOURCES;
2287 fsp->lease->ref_count = 1;
2288 fsp->lease->sconn = fsp->conn->sconn;
2289 fsp->lease->lease.lease_version = lease->lease_version;
2290 fsp->lease->lease.lease_key = lease->lease_key;
2291 fsp->lease->lease.lease_state = granted;
2292 fsp->lease->lease.lease_epoch = lease->lease_epoch + 1;
2294 status = leases_db_add(client_guid,
2297 fsp->lease->lease.lease_state,
2298 fsp->lease->lease.lease_version,
2299 fsp->lease->lease.lease_epoch,
2300 fsp->conn->connectpath,
2301 fsp->fsp_name->base_name,
2302 fsp->fsp_name->stream_name);
2303 if (!NT_STATUS_IS_OK(status)) {
2304 DEBUG(10, ("%s: leases_db_add failed: %s\n", __func__,
2305 nt_errstr(status)));
2306 TALLOC_FREE(fsp->lease);
2307 return NT_STATUS_INSUFFICIENT_RESOURCES;
2312 return NT_STATUS_OK;
2315 static NTSTATUS grant_fsp_lease(struct files_struct *fsp,
2316 struct share_mode_lock *lck,
2317 const struct smb2_lease *lease,
2320 const struct GUID *client_guid = fsp_client_guid(fsp);
2323 status = try_lease_upgrade(fsp, lck, client_guid, lease, granted);
2325 if (NT_STATUS_EQUAL(status, NT_STATUS_NOT_FOUND)) {
2326 status = grant_new_fsp_lease(
2327 fsp, lck, client_guid, lease, granted);
2333 static int map_lease_type_to_oplock(uint32_t lease_type)
2335 int result = NO_OPLOCK;
2337 switch (lease_type) {
2338 case SMB2_LEASE_READ|SMB2_LEASE_WRITE|SMB2_LEASE_HANDLE:
2339 result = BATCH_OPLOCK|EXCLUSIVE_OPLOCK;
2341 case SMB2_LEASE_READ|SMB2_LEASE_WRITE:
2342 result = EXCLUSIVE_OPLOCK;
2344 case SMB2_LEASE_READ|SMB2_LEASE_HANDLE:
2345 case SMB2_LEASE_READ:
2346 result = LEVEL_II_OPLOCK;
2353 struct delay_for_oplock_state {
2354 struct files_struct *fsp;
2355 const struct smb2_lease *lease;
2356 bool will_overwrite;
2357 uint32_t delay_mask;
2358 bool first_open_attempt;
2359 bool got_handle_lease;
2361 bool have_other_lease;
2365 static bool delay_for_oplock_fn(
2366 struct share_mode_entry *e,
2370 struct delay_for_oplock_state *state = private_data;
2371 struct files_struct *fsp = state->fsp;
2372 const struct smb2_lease *lease = state->lease;
2373 bool e_is_lease = (e->op_type == LEASE_OPLOCK);
2374 uint32_t e_lease_type = get_lease_type(e, fsp->file_id);
2376 bool lease_is_breaking = false;
2381 if (lease != NULL) {
2382 bool our_lease = is_same_lease(fsp, e, lease);
2384 DBG_DEBUG("Ignoring our own lease\n");
2389 status = leases_db_get(
2393 NULL, /* current_state */
2395 NULL, /* breaking_to_requested */
2396 NULL, /* breaking_to_required */
2397 NULL, /* lease_version */
2401 * leases_db_get() can return NT_STATUS_NOT_FOUND
2402 * if the share_mode_entry e is stale and the
2403 * lease record was already removed. In this case return
2404 * false so the traverse continues.
2407 if (NT_STATUS_EQUAL(status, NT_STATUS_NOT_FOUND) &&
2408 share_entry_stale_pid(e))
2410 struct GUID_txt_buf guid_strbuf;
2411 struct file_id_buf file_id_strbuf;
2412 DBG_DEBUG("leases_db_get for client_guid [%s] "
2413 "lease_key [%"PRIu64"/%"PRIu64"] "
2414 "file_id [%s] failed for stale "
2415 "share_mode_entry\n",
2416 GUID_buf_string(&e->client_guid, &guid_strbuf),
2417 e->lease_key.data[0],
2418 e->lease_key.data[1],
2419 file_id_str_buf(fsp->file_id, &file_id_strbuf));
2422 if (!NT_STATUS_IS_OK(status)) {
2423 struct GUID_txt_buf guid_strbuf;
2424 struct file_id_buf file_id_strbuf;
2425 DBG_ERR("leases_db_get for client_guid [%s] "
2426 "lease_key [%"PRIu64"/%"PRIu64"] "
2427 "file_id [%s] failed: %s\n",
2428 GUID_buf_string(&e->client_guid, &guid_strbuf),
2429 e->lease_key.data[0],
2430 e->lease_key.data[1],
2431 file_id_str_buf(fsp->file_id, &file_id_strbuf),
2433 smb_panic("leases_db_get() failed");
2437 if (!state->got_handle_lease &&
2438 ((e_lease_type & SMB2_LEASE_HANDLE) != 0) &&
2439 !share_entry_stale_pid(e)) {
2440 state->got_handle_lease = true;
2443 if (!state->got_oplock &&
2444 (e->op_type != LEASE_OPLOCK) &&
2445 !share_entry_stale_pid(e)) {
2446 state->got_oplock = true;
2449 if (!state->have_other_lease &&
2450 !is_same_lease(fsp, e, lease) &&
2451 !share_entry_stale_pid(e)) {
2452 state->have_other_lease = true;
2455 if (e_is_lease && is_lease_stat_open(fsp->access_mask)) {
2459 break_to = e_lease_type & ~state->delay_mask;
2461 if (state->will_overwrite) {
2462 break_to &= ~(SMB2_LEASE_HANDLE|SMB2_LEASE_READ);
2465 DBG_DEBUG("e_lease_type %u, will_overwrite: %u\n",
2466 (unsigned)e_lease_type,
2467 (unsigned)state->will_overwrite);
2469 if ((e_lease_type & ~break_to) == 0) {
2470 if (lease_is_breaking) {
2471 state->delay = true;
2476 if (share_entry_stale_pid(e)) {
2480 if (state->will_overwrite) {
2482 * If we break anyway break to NONE directly.
2483 * Otherwise vfs_set_filelen() will trigger the
2486 break_to &= ~(SMB2_LEASE_READ|SMB2_LEASE_WRITE);
2491 * Oplocks only support breaking to R or NONE.
2493 break_to &= ~(SMB2_LEASE_HANDLE|SMB2_LEASE_WRITE);
2496 DBG_DEBUG("breaking from %d to %d\n",
2500 fsp->conn->sconn->msg_ctx, &fsp->file_id, e, break_to);
2501 if (e_lease_type & state->delay_mask) {
2502 state->delay = true;
2504 if (lease_is_breaking && !state->first_open_attempt) {
2505 state->delay = true;
2511 static NTSTATUS delay_for_oplock(files_struct *fsp,
2513 const struct smb2_lease *lease,
2514 struct share_mode_lock *lck,
2515 bool have_sharing_violation,
2516 uint32_t create_disposition,
2517 bool first_open_attempt)
2519 struct delay_for_oplock_state state = {
2522 .first_open_attempt = first_open_attempt,
2528 if (is_oplock_stat_open(fsp->access_mask)) {
2532 state.delay_mask = have_sharing_violation ?
2533 SMB2_LEASE_HANDLE : SMB2_LEASE_WRITE;
2535 switch (create_disposition) {
2536 case FILE_SUPERSEDE:
2537 case FILE_OVERWRITE:
2538 case FILE_OVERWRITE_IF:
2539 state.will_overwrite = true;
2542 state.will_overwrite = false;
2546 ok = share_mode_forall_entries(lck, delay_for_oplock_fn, &state);
2548 return NT_STATUS_INTERNAL_ERROR;
2552 return NT_STATUS_RETRY;
2556 if (have_sharing_violation) {
2557 return NT_STATUS_SHARING_VIOLATION;
2560 if (oplock_request == LEASE_OPLOCK) {
2561 if (lease == NULL) {
2563 * The SMB2 layer should have checked this
2565 return NT_STATUS_INTERNAL_ERROR;
2568 granted = lease->lease_state;
2570 if (lp_kernel_oplocks(SNUM(fsp->conn))) {
2571 DEBUG(10, ("No lease granted because kernel oplocks are enabled\n"));
2572 granted = SMB2_LEASE_NONE;
2574 if ((granted & (SMB2_LEASE_READ|SMB2_LEASE_WRITE)) == 0) {
2575 DEBUG(10, ("No read or write lease requested\n"));
2576 granted = SMB2_LEASE_NONE;
2578 if (granted == SMB2_LEASE_WRITE) {
2579 DEBUG(10, ("pure write lease requested\n"));
2580 granted = SMB2_LEASE_NONE;
2582 if (granted == (SMB2_LEASE_WRITE|SMB2_LEASE_HANDLE)) {
2583 DEBUG(10, ("write and handle lease requested\n"));
2584 granted = SMB2_LEASE_NONE;
2587 granted = map_oplock_to_lease_type(
2588 oplock_request & ~SAMBA_PRIVATE_OPLOCK_MASK);
2591 if (lp_locking(fsp->conn->params) && file_has_brlocks(fsp)) {
2592 DBG_DEBUG("file %s has byte range locks\n",
2594 granted &= ~SMB2_LEASE_READ;
2597 if (state.have_other_lease) {
2599 * Can grant only one writer
2601 granted &= ~SMB2_LEASE_WRITE;
2604 if ((granted & SMB2_LEASE_READ) && !(granted & SMB2_LEASE_WRITE)) {
2606 (global_client_caps & CAP_LEVEL_II_OPLOCKS) &&
2607 lp_level2_oplocks(SNUM(fsp->conn));
2609 if (!allow_level2) {
2610 granted = SMB2_LEASE_NONE;
2614 if (oplock_request == LEASE_OPLOCK) {
2615 if (state.got_oplock) {
2616 granted &= ~SMB2_LEASE_HANDLE;
2619 fsp->oplock_type = LEASE_OPLOCK;
2621 status = grant_fsp_lease(fsp, lck, lease, granted);
2622 if (!NT_STATUS_IS_OK(status)) {
2627 DBG_DEBUG("lease_state=%d\n", fsp->lease->lease.lease_state);
2629 if (state.got_handle_lease) {
2630 granted = SMB2_LEASE_NONE;
2633 fsp->oplock_type = map_lease_type_to_oplock(granted);
2635 status = set_file_oplock(fsp);
2636 if (!NT_STATUS_IS_OK(status)) {
2638 * Could not get the kernel oplock
2640 fsp->oplock_type = NO_OPLOCK;
2644 if ((granted & SMB2_LEASE_READ) &&
2645 ((lck->data->flags & SHARE_MODE_LEASE_READ) == 0)) {
2646 lck->data->flags |= SHARE_MODE_LEASE_READ;
2647 lck->data->modified = true;
2650 DBG_DEBUG("oplock type 0x%x on file %s\n",
2651 fsp->oplock_type, fsp_str_dbg(fsp));
2653 return NT_STATUS_OK;
2656 static NTSTATUS handle_share_mode_lease(
2658 struct share_mode_lock *lck,
2659 uint32_t create_disposition,
2660 uint32_t access_mask,
2661 uint32_t share_access,
2663 const struct smb2_lease *lease,
2664 bool first_open_attempt)
2666 bool sharing_violation = false;
2669 status = open_mode_check(
2670 fsp->conn, lck, access_mask, share_access);
2671 if (NT_STATUS_EQUAL(status, NT_STATUS_SHARING_VIOLATION)) {
2672 sharing_violation = true;
2673 status = NT_STATUS_OK; /* handled later */
2676 if (!NT_STATUS_IS_OK(status)) {
2680 if (oplock_request == INTERNAL_OPEN_ONLY) {
2681 if (sharing_violation) {
2682 DBG_DEBUG("Sharing violation for internal open\n");
2683 return NT_STATUS_SHARING_VIOLATION;
2687 * Internal opens never do oplocks or leases. We don't
2688 * need to go through delay_for_oplock().
2690 fsp->oplock_type = NO_OPLOCK;
2692 return NT_STATUS_OK;
2695 status = delay_for_oplock(
2702 first_open_attempt);
2703 if (!NT_STATUS_IS_OK(status)) {
2707 return NT_STATUS_OK;
2710 static bool request_timed_out(struct smb_request *req, struct timeval timeout)
2712 struct timeval now, end_time;
2714 end_time = timeval_sum(&req->request_time, &timeout);
2715 return (timeval_compare(&end_time, &now) < 0);
2718 struct defer_open_state {
2719 struct smbXsrv_connection *xconn;
2723 static void defer_open_done(struct tevent_req *req);
2726 * Defer an open and watch a locking.tdb record
2728 * This defers an open that gets rescheduled once the locking.tdb record watch
2729 * is triggered by a change to the record.
2731 * It is used to defer opens that triggered an oplock break and for the SMB1
2732 * sharing violation delay.
2734 static void defer_open(struct share_mode_lock *lck,
2735 struct timeval timeout,
2736 struct smb_request *req,
2739 struct deferred_open_record *open_rec = NULL;
2740 struct timeval abs_timeout;
2741 struct defer_open_state *watch_state;
2742 struct tevent_req *watch_req;
2743 struct timeval_buf tvbuf1, tvbuf2;
2744 struct file_id_buf fbuf;
2747 abs_timeout = timeval_sum(&req->request_time, &timeout);
2749 DBG_DEBUG("request time [%s] timeout [%s] mid [%" PRIu64 "] "
2751 timeval_str_buf(&req->request_time, false, true, &tvbuf1),
2752 timeval_str_buf(&abs_timeout, false, true, &tvbuf2),
2754 file_id_str_buf(id, &fbuf));
2756 open_rec = talloc_zero(NULL, struct deferred_open_record);
2757 if (open_rec == NULL) {
2759 exit_server("talloc failed");
2762 watch_state = talloc(open_rec, struct defer_open_state);
2763 if (watch_state == NULL) {
2764 exit_server("talloc failed");
2766 watch_state->xconn = req->xconn;
2767 watch_state->mid = req->mid;
2769 DBG_DEBUG("defering mid %" PRIu64 "\n", req->mid);
2771 watch_req = share_mode_watch_send(
2775 (struct server_id){0});
2776 if (watch_req == NULL) {
2777 exit_server("Could not watch share mode record");
2779 tevent_req_set_callback(watch_req, defer_open_done, watch_state);
2781 ok = tevent_req_set_endtime(watch_req, req->sconn->ev_ctx, abs_timeout);
2783 exit_server("tevent_req_set_endtime failed");
2786 ok = push_deferred_open_message_smb(req, timeout, id, open_rec);
2789 exit_server("push_deferred_open_message_smb failed");
2793 static void defer_open_done(struct tevent_req *req)
2795 struct defer_open_state *state = tevent_req_callback_data(
2796 req, struct defer_open_state);
2800 status = share_mode_watch_recv(req, NULL, NULL);
2802 if (!NT_STATUS_IS_OK(status)) {
2803 DEBUG(5, ("dbwrap_watched_watch_recv returned %s\n",
2804 nt_errstr(status)));
2806 * Even if it failed, retry anyway. TODO: We need a way to
2807 * tell a re-scheduled open about that error.
2811 DEBUG(10, ("scheduling mid %llu\n", (unsigned long long)state->mid));
2813 ret = schedule_deferred_open_message_smb(state->xconn, state->mid);
2819 * Actually attempt the kernel oplock polling open.
2822 static void poll_open_fn(struct tevent_context *ev,
2823 struct tevent_timer *te,
2824 struct timeval current_time,
2827 struct deferred_open_record *open_rec = talloc_get_type_abort(
2828 private_data, struct deferred_open_record);
2831 TALLOC_FREE(open_rec->watch_req);
2833 ok = schedule_deferred_open_message_smb(
2834 open_rec->xconn, open_rec->mid);
2836 exit_server("schedule_deferred_open_message_smb failed");
2838 DBG_DEBUG("timer fired. Retrying open !\n");
2841 static void poll_open_done(struct tevent_req *subreq);
2844 * Reschedule an open for 1 second from now, if not timed out.
2846 static bool setup_poll_open(
2847 struct smb_request *req,
2848 struct share_mode_lock *lck,
2850 struct timeval max_timeout,
2851 struct timeval interval)
2854 struct deferred_open_record *open_rec = NULL;
2855 struct timeval endtime, next_interval;
2856 struct file_id_buf ftmp;
2858 if (request_timed_out(req, max_timeout)) {
2862 open_rec = talloc_zero(NULL, struct deferred_open_record);
2863 if (open_rec == NULL) {
2864 DBG_WARNING("talloc failed\n");
2867 open_rec->xconn = req->xconn;
2868 open_rec->mid = req->mid;
2871 * Make sure open_rec->te does not come later than the
2872 * request's maximum endtime.
2875 endtime = timeval_sum(&req->request_time, &max_timeout);
2876 next_interval = timeval_current_ofs(interval.tv_sec, interval.tv_usec);
2877 next_interval = timeval_min(&endtime, &next_interval);
2879 open_rec->te = tevent_add_timer(
2885 if (open_rec->te == NULL) {
2886 DBG_WARNING("tevent_add_timer failed\n");
2887 TALLOC_FREE(open_rec);
2892 open_rec->watch_req = share_mode_watch_send(
2896 (struct server_id) {0});
2897 if (open_rec->watch_req == NULL) {
2898 DBG_WARNING("share_mode_watch_send failed\n");
2899 TALLOC_FREE(open_rec);
2902 tevent_req_set_callback(
2903 open_rec->watch_req, poll_open_done, open_rec);
2906 ok = push_deferred_open_message_smb(req, max_timeout, id, open_rec);
2908 DBG_WARNING("push_deferred_open_message_smb failed\n");
2909 TALLOC_FREE(open_rec);
2913 DBG_DEBUG("poll request time [%s] mid [%" PRIu64 "] file_id [%s]\n",
2914 timeval_string(talloc_tos(), &req->request_time, false),
2916 file_id_str_buf(id, &ftmp));
2921 static void poll_open_done(struct tevent_req *subreq)
2923 struct deferred_open_record *open_rec = tevent_req_callback_data(
2924 subreq, struct deferred_open_record);
2928 status = share_mode_watch_recv(subreq, NULL, NULL);
2929 TALLOC_FREE(subreq);
2930 DBG_DEBUG("dbwrap_watched_watch_recv returned %s\n",
2933 ok = schedule_deferred_open_message_smb(
2934 open_rec->xconn, open_rec->mid);
2936 exit_server("schedule_deferred_open_message_smb failed");
2940 bool defer_smb1_sharing_violation(struct smb_request *req)
2945 if (!lp_defer_sharing_violations()) {
2950 * Try every 200msec up to (by default) one second. To be
2951 * precise, according to behaviour note <247> in [MS-CIFS],
2952 * the server tries 5 times. But up to one second should be
2956 timeout_usecs = lp_parm_int(
2960 SHARING_VIOLATION_USEC_WAIT);
2962 ok = setup_poll_open(
2965 (struct file_id) {0},
2966 (struct timeval) { .tv_usec = timeout_usecs },
2967 (struct timeval) { .tv_usec = 200000 });
2971 /****************************************************************************
2972 On overwrite open ensure that the attributes match.
2973 ****************************************************************************/
2975 static bool open_match_attributes(connection_struct *conn,
2976 uint32_t old_dos_attr,
2977 uint32_t new_dos_attr,
2978 mode_t new_unx_mode,
2979 mode_t *returned_unx_mode)
2981 uint32_t noarch_old_dos_attr, noarch_new_dos_attr;
2983 noarch_old_dos_attr = (old_dos_attr & ~FILE_ATTRIBUTE_ARCHIVE);
2984 noarch_new_dos_attr = (new_dos_attr & ~FILE_ATTRIBUTE_ARCHIVE);
2986 if((noarch_old_dos_attr == 0 && noarch_new_dos_attr != 0) ||
2987 (noarch_old_dos_attr != 0 && ((noarch_old_dos_attr & noarch_new_dos_attr) == noarch_old_dos_attr))) {
2988 *returned_unx_mode = new_unx_mode;
2990 *returned_unx_mode = (mode_t)0;
2993 DEBUG(10,("open_match_attributes: old_dos_attr = 0x%x, "
2994 "new_dos_attr = 0x%x "
2995 "returned_unx_mode = 0%o\n",
2996 (unsigned int)old_dos_attr,
2997 (unsigned int)new_dos_attr,
2998 (unsigned int)*returned_unx_mode ));
3000 /* If we're mapping SYSTEM and HIDDEN ensure they match. */
3001 if (lp_map_system(SNUM(conn)) || lp_store_dos_attributes(SNUM(conn))) {
3002 if ((old_dos_attr & FILE_ATTRIBUTE_SYSTEM) &&
3003 !(new_dos_attr & FILE_ATTRIBUTE_SYSTEM)) {
3007 if (lp_map_hidden(SNUM(conn)) || lp_store_dos_attributes(SNUM(conn))) {
3008 if ((old_dos_attr & FILE_ATTRIBUTE_HIDDEN) &&
3009 !(new_dos_attr & FILE_ATTRIBUTE_HIDDEN)) {
3016 static void schedule_defer_open(struct share_mode_lock *lck,
3018 struct smb_request *req)
3020 /* This is a relative time, added to the absolute
3021 request_time value to get the absolute timeout time.
3022 Note that if this is the second or greater time we enter
3023 this codepath for this particular request mid then
3024 request_time is left as the absolute time of the *first*
3025 time this request mid was processed. This is what allows
3026 the request to eventually time out. */
3028 struct timeval timeout;
3030 /* Normally the smbd we asked should respond within
3031 * OPLOCK_BREAK_TIMEOUT seconds regardless of whether
3032 * the client did, give twice the timeout as a safety
3033 * measure here in case the other smbd is stuck
3034 * somewhere else. */
3036 timeout = timeval_set(OPLOCK_BREAK_TIMEOUT*2, 0);
3038 if (request_timed_out(req, timeout)) {
3042 defer_open(lck, timeout, req, id);
3045 /****************************************************************************
3046 Reschedule an open call that went asynchronous.
3047 ****************************************************************************/
3049 static void schedule_async_open_timer(struct tevent_context *ev,
3050 struct tevent_timer *te,
3051 struct timeval current_time,
3054 exit_server("async open timeout");
3057 static void schedule_async_open(struct smb_request *req)
3059 struct deferred_open_record *open_rec = NULL;
3060 struct timeval timeout = timeval_set(20, 0);
3063 if (request_timed_out(req, timeout)) {
3067 open_rec = talloc_zero(NULL, struct deferred_open_record);
3068 if (open_rec == NULL) {
3069 exit_server("deferred_open_record_create failed");
3071 open_rec->async_open = true;
3073 ok = push_deferred_open_message_smb(
3074 req, timeout, (struct file_id){0}, open_rec);
3076 exit_server("push_deferred_open_message_smb failed");
3079 open_rec->te = tevent_add_timer(req->sconn->ev_ctx,
3081 timeval_current_ofs(20, 0),
3082 schedule_async_open_timer,
3084 if (open_rec->te == NULL) {
3085 exit_server("tevent_add_timer failed");
3089 /****************************************************************************
3090 Work out what access_mask to use from what the client sent us.
3091 ****************************************************************************/
3093 static NTSTATUS smbd_calculate_maximum_allowed_access(
3094 connection_struct *conn,
3095 struct files_struct *dirfsp,
3096 const struct smb_filename *smb_fname,
3098 uint32_t *p_access_mask)
3100 struct security_descriptor *sd;
3101 uint32_t access_granted;
3104 SMB_ASSERT(dirfsp == conn->cwd_fsp);
3106 if (!use_privs && (get_current_uid(conn) == (uid_t)0)) {
3107 *p_access_mask |= FILE_GENERIC_ALL;
3108 return NT_STATUS_OK;
3111 status = SMB_VFS_GET_NT_ACL_AT(conn,
3120 if (NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
3122 * File did not exist
3124 *p_access_mask = FILE_GENERIC_ALL;
3125 return NT_STATUS_OK;
3127 if (!NT_STATUS_IS_OK(status)) {
3128 DEBUG(10,("Could not get acl on file %s: %s\n",
3129 smb_fname_str_dbg(smb_fname),
3130 nt_errstr(status)));
3131 return NT_STATUS_ACCESS_DENIED;
3135 * If we can access the path to this file, by
3136 * default we have FILE_READ_ATTRIBUTES from the
3137 * containing directory. See the section:
3138 * "Algorithm to Check Access to an Existing File"
3141 * se_file_access_check()
3142 * also takes care of owner WRITE_DAC and READ_CONTROL.
3144 status = se_file_access_check(sd,
3145 get_current_nttok(conn),
3147 (*p_access_mask & ~FILE_READ_ATTRIBUTES),
3152 if (!NT_STATUS_IS_OK(status)) {
3153 DEBUG(10, ("Access denied on file %s: "
3154 "when calculating maximum access\n",
3155 smb_fname_str_dbg(smb_fname)));
3156 return NT_STATUS_ACCESS_DENIED;
3158 *p_access_mask = (access_granted | FILE_READ_ATTRIBUTES);
3160 if (!(access_granted & DELETE_ACCESS)) {
3161 if (can_delete_file_in_directory(conn,
3165 *p_access_mask |= DELETE_ACCESS;
3169 return NT_STATUS_OK;
3172 NTSTATUS smbd_calculate_access_mask(connection_struct *conn,
3173 struct files_struct *dirfsp,
3174 const struct smb_filename *smb_fname,
3176 uint32_t access_mask,
3177 uint32_t *access_mask_out)
3180 uint32_t orig_access_mask = access_mask;
3181 uint32_t rejected_share_access;
3183 SMB_ASSERT(dirfsp == conn->cwd_fsp);
3185 if (access_mask & SEC_MASK_INVALID) {
3186 DBG_DEBUG("access_mask [%8x] contains invalid bits\n",
3188 return NT_STATUS_ACCESS_DENIED;
3192 * Convert GENERIC bits to specific bits.
3195 se_map_generic(&access_mask, &file_generic_mapping);
3197 /* Calculate MAXIMUM_ALLOWED_ACCESS if requested. */
3198 if (access_mask & MAXIMUM_ALLOWED_ACCESS) {
3200 status = smbd_calculate_maximum_allowed_access(conn,
3206 if (!NT_STATUS_IS_OK(status)) {
3210 access_mask &= conn->share_access;
3213 rejected_share_access = access_mask & ~(conn->share_access);
3215 if (rejected_share_access) {
3216 DEBUG(10, ("smbd_calculate_access_mask: Access denied on "
3217 "file %s: rejected by share access mask[0x%08X] "
3218 "orig[0x%08X] mapped[0x%08X] reject[0x%08X]\n",
3219 smb_fname_str_dbg(smb_fname),
3221 orig_access_mask, access_mask,
3222 rejected_share_access));
3223 return NT_STATUS_ACCESS_DENIED;
3226 *access_mask_out = access_mask;
3227 return NT_STATUS_OK;
3230 /****************************************************************************
3231 Remove the deferred open entry under lock.
3232 ****************************************************************************/
3234 /****************************************************************************
3235 Return true if this is a state pointer to an asynchronous create.
3236 ****************************************************************************/
3238 bool is_deferred_open_async(const struct deferred_open_record *rec)
3240 return rec->async_open;
3243 static bool clear_ads(uint32_t create_disposition)
3247 switch (create_disposition) {
3248 case FILE_SUPERSEDE:
3249 case FILE_OVERWRITE_IF:
3250 case FILE_OVERWRITE:
3259 static int disposition_to_open_flags(uint32_t create_disposition)
3264 * Currently we're using FILE_SUPERSEDE as the same as
3265 * FILE_OVERWRITE_IF but they really are
3266 * different. FILE_SUPERSEDE deletes an existing file
3267 * (requiring delete access) then recreates it.
3270 switch (create_disposition) {
3271 case FILE_SUPERSEDE:
3272 case FILE_OVERWRITE_IF:
3274 * If file exists replace/overwrite. If file doesn't
3277 ret = O_CREAT|O_TRUNC;
3282 * If file exists open. If file doesn't exist error.
3287 case FILE_OVERWRITE:
3289 * If file exists overwrite. If file doesn't exist
3297 * If file exists error. If file doesn't exist create.
3299 ret = O_CREAT|O_EXCL;
3304 * If file exists open. If file doesn't exist create.
3312 static int calculate_open_access_flags(uint32_t access_mask,
3313 uint32_t private_flags)
3315 bool need_write, need_read;
3318 * Note that we ignore the append flag as append does not
3319 * mean the same thing under DOS and Unix.
3322 need_write = (access_mask & (FILE_WRITE_DATA | FILE_APPEND_DATA));
3327 /* DENY_DOS opens are always underlying read-write on the
3328 file handle, no matter what the requested access mask
3332 ((private_flags & NTCREATEX_OPTIONS_PRIVATE_DENY_DOS) ||
3333 access_mask & (FILE_READ_ATTRIBUTES|FILE_READ_DATA|
3334 FILE_READ_EA|FILE_EXECUTE));
3342 /****************************************************************************
3343 Open a file with a share mode. Passed in an already created files_struct *.
3344 ****************************************************************************/
3346 static NTSTATUS open_file_ntcreate(connection_struct *conn,
3347 struct smb_request *req,
3348 uint32_t access_mask, /* access bits (FILE_READ_DATA etc.) */
3349 uint32_t share_access, /* share constants (FILE_SHARE_READ etc) */
3350 uint32_t create_disposition, /* FILE_OPEN_IF etc. */
3351 uint32_t create_options, /* options such as delete on close. */
3352 uint32_t new_dos_attributes, /* attributes used for new file. */
3353 int oplock_request, /* internal Samba oplock codes. */
3354 const struct smb2_lease *lease,
3355 /* Information (FILE_EXISTS etc.) */
3356 uint32_t private_flags, /* Samba specific flags. */
3360 struct smb_filename *smb_fname = fsp->fsp_name;
3363 bool file_existed = VALID_STAT(smb_fname->st);
3364 bool def_acl = False;
3365 bool posix_open = False;
3366 bool new_file_created = False;
3367 bool first_open_attempt = true;
3368 NTSTATUS fsp_open = NT_STATUS_ACCESS_DENIED;
3369 mode_t new_unx_mode = (mode_t)0;
3370 mode_t unx_mode = (mode_t)0;
3372 uint32_t existing_dos_attributes = 0;
3373 struct share_mode_lock *lck = NULL;
3374 uint32_t open_access_mask = access_mask;
3376 struct smb_filename *parent_dir_fname = NULL;
3377 SMB_STRUCT_STAT saved_stat = smb_fname->st;
3378 struct timespec old_write_time;
3380 bool setup_poll = false;
3383 if (conn->printer) {
3385 * Printers are handled completely differently.
3386 * Most of the passed parameters are ignored.
3390 *pinfo = FILE_WAS_CREATED;
3393 DEBUG(10, ("open_file_ntcreate: printer open fname=%s\n",
3394 smb_fname_str_dbg(smb_fname)));
3397 DEBUG(0,("open_file_ntcreate: printer open without "
3398 "an SMB request!\n"));
3399 return NT_STATUS_INTERNAL_ERROR;
3402 return print_spool_open(fsp, smb_fname->base_name,
3406 ok = parent_smb_fname(talloc_tos(),
3411 return NT_STATUS_NO_MEMORY;
3414 if (new_dos_attributes & FILE_FLAG_POSIX_SEMANTICS) {
3416 unx_mode = (mode_t)(new_dos_attributes & ~FILE_FLAG_POSIX_SEMANTICS);
3417 new_dos_attributes = 0;
3419 /* Windows allows a new file to be created and
3420 silently removes a FILE_ATTRIBUTE_DIRECTORY
3421 sent by the client. Do the same. */
3423 new_dos_attributes &= ~FILE_ATTRIBUTE_DIRECTORY;
3425 /* We add FILE_ATTRIBUTE_ARCHIVE to this as this mode is only used if the file is
3427 unx_mode = unix_mode(conn, new_dos_attributes | FILE_ATTRIBUTE_ARCHIVE,
3428 smb_fname, parent_dir_fname);
3431 DEBUG(10, ("open_file_ntcreate: fname=%s, dos_attrs=0x%x "
3432 "access_mask=0x%x share_access=0x%x "
3433 "create_disposition = 0x%x create_options=0x%x "
3434 "unix mode=0%o oplock_request=%d private_flags = 0x%x\n",
3435 smb_fname_str_dbg(smb_fname), new_dos_attributes,
3436 access_mask, share_access, create_disposition,
3437 create_options, (unsigned int)unx_mode, oplock_request,
3438 (unsigned int)private_flags));
3441 /* Ensure req == NULL means INTERNAL_OPEN_ONLY */
3442 SMB_ASSERT(oplock_request == INTERNAL_OPEN_ONLY);
3444 /* And req != NULL means no INTERNAL_OPEN_ONLY */
3445 SMB_ASSERT(((oplock_request & INTERNAL_OPEN_ONLY) == 0));
3449 * Only non-internal opens can be deferred at all
3453 struct deferred_open_record *open_rec;
3454 if (get_deferred_open_message_state(req, NULL, &open_rec)) {
3456 /* If it was an async create retry, the file
3459 if (is_deferred_open_async(open_rec)) {
3460 SET_STAT_INVALID(smb_fname->st);
3461 file_existed = false;
3464 /* Ensure we don't reprocess this message. */
3465 remove_deferred_open_message_smb(req->xconn, req->mid);
3467 first_open_attempt = false;
3472 new_dos_attributes &= SAMBA_ATTRIBUTES_MASK;
3475 * Only use stored DOS attributes for checks
3476 * against requested attributes (below via
3477 * open_match_attributes()), cf bug #11992
3478 * for details. -slow
3482 status = SMB_VFS_GET_DOS_ATTRIBUTES(conn, smb_fname, &attr);
3483 if (NT_STATUS_IS_OK(status)) {
3484 existing_dos_attributes = attr;
3489 /* ignore any oplock requests if oplocks are disabled */
3490 if (!lp_oplocks(SNUM(conn)) ||
3491 IS_VETO_OPLOCK_PATH(conn, smb_fname->base_name)) {
3492 /* Mask off everything except the private Samba bits. */
3493 oplock_request &= SAMBA_PRIVATE_OPLOCK_MASK;
3496 /* this is for OS/2 long file names - say we don't support them */
3497 if (req != NULL && !req->posix_pathnames &&
3498 strstr(smb_fname->base_name,".+,;=[].")) {
3499 /* OS/2 Workplace shell fix may be main code stream in a later
3501 DEBUG(5,("open_file_ntcreate: OS/2 long filenames are not "
3503 if (use_nt_status()) {
3504 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3506 return NT_STATUS_DOS(ERRDOS, ERRcannotopen);
3509 switch( create_disposition ) {
3511 /* If file exists open. If file doesn't exist error. */
3512 if (!file_existed) {
3513 DEBUG(5,("open_file_ntcreate: FILE_OPEN "
3514 "requested for file %s and file "
3516 smb_fname_str_dbg(smb_fname)));
3518 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3522 case FILE_OVERWRITE:
3523 /* If file exists overwrite. If file doesn't exist
3525 if (!file_existed) {
3526 DEBUG(5,("open_file_ntcreate: FILE_OVERWRITE "
3527 "requested for file %s and file "
3529 smb_fname_str_dbg(smb_fname) ));
3531 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3536 /* If file exists error. If file doesn't exist
3539 DEBUG(5,("open_file_ntcreate: FILE_CREATE "
3540 "requested for file %s and file "
3541 "already exists.\n",
3542 smb_fname_str_dbg(smb_fname)));
3543 if (S_ISDIR(smb_fname->st.st_ex_mode)) {
3548 return map_nt_error_from_unix(errno);
3552 case FILE_SUPERSEDE:
3553 case FILE_OVERWRITE_IF:
3557 return NT_STATUS_INVALID_PARAMETER;
3560 flags2 = disposition_to_open_flags(create_disposition);
3562 /* We only care about matching attributes on file exists and
3565 if (!posix_open && file_existed &&
3566 ((create_disposition == FILE_OVERWRITE) ||
3567 (create_disposition == FILE_OVERWRITE_IF))) {
3568 if (!open_match_attributes(conn, existing_dos_attributes,
3570 unx_mode, &new_unx_mode)) {
3571 DEBUG(5,("open_file_ntcreate: attributes mismatch "
3572 "for file %s (%x %x) (0%o, 0%o)\n",
3573 smb_fname_str_dbg(smb_fname),
3574 existing_dos_attributes,
3576 (unsigned int)smb_fname->st.st_ex_mode,
3577 (unsigned int)unx_mode ));
3579 return NT_STATUS_ACCESS_DENIED;
3583 status = smbd_calculate_access_mask(conn,
3589 if (!NT_STATUS_IS_OK(status)) {
3590 DEBUG(10, ("open_file_ntcreate: smbd_calculate_access_mask "
3591 "on file %s returned %s\n",
3592 smb_fname_str_dbg(smb_fname), nt_errstr(status)));
3596 open_access_mask = access_mask;
3598 if (flags2 & O_TRUNC) {
3599 open_access_mask |= FILE_WRITE_DATA; /* This will cause oplock breaks. */
3604 * stat opens on existing files don't get oplocks.
3605 * They can get leases.
3607 * Note that we check for stat open on the *open_access_mask*,
3608 * i.e. the access mask we actually used to do the open,
3609 * not the one the client asked for (which is in
3610 * fsp->access_mask). This is due to the fact that
3611 * FILE_OVERWRITE and FILE_OVERWRITE_IF add in O_TRUNC,
3612 * which adds FILE_WRITE_DATA to open_access_mask.
3614 if (is_oplock_stat_open(open_access_mask) && lease == NULL) {
3615 oplock_request = NO_OPLOCK;
3619 DEBUG(10, ("open_file_ntcreate: fname=%s, after mapping "
3620 "access_mask=0x%x\n", smb_fname_str_dbg(smb_fname),
3624 * Note that we ignore the append flag as append does not
3625 * mean the same thing under DOS and Unix.
3628 flags = calculate_open_access_flags(access_mask, private_flags);
3631 * Currently we only look at FILE_WRITE_THROUGH for create options.
3635 if ((create_options & FILE_WRITE_THROUGH) && lp_strict_sync(SNUM(conn))) {
3640 if (posix_open && (access_mask & FILE_APPEND_DATA)) {
3644 if (!posix_open && !CAN_WRITE(conn)) {
3646 * We should really return a permission denied error if either
3647 * O_CREAT or O_TRUNC are set, but for compatibility with
3648 * older versions of Samba we just AND them out.
3650 flags2 &= ~(O_CREAT|O_TRUNC);
3654 * With kernel oplocks the open breaking an oplock
3655 * blocks until the oplock holder has given up the
3656 * oplock or closed the file. We prevent this by always
3657 * trying to open the file with O_NONBLOCK (see "man
3660 * If a process that doesn't use the smbd open files
3661 * database or communication methods holds a kernel
3662 * oplock we must periodically poll for available open
3665 flags2 |= O_NONBLOCK;
3668 * Ensure we can't write on a read-only share or file.
3671 if (flags != O_RDONLY && file_existed &&
3672 (!CAN_WRITE(conn) || IS_DOS_READONLY(existing_dos_attributes))) {
3673 DEBUG(5,("open_file_ntcreate: write access requested for "
3674 "file %s on read only %s\n",
3675 smb_fname_str_dbg(smb_fname),
3676 !CAN_WRITE(conn) ? "share" : "file" ));
3678 return NT_STATUS_ACCESS_DENIED;
3681 if (VALID_STAT(smb_fname->st)) {
3683 * Only try and create a file id before open
3684 * for an existing file. For a file being created
3685 * this won't do anything useful until the file
3686 * exists and has a valid stat struct.
3688 fsp->file_id = vfs_file_id_from_sbuf(conn, &smb_fname->st);
3690 fsp->fh->private_options = private_flags;
3691 fsp->access_mask = open_access_mask; /* We change this to the
3692 * requested access_mask after
3693 * the open is done. */
3695 fsp->posix_flags |= FSP_POSIX_FLAGS_ALL;
3698 if ((create_options & FILE_DELETE_ON_CLOSE) &&
3699 (flags2 & O_CREAT) &&
3701 /* Delete on close semantics for new files. */
3702 status = can_set_delete_on_close(fsp,
3703 new_dos_attributes);
3704 if (!NT_STATUS_IS_OK(status)) {
3711 * Ensure we pay attention to default ACLs on directories if required.
3714 if ((flags2 & O_CREAT) && lp_inherit_acls(SNUM(conn)) &&
3715 (def_acl = directory_has_default_acl(conn,
3719 unx_mode = (0777 & lp_create_mask(SNUM(conn)));
3722 DEBUG(4,("calling open_file with flags=0x%X flags2=0x%X mode=0%o, "
3723 "access_mask = 0x%x, open_access_mask = 0x%x\n",
3724 (unsigned int)flags, (unsigned int)flags2,
3725 (unsigned int)unx_mode, (unsigned int)access_mask,
3726 (unsigned int)open_access_mask));
3728 fsp_open = open_file(fsp,
3736 if (NT_STATUS_EQUAL(fsp_open, NT_STATUS_NETWORK_BUSY)) {
3737 if (file_existed && S_ISFIFO(fsp->fsp_name->st.st_ex_mode)) {
3738 DEBUG(10, ("FIFO busy\n"));
3739 return NT_STATUS_NETWORK_BUSY;
3742 DEBUG(10, ("Internal open busy\n"));
3743 return NT_STATUS_NETWORK_BUSY;
3746 * This handles the kernel oplock case:
3748 * the file has an active kernel oplock and the open() returned
3749 * EWOULDBLOCK/EAGAIN which maps to NETWORK_BUSY.
3751 * "Samba locking.tdb oplocks" are handled below after acquiring
3752 * the sharemode lock with get_share_mode_lock().
3757 if (NT_STATUS_EQUAL(fsp_open, NT_STATUS_RETRY)) {
3759 * EINTR from the open(2) syscall. Just setup a retry
3760 * in a bit. We can't use the sys_write() tight retry
3761 * loop here, as we might have to actually deal with
3762 * lease-break signals to avoid a deadlock.
3769 * From here on we assume this is an oplock break triggered
3772 lck = get_existing_share_mode_lock(talloc_tos(), fsp->file_id);
3774 if ((lck != NULL) && !validate_oplock_types(lck)) {
3775 smb_panic("validate_oplock_types failed");
3779 * Retry once a second. If there's a share_mode_lock
3780 * around, also wait for it in case it was smbd
3781 * holding that kernel oplock that can quickly tell us
3782 * the oplock got removed.
3789 timeval_set(OPLOCK_BREAK_TIMEOUT*2, 0),
3794 return NT_STATUS_SHARING_VIOLATION;
3797 if (!NT_STATUS_IS_OK(fsp_open)) {
3798 bool wait_for_aio = NT_STATUS_EQUAL(
3799 fsp_open, NT_STATUS_MORE_PROCESSING_REQUIRED);
3801 schedule_async_open(req);
3806 if (new_file_created) {
3808 * As we atomically create using O_CREAT|O_EXCL,
3809 * then if new_file_created is true, then
3810 * file_existed *MUST* have been false (even
3811 * if the file was previously detected as being
3814 file_existed = false;
3817 if (file_existed && !check_same_dev_ino(&saved_stat, &smb_fname->st)) {
3819 * The file did exist, but some other (local or NFS)
3820 * process either renamed/unlinked and re-created the
3821 * file with different dev/ino after we walked the path,
3822 * but before we did the open. We could retry the
3823 * open but it's a rare enough case it's easier to
3824 * just fail the open to prevent creating any problems
3825 * in the open file db having the wrong dev/ino key.
3828 DBG_WARNING("file %s - dev/ino mismatch. "
3829 "Old (dev=%ju, ino=%ju). "
3830 "New (dev=%ju, ino=%ju). Failing open "
3831 "with NT_STATUS_ACCESS_DENIED.\n",
3832 smb_fname_str_dbg(smb_fname),
3833 (uintmax_t)saved_stat.st_ex_dev,
3834 (uintmax_t)saved_stat.st_ex_ino,
3835 (uintmax_t)smb_fname->st.st_ex_dev,
3836 (uintmax_t)smb_fname->st.st_ex_ino);
3837 return NT_STATUS_ACCESS_DENIED;
3840 old_write_time = smb_fname->st.st_ex_mtime;
3843 * Deal with the race condition where two smbd's detect the
3844 * file doesn't exist and do the create at the same time. One
3845 * of them will win and set a share mode, the other (ie. this
3846 * one) should check if the requested share mode for this
3847 * create is allowed.
3851 * Now the file exists and fsp is successfully opened,
3852 * fsp->dev and fsp->inode are valid and should replace the
3853 * dev=0,inode=0 from a non existent file. Spotted by
3854 * Nadav Danieli <nadavd@exanet.com>. JRA.
3859 lck = get_share_mode_lock(talloc_tos(), id,
3861 smb_fname, &old_write_time);
3864 DEBUG(0, ("open_file_ntcreate: Could not get share "
3865 "mode lock for %s\n",
3866 smb_fname_str_dbg(smb_fname)));
3868 return NT_STATUS_SHARING_VIOLATION;
3871 /* Get the types we need to examine. */
3872 if (!validate_oplock_types(lck)) {
3873 smb_panic("validate_oplock_types failed");
3876 if (has_delete_on_close(lck, fsp->name_hash)) {
3879 return NT_STATUS_DELETE_PENDING;
3882 status = handle_share_mode_lease(
3890 first_open_attempt);
3892 if (NT_STATUS_EQUAL(status, NT_STATUS_RETRY)) {
3893 schedule_defer_open(lck, fsp->file_id, req);
3896 return NT_STATUS_SHARING_VIOLATION;
3899 if (!NT_STATUS_IS_OK(status)) {
3906 struct share_mode_data *d = lck->data;
3907 uint16_t new_flags = share_mode_flags_restrict(
3908 d->flags, access_mask, share_access, UINT32_MAX);
3910 if (new_flags != d->flags) {
3911 d->flags = new_flags;
3916 ok = set_share_mode(
3919 get_current_uid(fsp->conn),
3925 if (fsp->oplock_type == LEASE_OPLOCK) {
3926 status = remove_lease_if_stale(
3928 fsp_client_guid(fsp),
3929 &fsp->lease->lease.lease_key);
3930 if (!NT_STATUS_IS_OK(status)) {
3931 DBG_WARNING("remove_lease_if_stale "
3936 return NT_STATUS_NO_MEMORY;
3939 /* Should we atomically (to the client at least) truncate ? */
3940 if ((!new_file_created) &&
3941 (flags2 & O_TRUNC) &&
3942 (S_ISREG(fsp->fsp_name->st.st_ex_mode))) {
3945 ret = SMB_VFS_FTRUNCATE(fsp, 0);
3947 status = map_nt_error_from_unix(errno);
3948 del_share_mode(lck, fsp);
3953 notify_fname(fsp->conn, NOTIFY_ACTION_MODIFIED,
3954 FILE_NOTIFY_CHANGE_SIZE
3955 | FILE_NOTIFY_CHANGE_ATTRIBUTES,
3956 fsp->fsp_name->base_name);
3960 * We have the share entry *locked*.....
3963 /* Delete streams if create_disposition requires it */
3964 if (!new_file_created && clear_ads(create_disposition) &&
3965 !is_ntfs_stream_smb_fname(smb_fname)) {
3966 status = delete_all_streams(conn, smb_fname);
3967 if (!NT_STATUS_IS_OK(status)) {
3968 del_share_mode(lck, fsp);
3975 if (fsp->fh->fd != -1 && lp_kernel_share_modes(SNUM(conn))) {
3978 * Beware: streams implementing VFS modules may
3979 * implement streams in a way that fsp will have the
3980 * basefile open in the fsp fd, so lacking a distinct
3981 * fd for the stream kernel_flock will apply on the
3982 * basefile which is wrong. The actual check is
3983 * deferred to the VFS module implementing the
3984 * kernel_flock call.
3986 ret_flock = SMB_VFS_KERNEL_FLOCK(fsp, share_access, access_mask);
3987 if(ret_flock == -1 ){
3989 del_share_mode(lck, fsp);
3993 return NT_STATUS_SHARING_VIOLATION;
3996 fsp->fsp_flags.kernel_share_modes_taken = true;
4000 * At this point onwards, we can guarantee that the share entry
4001 * is locked, whether we created the file or not, and that the
4002 * deny mode is compatible with all current opens.
4006 * According to Samba4, SEC_FILE_READ_ATTRIBUTE is always granted,
4007 * but we don't have to store this - just ignore it on access check.
4009 if (conn->sconn->using_smb2) {
4011 * SMB2 doesn't return it (according to Microsoft tests).
4012 * Test Case: TestSuite_ScenarioNo009GrantedAccessTestS0
4013 * File created with access = 0x7 (Read, Write, Delete)
4014 * Query Info on file returns 0x87 (Read, Write, Delete, Read Attributes)
4016 fsp->access_mask = access_mask;
4018 /* But SMB1 does. */
4019 fsp->access_mask = access_mask | FILE_READ_ATTRIBUTES;
4022 if (new_file_created) {
4023 info = FILE_WAS_CREATED;
4025 if (flags2 & O_TRUNC) {
4026 info = FILE_WAS_OVERWRITTEN;
4028 info = FILE_WAS_OPENED;
4036 /* Handle strange delete on close create semantics. */
4037 if (create_options & FILE_DELETE_ON_CLOSE) {
4038 if (!new_file_created) {
4039 status = can_set_delete_on_close(fsp,
4040 existing_dos_attributes);
4042 if (!NT_STATUS_IS_OK(status)) {
4043 /* Remember to delete the mode we just added. */
4044 del_share_mode(lck, fsp);
4050 /* Note that here we set the *initial* delete on close flag,
4051 not the regular one. The magic gets handled in close. */
4052 fsp->fsp_flags.initial_delete_on_close = true;
4056 * If we created a file and it's not a stream, this is the point where
4057 * we set the itime (aka invented time) that get's stored in the DOS
4058 * attribute xattr. The value is going to be either what the filesystem
4059 * provided or a copy of the creation date.
4061 * Either way, we turn the itime into a File-ID, unless the filesystem
4062 * provided one (unlikely).
4064 if (info == FILE_WAS_CREATED && !is_named_stream(smb_fname)) {
4065 smb_fname->st.st_ex_iflags &= ~ST_EX_IFLAG_CALCULATED_ITIME;
4067 if (lp_store_dos_attributes(SNUM(conn)) &&
4068 smb_fname->st.st_ex_iflags & ST_EX_IFLAG_CALCULATED_FILE_ID)
4072 file_id = make_file_id_from_itime(&smb_fname->st);
4073 update_stat_ex_file_id(&smb_fname->st, file_id);
4077 if (info != FILE_WAS_OPENED) {
4078 /* Overwritten files should be initially set as archive */
4079 if ((info == FILE_WAS_OVERWRITTEN && lp_map_archive(SNUM(conn))) ||
4080 lp_store_dos_attributes(SNUM(conn))) {
4081 (void)dos_mode(conn, smb_fname);
4083 if (file_set_dosmode(conn, smb_fname,
4084 new_dos_attributes | FILE_ATTRIBUTE_ARCHIVE,
4085 parent_dir_fname, true) == 0) {
4086 unx_mode = smb_fname->st.st_ex_mode;
4092 /* Determine sparse flag. */
4094 /* POSIX opens are sparse by default. */
4095 fsp->fsp_flags.is_sparse = true;
4097 fsp->fsp_flags.is_sparse =
4098 (existing_dos_attributes & FILE_ATTRIBUTE_SPARSE);
4102 * Take care of inherited ACLs on created files - if default ACL not
4106 if (!posix_open && new_file_created && !def_acl) {
4107 if (unx_mode != smb_fname->st.st_ex_mode) {
4108 int ret = SMB_VFS_FCHMOD(fsp, unx_mode);
4110 DBG_INFO("failed to reset "
4111 "attributes of file %s to 0%o\n",
4112 smb_fname_str_dbg(smb_fname),
4113 (unsigned int)unx_mode);
4117 } else if (new_unx_mode) {
4119 * We only get here in the case of:
4121 * a). Not a POSIX open.
4122 * b). File already existed.
4123 * c). File was overwritten.
4124 * d). Requested DOS attributes didn't match
4125 * the DOS attributes on the existing file.
4127 * In that case new_unx_mode has been set
4128 * equal to the calculated mode (including
4129 * possible inheritance of the mode from the
4130 * containing directory).
4132 * Note this mode was calculated with the
4133 * DOS attribute FILE_ATTRIBUTE_ARCHIVE added,
4134 * so the mode change here is suitable for
4135 * an overwritten file.
4138 if (new_unx_mode != smb_fname->st.st_ex_mode) {
4139 int ret = SMB_VFS_FCHMOD(fsp, new_unx_mode);
4141 DBG_INFO("failed to reset "
4142 "attributes of file %s to 0%o\n",
4143 smb_fname_str_dbg(smb_fname),
4144 (unsigned int)new_unx_mode);
4151 * Deal with other opens having a modified write time.
4153 struct timespec write_time = get_share_mode_write_time(lck);
4155 if (!is_omit_timespec(&write_time)) {
4156 update_stat_ex_mtime(&fsp->fsp_name->st, write_time);
4162 return NT_STATUS_OK;
4165 static NTSTATUS mkdir_internal(connection_struct *conn,
4166 struct smb_filename *smb_dname,
4167 uint32_t file_attributes)
4169 const struct loadparm_substitution *lp_sub =
4170 loadparm_s3_global_substitution();
4172 struct smb_filename *parent_dir_fname = NULL;
4174 bool posix_open = false;
4175 bool need_re_stat = false;
4176 uint32_t access_mask = SEC_DIR_ADD_SUBDIR;
4180 if (!CAN_WRITE(conn) || (access_mask & ~(conn->share_access))) {
4181 DEBUG(5,("mkdir_internal: failing share access "
4182 "%s\n", lp_servicename(talloc_tos(), lp_sub, SNUM(conn))));
4183 return NT_STATUS_ACCESS_DENIED;
4186 ok = parent_smb_fname(talloc_tos(),
4191 return NT_STATUS_NO_MEMORY;
4194 if (file_attributes & FILE_FLAG_POSIX_SEMANTICS) {
4196 mode = (mode_t)(file_attributes & ~FILE_FLAG_POSIX_SEMANTICS);
4198 mode = unix_mode(conn,
4199 FILE_ATTRIBUTE_DIRECTORY,
4204 status = check_parent_access(conn,
4208 if(!NT_STATUS_IS_OK(status)) {
4209 DEBUG(5,("mkdir_internal: check_parent_access "
4210 "on directory %s for path %s returned %s\n",
4211 smb_fname_str_dbg(parent_dir_fname),
4212 smb_dname->base_name,
4213 nt_errstr(status) ));
4217 ret = SMB_VFS_MKDIRAT(conn,
4222 return map_nt_error_from_unix(errno);
4225 /* Ensure we're checking for a symlink here.... */
4226 /* We don't want to get caught by a symlink racer. */
4228 if (SMB_VFS_LSTAT(conn, smb_dname) == -1) {
4229 DEBUG(2, ("Could not stat directory '%s' just created: %s\n",
4230 smb_fname_str_dbg(smb_dname), strerror(errno)));
4231 return map_nt_error_from_unix(errno);
4234 if (!S_ISDIR(smb_dname->st.st_ex_mode)) {
4235 DEBUG(0, ("Directory '%s' just created is not a directory !\n",
4236 smb_fname_str_dbg(smb_dname)));
4237 return NT_STATUS_NOT_A_DIRECTORY;
4240 smb_dname->st.st_ex_iflags &= ~ST_EX_IFLAG_CALCULATED_ITIME;
4242 if (lp_store_dos_attributes(SNUM(conn))) {
4243 if (smb_dname->st.st_ex_iflags & ST_EX_IFLAG_CALCULATED_FILE_ID)
4247 file_id = make_file_id_from_itime(&smb_dname->st);
4248 update_stat_ex_file_id(&smb_dname->st, file_id);
4252 file_set_dosmode(conn, smb_dname,
4253 file_attributes | FILE_ATTRIBUTE_DIRECTORY,
4254 parent_dir_fname, true);
4258 if (lp_inherit_permissions(SNUM(conn))) {
4259 inherit_access_posix_acl(conn, parent_dir_fname,
4261 need_re_stat = true;
4266 * Check if high bits should have been set,
4267 * then (if bits are missing): add them.
4268 * Consider bits automagically set by UNIX, i.e. SGID bit from parent
4271 if ((mode & ~(S_IRWXU|S_IRWXG|S_IRWXO)) &&
4272 (mode & ~smb_dname->st.st_ex_mode)) {
4273 SMB_VFS_CHMOD(conn, smb_dname,
4274 (smb_dname->st.st_ex_mode |
4275 (mode & ~smb_dname->st.st_ex_mode)));
4276 need_re_stat = true;
4280 /* Change the owner if required. */
4281 if (lp_inherit_owner(SNUM(conn)) != INHERIT_OWNER_NO) {
4282 change_dir_owner_to_parent(conn, parent_dir_fname,
4285 need_re_stat = true;
4289 if (SMB_VFS_LSTAT(conn, smb_dname) == -1) {
4290 DEBUG(2, ("Could not stat directory '%s' just created: %s\n",
4291 smb_fname_str_dbg(smb_dname), strerror(errno)));
4292 return map_nt_error_from_unix(errno);
4296 notify_fname(conn, NOTIFY_ACTION_ADDED, FILE_NOTIFY_CHANGE_DIR_NAME,
4297 smb_dname->base_name);
4299 return NT_STATUS_OK;
4302 /****************************************************************************
4303 Open a directory from an NT SMB call.
4304 ****************************************************************************/
4306 static NTSTATUS open_directory(connection_struct *conn,
4307 struct smb_request *req,
4308 uint32_t access_mask,
4309 uint32_t share_access,
4310 uint32_t create_disposition,
4311 uint32_t create_options,
4312 uint32_t file_attributes,
4314 struct files_struct *fsp)
4316 struct smb_filename *smb_dname = fsp->fsp_name;
4317 bool dir_existed = VALID_STAT(smb_dname->st);
4318 struct share_mode_lock *lck = NULL;
4320 struct timespec mtimespec;
4325 if (is_ntfs_stream_smb_fname(smb_dname)) {
4326 DEBUG(2, ("open_directory: %s is a stream name!\n",
4327 smb_fname_str_dbg(smb_dname)));
4328 return NT_STATUS_NOT_A_DIRECTORY;
4331 if (!(file_attributes & FILE_FLAG_POSIX_SEMANTICS)) {
4332 /* Ensure we have a directory attribute. */
4333 file_attributes |= FILE_ATTRIBUTE_DIRECTORY;
4336 DBG_INFO("opening directory %s, access_mask = 0x%"PRIx32", "
4337 "share_access = 0x%"PRIx32" create_options = 0x%"PRIx32", "
4338 "create_disposition = 0x%"PRIx32", "
4339 "file_attributes = 0x%"PRIx32"\n",
4340 smb_fname_str_dbg(smb_dname),
4347 status = smbd_calculate_access_mask(conn,
4353 if (!NT_STATUS_IS_OK(status)) {
4354 DEBUG(10, ("open_directory: smbd_calculate_access_mask "
4355 "on file %s returned %s\n",
4356 smb_fname_str_dbg(smb_dname),
4357 nt_errstr(status)));
4361 if ((access_mask & SEC_FLAG_SYSTEM_SECURITY) &&
4362 !security_token_has_privilege(get_current_nttok(conn),
4363 SEC_PRIV_SECURITY)) {
4364 DEBUG(10, ("open_directory: open on %s "
4365 "failed - SEC_FLAG_SYSTEM_SECURITY denied.\n",
4366 smb_fname_str_dbg(smb_dname)));
4367 return NT_STATUS_PRIVILEGE_NOT_HELD;
4370 switch( create_disposition ) {
4374 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
4377 info = FILE_WAS_OPENED;
4382 /* If directory exists error. If directory doesn't
4386 status = NT_STATUS_OBJECT_NAME_COLLISION;
4387 DEBUG(2, ("open_directory: unable to create "
4388 "%s. Error was %s\n",
4389 smb_fname_str_dbg(smb_dname),
4390 nt_errstr(status)));
4394 status = mkdir_internal(conn,
4398 if (!NT_STATUS_IS_OK(status)) {
4399 DEBUG(2, ("open_directory: unable to create "
4400 "%s. Error was %s\n",
4401 smb_fname_str_dbg(smb_dname),
4402 nt_errstr(status)));
4406 info = FILE_WAS_CREATED;
4411 * If directory exists open. If directory doesn't
4416 status = NT_STATUS_OK;
4417 info = FILE_WAS_OPENED;
4419 status = mkdir_internal(conn,
4423 if (NT_STATUS_IS_OK(status)) {
4424 info = FILE_WAS_CREATED;
4426 /* Cope with create race. */
4427 if (!NT_STATUS_EQUAL(status,
4428 NT_STATUS_OBJECT_NAME_COLLISION)) {
4429 DEBUG(2, ("open_directory: unable to create "
4430 "%s. Error was %s\n",
4431 smb_fname_str_dbg(smb_dname),
4432 nt_errstr(status)));
4437 * If mkdir_internal() returned
4438 * NT_STATUS_OBJECT_NAME_COLLISION
4439 * we still must lstat the path.
4442 if (SMB_VFS_LSTAT(conn, smb_dname)
4444 DEBUG(2, ("Could not stat "
4445 "directory '%s' just "
4450 return map_nt_error_from_unix(
4454 info = FILE_WAS_OPENED;
4460 case FILE_SUPERSEDE:
4461 case FILE_OVERWRITE:
4462 case FILE_OVERWRITE_IF:
4464 DEBUG(5,("open_directory: invalid create_disposition "
4465 "0x%x for directory %s\n",
4466 (unsigned int)create_disposition,
4467 smb_fname_str_dbg(smb_dname)));
4468 return NT_STATUS_INVALID_PARAMETER;
4471 if(!S_ISDIR(smb_dname->st.st_ex_mode)) {
4472 DEBUG(5,("open_directory: %s is not a directory !\n",
4473 smb_fname_str_dbg(smb_dname)));
4474 return NT_STATUS_NOT_A_DIRECTORY;
4477 if (info == FILE_WAS_OPENED) {
4478 status = smbd_check_access_rights(conn,
4483 if (!NT_STATUS_IS_OK(status)) {
4484 DEBUG(10, ("open_directory: smbd_check_access_rights on "
4485 "file %s failed with %s\n",
4486 smb_fname_str_dbg(smb_dname),
4487 nt_errstr(status)));
4493 * Setup the files_struct for it.
4496 fsp->file_id = vfs_file_id_from_sbuf(conn, &smb_dname->st);
4497 fsp->vuid = req ? req->vuid : UID_FIELD_INVALID;
4498 fsp->file_pid = req ? req->smbpid : 0;
4499 fsp->fsp_flags.can_lock = false;
4500 fsp->fsp_flags.can_read = false;
4501 fsp->fsp_flags.can_write = false;
4503 fsp->fh->private_options = 0;
4505 * According to Samba4, SEC_FILE_READ_ATTRIBUTE is always granted,
4507 fsp->access_mask = access_mask | FILE_READ_ATTRIBUTES;
4508 fsp->print_file = NULL;
4509 fsp->fsp_flags.modified = false;
4510 fsp->oplock_type = NO_OPLOCK;
4511 fsp->sent_oplock_break = NO_BREAK_SENT;
4512 fsp->fsp_flags.is_directory = true;
4513 if (file_attributes & FILE_FLAG_POSIX_SEMANTICS) {
4514 fsp->posix_flags |= FSP_POSIX_FLAGS_ALL;
4517 /* Don't store old timestamps for directory
4518 handles in the internal database. We don't
4519 update them in there if new objects
4520 are created in the directory. Currently
4521 we only update timestamps on file writes.
4524 mtimespec = make_omit_timespec();
4526 /* POSIX allows us to open a directory with O_RDONLY. */
4529 flags |= O_DIRECTORY;
4532 status = fd_open(fsp, flags, 0);
4533 if (!NT_STATUS_IS_OK(status)) {
4534 DBG_INFO("Could not open fd for "
4536 smb_fname_str_dbg(smb_dname),
4541 status = vfs_stat_fsp(fsp);
4542 if (!NT_STATUS_IS_OK(status)) {
4547 if(!S_ISDIR(fsp->fsp_name->st.st_ex_mode)) {
4548 DEBUG(5,("open_directory: %s is not a directory !\n",
4549 smb_fname_str_dbg(smb_dname)));
4551 return NT_STATUS_NOT_A_DIRECTORY;
4554 /* Ensure there was no race condition. We need to check
4555 * dev/inode but not permissions, as these can change
4557 if (!check_same_dev_ino(&smb_dname->st, &fsp->fsp_name->st)) {
4558 DEBUG(5,("open_directory: stat struct differs for "
4560 smb_fname_str_dbg(smb_dname)));
4562 return NT_STATUS_ACCESS_DENIED;
4565 lck = get_share_mode_lock(talloc_tos(), fsp->file_id,
4566 conn->connectpath, smb_dname,
4570 DEBUG(0, ("open_directory: Could not get share mode lock for "
4571 "%s\n", smb_fname_str_dbg(smb_dname)));
4573 return NT_STATUS_SHARING_VIOLATION;
4576 if (has_delete_on_close(lck, fsp->name_hash)) {
4579 return NT_STATUS_DELETE_PENDING;
4582 status = open_mode_check(conn, lck,
4583 access_mask, share_access);
4585 if (!NT_STATUS_IS_OK(status)) {
4592 struct share_mode_data *d = lck->data;
4593 uint16_t new_flags = share_mode_flags_restrict(
4594 d->flags, access_mask, share_access, UINT32_MAX);
4596 if (new_flags != d->flags) {
4597 d->flags = new_flags;
4602 ok = set_share_mode(
4605 get_current_uid(conn),
4613 return NT_STATUS_NO_MEMORY;
4616 /* For directories the delete on close bit at open time seems
4617 always to be honored on close... See test 19 in Samba4 BASE-DELETE. */
4618 if (create_options & FILE_DELETE_ON_CLOSE) {
4619 status = can_set_delete_on_close(fsp, 0);
4620 if (!NT_STATUS_IS_OK(status) && !NT_STATUS_EQUAL(status, NT_STATUS_DIRECTORY_NOT_EMPTY)) {
4621 del_share_mode(lck, fsp);
4627 if (NT_STATUS_IS_OK(status)) {
4628 /* Note that here we set the *initial* delete on close flag,
4629 not the regular one. The magic gets handled in close. */
4630 fsp->fsp_flags.initial_delete_on_close = true;
4636 * Deal with other opens having a modified write time. Is this
4637 * possible for directories?
4639 struct timespec write_time = get_share_mode_write_time(lck);
4641 if (!is_omit_timespec(&write_time)) {
4642 update_stat_ex_mtime(&fsp->fsp_name->st, write_time);
4652 return NT_STATUS_OK;
4655 NTSTATUS create_directory(connection_struct *conn, struct smb_request *req,
4656 struct smb_filename *smb_dname)
4661 status = SMB_VFS_CREATE_FILE(
4664 smb_dname, /* fname */
4665 FILE_READ_ATTRIBUTES, /* access_mask */
4666 FILE_SHARE_NONE, /* share_access */
4667 FILE_CREATE, /* create_disposition*/
4668 FILE_DIRECTORY_FILE, /* create_options */
4669 FILE_ATTRIBUTE_DIRECTORY, /* file_attributes */
4670 0, /* oplock_request */
4672 0, /* allocation_size */
4673 0, /* private_flags */
4678 NULL, NULL); /* create context */
4680 if (NT_STATUS_IS_OK(status)) {
4681 close_file(req, fsp, NORMAL_CLOSE);
4687 /****************************************************************************
4688 Receive notification that one of our open files has been renamed by another
4690 ****************************************************************************/
4692 void msg_file_was_renamed(struct messaging_context *msg_ctx,
4695 struct server_id src,
4698 struct file_rename_message *msg = NULL;
4699 enum ndr_err_code ndr_err;
4701 struct smb_filename *smb_fname = NULL;
4702 struct smbd_server_connection *sconn =
4703 talloc_get_type_abort(private_data,
4704 struct smbd_server_connection);
4706 msg = talloc(talloc_tos(), struct file_rename_message);
4708 DBG_WARNING("talloc failed\n");
4712 ndr_err = ndr_pull_struct_blob_all(
4716 (ndr_pull_flags_fn_t)ndr_pull_file_rename_message);
4717 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
4718 DBG_DEBUG("ndr_pull_oplock_break_message failed: %s\n",
4719 ndr_errstr(ndr_err));
4722 if (DEBUGLEVEL >= 10) {
4723 struct server_id_buf buf;
4724 DBG_DEBUG("Got rename message from %s\n",
4725 server_id_str_buf(src, &buf));
4726 NDR_PRINT_DEBUG(file_rename_message, msg);
4729 /* stream_name must always be NULL if there is no stream. */
4730 if ((msg->stream_name != NULL) && (msg->stream_name[0] == '\0')) {
4731 msg->stream_name = NULL;
4734 smb_fname = synthetic_smb_fname(msg,
4740 if (smb_fname == NULL) {
4741 DBG_DEBUG("synthetic_smb_fname failed\n");
4745 fsp = file_find_dif(sconn, msg->id, msg->share_file_id);
4747 DBG_DEBUG("fsp not found\n");
4751 if (strcmp(fsp->conn->connectpath, msg->servicepath) == 0) {
4753 DBG_DEBUG("renaming file %s from %s -> %s\n",
4756 smb_fname_str_dbg(smb_fname));
4757 status = fsp_set_smb_fname(fsp, smb_fname);
4758 if (!NT_STATUS_IS_OK(status)) {
4759 DBG_DEBUG("fsp_set_smb_fname failed: %s\n",
4765 * Now we have the complete path we can work out if
4766 * this is actually within this share and adjust
4767 * newname accordingly.
4769 DBG_DEBUG("share mismatch (sharepath %s not sharepath %s) "
4770 "%s from %s -> %s\n",
4771 fsp->conn->connectpath,
4775 smb_fname_str_dbg(smb_fname));
4782 * If a main file is opened for delete, all streams need to be checked for
4783 * !FILE_SHARE_DELETE. Do this by opening with DELETE_ACCESS.
4784 * If that works, delete them all by setting the delete on close and close.
4787 static NTSTATUS open_streams_for_delete(connection_struct *conn,
4788 const struct smb_filename *smb_fname)
4790 struct stream_struct *stream_info = NULL;
4791 files_struct **streams = NULL;
4793 unsigned int i, num_streams = 0;
4794 TALLOC_CTX *frame = talloc_stackframe();
4797 status = vfs_streaminfo(conn, NULL, smb_fname, talloc_tos(),
4798 &num_streams, &stream_info);
4800 if (NT_STATUS_EQUAL(status, NT_STATUS_NOT_IMPLEMENTED)
4801 || NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
4802 DEBUG(10, ("no streams around\n"));
4804 return NT_STATUS_OK;
4807 if (!NT_STATUS_IS_OK(status)) {
4808 DEBUG(10, ("vfs_streaminfo failed: %s\n",
4809 nt_errstr(status)));
4813 DEBUG(10, ("open_streams_for_delete found %d streams\n",
4816 if (num_streams == 0) {
4818 return NT_STATUS_OK;
4821 streams = talloc_array(talloc_tos(), files_struct *, num_streams);
4822 if (streams == NULL) {
4823 DEBUG(0, ("talloc failed\n"));
4824 status = NT_STATUS_NO_MEMORY;
4828 for (i=0; i<num_streams; i++) {
4829 struct smb_filename *smb_fname_cp;
4831 if (strequal(stream_info[i].name, "::$DATA")) {
4836 smb_fname_cp = synthetic_smb_fname(talloc_tos(),
4837 smb_fname->base_name,
4838 stream_info[i].name,
4842 ~SMB_FILENAME_POSIX_PATH));
4843 if (smb_fname_cp == NULL) {
4844 status = NT_STATUS_NO_MEMORY;
4848 if (SMB_VFS_STAT(conn, smb_fname_cp) == -1) {
4849 DEBUG(10, ("Unable to stat stream: %s\n",
4850 smb_fname_str_dbg(smb_fname_cp)));
4853 status = SMB_VFS_CREATE_FILE(
4856 smb_fname_cp, /* fname */
4857 DELETE_ACCESS, /* access_mask */
4858 (FILE_SHARE_READ | /* share_access */
4859 FILE_SHARE_WRITE | FILE_SHARE_DELETE),
4860 FILE_OPEN, /* create_disposition*/
4861 0, /* create_options */
4862 FILE_ATTRIBUTE_NORMAL, /* file_attributes */
4863 0, /* oplock_request */
4865 0, /* allocation_size */
4866 0, /* private_flags */
4869 &streams[i], /* result */
4871 NULL, NULL); /* create context */
4873 if (!NT_STATUS_IS_OK(status)) {
4874 DEBUG(10, ("Could not open stream %s: %s\n",
4875 smb_fname_str_dbg(smb_fname_cp),
4876 nt_errstr(status)));
4878 TALLOC_FREE(smb_fname_cp);
4881 TALLOC_FREE(smb_fname_cp);
4885 * don't touch the variable "status" beyond this point :-)
4888 for (j = i-1 ; j >= 0; j--) {
4889 if (streams[j] == NULL) {
4893 DEBUG(10, ("Closing stream # %d, %s\n", j,
4894 fsp_str_dbg(streams[j])));
4895 close_file(NULL, streams[j], NORMAL_CLOSE);
4903 /*********************************************************************
4904 Create a default ACL by inheriting from the parent. If no inheritance
4905 from the parent available, don't set anything. This will leave the actual
4906 permissions the new file or directory already got from the filesystem
4907 as the NT ACL when read.
4908 *********************************************************************/
4910 static NTSTATUS inherit_new_acl(files_struct *fsp)
4912 TALLOC_CTX *frame = talloc_stackframe();
4913 struct security_descriptor *parent_desc = NULL;
4914 NTSTATUS status = NT_STATUS_OK;
4915 struct security_descriptor *psd = NULL;
4916 const struct dom_sid *owner_sid = NULL;
4917 const struct dom_sid *group_sid = NULL;
4918 uint32_t security_info_sent = (SECINFO_OWNER | SECINFO_GROUP | SECINFO_DACL);
4919 struct security_token *token = fsp->conn->session_info->security_token;
4920 bool inherit_owner =
4921 (lp_inherit_owner(SNUM(fsp->conn)) == INHERIT_OWNER_WINDOWS_AND_UNIX);
4922 bool inheritable_components = false;
4923 bool try_builtin_administrators = false;
4924 const struct dom_sid *BA_U_sid = NULL;
4925 const struct dom_sid *BA_G_sid = NULL;
4926 bool try_system = false;
4927 const struct dom_sid *SY_U_sid = NULL;
4928 const struct dom_sid *SY_G_sid = NULL;
4930 struct smb_filename *parent_dir = NULL;
4933 ok = parent_smb_fname(frame,
4939 return NT_STATUS_NO_MEMORY;
4942 status = SMB_VFS_GET_NT_ACL_AT(fsp->conn,
4945 (SECINFO_OWNER | SECINFO_GROUP | SECINFO_DACL),
4948 if (!NT_STATUS_IS_OK(status)) {
4953 inheritable_components = sd_has_inheritable_components(parent_desc,
4954 fsp->fsp_flags.is_directory);
4956 if (!inheritable_components && !inherit_owner) {
4958 /* Nothing to inherit and not setting owner. */
4959 return NT_STATUS_OK;
4962 /* Create an inherited descriptor from the parent. */
4964 if (DEBUGLEVEL >= 10) {
4965 DEBUG(10,("inherit_new_acl: parent acl for %s is:\n",
4966 fsp_str_dbg(fsp) ));
4967 NDR_PRINT_DEBUG(security_descriptor, parent_desc);
4970 /* Inherit from parent descriptor if "inherit owner" set. */
4971 if (inherit_owner) {
4972 owner_sid = parent_desc->owner_sid;
4973 group_sid = parent_desc->group_sid;
4976 if (owner_sid == NULL) {
4977 if (security_token_has_builtin_administrators(token)) {
4978 try_builtin_administrators = true;
4979 } else if (security_token_is_system(token)) {
4980 try_builtin_administrators = true;
4985 if (group_sid == NULL &&
4986 token->num_sids == PRIMARY_GROUP_SID_INDEX)
4988 if (security_token_is_system(token)) {
4989 try_builtin_administrators = true;
4994 if (try_builtin_administrators) {
4998 ok = sids_to_unixids(&global_sid_Builtin_Administrators, 1, &ids);
5002 BA_U_sid = &global_sid_Builtin_Administrators;
5003 BA_G_sid = &global_sid_Builtin_Administrators;
5006 BA_U_sid = &global_sid_Builtin_Administrators;
5009 BA_G_sid = &global_sid_Builtin_Administrators;
5021 ok = sids_to_unixids(&global_sid_System, 1, &ids);
5025 SY_U_sid = &global_sid_System;
5026 SY_G_sid = &global_sid_System;
5029 SY_U_sid = &global_sid_System;
5032 SY_G_sid = &global_sid_System;
5040 if (owner_sid == NULL) {
5041 owner_sid = BA_U_sid;
5044 if (owner_sid == NULL) {
5045 owner_sid = SY_U_sid;
5048 if (group_sid == NULL) {
5049 group_sid = SY_G_sid;
5052 if (try_system && group_sid == NULL) {
5053 group_sid = BA_G_sid;
5056 if (owner_sid == NULL) {
5057 owner_sid = &token->sids[PRIMARY_USER_SID_INDEX];
5059 if (group_sid == NULL) {
5060 if (token->num_sids == PRIMARY_GROUP_SID_INDEX) {
5061 group_sid = &token->sids[PRIMARY_USER_SID_INDEX];
5063 group_sid = &token->sids[PRIMARY_GROUP_SID_INDEX];
5067 status = se_create_child_secdesc(frame,
5073 fsp->fsp_flags.is_directory);
5074 if (!NT_STATUS_IS_OK(status)) {
5079 /* If inheritable_components == false,
5080 se_create_child_secdesc()
5081 creates a security descriptor with a NULL dacl
5082 entry, but with SEC_DESC_DACL_PRESENT. We need
5083 to remove that flag. */
5085 if (!inheritable_components) {
5086 security_info_sent &= ~SECINFO_DACL;
5087 psd->type &= ~SEC_DESC_DACL_PRESENT;
5090 if (DEBUGLEVEL >= 10) {
5091 DEBUG(10,("inherit_new_acl: child acl for %s is:\n",
5092 fsp_str_dbg(fsp) ));
5093 NDR_PRINT_DEBUG(security_descriptor, psd);
5096 if (inherit_owner) {
5097 /* We need to be root to force this. */
5100 status = SMB_VFS_FSET_NT_ACL(fsp,
5103 if (inherit_owner) {
5111 * If we already have a lease, it must match the new file id. [MS-SMB2]
5112 * 3.3.5.9.8 speaks about INVALID_PARAMETER if an already used lease key is
5113 * used for a different file name.
5116 struct lease_match_state {
5117 /* Input parameters. */
5118 TALLOC_CTX *mem_ctx;
5119 const char *servicepath;
5120 const struct smb_filename *fname;
5123 /* Return parameters. */
5124 uint32_t num_file_ids;
5125 struct file_id *ids;
5126 NTSTATUS match_status;
5129 /*************************************************************
5130 File doesn't exist but this lease key+guid is already in use.
5132 This is only allowable in the dynamic share case where the
5133 service path must be different.
5135 There is a small race condition here in the multi-connection
5136 case where a client sends two create calls on different connections,
5137 where the file doesn't exist and one smbd creates the leases_db
5138 entry first, but this will get fixed by the multichannel cleanup
5139 when all identical client_guids get handled by a single smbd.
5140 **************************************************************/
5142 static void lease_match_parser_new_file(
5144 const struct leases_db_file *files,
5145 struct lease_match_state *state)
5149 for (i = 0; i < num_files; i++) {
5150 const struct leases_db_file *f = &files[i];
5151 if (strequal(state->servicepath, f->servicepath)) {
5152 state->match_status = NT_STATUS_INVALID_PARAMETER;
5157 /* Dynamic share case. Break leases on all other files. */
5158 state->match_status = leases_db_copy_file_ids(state->mem_ctx,
5162 if (!NT_STATUS_IS_OK(state->match_status)) {
5166 state->num_file_ids = num_files;
5167 state->match_status = NT_STATUS_OPLOCK_NOT_GRANTED;
5171 static void lease_match_parser(
5173 const struct leases_db_file *files,
5176 struct lease_match_state *state =
5177 (struct lease_match_state *)private_data;
5180 if (!state->file_existed) {
5182 * Deal with name mismatch or
5183 * possible dynamic share case separately
5184 * to make code clearer.
5186 lease_match_parser_new_file(num_files,
5193 state->match_status = NT_STATUS_OK;
5195 for (i = 0; i < num_files; i++) {
5196 const struct leases_db_file *f = &files[i];
5198 /* Everything should be the same. */
5199 if (!file_id_equal(&state->id, &f->id)) {
5200 /* This should catch all dynamic share cases. */
5201 state->match_status = NT_STATUS_OPLOCK_NOT_GRANTED;
5204 if (!strequal(f->servicepath, state->servicepath)) {
5205 state->match_status = NT_STATUS_INVALID_PARAMETER;
5208 if (!strequal(f->base_name, state->fname->base_name)) {
5209 state->match_status = NT_STATUS_INVALID_PARAMETER;
5212 if (!strequal(f->stream_name, state->fname->stream_name)) {
5213 state->match_status = NT_STATUS_INVALID_PARAMETER;
5218 if (NT_STATUS_IS_OK(state->match_status)) {
5220 * Common case - just opening another handle on a
5221 * file on a non-dynamic share.
5226 if (NT_STATUS_EQUAL(state->match_status, NT_STATUS_INVALID_PARAMETER)) {
5227 /* Mismatched path. Error back to client. */
5232 * File id mismatch. Dynamic share case NT_STATUS_OPLOCK_NOT_GRANTED.
5233 * Don't allow leases.
5236 state->match_status = leases_db_copy_file_ids(state->mem_ctx,
5240 if (!NT_STATUS_IS_OK(state->match_status)) {
5244 state->num_file_ids = num_files;
5245 state->match_status = NT_STATUS_OPLOCK_NOT_GRANTED;
5249 struct lease_match_break_state {
5250 struct messaging_context *msg_ctx;
5251 const struct smb2_lease_key *lease_key;
5259 static bool lease_match_break_fn(
5260 struct share_mode_entry *e,
5263 struct lease_match_break_state *state = private_data;
5265 uint32_t e_lease_type;
5268 stale = share_entry_stale_pid(e);
5273 equal = smb2_lease_key_equal(&e->lease_key, state->lease_key);
5278 status = leases_db_get(
5282 NULL, /* current_state */
5283 NULL, /* breaking */
5284 NULL, /* breaking_to_requested */
5285 NULL, /* breaking_to_required */
5286 &state->version, /* lease_version */
5287 &state->epoch); /* epoch */
5288 if (NT_STATUS_IS_OK(status)) {
5289 state->found_lease = true;
5291 DBG_WARNING("Could not find version/epoch: %s\n",
5295 e_lease_type = get_lease_type(e, state->id);
5296 if (e_lease_type == SMB2_LEASE_NONE) {
5299 send_break_message(state->msg_ctx, &state->id, e, SMB2_LEASE_NONE);
5302 * Windows 7 and 8 lease clients are broken in that they will
5303 * not respond to lease break requests whilst waiting for an
5304 * outstanding open request on that lease handle on the same
5305 * TCP connection, due to holding an internal inode lock.
5307 * This means we can't reschedule ourselves here, but must
5308 * return from the create.
5312 * Send the breaks and then return SMB2_LEASE_NONE in the
5313 * lease handle to cause them to acknowledge the lease
5314 * break. Consultation with Microsoft engineering confirmed
5315 * this approach is safe.
5321 static NTSTATUS lease_match(connection_struct *conn,
5322 struct smb_request *req,
5323 const struct smb2_lease_key *lease_key,
5324 const char *servicepath,
5325 const struct smb_filename *fname,
5326 uint16_t *p_version,
5329 struct smbd_server_connection *sconn = req->sconn;
5330 TALLOC_CTX *tos = talloc_tos();
5331 struct lease_match_state state = {
5333 .servicepath = servicepath,
5335 .match_status = NT_STATUS_OK
5340 state.file_existed = VALID_STAT(fname->st);
5341 if (state.file_existed) {
5342 state.id = vfs_file_id_from_sbuf(conn, &fname->st);
5345 status = leases_db_parse(&sconn->client->global->client_guid,
5346 lease_key, lease_match_parser, &state);
5347 if (!NT_STATUS_IS_OK(status)) {
5349 * Not found or error means okay: We can make the lease pass
5351 return NT_STATUS_OK;
5353 if (!NT_STATUS_EQUAL(state.match_status, NT_STATUS_OPLOCK_NOT_GRANTED)) {
5355 * Anything but NT_STATUS_OPLOCK_NOT_GRANTED, let the caller
5358 return state.match_status;
5361 /* We have to break all existing leases. */
5362 for (i = 0; i < state.num_file_ids; i++) {
5363 struct lease_match_break_state break_state = {
5364 .msg_ctx = conn->sconn->msg_ctx,
5365 .lease_key = lease_key,
5367 struct share_mode_lock *lck;
5370 if (file_id_equal(&state.ids[i], &state.id)) {
5371 /* Don't need to break our own file. */
5375 break_state.id = state.ids[i];
5377 lck = get_existing_share_mode_lock(
5378 talloc_tos(), break_state.id);
5380 /* Race condition - file already closed. */
5384 ok = share_mode_forall_leases(
5385 lck, lease_match_break_fn, &break_state);
5387 DBG_DEBUG("share_mode_forall_leases failed\n");
5393 if (break_state.found_lease) {
5394 *p_version = break_state.version;
5395 *p_epoch = break_state.epoch;
5399 * Ensure we don't grant anything more so we
5402 return NT_STATUS_OPLOCK_NOT_GRANTED;
5406 * Wrapper around open_file_ntcreate and open_directory
5409 static NTSTATUS create_file_unixpath(connection_struct *conn,
5410 struct smb_request *req,
5411 struct smb_filename *smb_fname,
5412 uint32_t access_mask,
5413 uint32_t share_access,
5414 uint32_t create_disposition,
5415 uint32_t create_options,
5416 uint32_t file_attributes,
5417 uint32_t oplock_request,
5418 const struct smb2_lease *lease,
5419 uint64_t allocation_size,
5420 uint32_t private_flags,
5421 struct security_descriptor *sd,
5422 struct ea_list *ea_list,
5424 files_struct **result,
5427 struct smb2_lease none_lease;
5428 int info = FILE_WAS_OPENED;
5429 files_struct *base_fsp = NULL;
5430 files_struct *fsp = NULL;
5433 DBG_DEBUG("create_file_unixpath: access_mask = 0x%x "
5434 "file_attributes = 0x%x, share_access = 0x%x, "
5435 "create_disposition = 0x%x create_options = 0x%x "
5436 "oplock_request = 0x%x private_flags = 0x%x "
5437 "ea_list = %p, sd = %p, "
5439 (unsigned int)access_mask,
5440 (unsigned int)file_attributes,
5441 (unsigned int)share_access,
5442 (unsigned int)create_disposition,
5443 (unsigned int)create_options,
5444 (unsigned int)oplock_request,
5445 (unsigned int)private_flags,
5446 ea_list, sd, smb_fname_str_dbg(smb_fname));
5448 if (create_options & FILE_OPEN_BY_FILE_ID) {
5449 status = NT_STATUS_NOT_SUPPORTED;
5453 if (create_options & NTCREATEX_OPTIONS_INVALID_PARAM_MASK) {
5454 status = NT_STATUS_INVALID_PARAMETER;
5459 oplock_request |= INTERNAL_OPEN_ONLY;
5462 if (lease != NULL) {
5463 uint16_t epoch = lease->lease_epoch;
5464 uint16_t version = lease->lease_version;
5467 DBG_WARNING("Got lease on internal open\n");
5468 status = NT_STATUS_INTERNAL_ERROR;
5472 status = lease_match(conn,
5479 if (NT_STATUS_EQUAL(status, NT_STATUS_OPLOCK_NOT_GRANTED)) {
5480 /* Dynamic share file. No leases and update epoch... */
5481 none_lease = *lease;
5482 none_lease.lease_state = SMB2_LEASE_NONE;
5483 none_lease.lease_epoch = epoch;
5484 none_lease.lease_version = version;
5485 lease = &none_lease;
5486 } else if (!NT_STATUS_IS_OK(status)) {
5491 if ((conn->fs_capabilities & FILE_NAMED_STREAMS)
5492 && (access_mask & DELETE_ACCESS)
5493 && !is_ntfs_stream_smb_fname(smb_fname)) {
5495 * We can't open a file with DELETE access if any of the
5496 * streams is open without FILE_SHARE_DELETE
5498 status = open_streams_for_delete(conn, smb_fname);
5500 if (!NT_STATUS_IS_OK(status)) {
5505 if (access_mask & SEC_FLAG_SYSTEM_SECURITY) {
5508 ok = security_token_has_privilege(get_current_nttok(conn),
5511 DBG_DEBUG("open on %s failed - "
5512 "SEC_FLAG_SYSTEM_SECURITY denied.\n",
5513 smb_fname_str_dbg(smb_fname));
5514 status = NT_STATUS_PRIVILEGE_NOT_HELD;
5518 if (conn->sconn->using_smb2 &&
5519 (access_mask == SEC_FLAG_SYSTEM_SECURITY))
5522 * No other bits set. Windows SMB2 refuses this.
5523 * See smbtorture3 SMB2-SACL test.
5525 * Note this is an SMB2-only behavior,
5526 * smbtorture3 SMB1-SYSTEM-SECURITY already tests
5527 * that SMB1 allows this.
5529 status = NT_STATUS_ACCESS_DENIED;
5535 * Files or directories can't be opened DELETE_ON_CLOSE without
5537 * BUG: https://bugzilla.samba.org/show_bug.cgi?id=13358
5539 if (create_options & FILE_DELETE_ON_CLOSE) {
5540 if ((access_mask & DELETE_ACCESS) == 0) {
5541 status = NT_STATUS_INVALID_PARAMETER;
5546 if ((conn->fs_capabilities & FILE_NAMED_STREAMS)
5547 && is_ntfs_stream_smb_fname(smb_fname))
5549 uint32_t base_create_disposition;
5550 struct smb_filename *smb_fname_base = NULL;
5551 uint32_t base_privflags;
5553 if (create_options & FILE_DIRECTORY_FILE) {
5554 status = NT_STATUS_NOT_A_DIRECTORY;
5558 switch (create_disposition) {
5560 base_create_disposition = FILE_OPEN;
5563 base_create_disposition = FILE_OPEN_IF;
5567 /* Create an smb_filename with stream_name == NULL. */
5568 smb_fname_base = synthetic_smb_fname(talloc_tos(),
5569 smb_fname->base_name,
5574 if (smb_fname_base == NULL) {
5575 status = NT_STATUS_NO_MEMORY;
5579 if (SMB_VFS_STAT(conn, smb_fname_base) == -1) {
5580 DEBUG(10, ("Unable to stat stream: %s\n",
5581 smb_fname_str_dbg(smb_fname_base)));
5584 * https://bugzilla.samba.org/show_bug.cgi?id=10229
5585 * We need to check if the requested access mask
5586 * could be used to open the underlying file (if
5587 * it existed), as we're passing in zero for the
5588 * access mask to the base filename.
5590 status = check_base_file_access(conn,
5594 if (!NT_STATUS_IS_OK(status)) {
5595 DEBUG(10, ("Permission check "
5596 "for base %s failed: "
5597 "%s\n", smb_fname->base_name,
5598 nt_errstr(status)));
5603 base_privflags = NTCREATEX_OPTIONS_PRIVATE_STREAM_BASEOPEN;
5605 /* Open the base file. */
5606 status = create_file_unixpath(conn,
5612 | FILE_SHARE_DELETE,
5613 base_create_disposition,
5624 TALLOC_FREE(smb_fname_base);
5626 if (!NT_STATUS_IS_OK(status)) {
5627 DEBUG(10, ("create_file_unixpath for base %s failed: "
5628 "%s\n", smb_fname->base_name,
5629 nt_errstr(status)));
5632 /* we don't need the low level fd */
5636 status = file_new(req, conn, &fsp);
5637 if(!NT_STATUS_IS_OK(status)) {
5641 status = fsp_set_smb_fname(fsp, smb_fname);
5642 if (!NT_STATUS_IS_OK(status)) {
5648 * We're opening the stream element of a
5649 * base_fsp we already opened. Set up the
5652 fsp->base_fsp = base_fsp;
5656 * If it's a request for a directory open, deal with it separately.
5659 if (create_options & FILE_DIRECTORY_FILE) {
5661 if (create_options & FILE_NON_DIRECTORY_FILE) {
5662 status = NT_STATUS_INVALID_PARAMETER;
5666 /* Can't open a temp directory. IFS kit test. */
5667 if (!(file_attributes & FILE_FLAG_POSIX_SEMANTICS) &&
5668 (file_attributes & FILE_ATTRIBUTE_TEMPORARY)) {
5669 status = NT_STATUS_INVALID_PARAMETER;
5674 * We will get a create directory here if the Win32
5675 * app specified a security descriptor in the
5676 * CreateDirectory() call.
5680 status = open_directory(conn,
5692 * Ordinary file case.
5695 if (allocation_size) {
5696 fsp->initial_allocation_size = smb_roundup(fsp->conn,
5700 status = open_file_ntcreate(conn,
5712 if (NT_STATUS_EQUAL(status, NT_STATUS_FILE_IS_A_DIRECTORY)) {
5714 /* A stream open never opens a directory */
5717 status = NT_STATUS_FILE_IS_A_DIRECTORY;
5722 * Fail the open if it was explicitly a non-directory
5726 if (create_options & FILE_NON_DIRECTORY_FILE) {
5727 status = NT_STATUS_FILE_IS_A_DIRECTORY;
5732 status = open_directory(conn,
5744 if (!NT_STATUS_IS_OK(status)) {
5745 file_free(req, fsp);
5750 fsp->base_fsp = base_fsp;
5752 if ((ea_list != NULL) &&
5753 ((info == FILE_WAS_CREATED) || (info == FILE_WAS_OVERWRITTEN))) {
5754 status = set_ea(conn, fsp, fsp->fsp_name, ea_list);
5755 if (!NT_STATUS_IS_OK(status)) {
5760 if (!fsp->fsp_flags.is_directory &&
5761 S_ISDIR(fsp->fsp_name->st.st_ex_mode))
5763 status = NT_STATUS_ACCESS_DENIED;
5767 /* Save the requested allocation size. */
5768 if ((info == FILE_WAS_CREATED) || (info == FILE_WAS_OVERWRITTEN)) {
5769 if ((allocation_size > (uint64_t)fsp->fsp_name->st.st_ex_size)
5770 && !(fsp->fsp_flags.is_directory))
5772 fsp->initial_allocation_size = smb_roundup(
5773 fsp->conn, allocation_size);
5774 if (vfs_allocate_file_space(
5775 fsp, fsp->initial_allocation_size) == -1) {
5776 status = NT_STATUS_DISK_FULL;
5780 fsp->initial_allocation_size = smb_roundup(
5781 fsp->conn, (uint64_t)fsp->fsp_name->st.st_ex_size);
5784 fsp->initial_allocation_size = 0;
5787 if ((info == FILE_WAS_CREATED) && lp_nt_acl_support(SNUM(conn)) &&
5788 fsp->base_fsp == NULL) {
5791 * According to the MS documentation, the only time the security
5792 * descriptor is applied to the opened file is iff we *created* the
5793 * file; an existing file stays the same.
5795 * Also, it seems (from observation) that you can open the file with
5796 * any access mask but you can still write the sd. We need to override
5797 * the granted access before we call set_sd
5798 * Patch for bug #2242 from Tom Lackemann <cessnatomny@yahoo.com>.
5801 uint32_t sec_info_sent;
5802 uint32_t saved_access_mask = fsp->access_mask;
5804 sec_info_sent = get_sec_info(sd);
5806 fsp->access_mask = FILE_GENERIC_ALL;
5808 if (sec_info_sent & (SECINFO_OWNER|
5812 status = set_sd(fsp, sd, sec_info_sent);
5815 fsp->access_mask = saved_access_mask;
5817 if (!NT_STATUS_IS_OK(status)) {
5820 } else if (lp_inherit_acls(SNUM(conn))) {
5821 /* Inherit from parent. Errors here are not fatal. */
5822 status = inherit_new_acl(fsp);
5823 if (!NT_STATUS_IS_OK(status)) {
5824 DEBUG(10,("inherit_new_acl: failed for %s with %s\n",
5826 nt_errstr(status) ));
5831 if ((conn->fs_capabilities & FILE_FILE_COMPRESSION)
5832 && (create_options & FILE_NO_COMPRESSION)
5833 && (info == FILE_WAS_CREATED)) {
5834 status = SMB_VFS_SET_COMPRESSION(conn, fsp, fsp,
5835 COMPRESSION_FORMAT_NONE);
5836 if (!NT_STATUS_IS_OK(status)) {
5837 DEBUG(1, ("failed to disable compression: %s\n",
5838 nt_errstr(status)));
5842 DEBUG(10, ("create_file_unixpath: info=%d\n", info));
5845 if (pinfo != NULL) {
5849 smb_fname->st = fsp->fsp_name->st;
5851 return NT_STATUS_OK;
5854 DEBUG(10, ("create_file_unixpath: %s\n", nt_errstr(status)));
5857 if (base_fsp && fsp->base_fsp == base_fsp) {
5859 * The close_file below will close
5864 close_file(req, fsp, ERROR_CLOSE);
5867 if (base_fsp != NULL) {
5868 close_file(req, base_fsp, ERROR_CLOSE);
5874 NTSTATUS create_file_default(connection_struct *conn,
5875 struct smb_request *req,
5876 struct smb_filename *smb_fname,
5877 uint32_t access_mask,
5878 uint32_t share_access,
5879 uint32_t create_disposition,
5880 uint32_t create_options,
5881 uint32_t file_attributes,
5882 uint32_t oplock_request,
5883 const struct smb2_lease *lease,
5884 uint64_t allocation_size,
5885 uint32_t private_flags,
5886 struct security_descriptor *sd,
5887 struct ea_list *ea_list,
5888 files_struct **result,
5890 const struct smb2_create_blobs *in_context_blobs,
5891 struct smb2_create_blobs *out_context_blobs)
5893 int info = FILE_WAS_OPENED;
5894 files_struct *fsp = NULL;
5896 bool stream_name = false;
5897 struct smb2_create_blob *posx = NULL;
5899 DBG_DEBUG("create_file: access_mask = 0x%x "
5900 "file_attributes = 0x%x, share_access = 0x%x, "
5901 "create_disposition = 0x%x create_options = 0x%x "
5902 "oplock_request = 0x%x "
5903 "private_flags = 0x%x "
5904 "ea_list = %p, sd = %p, "
5906 (unsigned int)access_mask,
5907 (unsigned int)file_attributes,
5908 (unsigned int)share_access,
5909 (unsigned int)create_disposition,
5910 (unsigned int)create_options,
5911 (unsigned int)oplock_request,
5912 (unsigned int)private_flags,
5915 smb_fname_str_dbg(smb_fname));
5919 * Remember the absolute time of the original request
5920 * with this mid. We'll use it later to see if this
5923 get_deferred_open_message_state(req, &req->request_time, NULL);
5927 * Check to see if this is a mac fork of some kind.
5930 stream_name = is_ntfs_stream_smb_fname(smb_fname);
5932 enum FAKE_FILE_TYPE fake_file_type;
5934 fake_file_type = is_fake_file(smb_fname);
5936 if (req != NULL && fake_file_type != FAKE_FILE_TYPE_NONE) {
5939 * Here we go! support for changing the disk quotas
5942 * We need to fake up to open this MAGIC QUOTA file
5943 * and return a valid FID.
5945 * w2k close this file directly after openening xp
5946 * also tries a QUERY_FILE_INFO on the file and then
5949 status = open_fake_file(req, conn, req->vuid,
5950 fake_file_type, smb_fname,
5952 if (!NT_STATUS_IS_OK(status)) {
5956 ZERO_STRUCT(smb_fname->st);
5960 if (!(conn->fs_capabilities & FILE_NAMED_STREAMS)) {
5961 status = NT_STATUS_OBJECT_NAME_NOT_FOUND;
5966 if (is_ntfs_default_stream_smb_fname(smb_fname)) {
5968 smb_fname->stream_name = NULL;
5969 /* We have to handle this error here. */
5970 if (create_options & FILE_DIRECTORY_FILE) {
5971 status = NT_STATUS_NOT_A_DIRECTORY;
5974 if (req != NULL && req->posix_pathnames) {
5975 ret = SMB_VFS_LSTAT(conn, smb_fname);
5977 ret = SMB_VFS_STAT(conn, smb_fname);
5980 if (ret == 0 && VALID_STAT_OF_DIR(smb_fname->st)) {
5981 status = NT_STATUS_FILE_IS_A_DIRECTORY;
5986 posx = smb2_create_blob_find(
5987 in_context_blobs, SMB2_CREATE_TAG_POSIX);
5989 uint32_t wire_mode_bits = 0;
5990 mode_t mode_bits = 0;
5991 SMB_STRUCT_STAT sbuf = { 0 };
5992 enum perm_type ptype =
5993 (create_options & FILE_DIRECTORY_FILE) ?
5994 PERM_NEW_DIR : PERM_NEW_FILE;
5996 if (posx->data.length != 4) {
5997 status = NT_STATUS_INVALID_PARAMETER;
6001 wire_mode_bits = IVAL(posx->data.data, 0);
6002 status = unix_perms_from_wire(
6003 conn, &sbuf, wire_mode_bits, ptype, &mode_bits);
6004 if (!NT_STATUS_IS_OK(status)) {
6008 * Remove type info from mode, leaving only the
6009 * permissions and setuid/gid bits.
6011 mode_bits &= ~S_IFMT;
6013 file_attributes = (FILE_FLAG_POSIX_SEMANTICS | mode_bits);
6016 status = create_file_unixpath(conn,
6032 if (!NT_STATUS_IS_OK(status)) {
6037 DEBUG(10, ("create_file: info=%d\n", info));
6040 if (pinfo != NULL) {
6043 return NT_STATUS_OK;
6046 DEBUG(10, ("create_file: %s\n", nt_errstr(status)));
6049 close_file(req, fsp, ERROR_CLOSE);