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, smb_fname)) {
90 /****************************************************************************
91 Check if we have open rights.
92 ****************************************************************************/
94 NTSTATUS smbd_check_access_rights(struct connection_struct *conn,
95 const struct smb_filename *smb_fname,
99 /* Check if we have rights to open. */
101 struct security_descriptor *sd = NULL;
102 uint32_t rejected_share_access;
103 uint32_t rejected_mask = access_mask;
104 uint32_t do_not_check_mask = 0;
106 rejected_share_access = access_mask & ~(conn->share_access);
108 if (rejected_share_access) {
109 DEBUG(10, ("smbd_check_access_rights: rejected share access 0x%x "
111 (unsigned int)access_mask,
112 smb_fname_str_dbg(smb_fname),
113 (unsigned int)rejected_share_access ));
114 return NT_STATUS_ACCESS_DENIED;
117 if (!use_privs && get_current_uid(conn) == (uid_t)0) {
118 /* I'm sorry sir, I didn't know you were root... */
119 DEBUG(10,("smbd_check_access_rights: root override "
120 "on %s. Granting 0x%x\n",
121 smb_fname_str_dbg(smb_fname),
122 (unsigned int)access_mask ));
126 if ((access_mask & DELETE_ACCESS) && !lp_acl_check_permissions(SNUM(conn))) {
127 DEBUG(10,("smbd_check_access_rights: not checking ACL "
128 "on DELETE_ACCESS on file %s. Granting 0x%x\n",
129 smb_fname_str_dbg(smb_fname),
130 (unsigned int)access_mask ));
134 if (access_mask == DELETE_ACCESS &&
135 VALID_STAT(smb_fname->st) &&
136 S_ISLNK(smb_fname->st.st_ex_mode)) {
137 /* We can always delete a symlink. */
138 DEBUG(10,("smbd_check_access_rights: not checking ACL "
139 "on DELETE_ACCESS on symlink %s.\n",
140 smb_fname_str_dbg(smb_fname) ));
144 status = SMB_VFS_GET_NT_ACL(conn, smb_fname,
147 SECINFO_DACL), talloc_tos(), &sd);
149 if (!NT_STATUS_IS_OK(status)) {
150 DEBUG(10, ("smbd_check_access_rights: Could not get acl "
152 smb_fname_str_dbg(smb_fname),
155 if (NT_STATUS_EQUAL(status, NT_STATUS_ACCESS_DENIED)) {
163 * If we can access the path to this file, by
164 * default we have FILE_READ_ATTRIBUTES from the
165 * containing directory. See the section:
166 * "Algorithm to Check Access to an Existing File"
169 * se_file_access_check() also takes care of
170 * owner WRITE_DAC and READ_CONTROL.
172 do_not_check_mask = FILE_READ_ATTRIBUTES;
175 * Samba 3.6 and earlier granted execute access even
176 * if the ACL did not contain execute rights.
177 * Samba 4.0 is more correct and checks it.
178 * The compatibilty mode allows one to skip this check
179 * to smoothen upgrades.
181 if (lp_acl_allow_execute_always(SNUM(conn))) {
182 do_not_check_mask |= FILE_EXECUTE;
185 status = se_file_access_check(sd,
186 get_current_nttok(conn),
188 (access_mask & ~do_not_check_mask),
191 DEBUG(10,("smbd_check_access_rights: file %s requesting "
192 "0x%x returning 0x%x (%s)\n",
193 smb_fname_str_dbg(smb_fname),
194 (unsigned int)access_mask,
195 (unsigned int)rejected_mask,
196 nt_errstr(status) ));
198 if (!NT_STATUS_IS_OK(status)) {
199 if (DEBUGLEVEL >= 10) {
200 DEBUG(10,("smbd_check_access_rights: acl for %s is:\n",
201 smb_fname_str_dbg(smb_fname) ));
202 NDR_PRINT_DEBUG(security_descriptor, sd);
208 if (NT_STATUS_IS_OK(status) ||
209 !NT_STATUS_EQUAL(status, NT_STATUS_ACCESS_DENIED)) {
213 /* Here we know status == NT_STATUS_ACCESS_DENIED. */
217 if ((access_mask & FILE_WRITE_ATTRIBUTES) &&
218 (rejected_mask & FILE_WRITE_ATTRIBUTES) &&
219 !lp_store_dos_attributes(SNUM(conn)) &&
220 (lp_map_readonly(SNUM(conn)) ||
221 lp_map_archive(SNUM(conn)) ||
222 lp_map_hidden(SNUM(conn)) ||
223 lp_map_system(SNUM(conn)))) {
224 rejected_mask &= ~FILE_WRITE_ATTRIBUTES;
226 DEBUG(10,("smbd_check_access_rights: "
228 "FILE_WRITE_ATTRIBUTES "
230 smb_fname_str_dbg(smb_fname)));
233 if (parent_override_delete(conn,
237 /* Were we trying to do an open
238 * for delete and didn't get DELETE
239 * access (only) ? Check if the
240 * directory allows DELETE_CHILD.
242 * http://blogs.msdn.com/oldnewthing/archive/2004/06/04/148426.aspx
245 rejected_mask &= ~DELETE_ACCESS;
247 DEBUG(10,("smbd_check_access_rights: "
251 smb_fname_str_dbg(smb_fname)));
254 if (rejected_mask != 0) {
255 return NT_STATUS_ACCESS_DENIED;
260 NTSTATUS check_parent_access(struct connection_struct *conn,
261 struct smb_filename *smb_fname,
262 uint32_t access_mask)
265 struct security_descriptor *parent_sd = NULL;
266 uint32_t access_granted = 0;
267 struct smb_filename *parent_dir = NULL;
268 struct share_mode_lock *lck = NULL;
269 struct file_id id = {0};
271 bool delete_on_close_set;
273 TALLOC_CTX *frame = talloc_stackframe();
276 ok = parent_smb_fname(frame, smb_fname, &parent_dir, NULL);
278 status = NT_STATUS_NO_MEMORY;
282 if (get_current_uid(conn) == (uid_t)0) {
283 /* I'm sorry sir, I didn't know you were root... */
284 DEBUG(10,("check_parent_access: root override "
285 "on %s. Granting 0x%x\n",
286 smb_fname_str_dbg(smb_fname),
287 (unsigned int)access_mask ));
288 status = NT_STATUS_OK;
292 status = SMB_VFS_GET_NT_ACL(conn,
298 if (!NT_STATUS_IS_OK(status)) {
299 DEBUG(5,("check_parent_access: SMB_VFS_GET_NT_ACL failed for "
300 "%s with error %s\n",
301 smb_fname_str_dbg(parent_dir),
307 * If we can access the path to this file, by
308 * default we have FILE_READ_ATTRIBUTES from the
309 * containing directory. See the section:
310 * "Algorithm to Check Access to an Existing File"
313 * se_file_access_check() also takes care of
314 * owner WRITE_DAC and READ_CONTROL.
316 status = se_file_access_check(parent_sd,
317 get_current_nttok(conn),
319 (access_mask & ~FILE_READ_ATTRIBUTES),
321 if(!NT_STATUS_IS_OK(status)) {
322 DEBUG(5,("check_parent_access: access check "
323 "on directory %s for "
324 "path %s for mask 0x%x returned (0x%x) %s\n",
325 smb_fname_str_dbg(parent_dir),
326 smb_fname->base_name,
329 nt_errstr(status) ));
333 if (!(access_mask & (SEC_DIR_ADD_FILE | SEC_DIR_ADD_SUBDIR))) {
334 status = NT_STATUS_OK;
337 if (!lp_check_parent_directory_delete_on_close(SNUM(conn))) {
338 status = NT_STATUS_OK;
342 /* Check if the directory has delete-on-close set */
343 ret = SMB_VFS_STAT(conn, parent_dir);
345 status = map_nt_error_from_unix(errno);
349 id = SMB_VFS_FILE_ID_CREATE(conn, &parent_dir->st);
351 status = file_name_hash(conn, parent_dir->base_name, &name_hash);
352 if (!NT_STATUS_IS_OK(status)) {
356 lck = get_existing_share_mode_lock(frame, id);
358 status = NT_STATUS_OK;
362 delete_on_close_set = is_delete_on_close_set(lck, name_hash);
363 if (delete_on_close_set) {
364 status = NT_STATUS_DELETE_PENDING;
368 status = NT_STATUS_OK;
375 /****************************************************************************
376 Ensure when opening a base file for a stream open that we have permissions
377 to do so given the access mask on the base file.
378 ****************************************************************************/
380 static NTSTATUS check_base_file_access(struct connection_struct *conn,
381 struct smb_filename *smb_fname,
382 uint32_t access_mask)
386 status = smbd_calculate_access_mask(conn, smb_fname,
390 if (!NT_STATUS_IS_OK(status)) {
391 DEBUG(10, ("smbd_calculate_access_mask "
392 "on file %s returned %s\n",
393 smb_fname_str_dbg(smb_fname),
398 if (access_mask & (FILE_WRITE_DATA|FILE_APPEND_DATA)) {
400 if (!CAN_WRITE(conn)) {
401 return NT_STATUS_ACCESS_DENIED;
403 dosattrs = dos_mode(conn, smb_fname);
404 if (IS_DOS_READONLY(dosattrs)) {
405 return NT_STATUS_ACCESS_DENIED;
409 return smbd_check_access_rights(conn,
415 /****************************************************************************
416 Handle differing symlink errno's
417 ****************************************************************************/
419 static int link_errno_convert(int err)
421 #if defined(ENOTSUP) && defined(OSF1)
422 /* handle special Tru64 errno */
423 if (err == ENOTSUP) {
428 /* fix broken NetBSD errno */
433 /* fix broken FreeBSD errno */
440 static int non_widelink_open(struct connection_struct *conn,
441 const struct smb_filename *conn_rootdir_fname,
443 struct smb_filename *smb_fname,
446 unsigned int link_depth);
448 /****************************************************************************
449 Follow a symlink in userspace.
450 ****************************************************************************/
452 static int process_symlink_open(struct connection_struct *conn,
453 const struct smb_filename *conn_rootdir_fname,
455 struct smb_filename *smb_fname,
458 unsigned int link_depth)
461 char *link_target = NULL;
462 struct smb_filename target_fname = {0};
464 struct smb_filename *oldwd_fname = NULL;
465 size_t rootdir_len = 0;
466 struct smb_filename *resolved_fname = NULL;
467 char *resolved_name = NULL;
468 bool matched = false;
472 * Ensure we don't get stuck in a symlink loop.
475 if (link_depth >= 20) {
480 /* Allocate space for the link target. */
481 link_target = talloc_array(talloc_tos(), char, PATH_MAX);
482 if (link_target == NULL) {
487 /* Read the link target. */
488 link_len = SMB_VFS_READLINKAT(conn,
493 if (link_len == -1) {
497 /* Ensure it's at least null terminated. */
498 link_target[link_len] = '\0';
499 target_fname = (struct smb_filename){ .base_name = link_target };
501 /* Convert to an absolute path. */
502 resolved_fname = SMB_VFS_REALPATH(conn, talloc_tos(), &target_fname);
503 if (resolved_fname == NULL) {
506 resolved_name = resolved_fname->base_name;
509 * We know conn_rootdir starts with '/' and
510 * does not end in '/'. FIXME ! Should we
513 rootdir_len = strlen(conn_rootdir_fname->base_name);
515 matched = (strncmp(conn_rootdir_fname->base_name,
524 * Turn into a path relative to the share root.
526 if (resolved_name[rootdir_len] == '\0') {
527 /* Link to the root of the share. */
528 TALLOC_FREE(smb_fname->base_name);
529 smb_fname->base_name = talloc_strdup(smb_fname, ".");
530 } else if (resolved_name[rootdir_len] == '/') {
531 TALLOC_FREE(smb_fname->base_name);
532 smb_fname->base_name = talloc_strdup(smb_fname,
533 &resolved_name[rootdir_len+1]);
539 if (smb_fname->base_name == NULL) {
544 oldwd_fname = vfs_GetWd(talloc_tos(), conn);
545 if (oldwd_fname == NULL) {
549 /* Ensure we operate from the root of the share. */
550 if (vfs_ChDir(conn, conn_rootdir_fname) == -1) {
554 /* And do it all again.. */
555 fd = non_widelink_open(conn,
568 TALLOC_FREE(resolved_fname);
569 TALLOC_FREE(link_target);
570 if (oldwd_fname != NULL) {
571 int ret = vfs_ChDir(conn, oldwd_fname);
573 smb_panic("unable to get back to old directory\n");
575 TALLOC_FREE(oldwd_fname);
577 if (saved_errno != 0) {
583 /****************************************************************************
585 ****************************************************************************/
587 static int non_widelink_open(struct connection_struct *conn,
588 const struct smb_filename *conn_rootdir_fname,
590 struct smb_filename *smb_fname,
593 unsigned int link_depth)
597 struct smb_filename *smb_fname_rel = NULL;
599 struct smb_filename *oldwd_fname = NULL;
600 struct smb_filename *parent_dir_fname = NULL;
603 if (fsp->fsp_flags.is_directory) {
604 parent_dir_fname = cp_smb_filename(talloc_tos(), smb_fname);
605 if (parent_dir_fname == NULL) {
610 smb_fname_rel = synthetic_smb_fname(parent_dir_fname,
612 smb_fname->stream_name,
615 if (smb_fname_rel == NULL) {
620 ok = parent_smb_fname(talloc_tos(),
630 oldwd_fname = vfs_GetWd(talloc_tos(), conn);
631 if (oldwd_fname == NULL) {
635 /* Pin parent directory in place. */
636 if (vfs_ChDir(conn, parent_dir_fname) == -1) {
640 /* Ensure the relative path is below the share. */
641 status = check_reduced_name(conn, parent_dir_fname, smb_fname_rel);
642 if (!NT_STATUS_IS_OK(status)) {
643 saved_errno = map_errno_from_nt_status(status);
650 struct smb_filename *tmp_name = fsp->fsp_name;
651 fsp->fsp_name = smb_fname_rel;
652 fd = SMB_VFS_OPEN(conn, smb_fname_rel, fsp, flags, mode);
653 fsp->fsp_name = tmp_name;
657 saved_errno = link_errno_convert(errno);
659 * Trying to open a symlink to a directory with O_NOFOLLOW and
660 * O_DIRECTORY can return either of ELOOP and ENOTDIR. So
661 * ENOTDIR really means: might be a symlink, but we're not sure.
662 * In this case, we just assume there's a symlink. If we were
663 * wrong, process_symlink_open() will return EINVAL. We check
664 * this below, and fall back to returning the initial
667 * BUG: https://bugzilla.samba.org/show_bug.cgi?id=12860
669 if (saved_errno == ELOOP || saved_errno == ENOTDIR) {
670 if (fsp->posix_flags & FSP_POSIX_FLAGS_OPEN) {
671 /* Never follow symlinks on posix open. */
674 if (!lp_follow_symlinks(SNUM(conn))) {
675 /* Explicitly no symlinks. */
679 * We may have a symlink. Follow in userspace
680 * to ensure it's under the share definition.
682 fd = process_symlink_open(conn,
690 if (saved_errno == ENOTDIR &&
693 * O_DIRECTORY on neither a directory,
694 * nor a symlink. Just return
695 * saved_errno from initial open()
700 link_errno_convert(errno);
707 TALLOC_FREE(parent_dir_fname);
709 if (oldwd_fname != NULL) {
710 int ret = vfs_ChDir(conn, oldwd_fname);
712 smb_panic("unable to get back to old directory\n");
714 TALLOC_FREE(oldwd_fname);
716 if (saved_errno != 0) {
722 /****************************************************************************
723 fd support routines - attempt to do a dos_open.
724 ****************************************************************************/
726 NTSTATUS fd_open(struct connection_struct *conn,
731 struct smb_filename *smb_fname = fsp->fsp_name;
732 NTSTATUS status = NT_STATUS_OK;
733 struct smb_filename *conn_rootdir_fname = NULL;
734 const char *conn_rootdir;
738 * Never follow symlinks on a POSIX client. The
739 * client should be doing this.
742 if ((fsp->posix_flags & FSP_POSIX_FLAGS_OPEN) || !lp_follow_symlinks(SNUM(conn))) {
746 /* Ensure path is below share definition. */
747 conn_rootdir = SMB_VFS_CONNECTPATH(conn,
750 if (conn_rootdir == NULL) {
751 return NT_STATUS_NO_MEMORY;
753 conn_rootdir_fname = synthetic_smb_fname(talloc_tos(),
758 if (conn_rootdir_fname == NULL) {
759 return NT_STATUS_NO_MEMORY;
763 * Only follow symlinks within a share
766 fsp->fh->fd = non_widelink_open(conn,
773 if (fsp->fh->fd == -1) {
776 TALLOC_FREE(conn_rootdir_fname);
777 if (saved_errno != 0) {
781 if (fsp->fh->fd == -1) {
782 int posix_errno = link_errno_convert(errno);
783 status = map_nt_error_from_unix(posix_errno);
784 if (errno == EMFILE) {
785 static time_t last_warned = 0L;
787 if (time((time_t *) NULL) > last_warned) {
788 DEBUG(0,("Too many open files, unable "
789 "to open more! smbd's max "
791 lp_max_open_files()));
792 last_warned = time((time_t *) NULL);
798 DEBUG(10,("fd_open: name %s, flags = 0%o mode = 0%o, fd = %d. %s\n",
799 smb_fname_str_dbg(smb_fname), flags, (int)mode, fsp->fh->fd,
800 (fsp->fh->fd == -1) ? strerror(errno) : "" ));
805 /****************************************************************************
806 Close the file associated with a fsp.
807 ****************************************************************************/
809 NTSTATUS fd_close(files_struct *fsp)
816 if (fsp->fh->fd == -1) {
818 * Either a directory where the dptr_CloseDir() already closed
819 * the fd or a stat open.
823 if (fsp->fh->ref_count > 1) {
824 return NT_STATUS_OK; /* Shared handle. Only close last reference. */
827 ret = SMB_VFS_CLOSE(fsp);
830 return map_nt_error_from_unix(errno);
835 /****************************************************************************
836 Change the ownership of a file to that of the parent directory.
837 Do this by fd if possible.
838 ****************************************************************************/
840 void change_file_owner_to_parent(connection_struct *conn,
841 const char *inherit_from_dir,
844 struct smb_filename *smb_fname_parent;
847 smb_fname_parent = synthetic_smb_fname(talloc_tos(),
852 if (smb_fname_parent == NULL) {
856 ret = SMB_VFS_STAT(conn, smb_fname_parent);
858 DEBUG(0,("change_file_owner_to_parent: failed to stat parent "
859 "directory %s. Error was %s\n",
860 smb_fname_str_dbg(smb_fname_parent),
862 TALLOC_FREE(smb_fname_parent);
866 if (smb_fname_parent->st.st_ex_uid == fsp->fsp_name->st.st_ex_uid) {
867 /* Already this uid - no need to change. */
868 DEBUG(10,("change_file_owner_to_parent: file %s "
869 "is already owned by uid %d\n",
871 (int)fsp->fsp_name->st.st_ex_uid ));
872 TALLOC_FREE(smb_fname_parent);
877 ret = SMB_VFS_FCHOWN(fsp, smb_fname_parent->st.st_ex_uid, (gid_t)-1);
880 DEBUG(0,("change_file_owner_to_parent: failed to fchown "
881 "file %s to parent directory uid %u. Error "
882 "was %s\n", fsp_str_dbg(fsp),
883 (unsigned int)smb_fname_parent->st.st_ex_uid,
886 DEBUG(10,("change_file_owner_to_parent: changed new file %s to "
887 "parent directory uid %u.\n", fsp_str_dbg(fsp),
888 (unsigned int)smb_fname_parent->st.st_ex_uid));
889 /* Ensure the uid entry is updated. */
890 fsp->fsp_name->st.st_ex_uid = smb_fname_parent->st.st_ex_uid;
893 TALLOC_FREE(smb_fname_parent);
896 static NTSTATUS change_dir_owner_to_parent(connection_struct *conn,
897 const char *inherit_from_dir,
898 struct smb_filename *smb_dname,
899 SMB_STRUCT_STAT *psbuf)
901 struct smb_filename *smb_fname_parent;
902 struct smb_filename *smb_fname_cwd = NULL;
903 struct smb_filename *saved_dir_fname = NULL;
904 TALLOC_CTX *ctx = talloc_tos();
905 NTSTATUS status = NT_STATUS_OK;
908 smb_fname_parent = synthetic_smb_fname(ctx,
913 if (smb_fname_parent == NULL) {
914 return NT_STATUS_NO_MEMORY;
917 ret = SMB_VFS_STAT(conn, smb_fname_parent);
919 status = map_nt_error_from_unix(errno);
920 DEBUG(0,("change_dir_owner_to_parent: failed to stat parent "
921 "directory %s. Error was %s\n",
922 smb_fname_str_dbg(smb_fname_parent),
927 /* We've already done an lstat into psbuf, and we know it's a
928 directory. If we can cd into the directory and the dev/ino
929 are the same then we can safely chown without races as
930 we're locking the directory in place by being in it. This
931 should work on any UNIX (thanks tridge :-). JRA.
934 saved_dir_fname = vfs_GetWd(ctx,conn);
935 if (!saved_dir_fname) {
936 status = map_nt_error_from_unix(errno);
937 DEBUG(0,("change_dir_owner_to_parent: failed to get "
938 "current working directory. Error was %s\n",
943 /* Chdir into the new path. */
944 if (vfs_ChDir(conn, smb_dname) == -1) {
945 status = map_nt_error_from_unix(errno);
946 DEBUG(0,("change_dir_owner_to_parent: failed to change "
947 "current working directory to %s. Error "
948 "was %s\n", smb_dname->base_name, strerror(errno) ));
952 smb_fname_cwd = synthetic_smb_fname(ctx, ".", NULL, NULL, 0);
953 if (smb_fname_cwd == NULL) {
954 status = NT_STATUS_NO_MEMORY;
958 ret = SMB_VFS_STAT(conn, smb_fname_cwd);
960 status = map_nt_error_from_unix(errno);
961 DEBUG(0,("change_dir_owner_to_parent: failed to stat "
962 "directory '.' (%s) Error was %s\n",
963 smb_dname->base_name, strerror(errno)));
967 /* Ensure we're pointing at the same place. */
968 if (smb_fname_cwd->st.st_ex_dev != psbuf->st_ex_dev ||
969 smb_fname_cwd->st.st_ex_ino != psbuf->st_ex_ino) {
970 DEBUG(0,("change_dir_owner_to_parent: "
971 "device/inode on directory %s changed. "
972 "Refusing to chown !\n",
973 smb_dname->base_name ));
974 status = NT_STATUS_ACCESS_DENIED;
978 if (smb_fname_parent->st.st_ex_uid == smb_fname_cwd->st.st_ex_uid) {
979 /* Already this uid - no need to change. */
980 DEBUG(10,("change_dir_owner_to_parent: directory %s "
981 "is already owned by uid %d\n",
982 smb_dname->base_name,
983 (int)smb_fname_cwd->st.st_ex_uid ));
984 status = NT_STATUS_OK;
989 ret = SMB_VFS_LCHOWN(conn,
991 smb_fname_parent->st.st_ex_uid,
995 status = map_nt_error_from_unix(errno);
996 DEBUG(10,("change_dir_owner_to_parent: failed to chown "
997 "directory %s to parent directory uid %u. "
999 smb_dname->base_name,
1000 (unsigned int)smb_fname_parent->st.st_ex_uid,
1003 DEBUG(10,("change_dir_owner_to_parent: changed ownership of new "
1004 "directory %s to parent directory uid %u.\n",
1005 smb_dname->base_name,
1006 (unsigned int)smb_fname_parent->st.st_ex_uid ));
1007 /* Ensure the uid entry is updated. */
1008 psbuf->st_ex_uid = smb_fname_parent->st.st_ex_uid;
1012 vfs_ChDir(conn, saved_dir_fname);
1014 TALLOC_FREE(saved_dir_fname);
1015 TALLOC_FREE(smb_fname_parent);
1016 TALLOC_FREE(smb_fname_cwd);
1020 /****************************************************************************
1021 Open a file - returning a guaranteed ATOMIC indication of if the
1022 file was created or not.
1023 ****************************************************************************/
1025 static NTSTATUS fd_open_atomic(struct connection_struct *conn,
1031 NTSTATUS status = NT_STATUS_UNSUCCESSFUL;
1032 NTSTATUS retry_status;
1033 bool file_existed = VALID_STAT(fsp->fsp_name->st);
1036 if (!(flags & O_CREAT)) {
1038 * We're not creating the file, just pass through.
1040 status = fd_open(conn, fsp, flags, mode);
1041 *file_created = false;
1045 if (flags & O_EXCL) {
1047 * Fail if already exists, just pass through.
1049 status = fd_open(conn, fsp, flags, mode);
1052 * Here we've opened with O_CREAT|O_EXCL. If that went
1053 * NT_STATUS_OK, we *know* we created this file.
1055 *file_created = NT_STATUS_IS_OK(status);
1061 * Now it gets tricky. We have O_CREAT, but not O_EXCL.
1062 * To know absolutely if we created the file or not,
1063 * we can never call O_CREAT without O_EXCL. So if
1064 * we think the file existed, try without O_CREAT|O_EXCL.
1065 * If we think the file didn't exist, try with
1068 * The big problem here is dangling symlinks. Opening
1069 * without O_NOFOLLOW means both bad symlink
1070 * and missing path return -1, ENOENT from open(). As POSIX
1071 * is pathname based it's not possible to tell
1072 * the difference between these two cases in a
1073 * non-racy way, so change to try only two attempts before
1076 * We don't have this problem for the O_NOFOLLOW
1077 * case as it just returns NT_STATUS_OBJECT_PATH_NOT_FOUND
1078 * mapped from the ELOOP POSIX error.
1082 curr_flags = flags & ~(O_CREAT);
1083 retry_status = NT_STATUS_OBJECT_NAME_NOT_FOUND;
1085 curr_flags = flags | O_EXCL;
1086 retry_status = NT_STATUS_OBJECT_NAME_COLLISION;
1089 status = fd_open(conn, fsp, curr_flags, mode);
1090 if (NT_STATUS_IS_OK(status)) {
1091 *file_created = !file_existed;
1092 return NT_STATUS_OK;
1094 if (NT_STATUS_EQUAL(status, retry_status)) {
1096 file_existed = !file_existed;
1098 DBG_DEBUG("File %s %s. Retry.\n",
1100 file_existed ? "existed" : "did not exist");
1103 curr_flags = flags & ~(O_CREAT);
1105 curr_flags = flags | O_EXCL;
1108 status = fd_open(conn, fsp, curr_flags, mode);
1111 *file_created = (NT_STATUS_IS_OK(status) && !file_existed);
1115 /****************************************************************************
1117 ****************************************************************************/
1119 static NTSTATUS open_file(files_struct *fsp,
1120 connection_struct *conn,
1121 struct smb_request *req,
1122 const char *parent_dir,
1125 uint32_t access_mask, /* client requested access mask. */
1126 uint32_t open_access_mask, /* what we're actually using in the open. */
1127 bool *p_file_created)
1129 struct smb_filename *smb_fname = fsp->fsp_name;
1130 NTSTATUS status = NT_STATUS_OK;
1131 int accmode = (flags & O_ACCMODE);
1132 int local_flags = flags;
1133 bool file_existed = VALID_STAT(fsp->fsp_name->st);
1134 uint32_t need_fd_mask =
1140 WRITE_OWNER_ACCESS |
1141 SEC_FLAG_SYSTEM_SECURITY |
1142 READ_CONTROL_ACCESS;
1143 bool creating = !file_existed && (flags & O_CREAT);
1144 bool truncating = (flags & O_TRUNC);
1149 /* Check permissions */
1152 * This code was changed after seeing a client open request
1153 * containing the open mode of (DENY_WRITE/read-only) with
1154 * the 'create if not exist' bit set. The previous code
1155 * would fail to open the file read only on a read-only share
1156 * as it was checking the flags parameter directly against O_RDONLY,
1157 * this was failing as the flags parameter was set to O_RDONLY|O_CREAT.
1161 if (!CAN_WRITE(conn)) {
1162 /* It's a read-only share - fail if we wanted to write. */
1163 if(accmode != O_RDONLY || (flags & O_TRUNC) || (flags & O_APPEND)) {
1164 DEBUG(3,("Permission denied opening %s\n",
1165 smb_fname_str_dbg(smb_fname)));
1166 return NT_STATUS_ACCESS_DENIED;
1168 if (flags & O_CREAT) {
1169 /* We don't want to write - but we must make sure that
1170 O_CREAT doesn't create the file if we have write
1171 access into the directory.
1173 flags &= ~(O_CREAT|O_EXCL);
1174 local_flags &= ~(O_CREAT|O_EXCL);
1179 * This little piece of insanity is inspired by the
1180 * fact that an NT client can open a file for O_RDONLY,
1181 * but set the create disposition to FILE_EXISTS_TRUNCATE.
1182 * If the client *can* write to the file, then it expects to
1183 * truncate the file, even though it is opening for readonly.
1184 * Quicken uses this stupid trick in backup file creation...
1185 * Thanks *greatly* to "David W. Chapman Jr." <dwcjr@inethouston.net>
1186 * for helping track this one down. It didn't bite us in 2.0.x
1187 * as we always opened files read-write in that release. JRA.
1190 if ((accmode == O_RDONLY) && ((flags & O_TRUNC) == O_TRUNC)) {
1191 DEBUG(10,("open_file: truncate requested on read-only open "
1192 "for file %s\n", smb_fname_str_dbg(smb_fname)));
1193 local_flags = (flags & ~O_ACCMODE)|O_RDWR;
1196 if ((open_access_mask & need_fd_mask) || creating || truncating) {
1200 #if defined(O_NONBLOCK) && defined(S_ISFIFO)
1202 * We would block on opening a FIFO with no one else on the
1203 * other end. Do what we used to do and add O_NONBLOCK to the
1207 if (file_existed && S_ISFIFO(smb_fname->st.st_ex_mode)) {
1208 local_flags &= ~O_TRUNC; /* Can't truncate a FIFO. */
1209 local_flags |= O_NONBLOCK;
1214 /* Don't create files with Microsoft wildcard characters. */
1215 if (fsp->base_fsp) {
1217 * wildcard characters are allowed in stream names
1218 * only test the basefilename
1220 wild = fsp->base_fsp->fsp_name->base_name;
1222 wild = smb_fname->base_name;
1224 if ((local_flags & O_CREAT) && !file_existed &&
1225 !(fsp->posix_flags & FSP_POSIX_FLAGS_PATHNAMES) &&
1226 ms_has_wild(wild)) {
1227 return NT_STATUS_OBJECT_NAME_INVALID;
1230 /* Can we access this file ? */
1231 if (!fsp->base_fsp) {
1232 /* Only do this check on non-stream open. */
1234 status = smbd_check_access_rights(conn,
1239 if (!NT_STATUS_IS_OK(status)) {
1240 DEBUG(10, ("open_file: "
1241 "smbd_check_access_rights "
1242 "on file %s returned %s\n",
1243 smb_fname_str_dbg(smb_fname),
1244 nt_errstr(status)));
1247 if (!NT_STATUS_IS_OK(status) &&
1248 !NT_STATUS_EQUAL(status,
1249 NT_STATUS_OBJECT_NAME_NOT_FOUND))
1254 if (NT_STATUS_EQUAL(status,
1255 NT_STATUS_OBJECT_NAME_NOT_FOUND))
1257 DEBUG(10, ("open_file: "
1258 "file %s vanished since we "
1259 "checked for existence.\n",
1260 smb_fname_str_dbg(smb_fname)));
1261 file_existed = false;
1262 SET_STAT_INVALID(fsp->fsp_name->st);
1266 if (!file_existed) {
1267 if (!(local_flags & O_CREAT)) {
1268 /* File didn't exist and no O_CREAT. */
1269 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
1272 status = check_parent_access(conn,
1275 if (!NT_STATUS_IS_OK(status)) {
1276 DEBUG(10, ("open_file: "
1277 "check_parent_access on "
1278 "file %s returned %s\n",
1279 smb_fname_str_dbg(smb_fname),
1280 nt_errstr(status) ));
1287 * Actually do the open - if O_TRUNC is needed handle it
1288 * below under the share mode lock.
1290 status = fd_open_atomic(conn, fsp, local_flags & ~O_TRUNC,
1291 unx_mode, p_file_created);
1292 if (!NT_STATUS_IS_OK(status)) {
1293 DEBUG(3,("Error opening file %s (%s) (local_flags=%d) "
1294 "(flags=%d)\n", smb_fname_str_dbg(smb_fname),
1295 nt_errstr(status),local_flags,flags));
1299 if (local_flags & O_NONBLOCK) {
1301 * GPFS can return ETIMEDOUT for pread on
1302 * nonblocking file descriptors when files
1303 * migrated to tape need to be recalled. I
1304 * could imagine this happens elsewhere
1305 * too. With blocking file descriptors this
1308 ret = vfs_set_blocking(fsp, true);
1310 status = map_nt_error_from_unix(errno);
1311 DBG_WARNING("Could not set fd to blocking: "
1312 "%s\n", strerror(errno));
1318 ret = SMB_VFS_FSTAT(fsp, &smb_fname->st);
1320 /* If we have an fd, this stat should succeed. */
1321 DEBUG(0,("Error doing fstat on open file %s "
1323 smb_fname_str_dbg(smb_fname),
1325 status = map_nt_error_from_unix(errno);
1330 if (*p_file_created) {
1331 /* We created this file. */
1333 bool need_re_stat = false;
1334 /* Do all inheritance work after we've
1335 done a successful fstat call and filled
1336 in the stat struct in fsp->fsp_name. */
1338 /* Inherit the ACL if required */
1339 if (lp_inherit_permissions(SNUM(conn))) {
1340 inherit_access_posix_acl(conn, parent_dir,
1343 need_re_stat = true;
1346 /* Change the owner if required. */
1347 if (lp_inherit_owner(SNUM(conn)) != INHERIT_OWNER_NO) {
1348 change_file_owner_to_parent(conn, parent_dir,
1350 need_re_stat = true;
1354 ret = SMB_VFS_FSTAT(fsp, &smb_fname->st);
1355 /* If we have an fd, this stat should succeed. */
1357 DEBUG(0,("Error doing fstat on open file %s "
1359 smb_fname_str_dbg(smb_fname),
1364 notify_fname(conn, NOTIFY_ACTION_ADDED,
1365 FILE_NOTIFY_CHANGE_FILE_NAME,
1366 smb_fname->base_name);
1369 fsp->fh->fd = -1; /* What we used to call a stat open. */
1370 if (!file_existed) {
1371 /* File must exist for a stat open. */
1372 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
1375 status = smbd_check_access_rights(conn,
1380 if (NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND) &&
1381 (fsp->posix_flags & FSP_POSIX_FLAGS_OPEN) &&
1382 S_ISLNK(smb_fname->st.st_ex_mode)) {
1383 /* This is a POSIX stat open for delete
1384 * or rename on a symlink that points
1385 * nowhere. Allow. */
1386 DEBUG(10,("open_file: allowing POSIX "
1387 "open on bad symlink %s\n",
1388 smb_fname_str_dbg(smb_fname)));
1389 status = NT_STATUS_OK;
1392 if (!NT_STATUS_IS_OK(status)) {
1393 DEBUG(10,("open_file: "
1394 "smbd_check_access_rights on file "
1396 smb_fname_str_dbg(smb_fname),
1397 nt_errstr(status) ));
1403 * POSIX allows read-only opens of directories. We don't
1404 * want to do this (we use a different code path for this)
1405 * so catch a directory open and return an EISDIR. JRA.
1408 if(S_ISDIR(smb_fname->st.st_ex_mode)) {
1411 return NT_STATUS_FILE_IS_A_DIRECTORY;
1414 fsp->file_id = vfs_file_id_from_sbuf(conn, &smb_fname->st);
1415 fsp->vuid = req ? req->vuid : UID_FIELD_INVALID;
1416 fsp->file_pid = req ? req->smbpid : 0;
1417 fsp->fsp_flags.can_lock = true;
1418 fsp->fsp_flags.can_read = ((access_mask & FILE_READ_DATA) != 0);
1419 fsp->fsp_flags.can_write =
1421 ((access_mask & (FILE_WRITE_DATA | FILE_APPEND_DATA)) != 0);
1422 fsp->print_file = NULL;
1423 fsp->fsp_flags.modified = false;
1424 fsp->sent_oplock_break = NO_BREAK_SENT;
1425 fsp->fsp_flags.is_directory = false;
1426 if (conn->aio_write_behind_list &&
1427 is_in_path(smb_fname->base_name, conn->aio_write_behind_list,
1428 conn->case_sensitive)) {
1429 fsp->fsp_flags.aio_write_behind = true;
1432 DEBUG(2,("%s opened file %s read=%s write=%s (numopen=%d)\n",
1433 conn->session_info->unix_info->unix_name,
1434 smb_fname_str_dbg(smb_fname),
1435 BOOLSTR(fsp->fsp_flags.can_read),
1436 BOOLSTR(fsp->fsp_flags.can_write),
1437 conn->num_files_open));
1440 return NT_STATUS_OK;
1443 static bool mask_conflict(
1444 uint32_t new_access,
1445 uint32_t existing_access,
1446 uint32_t access_mask,
1447 uint32_t new_sharemode,
1448 uint32_t existing_sharemode,
1449 uint32_t sharemode_mask)
1451 bool want_access = (new_access & access_mask);
1452 bool allow_existing = (existing_sharemode & sharemode_mask);
1453 bool have_access = (existing_access & access_mask);
1454 bool allow_new = (new_sharemode & sharemode_mask);
1456 if (want_access && !allow_existing) {
1457 DBG_DEBUG("Access request 0x%"PRIx32"/0x%"PRIx32" conflicts "
1458 "with existing sharemode 0x%"PRIx32"/0x%"PRIx32"\n",
1465 if (have_access && !allow_new) {
1466 DBG_DEBUG("Sharemode request 0x%"PRIx32"/0x%"PRIx32" conflicts "
1467 "with existing access 0x%"PRIx32"/0x%"PRIx32"\n",
1477 /****************************************************************************
1478 Check if we can open a file with a share mode.
1479 Returns True if conflict, False if not.
1480 ****************************************************************************/
1482 static bool share_conflict(uint32_t e_access_mask,
1483 uint32_t e_share_access,
1484 uint32_t access_mask,
1485 uint32_t share_access)
1487 const uint32_t conflicting_access =
1495 DBG_DEBUG("existing access_mask = 0x%"PRIx32", "
1496 "existing share access = 0x%"PRIx32", "
1497 "access_mask = 0x%"PRIx32", "
1498 "share_access = 0x%"PRIx32"\n",
1504 if ((e_access_mask & conflicting_access) == 0) {
1505 DBG_DEBUG("No conflict due to "
1506 "existing access_mask = 0x%"PRIx32"\n",
1510 if ((access_mask & conflicting_access) == 0) {
1511 DBG_DEBUG("No conflict due to access_mask = 0x%"PRIx32"\n",
1516 conflict = mask_conflict(
1517 access_mask, e_access_mask, FILE_WRITE_DATA | FILE_APPEND_DATA,
1518 share_access, e_share_access, FILE_SHARE_WRITE);
1519 conflict |= mask_conflict(
1520 access_mask, e_access_mask, FILE_READ_DATA | FILE_EXECUTE,
1521 share_access, e_share_access, FILE_SHARE_READ);
1522 conflict |= mask_conflict(
1523 access_mask, e_access_mask, DELETE_ACCESS,
1524 share_access, e_share_access, FILE_SHARE_DELETE);
1526 DBG_DEBUG("conflict=%s\n", conflict ? "true" : "false");
1530 #if defined(DEVELOPER)
1532 struct validate_my_share_entries_state {
1533 struct smbd_server_connection *sconn;
1535 struct server_id self;
1538 static bool validate_my_share_entries_fn(
1539 struct share_mode_entry *e,
1543 struct validate_my_share_entries_state *state = private_data;
1546 if (!server_id_equal(&state->self, &e->pid)) {
1550 if (e->op_mid == 0) {
1551 /* INTERNAL_OPEN_ONLY */
1555 fsp = file_find_dif(state->sconn, state->fid, e->share_file_id);
1557 DBG_ERR("PANIC : %s\n",
1558 share_mode_str(talloc_tos(), 0, &state->fid, e));
1559 smb_panic("validate_my_share_entries: Cannot match a "
1560 "share entry with an open file\n");
1563 if (((uint16_t)fsp->oplock_type) != e->op_type) {
1572 DBG_ERR("validate_my_share_entries: PANIC : %s\n",
1573 share_mode_str(talloc_tos(), 0, &state->fid, e));
1574 str = talloc_asprintf(talloc_tos(),
1575 "validate_my_share_entries: "
1576 "file %s, oplock_type = 0x%x, op_type = 0x%x\n",
1577 fsp->fsp_name->base_name,
1578 (unsigned int)fsp->oplock_type,
1579 (unsigned int)e->op_type);
1587 bool is_stat_open(uint32_t access_mask)
1589 const uint32_t stat_open_bits =
1590 (SYNCHRONIZE_ACCESS|
1591 FILE_READ_ATTRIBUTES|
1592 FILE_WRITE_ATTRIBUTES);
1594 return (((access_mask & stat_open_bits) != 0) &&
1595 ((access_mask & ~stat_open_bits) == 0));
1598 struct has_delete_on_close_state {
1602 static bool has_delete_on_close_fn(
1603 struct share_mode_entry *e,
1607 struct has_delete_on_close_state *state = private_data;
1608 state->ret = !share_entry_stale_pid(e);
1612 static bool has_delete_on_close(struct share_mode_lock *lck,
1615 struct has_delete_on_close_state state = { .ret = false };
1618 if (!is_delete_on_close_set(lck, name_hash)) {
1622 ok= share_mode_forall_entries(lck, has_delete_on_close_fn, &state);
1624 DBG_DEBUG("share_mode_forall_entries failed\n");
1630 static void share_mode_flags_get(
1632 uint32_t *access_mask,
1633 uint32_t *share_mode,
1634 uint32_t *lease_type)
1636 if (access_mask != NULL) {
1638 ((flags & SHARE_MODE_ACCESS_READ) ?
1639 FILE_READ_DATA : 0) |
1640 ((flags & SHARE_MODE_ACCESS_WRITE) ?
1641 FILE_WRITE_DATA : 0) |
1642 ((flags & SHARE_MODE_ACCESS_DELETE) ?
1645 if (share_mode != NULL) {
1647 ((flags & SHARE_MODE_SHARE_READ) ?
1648 FILE_SHARE_READ : 0) |
1649 ((flags & SHARE_MODE_SHARE_WRITE) ?
1650 FILE_SHARE_WRITE : 0) |
1651 ((flags & SHARE_MODE_SHARE_DELETE) ?
1652 FILE_SHARE_DELETE : 0);
1654 if (lease_type != NULL) {
1656 ((flags & SHARE_MODE_LEASE_READ) ?
1657 SMB2_LEASE_READ : 0) |
1658 ((flags & SHARE_MODE_LEASE_WRITE) ?
1659 SMB2_LEASE_WRITE : 0) |
1660 ((flags & SHARE_MODE_LEASE_HANDLE) ?
1661 SMB2_LEASE_HANDLE : 0);
1665 static uint16_t share_mode_flags_set(
1667 uint32_t access_mask,
1668 uint32_t share_mode,
1669 uint32_t lease_type)
1671 if (access_mask != UINT32_MAX) {
1672 flags &= ~(SHARE_MODE_ACCESS_READ|
1673 SHARE_MODE_ACCESS_WRITE|
1674 SHARE_MODE_ACCESS_DELETE);
1675 flags |= (access_mask & (FILE_READ_DATA | FILE_EXECUTE)) ?
1676 SHARE_MODE_ACCESS_READ : 0;
1677 flags |= (access_mask & (FILE_WRITE_DATA | FILE_APPEND_DATA)) ?
1678 SHARE_MODE_ACCESS_WRITE : 0;
1679 flags |= (access_mask & (DELETE_ACCESS)) ?
1680 SHARE_MODE_ACCESS_DELETE : 0;
1682 if (share_mode != UINT32_MAX) {
1683 flags &= ~(SHARE_MODE_SHARE_READ|
1684 SHARE_MODE_SHARE_WRITE|
1685 SHARE_MODE_SHARE_DELETE);
1686 flags |= (share_mode & FILE_SHARE_READ) ?
1687 SHARE_MODE_SHARE_READ : 0;
1688 flags |= (share_mode & FILE_SHARE_WRITE) ?
1689 SHARE_MODE_SHARE_WRITE : 0;
1690 flags |= (share_mode & FILE_SHARE_DELETE) ?
1691 SHARE_MODE_SHARE_DELETE : 0;
1693 if (lease_type != UINT32_MAX) {
1694 flags &= ~(SHARE_MODE_LEASE_READ|
1695 SHARE_MODE_LEASE_WRITE|
1696 SHARE_MODE_LEASE_HANDLE);
1697 flags |= (lease_type & SMB2_LEASE_READ) ?
1698 SHARE_MODE_LEASE_READ : 0;
1699 flags |= (lease_type & SMB2_LEASE_WRITE) ?
1700 SHARE_MODE_LEASE_WRITE : 0;
1701 flags |= (lease_type & SMB2_LEASE_HANDLE) ?
1702 SHARE_MODE_LEASE_HANDLE : 0;
1708 static uint16_t share_mode_flags_restrict(
1710 uint32_t access_mask,
1711 uint32_t share_mode,
1712 uint32_t lease_type)
1714 uint32_t existing_access_mask, existing_share_mode;
1715 uint32_t existing_lease_type;
1718 share_mode_flags_get(
1720 &existing_access_mask,
1721 &existing_share_mode,
1722 &existing_lease_type);
1724 existing_access_mask |= access_mask;
1725 existing_share_mode &= share_mode;
1726 existing_lease_type |= lease_type;
1728 ret = share_mode_flags_set(
1730 existing_access_mask,
1731 existing_share_mode,
1732 existing_lease_type);
1736 /****************************************************************************
1737 Deal with share modes
1738 Invariant: Share mode must be locked on entry and exit.
1739 Returns -1 on error, or number of share modes on success (may be zero).
1740 ****************************************************************************/
1742 struct open_mode_check_state {
1744 uint32_t access_mask;
1745 uint32_t share_access;
1746 uint32_t lease_type;
1749 static bool open_mode_check_fn(
1750 struct share_mode_entry *e,
1754 struct open_mode_check_state *state = private_data;
1755 bool disconnected, stale;
1756 uint32_t access_mask, share_access, lease_type;
1758 disconnected = server_id_is_disconnected(&e->pid);
1763 access_mask = state->access_mask | e->access_mask;
1764 share_access = state->share_access & e->share_access;
1765 lease_type = state->lease_type | get_lease_type(e, state->fid);
1767 if ((access_mask == state->access_mask) &&
1768 (share_access == state->share_access) &&
1769 (lease_type == state->lease_type)) {
1773 stale = share_entry_stale_pid(e);
1778 state->access_mask = access_mask;
1779 state->share_access = share_access;
1780 state->lease_type = lease_type;
1785 static NTSTATUS open_mode_check(connection_struct *conn,
1786 struct share_mode_lock *lck,
1787 uint32_t access_mask,
1788 uint32_t share_access)
1790 struct share_mode_data *d = lck->data;
1791 struct open_mode_check_state state;
1793 bool ok, conflict, have_share_entries;
1795 if (is_stat_open(access_mask)) {
1796 /* Stat open that doesn't trigger oplock breaks or share mode
1797 * checks... ! JRA. */
1798 return NT_STATUS_OK;
1802 * Check if the share modes will give us access.
1805 #if defined(DEVELOPER)
1807 struct validate_my_share_entries_state validate_state = {
1808 .sconn = conn->sconn,
1810 .self = messaging_server_id(conn->sconn->msg_ctx),
1812 ok = share_mode_forall_entries(
1813 lck, validate_my_share_entries_fn, &validate_state);
1818 have_share_entries = share_mode_have_entries(lck);
1819 if (!have_share_entries) {
1821 * This is a fresh share mode lock where no conflicts
1824 return NT_STATUS_OK;
1827 share_mode_flags_get(
1828 d->flags, &state.access_mask, &state.share_access, NULL);
1830 conflict = share_conflict(
1836 DBG_DEBUG("No conflict due to share_mode_flags access\n");
1837 return NT_STATUS_OK;
1840 state = (struct open_mode_check_state) {
1842 .share_access = (FILE_SHARE_READ|
1848 * Walk the share mode array to recalculate d->flags
1851 ok = share_mode_forall_entries(lck, open_mode_check_fn, &state);
1853 DBG_DEBUG("share_mode_forall_entries failed\n");
1854 return NT_STATUS_INTERNAL_ERROR;
1857 new_flags = share_mode_flags_set(
1858 0, state.access_mask, state.share_access, state.lease_type);
1859 if (new_flags == d->flags) {
1861 * We only end up here if we had a sharing violation
1862 * from d->flags and have recalculated it.
1864 return NT_STATUS_SHARING_VIOLATION;
1867 d->flags = new_flags;
1870 conflict = share_conflict(
1876 DBG_DEBUG("No conflict due to share_mode_flags access\n");
1877 return NT_STATUS_OK;
1880 return NT_STATUS_SHARING_VIOLATION;
1884 * Send a break message to the oplock holder and delay the open for
1888 NTSTATUS send_break_message(struct messaging_context *msg_ctx,
1889 const struct file_id *id,
1890 const struct share_mode_entry *exclusive,
1893 struct oplock_break_message msg = {
1895 .share_file_id = exclusive->share_file_id,
1896 .break_to = break_to,
1898 enum ndr_err_code ndr_err;
1903 struct server_id_buf buf;
1904 DBG_DEBUG("Sending break message to %s\n",
1905 server_id_str_buf(exclusive->pid, &buf));
1906 NDR_PRINT_DEBUG(oplock_break_message, &msg);
1909 ndr_err = ndr_push_struct_blob(
1913 (ndr_push_flags_fn_t)ndr_push_oplock_break_message);
1914 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
1915 DBG_WARNING("ndr_push_oplock_break_message failed: %s\n",
1916 ndr_errstr(ndr_err));
1917 return ndr_map_error2ntstatus(ndr_err);
1920 status = messaging_send(
1921 msg_ctx, exclusive->pid, MSG_SMB_BREAK_REQUEST, &blob);
1922 TALLOC_FREE(blob.data);
1923 if (!NT_STATUS_IS_OK(status)) {
1924 DEBUG(3, ("Could not send oplock break message: %s\n",
1925 nt_errstr(status)));
1931 struct validate_oplock_types_state {
1937 uint32_t num_non_stat_opens;
1940 static bool validate_oplock_types_fn(
1941 struct share_mode_entry *e,
1945 struct validate_oplock_types_state *state = private_data;
1947 if (e->op_mid == 0) {
1948 /* INTERNAL_OPEN_ONLY */
1952 if (e->op_type == NO_OPLOCK && is_stat_open(e->access_mask)) {
1954 * We ignore stat opens in the table - they always
1955 * have NO_OPLOCK and never get or cause breaks. JRA.
1960 state->num_non_stat_opens += 1;
1962 if (BATCH_OPLOCK_TYPE(e->op_type)) {
1963 /* batch - can only be one. */
1964 if (share_entry_stale_pid(e)) {
1965 DBG_DEBUG("Found stale batch oplock\n");
1968 if (state->ex_or_batch ||
1972 DBG_ERR("Bad batch oplock entry\n");
1973 state->valid = false;
1976 state->batch = true;
1979 if (EXCLUSIVE_OPLOCK_TYPE(e->op_type)) {
1980 if (share_entry_stale_pid(e)) {
1981 DBG_DEBUG("Found stale duplicate oplock\n");
1984 /* Exclusive or batch - can only be one. */
1985 if (state->ex_or_batch ||
1988 DBG_ERR("Bad exclusive or batch oplock entry\n");
1989 state->valid = false;
1992 state->ex_or_batch = true;
1995 if (LEVEL_II_OPLOCK_TYPE(e->op_type)) {
1996 if (state->batch || state->ex_or_batch) {
1997 if (share_entry_stale_pid(e)) {
1998 DBG_DEBUG("Found stale LevelII oplock\n");
2001 DBG_DEBUG("Bad levelII oplock entry\n");
2002 state->valid = false;
2005 state->level2 = true;
2008 if (e->op_type == NO_OPLOCK) {
2009 if (state->batch || state->ex_or_batch) {
2010 if (share_entry_stale_pid(e)) {
2011 DBG_DEBUG("Found stale NO_OPLOCK entry\n");
2014 DBG_ERR("Bad no oplock entry\n");
2015 state->valid = false;
2018 state->no_oplock = true;
2025 * Do internal consistency checks on the share mode for a file.
2028 static bool validate_oplock_types(struct share_mode_lock *lck)
2030 struct validate_oplock_types_state state = { .valid = true };
2033 ok = share_mode_forall_entries(lck, validate_oplock_types_fn, &state);
2035 DBG_DEBUG("share_mode_forall_entries failed\n");
2039 DBG_DEBUG("Got invalid oplock configuration\n");
2043 if ((state.batch || state.ex_or_batch) &&
2044 (state.num_non_stat_opens != 1)) {
2045 DBG_WARNING("got batch (%d) or ex (%d) non-exclusively "
2048 (int)state.ex_or_batch,
2049 state.num_non_stat_opens);
2056 static bool is_same_lease(const files_struct *fsp,
2057 const struct share_mode_entry *e,
2058 const struct smb2_lease *lease)
2060 if (e->op_type != LEASE_OPLOCK) {
2063 if (lease == NULL) {
2067 return smb2_lease_equal(fsp_client_guid(fsp),
2073 static bool file_has_brlocks(files_struct *fsp)
2075 struct byte_range_lock *br_lck;
2077 br_lck = brl_get_locks_readonly(fsp);
2081 return (brl_num_locks(br_lck) > 0);
2084 struct fsp_lease *find_fsp_lease(struct files_struct *new_fsp,
2085 const struct smb2_lease_key *key,
2086 uint32_t current_state,
2087 uint16_t lease_version,
2088 uint16_t lease_epoch)
2090 struct files_struct *fsp;
2093 * TODO: Measure how expensive this loop is with thousands of open
2097 for (fsp = file_find_di_first(new_fsp->conn->sconn, new_fsp->file_id);
2099 fsp = file_find_di_next(fsp)) {
2101 if (fsp == new_fsp) {
2104 if (fsp->oplock_type != LEASE_OPLOCK) {
2107 if (smb2_lease_key_equal(&fsp->lease->lease.lease_key, key)) {
2108 fsp->lease->ref_count += 1;
2113 /* Not found - must be leased in another smbd. */
2114 new_fsp->lease = talloc_zero(new_fsp->conn->sconn, struct fsp_lease);
2115 if (new_fsp->lease == NULL) {
2118 new_fsp->lease->ref_count = 1;
2119 new_fsp->lease->sconn = new_fsp->conn->sconn;
2120 new_fsp->lease->lease.lease_key = *key;
2121 new_fsp->lease->lease.lease_state = current_state;
2123 * We internally treat all leases as V2 and update
2124 * the epoch, but when sending breaks it matters if
2125 * the requesting lease was v1 or v2.
2127 new_fsp->lease->lease.lease_version = lease_version;
2128 new_fsp->lease->lease.lease_epoch = lease_epoch;
2129 return new_fsp->lease;
2132 static NTSTATUS try_lease_upgrade(struct files_struct *fsp,
2133 struct share_mode_lock *lck,
2134 const struct GUID *client_guid,
2135 const struct smb2_lease *lease,
2139 uint32_t current_state, breaking_to_requested, breaking_to_required;
2141 uint16_t lease_version, epoch;
2142 uint32_t existing, requested;
2145 status = leases_db_get(
2151 &breaking_to_requested,
2152 &breaking_to_required,
2155 if (!NT_STATUS_IS_OK(status)) {
2159 fsp->lease = find_fsp_lease(
2165 if (fsp->lease == NULL) {
2166 DEBUG(1, ("Did not find existing lease for file %s\n",
2168 return NT_STATUS_NO_MEMORY;
2172 * Upgrade only if the requested lease is a strict upgrade.
2174 existing = current_state;
2175 requested = lease->lease_state;
2178 * Tricky: This test makes sure that "requested" is a
2179 * strict bitwise superset of "existing".
2181 do_upgrade = ((existing & requested) == existing);
2184 * Upgrade only if there's a change.
2186 do_upgrade &= (granted != existing);
2189 * Upgrade only if other leases don't prevent what was asked
2192 do_upgrade &= (granted == requested);
2195 * only upgrade if we are not in breaking state
2197 do_upgrade &= !breaking;
2199 DEBUG(10, ("existing=%"PRIu32", requested=%"PRIu32", "
2200 "granted=%"PRIu32", do_upgrade=%d\n",
2201 existing, requested, granted, (int)do_upgrade));
2204 NTSTATUS set_status;
2206 current_state = granted;
2209 set_status = leases_db_set(
2214 breaking_to_requested,
2215 breaking_to_required,
2219 if (!NT_STATUS_IS_OK(set_status)) {
2220 DBG_DEBUG("leases_db_set failed: %s\n",
2221 nt_errstr(set_status));
2226 fsp_lease_update(fsp);
2228 return NT_STATUS_OK;
2231 static NTSTATUS grant_new_fsp_lease(struct files_struct *fsp,
2232 struct share_mode_lock *lck,
2233 const struct GUID *client_guid,
2234 const struct smb2_lease *lease,
2237 struct share_mode_data *d = lck->data;
2240 fsp->lease = talloc_zero(fsp->conn->sconn, struct fsp_lease);
2241 if (fsp->lease == NULL) {
2242 return NT_STATUS_INSUFFICIENT_RESOURCES;
2244 fsp->lease->ref_count = 1;
2245 fsp->lease->sconn = fsp->conn->sconn;
2246 fsp->lease->lease.lease_version = lease->lease_version;
2247 fsp->lease->lease.lease_key = lease->lease_key;
2248 fsp->lease->lease.lease_state = granted;
2249 fsp->lease->lease.lease_epoch = lease->lease_epoch + 1;
2251 status = leases_db_add(client_guid,
2254 fsp->lease->lease.lease_state,
2255 fsp->lease->lease.lease_version,
2256 fsp->lease->lease.lease_epoch,
2257 fsp->conn->connectpath,
2258 fsp->fsp_name->base_name,
2259 fsp->fsp_name->stream_name);
2260 if (!NT_STATUS_IS_OK(status)) {
2261 DEBUG(10, ("%s: leases_db_add failed: %s\n", __func__,
2262 nt_errstr(status)));
2263 TALLOC_FREE(fsp->lease);
2264 return NT_STATUS_INSUFFICIENT_RESOURCES;
2269 return NT_STATUS_OK;
2272 static NTSTATUS grant_fsp_lease(struct files_struct *fsp,
2273 struct share_mode_lock *lck,
2274 const struct smb2_lease *lease,
2277 const struct GUID *client_guid = fsp_client_guid(fsp);
2280 status = try_lease_upgrade(fsp, lck, client_guid, lease, granted);
2282 if (NT_STATUS_EQUAL(status, NT_STATUS_NOT_FOUND)) {
2283 status = grant_new_fsp_lease(
2284 fsp, lck, client_guid, lease, granted);
2290 static int map_lease_type_to_oplock(uint32_t lease_type)
2292 int result = NO_OPLOCK;
2294 switch (lease_type) {
2295 case SMB2_LEASE_READ|SMB2_LEASE_WRITE|SMB2_LEASE_HANDLE:
2296 result = BATCH_OPLOCK|EXCLUSIVE_OPLOCK;
2298 case SMB2_LEASE_READ|SMB2_LEASE_WRITE:
2299 result = EXCLUSIVE_OPLOCK;
2301 case SMB2_LEASE_READ|SMB2_LEASE_HANDLE:
2302 case SMB2_LEASE_READ:
2303 result = LEVEL_II_OPLOCK;
2310 struct delay_for_oplock_state {
2311 struct files_struct *fsp;
2312 const struct smb2_lease *lease;
2313 bool will_overwrite;
2314 uint32_t delay_mask;
2315 bool first_open_attempt;
2316 bool got_handle_lease;
2318 bool have_other_lease;
2322 static bool delay_for_oplock_fn(
2323 struct share_mode_entry *e,
2327 struct delay_for_oplock_state *state = private_data;
2328 struct files_struct *fsp = state->fsp;
2329 const struct smb2_lease *lease = state->lease;
2330 bool e_is_lease = (e->op_type == LEASE_OPLOCK);
2331 uint32_t e_lease_type = get_lease_type(e, fsp->file_id);
2333 bool lease_is_breaking = false;
2338 if (lease != NULL) {
2339 bool our_lease = is_same_lease(fsp, e, lease);
2341 DBG_DEBUG("Ignoring our own lease\n");
2346 status = leases_db_get(
2350 NULL, /* current_state */
2352 NULL, /* breaking_to_requested */
2353 NULL, /* breaking_to_required */
2354 NULL, /* lease_version */
2356 SMB_ASSERT(NT_STATUS_IS_OK(status));
2359 if (!state->got_handle_lease &&
2360 ((e_lease_type & SMB2_LEASE_HANDLE) != 0) &&
2361 !share_entry_stale_pid(e)) {
2362 state->got_handle_lease = true;
2365 if (!state->got_oplock &&
2366 (e->op_type != LEASE_OPLOCK) &&
2367 !share_entry_stale_pid(e)) {
2368 state->got_oplock = true;
2371 if (!state->have_other_lease &&
2372 !is_same_lease(fsp, e, lease) &&
2373 !share_entry_stale_pid(e)) {
2374 state->have_other_lease = true;
2377 break_to = e_lease_type & ~state->delay_mask;
2379 if (state->will_overwrite) {
2380 break_to &= ~(SMB2_LEASE_HANDLE|SMB2_LEASE_READ);
2383 DBG_DEBUG("e_lease_type %u, will_overwrite: %u\n",
2384 (unsigned)e_lease_type,
2385 (unsigned)state->will_overwrite);
2387 if ((e_lease_type & ~break_to) == 0) {
2388 if (lease_is_breaking) {
2389 state->delay = true;
2394 if (share_entry_stale_pid(e)) {
2398 if (state->will_overwrite) {
2400 * If we break anyway break to NONE directly.
2401 * Otherwise vfs_set_filelen() will trigger the
2404 break_to &= ~(SMB2_LEASE_READ|SMB2_LEASE_WRITE);
2409 * Oplocks only support breaking to R or NONE.
2411 break_to &= ~(SMB2_LEASE_HANDLE|SMB2_LEASE_WRITE);
2414 DBG_DEBUG("breaking from %d to %d\n",
2418 fsp->conn->sconn->msg_ctx, &fsp->file_id, e, break_to);
2419 if (e_lease_type & state->delay_mask) {
2420 state->delay = true;
2422 if (lease_is_breaking && !state->first_open_attempt) {
2423 state->delay = true;
2429 static NTSTATUS delay_for_oplock(files_struct *fsp,
2431 const struct smb2_lease *lease,
2432 struct share_mode_lock *lck,
2433 bool have_sharing_violation,
2434 uint32_t create_disposition,
2435 bool first_open_attempt)
2437 struct delay_for_oplock_state state = {
2440 .first_open_attempt = first_open_attempt,
2446 if (is_stat_open(fsp->access_mask)) {
2450 state.delay_mask = have_sharing_violation ?
2451 SMB2_LEASE_HANDLE : SMB2_LEASE_WRITE;
2453 switch (create_disposition) {
2454 case FILE_SUPERSEDE:
2455 case FILE_OVERWRITE:
2456 case FILE_OVERWRITE_IF:
2457 state.will_overwrite = true;
2460 state.will_overwrite = false;
2464 ok = share_mode_forall_entries(lck, delay_for_oplock_fn, &state);
2466 return NT_STATUS_INTERNAL_ERROR;
2470 return NT_STATUS_RETRY;
2474 if (have_sharing_violation) {
2475 return NT_STATUS_SHARING_VIOLATION;
2478 if (oplock_request == LEASE_OPLOCK) {
2479 if (lease == NULL) {
2481 * The SMB2 layer should have checked this
2483 return NT_STATUS_INTERNAL_ERROR;
2486 granted = lease->lease_state;
2488 if (lp_kernel_oplocks(SNUM(fsp->conn))) {
2489 DEBUG(10, ("No lease granted because kernel oplocks are enabled\n"));
2490 granted = SMB2_LEASE_NONE;
2492 if ((granted & (SMB2_LEASE_READ|SMB2_LEASE_WRITE)) == 0) {
2493 DEBUG(10, ("No read or write lease requested\n"));
2494 granted = SMB2_LEASE_NONE;
2496 if (granted == SMB2_LEASE_WRITE) {
2497 DEBUG(10, ("pure write lease requested\n"));
2498 granted = SMB2_LEASE_NONE;
2500 if (granted == (SMB2_LEASE_WRITE|SMB2_LEASE_HANDLE)) {
2501 DEBUG(10, ("write and handle lease requested\n"));
2502 granted = SMB2_LEASE_NONE;
2505 granted = map_oplock_to_lease_type(
2506 oplock_request & ~SAMBA_PRIVATE_OPLOCK_MASK);
2509 if (lp_locking(fsp->conn->params) && file_has_brlocks(fsp)) {
2510 DBG_DEBUG("file %s has byte range locks\n",
2512 granted &= ~SMB2_LEASE_READ;
2515 if (state.have_other_lease) {
2517 * Can grant only one writer
2519 granted &= ~SMB2_LEASE_WRITE;
2522 if ((granted & SMB2_LEASE_READ) && !(granted & SMB2_LEASE_WRITE)) {
2524 (global_client_caps & CAP_LEVEL_II_OPLOCKS) &&
2525 lp_level2_oplocks(SNUM(fsp->conn));
2527 if (!allow_level2) {
2528 granted = SMB2_LEASE_NONE;
2532 if (oplock_request == LEASE_OPLOCK) {
2533 if (state.got_oplock) {
2534 granted &= ~SMB2_LEASE_HANDLE;
2537 fsp->oplock_type = LEASE_OPLOCK;
2539 status = grant_fsp_lease(fsp, lck, lease, granted);
2540 if (!NT_STATUS_IS_OK(status)) {
2545 DBG_DEBUG("lease_state=%d\n", fsp->lease->lease.lease_state);
2547 if (state.got_handle_lease) {
2548 granted = SMB2_LEASE_NONE;
2551 fsp->oplock_type = map_lease_type_to_oplock(granted);
2553 status = set_file_oplock(fsp);
2554 if (!NT_STATUS_IS_OK(status)) {
2556 * Could not get the kernel oplock
2558 fsp->oplock_type = NO_OPLOCK;
2562 if ((granted & SMB2_LEASE_READ) &&
2563 ((lck->data->flags & SHARE_MODE_LEASE_READ) == 0)) {
2564 lck->data->flags |= SHARE_MODE_LEASE_READ;
2565 lck->data->modified = true;
2568 DBG_DEBUG("oplock type 0x%x on file %s\n",
2569 fsp->oplock_type, fsp_str_dbg(fsp));
2571 return NT_STATUS_OK;
2574 static NTSTATUS handle_share_mode_lease(
2576 struct share_mode_lock *lck,
2577 uint32_t create_disposition,
2578 uint32_t access_mask,
2579 uint32_t share_access,
2581 const struct smb2_lease *lease,
2582 bool first_open_attempt)
2584 bool sharing_violation = false;
2587 status = open_mode_check(
2588 fsp->conn, lck, access_mask, share_access);
2589 if (NT_STATUS_EQUAL(status, NT_STATUS_SHARING_VIOLATION)) {
2590 sharing_violation = true;
2591 status = NT_STATUS_OK; /* handled later */
2594 if (!NT_STATUS_IS_OK(status)) {
2598 if (oplock_request == INTERNAL_OPEN_ONLY) {
2599 if (sharing_violation) {
2600 DBG_DEBUG("Sharing violation for internal open\n");
2601 return NT_STATUS_SHARING_VIOLATION;
2605 * Internal opens never do oplocks or leases. We don't
2606 * need to go through delay_for_oplock().
2608 fsp->oplock_type = NO_OPLOCK;
2610 return NT_STATUS_OK;
2613 status = delay_for_oplock(
2620 first_open_attempt);
2621 if (!NT_STATUS_IS_OK(status)) {
2625 return NT_STATUS_OK;
2628 static bool request_timed_out(struct smb_request *req, struct timeval timeout)
2630 struct timeval now, end_time;
2632 end_time = timeval_sum(&req->request_time, &timeout);
2633 return (timeval_compare(&end_time, &now) < 0);
2636 struct defer_open_state {
2637 struct smbXsrv_connection *xconn;
2641 static void defer_open_done(struct tevent_req *req);
2644 * Defer an open and watch a locking.tdb record
2646 * This defers an open that gets rescheduled once the locking.tdb record watch
2647 * is triggered by a change to the record.
2649 * It is used to defer opens that triggered an oplock break and for the SMB1
2650 * sharing violation delay.
2652 static void defer_open(struct share_mode_lock *lck,
2653 struct timeval timeout,
2654 struct smb_request *req,
2657 struct deferred_open_record *open_rec = NULL;
2658 struct timeval abs_timeout;
2659 struct defer_open_state *watch_state;
2660 struct tevent_req *watch_req;
2661 struct timeval_buf tvbuf1, tvbuf2;
2662 struct file_id_buf fbuf;
2665 abs_timeout = timeval_sum(&req->request_time, &timeout);
2667 DBG_DEBUG("request time [%s] timeout [%s] mid [%" PRIu64 "] "
2669 timeval_str_buf(&req->request_time, false, true, &tvbuf1),
2670 timeval_str_buf(&abs_timeout, false, true, &tvbuf2),
2672 file_id_str_buf(id, &fbuf));
2674 open_rec = talloc_zero(NULL, struct deferred_open_record);
2675 if (open_rec == NULL) {
2677 exit_server("talloc failed");
2680 watch_state = talloc(open_rec, struct defer_open_state);
2681 if (watch_state == NULL) {
2682 exit_server("talloc failed");
2684 watch_state->xconn = req->xconn;
2685 watch_state->mid = req->mid;
2687 DBG_DEBUG("defering mid %" PRIu64 "\n", req->mid);
2689 watch_req = share_mode_watch_send(
2693 (struct server_id){0});
2694 if (watch_req == NULL) {
2695 exit_server("Could not watch share mode record");
2697 tevent_req_set_callback(watch_req, defer_open_done, watch_state);
2699 ok = tevent_req_set_endtime(watch_req, req->sconn->ev_ctx, abs_timeout);
2701 exit_server("tevent_req_set_endtime failed");
2704 ok = push_deferred_open_message_smb(req, timeout, id, open_rec);
2707 exit_server("push_deferred_open_message_smb failed");
2711 static void defer_open_done(struct tevent_req *req)
2713 struct defer_open_state *state = tevent_req_callback_data(
2714 req, struct defer_open_state);
2718 status = share_mode_watch_recv(req, NULL, NULL);
2720 if (!NT_STATUS_IS_OK(status)) {
2721 DEBUG(5, ("dbwrap_watched_watch_recv returned %s\n",
2722 nt_errstr(status)));
2724 * Even if it failed, retry anyway. TODO: We need a way to
2725 * tell a re-scheduled open about that error.
2729 DEBUG(10, ("scheduling mid %llu\n", (unsigned long long)state->mid));
2731 ret = schedule_deferred_open_message_smb(state->xconn, state->mid);
2737 * Actually attempt the kernel oplock polling open.
2740 static void poll_open_fn(struct tevent_context *ev,
2741 struct tevent_timer *te,
2742 struct timeval current_time,
2745 struct deferred_open_record *open_rec = talloc_get_type_abort(
2746 private_data, struct deferred_open_record);
2749 TALLOC_FREE(open_rec->watch_req);
2751 ok = schedule_deferred_open_message_smb(
2752 open_rec->xconn, open_rec->mid);
2754 exit_server("schedule_deferred_open_message_smb failed");
2756 DBG_DEBUG("timer fired. Retrying open !\n");
2759 static void poll_open_done(struct tevent_req *subreq);
2762 * Reschedule an open for 1 second from now, if not timed out.
2764 static bool setup_poll_open(
2765 struct smb_request *req,
2766 struct share_mode_lock *lck,
2768 struct timeval max_timeout,
2769 struct timeval interval)
2772 struct deferred_open_record *open_rec = NULL;
2773 struct timeval endtime, next_interval;
2774 struct file_id_buf ftmp;
2776 if (request_timed_out(req, max_timeout)) {
2780 open_rec = talloc_zero(NULL, struct deferred_open_record);
2781 if (open_rec == NULL) {
2782 DBG_WARNING("talloc failed\n");
2785 open_rec->xconn = req->xconn;
2786 open_rec->mid = req->mid;
2789 * Make sure open_rec->te does not come later than the
2790 * request's maximum endtime.
2793 endtime = timeval_sum(&req->request_time, &max_timeout);
2794 next_interval = timeval_current_ofs(interval.tv_sec, interval.tv_usec);
2795 next_interval = timeval_min(&endtime, &next_interval);
2797 open_rec->te = tevent_add_timer(
2803 if (open_rec->te == NULL) {
2804 DBG_WARNING("tevent_add_timer failed\n");
2805 TALLOC_FREE(open_rec);
2810 open_rec->watch_req = share_mode_watch_send(
2814 (struct server_id) {0});
2815 if (open_rec->watch_req == NULL) {
2816 DBG_WARNING("share_mode_watch_send failed\n");
2817 TALLOC_FREE(open_rec);
2820 tevent_req_set_callback(
2821 open_rec->watch_req, poll_open_done, open_rec);
2824 ok = push_deferred_open_message_smb(req, max_timeout, id, open_rec);
2826 DBG_WARNING("push_deferred_open_message_smb failed\n");
2827 TALLOC_FREE(open_rec);
2831 DBG_DEBUG("poll request time [%s] mid [%" PRIu64 "] file_id [%s]\n",
2832 timeval_string(talloc_tos(), &req->request_time, false),
2834 file_id_str_buf(id, &ftmp));
2839 static void poll_open_done(struct tevent_req *subreq)
2841 struct deferred_open_record *open_rec = tevent_req_callback_data(
2842 subreq, struct deferred_open_record);
2846 status = share_mode_watch_recv(subreq, NULL, NULL);
2847 TALLOC_FREE(subreq);
2848 DBG_DEBUG("dbwrap_watched_watch_recv returned %s\n",
2851 ok = schedule_deferred_open_message_smb(
2852 open_rec->xconn, open_rec->mid);
2854 exit_server("schedule_deferred_open_message_smb failed");
2858 bool defer_smb1_sharing_violation(struct smb_request *req)
2863 if (!lp_defer_sharing_violations()) {
2868 * Try every 200msec up to (by default) one second. To be
2869 * precise, according to behaviour note <247> in [MS-CIFS],
2870 * the server tries 5 times. But up to one second should be
2874 timeout_usecs = lp_parm_int(
2878 SHARING_VIOLATION_USEC_WAIT);
2880 ok = setup_poll_open(
2883 (struct file_id) {0},
2884 (struct timeval) { .tv_usec = timeout_usecs },
2885 (struct timeval) { .tv_usec = 200000 });
2889 /****************************************************************************
2890 On overwrite open ensure that the attributes match.
2891 ****************************************************************************/
2893 static bool open_match_attributes(connection_struct *conn,
2894 uint32_t old_dos_attr,
2895 uint32_t new_dos_attr,
2896 mode_t new_unx_mode,
2897 mode_t *returned_unx_mode)
2899 uint32_t noarch_old_dos_attr, noarch_new_dos_attr;
2901 noarch_old_dos_attr = (old_dos_attr & ~FILE_ATTRIBUTE_ARCHIVE);
2902 noarch_new_dos_attr = (new_dos_attr & ~FILE_ATTRIBUTE_ARCHIVE);
2904 if((noarch_old_dos_attr == 0 && noarch_new_dos_attr != 0) ||
2905 (noarch_old_dos_attr != 0 && ((noarch_old_dos_attr & noarch_new_dos_attr) == noarch_old_dos_attr))) {
2906 *returned_unx_mode = new_unx_mode;
2908 *returned_unx_mode = (mode_t)0;
2911 DEBUG(10,("open_match_attributes: old_dos_attr = 0x%x, "
2912 "new_dos_attr = 0x%x "
2913 "returned_unx_mode = 0%o\n",
2914 (unsigned int)old_dos_attr,
2915 (unsigned int)new_dos_attr,
2916 (unsigned int)*returned_unx_mode ));
2918 /* If we're mapping SYSTEM and HIDDEN ensure they match. */
2919 if (lp_map_system(SNUM(conn)) || lp_store_dos_attributes(SNUM(conn))) {
2920 if ((old_dos_attr & FILE_ATTRIBUTE_SYSTEM) &&
2921 !(new_dos_attr & FILE_ATTRIBUTE_SYSTEM)) {
2925 if (lp_map_hidden(SNUM(conn)) || lp_store_dos_attributes(SNUM(conn))) {
2926 if ((old_dos_attr & FILE_ATTRIBUTE_HIDDEN) &&
2927 !(new_dos_attr & FILE_ATTRIBUTE_HIDDEN)) {
2934 static void schedule_defer_open(struct share_mode_lock *lck,
2936 struct smb_request *req)
2938 /* This is a relative time, added to the absolute
2939 request_time value to get the absolute timeout time.
2940 Note that if this is the second or greater time we enter
2941 this codepath for this particular request mid then
2942 request_time is left as the absolute time of the *first*
2943 time this request mid was processed. This is what allows
2944 the request to eventually time out. */
2946 struct timeval timeout;
2948 /* Normally the smbd we asked should respond within
2949 * OPLOCK_BREAK_TIMEOUT seconds regardless of whether
2950 * the client did, give twice the timeout as a safety
2951 * measure here in case the other smbd is stuck
2952 * somewhere else. */
2954 timeout = timeval_set(OPLOCK_BREAK_TIMEOUT*2, 0);
2956 if (request_timed_out(req, timeout)) {
2960 defer_open(lck, timeout, req, id);
2963 /****************************************************************************
2964 Reschedule an open call that went asynchronous.
2965 ****************************************************************************/
2967 static void schedule_async_open_timer(struct tevent_context *ev,
2968 struct tevent_timer *te,
2969 struct timeval current_time,
2972 exit_server("async open timeout");
2975 static void schedule_async_open(struct smb_request *req)
2977 struct deferred_open_record *open_rec = NULL;
2978 struct timeval timeout = timeval_set(20, 0);
2981 if (request_timed_out(req, timeout)) {
2985 open_rec = talloc_zero(NULL, struct deferred_open_record);
2986 if (open_rec == NULL) {
2987 exit_server("deferred_open_record_create failed");
2989 open_rec->async_open = true;
2991 ok = push_deferred_open_message_smb(
2992 req, timeout, (struct file_id){0}, open_rec);
2994 exit_server("push_deferred_open_message_smb failed");
2997 open_rec->te = tevent_add_timer(req->sconn->ev_ctx,
2999 timeval_current_ofs(20, 0),
3000 schedule_async_open_timer,
3002 if (open_rec->te == NULL) {
3003 exit_server("tevent_add_timer failed");
3007 /****************************************************************************
3008 Work out what access_mask to use from what the client sent us.
3009 ****************************************************************************/
3011 static NTSTATUS smbd_calculate_maximum_allowed_access(
3012 connection_struct *conn,
3013 const struct smb_filename *smb_fname,
3015 uint32_t *p_access_mask)
3017 struct security_descriptor *sd;
3018 uint32_t access_granted;
3021 if (!use_privs && (get_current_uid(conn) == (uid_t)0)) {
3022 *p_access_mask |= FILE_GENERIC_ALL;
3023 return NT_STATUS_OK;
3026 status = SMB_VFS_GET_NT_ACL(conn, smb_fname,
3032 if (NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
3034 * File did not exist
3036 *p_access_mask = FILE_GENERIC_ALL;
3037 return NT_STATUS_OK;
3039 if (!NT_STATUS_IS_OK(status)) {
3040 DEBUG(10,("Could not get acl on file %s: %s\n",
3041 smb_fname_str_dbg(smb_fname),
3042 nt_errstr(status)));
3043 return NT_STATUS_ACCESS_DENIED;
3047 * If we can access the path to this file, by
3048 * default we have FILE_READ_ATTRIBUTES from the
3049 * containing directory. See the section:
3050 * "Algorithm to Check Access to an Existing File"
3053 * se_file_access_check()
3054 * also takes care of owner WRITE_DAC and READ_CONTROL.
3056 status = se_file_access_check(sd,
3057 get_current_nttok(conn),
3059 (*p_access_mask & ~FILE_READ_ATTRIBUTES),
3064 if (!NT_STATUS_IS_OK(status)) {
3065 DEBUG(10, ("Access denied on file %s: "
3066 "when calculating maximum access\n",
3067 smb_fname_str_dbg(smb_fname)));
3068 return NT_STATUS_ACCESS_DENIED;
3070 *p_access_mask = (access_granted | FILE_READ_ATTRIBUTES);
3072 if (!(access_granted & DELETE_ACCESS)) {
3073 if (can_delete_file_in_directory(conn, smb_fname)) {
3074 *p_access_mask |= DELETE_ACCESS;
3078 return NT_STATUS_OK;
3081 NTSTATUS smbd_calculate_access_mask(connection_struct *conn,
3082 const struct smb_filename *smb_fname,
3084 uint32_t access_mask,
3085 uint32_t *access_mask_out)
3088 uint32_t orig_access_mask = access_mask;
3089 uint32_t rejected_share_access;
3091 if (access_mask & SEC_MASK_INVALID) {
3092 DBG_DEBUG("access_mask [%8x] contains invalid bits\n",
3094 return NT_STATUS_ACCESS_DENIED;
3098 * Convert GENERIC bits to specific bits.
3101 se_map_generic(&access_mask, &file_generic_mapping);
3103 /* Calculate MAXIMUM_ALLOWED_ACCESS if requested. */
3104 if (access_mask & MAXIMUM_ALLOWED_ACCESS) {
3106 status = smbd_calculate_maximum_allowed_access(
3107 conn, smb_fname, use_privs, &access_mask);
3109 if (!NT_STATUS_IS_OK(status)) {
3113 access_mask &= conn->share_access;
3116 rejected_share_access = access_mask & ~(conn->share_access);
3118 if (rejected_share_access) {
3119 DEBUG(10, ("smbd_calculate_access_mask: Access denied on "
3120 "file %s: rejected by share access mask[0x%08X] "
3121 "orig[0x%08X] mapped[0x%08X] reject[0x%08X]\n",
3122 smb_fname_str_dbg(smb_fname),
3124 orig_access_mask, access_mask,
3125 rejected_share_access));
3126 return NT_STATUS_ACCESS_DENIED;
3129 *access_mask_out = access_mask;
3130 return NT_STATUS_OK;
3133 /****************************************************************************
3134 Remove the deferred open entry under lock.
3135 ****************************************************************************/
3137 /****************************************************************************
3138 Return true if this is a state pointer to an asynchronous create.
3139 ****************************************************************************/
3141 bool is_deferred_open_async(const struct deferred_open_record *rec)
3143 return rec->async_open;
3146 static bool clear_ads(uint32_t create_disposition)
3150 switch (create_disposition) {
3151 case FILE_SUPERSEDE:
3152 case FILE_OVERWRITE_IF:
3153 case FILE_OVERWRITE:
3162 static int disposition_to_open_flags(uint32_t create_disposition)
3167 * Currently we're using FILE_SUPERSEDE as the same as
3168 * FILE_OVERWRITE_IF but they really are
3169 * different. FILE_SUPERSEDE deletes an existing file
3170 * (requiring delete access) then recreates it.
3173 switch (create_disposition) {
3174 case FILE_SUPERSEDE:
3175 case FILE_OVERWRITE_IF:
3177 * If file exists replace/overwrite. If file doesn't
3180 ret = O_CREAT|O_TRUNC;
3185 * If file exists open. If file doesn't exist error.
3190 case FILE_OVERWRITE:
3192 * If file exists overwrite. If file doesn't exist
3200 * If file exists error. If file doesn't exist create.
3202 ret = O_CREAT|O_EXCL;
3207 * If file exists open. If file doesn't exist create.
3215 static int calculate_open_access_flags(uint32_t access_mask,
3216 uint32_t private_flags)
3218 bool need_write, need_read;
3221 * Note that we ignore the append flag as append does not
3222 * mean the same thing under DOS and Unix.
3225 need_write = (access_mask & (FILE_WRITE_DATA | FILE_APPEND_DATA));
3230 /* DENY_DOS opens are always underlying read-write on the
3231 file handle, no matter what the requested access mask
3235 ((private_flags & NTCREATEX_OPTIONS_PRIVATE_DENY_DOS) ||
3236 access_mask & (FILE_READ_ATTRIBUTES|FILE_READ_DATA|
3237 FILE_READ_EA|FILE_EXECUTE));
3245 /****************************************************************************
3246 Open a file with a share mode. Passed in an already created files_struct *.
3247 ****************************************************************************/
3249 static NTSTATUS open_file_ntcreate(connection_struct *conn,
3250 struct smb_request *req,
3251 uint32_t access_mask, /* access bits (FILE_READ_DATA etc.) */
3252 uint32_t share_access, /* share constants (FILE_SHARE_READ etc) */
3253 uint32_t create_disposition, /* FILE_OPEN_IF etc. */
3254 uint32_t create_options, /* options such as delete on close. */
3255 uint32_t new_dos_attributes, /* attributes used for new file. */
3256 int oplock_request, /* internal Samba oplock codes. */
3257 const struct smb2_lease *lease,
3258 /* Information (FILE_EXISTS etc.) */
3259 uint32_t private_flags, /* Samba specific flags. */
3263 struct smb_filename *smb_fname = fsp->fsp_name;
3266 bool file_existed = VALID_STAT(smb_fname->st);
3267 bool def_acl = False;
3268 bool posix_open = False;
3269 bool new_file_created = False;
3270 bool first_open_attempt = true;
3271 NTSTATUS fsp_open = NT_STATUS_ACCESS_DENIED;
3272 mode_t new_unx_mode = (mode_t)0;
3273 mode_t unx_mode = (mode_t)0;
3275 uint32_t existing_dos_attributes = 0;
3276 struct share_mode_lock *lck = NULL;
3277 uint32_t open_access_mask = access_mask;
3280 SMB_STRUCT_STAT saved_stat = smb_fname->st;
3281 struct timespec old_write_time;
3283 bool setup_poll = false;
3286 if (conn->printer) {
3288 * Printers are handled completely differently.
3289 * Most of the passed parameters are ignored.
3293 *pinfo = FILE_WAS_CREATED;
3296 DEBUG(10, ("open_file_ntcreate: printer open fname=%s\n",
3297 smb_fname_str_dbg(smb_fname)));
3300 DEBUG(0,("open_file_ntcreate: printer open without "
3301 "an SMB request!\n"));
3302 return NT_STATUS_INTERNAL_ERROR;
3305 return print_spool_open(fsp, smb_fname->base_name,
3309 if (!parent_dirname(talloc_tos(), smb_fname->base_name, &parent_dir,
3311 return NT_STATUS_NO_MEMORY;
3314 if (new_dos_attributes & FILE_FLAG_POSIX_SEMANTICS) {
3316 unx_mode = (mode_t)(new_dos_attributes & ~FILE_FLAG_POSIX_SEMANTICS);
3317 new_dos_attributes = 0;
3319 /* Windows allows a new file to be created and
3320 silently removes a FILE_ATTRIBUTE_DIRECTORY
3321 sent by the client. Do the same. */
3323 new_dos_attributes &= ~FILE_ATTRIBUTE_DIRECTORY;
3325 /* We add FILE_ATTRIBUTE_ARCHIVE to this as this mode is only used if the file is
3327 unx_mode = unix_mode(conn, new_dos_attributes | FILE_ATTRIBUTE_ARCHIVE,
3328 smb_fname, parent_dir);
3331 DEBUG(10, ("open_file_ntcreate: fname=%s, dos_attrs=0x%x "
3332 "access_mask=0x%x share_access=0x%x "
3333 "create_disposition = 0x%x create_options=0x%x "
3334 "unix mode=0%o oplock_request=%d private_flags = 0x%x\n",
3335 smb_fname_str_dbg(smb_fname), new_dos_attributes,
3336 access_mask, share_access, create_disposition,
3337 create_options, (unsigned int)unx_mode, oplock_request,
3338 (unsigned int)private_flags));
3341 /* Ensure req == NULL means INTERNAL_OPEN_ONLY */
3342 SMB_ASSERT(oplock_request == INTERNAL_OPEN_ONLY);
3344 /* And req != NULL means no INTERNAL_OPEN_ONLY */
3345 SMB_ASSERT(((oplock_request & INTERNAL_OPEN_ONLY) == 0));
3349 * Only non-internal opens can be deferred at all
3353 struct deferred_open_record *open_rec;
3354 if (get_deferred_open_message_state(req, NULL, &open_rec)) {
3356 /* If it was an async create retry, the file
3359 if (is_deferred_open_async(open_rec)) {
3360 SET_STAT_INVALID(smb_fname->st);
3361 file_existed = false;
3364 /* Ensure we don't reprocess this message. */
3365 remove_deferred_open_message_smb(req->xconn, req->mid);
3367 first_open_attempt = false;
3372 new_dos_attributes &= SAMBA_ATTRIBUTES_MASK;
3375 * Only use stored DOS attributes for checks
3376 * against requested attributes (below via
3377 * open_match_attributes()), cf bug #11992
3378 * for details. -slow
3382 status = SMB_VFS_GET_DOS_ATTRIBUTES(conn, smb_fname, &attr);
3383 if (NT_STATUS_IS_OK(status)) {
3384 existing_dos_attributes = attr;
3389 /* ignore any oplock requests if oplocks are disabled */
3390 if (!lp_oplocks(SNUM(conn)) ||
3391 IS_VETO_OPLOCK_PATH(conn, smb_fname->base_name)) {
3392 /* Mask off everything except the private Samba bits. */
3393 oplock_request &= SAMBA_PRIVATE_OPLOCK_MASK;
3396 /* this is for OS/2 long file names - say we don't support them */
3397 if (req != NULL && !req->posix_pathnames &&
3398 strstr(smb_fname->base_name,".+,;=[].")) {
3399 /* OS/2 Workplace shell fix may be main code stream in a later
3401 DEBUG(5,("open_file_ntcreate: OS/2 long filenames are not "
3403 if (use_nt_status()) {
3404 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3406 return NT_STATUS_DOS(ERRDOS, ERRcannotopen);
3409 switch( create_disposition ) {
3411 /* If file exists open. If file doesn't exist error. */
3412 if (!file_existed) {
3413 DEBUG(5,("open_file_ntcreate: FILE_OPEN "
3414 "requested for file %s and file "
3416 smb_fname_str_dbg(smb_fname)));
3418 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3422 case FILE_OVERWRITE:
3423 /* If file exists overwrite. If file doesn't exist
3425 if (!file_existed) {
3426 DEBUG(5,("open_file_ntcreate: FILE_OVERWRITE "
3427 "requested for file %s and file "
3429 smb_fname_str_dbg(smb_fname) ));
3431 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3436 /* If file exists error. If file doesn't exist
3439 DEBUG(5,("open_file_ntcreate: FILE_CREATE "
3440 "requested for file %s and file "
3441 "already exists.\n",
3442 smb_fname_str_dbg(smb_fname)));
3443 if (S_ISDIR(smb_fname->st.st_ex_mode)) {
3448 return map_nt_error_from_unix(errno);
3452 case FILE_SUPERSEDE:
3453 case FILE_OVERWRITE_IF:
3457 return NT_STATUS_INVALID_PARAMETER;
3460 flags2 = disposition_to_open_flags(create_disposition);
3462 /* We only care about matching attributes on file exists and
3465 if (!posix_open && file_existed &&
3466 ((create_disposition == FILE_OVERWRITE) ||
3467 (create_disposition == FILE_OVERWRITE_IF))) {
3468 if (!open_match_attributes(conn, existing_dos_attributes,
3470 unx_mode, &new_unx_mode)) {
3471 DEBUG(5,("open_file_ntcreate: attributes mismatch "
3472 "for file %s (%x %x) (0%o, 0%o)\n",
3473 smb_fname_str_dbg(smb_fname),
3474 existing_dos_attributes,
3476 (unsigned int)smb_fname->st.st_ex_mode,
3477 (unsigned int)unx_mode ));
3479 return NT_STATUS_ACCESS_DENIED;
3483 status = smbd_calculate_access_mask(conn, smb_fname,
3487 if (!NT_STATUS_IS_OK(status)) {
3488 DEBUG(10, ("open_file_ntcreate: smbd_calculate_access_mask "
3489 "on file %s returned %s\n",
3490 smb_fname_str_dbg(smb_fname), nt_errstr(status)));
3494 open_access_mask = access_mask;
3496 if (flags2 & O_TRUNC) {
3497 open_access_mask |= FILE_WRITE_DATA; /* This will cause oplock breaks. */
3502 * stat opens on existing files don't get oplocks.
3503 * They can get leases.
3505 * Note that we check for stat open on the *open_access_mask*,
3506 * i.e. the access mask we actually used to do the open,
3507 * not the one the client asked for (which is in
3508 * fsp->access_mask). This is due to the fact that
3509 * FILE_OVERWRITE and FILE_OVERWRITE_IF add in O_TRUNC,
3510 * which adds FILE_WRITE_DATA to open_access_mask.
3512 if (is_stat_open(open_access_mask) && lease == NULL) {
3513 oplock_request = NO_OPLOCK;
3517 DEBUG(10, ("open_file_ntcreate: fname=%s, after mapping "
3518 "access_mask=0x%x\n", smb_fname_str_dbg(smb_fname),
3522 * Note that we ignore the append flag as append does not
3523 * mean the same thing under DOS and Unix.
3526 flags = calculate_open_access_flags(access_mask, private_flags);
3529 * Currently we only look at FILE_WRITE_THROUGH for create options.
3533 if ((create_options & FILE_WRITE_THROUGH) && lp_strict_sync(SNUM(conn))) {
3538 if (posix_open && (access_mask & FILE_APPEND_DATA)) {
3542 if (!posix_open && !CAN_WRITE(conn)) {
3544 * We should really return a permission denied error if either
3545 * O_CREAT or O_TRUNC are set, but for compatibility with
3546 * older versions of Samba we just AND them out.
3548 flags2 &= ~(O_CREAT|O_TRUNC);
3552 * With kernel oplocks the open breaking an oplock
3553 * blocks until the oplock holder has given up the
3554 * oplock or closed the file. We prevent this by always
3555 * trying to open the file with O_NONBLOCK (see "man
3558 * If a process that doesn't use the smbd open files
3559 * database or communication methods holds a kernel
3560 * oplock we must periodically poll for available open
3563 flags2 |= O_NONBLOCK;
3566 * Ensure we can't write on a read-only share or file.
3569 if (flags != O_RDONLY && file_existed &&
3570 (!CAN_WRITE(conn) || IS_DOS_READONLY(existing_dos_attributes))) {
3571 DEBUG(5,("open_file_ntcreate: write access requested for "
3572 "file %s on read only %s\n",
3573 smb_fname_str_dbg(smb_fname),
3574 !CAN_WRITE(conn) ? "share" : "file" ));
3576 return NT_STATUS_ACCESS_DENIED;
3579 if (VALID_STAT(smb_fname->st)) {
3581 * Only try and create a file id before open
3582 * for an existing file. For a file being created
3583 * this won't do anything useful until the file
3584 * exists and has a valid stat struct.
3586 fsp->file_id = vfs_file_id_from_sbuf(conn, &smb_fname->st);
3588 fsp->fh->private_options = private_flags;
3589 fsp->access_mask = open_access_mask; /* We change this to the
3590 * requested access_mask after
3591 * the open is done. */
3593 fsp->posix_flags |= FSP_POSIX_FLAGS_ALL;
3596 if ((create_options & FILE_DELETE_ON_CLOSE) &&
3597 (flags2 & O_CREAT) &&
3599 /* Delete on close semantics for new files. */
3600 status = can_set_delete_on_close(fsp,
3601 new_dos_attributes);
3602 if (!NT_STATUS_IS_OK(status)) {
3609 * Ensure we pay attention to default ACLs on directories if required.
3612 if ((flags2 & O_CREAT) && lp_inherit_acls(SNUM(conn)) &&
3613 (def_acl = directory_has_default_acl(conn, parent_dir))) {
3614 unx_mode = (0777 & lp_create_mask(SNUM(conn)));
3617 DEBUG(4,("calling open_file with flags=0x%X flags2=0x%X mode=0%o, "
3618 "access_mask = 0x%x, open_access_mask = 0x%x\n",
3619 (unsigned int)flags, (unsigned int)flags2,
3620 (unsigned int)unx_mode, (unsigned int)access_mask,
3621 (unsigned int)open_access_mask));
3623 fsp_open = open_file(fsp, conn, req, parent_dir,
3624 flags|flags2, unx_mode, access_mask,
3625 open_access_mask, &new_file_created);
3627 if (NT_STATUS_EQUAL(fsp_open, NT_STATUS_NETWORK_BUSY)) {
3628 if (file_existed && S_ISFIFO(fsp->fsp_name->st.st_ex_mode)) {
3629 DEBUG(10, ("FIFO busy\n"));
3630 return NT_STATUS_NETWORK_BUSY;
3633 DEBUG(10, ("Internal open busy\n"));
3634 return NT_STATUS_NETWORK_BUSY;
3637 * This handles the kernel oplock case:
3639 * the file has an active kernel oplock and the open() returned
3640 * EWOULDBLOCK/EAGAIN which maps to NETWORK_BUSY.
3642 * "Samba locking.tdb oplocks" are handled below after acquiring
3643 * the sharemode lock with get_share_mode_lock().
3648 if (NT_STATUS_EQUAL(fsp_open, NT_STATUS_RETRY)) {
3650 * EINTR from the open(2) syscall. Just setup a retry
3651 * in a bit. We can't use the sys_write() tight retry
3652 * loop here, as we might have to actually deal with
3653 * lease-break signals to avoid a deadlock.
3660 * From here on we assume this is an oplock break triggered
3663 lck = get_existing_share_mode_lock(talloc_tos(), fsp->file_id);
3665 if ((lck != NULL) && !validate_oplock_types(lck)) {
3666 smb_panic("validate_oplock_types failed");
3670 * Retry once a second. If there's a share_mode_lock
3671 * around, also wait for it in case it was smbd
3672 * holding that kernel oplock that can quickly tell us
3673 * the oplock got removed.
3680 timeval_set(OPLOCK_BREAK_TIMEOUT*2, 0),
3685 return NT_STATUS_SHARING_VIOLATION;
3688 if (!NT_STATUS_IS_OK(fsp_open)) {
3689 bool wait_for_aio = NT_STATUS_EQUAL(
3690 fsp_open, NT_STATUS_MORE_PROCESSING_REQUIRED);
3692 schedule_async_open(req);
3697 if (new_file_created) {
3699 * As we atomically create using O_CREAT|O_EXCL,
3700 * then if new_file_created is true, then
3701 * file_existed *MUST* have been false (even
3702 * if the file was previously detected as being
3705 file_existed = false;
3708 if (file_existed && !check_same_dev_ino(&saved_stat, &smb_fname->st)) {
3710 * The file did exist, but some other (local or NFS)
3711 * process either renamed/unlinked and re-created the
3712 * file with different dev/ino after we walked the path,
3713 * but before we did the open. We could retry the
3714 * open but it's a rare enough case it's easier to
3715 * just fail the open to prevent creating any problems
3716 * in the open file db having the wrong dev/ino key.
3719 DBG_WARNING("file %s - dev/ino mismatch. "
3720 "Old (dev=%ju, ino=%ju). "
3721 "New (dev=%ju, ino=%ju). Failing open "
3722 "with NT_STATUS_ACCESS_DENIED.\n",
3723 smb_fname_str_dbg(smb_fname),
3724 (uintmax_t)saved_stat.st_ex_dev,
3725 (uintmax_t)saved_stat.st_ex_ino,
3726 (uintmax_t)smb_fname->st.st_ex_dev,
3727 (uintmax_t)smb_fname->st.st_ex_ino);
3728 return NT_STATUS_ACCESS_DENIED;
3731 old_write_time = smb_fname->st.st_ex_mtime;
3734 * Deal with the race condition where two smbd's detect the
3735 * file doesn't exist and do the create at the same time. One
3736 * of them will win and set a share mode, the other (ie. this
3737 * one) should check if the requested share mode for this
3738 * create is allowed.
3742 * Now the file exists and fsp is successfully opened,
3743 * fsp->dev and fsp->inode are valid and should replace the
3744 * dev=0,inode=0 from a non existent file. Spotted by
3745 * Nadav Danieli <nadavd@exanet.com>. JRA.
3750 lck = get_share_mode_lock(talloc_tos(), id,
3752 smb_fname, &old_write_time);
3755 DEBUG(0, ("open_file_ntcreate: Could not get share "
3756 "mode lock for %s\n",
3757 smb_fname_str_dbg(smb_fname)));
3759 return NT_STATUS_SHARING_VIOLATION;
3762 /* Get the types we need to examine. */
3763 if (!validate_oplock_types(lck)) {
3764 smb_panic("validate_oplock_types failed");
3767 if (has_delete_on_close(lck, fsp->name_hash)) {
3770 return NT_STATUS_DELETE_PENDING;
3773 status = handle_share_mode_lease(
3781 first_open_attempt);
3783 if (NT_STATUS_EQUAL(status, NT_STATUS_RETRY)) {
3784 schedule_defer_open(lck, fsp->file_id, req);
3787 return NT_STATUS_SHARING_VIOLATION;
3790 if (!NT_STATUS_IS_OK(status)) {
3797 struct share_mode_data *d = lck->data;
3798 uint16_t new_flags = share_mode_flags_restrict(
3799 d->flags, access_mask, share_access, UINT32_MAX);
3801 if (new_flags != d->flags) {
3802 d->flags = new_flags;
3807 ok = set_share_mode(
3810 get_current_uid(fsp->conn),
3816 if (fsp->oplock_type == LEASE_OPLOCK) {
3817 status = remove_lease_if_stale(
3819 fsp_client_guid(fsp),
3820 &fsp->lease->lease.lease_key);
3821 if (!NT_STATUS_IS_OK(status)) {
3822 DBG_WARNING("remove_lease_if_stale "
3827 return NT_STATUS_NO_MEMORY;
3830 /* Should we atomically (to the client at least) truncate ? */
3831 if ((!new_file_created) &&
3832 (flags2 & O_TRUNC) &&
3833 (S_ISREG(fsp->fsp_name->st.st_ex_mode))) {
3836 ret = SMB_VFS_FTRUNCATE(fsp, 0);
3838 status = map_nt_error_from_unix(errno);
3839 del_share_mode(lck, fsp);
3844 notify_fname(fsp->conn, NOTIFY_ACTION_MODIFIED,
3845 FILE_NOTIFY_CHANGE_SIZE
3846 | FILE_NOTIFY_CHANGE_ATTRIBUTES,
3847 fsp->fsp_name->base_name);
3851 * We have the share entry *locked*.....
3854 /* Delete streams if create_disposition requires it */
3855 if (!new_file_created && clear_ads(create_disposition) &&
3856 !is_ntfs_stream_smb_fname(smb_fname)) {
3857 status = delete_all_streams(conn, smb_fname);
3858 if (!NT_STATUS_IS_OK(status)) {
3859 del_share_mode(lck, fsp);
3866 if (fsp->fh->fd != -1 && lp_kernel_share_modes(SNUM(conn))) {
3869 * Beware: streams implementing VFS modules may
3870 * implement streams in a way that fsp will have the
3871 * basefile open in the fsp fd, so lacking a distinct
3872 * fd for the stream kernel_flock will apply on the
3873 * basefile which is wrong. The actual check is
3874 * deferred to the VFS module implementing the
3875 * kernel_flock call.
3877 ret_flock = SMB_VFS_KERNEL_FLOCK(fsp, share_access, access_mask);
3878 if(ret_flock == -1 ){
3880 del_share_mode(lck, fsp);
3884 return NT_STATUS_SHARING_VIOLATION;
3887 fsp->fsp_flags.kernel_share_modes_taken = true;
3891 * At this point onwards, we can guarantee that the share entry
3892 * is locked, whether we created the file or not, and that the
3893 * deny mode is compatible with all current opens.
3897 * According to Samba4, SEC_FILE_READ_ATTRIBUTE is always granted,
3898 * but we don't have to store this - just ignore it on access check.
3900 if (conn->sconn->using_smb2) {
3902 * SMB2 doesn't return it (according to Microsoft tests).
3903 * Test Case: TestSuite_ScenarioNo009GrantedAccessTestS0
3904 * File created with access = 0x7 (Read, Write, Delete)
3905 * Query Info on file returns 0x87 (Read, Write, Delete, Read Attributes)
3907 fsp->access_mask = access_mask;
3909 /* But SMB1 does. */
3910 fsp->access_mask = access_mask | FILE_READ_ATTRIBUTES;
3913 if (new_file_created) {
3914 info = FILE_WAS_CREATED;
3916 if (flags2 & O_TRUNC) {
3917 info = FILE_WAS_OVERWRITTEN;
3919 info = FILE_WAS_OPENED;
3927 /* Handle strange delete on close create semantics. */
3928 if (create_options & FILE_DELETE_ON_CLOSE) {
3929 if (!new_file_created) {
3930 status = can_set_delete_on_close(fsp,
3931 existing_dos_attributes);
3933 if (!NT_STATUS_IS_OK(status)) {
3934 /* Remember to delete the mode we just added. */
3935 del_share_mode(lck, fsp);
3941 /* Note that here we set the *initial* delete on close flag,
3942 not the regular one. The magic gets handled in close. */
3943 fsp->fsp_flags.initial_delete_on_close = true;
3947 * If we created a file and it's not a stream, this is the point where
3948 * we set the itime (aka invented time) that get's stored in the DOS
3949 * attribute xattr. The value is going to be either what the filesystem
3950 * provided or a copy of the creation date.
3952 * Either way, we turn the itime into a File-ID, unless the filesystem
3953 * provided one (unlikely).
3955 if (info == FILE_WAS_CREATED && !is_named_stream(smb_fname)) {
3956 smb_fname->st.st_ex_iflags &= ~ST_EX_IFLAG_CALCULATED_ITIME;
3958 if (lp_store_dos_attributes(SNUM(conn)) &&
3959 smb_fname->st.st_ex_iflags & ST_EX_IFLAG_CALCULATED_FILE_ID)
3963 file_id = make_file_id_from_itime(&smb_fname->st);
3964 update_stat_ex_file_id(&smb_fname->st, file_id);
3968 if (info != FILE_WAS_OPENED) {
3969 /* Overwritten files should be initially set as archive */
3970 if ((info == FILE_WAS_OVERWRITTEN && lp_map_archive(SNUM(conn))) ||
3971 lp_store_dos_attributes(SNUM(conn))) {
3972 (void)dos_mode(conn, smb_fname);
3974 if (file_set_dosmode(conn, smb_fname,
3975 new_dos_attributes | FILE_ATTRIBUTE_ARCHIVE,
3976 parent_dir, true) == 0) {
3977 unx_mode = smb_fname->st.st_ex_mode;
3983 /* Determine sparse flag. */
3985 /* POSIX opens are sparse by default. */
3986 fsp->fsp_flags.is_sparse = true;
3988 fsp->fsp_flags.is_sparse =
3989 (existing_dos_attributes & FILE_ATTRIBUTE_SPARSE);
3993 * Take care of inherited ACLs on created files - if default ACL not
3997 if (!posix_open && new_file_created && !def_acl) {
3998 if (unx_mode != smb_fname->st.st_ex_mode) {
3999 int ret = SMB_VFS_FCHMOD(fsp, unx_mode);
4001 DBG_INFO("failed to reset "
4002 "attributes of file %s to 0%o\n",
4003 smb_fname_str_dbg(smb_fname),
4004 (unsigned int)unx_mode);
4008 } else if (new_unx_mode) {
4010 * We only get here in the case of:
4012 * a). Not a POSIX open.
4013 * b). File already existed.
4014 * c). File was overwritten.
4015 * d). Requested DOS attributes didn't match
4016 * the DOS attributes on the existing file.
4018 * In that case new_unx_mode has been set
4019 * equal to the calculated mode (including
4020 * possible inheritance of the mode from the
4021 * containing directory).
4023 * Note this mode was calculated with the
4024 * DOS attribute FILE_ATTRIBUTE_ARCHIVE added,
4025 * so the mode change here is suitable for
4026 * an overwritten file.
4029 if (new_unx_mode != smb_fname->st.st_ex_mode) {
4030 int ret = SMB_VFS_FCHMOD(fsp, new_unx_mode);
4032 DBG_INFO("failed to reset "
4033 "attributes of file %s to 0%o\n",
4034 smb_fname_str_dbg(smb_fname),
4035 (unsigned int)new_unx_mode);
4042 * Deal with other opens having a modified write time.
4044 struct timespec write_time = get_share_mode_write_time(lck);
4046 if (!is_omit_timespec(&write_time)) {
4047 update_stat_ex_mtime(&fsp->fsp_name->st, write_time);
4053 return NT_STATUS_OK;
4056 static NTSTATUS mkdir_internal(connection_struct *conn,
4057 struct smb_filename *smb_dname,
4058 uint32_t file_attributes)
4060 const struct loadparm_substitution *lp_sub =
4061 loadparm_s3_global_substitution();
4063 char *parent_dir = NULL;
4065 bool posix_open = false;
4066 bool need_re_stat = false;
4067 uint32_t access_mask = SEC_DIR_ADD_SUBDIR;
4070 if (!CAN_WRITE(conn) || (access_mask & ~(conn->share_access))) {
4071 DEBUG(5,("mkdir_internal: failing share access "
4072 "%s\n", lp_servicename(talloc_tos(), lp_sub, SNUM(conn))));
4073 return NT_STATUS_ACCESS_DENIED;
4076 if (!parent_dirname(talloc_tos(), smb_dname->base_name, &parent_dir,
4078 return NT_STATUS_NO_MEMORY;
4081 if (file_attributes & FILE_FLAG_POSIX_SEMANTICS) {
4083 mode = (mode_t)(file_attributes & ~FILE_FLAG_POSIX_SEMANTICS);
4085 mode = unix_mode(conn, FILE_ATTRIBUTE_DIRECTORY, smb_dname, parent_dir);
4088 status = check_parent_access(conn,
4091 if(!NT_STATUS_IS_OK(status)) {
4092 DEBUG(5,("mkdir_internal: check_parent_access "
4093 "on directory %s for path %s returned %s\n",
4095 smb_dname->base_name,
4096 nt_errstr(status) ));
4100 ret = SMB_VFS_MKDIRAT(conn,
4105 return map_nt_error_from_unix(errno);
4108 /* Ensure we're checking for a symlink here.... */
4109 /* We don't want to get caught by a symlink racer. */
4111 if (SMB_VFS_LSTAT(conn, smb_dname) == -1) {
4112 DEBUG(2, ("Could not stat directory '%s' just created: %s\n",
4113 smb_fname_str_dbg(smb_dname), strerror(errno)));
4114 return map_nt_error_from_unix(errno);
4117 if (!S_ISDIR(smb_dname->st.st_ex_mode)) {
4118 DEBUG(0, ("Directory '%s' just created is not a directory !\n",
4119 smb_fname_str_dbg(smb_dname)));
4120 return NT_STATUS_NOT_A_DIRECTORY;
4123 smb_dname->st.st_ex_iflags &= ~ST_EX_IFLAG_CALCULATED_ITIME;
4125 if (lp_store_dos_attributes(SNUM(conn))) {
4126 if (smb_dname->st.st_ex_iflags & ST_EX_IFLAG_CALCULATED_FILE_ID)
4130 file_id = make_file_id_from_itime(&smb_dname->st);
4131 update_stat_ex_file_id(&smb_dname->st, file_id);
4135 file_set_dosmode(conn, smb_dname,
4136 file_attributes | FILE_ATTRIBUTE_DIRECTORY,
4141 if (lp_inherit_permissions(SNUM(conn))) {
4142 inherit_access_posix_acl(conn, parent_dir,
4144 need_re_stat = true;
4149 * Check if high bits should have been set,
4150 * then (if bits are missing): add them.
4151 * Consider bits automagically set by UNIX, i.e. SGID bit from parent
4154 if ((mode & ~(S_IRWXU|S_IRWXG|S_IRWXO)) &&
4155 (mode & ~smb_dname->st.st_ex_mode)) {
4156 SMB_VFS_CHMOD(conn, smb_dname,
4157 (smb_dname->st.st_ex_mode |
4158 (mode & ~smb_dname->st.st_ex_mode)));
4159 need_re_stat = true;
4163 /* Change the owner if required. */
4164 if (lp_inherit_owner(SNUM(conn)) != INHERIT_OWNER_NO) {
4165 change_dir_owner_to_parent(conn, parent_dir,
4168 need_re_stat = true;
4172 if (SMB_VFS_LSTAT(conn, smb_dname) == -1) {
4173 DEBUG(2, ("Could not stat directory '%s' just created: %s\n",
4174 smb_fname_str_dbg(smb_dname), strerror(errno)));
4175 return map_nt_error_from_unix(errno);
4179 notify_fname(conn, NOTIFY_ACTION_ADDED, FILE_NOTIFY_CHANGE_DIR_NAME,
4180 smb_dname->base_name);
4182 return NT_STATUS_OK;
4185 /****************************************************************************
4186 Open a directory from an NT SMB call.
4187 ****************************************************************************/
4189 static NTSTATUS open_directory(connection_struct *conn,
4190 struct smb_request *req,
4191 struct smb_filename *smb_dname,
4192 uint32_t access_mask,
4193 uint32_t share_access,
4194 uint32_t create_disposition,
4195 uint32_t create_options,
4196 uint32_t file_attributes,
4198 files_struct **result)
4200 files_struct *fsp = NULL;
4201 bool dir_existed = VALID_STAT(smb_dname->st);
4202 struct share_mode_lock *lck = NULL;
4204 struct timespec mtimespec;
4208 if (is_ntfs_stream_smb_fname(smb_dname)) {
4209 DEBUG(2, ("open_directory: %s is a stream name!\n",
4210 smb_fname_str_dbg(smb_dname)));
4211 return NT_STATUS_NOT_A_DIRECTORY;
4214 if (!(file_attributes & FILE_FLAG_POSIX_SEMANTICS)) {
4215 /* Ensure we have a directory attribute. */
4216 file_attributes |= FILE_ATTRIBUTE_DIRECTORY;
4219 DBG_INFO("opening directory %s, access_mask = 0x%"PRIx32", "
4220 "share_access = 0x%"PRIx32" create_options = 0x%"PRIx32", "
4221 "create_disposition = 0x%"PRIx32", "
4222 "file_attributes = 0x%"PRIx32"\n",
4223 smb_fname_str_dbg(smb_dname),
4230 status = smbd_calculate_access_mask(conn, smb_dname, false,
4231 access_mask, &access_mask);
4232 if (!NT_STATUS_IS_OK(status)) {
4233 DEBUG(10, ("open_directory: smbd_calculate_access_mask "
4234 "on file %s returned %s\n",
4235 smb_fname_str_dbg(smb_dname),
4236 nt_errstr(status)));
4240 if ((access_mask & SEC_FLAG_SYSTEM_SECURITY) &&
4241 !security_token_has_privilege(get_current_nttok(conn),
4242 SEC_PRIV_SECURITY)) {
4243 DEBUG(10, ("open_directory: open on %s "
4244 "failed - SEC_FLAG_SYSTEM_SECURITY denied.\n",
4245 smb_fname_str_dbg(smb_dname)));
4246 return NT_STATUS_PRIVILEGE_NOT_HELD;
4249 switch( create_disposition ) {
4253 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
4256 info = FILE_WAS_OPENED;
4261 /* If directory exists error. If directory doesn't
4265 status = NT_STATUS_OBJECT_NAME_COLLISION;
4266 DEBUG(2, ("open_directory: unable to create "
4267 "%s. Error was %s\n",
4268 smb_fname_str_dbg(smb_dname),
4269 nt_errstr(status)));
4273 status = mkdir_internal(conn, smb_dname,
4276 if (!NT_STATUS_IS_OK(status)) {
4277 DEBUG(2, ("open_directory: unable to create "
4278 "%s. Error was %s\n",
4279 smb_fname_str_dbg(smb_dname),
4280 nt_errstr(status)));
4284 info = FILE_WAS_CREATED;
4289 * If directory exists open. If directory doesn't
4294 status = NT_STATUS_OK;
4295 info = FILE_WAS_OPENED;
4297 status = mkdir_internal(conn, smb_dname,
4300 if (NT_STATUS_IS_OK(status)) {
4301 info = FILE_WAS_CREATED;
4303 /* Cope with create race. */
4304 if (!NT_STATUS_EQUAL(status,
4305 NT_STATUS_OBJECT_NAME_COLLISION)) {
4306 DEBUG(2, ("open_directory: unable to create "
4307 "%s. Error was %s\n",
4308 smb_fname_str_dbg(smb_dname),
4309 nt_errstr(status)));
4314 * If mkdir_internal() returned
4315 * NT_STATUS_OBJECT_NAME_COLLISION
4316 * we still must lstat the path.
4319 if (SMB_VFS_LSTAT(conn, smb_dname)
4321 DEBUG(2, ("Could not stat "
4322 "directory '%s' just "
4327 return map_nt_error_from_unix(
4331 info = FILE_WAS_OPENED;
4337 case FILE_SUPERSEDE:
4338 case FILE_OVERWRITE:
4339 case FILE_OVERWRITE_IF:
4341 DEBUG(5,("open_directory: invalid create_disposition "
4342 "0x%x for directory %s\n",
4343 (unsigned int)create_disposition,
4344 smb_fname_str_dbg(smb_dname)));
4345 return NT_STATUS_INVALID_PARAMETER;
4348 if(!S_ISDIR(smb_dname->st.st_ex_mode)) {
4349 DEBUG(5,("open_directory: %s is not a directory !\n",
4350 smb_fname_str_dbg(smb_dname)));
4351 return NT_STATUS_NOT_A_DIRECTORY;
4354 if (info == FILE_WAS_OPENED) {
4355 status = smbd_check_access_rights(conn,
4359 if (!NT_STATUS_IS_OK(status)) {
4360 DEBUG(10, ("open_directory: smbd_check_access_rights on "
4361 "file %s failed with %s\n",
4362 smb_fname_str_dbg(smb_dname),
4363 nt_errstr(status)));
4368 status = file_new(req, conn, &fsp);
4369 if(!NT_STATUS_IS_OK(status)) {
4374 * Setup the files_struct for it.
4377 fsp->file_id = vfs_file_id_from_sbuf(conn, &smb_dname->st);
4378 fsp->vuid = req ? req->vuid : UID_FIELD_INVALID;
4379 fsp->file_pid = req ? req->smbpid : 0;
4380 fsp->fsp_flags.can_lock = false;
4381 fsp->fsp_flags.can_read = false;
4382 fsp->fsp_flags.can_write = false;
4384 fsp->fh->private_options = 0;
4386 * According to Samba4, SEC_FILE_READ_ATTRIBUTE is always granted,
4388 fsp->access_mask = access_mask | FILE_READ_ATTRIBUTES;
4389 fsp->print_file = NULL;
4390 fsp->fsp_flags.modified = false;
4391 fsp->oplock_type = NO_OPLOCK;
4392 fsp->sent_oplock_break = NO_BREAK_SENT;
4393 fsp->fsp_flags.is_directory = true;
4394 if (file_attributes & FILE_FLAG_POSIX_SEMANTICS) {
4395 fsp->posix_flags |= FSP_POSIX_FLAGS_ALL;
4397 status = fsp_set_smb_fname(fsp, smb_dname);
4398 if (!NT_STATUS_IS_OK(status)) {
4399 file_free(req, fsp);
4403 /* Don't store old timestamps for directory
4404 handles in the internal database. We don't
4405 update them in there if new objects
4406 are created in the directory. Currently
4407 we only update timestamps on file writes.
4410 mtimespec = make_omit_timespec();
4413 status = fd_open(conn, fsp, O_RDONLY|O_DIRECTORY, 0);
4415 /* POSIX allows us to open a directory with O_RDONLY. */
4416 status = fd_open(conn, fsp, O_RDONLY, 0);
4418 if (!NT_STATUS_IS_OK(status)) {
4419 DBG_INFO("Could not open fd for "
4421 smb_fname_str_dbg(smb_dname),
4423 file_free(req, fsp);
4427 status = vfs_stat_fsp(fsp);
4428 if (!NT_STATUS_IS_OK(status)) {
4430 file_free(req, fsp);
4434 if(!S_ISDIR(fsp->fsp_name->st.st_ex_mode)) {
4435 DEBUG(5,("open_directory: %s is not a directory !\n",
4436 smb_fname_str_dbg(smb_dname)));
4438 file_free(req, fsp);
4439 return NT_STATUS_NOT_A_DIRECTORY;
4442 /* Ensure there was no race condition. We need to check
4443 * dev/inode but not permissions, as these can change
4445 if (!check_same_dev_ino(&smb_dname->st, &fsp->fsp_name->st)) {
4446 DEBUG(5,("open_directory: stat struct differs for "
4448 smb_fname_str_dbg(smb_dname)));
4450 file_free(req, fsp);
4451 return NT_STATUS_ACCESS_DENIED;
4454 lck = get_share_mode_lock(talloc_tos(), fsp->file_id,
4455 conn->connectpath, smb_dname,
4459 DEBUG(0, ("open_directory: Could not get share mode lock for "
4460 "%s\n", smb_fname_str_dbg(smb_dname)));
4462 file_free(req, fsp);
4463 return NT_STATUS_SHARING_VIOLATION;
4466 if (has_delete_on_close(lck, fsp->name_hash)) {
4469 file_free(req, fsp);
4470 return NT_STATUS_DELETE_PENDING;
4473 status = open_mode_check(conn, lck,
4474 access_mask, share_access);
4476 if (!NT_STATUS_IS_OK(status)) {
4479 file_free(req, fsp);
4484 struct share_mode_data *d = lck->data;
4485 uint16_t new_flags = share_mode_flags_restrict(
4486 d->flags, access_mask, share_access, UINT32_MAX);
4488 if (new_flags != d->flags) {
4489 d->flags = new_flags;
4494 ok = set_share_mode(
4497 get_current_uid(conn),
4505 file_free(req, fsp);
4506 return NT_STATUS_NO_MEMORY;
4509 /* For directories the delete on close bit at open time seems
4510 always to be honored on close... See test 19 in Samba4 BASE-DELETE. */
4511 if (create_options & FILE_DELETE_ON_CLOSE) {
4512 status = can_set_delete_on_close(fsp, 0);
4513 if (!NT_STATUS_IS_OK(status) && !NT_STATUS_EQUAL(status, NT_STATUS_DIRECTORY_NOT_EMPTY)) {
4514 del_share_mode(lck, fsp);
4517 file_free(req, fsp);
4521 if (NT_STATUS_IS_OK(status)) {
4522 /* Note that here we set the *initial* delete on close flag,
4523 not the regular one. The magic gets handled in close. */
4524 fsp->fsp_flags.initial_delete_on_close = true;
4530 * Deal with other opens having a modified write time. Is this
4531 * possible for directories?
4533 struct timespec write_time = get_share_mode_write_time(lck);
4535 if (!is_omit_timespec(&write_time)) {
4536 update_stat_ex_mtime(&fsp->fsp_name->st, write_time);
4547 return NT_STATUS_OK;
4550 NTSTATUS create_directory(connection_struct *conn, struct smb_request *req,
4551 struct smb_filename *smb_dname)
4556 status = SMB_VFS_CREATE_FILE(
4559 0, /* root_dir_fid */
4560 smb_dname, /* fname */
4561 FILE_READ_ATTRIBUTES, /* access_mask */
4562 FILE_SHARE_NONE, /* share_access */
4563 FILE_CREATE, /* create_disposition*/
4564 FILE_DIRECTORY_FILE, /* create_options */
4565 FILE_ATTRIBUTE_DIRECTORY, /* file_attributes */
4566 0, /* oplock_request */
4568 0, /* allocation_size */
4569 0, /* private_flags */
4574 NULL, NULL); /* create context */
4576 if (NT_STATUS_IS_OK(status)) {
4577 close_file(req, fsp, NORMAL_CLOSE);
4583 /****************************************************************************
4584 Receive notification that one of our open files has been renamed by another
4586 ****************************************************************************/
4588 void msg_file_was_renamed(struct messaging_context *msg_ctx,
4591 struct server_id src,
4594 struct file_rename_message *msg = NULL;
4595 enum ndr_err_code ndr_err;
4597 struct smb_filename *smb_fname = NULL;
4598 struct smbd_server_connection *sconn =
4599 talloc_get_type_abort(private_data,
4600 struct smbd_server_connection);
4602 msg = talloc(talloc_tos(), struct file_rename_message);
4604 DBG_WARNING("talloc failed\n");
4608 ndr_err = ndr_pull_struct_blob_all(
4612 (ndr_pull_flags_fn_t)ndr_pull_file_rename_message);
4613 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
4614 DBG_DEBUG("ndr_pull_oplock_break_message failed: %s\n",
4615 ndr_errstr(ndr_err));
4618 if (DEBUGLEVEL >= 10) {
4619 struct server_id_buf buf;
4620 DBG_DEBUG("Got rename message from %s\n",
4621 server_id_str_buf(src, &buf));
4622 NDR_PRINT_DEBUG(file_rename_message, msg);
4625 /* stream_name must always be NULL if there is no stream. */
4626 if ((msg->stream_name != NULL) && (msg->stream_name[0] == '\0')) {
4627 msg->stream_name = NULL;
4630 smb_fname = synthetic_smb_fname(
4631 msg, msg->base_name, msg->stream_name, NULL, 0);
4632 if (smb_fname == NULL) {
4633 DBG_DEBUG("synthetic_smb_fname failed\n");
4637 fsp = file_find_dif(sconn, msg->id, msg->share_file_id);
4639 DBG_DEBUG("fsp not found\n");
4643 if (strcmp(fsp->conn->connectpath, msg->servicepath) == 0) {
4645 DBG_DEBUG("renaming file %s from %s -> %s\n",
4648 smb_fname_str_dbg(smb_fname));
4649 status = fsp_set_smb_fname(fsp, smb_fname);
4650 if (!NT_STATUS_IS_OK(status)) {
4651 DBG_DEBUG("fsp_set_smb_fname failed: %s\n",
4657 * Now we have the complete path we can work out if
4658 * this is actually within this share and adjust
4659 * newname accordingly.
4661 DBG_DEBUG("share mismatch (sharepath %s not sharepath %s) "
4662 "%s from %s -> %s\n",
4663 fsp->conn->connectpath,
4667 smb_fname_str_dbg(smb_fname));
4674 * If a main file is opened for delete, all streams need to be checked for
4675 * !FILE_SHARE_DELETE. Do this by opening with DELETE_ACCESS.
4676 * If that works, delete them all by setting the delete on close and close.
4679 static NTSTATUS open_streams_for_delete(connection_struct *conn,
4680 const struct smb_filename *smb_fname)
4682 struct stream_struct *stream_info = NULL;
4683 files_struct **streams = NULL;
4685 unsigned int i, num_streams = 0;
4686 TALLOC_CTX *frame = talloc_stackframe();
4689 status = vfs_streaminfo(conn, NULL, smb_fname, talloc_tos(),
4690 &num_streams, &stream_info);
4692 if (NT_STATUS_EQUAL(status, NT_STATUS_NOT_IMPLEMENTED)
4693 || NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
4694 DEBUG(10, ("no streams around\n"));
4696 return NT_STATUS_OK;
4699 if (!NT_STATUS_IS_OK(status)) {
4700 DEBUG(10, ("vfs_streaminfo failed: %s\n",
4701 nt_errstr(status)));
4705 DEBUG(10, ("open_streams_for_delete found %d streams\n",
4708 if (num_streams == 0) {
4710 return NT_STATUS_OK;
4713 streams = talloc_array(talloc_tos(), files_struct *, num_streams);
4714 if (streams == NULL) {
4715 DEBUG(0, ("talloc failed\n"));
4716 status = NT_STATUS_NO_MEMORY;
4720 for (i=0; i<num_streams; i++) {
4721 struct smb_filename *smb_fname_cp;
4723 if (strequal(stream_info[i].name, "::$DATA")) {
4728 smb_fname_cp = synthetic_smb_fname(talloc_tos(),
4729 smb_fname->base_name,
4730 stream_info[i].name,
4733 ~SMB_FILENAME_POSIX_PATH));
4734 if (smb_fname_cp == NULL) {
4735 status = NT_STATUS_NO_MEMORY;
4739 if (SMB_VFS_STAT(conn, smb_fname_cp) == -1) {
4740 DEBUG(10, ("Unable to stat stream: %s\n",
4741 smb_fname_str_dbg(smb_fname_cp)));
4744 status = SMB_VFS_CREATE_FILE(
4747 0, /* root_dir_fid */
4748 smb_fname_cp, /* fname */
4749 DELETE_ACCESS, /* access_mask */
4750 (FILE_SHARE_READ | /* share_access */
4751 FILE_SHARE_WRITE | FILE_SHARE_DELETE),
4752 FILE_OPEN, /* create_disposition*/
4753 0, /* create_options */
4754 FILE_ATTRIBUTE_NORMAL, /* file_attributes */
4755 0, /* oplock_request */
4757 0, /* allocation_size */
4758 NTCREATEX_OPTIONS_PRIVATE_STREAM_DELETE, /* private_flags */
4761 &streams[i], /* result */
4763 NULL, NULL); /* create context */
4765 if (!NT_STATUS_IS_OK(status)) {
4766 DEBUG(10, ("Could not open stream %s: %s\n",
4767 smb_fname_str_dbg(smb_fname_cp),
4768 nt_errstr(status)));
4770 TALLOC_FREE(smb_fname_cp);
4773 TALLOC_FREE(smb_fname_cp);
4777 * don't touch the variable "status" beyond this point :-)
4780 for (j = i-1 ; j >= 0; j--) {
4781 if (streams[j] == NULL) {
4785 DEBUG(10, ("Closing stream # %d, %s\n", j,
4786 fsp_str_dbg(streams[j])));
4787 close_file(NULL, streams[j], NORMAL_CLOSE);
4795 /*********************************************************************
4796 Create a default ACL by inheriting from the parent. If no inheritance
4797 from the parent available, don't set anything. This will leave the actual
4798 permissions the new file or directory already got from the filesystem
4799 as the NT ACL when read.
4800 *********************************************************************/
4802 static NTSTATUS inherit_new_acl(files_struct *fsp)
4804 TALLOC_CTX *frame = talloc_stackframe();
4805 char *parent_name = NULL;
4806 struct security_descriptor *parent_desc = NULL;
4807 NTSTATUS status = NT_STATUS_OK;
4808 struct security_descriptor *psd = NULL;
4809 const struct dom_sid *owner_sid = NULL;
4810 const struct dom_sid *group_sid = NULL;
4811 uint32_t security_info_sent = (SECINFO_OWNER | SECINFO_GROUP | SECINFO_DACL);
4812 struct security_token *token = fsp->conn->session_info->security_token;
4813 bool inherit_owner =
4814 (lp_inherit_owner(SNUM(fsp->conn)) == INHERIT_OWNER_WINDOWS_AND_UNIX);
4815 bool inheritable_components = false;
4816 bool try_builtin_administrators = false;
4817 const struct dom_sid *BA_U_sid = NULL;
4818 const struct dom_sid *BA_G_sid = NULL;
4819 bool try_system = false;
4820 const struct dom_sid *SY_U_sid = NULL;
4821 const struct dom_sid *SY_G_sid = NULL;
4823 struct smb_filename *parent_smb_fname = NULL;
4825 if (!parent_dirname(frame, fsp->fsp_name->base_name, &parent_name, NULL)) {
4827 return NT_STATUS_NO_MEMORY;
4829 parent_smb_fname = synthetic_smb_fname(talloc_tos(),
4833 fsp->fsp_name->flags);
4835 if (parent_smb_fname == NULL) {
4837 return NT_STATUS_NO_MEMORY;
4840 status = SMB_VFS_GET_NT_ACL(fsp->conn,
4842 (SECINFO_OWNER | SECINFO_GROUP | SECINFO_DACL),
4845 if (!NT_STATUS_IS_OK(status)) {
4850 inheritable_components = sd_has_inheritable_components(parent_desc,
4851 fsp->fsp_flags.is_directory);
4853 if (!inheritable_components && !inherit_owner) {
4855 /* Nothing to inherit and not setting owner. */
4856 return NT_STATUS_OK;
4859 /* Create an inherited descriptor from the parent. */
4861 if (DEBUGLEVEL >= 10) {
4862 DEBUG(10,("inherit_new_acl: parent acl for %s is:\n",
4863 fsp_str_dbg(fsp) ));
4864 NDR_PRINT_DEBUG(security_descriptor, parent_desc);
4867 /* Inherit from parent descriptor if "inherit owner" set. */
4868 if (inherit_owner) {
4869 owner_sid = parent_desc->owner_sid;
4870 group_sid = parent_desc->group_sid;
4873 if (owner_sid == NULL) {
4874 if (security_token_has_builtin_administrators(token)) {
4875 try_builtin_administrators = true;
4876 } else if (security_token_is_system(token)) {
4877 try_builtin_administrators = true;
4882 if (group_sid == NULL &&
4883 token->num_sids == PRIMARY_GROUP_SID_INDEX)
4885 if (security_token_is_system(token)) {
4886 try_builtin_administrators = true;
4891 if (try_builtin_administrators) {
4896 ok = sids_to_unixids(&global_sid_Builtin_Administrators, 1, &ids);
4900 BA_U_sid = &global_sid_Builtin_Administrators;
4901 BA_G_sid = &global_sid_Builtin_Administrators;
4904 BA_U_sid = &global_sid_Builtin_Administrators;
4907 BA_G_sid = &global_sid_Builtin_Administrators;
4920 ok = sids_to_unixids(&global_sid_System, 1, &ids);
4924 SY_U_sid = &global_sid_System;
4925 SY_G_sid = &global_sid_System;
4928 SY_U_sid = &global_sid_System;
4931 SY_G_sid = &global_sid_System;
4939 if (owner_sid == NULL) {
4940 owner_sid = BA_U_sid;
4943 if (owner_sid == NULL) {
4944 owner_sid = SY_U_sid;
4947 if (group_sid == NULL) {
4948 group_sid = SY_G_sid;
4951 if (try_system && group_sid == NULL) {
4952 group_sid = BA_G_sid;
4955 if (owner_sid == NULL) {
4956 owner_sid = &token->sids[PRIMARY_USER_SID_INDEX];
4958 if (group_sid == NULL) {
4959 if (token->num_sids == PRIMARY_GROUP_SID_INDEX) {
4960 group_sid = &token->sids[PRIMARY_USER_SID_INDEX];
4962 group_sid = &token->sids[PRIMARY_GROUP_SID_INDEX];
4966 status = se_create_child_secdesc(frame,
4972 fsp->fsp_flags.is_directory);
4973 if (!NT_STATUS_IS_OK(status)) {
4978 /* If inheritable_components == false,
4979 se_create_child_secdesc()
4980 creates a security descriptor with a NULL dacl
4981 entry, but with SEC_DESC_DACL_PRESENT. We need
4982 to remove that flag. */
4984 if (!inheritable_components) {
4985 security_info_sent &= ~SECINFO_DACL;
4986 psd->type &= ~SEC_DESC_DACL_PRESENT;
4989 if (DEBUGLEVEL >= 10) {
4990 DEBUG(10,("inherit_new_acl: child acl for %s is:\n",
4991 fsp_str_dbg(fsp) ));
4992 NDR_PRINT_DEBUG(security_descriptor, psd);
4995 if (inherit_owner) {
4996 /* We need to be root to force this. */
4999 status = SMB_VFS_FSET_NT_ACL(fsp,
5002 if (inherit_owner) {
5010 * If we already have a lease, it must match the new file id. [MS-SMB2]
5011 * 3.3.5.9.8 speaks about INVALID_PARAMETER if an already used lease key is
5012 * used for a different file name.
5015 struct lease_match_state {
5016 /* Input parameters. */
5017 TALLOC_CTX *mem_ctx;
5018 const char *servicepath;
5019 const struct smb_filename *fname;
5022 /* Return parameters. */
5023 uint32_t num_file_ids;
5024 struct file_id *ids;
5025 NTSTATUS match_status;
5028 /*************************************************************
5029 File doesn't exist but this lease key+guid is already in use.
5031 This is only allowable in the dynamic share case where the
5032 service path must be different.
5034 There is a small race condition here in the multi-connection
5035 case where a client sends two create calls on different connections,
5036 where the file doesn't exist and one smbd creates the leases_db
5037 entry first, but this will get fixed by the multichannel cleanup
5038 when all identical client_guids get handled by a single smbd.
5039 **************************************************************/
5041 static void lease_match_parser_new_file(
5043 const struct leases_db_file *files,
5044 struct lease_match_state *state)
5048 for (i = 0; i < num_files; i++) {
5049 const struct leases_db_file *f = &files[i];
5050 if (strequal(state->servicepath, f->servicepath)) {
5051 state->match_status = NT_STATUS_INVALID_PARAMETER;
5056 /* Dynamic share case. Break leases on all other files. */
5057 state->match_status = leases_db_copy_file_ids(state->mem_ctx,
5061 if (!NT_STATUS_IS_OK(state->match_status)) {
5065 state->num_file_ids = num_files;
5066 state->match_status = NT_STATUS_OPLOCK_NOT_GRANTED;
5070 static void lease_match_parser(
5072 const struct leases_db_file *files,
5075 struct lease_match_state *state =
5076 (struct lease_match_state *)private_data;
5079 if (!state->file_existed) {
5081 * Deal with name mismatch or
5082 * possible dynamic share case separately
5083 * to make code clearer.
5085 lease_match_parser_new_file(num_files,
5092 state->match_status = NT_STATUS_OK;
5094 for (i = 0; i < num_files; i++) {
5095 const struct leases_db_file *f = &files[i];
5097 /* Everything should be the same. */
5098 if (!file_id_equal(&state->id, &f->id)) {
5099 /* This should catch all dynamic share cases. */
5100 state->match_status = NT_STATUS_OPLOCK_NOT_GRANTED;
5103 if (!strequal(f->servicepath, state->servicepath)) {
5104 state->match_status = NT_STATUS_INVALID_PARAMETER;
5107 if (!strequal(f->base_name, state->fname->base_name)) {
5108 state->match_status = NT_STATUS_INVALID_PARAMETER;
5111 if (!strequal(f->stream_name, state->fname->stream_name)) {
5112 state->match_status = NT_STATUS_INVALID_PARAMETER;
5117 if (NT_STATUS_IS_OK(state->match_status)) {
5119 * Common case - just opening another handle on a
5120 * file on a non-dynamic share.
5125 if (NT_STATUS_EQUAL(state->match_status, NT_STATUS_INVALID_PARAMETER)) {
5126 /* Mismatched path. Error back to client. */
5131 * File id mismatch. Dynamic share case NT_STATUS_OPLOCK_NOT_GRANTED.
5132 * Don't allow leases.
5135 state->match_status = leases_db_copy_file_ids(state->mem_ctx,
5139 if (!NT_STATUS_IS_OK(state->match_status)) {
5143 state->num_file_ids = num_files;
5144 state->match_status = NT_STATUS_OPLOCK_NOT_GRANTED;
5148 struct lease_match_break_state {
5149 struct messaging_context *msg_ctx;
5150 const struct smb2_lease_key *lease_key;
5158 static bool lease_match_break_fn(
5159 struct share_mode_entry *e,
5162 struct lease_match_break_state *state = private_data;
5164 uint32_t e_lease_type;
5167 stale = share_entry_stale_pid(e);
5172 equal = smb2_lease_key_equal(&e->lease_key, state->lease_key);
5177 status = leases_db_get(
5181 NULL, /* current_state */
5182 NULL, /* breaking */
5183 NULL, /* breaking_to_requested */
5184 NULL, /* breaking_to_required */
5185 &state->version, /* lease_version */
5186 &state->epoch); /* epoch */
5187 if (NT_STATUS_IS_OK(status)) {
5188 state->found_lease = true;
5190 DBG_WARNING("Could not find version/epoch: %s\n",
5194 e_lease_type = get_lease_type(e, state->id);
5195 if (e_lease_type == SMB2_LEASE_NONE) {
5198 send_break_message(state->msg_ctx, &state->id, e, SMB2_LEASE_NONE);
5201 * Windows 7 and 8 lease clients are broken in that they will
5202 * not respond to lease break requests whilst waiting for an
5203 * outstanding open request on that lease handle on the same
5204 * TCP connection, due to holding an internal inode lock.
5206 * This means we can't reschedule ourselves here, but must
5207 * return from the create.
5211 * Send the breaks and then return SMB2_LEASE_NONE in the
5212 * lease handle to cause them to acknowledge the lease
5213 * break. Consultation with Microsoft engineering confirmed
5214 * this approach is safe.
5220 static NTSTATUS lease_match(connection_struct *conn,
5221 struct smb_request *req,
5222 const struct smb2_lease_key *lease_key,
5223 const char *servicepath,
5224 const struct smb_filename *fname,
5225 uint16_t *p_version,
5228 struct smbd_server_connection *sconn = req->sconn;
5229 TALLOC_CTX *tos = talloc_tos();
5230 struct lease_match_state state = {
5232 .servicepath = servicepath,
5234 .match_status = NT_STATUS_OK
5239 state.file_existed = VALID_STAT(fname->st);
5240 if (state.file_existed) {
5241 state.id = vfs_file_id_from_sbuf(conn, &fname->st);
5244 status = leases_db_parse(&sconn->client->connections->smb2.client.guid,
5245 lease_key, lease_match_parser, &state);
5246 if (!NT_STATUS_IS_OK(status)) {
5248 * Not found or error means okay: We can make the lease pass
5250 return NT_STATUS_OK;
5252 if (!NT_STATUS_EQUAL(state.match_status, NT_STATUS_OPLOCK_NOT_GRANTED)) {
5254 * Anything but NT_STATUS_OPLOCK_NOT_GRANTED, let the caller
5257 return state.match_status;
5260 /* We have to break all existing leases. */
5261 for (i = 0; i < state.num_file_ids; i++) {
5262 struct lease_match_break_state break_state = {
5263 .msg_ctx = conn->sconn->msg_ctx,
5264 .lease_key = lease_key,
5266 struct share_mode_lock *lck;
5269 if (file_id_equal(&state.ids[i], &state.id)) {
5270 /* Don't need to break our own file. */
5274 break_state.id = state.ids[i];
5276 lck = get_existing_share_mode_lock(
5277 talloc_tos(), break_state.id);
5279 /* Race condition - file already closed. */
5283 ok = share_mode_forall_leases(
5284 lck, lease_match_break_fn, &break_state);
5286 DBG_DEBUG("share_mode_forall_leases failed\n");
5292 if (break_state.found_lease) {
5293 *p_version = break_state.version;
5294 *p_epoch = break_state.epoch;
5298 * Ensure we don't grant anything more so we
5301 return NT_STATUS_OPLOCK_NOT_GRANTED;
5305 * Wrapper around open_file_ntcreate and open_directory
5308 static NTSTATUS create_file_unixpath(connection_struct *conn,
5309 struct smb_request *req,
5310 struct smb_filename *smb_fname,
5311 uint32_t access_mask,
5312 uint32_t share_access,
5313 uint32_t create_disposition,
5314 uint32_t create_options,
5315 uint32_t file_attributes,
5316 uint32_t oplock_request,
5317 const struct smb2_lease *lease,
5318 uint64_t allocation_size,
5319 uint32_t private_flags,
5320 struct security_descriptor *sd,
5321 struct ea_list *ea_list,
5323 files_struct **result,
5326 struct smb2_lease none_lease;
5327 int info = FILE_WAS_OPENED;
5328 files_struct *base_fsp = NULL;
5329 files_struct *fsp = NULL;
5332 DBG_DEBUG("create_file_unixpath: access_mask = 0x%x "
5333 "file_attributes = 0x%x, share_access = 0x%x, "
5334 "create_disposition = 0x%x create_options = 0x%x "
5335 "oplock_request = 0x%x private_flags = 0x%x "
5336 "ea_list = %p, sd = %p, "
5338 (unsigned int)access_mask,
5339 (unsigned int)file_attributes,
5340 (unsigned int)share_access,
5341 (unsigned int)create_disposition,
5342 (unsigned int)create_options,
5343 (unsigned int)oplock_request,
5344 (unsigned int)private_flags,
5345 ea_list, sd, smb_fname_str_dbg(smb_fname));
5347 if (create_options & FILE_OPEN_BY_FILE_ID) {
5348 status = NT_STATUS_NOT_SUPPORTED;
5352 if (create_options & NTCREATEX_OPTIONS_INVALID_PARAM_MASK) {
5353 status = NT_STATUS_INVALID_PARAMETER;
5358 oplock_request |= INTERNAL_OPEN_ONLY;
5361 if (lease != NULL) {
5362 uint16_t epoch = lease->lease_epoch;
5363 uint16_t version = lease->lease_version;
5366 DBG_WARNING("Got lease on internal open\n");
5367 status = NT_STATUS_INTERNAL_ERROR;
5371 status = lease_match(conn,
5378 if (NT_STATUS_EQUAL(status, NT_STATUS_OPLOCK_NOT_GRANTED)) {
5379 /* Dynamic share file. No leases and update epoch... */
5380 none_lease = *lease;
5381 none_lease.lease_state = SMB2_LEASE_NONE;
5382 none_lease.lease_epoch = epoch;
5383 none_lease.lease_version = version;
5384 lease = &none_lease;
5385 } else if (!NT_STATUS_IS_OK(status)) {
5390 if ((conn->fs_capabilities & FILE_NAMED_STREAMS)
5391 && (access_mask & DELETE_ACCESS)
5392 && !is_ntfs_stream_smb_fname(smb_fname)) {
5394 * We can't open a file with DELETE access if any of the
5395 * streams is open without FILE_SHARE_DELETE
5397 status = open_streams_for_delete(conn, smb_fname);
5399 if (!NT_STATUS_IS_OK(status)) {
5404 if (access_mask & SEC_FLAG_SYSTEM_SECURITY) {
5407 ok = security_token_has_privilege(get_current_nttok(conn),
5410 DBG_DEBUG("open on %s failed - "
5411 "SEC_FLAG_SYSTEM_SECURITY denied.\n",
5412 smb_fname_str_dbg(smb_fname));
5413 status = NT_STATUS_PRIVILEGE_NOT_HELD;
5417 if (conn->sconn->using_smb2 &&
5418 (access_mask == SEC_FLAG_SYSTEM_SECURITY))
5421 * No other bits set. Windows SMB2 refuses this.
5422 * See smbtorture3 SMB2-SACL test.
5424 * Note this is an SMB2-only behavior,
5425 * smbtorture3 SMB1-SYSTEM-SECURITY already tests
5426 * that SMB1 allows this.
5428 status = NT_STATUS_ACCESS_DENIED;
5434 * Files or directories can't be opened DELETE_ON_CLOSE without
5436 * BUG: https://bugzilla.samba.org/show_bug.cgi?id=13358
5438 if (create_options & FILE_DELETE_ON_CLOSE) {
5439 if ((access_mask & DELETE_ACCESS) == 0) {
5440 status = NT_STATUS_INVALID_PARAMETER;
5445 if ((conn->fs_capabilities & FILE_NAMED_STREAMS)
5446 && is_ntfs_stream_smb_fname(smb_fname)
5447 && (!(private_flags & NTCREATEX_OPTIONS_PRIVATE_STREAM_DELETE))) {
5448 uint32_t base_create_disposition;
5449 struct smb_filename *smb_fname_base = NULL;
5450 uint32_t base_privflags;
5452 if (create_options & FILE_DIRECTORY_FILE) {
5453 status = NT_STATUS_NOT_A_DIRECTORY;
5457 switch (create_disposition) {
5459 base_create_disposition = FILE_OPEN;
5462 base_create_disposition = FILE_OPEN_IF;
5466 /* Create an smb_filename with stream_name == NULL. */
5467 smb_fname_base = synthetic_smb_fname(talloc_tos(),
5468 smb_fname->base_name,
5472 if (smb_fname_base == NULL) {
5473 status = NT_STATUS_NO_MEMORY;
5477 if (SMB_VFS_STAT(conn, smb_fname_base) == -1) {
5478 DEBUG(10, ("Unable to stat stream: %s\n",
5479 smb_fname_str_dbg(smb_fname_base)));
5482 * https://bugzilla.samba.org/show_bug.cgi?id=10229
5483 * We need to check if the requested access mask
5484 * could be used to open the underlying file (if
5485 * it existed), as we're passing in zero for the
5486 * access mask to the base filename.
5488 status = check_base_file_access(conn,
5492 if (!NT_STATUS_IS_OK(status)) {
5493 DEBUG(10, ("Permission check "
5494 "for base %s failed: "
5495 "%s\n", smb_fname->base_name,
5496 nt_errstr(status)));
5501 base_privflags = NTCREATEX_OPTIONS_PRIVATE_STREAM_BASEOPEN;
5503 /* Open the base file. */
5504 status = create_file_unixpath(conn, NULL, smb_fname_base, 0,
5507 | FILE_SHARE_DELETE,
5508 base_create_disposition,
5513 TALLOC_FREE(smb_fname_base);
5515 if (!NT_STATUS_IS_OK(status)) {
5516 DEBUG(10, ("create_file_unixpath for base %s failed: "
5517 "%s\n", smb_fname->base_name,
5518 nt_errstr(status)));
5521 /* we don't need the low level fd */
5526 * If it's a request for a directory open, deal with it separately.
5529 if (create_options & FILE_DIRECTORY_FILE) {
5531 if (create_options & FILE_NON_DIRECTORY_FILE) {
5532 status = NT_STATUS_INVALID_PARAMETER;
5536 /* Can't open a temp directory. IFS kit test. */
5537 if (!(file_attributes & FILE_FLAG_POSIX_SEMANTICS) &&
5538 (file_attributes & FILE_ATTRIBUTE_TEMPORARY)) {
5539 status = NT_STATUS_INVALID_PARAMETER;
5544 * We will get a create directory here if the Win32
5545 * app specified a security descriptor in the
5546 * CreateDirectory() call.
5550 status = open_directory(
5551 conn, req, smb_fname, access_mask, share_access,
5552 create_disposition, create_options, file_attributes,
5557 * Ordinary file case.
5560 status = file_new(req, conn, &fsp);
5561 if(!NT_STATUS_IS_OK(status)) {
5565 status = fsp_set_smb_fname(fsp, smb_fname);
5566 if (!NT_STATUS_IS_OK(status)) {
5572 * We're opening the stream element of a
5573 * base_fsp we already opened. Set up the
5576 fsp->base_fsp = base_fsp;
5579 if (allocation_size) {
5580 fsp->initial_allocation_size = smb_roundup(fsp->conn,
5584 status = open_file_ntcreate(conn,
5597 if(!NT_STATUS_IS_OK(status)) {
5598 file_free(req, fsp);
5602 if (NT_STATUS_EQUAL(status, NT_STATUS_FILE_IS_A_DIRECTORY)) {
5604 /* A stream open never opens a directory */
5607 status = NT_STATUS_FILE_IS_A_DIRECTORY;
5612 * Fail the open if it was explicitly a non-directory
5616 if (create_options & FILE_NON_DIRECTORY_FILE) {
5617 status = NT_STATUS_FILE_IS_A_DIRECTORY;
5622 status = open_directory(
5623 conn, req, smb_fname, access_mask,
5624 share_access, create_disposition,
5625 create_options, file_attributes,
5630 if (!NT_STATUS_IS_OK(status)) {
5634 fsp->base_fsp = base_fsp;
5636 if ((ea_list != NULL) &&
5637 ((info == FILE_WAS_CREATED) || (info == FILE_WAS_OVERWRITTEN))) {
5638 status = set_ea(conn, fsp, fsp->fsp_name, ea_list);
5639 if (!NT_STATUS_IS_OK(status)) {
5644 if (!fsp->fsp_flags.is_directory &&
5645 S_ISDIR(fsp->fsp_name->st.st_ex_mode))
5647 status = NT_STATUS_ACCESS_DENIED;
5651 /* Save the requested allocation size. */
5652 if ((info == FILE_WAS_CREATED) || (info == FILE_WAS_OVERWRITTEN)) {
5653 if ((allocation_size > (uint64_t)fsp->fsp_name->st.st_ex_size)
5654 && !(fsp->fsp_flags.is_directory))
5656 fsp->initial_allocation_size = smb_roundup(
5657 fsp->conn, allocation_size);
5658 if (vfs_allocate_file_space(
5659 fsp, fsp->initial_allocation_size) == -1) {
5660 status = NT_STATUS_DISK_FULL;
5664 fsp->initial_allocation_size = smb_roundup(
5665 fsp->conn, (uint64_t)fsp->fsp_name->st.st_ex_size);
5668 fsp->initial_allocation_size = 0;
5671 if ((info == FILE_WAS_CREATED) && lp_nt_acl_support(SNUM(conn)) &&
5672 fsp->base_fsp == NULL) {
5675 * According to the MS documentation, the only time the security
5676 * descriptor is applied to the opened file is iff we *created* the
5677 * file; an existing file stays the same.
5679 * Also, it seems (from observation) that you can open the file with
5680 * any access mask but you can still write the sd. We need to override
5681 * the granted access before we call set_sd
5682 * Patch for bug #2242 from Tom Lackemann <cessnatomny@yahoo.com>.
5685 uint32_t sec_info_sent;
5686 uint32_t saved_access_mask = fsp->access_mask;
5688 sec_info_sent = get_sec_info(sd);
5690 fsp->access_mask = FILE_GENERIC_ALL;
5692 if (sec_info_sent & (SECINFO_OWNER|
5696 status = set_sd(fsp, sd, sec_info_sent);
5699 fsp->access_mask = saved_access_mask;
5701 if (!NT_STATUS_IS_OK(status)) {
5704 } else if (lp_inherit_acls(SNUM(conn))) {
5705 /* Inherit from parent. Errors here are not fatal. */
5706 status = inherit_new_acl(fsp);
5707 if (!NT_STATUS_IS_OK(status)) {
5708 DEBUG(10,("inherit_new_acl: failed for %s with %s\n",
5710 nt_errstr(status) ));
5715 if ((conn->fs_capabilities & FILE_FILE_COMPRESSION)
5716 && (create_options & FILE_NO_COMPRESSION)
5717 && (info == FILE_WAS_CREATED)) {
5718 status = SMB_VFS_SET_COMPRESSION(conn, fsp, fsp,
5719 COMPRESSION_FORMAT_NONE);
5720 if (!NT_STATUS_IS_OK(status)) {
5721 DEBUG(1, ("failed to disable compression: %s\n",
5722 nt_errstr(status)));
5726 DEBUG(10, ("create_file_unixpath: info=%d\n", info));
5729 if (pinfo != NULL) {
5733 smb_fname->st = fsp->fsp_name->st;
5735 return NT_STATUS_OK;
5738 DEBUG(10, ("create_file_unixpath: %s\n", nt_errstr(status)));
5741 if (base_fsp && fsp->base_fsp == base_fsp) {
5743 * The close_file below will close
5748 close_file(req, fsp, ERROR_CLOSE);
5751 if (base_fsp != NULL) {
5752 close_file(req, base_fsp, ERROR_CLOSE);
5759 * Calculate the full path name given a relative fid.
5761 static NTSTATUS get_relative_fid_filename(
5762 connection_struct *conn,
5763 struct smb_request *req,
5764 uint16_t root_dir_fid,
5765 const struct smb_filename *smb_fname,
5766 struct smb_filename **smb_fname_out)
5768 files_struct *dir_fsp;
5769 char *parent_fname = NULL;
5770 char *new_base_name = NULL;
5771 uint32_t ucf_flags = ucf_flags_from_smb_request(req);
5774 if (root_dir_fid == 0 || !smb_fname) {
5775 status = NT_STATUS_INTERNAL_ERROR;
5779 dir_fsp = file_fsp(req, root_dir_fid);
5781 if (dir_fsp == NULL) {
5782 status = NT_STATUS_INVALID_HANDLE;
5786 if (is_ntfs_stream_smb_fname(dir_fsp->fsp_name)) {
5787 status = NT_STATUS_INVALID_HANDLE;
5791 if (!dir_fsp->fsp_flags.is_directory) {
5794 * Check to see if this is a mac fork of some kind.
5797 if ((conn->fs_capabilities & FILE_NAMED_STREAMS) &&
5798 is_ntfs_stream_smb_fname(smb_fname)) {
5799 status = NT_STATUS_OBJECT_PATH_NOT_FOUND;
5804 we need to handle the case when we get a
5805 relative open relative to a file and the
5806 pathname is blank - this is a reopen!
5807 (hint from demyn plantenberg)
5810 status = NT_STATUS_INVALID_HANDLE;
5814 if (ISDOT(dir_fsp->fsp_name->base_name)) {
5816 * We're at the toplevel dir, the final file name
5817 * must not contain ./, as this is filtered out
5818 * normally by srvstr_get_path and unix_convert
5819 * explicitly rejects paths containing ./.
5821 parent_fname = talloc_strdup(talloc_tos(), "");
5822 if (parent_fname == NULL) {
5823 status = NT_STATUS_NO_MEMORY;
5827 size_t dir_name_len = strlen(dir_fsp->fsp_name->base_name);
5830 * Copy in the base directory name.
5833 parent_fname = talloc_array(talloc_tos(), char,
5835 if (parent_fname == NULL) {
5836 status = NT_STATUS_NO_MEMORY;
5839 memcpy(parent_fname, dir_fsp->fsp_name->base_name,
5843 * Ensure it ends in a '/'.
5844 * We used TALLOC_SIZE +2 to add space for the '/'.
5848 && (parent_fname[dir_name_len-1] != '\\')
5849 && (parent_fname[dir_name_len-1] != '/')) {
5850 parent_fname[dir_name_len] = '/';
5851 parent_fname[dir_name_len+1] = '\0';
5855 new_base_name = talloc_asprintf(talloc_tos(), "%s%s", parent_fname,
5856 smb_fname->base_name);
5857 if (new_base_name == NULL) {
5858 status = NT_STATUS_NO_MEMORY;
5862 status = filename_convert(req,
5869 if (!NT_STATUS_IS_OK(status)) {
5874 TALLOC_FREE(parent_fname);
5875 TALLOC_FREE(new_base_name);
5879 NTSTATUS create_file_default(connection_struct *conn,
5880 struct smb_request *req,
5881 uint16_t root_dir_fid,
5882 struct smb_filename *smb_fname,
5883 uint32_t access_mask,
5884 uint32_t share_access,
5885 uint32_t create_disposition,
5886 uint32_t create_options,
5887 uint32_t file_attributes,
5888 uint32_t oplock_request,
5889 const struct smb2_lease *lease,
5890 uint64_t allocation_size,
5891 uint32_t private_flags,
5892 struct security_descriptor *sd,
5893 struct ea_list *ea_list,
5894 files_struct **result,
5896 const struct smb2_create_blobs *in_context_blobs,
5897 struct smb2_create_blobs *out_context_blobs)
5899 int info = FILE_WAS_OPENED;
5900 files_struct *fsp = NULL;
5902 bool stream_name = false;
5903 struct smb2_create_blob *posx = NULL;
5905 DBG_DEBUG("create_file: access_mask = 0x%x "
5906 "file_attributes = 0x%x, share_access = 0x%x, "
5907 "create_disposition = 0x%x create_options = 0x%x "
5908 "oplock_request = 0x%x "
5909 "private_flags = 0x%x "
5910 "root_dir_fid = 0x%x, ea_list = %p, sd = %p, "
5912 (unsigned int)access_mask,
5913 (unsigned int)file_attributes,
5914 (unsigned int)share_access,
5915 (unsigned int)create_disposition,
5916 (unsigned int)create_options,
5917 (unsigned int)oplock_request,
5918 (unsigned int)private_flags,
5919 (unsigned int)root_dir_fid,
5920 ea_list, sd, smb_fname_str_dbg(smb_fname));
5924 * Remember the absolute time of the original request
5925 * with this mid. We'll use it later to see if this
5928 get_deferred_open_message_state(req, &req->request_time, NULL);
5932 * Calculate the filename from the root_dir_if if necessary.
5935 if (root_dir_fid != 0) {
5936 struct smb_filename *smb_fname_out = NULL;
5937 status = get_relative_fid_filename(conn, req, root_dir_fid,
5938 smb_fname, &smb_fname_out);
5939 if (!NT_STATUS_IS_OK(status)) {
5942 smb_fname = smb_fname_out;
5946 * Check to see if this is a mac fork of some kind.
5949 stream_name = is_ntfs_stream_smb_fname(smb_fname);
5951 enum FAKE_FILE_TYPE fake_file_type;
5953 fake_file_type = is_fake_file(smb_fname);
5955 if (fake_file_type != FAKE_FILE_TYPE_NONE) {
5958 * Here we go! support for changing the disk quotas
5961 * We need to fake up to open this MAGIC QUOTA file
5962 * and return a valid FID.
5964 * w2k close this file directly after openening xp
5965 * also tries a QUERY_FILE_INFO on the file and then
5968 status = open_fake_file(req, conn, req->vuid,
5969 fake_file_type, smb_fname,
5971 if (!NT_STATUS_IS_OK(status)) {
5975 ZERO_STRUCT(smb_fname->st);
5979 if (!(conn->fs_capabilities & FILE_NAMED_STREAMS)) {
5980 status = NT_STATUS_OBJECT_NAME_NOT_FOUND;
5985 if (is_ntfs_default_stream_smb_fname(smb_fname)) {
5987 smb_fname->stream_name = NULL;
5988 /* We have to handle this error here. */
5989 if (create_options & FILE_DIRECTORY_FILE) {
5990 status = NT_STATUS_NOT_A_DIRECTORY;
5993 if (req != NULL && req->posix_pathnames) {
5994 ret = SMB_VFS_LSTAT(conn, smb_fname);
5996 ret = SMB_VFS_STAT(conn, smb_fname);
5999 if (ret == 0 && VALID_STAT_OF_DIR(smb_fname->st)) {
6000 status = NT_STATUS_FILE_IS_A_DIRECTORY;
6005 posx = smb2_create_blob_find(
6006 in_context_blobs, SMB2_CREATE_TAG_POSIX);
6008 uint32_t wire_mode_bits = 0;
6009 mode_t mode_bits = 0;
6010 SMB_STRUCT_STAT sbuf = { 0 };
6011 enum perm_type ptype =
6012 (create_options & FILE_DIRECTORY_FILE) ?
6013 PERM_NEW_DIR : PERM_NEW_FILE;
6015 if (posx->data.length != 4) {
6016 status = NT_STATUS_INVALID_PARAMETER;
6020 wire_mode_bits = IVAL(posx->data.data, 0);
6021 status = unix_perms_from_wire(
6022 conn, &sbuf, wire_mode_bits, ptype, &mode_bits);
6023 if (!NT_STATUS_IS_OK(status)) {
6027 * Remove type info from mode, leaving only the
6028 * permissions and setuid/gid bits.
6030 mode_bits &= ~S_IFMT;
6032 file_attributes = (FILE_FLAG_POSIX_SEMANTICS | mode_bits);
6035 status = create_file_unixpath(
6036 conn, req, smb_fname, access_mask, share_access,
6037 create_disposition, create_options, file_attributes,
6038 oplock_request, lease, allocation_size, private_flags,
6042 if (!NT_STATUS_IS_OK(status)) {
6047 DEBUG(10, ("create_file: info=%d\n", info));
6050 if (pinfo != NULL) {
6053 return NT_STATUS_OK;
6056 DEBUG(10, ("create_file: %s\n", nt_errstr(status)));
6059 close_file(req, fsp, ERROR_CLOSE);