2 Unix SMB/CIFS implementation.
3 file opening and share modes
4 Copyright (C) Andrew Tridgell 1992-1998
5 Copyright (C) Jeremy Allison 2001-2004
6 Copyright (C) Volker Lendecke 2005
7 Copyright (C) Ralph Boehme 2017
9 This program is free software; you can redistribute it and/or modify
10 it under the terms of the GNU General Public License as published by
11 the Free Software Foundation; either version 3 of the License, or
12 (at your option) any later version.
14 This program is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 GNU General Public License for more details.
19 You should have received a copy of the GNU General Public License
20 along with this program. If not, see <http://www.gnu.org/licenses/>.
24 #include "smb1_utils.h"
25 #include "system/filesys.h"
26 #include "lib/util/server_id.h"
28 #include "smbd/smbd.h"
29 #include "smbd/globals.h"
30 #include "fake_file.h"
31 #include "../libcli/security/security.h"
32 #include "../librpc/gen_ndr/ndr_security.h"
33 #include "../librpc/gen_ndr/ndr_open_files.h"
34 #include "../librpc/gen_ndr/idmap.h"
35 #include "../librpc/gen_ndr/ioctl.h"
36 #include "passdb/lookup_sid.h"
40 #include "source3/lib/dbwrap/dbwrap_watch.h"
41 #include "locking/leases_db.h"
42 #include "librpc/gen_ndr/ndr_leases_db.h"
43 #include "lib/util/time_basic.h"
45 extern const struct generic_mapping file_generic_mapping;
47 struct deferred_open_record {
48 struct smbXsrv_connection *xconn;
54 * Timer for async opens, needed because they don't use a watch on
55 * a locking.tdb record. This is currently only used for real async
56 * opens and just terminates smbd if the async open times out.
58 struct tevent_timer *te;
61 * For the samba kernel oplock case we use both a timeout and
62 * a watch on locking.tdb. This way in case it's smbd holding
63 * the kernel oplock we get directly notified for the retry
64 * once the kernel oplock is properly broken. Store the req
65 * here so that it can be timely discarded once the timer
68 struct tevent_req *watch_req;
71 /****************************************************************************
72 If the requester wanted DELETE_ACCESS and was rejected because
73 the file ACL didn't include DELETE_ACCESS, see if the parent ACL
75 ****************************************************************************/
77 static bool parent_override_delete(connection_struct *conn,
78 const struct smb_filename *smb_fname,
80 uint32_t rejected_mask)
82 if ((access_mask & DELETE_ACCESS) &&
83 (rejected_mask & DELETE_ACCESS) &&
84 can_delete_file_in_directory(conn,
93 /****************************************************************************
94 Check if we have open rights.
95 ****************************************************************************/
97 NTSTATUS smbd_check_access_rights(struct connection_struct *conn,
98 struct files_struct *dirfsp,
99 const struct smb_filename *smb_fname,
101 uint32_t access_mask)
103 /* Check if we have rights to open. */
105 struct security_descriptor *sd = NULL;
106 uint32_t rejected_share_access;
107 uint32_t rejected_mask = access_mask;
108 uint32_t do_not_check_mask = 0;
110 SMB_ASSERT(dirfsp == conn->cwd_fsp);
112 rejected_share_access = access_mask & ~(conn->share_access);
114 if (rejected_share_access) {
115 DEBUG(10, ("smbd_check_access_rights: rejected share access 0x%x "
117 (unsigned int)access_mask,
118 smb_fname_str_dbg(smb_fname),
119 (unsigned int)rejected_share_access ));
120 return NT_STATUS_ACCESS_DENIED;
123 if (!use_privs && get_current_uid(conn) == (uid_t)0) {
124 /* I'm sorry sir, I didn't know you were root... */
125 DEBUG(10,("smbd_check_access_rights: root override "
126 "on %s. Granting 0x%x\n",
127 smb_fname_str_dbg(smb_fname),
128 (unsigned int)access_mask ));
132 if ((access_mask & DELETE_ACCESS) && !lp_acl_check_permissions(SNUM(conn))) {
133 DEBUG(10,("smbd_check_access_rights: not checking ACL "
134 "on DELETE_ACCESS on file %s. Granting 0x%x\n",
135 smb_fname_str_dbg(smb_fname),
136 (unsigned int)access_mask ));
140 if (access_mask == DELETE_ACCESS &&
141 VALID_STAT(smb_fname->st) &&
142 S_ISLNK(smb_fname->st.st_ex_mode)) {
143 /* We can always delete a symlink. */
144 DEBUG(10,("smbd_check_access_rights: not checking ACL "
145 "on DELETE_ACCESS on symlink %s.\n",
146 smb_fname_str_dbg(smb_fname) ));
150 status = SMB_VFS_GET_NT_ACL(conn, smb_fname,
153 SECINFO_DACL), talloc_tos(), &sd);
155 if (!NT_STATUS_IS_OK(status)) {
156 DEBUG(10, ("smbd_check_access_rights: Could not get acl "
158 smb_fname_str_dbg(smb_fname),
161 if (NT_STATUS_EQUAL(status, NT_STATUS_ACCESS_DENIED)) {
169 * If we can access the path to this file, by
170 * default we have FILE_READ_ATTRIBUTES from the
171 * containing directory. See the section:
172 * "Algorithm to Check Access to an Existing File"
175 * se_file_access_check() also takes care of
176 * owner WRITE_DAC and READ_CONTROL.
178 do_not_check_mask = FILE_READ_ATTRIBUTES;
181 * Samba 3.6 and earlier granted execute access even
182 * if the ACL did not contain execute rights.
183 * Samba 4.0 is more correct and checks it.
184 * The compatibilty mode allows one to skip this check
185 * to smoothen upgrades.
187 if (lp_acl_allow_execute_always(SNUM(conn))) {
188 do_not_check_mask |= FILE_EXECUTE;
191 status = se_file_access_check(sd,
192 get_current_nttok(conn),
194 (access_mask & ~do_not_check_mask),
197 DEBUG(10,("smbd_check_access_rights: file %s requesting "
198 "0x%x returning 0x%x (%s)\n",
199 smb_fname_str_dbg(smb_fname),
200 (unsigned int)access_mask,
201 (unsigned int)rejected_mask,
202 nt_errstr(status) ));
204 if (!NT_STATUS_IS_OK(status)) {
205 if (DEBUGLEVEL >= 10) {
206 DEBUG(10,("smbd_check_access_rights: acl for %s is:\n",
207 smb_fname_str_dbg(smb_fname) ));
208 NDR_PRINT_DEBUG(security_descriptor, sd);
214 if (NT_STATUS_IS_OK(status) ||
215 !NT_STATUS_EQUAL(status, NT_STATUS_ACCESS_DENIED)) {
219 /* Here we know status == NT_STATUS_ACCESS_DENIED. */
223 if ((access_mask & FILE_WRITE_ATTRIBUTES) &&
224 (rejected_mask & FILE_WRITE_ATTRIBUTES) &&
225 !lp_store_dos_attributes(SNUM(conn)) &&
226 (lp_map_readonly(SNUM(conn)) ||
227 lp_map_archive(SNUM(conn)) ||
228 lp_map_hidden(SNUM(conn)) ||
229 lp_map_system(SNUM(conn)))) {
230 rejected_mask &= ~FILE_WRITE_ATTRIBUTES;
232 DEBUG(10,("smbd_check_access_rights: "
234 "FILE_WRITE_ATTRIBUTES "
236 smb_fname_str_dbg(smb_fname)));
239 if (parent_override_delete(conn,
243 /* Were we trying to do an open
244 * for delete and didn't get DELETE
245 * access (only) ? Check if the
246 * directory allows DELETE_CHILD.
248 * http://blogs.msdn.com/oldnewthing/archive/2004/06/04/148426.aspx
251 rejected_mask &= ~DELETE_ACCESS;
253 DEBUG(10,("smbd_check_access_rights: "
257 smb_fname_str_dbg(smb_fname)));
260 if (rejected_mask != 0) {
261 return NT_STATUS_ACCESS_DENIED;
266 NTSTATUS check_parent_access(struct connection_struct *conn,
267 struct smb_filename *smb_fname,
268 uint32_t access_mask)
271 struct security_descriptor *parent_sd = NULL;
272 uint32_t access_granted = 0;
273 struct smb_filename *parent_dir = NULL;
274 struct share_mode_lock *lck = NULL;
275 struct file_id id = {0};
277 bool delete_on_close_set;
279 TALLOC_CTX *frame = talloc_stackframe();
282 ok = parent_smb_fname(frame, smb_fname, &parent_dir, NULL);
284 status = NT_STATUS_NO_MEMORY;
288 if (get_current_uid(conn) == (uid_t)0) {
289 /* I'm sorry sir, I didn't know you were root... */
290 DEBUG(10,("check_parent_access: root override "
291 "on %s. Granting 0x%x\n",
292 smb_fname_str_dbg(smb_fname),
293 (unsigned int)access_mask ));
294 status = NT_STATUS_OK;
298 status = SMB_VFS_GET_NT_ACL(conn,
304 if (!NT_STATUS_IS_OK(status)) {
305 DEBUG(5,("check_parent_access: SMB_VFS_GET_NT_ACL failed for "
306 "%s with error %s\n",
307 smb_fname_str_dbg(parent_dir),
313 * If we can access the path to this file, by
314 * default we have FILE_READ_ATTRIBUTES from the
315 * containing directory. See the section:
316 * "Algorithm to Check Access to an Existing File"
319 * se_file_access_check() also takes care of
320 * owner WRITE_DAC and READ_CONTROL.
322 status = se_file_access_check(parent_sd,
323 get_current_nttok(conn),
325 (access_mask & ~FILE_READ_ATTRIBUTES),
327 if(!NT_STATUS_IS_OK(status)) {
328 DEBUG(5,("check_parent_access: access check "
329 "on directory %s for "
330 "path %s for mask 0x%x returned (0x%x) %s\n",
331 smb_fname_str_dbg(parent_dir),
332 smb_fname->base_name,
335 nt_errstr(status) ));
339 if (!(access_mask & (SEC_DIR_ADD_FILE | SEC_DIR_ADD_SUBDIR))) {
340 status = NT_STATUS_OK;
343 if (!lp_check_parent_directory_delete_on_close(SNUM(conn))) {
344 status = NT_STATUS_OK;
348 /* Check if the directory has delete-on-close set */
349 ret = SMB_VFS_STAT(conn, parent_dir);
351 status = map_nt_error_from_unix(errno);
355 id = SMB_VFS_FILE_ID_CREATE(conn, &parent_dir->st);
357 status = file_name_hash(conn, parent_dir->base_name, &name_hash);
358 if (!NT_STATUS_IS_OK(status)) {
362 lck = get_existing_share_mode_lock(frame, id);
364 status = NT_STATUS_OK;
368 delete_on_close_set = is_delete_on_close_set(lck, name_hash);
369 if (delete_on_close_set) {
370 status = NT_STATUS_DELETE_PENDING;
374 status = NT_STATUS_OK;
381 /****************************************************************************
382 Ensure when opening a base file for a stream open that we have permissions
383 to do so given the access mask on the base file.
384 ****************************************************************************/
386 static NTSTATUS check_base_file_access(struct connection_struct *conn,
387 struct smb_filename *smb_fname,
388 uint32_t access_mask)
392 status = smbd_calculate_access_mask(conn, smb_fname,
396 if (!NT_STATUS_IS_OK(status)) {
397 DEBUG(10, ("smbd_calculate_access_mask "
398 "on file %s returned %s\n",
399 smb_fname_str_dbg(smb_fname),
404 if (access_mask & (FILE_WRITE_DATA|FILE_APPEND_DATA)) {
406 if (!CAN_WRITE(conn)) {
407 return NT_STATUS_ACCESS_DENIED;
409 dosattrs = dos_mode(conn, smb_fname);
410 if (IS_DOS_READONLY(dosattrs)) {
411 return NT_STATUS_ACCESS_DENIED;
415 return smbd_check_access_rights(conn,
422 /****************************************************************************
423 Handle differing symlink errno's
424 ****************************************************************************/
426 static int link_errno_convert(int err)
428 #if defined(ENOTSUP) && defined(OSF1)
429 /* handle special Tru64 errno */
430 if (err == ENOTSUP) {
435 /* fix broken NetBSD errno */
440 /* fix broken FreeBSD errno */
447 static int non_widelink_open(struct connection_struct *conn,
448 const struct smb_filename *conn_rootdir_fname,
450 struct smb_filename *smb_fname,
453 unsigned int link_depth);
455 /****************************************************************************
456 Follow a symlink in userspace.
457 ****************************************************************************/
459 static int process_symlink_open(struct connection_struct *conn,
460 const struct smb_filename *conn_rootdir_fname,
462 struct smb_filename *smb_fname,
465 unsigned int link_depth)
468 char *link_target = NULL;
469 struct smb_filename target_fname = {0};
471 struct smb_filename *oldwd_fname = NULL;
472 size_t rootdir_len = 0;
473 struct smb_filename *resolved_fname = NULL;
474 char *resolved_name = NULL;
475 bool matched = false;
479 * Ensure we don't get stuck in a symlink loop.
482 if (link_depth >= 20) {
487 /* Allocate space for the link target. */
488 link_target = talloc_array(talloc_tos(), char, PATH_MAX);
489 if (link_target == NULL) {
494 /* Read the link target. */
495 link_len = SMB_VFS_READLINKAT(conn,
500 if (link_len == -1) {
504 /* Ensure it's at least null terminated. */
505 link_target[link_len] = '\0';
506 target_fname = (struct smb_filename){ .base_name = link_target };
508 /* Convert to an absolute path. */
509 resolved_fname = SMB_VFS_REALPATH(conn, talloc_tos(), &target_fname);
510 if (resolved_fname == NULL) {
513 resolved_name = resolved_fname->base_name;
516 * We know conn_rootdir starts with '/' and
517 * does not end in '/'. FIXME ! Should we
520 rootdir_len = strlen(conn_rootdir_fname->base_name);
522 matched = (strncmp(conn_rootdir_fname->base_name,
531 * Turn into a path relative to the share root.
533 if (resolved_name[rootdir_len] == '\0') {
534 /* Link to the root of the share. */
535 TALLOC_FREE(smb_fname->base_name);
536 smb_fname->base_name = talloc_strdup(smb_fname, ".");
537 } else if (resolved_name[rootdir_len] == '/') {
538 TALLOC_FREE(smb_fname->base_name);
539 smb_fname->base_name = talloc_strdup(smb_fname,
540 &resolved_name[rootdir_len+1]);
546 if (smb_fname->base_name == NULL) {
551 oldwd_fname = vfs_GetWd(talloc_tos(), conn);
552 if (oldwd_fname == NULL) {
556 /* Ensure we operate from the root of the share. */
557 if (vfs_ChDir(conn, conn_rootdir_fname) == -1) {
561 /* And do it all again.. */
562 fd = non_widelink_open(conn,
575 TALLOC_FREE(resolved_fname);
576 TALLOC_FREE(link_target);
577 if (oldwd_fname != NULL) {
578 int ret = vfs_ChDir(conn, oldwd_fname);
580 smb_panic("unable to get back to old directory\n");
582 TALLOC_FREE(oldwd_fname);
584 if (saved_errno != 0) {
590 /****************************************************************************
592 ****************************************************************************/
594 static int non_widelink_open(struct connection_struct *conn,
595 const struct smb_filename *conn_rootdir_fname,
597 struct smb_filename *smb_fname,
600 unsigned int link_depth)
604 struct smb_filename *smb_fname_rel = NULL;
606 struct smb_filename *oldwd_fname = NULL;
607 struct smb_filename *parent_dir_fname = NULL;
610 if (fsp->fsp_flags.is_directory) {
611 parent_dir_fname = cp_smb_filename(talloc_tos(), smb_fname);
612 if (parent_dir_fname == NULL) {
617 smb_fname_rel = synthetic_smb_fname(parent_dir_fname,
619 smb_fname->stream_name,
622 if (smb_fname_rel == NULL) {
627 ok = parent_smb_fname(talloc_tos(),
637 oldwd_fname = vfs_GetWd(talloc_tos(), conn);
638 if (oldwd_fname == NULL) {
642 /* Pin parent directory in place. */
643 if (vfs_ChDir(conn, parent_dir_fname) == -1) {
647 /* Ensure the relative path is below the share. */
648 status = check_reduced_name(conn, parent_dir_fname, smb_fname_rel);
649 if (!NT_STATUS_IS_OK(status)) {
650 saved_errno = map_errno_from_nt_status(status);
657 struct smb_filename *tmp_name = fsp->fsp_name;
658 fsp->fsp_name = smb_fname_rel;
659 fd = SMB_VFS_OPEN(conn, smb_fname_rel, fsp, flags, mode);
660 fsp->fsp_name = tmp_name;
664 saved_errno = link_errno_convert(errno);
666 * Trying to open a symlink to a directory with O_NOFOLLOW and
667 * O_DIRECTORY can return either of ELOOP and ENOTDIR. So
668 * ENOTDIR really means: might be a symlink, but we're not sure.
669 * In this case, we just assume there's a symlink. If we were
670 * wrong, process_symlink_open() will return EINVAL. We check
671 * this below, and fall back to returning the initial
674 * BUG: https://bugzilla.samba.org/show_bug.cgi?id=12860
676 if (saved_errno == ELOOP || saved_errno == ENOTDIR) {
677 if (fsp->posix_flags & FSP_POSIX_FLAGS_OPEN) {
678 /* Never follow symlinks on posix open. */
681 if (!lp_follow_symlinks(SNUM(conn))) {
682 /* Explicitly no symlinks. */
686 * We may have a symlink. Follow in userspace
687 * to ensure it's under the share definition.
689 fd = process_symlink_open(conn,
697 if (saved_errno == ENOTDIR &&
700 * O_DIRECTORY on neither a directory,
701 * nor a symlink. Just return
702 * saved_errno from initial open()
707 link_errno_convert(errno);
714 TALLOC_FREE(parent_dir_fname);
716 if (oldwd_fname != NULL) {
717 int ret = vfs_ChDir(conn, oldwd_fname);
719 smb_panic("unable to get back to old directory\n");
721 TALLOC_FREE(oldwd_fname);
723 if (saved_errno != 0) {
729 /****************************************************************************
730 fd support routines - attempt to do a dos_open.
731 ****************************************************************************/
733 NTSTATUS fd_open(struct connection_struct *conn,
738 struct smb_filename *smb_fname = fsp->fsp_name;
739 NTSTATUS status = NT_STATUS_OK;
740 struct smb_filename *conn_rootdir_fname = NULL;
741 const char *conn_rootdir;
745 * Never follow symlinks on a POSIX client. The
746 * client should be doing this.
749 if ((fsp->posix_flags & FSP_POSIX_FLAGS_OPEN) || !lp_follow_symlinks(SNUM(conn))) {
753 /* Ensure path is below share definition. */
754 conn_rootdir = SMB_VFS_CONNECTPATH(conn,
757 if (conn_rootdir == NULL) {
758 return NT_STATUS_NO_MEMORY;
760 conn_rootdir_fname = synthetic_smb_fname(talloc_tos(),
765 if (conn_rootdir_fname == NULL) {
766 return NT_STATUS_NO_MEMORY;
770 * Only follow symlinks within a share
773 fsp->fh->fd = non_widelink_open(conn,
780 if (fsp->fh->fd == -1) {
783 TALLOC_FREE(conn_rootdir_fname);
784 if (saved_errno != 0) {
788 if (fsp->fh->fd == -1) {
789 int posix_errno = link_errno_convert(errno);
790 status = map_nt_error_from_unix(posix_errno);
791 if (errno == EMFILE) {
792 static time_t last_warned = 0L;
794 if (time((time_t *) NULL) > last_warned) {
795 DEBUG(0,("Too many open files, unable "
796 "to open more! smbd's max "
798 lp_max_open_files()));
799 last_warned = time((time_t *) NULL);
805 DEBUG(10,("fd_open: name %s, flags = 0%o mode = 0%o, fd = %d. %s\n",
806 smb_fname_str_dbg(smb_fname), flags, (int)mode, fsp->fh->fd,
807 (fsp->fh->fd == -1) ? strerror(errno) : "" ));
812 /****************************************************************************
813 Close the file associated with a fsp.
814 ****************************************************************************/
816 NTSTATUS fd_close(files_struct *fsp)
823 if (fsp->fh->fd == -1) {
825 * Either a directory where the dptr_CloseDir() already closed
826 * the fd or a stat open.
830 if (fsp->fh->ref_count > 1) {
831 return NT_STATUS_OK; /* Shared handle. Only close last reference. */
834 ret = SMB_VFS_CLOSE(fsp);
837 return map_nt_error_from_unix(errno);
842 /****************************************************************************
843 Change the ownership of a file to that of the parent directory.
844 Do this by fd if possible.
845 ****************************************************************************/
847 void change_file_owner_to_parent(connection_struct *conn,
848 struct smb_filename *smb_fname_parent,
853 ret = SMB_VFS_STAT(conn, smb_fname_parent);
855 DEBUG(0,("change_file_owner_to_parent: failed to stat parent "
856 "directory %s. Error was %s\n",
857 smb_fname_str_dbg(smb_fname_parent),
859 TALLOC_FREE(smb_fname_parent);
863 if (smb_fname_parent->st.st_ex_uid == fsp->fsp_name->st.st_ex_uid) {
864 /* Already this uid - no need to change. */
865 DEBUG(10,("change_file_owner_to_parent: file %s "
866 "is already owned by uid %d\n",
868 (int)fsp->fsp_name->st.st_ex_uid ));
869 TALLOC_FREE(smb_fname_parent);
874 ret = SMB_VFS_FCHOWN(fsp, smb_fname_parent->st.st_ex_uid, (gid_t)-1);
877 DEBUG(0,("change_file_owner_to_parent: failed to fchown "
878 "file %s to parent directory uid %u. Error "
879 "was %s\n", fsp_str_dbg(fsp),
880 (unsigned int)smb_fname_parent->st.st_ex_uid,
883 DEBUG(10,("change_file_owner_to_parent: changed new file %s to "
884 "parent directory uid %u.\n", fsp_str_dbg(fsp),
885 (unsigned int)smb_fname_parent->st.st_ex_uid));
886 /* Ensure the uid entry is updated. */
887 fsp->fsp_name->st.st_ex_uid = smb_fname_parent->st.st_ex_uid;
891 static NTSTATUS change_dir_owner_to_parent(connection_struct *conn,
892 struct smb_filename *smb_fname_parent,
893 struct smb_filename *smb_dname,
894 SMB_STRUCT_STAT *psbuf)
896 struct smb_filename *smb_fname_cwd = NULL;
897 struct smb_filename *saved_dir_fname = NULL;
898 TALLOC_CTX *ctx = talloc_tos();
899 NTSTATUS status = NT_STATUS_OK;
902 ret = SMB_VFS_STAT(conn, smb_fname_parent);
904 status = map_nt_error_from_unix(errno);
905 DEBUG(0,("change_dir_owner_to_parent: failed to stat parent "
906 "directory %s. Error was %s\n",
907 smb_fname_str_dbg(smb_fname_parent),
912 /* We've already done an lstat into psbuf, and we know it's a
913 directory. If we can cd into the directory and the dev/ino
914 are the same then we can safely chown without races as
915 we're locking the directory in place by being in it. This
916 should work on any UNIX (thanks tridge :-). JRA.
919 saved_dir_fname = vfs_GetWd(ctx,conn);
920 if (!saved_dir_fname) {
921 status = map_nt_error_from_unix(errno);
922 DEBUG(0,("change_dir_owner_to_parent: failed to get "
923 "current working directory. Error was %s\n",
928 /* Chdir into the new path. */
929 if (vfs_ChDir(conn, smb_dname) == -1) {
930 status = map_nt_error_from_unix(errno);
931 DEBUG(0,("change_dir_owner_to_parent: failed to change "
932 "current working directory to %s. Error "
933 "was %s\n", smb_dname->base_name, strerror(errno) ));
937 smb_fname_cwd = synthetic_smb_fname(ctx, ".", NULL, NULL, 0);
938 if (smb_fname_cwd == NULL) {
939 status = NT_STATUS_NO_MEMORY;
943 ret = SMB_VFS_STAT(conn, smb_fname_cwd);
945 status = map_nt_error_from_unix(errno);
946 DEBUG(0,("change_dir_owner_to_parent: failed to stat "
947 "directory '.' (%s) Error was %s\n",
948 smb_dname->base_name, strerror(errno)));
952 /* Ensure we're pointing at the same place. */
953 if (smb_fname_cwd->st.st_ex_dev != psbuf->st_ex_dev ||
954 smb_fname_cwd->st.st_ex_ino != psbuf->st_ex_ino) {
955 DEBUG(0,("change_dir_owner_to_parent: "
956 "device/inode on directory %s changed. "
957 "Refusing to chown !\n",
958 smb_dname->base_name ));
959 status = NT_STATUS_ACCESS_DENIED;
963 if (smb_fname_parent->st.st_ex_uid == smb_fname_cwd->st.st_ex_uid) {
964 /* Already this uid - no need to change. */
965 DEBUG(10,("change_dir_owner_to_parent: directory %s "
966 "is already owned by uid %d\n",
967 smb_dname->base_name,
968 (int)smb_fname_cwd->st.st_ex_uid ));
969 status = NT_STATUS_OK;
974 ret = SMB_VFS_LCHOWN(conn,
976 smb_fname_parent->st.st_ex_uid,
980 status = map_nt_error_from_unix(errno);
981 DEBUG(10,("change_dir_owner_to_parent: failed to chown "
982 "directory %s to parent directory uid %u. "
984 smb_dname->base_name,
985 (unsigned int)smb_fname_parent->st.st_ex_uid,
988 DEBUG(10,("change_dir_owner_to_parent: changed ownership of new "
989 "directory %s to parent directory uid %u.\n",
990 smb_dname->base_name,
991 (unsigned int)smb_fname_parent->st.st_ex_uid ));
992 /* Ensure the uid entry is updated. */
993 psbuf->st_ex_uid = smb_fname_parent->st.st_ex_uid;
997 vfs_ChDir(conn, saved_dir_fname);
999 TALLOC_FREE(saved_dir_fname);
1000 TALLOC_FREE(smb_fname_cwd);
1004 /****************************************************************************
1005 Open a file - returning a guaranteed ATOMIC indication of if the
1006 file was created or not.
1007 ****************************************************************************/
1009 static NTSTATUS fd_open_atomic(struct connection_struct *conn,
1015 NTSTATUS status = NT_STATUS_UNSUCCESSFUL;
1016 NTSTATUS retry_status;
1017 bool file_existed = VALID_STAT(fsp->fsp_name->st);
1020 if (!(flags & O_CREAT)) {
1022 * We're not creating the file, just pass through.
1024 status = fd_open(conn, fsp, flags, mode);
1025 *file_created = false;
1029 if (flags & O_EXCL) {
1031 * Fail if already exists, just pass through.
1033 status = fd_open(conn, fsp, flags, mode);
1036 * Here we've opened with O_CREAT|O_EXCL. If that went
1037 * NT_STATUS_OK, we *know* we created this file.
1039 *file_created = NT_STATUS_IS_OK(status);
1045 * Now it gets tricky. We have O_CREAT, but not O_EXCL.
1046 * To know absolutely if we created the file or not,
1047 * we can never call O_CREAT without O_EXCL. So if
1048 * we think the file existed, try without O_CREAT|O_EXCL.
1049 * If we think the file didn't exist, try with
1052 * The big problem here is dangling symlinks. Opening
1053 * without O_NOFOLLOW means both bad symlink
1054 * and missing path return -1, ENOENT from open(). As POSIX
1055 * is pathname based it's not possible to tell
1056 * the difference between these two cases in a
1057 * non-racy way, so change to try only two attempts before
1060 * We don't have this problem for the O_NOFOLLOW
1061 * case as it just returns NT_STATUS_OBJECT_PATH_NOT_FOUND
1062 * mapped from the ELOOP POSIX error.
1066 curr_flags = flags & ~(O_CREAT);
1067 retry_status = NT_STATUS_OBJECT_NAME_NOT_FOUND;
1069 curr_flags = flags | O_EXCL;
1070 retry_status = NT_STATUS_OBJECT_NAME_COLLISION;
1073 status = fd_open(conn, fsp, curr_flags, mode);
1074 if (NT_STATUS_IS_OK(status)) {
1075 *file_created = !file_existed;
1076 return NT_STATUS_OK;
1078 if (NT_STATUS_EQUAL(status, retry_status)) {
1080 file_existed = !file_existed;
1082 DBG_DEBUG("File %s %s. Retry.\n",
1084 file_existed ? "existed" : "did not exist");
1087 curr_flags = flags & ~(O_CREAT);
1089 curr_flags = flags | O_EXCL;
1092 status = fd_open(conn, fsp, curr_flags, mode);
1095 *file_created = (NT_STATUS_IS_OK(status) && !file_existed);
1099 /****************************************************************************
1101 ****************************************************************************/
1103 static NTSTATUS open_file(files_struct *fsp,
1104 connection_struct *conn,
1105 struct smb_request *req,
1106 struct smb_filename *parent_dir,
1109 uint32_t access_mask, /* client requested access mask. */
1110 uint32_t open_access_mask, /* what we're actually using in the open. */
1111 bool *p_file_created)
1113 struct smb_filename *smb_fname = fsp->fsp_name;
1114 NTSTATUS status = NT_STATUS_OK;
1115 int accmode = (flags & O_ACCMODE);
1116 int local_flags = flags;
1117 bool file_existed = VALID_STAT(fsp->fsp_name->st);
1118 uint32_t need_fd_mask =
1124 WRITE_OWNER_ACCESS |
1125 SEC_FLAG_SYSTEM_SECURITY |
1126 READ_CONTROL_ACCESS;
1127 bool creating = !file_existed && (flags & O_CREAT);
1128 bool truncating = (flags & O_TRUNC);
1133 /* Check permissions */
1136 * This code was changed after seeing a client open request
1137 * containing the open mode of (DENY_WRITE/read-only) with
1138 * the 'create if not exist' bit set. The previous code
1139 * would fail to open the file read only on a read-only share
1140 * as it was checking the flags parameter directly against O_RDONLY,
1141 * this was failing as the flags parameter was set to O_RDONLY|O_CREAT.
1145 if (!CAN_WRITE(conn)) {
1146 /* It's a read-only share - fail if we wanted to write. */
1147 if(accmode != O_RDONLY || (flags & O_TRUNC) || (flags & O_APPEND)) {
1148 DEBUG(3,("Permission denied opening %s\n",
1149 smb_fname_str_dbg(smb_fname)));
1150 return NT_STATUS_ACCESS_DENIED;
1152 if (flags & O_CREAT) {
1153 /* We don't want to write - but we must make sure that
1154 O_CREAT doesn't create the file if we have write
1155 access into the directory.
1157 flags &= ~(O_CREAT|O_EXCL);
1158 local_flags &= ~(O_CREAT|O_EXCL);
1163 * This little piece of insanity is inspired by the
1164 * fact that an NT client can open a file for O_RDONLY,
1165 * but set the create disposition to FILE_EXISTS_TRUNCATE.
1166 * If the client *can* write to the file, then it expects to
1167 * truncate the file, even though it is opening for readonly.
1168 * Quicken uses this stupid trick in backup file creation...
1169 * Thanks *greatly* to "David W. Chapman Jr." <dwcjr@inethouston.net>
1170 * for helping track this one down. It didn't bite us in 2.0.x
1171 * as we always opened files read-write in that release. JRA.
1174 if ((accmode == O_RDONLY) && ((flags & O_TRUNC) == O_TRUNC)) {
1175 DEBUG(10,("open_file: truncate requested on read-only open "
1176 "for file %s\n", smb_fname_str_dbg(smb_fname)));
1177 local_flags = (flags & ~O_ACCMODE)|O_RDWR;
1180 if ((open_access_mask & need_fd_mask) || creating || truncating) {
1184 #if defined(O_NONBLOCK) && defined(S_ISFIFO)
1186 * We would block on opening a FIFO with no one else on the
1187 * other end. Do what we used to do and add O_NONBLOCK to the
1191 if (file_existed && S_ISFIFO(smb_fname->st.st_ex_mode)) {
1192 local_flags &= ~O_TRUNC; /* Can't truncate a FIFO. */
1193 local_flags |= O_NONBLOCK;
1198 /* Don't create files with Microsoft wildcard characters. */
1199 if (fsp->base_fsp) {
1201 * wildcard characters are allowed in stream names
1202 * only test the basefilename
1204 wild = fsp->base_fsp->fsp_name->base_name;
1206 wild = smb_fname->base_name;
1208 if ((local_flags & O_CREAT) && !file_existed &&
1209 !(fsp->posix_flags & FSP_POSIX_FLAGS_PATHNAMES) &&
1210 ms_has_wild(wild)) {
1211 return NT_STATUS_OBJECT_NAME_INVALID;
1214 /* Can we access this file ? */
1215 if (!fsp->base_fsp) {
1216 /* Only do this check on non-stream open. */
1218 status = smbd_check_access_rights(conn,
1224 if (!NT_STATUS_IS_OK(status)) {
1225 DEBUG(10, ("open_file: "
1226 "smbd_check_access_rights "
1227 "on file %s returned %s\n",
1228 smb_fname_str_dbg(smb_fname),
1229 nt_errstr(status)));
1232 if (!NT_STATUS_IS_OK(status) &&
1233 !NT_STATUS_EQUAL(status,
1234 NT_STATUS_OBJECT_NAME_NOT_FOUND))
1239 if (NT_STATUS_EQUAL(status,
1240 NT_STATUS_OBJECT_NAME_NOT_FOUND))
1242 DEBUG(10, ("open_file: "
1243 "file %s vanished since we "
1244 "checked for existence.\n",
1245 smb_fname_str_dbg(smb_fname)));
1246 file_existed = false;
1247 SET_STAT_INVALID(fsp->fsp_name->st);
1251 if (!file_existed) {
1252 if (!(local_flags & O_CREAT)) {
1253 /* File didn't exist and no O_CREAT. */
1254 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
1257 status = check_parent_access(conn,
1260 if (!NT_STATUS_IS_OK(status)) {
1261 DEBUG(10, ("open_file: "
1262 "check_parent_access on "
1263 "file %s returned %s\n",
1264 smb_fname_str_dbg(smb_fname),
1265 nt_errstr(status) ));
1272 * Actually do the open - if O_TRUNC is needed handle it
1273 * below under the share mode lock.
1275 status = fd_open_atomic(conn, fsp, local_flags & ~O_TRUNC,
1276 unx_mode, p_file_created);
1277 if (!NT_STATUS_IS_OK(status)) {
1278 DEBUG(3,("Error opening file %s (%s) (local_flags=%d) "
1279 "(flags=%d)\n", smb_fname_str_dbg(smb_fname),
1280 nt_errstr(status),local_flags,flags));
1284 if (local_flags & O_NONBLOCK) {
1286 * GPFS can return ETIMEDOUT for pread on
1287 * nonblocking file descriptors when files
1288 * migrated to tape need to be recalled. I
1289 * could imagine this happens elsewhere
1290 * too. With blocking file descriptors this
1293 ret = vfs_set_blocking(fsp, true);
1295 status = map_nt_error_from_unix(errno);
1296 DBG_WARNING("Could not set fd to blocking: "
1297 "%s\n", strerror(errno));
1303 ret = SMB_VFS_FSTAT(fsp, &smb_fname->st);
1305 /* If we have an fd, this stat should succeed. */
1306 DEBUG(0,("Error doing fstat on open file %s "
1308 smb_fname_str_dbg(smb_fname),
1310 status = map_nt_error_from_unix(errno);
1315 if (*p_file_created) {
1316 /* We created this file. */
1318 bool need_re_stat = false;
1319 /* Do all inheritance work after we've
1320 done a successful fstat call and filled
1321 in the stat struct in fsp->fsp_name. */
1323 /* Inherit the ACL if required */
1324 if (lp_inherit_permissions(SNUM(conn))) {
1325 inherit_access_posix_acl(conn,
1329 need_re_stat = true;
1332 /* Change the owner if required. */
1333 if (lp_inherit_owner(SNUM(conn)) != INHERIT_OWNER_NO) {
1334 change_file_owner_to_parent(conn,
1337 need_re_stat = true;
1341 ret = SMB_VFS_FSTAT(fsp, &smb_fname->st);
1342 /* If we have an fd, this stat should succeed. */
1344 DEBUG(0,("Error doing fstat on open file %s "
1346 smb_fname_str_dbg(smb_fname),
1351 notify_fname(conn, NOTIFY_ACTION_ADDED,
1352 FILE_NOTIFY_CHANGE_FILE_NAME,
1353 smb_fname->base_name);
1356 fsp->fh->fd = -1; /* What we used to call a stat open. */
1357 if (!file_existed) {
1358 /* File must exist for a stat open. */
1359 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
1362 status = smbd_check_access_rights(conn,
1368 if (NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND) &&
1369 (fsp->posix_flags & FSP_POSIX_FLAGS_OPEN) &&
1370 S_ISLNK(smb_fname->st.st_ex_mode)) {
1371 /* This is a POSIX stat open for delete
1372 * or rename on a symlink that points
1373 * nowhere. Allow. */
1374 DEBUG(10,("open_file: allowing POSIX "
1375 "open on bad symlink %s\n",
1376 smb_fname_str_dbg(smb_fname)));
1377 status = NT_STATUS_OK;
1380 if (!NT_STATUS_IS_OK(status)) {
1381 DEBUG(10,("open_file: "
1382 "smbd_check_access_rights on file "
1384 smb_fname_str_dbg(smb_fname),
1385 nt_errstr(status) ));
1391 * POSIX allows read-only opens of directories. We don't
1392 * want to do this (we use a different code path for this)
1393 * so catch a directory open and return an EISDIR. JRA.
1396 if(S_ISDIR(smb_fname->st.st_ex_mode)) {
1399 return NT_STATUS_FILE_IS_A_DIRECTORY;
1402 fsp->file_id = vfs_file_id_from_sbuf(conn, &smb_fname->st);
1403 fsp->vuid = req ? req->vuid : UID_FIELD_INVALID;
1404 fsp->file_pid = req ? req->smbpid : 0;
1405 fsp->fsp_flags.can_lock = true;
1406 fsp->fsp_flags.can_read = ((access_mask & FILE_READ_DATA) != 0);
1407 fsp->fsp_flags.can_write =
1409 ((access_mask & (FILE_WRITE_DATA | FILE_APPEND_DATA)) != 0);
1410 fsp->print_file = NULL;
1411 fsp->fsp_flags.modified = false;
1412 fsp->sent_oplock_break = NO_BREAK_SENT;
1413 fsp->fsp_flags.is_directory = false;
1414 if (conn->aio_write_behind_list &&
1415 is_in_path(smb_fname->base_name, conn->aio_write_behind_list,
1416 conn->case_sensitive)) {
1417 fsp->fsp_flags.aio_write_behind = true;
1420 DEBUG(2,("%s opened file %s read=%s write=%s (numopen=%d)\n",
1421 conn->session_info->unix_info->unix_name,
1422 smb_fname_str_dbg(smb_fname),
1423 BOOLSTR(fsp->fsp_flags.can_read),
1424 BOOLSTR(fsp->fsp_flags.can_write),
1425 conn->num_files_open));
1428 return NT_STATUS_OK;
1431 static bool mask_conflict(
1432 uint32_t new_access,
1433 uint32_t existing_access,
1434 uint32_t access_mask,
1435 uint32_t new_sharemode,
1436 uint32_t existing_sharemode,
1437 uint32_t sharemode_mask)
1439 bool want_access = (new_access & access_mask);
1440 bool allow_existing = (existing_sharemode & sharemode_mask);
1441 bool have_access = (existing_access & access_mask);
1442 bool allow_new = (new_sharemode & sharemode_mask);
1444 if (want_access && !allow_existing) {
1445 DBG_DEBUG("Access request 0x%"PRIx32"/0x%"PRIx32" conflicts "
1446 "with existing sharemode 0x%"PRIx32"/0x%"PRIx32"\n",
1453 if (have_access && !allow_new) {
1454 DBG_DEBUG("Sharemode request 0x%"PRIx32"/0x%"PRIx32" conflicts "
1455 "with existing access 0x%"PRIx32"/0x%"PRIx32"\n",
1465 /****************************************************************************
1466 Check if we can open a file with a share mode.
1467 Returns True if conflict, False if not.
1468 ****************************************************************************/
1470 static bool share_conflict(uint32_t e_access_mask,
1471 uint32_t e_share_access,
1472 uint32_t access_mask,
1473 uint32_t share_access)
1475 const uint32_t conflicting_access =
1483 DBG_DEBUG("existing access_mask = 0x%"PRIx32", "
1484 "existing share access = 0x%"PRIx32", "
1485 "access_mask = 0x%"PRIx32", "
1486 "share_access = 0x%"PRIx32"\n",
1492 if ((e_access_mask & conflicting_access) == 0) {
1493 DBG_DEBUG("No conflict due to "
1494 "existing access_mask = 0x%"PRIx32"\n",
1498 if ((access_mask & conflicting_access) == 0) {
1499 DBG_DEBUG("No conflict due to access_mask = 0x%"PRIx32"\n",
1504 conflict = mask_conflict(
1505 access_mask, e_access_mask, FILE_WRITE_DATA | FILE_APPEND_DATA,
1506 share_access, e_share_access, FILE_SHARE_WRITE);
1507 conflict |= mask_conflict(
1508 access_mask, e_access_mask, FILE_READ_DATA | FILE_EXECUTE,
1509 share_access, e_share_access, FILE_SHARE_READ);
1510 conflict |= mask_conflict(
1511 access_mask, e_access_mask, DELETE_ACCESS,
1512 share_access, e_share_access, FILE_SHARE_DELETE);
1514 DBG_DEBUG("conflict=%s\n", conflict ? "true" : "false");
1518 #if defined(DEVELOPER)
1520 struct validate_my_share_entries_state {
1521 struct smbd_server_connection *sconn;
1523 struct server_id self;
1526 static bool validate_my_share_entries_fn(
1527 struct share_mode_entry *e,
1531 struct validate_my_share_entries_state *state = private_data;
1534 if (!server_id_equal(&state->self, &e->pid)) {
1538 if (e->op_mid == 0) {
1539 /* INTERNAL_OPEN_ONLY */
1543 fsp = file_find_dif(state->sconn, state->fid, e->share_file_id);
1545 DBG_ERR("PANIC : %s\n",
1546 share_mode_str(talloc_tos(), 0, &state->fid, e));
1547 smb_panic("validate_my_share_entries: Cannot match a "
1548 "share entry with an open file\n");
1551 if (((uint16_t)fsp->oplock_type) != e->op_type) {
1560 DBG_ERR("validate_my_share_entries: PANIC : %s\n",
1561 share_mode_str(talloc_tos(), 0, &state->fid, e));
1562 str = talloc_asprintf(talloc_tos(),
1563 "validate_my_share_entries: "
1564 "file %s, oplock_type = 0x%x, op_type = 0x%x\n",
1565 fsp->fsp_name->base_name,
1566 (unsigned int)fsp->oplock_type,
1567 (unsigned int)e->op_type);
1576 * Allowed access mask for stat opens relevant to oplocks
1578 bool is_oplock_stat_open(uint32_t access_mask)
1580 const uint32_t stat_open_bits =
1581 (SYNCHRONIZE_ACCESS|
1582 FILE_READ_ATTRIBUTES|
1583 FILE_WRITE_ATTRIBUTES);
1585 return (((access_mask & stat_open_bits) != 0) &&
1586 ((access_mask & ~stat_open_bits) == 0));
1590 * Allowed access mask for stat opens relevant to leases
1592 bool is_lease_stat_open(uint32_t access_mask)
1594 const uint32_t stat_open_bits =
1595 (SYNCHRONIZE_ACCESS|
1596 FILE_READ_ATTRIBUTES|
1597 FILE_WRITE_ATTRIBUTES|
1598 READ_CONTROL_ACCESS);
1600 return (((access_mask & stat_open_bits) != 0) &&
1601 ((access_mask & ~stat_open_bits) == 0));
1604 struct has_delete_on_close_state {
1608 static bool has_delete_on_close_fn(
1609 struct share_mode_entry *e,
1613 struct has_delete_on_close_state *state = private_data;
1614 state->ret = !share_entry_stale_pid(e);
1618 static bool has_delete_on_close(struct share_mode_lock *lck,
1621 struct has_delete_on_close_state state = { .ret = false };
1624 if (!is_delete_on_close_set(lck, name_hash)) {
1628 ok= share_mode_forall_entries(lck, has_delete_on_close_fn, &state);
1630 DBG_DEBUG("share_mode_forall_entries failed\n");
1636 static void share_mode_flags_get(
1638 uint32_t *access_mask,
1639 uint32_t *share_mode,
1640 uint32_t *lease_type)
1642 if (access_mask != NULL) {
1644 ((flags & SHARE_MODE_ACCESS_READ) ?
1645 FILE_READ_DATA : 0) |
1646 ((flags & SHARE_MODE_ACCESS_WRITE) ?
1647 FILE_WRITE_DATA : 0) |
1648 ((flags & SHARE_MODE_ACCESS_DELETE) ?
1651 if (share_mode != NULL) {
1653 ((flags & SHARE_MODE_SHARE_READ) ?
1654 FILE_SHARE_READ : 0) |
1655 ((flags & SHARE_MODE_SHARE_WRITE) ?
1656 FILE_SHARE_WRITE : 0) |
1657 ((flags & SHARE_MODE_SHARE_DELETE) ?
1658 FILE_SHARE_DELETE : 0);
1660 if (lease_type != NULL) {
1662 ((flags & SHARE_MODE_LEASE_READ) ?
1663 SMB2_LEASE_READ : 0) |
1664 ((flags & SHARE_MODE_LEASE_WRITE) ?
1665 SMB2_LEASE_WRITE : 0) |
1666 ((flags & SHARE_MODE_LEASE_HANDLE) ?
1667 SMB2_LEASE_HANDLE : 0);
1671 static uint16_t share_mode_flags_set(
1673 uint32_t access_mask,
1674 uint32_t share_mode,
1675 uint32_t lease_type)
1677 if (access_mask != UINT32_MAX) {
1678 flags &= ~(SHARE_MODE_ACCESS_READ|
1679 SHARE_MODE_ACCESS_WRITE|
1680 SHARE_MODE_ACCESS_DELETE);
1681 flags |= (access_mask & (FILE_READ_DATA | FILE_EXECUTE)) ?
1682 SHARE_MODE_ACCESS_READ : 0;
1683 flags |= (access_mask & (FILE_WRITE_DATA | FILE_APPEND_DATA)) ?
1684 SHARE_MODE_ACCESS_WRITE : 0;
1685 flags |= (access_mask & (DELETE_ACCESS)) ?
1686 SHARE_MODE_ACCESS_DELETE : 0;
1688 if (share_mode != UINT32_MAX) {
1689 flags &= ~(SHARE_MODE_SHARE_READ|
1690 SHARE_MODE_SHARE_WRITE|
1691 SHARE_MODE_SHARE_DELETE);
1692 flags |= (share_mode & FILE_SHARE_READ) ?
1693 SHARE_MODE_SHARE_READ : 0;
1694 flags |= (share_mode & FILE_SHARE_WRITE) ?
1695 SHARE_MODE_SHARE_WRITE : 0;
1696 flags |= (share_mode & FILE_SHARE_DELETE) ?
1697 SHARE_MODE_SHARE_DELETE : 0;
1699 if (lease_type != UINT32_MAX) {
1700 flags &= ~(SHARE_MODE_LEASE_READ|
1701 SHARE_MODE_LEASE_WRITE|
1702 SHARE_MODE_LEASE_HANDLE);
1703 flags |= (lease_type & SMB2_LEASE_READ) ?
1704 SHARE_MODE_LEASE_READ : 0;
1705 flags |= (lease_type & SMB2_LEASE_WRITE) ?
1706 SHARE_MODE_LEASE_WRITE : 0;
1707 flags |= (lease_type & SMB2_LEASE_HANDLE) ?
1708 SHARE_MODE_LEASE_HANDLE : 0;
1714 static uint16_t share_mode_flags_restrict(
1716 uint32_t access_mask,
1717 uint32_t share_mode,
1718 uint32_t lease_type)
1720 uint32_t existing_access_mask, existing_share_mode;
1721 uint32_t existing_lease_type;
1724 share_mode_flags_get(
1726 &existing_access_mask,
1727 &existing_share_mode,
1728 &existing_lease_type);
1730 existing_access_mask |= access_mask;
1731 existing_share_mode &= share_mode;
1732 existing_lease_type |= lease_type;
1734 ret = share_mode_flags_set(
1736 existing_access_mask,
1737 existing_share_mode,
1738 existing_lease_type);
1742 /****************************************************************************
1743 Deal with share modes
1744 Invariant: Share mode must be locked on entry and exit.
1745 Returns -1 on error, or number of share modes on success (may be zero).
1746 ****************************************************************************/
1748 struct open_mode_check_state {
1750 uint32_t access_mask;
1751 uint32_t share_access;
1752 uint32_t lease_type;
1755 static bool open_mode_check_fn(
1756 struct share_mode_entry *e,
1760 struct open_mode_check_state *state = private_data;
1761 bool disconnected, stale;
1762 uint32_t access_mask, share_access, lease_type;
1764 disconnected = server_id_is_disconnected(&e->pid);
1769 access_mask = state->access_mask | e->access_mask;
1770 share_access = state->share_access & e->share_access;
1771 lease_type = state->lease_type | get_lease_type(e, state->fid);
1773 if ((access_mask == state->access_mask) &&
1774 (share_access == state->share_access) &&
1775 (lease_type == state->lease_type)) {
1779 stale = share_entry_stale_pid(e);
1784 state->access_mask = access_mask;
1785 state->share_access = share_access;
1786 state->lease_type = lease_type;
1791 static NTSTATUS open_mode_check(connection_struct *conn,
1792 struct share_mode_lock *lck,
1793 uint32_t access_mask,
1794 uint32_t share_access)
1796 struct share_mode_data *d = lck->data;
1797 struct open_mode_check_state state;
1799 bool ok, conflict, have_share_entries;
1801 if (is_oplock_stat_open(access_mask)) {
1802 /* Stat open that doesn't trigger oplock breaks or share mode
1803 * checks... ! JRA. */
1804 return NT_STATUS_OK;
1808 * Check if the share modes will give us access.
1811 #if defined(DEVELOPER)
1813 struct validate_my_share_entries_state validate_state = {
1814 .sconn = conn->sconn,
1816 .self = messaging_server_id(conn->sconn->msg_ctx),
1818 ok = share_mode_forall_entries(
1819 lck, validate_my_share_entries_fn, &validate_state);
1824 have_share_entries = share_mode_have_entries(lck);
1825 if (!have_share_entries) {
1827 * This is a fresh share mode lock where no conflicts
1830 return NT_STATUS_OK;
1833 share_mode_flags_get(
1834 d->flags, &state.access_mask, &state.share_access, NULL);
1836 conflict = share_conflict(
1842 DBG_DEBUG("No conflict due to share_mode_flags access\n");
1843 return NT_STATUS_OK;
1846 state = (struct open_mode_check_state) {
1848 .share_access = (FILE_SHARE_READ|
1854 * Walk the share mode array to recalculate d->flags
1857 ok = share_mode_forall_entries(lck, open_mode_check_fn, &state);
1859 DBG_DEBUG("share_mode_forall_entries failed\n");
1860 return NT_STATUS_INTERNAL_ERROR;
1863 new_flags = share_mode_flags_set(
1864 0, state.access_mask, state.share_access, state.lease_type);
1865 if (new_flags == d->flags) {
1867 * We only end up here if we had a sharing violation
1868 * from d->flags and have recalculated it.
1870 return NT_STATUS_SHARING_VIOLATION;
1873 d->flags = new_flags;
1876 conflict = share_conflict(
1882 DBG_DEBUG("No conflict due to share_mode_flags access\n");
1883 return NT_STATUS_OK;
1886 return NT_STATUS_SHARING_VIOLATION;
1890 * Send a break message to the oplock holder and delay the open for
1894 NTSTATUS send_break_message(struct messaging_context *msg_ctx,
1895 const struct file_id *id,
1896 const struct share_mode_entry *exclusive,
1899 struct oplock_break_message msg = {
1901 .share_file_id = exclusive->share_file_id,
1902 .break_to = break_to,
1904 enum ndr_err_code ndr_err;
1909 struct server_id_buf buf;
1910 DBG_DEBUG("Sending break message to %s\n",
1911 server_id_str_buf(exclusive->pid, &buf));
1912 NDR_PRINT_DEBUG(oplock_break_message, &msg);
1915 ndr_err = ndr_push_struct_blob(
1919 (ndr_push_flags_fn_t)ndr_push_oplock_break_message);
1920 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
1921 DBG_WARNING("ndr_push_oplock_break_message failed: %s\n",
1922 ndr_errstr(ndr_err));
1923 return ndr_map_error2ntstatus(ndr_err);
1926 status = messaging_send(
1927 msg_ctx, exclusive->pid, MSG_SMB_BREAK_REQUEST, &blob);
1928 TALLOC_FREE(blob.data);
1929 if (!NT_STATUS_IS_OK(status)) {
1930 DEBUG(3, ("Could not send oplock break message: %s\n",
1931 nt_errstr(status)));
1937 struct validate_oplock_types_state {
1943 uint32_t num_non_stat_opens;
1946 static bool validate_oplock_types_fn(
1947 struct share_mode_entry *e,
1951 struct validate_oplock_types_state *state = private_data;
1953 if (e->op_mid == 0) {
1954 /* INTERNAL_OPEN_ONLY */
1958 if (e->op_type == NO_OPLOCK && is_oplock_stat_open(e->access_mask)) {
1960 * We ignore stat opens in the table - they always
1961 * have NO_OPLOCK and never get or cause breaks. JRA.
1966 state->num_non_stat_opens += 1;
1968 if (BATCH_OPLOCK_TYPE(e->op_type)) {
1969 /* batch - can only be one. */
1970 if (share_entry_stale_pid(e)) {
1971 DBG_DEBUG("Found stale batch oplock\n");
1974 if (state->ex_or_batch ||
1978 DBG_ERR("Bad batch oplock entry\n");
1979 state->valid = false;
1982 state->batch = true;
1985 if (EXCLUSIVE_OPLOCK_TYPE(e->op_type)) {
1986 if (share_entry_stale_pid(e)) {
1987 DBG_DEBUG("Found stale duplicate oplock\n");
1990 /* Exclusive or batch - can only be one. */
1991 if (state->ex_or_batch ||
1994 DBG_ERR("Bad exclusive or batch oplock entry\n");
1995 state->valid = false;
1998 state->ex_or_batch = true;
2001 if (LEVEL_II_OPLOCK_TYPE(e->op_type)) {
2002 if (state->batch || state->ex_or_batch) {
2003 if (share_entry_stale_pid(e)) {
2004 DBG_DEBUG("Found stale LevelII oplock\n");
2007 DBG_DEBUG("Bad levelII oplock entry\n");
2008 state->valid = false;
2011 state->level2 = true;
2014 if (e->op_type == NO_OPLOCK) {
2015 if (state->batch || state->ex_or_batch) {
2016 if (share_entry_stale_pid(e)) {
2017 DBG_DEBUG("Found stale NO_OPLOCK entry\n");
2020 DBG_ERR("Bad no oplock entry\n");
2021 state->valid = false;
2024 state->no_oplock = true;
2031 * Do internal consistency checks on the share mode for a file.
2034 static bool validate_oplock_types(struct share_mode_lock *lck)
2036 struct validate_oplock_types_state state = { .valid = true };
2039 ok = share_mode_forall_entries(lck, validate_oplock_types_fn, &state);
2041 DBG_DEBUG("share_mode_forall_entries failed\n");
2045 DBG_DEBUG("Got invalid oplock configuration\n");
2049 if ((state.batch || state.ex_or_batch) &&
2050 (state.num_non_stat_opens != 1)) {
2051 DBG_WARNING("got batch (%d) or ex (%d) non-exclusively "
2054 (int)state.ex_or_batch,
2055 state.num_non_stat_opens);
2062 static bool is_same_lease(const files_struct *fsp,
2063 const struct share_mode_entry *e,
2064 const struct smb2_lease *lease)
2066 if (e->op_type != LEASE_OPLOCK) {
2069 if (lease == NULL) {
2073 return smb2_lease_equal(fsp_client_guid(fsp),
2079 static bool file_has_brlocks(files_struct *fsp)
2081 struct byte_range_lock *br_lck;
2083 br_lck = brl_get_locks_readonly(fsp);
2087 return (brl_num_locks(br_lck) > 0);
2090 struct fsp_lease *find_fsp_lease(struct files_struct *new_fsp,
2091 const struct smb2_lease_key *key,
2092 uint32_t current_state,
2093 uint16_t lease_version,
2094 uint16_t lease_epoch)
2096 struct files_struct *fsp;
2099 * TODO: Measure how expensive this loop is with thousands of open
2103 for (fsp = file_find_di_first(new_fsp->conn->sconn, new_fsp->file_id);
2105 fsp = file_find_di_next(fsp)) {
2107 if (fsp == new_fsp) {
2110 if (fsp->oplock_type != LEASE_OPLOCK) {
2113 if (smb2_lease_key_equal(&fsp->lease->lease.lease_key, key)) {
2114 fsp->lease->ref_count += 1;
2119 /* Not found - must be leased in another smbd. */
2120 new_fsp->lease = talloc_zero(new_fsp->conn->sconn, struct fsp_lease);
2121 if (new_fsp->lease == NULL) {
2124 new_fsp->lease->ref_count = 1;
2125 new_fsp->lease->sconn = new_fsp->conn->sconn;
2126 new_fsp->lease->lease.lease_key = *key;
2127 new_fsp->lease->lease.lease_state = current_state;
2129 * We internally treat all leases as V2 and update
2130 * the epoch, but when sending breaks it matters if
2131 * the requesting lease was v1 or v2.
2133 new_fsp->lease->lease.lease_version = lease_version;
2134 new_fsp->lease->lease.lease_epoch = lease_epoch;
2135 return new_fsp->lease;
2138 static NTSTATUS try_lease_upgrade(struct files_struct *fsp,
2139 struct share_mode_lock *lck,
2140 const struct GUID *client_guid,
2141 const struct smb2_lease *lease,
2145 uint32_t current_state, breaking_to_requested, breaking_to_required;
2147 uint16_t lease_version, epoch;
2148 uint32_t existing, requested;
2151 status = leases_db_get(
2157 &breaking_to_requested,
2158 &breaking_to_required,
2161 if (!NT_STATUS_IS_OK(status)) {
2165 fsp->lease = find_fsp_lease(
2171 if (fsp->lease == NULL) {
2172 DEBUG(1, ("Did not find existing lease for file %s\n",
2174 return NT_STATUS_NO_MEMORY;
2178 * Upgrade only if the requested lease is a strict upgrade.
2180 existing = current_state;
2181 requested = lease->lease_state;
2184 * Tricky: This test makes sure that "requested" is a
2185 * strict bitwise superset of "existing".
2187 do_upgrade = ((existing & requested) == existing);
2190 * Upgrade only if there's a change.
2192 do_upgrade &= (granted != existing);
2195 * Upgrade only if other leases don't prevent what was asked
2198 do_upgrade &= (granted == requested);
2201 * only upgrade if we are not in breaking state
2203 do_upgrade &= !breaking;
2205 DEBUG(10, ("existing=%"PRIu32", requested=%"PRIu32", "
2206 "granted=%"PRIu32", do_upgrade=%d\n",
2207 existing, requested, granted, (int)do_upgrade));
2210 NTSTATUS set_status;
2212 current_state = granted;
2215 set_status = leases_db_set(
2220 breaking_to_requested,
2221 breaking_to_required,
2225 if (!NT_STATUS_IS_OK(set_status)) {
2226 DBG_DEBUG("leases_db_set failed: %s\n",
2227 nt_errstr(set_status));
2232 fsp_lease_update(fsp);
2234 return NT_STATUS_OK;
2237 static NTSTATUS grant_new_fsp_lease(struct files_struct *fsp,
2238 struct share_mode_lock *lck,
2239 const struct GUID *client_guid,
2240 const struct smb2_lease *lease,
2243 struct share_mode_data *d = lck->data;
2246 fsp->lease = talloc_zero(fsp->conn->sconn, struct fsp_lease);
2247 if (fsp->lease == NULL) {
2248 return NT_STATUS_INSUFFICIENT_RESOURCES;
2250 fsp->lease->ref_count = 1;
2251 fsp->lease->sconn = fsp->conn->sconn;
2252 fsp->lease->lease.lease_version = lease->lease_version;
2253 fsp->lease->lease.lease_key = lease->lease_key;
2254 fsp->lease->lease.lease_state = granted;
2255 fsp->lease->lease.lease_epoch = lease->lease_epoch + 1;
2257 status = leases_db_add(client_guid,
2260 fsp->lease->lease.lease_state,
2261 fsp->lease->lease.lease_version,
2262 fsp->lease->lease.lease_epoch,
2263 fsp->conn->connectpath,
2264 fsp->fsp_name->base_name,
2265 fsp->fsp_name->stream_name);
2266 if (!NT_STATUS_IS_OK(status)) {
2267 DEBUG(10, ("%s: leases_db_add failed: %s\n", __func__,
2268 nt_errstr(status)));
2269 TALLOC_FREE(fsp->lease);
2270 return NT_STATUS_INSUFFICIENT_RESOURCES;
2275 return NT_STATUS_OK;
2278 static NTSTATUS grant_fsp_lease(struct files_struct *fsp,
2279 struct share_mode_lock *lck,
2280 const struct smb2_lease *lease,
2283 const struct GUID *client_guid = fsp_client_guid(fsp);
2286 status = try_lease_upgrade(fsp, lck, client_guid, lease, granted);
2288 if (NT_STATUS_EQUAL(status, NT_STATUS_NOT_FOUND)) {
2289 status = grant_new_fsp_lease(
2290 fsp, lck, client_guid, lease, granted);
2296 static int map_lease_type_to_oplock(uint32_t lease_type)
2298 int result = NO_OPLOCK;
2300 switch (lease_type) {
2301 case SMB2_LEASE_READ|SMB2_LEASE_WRITE|SMB2_LEASE_HANDLE:
2302 result = BATCH_OPLOCK|EXCLUSIVE_OPLOCK;
2304 case SMB2_LEASE_READ|SMB2_LEASE_WRITE:
2305 result = EXCLUSIVE_OPLOCK;
2307 case SMB2_LEASE_READ|SMB2_LEASE_HANDLE:
2308 case SMB2_LEASE_READ:
2309 result = LEVEL_II_OPLOCK;
2316 struct delay_for_oplock_state {
2317 struct files_struct *fsp;
2318 const struct smb2_lease *lease;
2319 bool will_overwrite;
2320 uint32_t delay_mask;
2321 bool first_open_attempt;
2322 bool got_handle_lease;
2324 bool have_other_lease;
2328 static bool delay_for_oplock_fn(
2329 struct share_mode_entry *e,
2333 struct delay_for_oplock_state *state = private_data;
2334 struct files_struct *fsp = state->fsp;
2335 const struct smb2_lease *lease = state->lease;
2336 bool e_is_lease = (e->op_type == LEASE_OPLOCK);
2337 uint32_t e_lease_type = get_lease_type(e, fsp->file_id);
2339 bool lease_is_breaking = false;
2344 if (lease != NULL) {
2345 bool our_lease = is_same_lease(fsp, e, lease);
2347 DBG_DEBUG("Ignoring our own lease\n");
2352 status = leases_db_get(
2356 NULL, /* current_state */
2358 NULL, /* breaking_to_requested */
2359 NULL, /* breaking_to_required */
2360 NULL, /* lease_version */
2362 SMB_ASSERT(NT_STATUS_IS_OK(status));
2365 if (!state->got_handle_lease &&
2366 ((e_lease_type & SMB2_LEASE_HANDLE) != 0) &&
2367 !share_entry_stale_pid(e)) {
2368 state->got_handle_lease = true;
2371 if (!state->got_oplock &&
2372 (e->op_type != LEASE_OPLOCK) &&
2373 !share_entry_stale_pid(e)) {
2374 state->got_oplock = true;
2377 if (!state->have_other_lease &&
2378 !is_same_lease(fsp, e, lease) &&
2379 !share_entry_stale_pid(e)) {
2380 state->have_other_lease = true;
2383 if (e_is_lease && is_lease_stat_open(fsp->access_mask)) {
2387 break_to = e_lease_type & ~state->delay_mask;
2389 if (state->will_overwrite) {
2390 break_to &= ~(SMB2_LEASE_HANDLE|SMB2_LEASE_READ);
2393 DBG_DEBUG("e_lease_type %u, will_overwrite: %u\n",
2394 (unsigned)e_lease_type,
2395 (unsigned)state->will_overwrite);
2397 if ((e_lease_type & ~break_to) == 0) {
2398 if (lease_is_breaking) {
2399 state->delay = true;
2404 if (share_entry_stale_pid(e)) {
2408 if (state->will_overwrite) {
2410 * If we break anyway break to NONE directly.
2411 * Otherwise vfs_set_filelen() will trigger the
2414 break_to &= ~(SMB2_LEASE_READ|SMB2_LEASE_WRITE);
2419 * Oplocks only support breaking to R or NONE.
2421 break_to &= ~(SMB2_LEASE_HANDLE|SMB2_LEASE_WRITE);
2424 DBG_DEBUG("breaking from %d to %d\n",
2428 fsp->conn->sconn->msg_ctx, &fsp->file_id, e, break_to);
2429 if (e_lease_type & state->delay_mask) {
2430 state->delay = true;
2432 if (lease_is_breaking && !state->first_open_attempt) {
2433 state->delay = true;
2439 static NTSTATUS delay_for_oplock(files_struct *fsp,
2441 const struct smb2_lease *lease,
2442 struct share_mode_lock *lck,
2443 bool have_sharing_violation,
2444 uint32_t create_disposition,
2445 bool first_open_attempt)
2447 struct delay_for_oplock_state state = {
2450 .first_open_attempt = first_open_attempt,
2456 if (is_oplock_stat_open(fsp->access_mask)) {
2460 state.delay_mask = have_sharing_violation ?
2461 SMB2_LEASE_HANDLE : SMB2_LEASE_WRITE;
2463 switch (create_disposition) {
2464 case FILE_SUPERSEDE:
2465 case FILE_OVERWRITE:
2466 case FILE_OVERWRITE_IF:
2467 state.will_overwrite = true;
2470 state.will_overwrite = false;
2474 ok = share_mode_forall_entries(lck, delay_for_oplock_fn, &state);
2476 return NT_STATUS_INTERNAL_ERROR;
2480 return NT_STATUS_RETRY;
2484 if (have_sharing_violation) {
2485 return NT_STATUS_SHARING_VIOLATION;
2488 if (oplock_request == LEASE_OPLOCK) {
2489 if (lease == NULL) {
2491 * The SMB2 layer should have checked this
2493 return NT_STATUS_INTERNAL_ERROR;
2496 granted = lease->lease_state;
2498 if (lp_kernel_oplocks(SNUM(fsp->conn))) {
2499 DEBUG(10, ("No lease granted because kernel oplocks are enabled\n"));
2500 granted = SMB2_LEASE_NONE;
2502 if ((granted & (SMB2_LEASE_READ|SMB2_LEASE_WRITE)) == 0) {
2503 DEBUG(10, ("No read or write lease requested\n"));
2504 granted = SMB2_LEASE_NONE;
2506 if (granted == SMB2_LEASE_WRITE) {
2507 DEBUG(10, ("pure write lease requested\n"));
2508 granted = SMB2_LEASE_NONE;
2510 if (granted == (SMB2_LEASE_WRITE|SMB2_LEASE_HANDLE)) {
2511 DEBUG(10, ("write and handle lease requested\n"));
2512 granted = SMB2_LEASE_NONE;
2515 granted = map_oplock_to_lease_type(
2516 oplock_request & ~SAMBA_PRIVATE_OPLOCK_MASK);
2519 if (lp_locking(fsp->conn->params) && file_has_brlocks(fsp)) {
2520 DBG_DEBUG("file %s has byte range locks\n",
2522 granted &= ~SMB2_LEASE_READ;
2525 if (state.have_other_lease) {
2527 * Can grant only one writer
2529 granted &= ~SMB2_LEASE_WRITE;
2532 if ((granted & SMB2_LEASE_READ) && !(granted & SMB2_LEASE_WRITE)) {
2534 (global_client_caps & CAP_LEVEL_II_OPLOCKS) &&
2535 lp_level2_oplocks(SNUM(fsp->conn));
2537 if (!allow_level2) {
2538 granted = SMB2_LEASE_NONE;
2542 if (oplock_request == LEASE_OPLOCK) {
2543 if (state.got_oplock) {
2544 granted &= ~SMB2_LEASE_HANDLE;
2547 fsp->oplock_type = LEASE_OPLOCK;
2549 status = grant_fsp_lease(fsp, lck, lease, granted);
2550 if (!NT_STATUS_IS_OK(status)) {
2555 DBG_DEBUG("lease_state=%d\n", fsp->lease->lease.lease_state);
2557 if (state.got_handle_lease) {
2558 granted = SMB2_LEASE_NONE;
2561 fsp->oplock_type = map_lease_type_to_oplock(granted);
2563 status = set_file_oplock(fsp);
2564 if (!NT_STATUS_IS_OK(status)) {
2566 * Could not get the kernel oplock
2568 fsp->oplock_type = NO_OPLOCK;
2572 if ((granted & SMB2_LEASE_READ) &&
2573 ((lck->data->flags & SHARE_MODE_LEASE_READ) == 0)) {
2574 lck->data->flags |= SHARE_MODE_LEASE_READ;
2575 lck->data->modified = true;
2578 DBG_DEBUG("oplock type 0x%x on file %s\n",
2579 fsp->oplock_type, fsp_str_dbg(fsp));
2581 return NT_STATUS_OK;
2584 static NTSTATUS handle_share_mode_lease(
2586 struct share_mode_lock *lck,
2587 uint32_t create_disposition,
2588 uint32_t access_mask,
2589 uint32_t share_access,
2591 const struct smb2_lease *lease,
2592 bool first_open_attempt)
2594 bool sharing_violation = false;
2597 status = open_mode_check(
2598 fsp->conn, lck, access_mask, share_access);
2599 if (NT_STATUS_EQUAL(status, NT_STATUS_SHARING_VIOLATION)) {
2600 sharing_violation = true;
2601 status = NT_STATUS_OK; /* handled later */
2604 if (!NT_STATUS_IS_OK(status)) {
2608 if (oplock_request == INTERNAL_OPEN_ONLY) {
2609 if (sharing_violation) {
2610 DBG_DEBUG("Sharing violation for internal open\n");
2611 return NT_STATUS_SHARING_VIOLATION;
2615 * Internal opens never do oplocks or leases. We don't
2616 * need to go through delay_for_oplock().
2618 fsp->oplock_type = NO_OPLOCK;
2620 return NT_STATUS_OK;
2623 status = delay_for_oplock(
2630 first_open_attempt);
2631 if (!NT_STATUS_IS_OK(status)) {
2635 return NT_STATUS_OK;
2638 static bool request_timed_out(struct smb_request *req, struct timeval timeout)
2640 struct timeval now, end_time;
2642 end_time = timeval_sum(&req->request_time, &timeout);
2643 return (timeval_compare(&end_time, &now) < 0);
2646 struct defer_open_state {
2647 struct smbXsrv_connection *xconn;
2651 static void defer_open_done(struct tevent_req *req);
2654 * Defer an open and watch a locking.tdb record
2656 * This defers an open that gets rescheduled once the locking.tdb record watch
2657 * is triggered by a change to the record.
2659 * It is used to defer opens that triggered an oplock break and for the SMB1
2660 * sharing violation delay.
2662 static void defer_open(struct share_mode_lock *lck,
2663 struct timeval timeout,
2664 struct smb_request *req,
2667 struct deferred_open_record *open_rec = NULL;
2668 struct timeval abs_timeout;
2669 struct defer_open_state *watch_state;
2670 struct tevent_req *watch_req;
2671 struct timeval_buf tvbuf1, tvbuf2;
2672 struct file_id_buf fbuf;
2675 abs_timeout = timeval_sum(&req->request_time, &timeout);
2677 DBG_DEBUG("request time [%s] timeout [%s] mid [%" PRIu64 "] "
2679 timeval_str_buf(&req->request_time, false, true, &tvbuf1),
2680 timeval_str_buf(&abs_timeout, false, true, &tvbuf2),
2682 file_id_str_buf(id, &fbuf));
2684 open_rec = talloc_zero(NULL, struct deferred_open_record);
2685 if (open_rec == NULL) {
2687 exit_server("talloc failed");
2690 watch_state = talloc(open_rec, struct defer_open_state);
2691 if (watch_state == NULL) {
2692 exit_server("talloc failed");
2694 watch_state->xconn = req->xconn;
2695 watch_state->mid = req->mid;
2697 DBG_DEBUG("defering mid %" PRIu64 "\n", req->mid);
2699 watch_req = share_mode_watch_send(
2703 (struct server_id){0});
2704 if (watch_req == NULL) {
2705 exit_server("Could not watch share mode record");
2707 tevent_req_set_callback(watch_req, defer_open_done, watch_state);
2709 ok = tevent_req_set_endtime(watch_req, req->sconn->ev_ctx, abs_timeout);
2711 exit_server("tevent_req_set_endtime failed");
2714 ok = push_deferred_open_message_smb(req, timeout, id, open_rec);
2717 exit_server("push_deferred_open_message_smb failed");
2721 static void defer_open_done(struct tevent_req *req)
2723 struct defer_open_state *state = tevent_req_callback_data(
2724 req, struct defer_open_state);
2728 status = share_mode_watch_recv(req, NULL, NULL);
2730 if (!NT_STATUS_IS_OK(status)) {
2731 DEBUG(5, ("dbwrap_watched_watch_recv returned %s\n",
2732 nt_errstr(status)));
2734 * Even if it failed, retry anyway. TODO: We need a way to
2735 * tell a re-scheduled open about that error.
2739 DEBUG(10, ("scheduling mid %llu\n", (unsigned long long)state->mid));
2741 ret = schedule_deferred_open_message_smb(state->xconn, state->mid);
2747 * Actually attempt the kernel oplock polling open.
2750 static void poll_open_fn(struct tevent_context *ev,
2751 struct tevent_timer *te,
2752 struct timeval current_time,
2755 struct deferred_open_record *open_rec = talloc_get_type_abort(
2756 private_data, struct deferred_open_record);
2759 TALLOC_FREE(open_rec->watch_req);
2761 ok = schedule_deferred_open_message_smb(
2762 open_rec->xconn, open_rec->mid);
2764 exit_server("schedule_deferred_open_message_smb failed");
2766 DBG_DEBUG("timer fired. Retrying open !\n");
2769 static void poll_open_done(struct tevent_req *subreq);
2772 * Reschedule an open for 1 second from now, if not timed out.
2774 static bool setup_poll_open(
2775 struct smb_request *req,
2776 struct share_mode_lock *lck,
2778 struct timeval max_timeout,
2779 struct timeval interval)
2782 struct deferred_open_record *open_rec = NULL;
2783 struct timeval endtime, next_interval;
2784 struct file_id_buf ftmp;
2786 if (request_timed_out(req, max_timeout)) {
2790 open_rec = talloc_zero(NULL, struct deferred_open_record);
2791 if (open_rec == NULL) {
2792 DBG_WARNING("talloc failed\n");
2795 open_rec->xconn = req->xconn;
2796 open_rec->mid = req->mid;
2799 * Make sure open_rec->te does not come later than the
2800 * request's maximum endtime.
2803 endtime = timeval_sum(&req->request_time, &max_timeout);
2804 next_interval = timeval_current_ofs(interval.tv_sec, interval.tv_usec);
2805 next_interval = timeval_min(&endtime, &next_interval);
2807 open_rec->te = tevent_add_timer(
2813 if (open_rec->te == NULL) {
2814 DBG_WARNING("tevent_add_timer failed\n");
2815 TALLOC_FREE(open_rec);
2820 open_rec->watch_req = share_mode_watch_send(
2824 (struct server_id) {0});
2825 if (open_rec->watch_req == NULL) {
2826 DBG_WARNING("share_mode_watch_send failed\n");
2827 TALLOC_FREE(open_rec);
2830 tevent_req_set_callback(
2831 open_rec->watch_req, poll_open_done, open_rec);
2834 ok = push_deferred_open_message_smb(req, max_timeout, id, open_rec);
2836 DBG_WARNING("push_deferred_open_message_smb failed\n");
2837 TALLOC_FREE(open_rec);
2841 DBG_DEBUG("poll request time [%s] mid [%" PRIu64 "] file_id [%s]\n",
2842 timeval_string(talloc_tos(), &req->request_time, false),
2844 file_id_str_buf(id, &ftmp));
2849 static void poll_open_done(struct tevent_req *subreq)
2851 struct deferred_open_record *open_rec = tevent_req_callback_data(
2852 subreq, struct deferred_open_record);
2856 status = share_mode_watch_recv(subreq, NULL, NULL);
2857 TALLOC_FREE(subreq);
2858 DBG_DEBUG("dbwrap_watched_watch_recv returned %s\n",
2861 ok = schedule_deferred_open_message_smb(
2862 open_rec->xconn, open_rec->mid);
2864 exit_server("schedule_deferred_open_message_smb failed");
2868 bool defer_smb1_sharing_violation(struct smb_request *req)
2873 if (!lp_defer_sharing_violations()) {
2878 * Try every 200msec up to (by default) one second. To be
2879 * precise, according to behaviour note <247> in [MS-CIFS],
2880 * the server tries 5 times. But up to one second should be
2884 timeout_usecs = lp_parm_int(
2888 SHARING_VIOLATION_USEC_WAIT);
2890 ok = setup_poll_open(
2893 (struct file_id) {0},
2894 (struct timeval) { .tv_usec = timeout_usecs },
2895 (struct timeval) { .tv_usec = 200000 });
2899 /****************************************************************************
2900 On overwrite open ensure that the attributes match.
2901 ****************************************************************************/
2903 static bool open_match_attributes(connection_struct *conn,
2904 uint32_t old_dos_attr,
2905 uint32_t new_dos_attr,
2906 mode_t new_unx_mode,
2907 mode_t *returned_unx_mode)
2909 uint32_t noarch_old_dos_attr, noarch_new_dos_attr;
2911 noarch_old_dos_attr = (old_dos_attr & ~FILE_ATTRIBUTE_ARCHIVE);
2912 noarch_new_dos_attr = (new_dos_attr & ~FILE_ATTRIBUTE_ARCHIVE);
2914 if((noarch_old_dos_attr == 0 && noarch_new_dos_attr != 0) ||
2915 (noarch_old_dos_attr != 0 && ((noarch_old_dos_attr & noarch_new_dos_attr) == noarch_old_dos_attr))) {
2916 *returned_unx_mode = new_unx_mode;
2918 *returned_unx_mode = (mode_t)0;
2921 DEBUG(10,("open_match_attributes: old_dos_attr = 0x%x, "
2922 "new_dos_attr = 0x%x "
2923 "returned_unx_mode = 0%o\n",
2924 (unsigned int)old_dos_attr,
2925 (unsigned int)new_dos_attr,
2926 (unsigned int)*returned_unx_mode ));
2928 /* If we're mapping SYSTEM and HIDDEN ensure they match. */
2929 if (lp_map_system(SNUM(conn)) || lp_store_dos_attributes(SNUM(conn))) {
2930 if ((old_dos_attr & FILE_ATTRIBUTE_SYSTEM) &&
2931 !(new_dos_attr & FILE_ATTRIBUTE_SYSTEM)) {
2935 if (lp_map_hidden(SNUM(conn)) || lp_store_dos_attributes(SNUM(conn))) {
2936 if ((old_dos_attr & FILE_ATTRIBUTE_HIDDEN) &&
2937 !(new_dos_attr & FILE_ATTRIBUTE_HIDDEN)) {
2944 static void schedule_defer_open(struct share_mode_lock *lck,
2946 struct smb_request *req)
2948 /* This is a relative time, added to the absolute
2949 request_time value to get the absolute timeout time.
2950 Note that if this is the second or greater time we enter
2951 this codepath for this particular request mid then
2952 request_time is left as the absolute time of the *first*
2953 time this request mid was processed. This is what allows
2954 the request to eventually time out. */
2956 struct timeval timeout;
2958 /* Normally the smbd we asked should respond within
2959 * OPLOCK_BREAK_TIMEOUT seconds regardless of whether
2960 * the client did, give twice the timeout as a safety
2961 * measure here in case the other smbd is stuck
2962 * somewhere else. */
2964 timeout = timeval_set(OPLOCK_BREAK_TIMEOUT*2, 0);
2966 if (request_timed_out(req, timeout)) {
2970 defer_open(lck, timeout, req, id);
2973 /****************************************************************************
2974 Reschedule an open call that went asynchronous.
2975 ****************************************************************************/
2977 static void schedule_async_open_timer(struct tevent_context *ev,
2978 struct tevent_timer *te,
2979 struct timeval current_time,
2982 exit_server("async open timeout");
2985 static void schedule_async_open(struct smb_request *req)
2987 struct deferred_open_record *open_rec = NULL;
2988 struct timeval timeout = timeval_set(20, 0);
2991 if (request_timed_out(req, timeout)) {
2995 open_rec = talloc_zero(NULL, struct deferred_open_record);
2996 if (open_rec == NULL) {
2997 exit_server("deferred_open_record_create failed");
2999 open_rec->async_open = true;
3001 ok = push_deferred_open_message_smb(
3002 req, timeout, (struct file_id){0}, open_rec);
3004 exit_server("push_deferred_open_message_smb failed");
3007 open_rec->te = tevent_add_timer(req->sconn->ev_ctx,
3009 timeval_current_ofs(20, 0),
3010 schedule_async_open_timer,
3012 if (open_rec->te == NULL) {
3013 exit_server("tevent_add_timer failed");
3017 /****************************************************************************
3018 Work out what access_mask to use from what the client sent us.
3019 ****************************************************************************/
3021 static NTSTATUS smbd_calculate_maximum_allowed_access(
3022 connection_struct *conn,
3023 const struct smb_filename *smb_fname,
3025 uint32_t *p_access_mask)
3027 struct security_descriptor *sd;
3028 uint32_t access_granted;
3031 if (!use_privs && (get_current_uid(conn) == (uid_t)0)) {
3032 *p_access_mask |= FILE_GENERIC_ALL;
3033 return NT_STATUS_OK;
3036 status = SMB_VFS_GET_NT_ACL(conn, smb_fname,
3042 if (NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
3044 * File did not exist
3046 *p_access_mask = FILE_GENERIC_ALL;
3047 return NT_STATUS_OK;
3049 if (!NT_STATUS_IS_OK(status)) {
3050 DEBUG(10,("Could not get acl on file %s: %s\n",
3051 smb_fname_str_dbg(smb_fname),
3052 nt_errstr(status)));
3053 return NT_STATUS_ACCESS_DENIED;
3057 * If we can access the path to this file, by
3058 * default we have FILE_READ_ATTRIBUTES from the
3059 * containing directory. See the section:
3060 * "Algorithm to Check Access to an Existing File"
3063 * se_file_access_check()
3064 * also takes care of owner WRITE_DAC and READ_CONTROL.
3066 status = se_file_access_check(sd,
3067 get_current_nttok(conn),
3069 (*p_access_mask & ~FILE_READ_ATTRIBUTES),
3074 if (!NT_STATUS_IS_OK(status)) {
3075 DEBUG(10, ("Access denied on file %s: "
3076 "when calculating maximum access\n",
3077 smb_fname_str_dbg(smb_fname)));
3078 return NT_STATUS_ACCESS_DENIED;
3080 *p_access_mask = (access_granted | FILE_READ_ATTRIBUTES);
3082 if (!(access_granted & DELETE_ACCESS)) {
3083 if (can_delete_file_in_directory(conn,
3087 *p_access_mask |= DELETE_ACCESS;
3091 return NT_STATUS_OK;
3094 NTSTATUS smbd_calculate_access_mask(connection_struct *conn,
3095 const struct smb_filename *smb_fname,
3097 uint32_t access_mask,
3098 uint32_t *access_mask_out)
3101 uint32_t orig_access_mask = access_mask;
3102 uint32_t rejected_share_access;
3104 if (access_mask & SEC_MASK_INVALID) {
3105 DBG_DEBUG("access_mask [%8x] contains invalid bits\n",
3107 return NT_STATUS_ACCESS_DENIED;
3111 * Convert GENERIC bits to specific bits.
3114 se_map_generic(&access_mask, &file_generic_mapping);
3116 /* Calculate MAXIMUM_ALLOWED_ACCESS if requested. */
3117 if (access_mask & MAXIMUM_ALLOWED_ACCESS) {
3119 status = smbd_calculate_maximum_allowed_access(
3120 conn, smb_fname, use_privs, &access_mask);
3122 if (!NT_STATUS_IS_OK(status)) {
3126 access_mask &= conn->share_access;
3129 rejected_share_access = access_mask & ~(conn->share_access);
3131 if (rejected_share_access) {
3132 DEBUG(10, ("smbd_calculate_access_mask: Access denied on "
3133 "file %s: rejected by share access mask[0x%08X] "
3134 "orig[0x%08X] mapped[0x%08X] reject[0x%08X]\n",
3135 smb_fname_str_dbg(smb_fname),
3137 orig_access_mask, access_mask,
3138 rejected_share_access));
3139 return NT_STATUS_ACCESS_DENIED;
3142 *access_mask_out = access_mask;
3143 return NT_STATUS_OK;
3146 /****************************************************************************
3147 Remove the deferred open entry under lock.
3148 ****************************************************************************/
3150 /****************************************************************************
3151 Return true if this is a state pointer to an asynchronous create.
3152 ****************************************************************************/
3154 bool is_deferred_open_async(const struct deferred_open_record *rec)
3156 return rec->async_open;
3159 static bool clear_ads(uint32_t create_disposition)
3163 switch (create_disposition) {
3164 case FILE_SUPERSEDE:
3165 case FILE_OVERWRITE_IF:
3166 case FILE_OVERWRITE:
3175 static int disposition_to_open_flags(uint32_t create_disposition)
3180 * Currently we're using FILE_SUPERSEDE as the same as
3181 * FILE_OVERWRITE_IF but they really are
3182 * different. FILE_SUPERSEDE deletes an existing file
3183 * (requiring delete access) then recreates it.
3186 switch (create_disposition) {
3187 case FILE_SUPERSEDE:
3188 case FILE_OVERWRITE_IF:
3190 * If file exists replace/overwrite. If file doesn't
3193 ret = O_CREAT|O_TRUNC;
3198 * If file exists open. If file doesn't exist error.
3203 case FILE_OVERWRITE:
3205 * If file exists overwrite. If file doesn't exist
3213 * If file exists error. If file doesn't exist create.
3215 ret = O_CREAT|O_EXCL;
3220 * If file exists open. If file doesn't exist create.
3228 static int calculate_open_access_flags(uint32_t access_mask,
3229 uint32_t private_flags)
3231 bool need_write, need_read;
3234 * Note that we ignore the append flag as append does not
3235 * mean the same thing under DOS and Unix.
3238 need_write = (access_mask & (FILE_WRITE_DATA | FILE_APPEND_DATA));
3243 /* DENY_DOS opens are always underlying read-write on the
3244 file handle, no matter what the requested access mask
3248 ((private_flags & NTCREATEX_OPTIONS_PRIVATE_DENY_DOS) ||
3249 access_mask & (FILE_READ_ATTRIBUTES|FILE_READ_DATA|
3250 FILE_READ_EA|FILE_EXECUTE));
3258 /****************************************************************************
3259 Open a file with a share mode. Passed in an already created files_struct *.
3260 ****************************************************************************/
3262 static NTSTATUS open_file_ntcreate(connection_struct *conn,
3263 struct smb_request *req,
3264 uint32_t access_mask, /* access bits (FILE_READ_DATA etc.) */
3265 uint32_t share_access, /* share constants (FILE_SHARE_READ etc) */
3266 uint32_t create_disposition, /* FILE_OPEN_IF etc. */
3267 uint32_t create_options, /* options such as delete on close. */
3268 uint32_t new_dos_attributes, /* attributes used for new file. */
3269 int oplock_request, /* internal Samba oplock codes. */
3270 const struct smb2_lease *lease,
3271 /* Information (FILE_EXISTS etc.) */
3272 uint32_t private_flags, /* Samba specific flags. */
3276 struct smb_filename *smb_fname = fsp->fsp_name;
3279 bool file_existed = VALID_STAT(smb_fname->st);
3280 bool def_acl = False;
3281 bool posix_open = False;
3282 bool new_file_created = False;
3283 bool first_open_attempt = true;
3284 NTSTATUS fsp_open = NT_STATUS_ACCESS_DENIED;
3285 mode_t new_unx_mode = (mode_t)0;
3286 mode_t unx_mode = (mode_t)0;
3288 uint32_t existing_dos_attributes = 0;
3289 struct share_mode_lock *lck = NULL;
3290 uint32_t open_access_mask = access_mask;
3292 struct smb_filename *parent_dir_fname = NULL;
3293 SMB_STRUCT_STAT saved_stat = smb_fname->st;
3294 struct timespec old_write_time;
3296 bool setup_poll = false;
3299 if (conn->printer) {
3301 * Printers are handled completely differently.
3302 * Most of the passed parameters are ignored.
3306 *pinfo = FILE_WAS_CREATED;
3309 DEBUG(10, ("open_file_ntcreate: printer open fname=%s\n",
3310 smb_fname_str_dbg(smb_fname)));
3313 DEBUG(0,("open_file_ntcreate: printer open without "
3314 "an SMB request!\n"));
3315 return NT_STATUS_INTERNAL_ERROR;
3318 return print_spool_open(fsp, smb_fname->base_name,
3322 ok = parent_smb_fname(talloc_tos(),
3327 return NT_STATUS_NO_MEMORY;
3330 if (new_dos_attributes & FILE_FLAG_POSIX_SEMANTICS) {
3332 unx_mode = (mode_t)(new_dos_attributes & ~FILE_FLAG_POSIX_SEMANTICS);
3333 new_dos_attributes = 0;
3335 /* Windows allows a new file to be created and
3336 silently removes a FILE_ATTRIBUTE_DIRECTORY
3337 sent by the client. Do the same. */
3339 new_dos_attributes &= ~FILE_ATTRIBUTE_DIRECTORY;
3341 /* We add FILE_ATTRIBUTE_ARCHIVE to this as this mode is only used if the file is
3343 unx_mode = unix_mode(conn, new_dos_attributes | FILE_ATTRIBUTE_ARCHIVE,
3344 smb_fname, parent_dir_fname);
3347 DEBUG(10, ("open_file_ntcreate: fname=%s, dos_attrs=0x%x "
3348 "access_mask=0x%x share_access=0x%x "
3349 "create_disposition = 0x%x create_options=0x%x "
3350 "unix mode=0%o oplock_request=%d private_flags = 0x%x\n",
3351 smb_fname_str_dbg(smb_fname), new_dos_attributes,
3352 access_mask, share_access, create_disposition,
3353 create_options, (unsigned int)unx_mode, oplock_request,
3354 (unsigned int)private_flags));
3357 /* Ensure req == NULL means INTERNAL_OPEN_ONLY */
3358 SMB_ASSERT(oplock_request == INTERNAL_OPEN_ONLY);
3360 /* And req != NULL means no INTERNAL_OPEN_ONLY */
3361 SMB_ASSERT(((oplock_request & INTERNAL_OPEN_ONLY) == 0));
3365 * Only non-internal opens can be deferred at all
3369 struct deferred_open_record *open_rec;
3370 if (get_deferred_open_message_state(req, NULL, &open_rec)) {
3372 /* If it was an async create retry, the file
3375 if (is_deferred_open_async(open_rec)) {
3376 SET_STAT_INVALID(smb_fname->st);
3377 file_existed = false;
3380 /* Ensure we don't reprocess this message. */
3381 remove_deferred_open_message_smb(req->xconn, req->mid);
3383 first_open_attempt = false;
3388 new_dos_attributes &= SAMBA_ATTRIBUTES_MASK;
3391 * Only use stored DOS attributes for checks
3392 * against requested attributes (below via
3393 * open_match_attributes()), cf bug #11992
3394 * for details. -slow
3398 status = SMB_VFS_GET_DOS_ATTRIBUTES(conn, smb_fname, &attr);
3399 if (NT_STATUS_IS_OK(status)) {
3400 existing_dos_attributes = attr;
3405 /* ignore any oplock requests if oplocks are disabled */
3406 if (!lp_oplocks(SNUM(conn)) ||
3407 IS_VETO_OPLOCK_PATH(conn, smb_fname->base_name)) {
3408 /* Mask off everything except the private Samba bits. */
3409 oplock_request &= SAMBA_PRIVATE_OPLOCK_MASK;
3412 /* this is for OS/2 long file names - say we don't support them */
3413 if (req != NULL && !req->posix_pathnames &&
3414 strstr(smb_fname->base_name,".+,;=[].")) {
3415 /* OS/2 Workplace shell fix may be main code stream in a later
3417 DEBUG(5,("open_file_ntcreate: OS/2 long filenames are not "
3419 if (use_nt_status()) {
3420 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3422 return NT_STATUS_DOS(ERRDOS, ERRcannotopen);
3425 switch( create_disposition ) {
3427 /* If file exists open. If file doesn't exist error. */
3428 if (!file_existed) {
3429 DEBUG(5,("open_file_ntcreate: FILE_OPEN "
3430 "requested for file %s and file "
3432 smb_fname_str_dbg(smb_fname)));
3434 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3438 case FILE_OVERWRITE:
3439 /* If file exists overwrite. If file doesn't exist
3441 if (!file_existed) {
3442 DEBUG(5,("open_file_ntcreate: FILE_OVERWRITE "
3443 "requested for file %s and file "
3445 smb_fname_str_dbg(smb_fname) ));
3447 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3452 /* If file exists error. If file doesn't exist
3455 DEBUG(5,("open_file_ntcreate: FILE_CREATE "
3456 "requested for file %s and file "
3457 "already exists.\n",
3458 smb_fname_str_dbg(smb_fname)));
3459 if (S_ISDIR(smb_fname->st.st_ex_mode)) {
3464 return map_nt_error_from_unix(errno);
3468 case FILE_SUPERSEDE:
3469 case FILE_OVERWRITE_IF:
3473 return NT_STATUS_INVALID_PARAMETER;
3476 flags2 = disposition_to_open_flags(create_disposition);
3478 /* We only care about matching attributes on file exists and
3481 if (!posix_open && file_existed &&
3482 ((create_disposition == FILE_OVERWRITE) ||
3483 (create_disposition == FILE_OVERWRITE_IF))) {
3484 if (!open_match_attributes(conn, existing_dos_attributes,
3486 unx_mode, &new_unx_mode)) {
3487 DEBUG(5,("open_file_ntcreate: attributes mismatch "
3488 "for file %s (%x %x) (0%o, 0%o)\n",
3489 smb_fname_str_dbg(smb_fname),
3490 existing_dos_attributes,
3492 (unsigned int)smb_fname->st.st_ex_mode,
3493 (unsigned int)unx_mode ));
3495 return NT_STATUS_ACCESS_DENIED;
3499 status = smbd_calculate_access_mask(conn, smb_fname,
3503 if (!NT_STATUS_IS_OK(status)) {
3504 DEBUG(10, ("open_file_ntcreate: smbd_calculate_access_mask "
3505 "on file %s returned %s\n",
3506 smb_fname_str_dbg(smb_fname), nt_errstr(status)));
3510 open_access_mask = access_mask;
3512 if (flags2 & O_TRUNC) {
3513 open_access_mask |= FILE_WRITE_DATA; /* This will cause oplock breaks. */
3518 * stat opens on existing files don't get oplocks.
3519 * They can get leases.
3521 * Note that we check for stat open on the *open_access_mask*,
3522 * i.e. the access mask we actually used to do the open,
3523 * not the one the client asked for (which is in
3524 * fsp->access_mask). This is due to the fact that
3525 * FILE_OVERWRITE and FILE_OVERWRITE_IF add in O_TRUNC,
3526 * which adds FILE_WRITE_DATA to open_access_mask.
3528 if (is_oplock_stat_open(open_access_mask) && lease == NULL) {
3529 oplock_request = NO_OPLOCK;
3533 DEBUG(10, ("open_file_ntcreate: fname=%s, after mapping "
3534 "access_mask=0x%x\n", smb_fname_str_dbg(smb_fname),
3538 * Note that we ignore the append flag as append does not
3539 * mean the same thing under DOS and Unix.
3542 flags = calculate_open_access_flags(access_mask, private_flags);
3545 * Currently we only look at FILE_WRITE_THROUGH for create options.
3549 if ((create_options & FILE_WRITE_THROUGH) && lp_strict_sync(SNUM(conn))) {
3554 if (posix_open && (access_mask & FILE_APPEND_DATA)) {
3558 if (!posix_open && !CAN_WRITE(conn)) {
3560 * We should really return a permission denied error if either
3561 * O_CREAT or O_TRUNC are set, but for compatibility with
3562 * older versions of Samba we just AND them out.
3564 flags2 &= ~(O_CREAT|O_TRUNC);
3568 * With kernel oplocks the open breaking an oplock
3569 * blocks until the oplock holder has given up the
3570 * oplock or closed the file. We prevent this by always
3571 * trying to open the file with O_NONBLOCK (see "man
3574 * If a process that doesn't use the smbd open files
3575 * database or communication methods holds a kernel
3576 * oplock we must periodically poll for available open
3579 flags2 |= O_NONBLOCK;
3582 * Ensure we can't write on a read-only share or file.
3585 if (flags != O_RDONLY && file_existed &&
3586 (!CAN_WRITE(conn) || IS_DOS_READONLY(existing_dos_attributes))) {
3587 DEBUG(5,("open_file_ntcreate: write access requested for "
3588 "file %s on read only %s\n",
3589 smb_fname_str_dbg(smb_fname),
3590 !CAN_WRITE(conn) ? "share" : "file" ));
3592 return NT_STATUS_ACCESS_DENIED;
3595 if (VALID_STAT(smb_fname->st)) {
3597 * Only try and create a file id before open
3598 * for an existing file. For a file being created
3599 * this won't do anything useful until the file
3600 * exists and has a valid stat struct.
3602 fsp->file_id = vfs_file_id_from_sbuf(conn, &smb_fname->st);
3604 fsp->fh->private_options = private_flags;
3605 fsp->access_mask = open_access_mask; /* We change this to the
3606 * requested access_mask after
3607 * the open is done. */
3609 fsp->posix_flags |= FSP_POSIX_FLAGS_ALL;
3612 if ((create_options & FILE_DELETE_ON_CLOSE) &&
3613 (flags2 & O_CREAT) &&
3615 /* Delete on close semantics for new files. */
3616 status = can_set_delete_on_close(fsp,
3617 new_dos_attributes);
3618 if (!NT_STATUS_IS_OK(status)) {
3625 * Ensure we pay attention to default ACLs on directories if required.
3628 if ((flags2 & O_CREAT) && lp_inherit_acls(SNUM(conn)) &&
3629 (def_acl = directory_has_default_acl(conn,
3633 unx_mode = (0777 & lp_create_mask(SNUM(conn)));
3636 DEBUG(4,("calling open_file with flags=0x%X flags2=0x%X mode=0%o, "
3637 "access_mask = 0x%x, open_access_mask = 0x%x\n",
3638 (unsigned int)flags, (unsigned int)flags2,
3639 (unsigned int)unx_mode, (unsigned int)access_mask,
3640 (unsigned int)open_access_mask));
3642 fsp_open = open_file(fsp, conn, req, parent_dir_fname,
3643 flags|flags2, unx_mode, access_mask,
3644 open_access_mask, &new_file_created);
3646 if (NT_STATUS_EQUAL(fsp_open, NT_STATUS_NETWORK_BUSY)) {
3647 if (file_existed && S_ISFIFO(fsp->fsp_name->st.st_ex_mode)) {
3648 DEBUG(10, ("FIFO busy\n"));
3649 return NT_STATUS_NETWORK_BUSY;
3652 DEBUG(10, ("Internal open busy\n"));
3653 return NT_STATUS_NETWORK_BUSY;
3656 * This handles the kernel oplock case:
3658 * the file has an active kernel oplock and the open() returned
3659 * EWOULDBLOCK/EAGAIN which maps to NETWORK_BUSY.
3661 * "Samba locking.tdb oplocks" are handled below after acquiring
3662 * the sharemode lock with get_share_mode_lock().
3667 if (NT_STATUS_EQUAL(fsp_open, NT_STATUS_RETRY)) {
3669 * EINTR from the open(2) syscall. Just setup a retry
3670 * in a bit. We can't use the sys_write() tight retry
3671 * loop here, as we might have to actually deal with
3672 * lease-break signals to avoid a deadlock.
3679 * From here on we assume this is an oplock break triggered
3682 lck = get_existing_share_mode_lock(talloc_tos(), fsp->file_id);
3684 if ((lck != NULL) && !validate_oplock_types(lck)) {
3685 smb_panic("validate_oplock_types failed");
3689 * Retry once a second. If there's a share_mode_lock
3690 * around, also wait for it in case it was smbd
3691 * holding that kernel oplock that can quickly tell us
3692 * the oplock got removed.
3699 timeval_set(OPLOCK_BREAK_TIMEOUT*2, 0),
3704 return NT_STATUS_SHARING_VIOLATION;
3707 if (!NT_STATUS_IS_OK(fsp_open)) {
3708 bool wait_for_aio = NT_STATUS_EQUAL(
3709 fsp_open, NT_STATUS_MORE_PROCESSING_REQUIRED);
3711 schedule_async_open(req);
3716 if (new_file_created) {
3718 * As we atomically create using O_CREAT|O_EXCL,
3719 * then if new_file_created is true, then
3720 * file_existed *MUST* have been false (even
3721 * if the file was previously detected as being
3724 file_existed = false;
3727 if (file_existed && !check_same_dev_ino(&saved_stat, &smb_fname->st)) {
3729 * The file did exist, but some other (local or NFS)
3730 * process either renamed/unlinked and re-created the
3731 * file with different dev/ino after we walked the path,
3732 * but before we did the open. We could retry the
3733 * open but it's a rare enough case it's easier to
3734 * just fail the open to prevent creating any problems
3735 * in the open file db having the wrong dev/ino key.
3738 DBG_WARNING("file %s - dev/ino mismatch. "
3739 "Old (dev=%ju, ino=%ju). "
3740 "New (dev=%ju, ino=%ju). Failing open "
3741 "with NT_STATUS_ACCESS_DENIED.\n",
3742 smb_fname_str_dbg(smb_fname),
3743 (uintmax_t)saved_stat.st_ex_dev,
3744 (uintmax_t)saved_stat.st_ex_ino,
3745 (uintmax_t)smb_fname->st.st_ex_dev,
3746 (uintmax_t)smb_fname->st.st_ex_ino);
3747 return NT_STATUS_ACCESS_DENIED;
3750 old_write_time = smb_fname->st.st_ex_mtime;
3753 * Deal with the race condition where two smbd's detect the
3754 * file doesn't exist and do the create at the same time. One
3755 * of them will win and set a share mode, the other (ie. this
3756 * one) should check if the requested share mode for this
3757 * create is allowed.
3761 * Now the file exists and fsp is successfully opened,
3762 * fsp->dev and fsp->inode are valid and should replace the
3763 * dev=0,inode=0 from a non existent file. Spotted by
3764 * Nadav Danieli <nadavd@exanet.com>. JRA.
3769 lck = get_share_mode_lock(talloc_tos(), id,
3771 smb_fname, &old_write_time);
3774 DEBUG(0, ("open_file_ntcreate: Could not get share "
3775 "mode lock for %s\n",
3776 smb_fname_str_dbg(smb_fname)));
3778 return NT_STATUS_SHARING_VIOLATION;
3781 /* Get the types we need to examine. */
3782 if (!validate_oplock_types(lck)) {
3783 smb_panic("validate_oplock_types failed");
3786 if (has_delete_on_close(lck, fsp->name_hash)) {
3789 return NT_STATUS_DELETE_PENDING;
3792 status = handle_share_mode_lease(
3800 first_open_attempt);
3802 if (NT_STATUS_EQUAL(status, NT_STATUS_RETRY)) {
3803 schedule_defer_open(lck, fsp->file_id, req);
3806 return NT_STATUS_SHARING_VIOLATION;
3809 if (!NT_STATUS_IS_OK(status)) {
3816 struct share_mode_data *d = lck->data;
3817 uint16_t new_flags = share_mode_flags_restrict(
3818 d->flags, access_mask, share_access, UINT32_MAX);
3820 if (new_flags != d->flags) {
3821 d->flags = new_flags;
3826 ok = set_share_mode(
3829 get_current_uid(fsp->conn),
3835 if (fsp->oplock_type == LEASE_OPLOCK) {
3836 status = remove_lease_if_stale(
3838 fsp_client_guid(fsp),
3839 &fsp->lease->lease.lease_key);
3840 if (!NT_STATUS_IS_OK(status)) {
3841 DBG_WARNING("remove_lease_if_stale "
3846 return NT_STATUS_NO_MEMORY;
3849 /* Should we atomically (to the client at least) truncate ? */
3850 if ((!new_file_created) &&
3851 (flags2 & O_TRUNC) &&
3852 (S_ISREG(fsp->fsp_name->st.st_ex_mode))) {
3855 ret = SMB_VFS_FTRUNCATE(fsp, 0);
3857 status = map_nt_error_from_unix(errno);
3858 del_share_mode(lck, fsp);
3863 notify_fname(fsp->conn, NOTIFY_ACTION_MODIFIED,
3864 FILE_NOTIFY_CHANGE_SIZE
3865 | FILE_NOTIFY_CHANGE_ATTRIBUTES,
3866 fsp->fsp_name->base_name);
3870 * We have the share entry *locked*.....
3873 /* Delete streams if create_disposition requires it */
3874 if (!new_file_created && clear_ads(create_disposition) &&
3875 !is_ntfs_stream_smb_fname(smb_fname)) {
3876 status = delete_all_streams(conn, smb_fname);
3877 if (!NT_STATUS_IS_OK(status)) {
3878 del_share_mode(lck, fsp);
3885 if (fsp->fh->fd != -1 && lp_kernel_share_modes(SNUM(conn))) {
3888 * Beware: streams implementing VFS modules may
3889 * implement streams in a way that fsp will have the
3890 * basefile open in the fsp fd, so lacking a distinct
3891 * fd for the stream kernel_flock will apply on the
3892 * basefile which is wrong. The actual check is
3893 * deferred to the VFS module implementing the
3894 * kernel_flock call.
3896 ret_flock = SMB_VFS_KERNEL_FLOCK(fsp, share_access, access_mask);
3897 if(ret_flock == -1 ){
3899 del_share_mode(lck, fsp);
3903 return NT_STATUS_SHARING_VIOLATION;
3906 fsp->fsp_flags.kernel_share_modes_taken = true;
3910 * At this point onwards, we can guarantee that the share entry
3911 * is locked, whether we created the file or not, and that the
3912 * deny mode is compatible with all current opens.
3916 * According to Samba4, SEC_FILE_READ_ATTRIBUTE is always granted,
3917 * but we don't have to store this - just ignore it on access check.
3919 if (conn->sconn->using_smb2) {
3921 * SMB2 doesn't return it (according to Microsoft tests).
3922 * Test Case: TestSuite_ScenarioNo009GrantedAccessTestS0
3923 * File created with access = 0x7 (Read, Write, Delete)
3924 * Query Info on file returns 0x87 (Read, Write, Delete, Read Attributes)
3926 fsp->access_mask = access_mask;
3928 /* But SMB1 does. */
3929 fsp->access_mask = access_mask | FILE_READ_ATTRIBUTES;
3932 if (new_file_created) {
3933 info = FILE_WAS_CREATED;
3935 if (flags2 & O_TRUNC) {
3936 info = FILE_WAS_OVERWRITTEN;
3938 info = FILE_WAS_OPENED;
3946 /* Handle strange delete on close create semantics. */
3947 if (create_options & FILE_DELETE_ON_CLOSE) {
3948 if (!new_file_created) {
3949 status = can_set_delete_on_close(fsp,
3950 existing_dos_attributes);
3952 if (!NT_STATUS_IS_OK(status)) {
3953 /* Remember to delete the mode we just added. */
3954 del_share_mode(lck, fsp);
3960 /* Note that here we set the *initial* delete on close flag,
3961 not the regular one. The magic gets handled in close. */
3962 fsp->fsp_flags.initial_delete_on_close = true;
3966 * If we created a file and it's not a stream, this is the point where
3967 * we set the itime (aka invented time) that get's stored in the DOS
3968 * attribute xattr. The value is going to be either what the filesystem
3969 * provided or a copy of the creation date.
3971 * Either way, we turn the itime into a File-ID, unless the filesystem
3972 * provided one (unlikely).
3974 if (info == FILE_WAS_CREATED && !is_named_stream(smb_fname)) {
3975 smb_fname->st.st_ex_iflags &= ~ST_EX_IFLAG_CALCULATED_ITIME;
3977 if (lp_store_dos_attributes(SNUM(conn)) &&
3978 smb_fname->st.st_ex_iflags & ST_EX_IFLAG_CALCULATED_FILE_ID)
3982 file_id = make_file_id_from_itime(&smb_fname->st);
3983 update_stat_ex_file_id(&smb_fname->st, file_id);
3987 if (info != FILE_WAS_OPENED) {
3988 /* Overwritten files should be initially set as archive */
3989 if ((info == FILE_WAS_OVERWRITTEN && lp_map_archive(SNUM(conn))) ||
3990 lp_store_dos_attributes(SNUM(conn))) {
3991 (void)dos_mode(conn, smb_fname);
3993 if (file_set_dosmode(conn, smb_fname,
3994 new_dos_attributes | FILE_ATTRIBUTE_ARCHIVE,
3995 parent_dir_fname, true) == 0) {
3996 unx_mode = smb_fname->st.st_ex_mode;
4002 /* Determine sparse flag. */
4004 /* POSIX opens are sparse by default. */
4005 fsp->fsp_flags.is_sparse = true;
4007 fsp->fsp_flags.is_sparse =
4008 (existing_dos_attributes & FILE_ATTRIBUTE_SPARSE);
4012 * Take care of inherited ACLs on created files - if default ACL not
4016 if (!posix_open && new_file_created && !def_acl) {
4017 if (unx_mode != smb_fname->st.st_ex_mode) {
4018 int ret = SMB_VFS_FCHMOD(fsp, unx_mode);
4020 DBG_INFO("failed to reset "
4021 "attributes of file %s to 0%o\n",
4022 smb_fname_str_dbg(smb_fname),
4023 (unsigned int)unx_mode);
4027 } else if (new_unx_mode) {
4029 * We only get here in the case of:
4031 * a). Not a POSIX open.
4032 * b). File already existed.
4033 * c). File was overwritten.
4034 * d). Requested DOS attributes didn't match
4035 * the DOS attributes on the existing file.
4037 * In that case new_unx_mode has been set
4038 * equal to the calculated mode (including
4039 * possible inheritance of the mode from the
4040 * containing directory).
4042 * Note this mode was calculated with the
4043 * DOS attribute FILE_ATTRIBUTE_ARCHIVE added,
4044 * so the mode change here is suitable for
4045 * an overwritten file.
4048 if (new_unx_mode != smb_fname->st.st_ex_mode) {
4049 int ret = SMB_VFS_FCHMOD(fsp, new_unx_mode);
4051 DBG_INFO("failed to reset "
4052 "attributes of file %s to 0%o\n",
4053 smb_fname_str_dbg(smb_fname),
4054 (unsigned int)new_unx_mode);
4061 * Deal with other opens having a modified write time.
4063 struct timespec write_time = get_share_mode_write_time(lck);
4065 if (!is_omit_timespec(&write_time)) {
4066 update_stat_ex_mtime(&fsp->fsp_name->st, write_time);
4072 return NT_STATUS_OK;
4075 static NTSTATUS mkdir_internal(connection_struct *conn,
4076 struct smb_filename *smb_dname,
4077 uint32_t file_attributes)
4079 const struct loadparm_substitution *lp_sub =
4080 loadparm_s3_global_substitution();
4082 struct smb_filename *parent_dir_fname = NULL;
4084 bool posix_open = false;
4085 bool need_re_stat = false;
4086 uint32_t access_mask = SEC_DIR_ADD_SUBDIR;
4090 if (!CAN_WRITE(conn) || (access_mask & ~(conn->share_access))) {
4091 DEBUG(5,("mkdir_internal: failing share access "
4092 "%s\n", lp_servicename(talloc_tos(), lp_sub, SNUM(conn))));
4093 return NT_STATUS_ACCESS_DENIED;
4096 ok = parent_smb_fname(talloc_tos(),
4101 return NT_STATUS_NO_MEMORY;
4104 if (file_attributes & FILE_FLAG_POSIX_SEMANTICS) {
4106 mode = (mode_t)(file_attributes & ~FILE_FLAG_POSIX_SEMANTICS);
4108 mode = unix_mode(conn,
4109 FILE_ATTRIBUTE_DIRECTORY,
4114 status = check_parent_access(conn,
4117 if(!NT_STATUS_IS_OK(status)) {
4118 DEBUG(5,("mkdir_internal: check_parent_access "
4119 "on directory %s for path %s returned %s\n",
4120 smb_fname_str_dbg(parent_dir_fname),
4121 smb_dname->base_name,
4122 nt_errstr(status) ));
4126 ret = SMB_VFS_MKDIRAT(conn,
4131 return map_nt_error_from_unix(errno);
4134 /* Ensure we're checking for a symlink here.... */
4135 /* We don't want to get caught by a symlink racer. */
4137 if (SMB_VFS_LSTAT(conn, smb_dname) == -1) {
4138 DEBUG(2, ("Could not stat directory '%s' just created: %s\n",
4139 smb_fname_str_dbg(smb_dname), strerror(errno)));
4140 return map_nt_error_from_unix(errno);
4143 if (!S_ISDIR(smb_dname->st.st_ex_mode)) {
4144 DEBUG(0, ("Directory '%s' just created is not a directory !\n",
4145 smb_fname_str_dbg(smb_dname)));
4146 return NT_STATUS_NOT_A_DIRECTORY;
4149 smb_dname->st.st_ex_iflags &= ~ST_EX_IFLAG_CALCULATED_ITIME;
4151 if (lp_store_dos_attributes(SNUM(conn))) {
4152 if (smb_dname->st.st_ex_iflags & ST_EX_IFLAG_CALCULATED_FILE_ID)
4156 file_id = make_file_id_from_itime(&smb_dname->st);
4157 update_stat_ex_file_id(&smb_dname->st, file_id);
4161 file_set_dosmode(conn, smb_dname,
4162 file_attributes | FILE_ATTRIBUTE_DIRECTORY,
4163 parent_dir_fname, true);
4167 if (lp_inherit_permissions(SNUM(conn))) {
4168 inherit_access_posix_acl(conn, parent_dir_fname,
4170 need_re_stat = true;
4175 * Check if high bits should have been set,
4176 * then (if bits are missing): add them.
4177 * Consider bits automagically set by UNIX, i.e. SGID bit from parent
4180 if ((mode & ~(S_IRWXU|S_IRWXG|S_IRWXO)) &&
4181 (mode & ~smb_dname->st.st_ex_mode)) {
4182 SMB_VFS_CHMOD(conn, smb_dname,
4183 (smb_dname->st.st_ex_mode |
4184 (mode & ~smb_dname->st.st_ex_mode)));
4185 need_re_stat = true;
4189 /* Change the owner if required. */
4190 if (lp_inherit_owner(SNUM(conn)) != INHERIT_OWNER_NO) {
4191 change_dir_owner_to_parent(conn, parent_dir_fname,
4194 need_re_stat = true;
4198 if (SMB_VFS_LSTAT(conn, smb_dname) == -1) {
4199 DEBUG(2, ("Could not stat directory '%s' just created: %s\n",
4200 smb_fname_str_dbg(smb_dname), strerror(errno)));
4201 return map_nt_error_from_unix(errno);
4205 notify_fname(conn, NOTIFY_ACTION_ADDED, FILE_NOTIFY_CHANGE_DIR_NAME,
4206 smb_dname->base_name);
4208 return NT_STATUS_OK;
4211 /****************************************************************************
4212 Open a directory from an NT SMB call.
4213 ****************************************************************************/
4215 static NTSTATUS open_directory(connection_struct *conn,
4216 struct smb_request *req,
4217 struct smb_filename *smb_dname,
4218 uint32_t access_mask,
4219 uint32_t share_access,
4220 uint32_t create_disposition,
4221 uint32_t create_options,
4222 uint32_t file_attributes,
4224 files_struct **result)
4226 files_struct *fsp = NULL;
4227 bool dir_existed = VALID_STAT(smb_dname->st);
4228 struct share_mode_lock *lck = NULL;
4230 struct timespec mtimespec;
4234 if (is_ntfs_stream_smb_fname(smb_dname)) {
4235 DEBUG(2, ("open_directory: %s is a stream name!\n",
4236 smb_fname_str_dbg(smb_dname)));
4237 return NT_STATUS_NOT_A_DIRECTORY;
4240 if (!(file_attributes & FILE_FLAG_POSIX_SEMANTICS)) {
4241 /* Ensure we have a directory attribute. */
4242 file_attributes |= FILE_ATTRIBUTE_DIRECTORY;
4245 DBG_INFO("opening directory %s, access_mask = 0x%"PRIx32", "
4246 "share_access = 0x%"PRIx32" create_options = 0x%"PRIx32", "
4247 "create_disposition = 0x%"PRIx32", "
4248 "file_attributes = 0x%"PRIx32"\n",
4249 smb_fname_str_dbg(smb_dname),
4256 status = smbd_calculate_access_mask(conn, smb_dname, false,
4257 access_mask, &access_mask);
4258 if (!NT_STATUS_IS_OK(status)) {
4259 DEBUG(10, ("open_directory: smbd_calculate_access_mask "
4260 "on file %s returned %s\n",
4261 smb_fname_str_dbg(smb_dname),
4262 nt_errstr(status)));
4266 if ((access_mask & SEC_FLAG_SYSTEM_SECURITY) &&
4267 !security_token_has_privilege(get_current_nttok(conn),
4268 SEC_PRIV_SECURITY)) {
4269 DEBUG(10, ("open_directory: open on %s "
4270 "failed - SEC_FLAG_SYSTEM_SECURITY denied.\n",
4271 smb_fname_str_dbg(smb_dname)));
4272 return NT_STATUS_PRIVILEGE_NOT_HELD;
4275 switch( create_disposition ) {
4279 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
4282 info = FILE_WAS_OPENED;
4287 /* If directory exists error. If directory doesn't
4291 status = NT_STATUS_OBJECT_NAME_COLLISION;
4292 DEBUG(2, ("open_directory: unable to create "
4293 "%s. Error was %s\n",
4294 smb_fname_str_dbg(smb_dname),
4295 nt_errstr(status)));
4299 status = mkdir_internal(conn, smb_dname,
4302 if (!NT_STATUS_IS_OK(status)) {
4303 DEBUG(2, ("open_directory: unable to create "
4304 "%s. Error was %s\n",
4305 smb_fname_str_dbg(smb_dname),
4306 nt_errstr(status)));
4310 info = FILE_WAS_CREATED;
4315 * If directory exists open. If directory doesn't
4320 status = NT_STATUS_OK;
4321 info = FILE_WAS_OPENED;
4323 status = mkdir_internal(conn, smb_dname,
4326 if (NT_STATUS_IS_OK(status)) {
4327 info = FILE_WAS_CREATED;
4329 /* Cope with create race. */
4330 if (!NT_STATUS_EQUAL(status,
4331 NT_STATUS_OBJECT_NAME_COLLISION)) {
4332 DEBUG(2, ("open_directory: unable to create "
4333 "%s. Error was %s\n",
4334 smb_fname_str_dbg(smb_dname),
4335 nt_errstr(status)));
4340 * If mkdir_internal() returned
4341 * NT_STATUS_OBJECT_NAME_COLLISION
4342 * we still must lstat the path.
4345 if (SMB_VFS_LSTAT(conn, smb_dname)
4347 DEBUG(2, ("Could not stat "
4348 "directory '%s' just "
4353 return map_nt_error_from_unix(
4357 info = FILE_WAS_OPENED;
4363 case FILE_SUPERSEDE:
4364 case FILE_OVERWRITE:
4365 case FILE_OVERWRITE_IF:
4367 DEBUG(5,("open_directory: invalid create_disposition "
4368 "0x%x for directory %s\n",
4369 (unsigned int)create_disposition,
4370 smb_fname_str_dbg(smb_dname)));
4371 return NT_STATUS_INVALID_PARAMETER;
4374 if(!S_ISDIR(smb_dname->st.st_ex_mode)) {
4375 DEBUG(5,("open_directory: %s is not a directory !\n",
4376 smb_fname_str_dbg(smb_dname)));
4377 return NT_STATUS_NOT_A_DIRECTORY;
4380 if (info == FILE_WAS_OPENED) {
4381 status = smbd_check_access_rights(conn,
4386 if (!NT_STATUS_IS_OK(status)) {
4387 DEBUG(10, ("open_directory: smbd_check_access_rights on "
4388 "file %s failed with %s\n",
4389 smb_fname_str_dbg(smb_dname),
4390 nt_errstr(status)));
4395 status = file_new(req, conn, &fsp);
4396 if(!NT_STATUS_IS_OK(status)) {
4401 * Setup the files_struct for it.
4404 fsp->file_id = vfs_file_id_from_sbuf(conn, &smb_dname->st);
4405 fsp->vuid = req ? req->vuid : UID_FIELD_INVALID;
4406 fsp->file_pid = req ? req->smbpid : 0;
4407 fsp->fsp_flags.can_lock = false;
4408 fsp->fsp_flags.can_read = false;
4409 fsp->fsp_flags.can_write = false;
4411 fsp->fh->private_options = 0;
4413 * According to Samba4, SEC_FILE_READ_ATTRIBUTE is always granted,
4415 fsp->access_mask = access_mask | FILE_READ_ATTRIBUTES;
4416 fsp->print_file = NULL;
4417 fsp->fsp_flags.modified = false;
4418 fsp->oplock_type = NO_OPLOCK;
4419 fsp->sent_oplock_break = NO_BREAK_SENT;
4420 fsp->fsp_flags.is_directory = true;
4421 if (file_attributes & FILE_FLAG_POSIX_SEMANTICS) {
4422 fsp->posix_flags |= FSP_POSIX_FLAGS_ALL;
4424 status = fsp_set_smb_fname(fsp, smb_dname);
4425 if (!NT_STATUS_IS_OK(status)) {
4426 file_free(req, fsp);
4430 /* Don't store old timestamps for directory
4431 handles in the internal database. We don't
4432 update them in there if new objects
4433 are created in the directory. Currently
4434 we only update timestamps on file writes.
4437 mtimespec = make_omit_timespec();
4440 status = fd_open(conn, fsp, O_RDONLY|O_DIRECTORY, 0);
4442 /* POSIX allows us to open a directory with O_RDONLY. */
4443 status = fd_open(conn, fsp, O_RDONLY, 0);
4445 if (!NT_STATUS_IS_OK(status)) {
4446 DBG_INFO("Could not open fd for "
4448 smb_fname_str_dbg(smb_dname),
4450 file_free(req, fsp);
4454 status = vfs_stat_fsp(fsp);
4455 if (!NT_STATUS_IS_OK(status)) {
4457 file_free(req, fsp);
4461 if(!S_ISDIR(fsp->fsp_name->st.st_ex_mode)) {
4462 DEBUG(5,("open_directory: %s is not a directory !\n",
4463 smb_fname_str_dbg(smb_dname)));
4465 file_free(req, fsp);
4466 return NT_STATUS_NOT_A_DIRECTORY;
4469 /* Ensure there was no race condition. We need to check
4470 * dev/inode but not permissions, as these can change
4472 if (!check_same_dev_ino(&smb_dname->st, &fsp->fsp_name->st)) {
4473 DEBUG(5,("open_directory: stat struct differs for "
4475 smb_fname_str_dbg(smb_dname)));
4477 file_free(req, fsp);
4478 return NT_STATUS_ACCESS_DENIED;
4481 lck = get_share_mode_lock(talloc_tos(), fsp->file_id,
4482 conn->connectpath, smb_dname,
4486 DEBUG(0, ("open_directory: Could not get share mode lock for "
4487 "%s\n", smb_fname_str_dbg(smb_dname)));
4489 file_free(req, fsp);
4490 return NT_STATUS_SHARING_VIOLATION;
4493 if (has_delete_on_close(lck, fsp->name_hash)) {
4496 file_free(req, fsp);
4497 return NT_STATUS_DELETE_PENDING;
4500 status = open_mode_check(conn, lck,
4501 access_mask, share_access);
4503 if (!NT_STATUS_IS_OK(status)) {
4506 file_free(req, fsp);
4511 struct share_mode_data *d = lck->data;
4512 uint16_t new_flags = share_mode_flags_restrict(
4513 d->flags, access_mask, share_access, UINT32_MAX);
4515 if (new_flags != d->flags) {
4516 d->flags = new_flags;
4521 ok = set_share_mode(
4524 get_current_uid(conn),
4532 file_free(req, fsp);
4533 return NT_STATUS_NO_MEMORY;
4536 /* For directories the delete on close bit at open time seems
4537 always to be honored on close... See test 19 in Samba4 BASE-DELETE. */
4538 if (create_options & FILE_DELETE_ON_CLOSE) {
4539 status = can_set_delete_on_close(fsp, 0);
4540 if (!NT_STATUS_IS_OK(status) && !NT_STATUS_EQUAL(status, NT_STATUS_DIRECTORY_NOT_EMPTY)) {
4541 del_share_mode(lck, fsp);
4544 file_free(req, fsp);
4548 if (NT_STATUS_IS_OK(status)) {
4549 /* Note that here we set the *initial* delete on close flag,
4550 not the regular one. The magic gets handled in close. */
4551 fsp->fsp_flags.initial_delete_on_close = true;
4557 * Deal with other opens having a modified write time. Is this
4558 * possible for directories?
4560 struct timespec write_time = get_share_mode_write_time(lck);
4562 if (!is_omit_timespec(&write_time)) {
4563 update_stat_ex_mtime(&fsp->fsp_name->st, write_time);
4574 return NT_STATUS_OK;
4577 NTSTATUS create_directory(connection_struct *conn, struct smb_request *req,
4578 struct smb_filename *smb_dname)
4583 status = SMB_VFS_CREATE_FILE(
4586 0, /* root_dir_fid */
4587 smb_dname, /* fname */
4588 FILE_READ_ATTRIBUTES, /* access_mask */
4589 FILE_SHARE_NONE, /* share_access */
4590 FILE_CREATE, /* create_disposition*/
4591 FILE_DIRECTORY_FILE, /* create_options */
4592 FILE_ATTRIBUTE_DIRECTORY, /* file_attributes */
4593 0, /* oplock_request */
4595 0, /* allocation_size */
4596 0, /* private_flags */
4601 NULL, NULL); /* create context */
4603 if (NT_STATUS_IS_OK(status)) {
4604 close_file(req, fsp, NORMAL_CLOSE);
4610 /****************************************************************************
4611 Receive notification that one of our open files has been renamed by another
4613 ****************************************************************************/
4615 void msg_file_was_renamed(struct messaging_context *msg_ctx,
4618 struct server_id src,
4621 struct file_rename_message *msg = NULL;
4622 enum ndr_err_code ndr_err;
4624 struct smb_filename *smb_fname = NULL;
4625 struct smbd_server_connection *sconn =
4626 talloc_get_type_abort(private_data,
4627 struct smbd_server_connection);
4629 msg = talloc(talloc_tos(), struct file_rename_message);
4631 DBG_WARNING("talloc failed\n");
4635 ndr_err = ndr_pull_struct_blob_all(
4639 (ndr_pull_flags_fn_t)ndr_pull_file_rename_message);
4640 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
4641 DBG_DEBUG("ndr_pull_oplock_break_message failed: %s\n",
4642 ndr_errstr(ndr_err));
4645 if (DEBUGLEVEL >= 10) {
4646 struct server_id_buf buf;
4647 DBG_DEBUG("Got rename message from %s\n",
4648 server_id_str_buf(src, &buf));
4649 NDR_PRINT_DEBUG(file_rename_message, msg);
4652 /* stream_name must always be NULL if there is no stream. */
4653 if ((msg->stream_name != NULL) && (msg->stream_name[0] == '\0')) {
4654 msg->stream_name = NULL;
4657 smb_fname = synthetic_smb_fname(
4658 msg, msg->base_name, msg->stream_name, NULL, 0);
4659 if (smb_fname == NULL) {
4660 DBG_DEBUG("synthetic_smb_fname failed\n");
4664 fsp = file_find_dif(sconn, msg->id, msg->share_file_id);
4666 DBG_DEBUG("fsp not found\n");
4670 if (strcmp(fsp->conn->connectpath, msg->servicepath) == 0) {
4672 DBG_DEBUG("renaming file %s from %s -> %s\n",
4675 smb_fname_str_dbg(smb_fname));
4676 status = fsp_set_smb_fname(fsp, smb_fname);
4677 if (!NT_STATUS_IS_OK(status)) {
4678 DBG_DEBUG("fsp_set_smb_fname failed: %s\n",
4684 * Now we have the complete path we can work out if
4685 * this is actually within this share and adjust
4686 * newname accordingly.
4688 DBG_DEBUG("share mismatch (sharepath %s not sharepath %s) "
4689 "%s from %s -> %s\n",
4690 fsp->conn->connectpath,
4694 smb_fname_str_dbg(smb_fname));
4701 * If a main file is opened for delete, all streams need to be checked for
4702 * !FILE_SHARE_DELETE. Do this by opening with DELETE_ACCESS.
4703 * If that works, delete them all by setting the delete on close and close.
4706 static NTSTATUS open_streams_for_delete(connection_struct *conn,
4707 const struct smb_filename *smb_fname)
4709 struct stream_struct *stream_info = NULL;
4710 files_struct **streams = NULL;
4712 unsigned int i, num_streams = 0;
4713 TALLOC_CTX *frame = talloc_stackframe();
4716 status = vfs_streaminfo(conn, NULL, smb_fname, talloc_tos(),
4717 &num_streams, &stream_info);
4719 if (NT_STATUS_EQUAL(status, NT_STATUS_NOT_IMPLEMENTED)
4720 || NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
4721 DEBUG(10, ("no streams around\n"));
4723 return NT_STATUS_OK;
4726 if (!NT_STATUS_IS_OK(status)) {
4727 DEBUG(10, ("vfs_streaminfo failed: %s\n",
4728 nt_errstr(status)));
4732 DEBUG(10, ("open_streams_for_delete found %d streams\n",
4735 if (num_streams == 0) {
4737 return NT_STATUS_OK;
4740 streams = talloc_array(talloc_tos(), files_struct *, num_streams);
4741 if (streams == NULL) {
4742 DEBUG(0, ("talloc failed\n"));
4743 status = NT_STATUS_NO_MEMORY;
4747 for (i=0; i<num_streams; i++) {
4748 struct smb_filename *smb_fname_cp;
4750 if (strequal(stream_info[i].name, "::$DATA")) {
4755 smb_fname_cp = synthetic_smb_fname(talloc_tos(),
4756 smb_fname->base_name,
4757 stream_info[i].name,
4760 ~SMB_FILENAME_POSIX_PATH));
4761 if (smb_fname_cp == NULL) {
4762 status = NT_STATUS_NO_MEMORY;
4766 if (SMB_VFS_STAT(conn, smb_fname_cp) == -1) {
4767 DEBUG(10, ("Unable to stat stream: %s\n",
4768 smb_fname_str_dbg(smb_fname_cp)));
4771 status = SMB_VFS_CREATE_FILE(
4774 0, /* root_dir_fid */
4775 smb_fname_cp, /* fname */
4776 DELETE_ACCESS, /* access_mask */
4777 (FILE_SHARE_READ | /* share_access */
4778 FILE_SHARE_WRITE | FILE_SHARE_DELETE),
4779 FILE_OPEN, /* create_disposition*/
4780 0, /* create_options */
4781 FILE_ATTRIBUTE_NORMAL, /* file_attributes */
4782 0, /* oplock_request */
4784 0, /* allocation_size */
4785 NTCREATEX_OPTIONS_PRIVATE_STREAM_DELETE, /* private_flags */
4788 &streams[i], /* result */
4790 NULL, NULL); /* create context */
4792 if (!NT_STATUS_IS_OK(status)) {
4793 DEBUG(10, ("Could not open stream %s: %s\n",
4794 smb_fname_str_dbg(smb_fname_cp),
4795 nt_errstr(status)));
4797 TALLOC_FREE(smb_fname_cp);
4800 TALLOC_FREE(smb_fname_cp);
4804 * don't touch the variable "status" beyond this point :-)
4807 for (j = i-1 ; j >= 0; j--) {
4808 if (streams[j] == NULL) {
4812 DEBUG(10, ("Closing stream # %d, %s\n", j,
4813 fsp_str_dbg(streams[j])));
4814 close_file(NULL, streams[j], NORMAL_CLOSE);
4822 /*********************************************************************
4823 Create a default ACL by inheriting from the parent. If no inheritance
4824 from the parent available, don't set anything. This will leave the actual
4825 permissions the new file or directory already got from the filesystem
4826 as the NT ACL when read.
4827 *********************************************************************/
4829 static NTSTATUS inherit_new_acl(files_struct *fsp)
4831 TALLOC_CTX *frame = talloc_stackframe();
4832 struct security_descriptor *parent_desc = NULL;
4833 NTSTATUS status = NT_STATUS_OK;
4834 struct security_descriptor *psd = NULL;
4835 const struct dom_sid *owner_sid = NULL;
4836 const struct dom_sid *group_sid = NULL;
4837 uint32_t security_info_sent = (SECINFO_OWNER | SECINFO_GROUP | SECINFO_DACL);
4838 struct security_token *token = fsp->conn->session_info->security_token;
4839 bool inherit_owner =
4840 (lp_inherit_owner(SNUM(fsp->conn)) == INHERIT_OWNER_WINDOWS_AND_UNIX);
4841 bool inheritable_components = false;
4842 bool try_builtin_administrators = false;
4843 const struct dom_sid *BA_U_sid = NULL;
4844 const struct dom_sid *BA_G_sid = NULL;
4845 bool try_system = false;
4846 const struct dom_sid *SY_U_sid = NULL;
4847 const struct dom_sid *SY_G_sid = NULL;
4849 struct smb_filename *parent_dir = NULL;
4852 ok = parent_smb_fname(frame,
4858 return NT_STATUS_NO_MEMORY;
4861 status = SMB_VFS_GET_NT_ACL(fsp->conn,
4863 (SECINFO_OWNER | SECINFO_GROUP | SECINFO_DACL),
4866 if (!NT_STATUS_IS_OK(status)) {
4871 inheritable_components = sd_has_inheritable_components(parent_desc,
4872 fsp->fsp_flags.is_directory);
4874 if (!inheritable_components && !inherit_owner) {
4876 /* Nothing to inherit and not setting owner. */
4877 return NT_STATUS_OK;
4880 /* Create an inherited descriptor from the parent. */
4882 if (DEBUGLEVEL >= 10) {
4883 DEBUG(10,("inherit_new_acl: parent acl for %s is:\n",
4884 fsp_str_dbg(fsp) ));
4885 NDR_PRINT_DEBUG(security_descriptor, parent_desc);
4888 /* Inherit from parent descriptor if "inherit owner" set. */
4889 if (inherit_owner) {
4890 owner_sid = parent_desc->owner_sid;
4891 group_sid = parent_desc->group_sid;
4894 if (owner_sid == NULL) {
4895 if (security_token_has_builtin_administrators(token)) {
4896 try_builtin_administrators = true;
4897 } else if (security_token_is_system(token)) {
4898 try_builtin_administrators = true;
4903 if (group_sid == NULL &&
4904 token->num_sids == PRIMARY_GROUP_SID_INDEX)
4906 if (security_token_is_system(token)) {
4907 try_builtin_administrators = true;
4912 if (try_builtin_administrators) {
4916 ok = sids_to_unixids(&global_sid_Builtin_Administrators, 1, &ids);
4920 BA_U_sid = &global_sid_Builtin_Administrators;
4921 BA_G_sid = &global_sid_Builtin_Administrators;
4924 BA_U_sid = &global_sid_Builtin_Administrators;
4927 BA_G_sid = &global_sid_Builtin_Administrators;
4939 ok = sids_to_unixids(&global_sid_System, 1, &ids);
4943 SY_U_sid = &global_sid_System;
4944 SY_G_sid = &global_sid_System;
4947 SY_U_sid = &global_sid_System;
4950 SY_G_sid = &global_sid_System;
4958 if (owner_sid == NULL) {
4959 owner_sid = BA_U_sid;
4962 if (owner_sid == NULL) {
4963 owner_sid = SY_U_sid;
4966 if (group_sid == NULL) {
4967 group_sid = SY_G_sid;
4970 if (try_system && group_sid == NULL) {
4971 group_sid = BA_G_sid;
4974 if (owner_sid == NULL) {
4975 owner_sid = &token->sids[PRIMARY_USER_SID_INDEX];
4977 if (group_sid == NULL) {
4978 if (token->num_sids == PRIMARY_GROUP_SID_INDEX) {
4979 group_sid = &token->sids[PRIMARY_USER_SID_INDEX];
4981 group_sid = &token->sids[PRIMARY_GROUP_SID_INDEX];
4985 status = se_create_child_secdesc(frame,
4991 fsp->fsp_flags.is_directory);
4992 if (!NT_STATUS_IS_OK(status)) {
4997 /* If inheritable_components == false,
4998 se_create_child_secdesc()
4999 creates a security descriptor with a NULL dacl
5000 entry, but with SEC_DESC_DACL_PRESENT. We need
5001 to remove that flag. */
5003 if (!inheritable_components) {
5004 security_info_sent &= ~SECINFO_DACL;
5005 psd->type &= ~SEC_DESC_DACL_PRESENT;
5008 if (DEBUGLEVEL >= 10) {
5009 DEBUG(10,("inherit_new_acl: child acl for %s is:\n",
5010 fsp_str_dbg(fsp) ));
5011 NDR_PRINT_DEBUG(security_descriptor, psd);
5014 if (inherit_owner) {
5015 /* We need to be root to force this. */
5018 status = SMB_VFS_FSET_NT_ACL(fsp,
5021 if (inherit_owner) {
5029 * If we already have a lease, it must match the new file id. [MS-SMB2]
5030 * 3.3.5.9.8 speaks about INVALID_PARAMETER if an already used lease key is
5031 * used for a different file name.
5034 struct lease_match_state {
5035 /* Input parameters. */
5036 TALLOC_CTX *mem_ctx;
5037 const char *servicepath;
5038 const struct smb_filename *fname;
5041 /* Return parameters. */
5042 uint32_t num_file_ids;
5043 struct file_id *ids;
5044 NTSTATUS match_status;
5047 /*************************************************************
5048 File doesn't exist but this lease key+guid is already in use.
5050 This is only allowable in the dynamic share case where the
5051 service path must be different.
5053 There is a small race condition here in the multi-connection
5054 case where a client sends two create calls on different connections,
5055 where the file doesn't exist and one smbd creates the leases_db
5056 entry first, but this will get fixed by the multichannel cleanup
5057 when all identical client_guids get handled by a single smbd.
5058 **************************************************************/
5060 static void lease_match_parser_new_file(
5062 const struct leases_db_file *files,
5063 struct lease_match_state *state)
5067 for (i = 0; i < num_files; i++) {
5068 const struct leases_db_file *f = &files[i];
5069 if (strequal(state->servicepath, f->servicepath)) {
5070 state->match_status = NT_STATUS_INVALID_PARAMETER;
5075 /* Dynamic share case. Break leases on all other files. */
5076 state->match_status = leases_db_copy_file_ids(state->mem_ctx,
5080 if (!NT_STATUS_IS_OK(state->match_status)) {
5084 state->num_file_ids = num_files;
5085 state->match_status = NT_STATUS_OPLOCK_NOT_GRANTED;
5089 static void lease_match_parser(
5091 const struct leases_db_file *files,
5094 struct lease_match_state *state =
5095 (struct lease_match_state *)private_data;
5098 if (!state->file_existed) {
5100 * Deal with name mismatch or
5101 * possible dynamic share case separately
5102 * to make code clearer.
5104 lease_match_parser_new_file(num_files,
5111 state->match_status = NT_STATUS_OK;
5113 for (i = 0; i < num_files; i++) {
5114 const struct leases_db_file *f = &files[i];
5116 /* Everything should be the same. */
5117 if (!file_id_equal(&state->id, &f->id)) {
5118 /* This should catch all dynamic share cases. */
5119 state->match_status = NT_STATUS_OPLOCK_NOT_GRANTED;
5122 if (!strequal(f->servicepath, state->servicepath)) {
5123 state->match_status = NT_STATUS_INVALID_PARAMETER;
5126 if (!strequal(f->base_name, state->fname->base_name)) {
5127 state->match_status = NT_STATUS_INVALID_PARAMETER;
5130 if (!strequal(f->stream_name, state->fname->stream_name)) {
5131 state->match_status = NT_STATUS_INVALID_PARAMETER;
5136 if (NT_STATUS_IS_OK(state->match_status)) {
5138 * Common case - just opening another handle on a
5139 * file on a non-dynamic share.
5144 if (NT_STATUS_EQUAL(state->match_status, NT_STATUS_INVALID_PARAMETER)) {
5145 /* Mismatched path. Error back to client. */
5150 * File id mismatch. Dynamic share case NT_STATUS_OPLOCK_NOT_GRANTED.
5151 * Don't allow leases.
5154 state->match_status = leases_db_copy_file_ids(state->mem_ctx,
5158 if (!NT_STATUS_IS_OK(state->match_status)) {
5162 state->num_file_ids = num_files;
5163 state->match_status = NT_STATUS_OPLOCK_NOT_GRANTED;
5167 struct lease_match_break_state {
5168 struct messaging_context *msg_ctx;
5169 const struct smb2_lease_key *lease_key;
5177 static bool lease_match_break_fn(
5178 struct share_mode_entry *e,
5181 struct lease_match_break_state *state = private_data;
5183 uint32_t e_lease_type;
5186 stale = share_entry_stale_pid(e);
5191 equal = smb2_lease_key_equal(&e->lease_key, state->lease_key);
5196 status = leases_db_get(
5200 NULL, /* current_state */
5201 NULL, /* breaking */
5202 NULL, /* breaking_to_requested */
5203 NULL, /* breaking_to_required */
5204 &state->version, /* lease_version */
5205 &state->epoch); /* epoch */
5206 if (NT_STATUS_IS_OK(status)) {
5207 state->found_lease = true;
5209 DBG_WARNING("Could not find version/epoch: %s\n",
5213 e_lease_type = get_lease_type(e, state->id);
5214 if (e_lease_type == SMB2_LEASE_NONE) {
5217 send_break_message(state->msg_ctx, &state->id, e, SMB2_LEASE_NONE);
5220 * Windows 7 and 8 lease clients are broken in that they will
5221 * not respond to lease break requests whilst waiting for an
5222 * outstanding open request on that lease handle on the same
5223 * TCP connection, due to holding an internal inode lock.
5225 * This means we can't reschedule ourselves here, but must
5226 * return from the create.
5230 * Send the breaks and then return SMB2_LEASE_NONE in the
5231 * lease handle to cause them to acknowledge the lease
5232 * break. Consultation with Microsoft engineering confirmed
5233 * this approach is safe.
5239 static NTSTATUS lease_match(connection_struct *conn,
5240 struct smb_request *req,
5241 const struct smb2_lease_key *lease_key,
5242 const char *servicepath,
5243 const struct smb_filename *fname,
5244 uint16_t *p_version,
5247 struct smbd_server_connection *sconn = req->sconn;
5248 TALLOC_CTX *tos = talloc_tos();
5249 struct lease_match_state state = {
5251 .servicepath = servicepath,
5253 .match_status = NT_STATUS_OK
5258 state.file_existed = VALID_STAT(fname->st);
5259 if (state.file_existed) {
5260 state.id = vfs_file_id_from_sbuf(conn, &fname->st);
5263 status = leases_db_parse(&sconn->client->connections->smb2.client.guid,
5264 lease_key, lease_match_parser, &state);
5265 if (!NT_STATUS_IS_OK(status)) {
5267 * Not found or error means okay: We can make the lease pass
5269 return NT_STATUS_OK;
5271 if (!NT_STATUS_EQUAL(state.match_status, NT_STATUS_OPLOCK_NOT_GRANTED)) {
5273 * Anything but NT_STATUS_OPLOCK_NOT_GRANTED, let the caller
5276 return state.match_status;
5279 /* We have to break all existing leases. */
5280 for (i = 0; i < state.num_file_ids; i++) {
5281 struct lease_match_break_state break_state = {
5282 .msg_ctx = conn->sconn->msg_ctx,
5283 .lease_key = lease_key,
5285 struct share_mode_lock *lck;
5288 if (file_id_equal(&state.ids[i], &state.id)) {
5289 /* Don't need to break our own file. */
5293 break_state.id = state.ids[i];
5295 lck = get_existing_share_mode_lock(
5296 talloc_tos(), break_state.id);
5298 /* Race condition - file already closed. */
5302 ok = share_mode_forall_leases(
5303 lck, lease_match_break_fn, &break_state);
5305 DBG_DEBUG("share_mode_forall_leases failed\n");
5311 if (break_state.found_lease) {
5312 *p_version = break_state.version;
5313 *p_epoch = break_state.epoch;
5317 * Ensure we don't grant anything more so we
5320 return NT_STATUS_OPLOCK_NOT_GRANTED;
5324 * Wrapper around open_file_ntcreate and open_directory
5327 static NTSTATUS create_file_unixpath(connection_struct *conn,
5328 struct smb_request *req,
5329 struct smb_filename *smb_fname,
5330 uint32_t access_mask,
5331 uint32_t share_access,
5332 uint32_t create_disposition,
5333 uint32_t create_options,
5334 uint32_t file_attributes,
5335 uint32_t oplock_request,
5336 const struct smb2_lease *lease,
5337 uint64_t allocation_size,
5338 uint32_t private_flags,
5339 struct security_descriptor *sd,
5340 struct ea_list *ea_list,
5342 files_struct **result,
5345 struct smb2_lease none_lease;
5346 int info = FILE_WAS_OPENED;
5347 files_struct *base_fsp = NULL;
5348 files_struct *fsp = NULL;
5351 DBG_DEBUG("create_file_unixpath: access_mask = 0x%x "
5352 "file_attributes = 0x%x, share_access = 0x%x, "
5353 "create_disposition = 0x%x create_options = 0x%x "
5354 "oplock_request = 0x%x private_flags = 0x%x "
5355 "ea_list = %p, sd = %p, "
5357 (unsigned int)access_mask,
5358 (unsigned int)file_attributes,
5359 (unsigned int)share_access,
5360 (unsigned int)create_disposition,
5361 (unsigned int)create_options,
5362 (unsigned int)oplock_request,
5363 (unsigned int)private_flags,
5364 ea_list, sd, smb_fname_str_dbg(smb_fname));
5366 if (create_options & FILE_OPEN_BY_FILE_ID) {
5367 status = NT_STATUS_NOT_SUPPORTED;
5371 if (create_options & NTCREATEX_OPTIONS_INVALID_PARAM_MASK) {
5372 status = NT_STATUS_INVALID_PARAMETER;
5377 oplock_request |= INTERNAL_OPEN_ONLY;
5380 if (lease != NULL) {
5381 uint16_t epoch = lease->lease_epoch;
5382 uint16_t version = lease->lease_version;
5385 DBG_WARNING("Got lease on internal open\n");
5386 status = NT_STATUS_INTERNAL_ERROR;
5390 status = lease_match(conn,
5397 if (NT_STATUS_EQUAL(status, NT_STATUS_OPLOCK_NOT_GRANTED)) {
5398 /* Dynamic share file. No leases and update epoch... */
5399 none_lease = *lease;
5400 none_lease.lease_state = SMB2_LEASE_NONE;
5401 none_lease.lease_epoch = epoch;
5402 none_lease.lease_version = version;
5403 lease = &none_lease;
5404 } else if (!NT_STATUS_IS_OK(status)) {
5409 if ((conn->fs_capabilities & FILE_NAMED_STREAMS)
5410 && (access_mask & DELETE_ACCESS)
5411 && !is_ntfs_stream_smb_fname(smb_fname)) {
5413 * We can't open a file with DELETE access if any of the
5414 * streams is open without FILE_SHARE_DELETE
5416 status = open_streams_for_delete(conn, smb_fname);
5418 if (!NT_STATUS_IS_OK(status)) {
5423 if (access_mask & SEC_FLAG_SYSTEM_SECURITY) {
5426 ok = security_token_has_privilege(get_current_nttok(conn),
5429 DBG_DEBUG("open on %s failed - "
5430 "SEC_FLAG_SYSTEM_SECURITY denied.\n",
5431 smb_fname_str_dbg(smb_fname));
5432 status = NT_STATUS_PRIVILEGE_NOT_HELD;
5436 if (conn->sconn->using_smb2 &&
5437 (access_mask == SEC_FLAG_SYSTEM_SECURITY))
5440 * No other bits set. Windows SMB2 refuses this.
5441 * See smbtorture3 SMB2-SACL test.
5443 * Note this is an SMB2-only behavior,
5444 * smbtorture3 SMB1-SYSTEM-SECURITY already tests
5445 * that SMB1 allows this.
5447 status = NT_STATUS_ACCESS_DENIED;
5453 * Files or directories can't be opened DELETE_ON_CLOSE without
5455 * BUG: https://bugzilla.samba.org/show_bug.cgi?id=13358
5457 if (create_options & FILE_DELETE_ON_CLOSE) {
5458 if ((access_mask & DELETE_ACCESS) == 0) {
5459 status = NT_STATUS_INVALID_PARAMETER;
5464 if ((conn->fs_capabilities & FILE_NAMED_STREAMS)
5465 && is_ntfs_stream_smb_fname(smb_fname)
5466 && (!(private_flags & NTCREATEX_OPTIONS_PRIVATE_STREAM_DELETE))) {
5467 uint32_t base_create_disposition;
5468 struct smb_filename *smb_fname_base = NULL;
5469 uint32_t base_privflags;
5471 if (create_options & FILE_DIRECTORY_FILE) {
5472 status = NT_STATUS_NOT_A_DIRECTORY;
5476 switch (create_disposition) {
5478 base_create_disposition = FILE_OPEN;
5481 base_create_disposition = FILE_OPEN_IF;
5485 /* Create an smb_filename with stream_name == NULL. */
5486 smb_fname_base = synthetic_smb_fname(talloc_tos(),
5487 smb_fname->base_name,
5491 if (smb_fname_base == NULL) {
5492 status = NT_STATUS_NO_MEMORY;
5496 if (SMB_VFS_STAT(conn, smb_fname_base) == -1) {
5497 DEBUG(10, ("Unable to stat stream: %s\n",
5498 smb_fname_str_dbg(smb_fname_base)));
5501 * https://bugzilla.samba.org/show_bug.cgi?id=10229
5502 * We need to check if the requested access mask
5503 * could be used to open the underlying file (if
5504 * it existed), as we're passing in zero for the
5505 * access mask to the base filename.
5507 status = check_base_file_access(conn,
5511 if (!NT_STATUS_IS_OK(status)) {
5512 DEBUG(10, ("Permission check "
5513 "for base %s failed: "
5514 "%s\n", smb_fname->base_name,
5515 nt_errstr(status)));
5520 base_privflags = NTCREATEX_OPTIONS_PRIVATE_STREAM_BASEOPEN;
5522 /* Open the base file. */
5523 status = create_file_unixpath(conn, NULL, smb_fname_base, 0,
5526 | FILE_SHARE_DELETE,
5527 base_create_disposition,
5532 TALLOC_FREE(smb_fname_base);
5534 if (!NT_STATUS_IS_OK(status)) {
5535 DEBUG(10, ("create_file_unixpath for base %s failed: "
5536 "%s\n", smb_fname->base_name,
5537 nt_errstr(status)));
5540 /* we don't need the low level fd */
5545 * If it's a request for a directory open, deal with it separately.
5548 if (create_options & FILE_DIRECTORY_FILE) {
5550 if (create_options & FILE_NON_DIRECTORY_FILE) {
5551 status = NT_STATUS_INVALID_PARAMETER;
5555 /* Can't open a temp directory. IFS kit test. */
5556 if (!(file_attributes & FILE_FLAG_POSIX_SEMANTICS) &&
5557 (file_attributes & FILE_ATTRIBUTE_TEMPORARY)) {
5558 status = NT_STATUS_INVALID_PARAMETER;
5563 * We will get a create directory here if the Win32
5564 * app specified a security descriptor in the
5565 * CreateDirectory() call.
5569 status = open_directory(
5570 conn, req, smb_fname, access_mask, share_access,
5571 create_disposition, create_options, file_attributes,
5576 * Ordinary file case.
5579 status = file_new(req, conn, &fsp);
5580 if(!NT_STATUS_IS_OK(status)) {
5584 status = fsp_set_smb_fname(fsp, smb_fname);
5585 if (!NT_STATUS_IS_OK(status)) {
5591 * We're opening the stream element of a
5592 * base_fsp we already opened. Set up the
5595 fsp->base_fsp = base_fsp;
5598 if (allocation_size) {
5599 fsp->initial_allocation_size = smb_roundup(fsp->conn,
5603 status = open_file_ntcreate(conn,
5616 if(!NT_STATUS_IS_OK(status)) {
5617 file_free(req, fsp);
5621 if (NT_STATUS_EQUAL(status, NT_STATUS_FILE_IS_A_DIRECTORY)) {
5623 /* A stream open never opens a directory */
5626 status = NT_STATUS_FILE_IS_A_DIRECTORY;
5631 * Fail the open if it was explicitly a non-directory
5635 if (create_options & FILE_NON_DIRECTORY_FILE) {
5636 status = NT_STATUS_FILE_IS_A_DIRECTORY;
5641 status = open_directory(
5642 conn, req, smb_fname, access_mask,
5643 share_access, create_disposition,
5644 create_options, file_attributes,
5649 if (!NT_STATUS_IS_OK(status)) {
5653 fsp->base_fsp = base_fsp;
5655 if ((ea_list != NULL) &&
5656 ((info == FILE_WAS_CREATED) || (info == FILE_WAS_OVERWRITTEN))) {
5657 status = set_ea(conn, fsp, fsp->fsp_name, ea_list);
5658 if (!NT_STATUS_IS_OK(status)) {
5663 if (!fsp->fsp_flags.is_directory &&
5664 S_ISDIR(fsp->fsp_name->st.st_ex_mode))
5666 status = NT_STATUS_ACCESS_DENIED;
5670 /* Save the requested allocation size. */
5671 if ((info == FILE_WAS_CREATED) || (info == FILE_WAS_OVERWRITTEN)) {
5672 if ((allocation_size > (uint64_t)fsp->fsp_name->st.st_ex_size)
5673 && !(fsp->fsp_flags.is_directory))
5675 fsp->initial_allocation_size = smb_roundup(
5676 fsp->conn, allocation_size);
5677 if (vfs_allocate_file_space(
5678 fsp, fsp->initial_allocation_size) == -1) {
5679 status = NT_STATUS_DISK_FULL;
5683 fsp->initial_allocation_size = smb_roundup(
5684 fsp->conn, (uint64_t)fsp->fsp_name->st.st_ex_size);
5687 fsp->initial_allocation_size = 0;
5690 if ((info == FILE_WAS_CREATED) && lp_nt_acl_support(SNUM(conn)) &&
5691 fsp->base_fsp == NULL) {
5694 * According to the MS documentation, the only time the security
5695 * descriptor is applied to the opened file is iff we *created* the
5696 * file; an existing file stays the same.
5698 * Also, it seems (from observation) that you can open the file with
5699 * any access mask but you can still write the sd. We need to override
5700 * the granted access before we call set_sd
5701 * Patch for bug #2242 from Tom Lackemann <cessnatomny@yahoo.com>.
5704 uint32_t sec_info_sent;
5705 uint32_t saved_access_mask = fsp->access_mask;
5707 sec_info_sent = get_sec_info(sd);
5709 fsp->access_mask = FILE_GENERIC_ALL;
5711 if (sec_info_sent & (SECINFO_OWNER|
5715 status = set_sd(fsp, sd, sec_info_sent);
5718 fsp->access_mask = saved_access_mask;
5720 if (!NT_STATUS_IS_OK(status)) {
5723 } else if (lp_inherit_acls(SNUM(conn))) {
5724 /* Inherit from parent. Errors here are not fatal. */
5725 status = inherit_new_acl(fsp);
5726 if (!NT_STATUS_IS_OK(status)) {
5727 DEBUG(10,("inherit_new_acl: failed for %s with %s\n",
5729 nt_errstr(status) ));
5734 if ((conn->fs_capabilities & FILE_FILE_COMPRESSION)
5735 && (create_options & FILE_NO_COMPRESSION)
5736 && (info == FILE_WAS_CREATED)) {
5737 status = SMB_VFS_SET_COMPRESSION(conn, fsp, fsp,
5738 COMPRESSION_FORMAT_NONE);
5739 if (!NT_STATUS_IS_OK(status)) {
5740 DEBUG(1, ("failed to disable compression: %s\n",
5741 nt_errstr(status)));
5745 DEBUG(10, ("create_file_unixpath: info=%d\n", info));
5748 if (pinfo != NULL) {
5752 smb_fname->st = fsp->fsp_name->st;
5754 return NT_STATUS_OK;
5757 DEBUG(10, ("create_file_unixpath: %s\n", nt_errstr(status)));
5760 if (base_fsp && fsp->base_fsp == base_fsp) {
5762 * The close_file below will close
5767 close_file(req, fsp, ERROR_CLOSE);
5770 if (base_fsp != NULL) {
5771 close_file(req, base_fsp, ERROR_CLOSE);
5778 * Calculate the full path name given a relative fid.
5780 static NTSTATUS get_relative_fid_filename(
5781 connection_struct *conn,
5782 struct smb_request *req,
5783 uint16_t root_dir_fid,
5784 const struct smb_filename *smb_fname,
5785 struct smb_filename **smb_fname_out)
5787 files_struct *dir_fsp;
5788 char *parent_fname = NULL;
5789 char *new_base_name = NULL;
5790 uint32_t ucf_flags = ucf_flags_from_smb_request(req);
5793 if (root_dir_fid == 0 || !smb_fname) {
5794 status = NT_STATUS_INTERNAL_ERROR;
5798 dir_fsp = file_fsp(req, root_dir_fid);
5800 if (dir_fsp == NULL) {
5801 status = NT_STATUS_INVALID_HANDLE;
5805 if (is_ntfs_stream_smb_fname(dir_fsp->fsp_name)) {
5806 status = NT_STATUS_INVALID_HANDLE;
5810 if (!dir_fsp->fsp_flags.is_directory) {
5813 * Check to see if this is a mac fork of some kind.
5816 if ((conn->fs_capabilities & FILE_NAMED_STREAMS) &&
5817 is_ntfs_stream_smb_fname(smb_fname)) {
5818 status = NT_STATUS_OBJECT_PATH_NOT_FOUND;
5823 we need to handle the case when we get a
5824 relative open relative to a file and the
5825 pathname is blank - this is a reopen!
5826 (hint from demyn plantenberg)
5829 status = NT_STATUS_INVALID_HANDLE;
5833 if (ISDOT(dir_fsp->fsp_name->base_name)) {
5835 * We're at the toplevel dir, the final file name
5836 * must not contain ./, as this is filtered out
5837 * normally by srvstr_get_path and unix_convert
5838 * explicitly rejects paths containing ./.
5840 parent_fname = talloc_strdup(talloc_tos(), "");
5841 if (parent_fname == NULL) {
5842 status = NT_STATUS_NO_MEMORY;
5846 size_t dir_name_len = strlen(dir_fsp->fsp_name->base_name);
5849 * Copy in the base directory name.
5852 parent_fname = talloc_array(talloc_tos(), char,
5854 if (parent_fname == NULL) {
5855 status = NT_STATUS_NO_MEMORY;
5858 memcpy(parent_fname, dir_fsp->fsp_name->base_name,
5862 * Ensure it ends in a '/'.
5863 * We used TALLOC_SIZE +2 to add space for the '/'.
5867 && (parent_fname[dir_name_len-1] != '\\')
5868 && (parent_fname[dir_name_len-1] != '/')) {
5869 parent_fname[dir_name_len] = '/';
5870 parent_fname[dir_name_len+1] = '\0';
5874 new_base_name = talloc_asprintf(talloc_tos(), "%s%s", parent_fname,
5875 smb_fname->base_name);
5876 if (new_base_name == NULL) {
5877 status = NT_STATUS_NO_MEMORY;
5881 status = filename_convert(req,
5888 if (!NT_STATUS_IS_OK(status)) {
5893 TALLOC_FREE(parent_fname);
5894 TALLOC_FREE(new_base_name);
5898 NTSTATUS create_file_default(connection_struct *conn,
5899 struct smb_request *req,
5900 uint16_t root_dir_fid,
5901 struct smb_filename *smb_fname,
5902 uint32_t access_mask,
5903 uint32_t share_access,
5904 uint32_t create_disposition,
5905 uint32_t create_options,
5906 uint32_t file_attributes,
5907 uint32_t oplock_request,
5908 const struct smb2_lease *lease,
5909 uint64_t allocation_size,
5910 uint32_t private_flags,
5911 struct security_descriptor *sd,
5912 struct ea_list *ea_list,
5913 files_struct **result,
5915 const struct smb2_create_blobs *in_context_blobs,
5916 struct smb2_create_blobs *out_context_blobs)
5918 int info = FILE_WAS_OPENED;
5919 files_struct *fsp = NULL;
5921 bool stream_name = false;
5922 struct smb2_create_blob *posx = NULL;
5924 DBG_DEBUG("create_file: access_mask = 0x%x "
5925 "file_attributes = 0x%x, share_access = 0x%x, "
5926 "create_disposition = 0x%x create_options = 0x%x "
5927 "oplock_request = 0x%x "
5928 "private_flags = 0x%x "
5929 "root_dir_fid = 0x%x, ea_list = %p, sd = %p, "
5931 (unsigned int)access_mask,
5932 (unsigned int)file_attributes,
5933 (unsigned int)share_access,
5934 (unsigned int)create_disposition,
5935 (unsigned int)create_options,
5936 (unsigned int)oplock_request,
5937 (unsigned int)private_flags,
5938 (unsigned int)root_dir_fid,
5939 ea_list, sd, smb_fname_str_dbg(smb_fname));
5943 * Remember the absolute time of the original request
5944 * with this mid. We'll use it later to see if this
5947 get_deferred_open_message_state(req, &req->request_time, NULL);
5951 * Calculate the filename from the root_dir_if if necessary.
5954 if (root_dir_fid != 0) {
5955 struct smb_filename *smb_fname_out = NULL;
5956 status = get_relative_fid_filename(conn, req, root_dir_fid,
5957 smb_fname, &smb_fname_out);
5958 if (!NT_STATUS_IS_OK(status)) {
5961 smb_fname = smb_fname_out;
5965 * Check to see if this is a mac fork of some kind.
5968 stream_name = is_ntfs_stream_smb_fname(smb_fname);
5970 enum FAKE_FILE_TYPE fake_file_type;
5972 fake_file_type = is_fake_file(smb_fname);
5974 if (fake_file_type != FAKE_FILE_TYPE_NONE) {
5977 * Here we go! support for changing the disk quotas
5980 * We need to fake up to open this MAGIC QUOTA file
5981 * and return a valid FID.
5983 * w2k close this file directly after openening xp
5984 * also tries a QUERY_FILE_INFO on the file and then
5987 status = open_fake_file(req, conn, req->vuid,
5988 fake_file_type, smb_fname,
5990 if (!NT_STATUS_IS_OK(status)) {
5994 ZERO_STRUCT(smb_fname->st);
5998 if (!(conn->fs_capabilities & FILE_NAMED_STREAMS)) {
5999 status = NT_STATUS_OBJECT_NAME_NOT_FOUND;
6004 if (is_ntfs_default_stream_smb_fname(smb_fname)) {
6006 smb_fname->stream_name = NULL;
6007 /* We have to handle this error here. */
6008 if (create_options & FILE_DIRECTORY_FILE) {
6009 status = NT_STATUS_NOT_A_DIRECTORY;
6012 if (req != NULL && req->posix_pathnames) {
6013 ret = SMB_VFS_LSTAT(conn, smb_fname);
6015 ret = SMB_VFS_STAT(conn, smb_fname);
6018 if (ret == 0 && VALID_STAT_OF_DIR(smb_fname->st)) {
6019 status = NT_STATUS_FILE_IS_A_DIRECTORY;
6024 posx = smb2_create_blob_find(
6025 in_context_blobs, SMB2_CREATE_TAG_POSIX);
6027 uint32_t wire_mode_bits = 0;
6028 mode_t mode_bits = 0;
6029 SMB_STRUCT_STAT sbuf = { 0 };
6030 enum perm_type ptype =
6031 (create_options & FILE_DIRECTORY_FILE) ?
6032 PERM_NEW_DIR : PERM_NEW_FILE;
6034 if (posx->data.length != 4) {
6035 status = NT_STATUS_INVALID_PARAMETER;
6039 wire_mode_bits = IVAL(posx->data.data, 0);
6040 status = unix_perms_from_wire(
6041 conn, &sbuf, wire_mode_bits, ptype, &mode_bits);
6042 if (!NT_STATUS_IS_OK(status)) {
6046 * Remove type info from mode, leaving only the
6047 * permissions and setuid/gid bits.
6049 mode_bits &= ~S_IFMT;
6051 file_attributes = (FILE_FLAG_POSIX_SEMANTICS | mode_bits);
6054 status = create_file_unixpath(
6055 conn, req, smb_fname, access_mask, share_access,
6056 create_disposition, create_options, file_attributes,
6057 oplock_request, lease, allocation_size, private_flags,
6061 if (!NT_STATUS_IS_OK(status)) {
6066 DEBUG(10, ("create_file: info=%d\n", info));
6069 if (pinfo != NULL) {
6072 return NT_STATUS_OK;
6075 DEBUG(10, ("create_file: %s\n", nt_errstr(status)));
6078 close_file(req, fsp, ERROR_CLOSE);