2 Unix SMB/CIFS implementation.
3 file opening and share modes
4 Copyright (C) Andrew Tridgell 1992-1998
5 Copyright (C) Jeremy Allison 2001-2004
6 Copyright (C) Volker Lendecke 2005
7 Copyright (C) Ralph Boehme 2017
9 This program is free software; you can redistribute it and/or modify
10 it under the terms of the GNU General Public License as published by
11 the Free Software Foundation; either version 3 of the License, or
12 (at your option) any later version.
14 This program is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 GNU General Public License for more details.
19 You should have received a copy of the GNU General Public License
20 along with this program. If not, see <http://www.gnu.org/licenses/>.
24 #include "smb1_utils.h"
25 #include "system/filesys.h"
26 #include "lib/util/server_id.h"
28 #include "smbd/smbd.h"
29 #include "smbd/globals.h"
30 #include "fake_file.h"
31 #include "../libcli/security/security.h"
32 #include "../librpc/gen_ndr/ndr_security.h"
33 #include "../librpc/gen_ndr/ndr_open_files.h"
34 #include "../librpc/gen_ndr/idmap.h"
35 #include "../librpc/gen_ndr/ioctl.h"
36 #include "passdb/lookup_sid.h"
40 #include "source3/lib/dbwrap/dbwrap_watch.h"
41 #include "locking/leases_db.h"
42 #include "librpc/gen_ndr/ndr_leases_db.h"
43 #include "lib/util/time_basic.h"
45 extern const struct generic_mapping file_generic_mapping;
47 struct deferred_open_record {
48 struct smbXsrv_connection *xconn;
54 * Timer for async opens, needed because they don't use a watch on
55 * a locking.tdb record. This is currently only used for real async
56 * opens and just terminates smbd if the async open times out.
58 struct tevent_timer *te;
61 * For the samba kernel oplock case we use both a timeout and
62 * a watch on locking.tdb. This way in case it's smbd holding
63 * the kernel oplock we get directly notified for the retry
64 * once the kernel oplock is properly broken. Store the req
65 * here so that it can be timely discarded once the timer
68 struct tevent_req *watch_req;
71 /****************************************************************************
72 If the requester wanted DELETE_ACCESS and was rejected because
73 the file ACL didn't include DELETE_ACCESS, see if the parent ACL
75 ****************************************************************************/
77 static bool parent_override_delete(connection_struct *conn,
78 const struct smb_filename *smb_fname,
80 uint32_t rejected_mask)
82 if ((access_mask & DELETE_ACCESS) &&
83 (rejected_mask & DELETE_ACCESS) &&
84 can_delete_file_in_directory(conn, smb_fname)) {
90 /****************************************************************************
91 Check if we have open rights.
92 ****************************************************************************/
94 NTSTATUS smbd_check_access_rights(struct connection_struct *conn,
95 const struct smb_filename *smb_fname,
99 /* Check if we have rights to open. */
101 struct security_descriptor *sd = NULL;
102 uint32_t rejected_share_access;
103 uint32_t rejected_mask = access_mask;
104 uint32_t do_not_check_mask = 0;
106 rejected_share_access = access_mask & ~(conn->share_access);
108 if (rejected_share_access) {
109 DEBUG(10, ("smbd_check_access_rights: rejected share access 0x%x "
111 (unsigned int)access_mask,
112 smb_fname_str_dbg(smb_fname),
113 (unsigned int)rejected_share_access ));
114 return NT_STATUS_ACCESS_DENIED;
117 if (!use_privs && get_current_uid(conn) == (uid_t)0) {
118 /* I'm sorry sir, I didn't know you were root... */
119 DEBUG(10,("smbd_check_access_rights: root override "
120 "on %s. Granting 0x%x\n",
121 smb_fname_str_dbg(smb_fname),
122 (unsigned int)access_mask ));
126 if ((access_mask & DELETE_ACCESS) && !lp_acl_check_permissions(SNUM(conn))) {
127 DEBUG(10,("smbd_check_access_rights: not checking ACL "
128 "on DELETE_ACCESS on file %s. Granting 0x%x\n",
129 smb_fname_str_dbg(smb_fname),
130 (unsigned int)access_mask ));
134 if (access_mask == DELETE_ACCESS &&
135 VALID_STAT(smb_fname->st) &&
136 S_ISLNK(smb_fname->st.st_ex_mode)) {
137 /* We can always delete a symlink. */
138 DEBUG(10,("smbd_check_access_rights: not checking ACL "
139 "on DELETE_ACCESS on symlink %s.\n",
140 smb_fname_str_dbg(smb_fname) ));
144 status = SMB_VFS_GET_NT_ACL(conn, smb_fname,
147 SECINFO_DACL), talloc_tos(), &sd);
149 if (!NT_STATUS_IS_OK(status)) {
150 DEBUG(10, ("smbd_check_access_rights: Could not get acl "
152 smb_fname_str_dbg(smb_fname),
155 if (NT_STATUS_EQUAL(status, NT_STATUS_ACCESS_DENIED)) {
163 * If we can access the path to this file, by
164 * default we have FILE_READ_ATTRIBUTES from the
165 * containing directory. See the section:
166 * "Algorithm to Check Access to an Existing File"
169 * se_file_access_check() also takes care of
170 * owner WRITE_DAC and READ_CONTROL.
172 do_not_check_mask = FILE_READ_ATTRIBUTES;
175 * Samba 3.6 and earlier granted execute access even
176 * if the ACL did not contain execute rights.
177 * Samba 4.0 is more correct and checks it.
178 * The compatibilty mode allows one to skip this check
179 * to smoothen upgrades.
181 if (lp_acl_allow_execute_always(SNUM(conn))) {
182 do_not_check_mask |= FILE_EXECUTE;
185 status = se_file_access_check(sd,
186 get_current_nttok(conn),
188 (access_mask & ~do_not_check_mask),
191 DEBUG(10,("smbd_check_access_rights: file %s requesting "
192 "0x%x returning 0x%x (%s)\n",
193 smb_fname_str_dbg(smb_fname),
194 (unsigned int)access_mask,
195 (unsigned int)rejected_mask,
196 nt_errstr(status) ));
198 if (!NT_STATUS_IS_OK(status)) {
199 if (DEBUGLEVEL >= 10) {
200 DEBUG(10,("smbd_check_access_rights: acl for %s is:\n",
201 smb_fname_str_dbg(smb_fname) ));
202 NDR_PRINT_DEBUG(security_descriptor, sd);
208 if (NT_STATUS_IS_OK(status) ||
209 !NT_STATUS_EQUAL(status, NT_STATUS_ACCESS_DENIED)) {
213 /* Here we know status == NT_STATUS_ACCESS_DENIED. */
217 if ((access_mask & FILE_WRITE_ATTRIBUTES) &&
218 (rejected_mask & FILE_WRITE_ATTRIBUTES) &&
219 !lp_store_dos_attributes(SNUM(conn)) &&
220 (lp_map_readonly(SNUM(conn)) ||
221 lp_map_archive(SNUM(conn)) ||
222 lp_map_hidden(SNUM(conn)) ||
223 lp_map_system(SNUM(conn)))) {
224 rejected_mask &= ~FILE_WRITE_ATTRIBUTES;
226 DEBUG(10,("smbd_check_access_rights: "
228 "FILE_WRITE_ATTRIBUTES "
230 smb_fname_str_dbg(smb_fname)));
233 if (parent_override_delete(conn,
237 /* Were we trying to do an open
238 * for delete and didn't get DELETE
239 * access (only) ? Check if the
240 * directory allows DELETE_CHILD.
242 * http://blogs.msdn.com/oldnewthing/archive/2004/06/04/148426.aspx
245 rejected_mask &= ~DELETE_ACCESS;
247 DEBUG(10,("smbd_check_access_rights: "
251 smb_fname_str_dbg(smb_fname)));
254 if (rejected_mask != 0) {
255 return NT_STATUS_ACCESS_DENIED;
260 NTSTATUS check_parent_access(struct connection_struct *conn,
261 struct smb_filename *smb_fname,
262 uint32_t access_mask)
265 char *parent_dir = NULL;
266 struct security_descriptor *parent_sd = NULL;
267 uint32_t access_granted = 0;
268 struct smb_filename *parent_smb_fname = NULL;
269 struct share_mode_lock *lck = NULL;
270 struct file_id id = {0};
272 bool delete_on_close_set;
274 TALLOC_CTX *frame = talloc_stackframe();
276 if (!parent_dirname(frame,
277 smb_fname->base_name,
280 status = NT_STATUS_NO_MEMORY;
284 parent_smb_fname = synthetic_smb_fname(frame,
289 if (parent_smb_fname == NULL) {
290 status = NT_STATUS_NO_MEMORY;
294 if (get_current_uid(conn) == (uid_t)0) {
295 /* I'm sorry sir, I didn't know you were root... */
296 DEBUG(10,("check_parent_access: root override "
297 "on %s. Granting 0x%x\n",
298 smb_fname_str_dbg(smb_fname),
299 (unsigned int)access_mask ));
300 status = NT_STATUS_OK;
304 status = SMB_VFS_GET_NT_ACL(conn,
310 if (!NT_STATUS_IS_OK(status)) {
311 DEBUG(5,("check_parent_access: SMB_VFS_GET_NT_ACL failed for "
312 "%s with error %s\n",
319 * If we can access the path to this file, by
320 * default we have FILE_READ_ATTRIBUTES from the
321 * containing directory. See the section:
322 * "Algorithm to Check Access to an Existing File"
325 * se_file_access_check() also takes care of
326 * owner WRITE_DAC and READ_CONTROL.
328 status = se_file_access_check(parent_sd,
329 get_current_nttok(conn),
331 (access_mask & ~FILE_READ_ATTRIBUTES),
333 if(!NT_STATUS_IS_OK(status)) {
334 DEBUG(5,("check_parent_access: access check "
335 "on directory %s for "
336 "path %s for mask 0x%x returned (0x%x) %s\n",
338 smb_fname->base_name,
341 nt_errstr(status) ));
345 if (!(access_mask & (SEC_DIR_ADD_FILE | SEC_DIR_ADD_SUBDIR))) {
346 status = NT_STATUS_OK;
349 if (!lp_check_parent_directory_delete_on_close(SNUM(conn))) {
350 status = NT_STATUS_OK;
354 /* Check if the directory has delete-on-close set */
355 ret = SMB_VFS_STAT(conn, parent_smb_fname);
357 status = map_nt_error_from_unix(errno);
361 id = SMB_VFS_FILE_ID_CREATE(conn, &parent_smb_fname->st);
363 status = file_name_hash(conn, parent_smb_fname->base_name, &name_hash);
364 if (!NT_STATUS_IS_OK(status)) {
368 lck = get_existing_share_mode_lock(frame, id);
370 status = NT_STATUS_OK;
374 delete_on_close_set = is_delete_on_close_set(lck, name_hash);
375 if (delete_on_close_set) {
376 status = NT_STATUS_DELETE_PENDING;
380 status = NT_STATUS_OK;
387 /****************************************************************************
388 Ensure when opening a base file for a stream open that we have permissions
389 to do so given the access mask on the base file.
390 ****************************************************************************/
392 static NTSTATUS check_base_file_access(struct connection_struct *conn,
393 struct smb_filename *smb_fname,
394 uint32_t access_mask)
398 status = smbd_calculate_access_mask(conn, smb_fname,
402 if (!NT_STATUS_IS_OK(status)) {
403 DEBUG(10, ("smbd_calculate_access_mask "
404 "on file %s returned %s\n",
405 smb_fname_str_dbg(smb_fname),
410 if (access_mask & (FILE_WRITE_DATA|FILE_APPEND_DATA)) {
412 if (!CAN_WRITE(conn)) {
413 return NT_STATUS_ACCESS_DENIED;
415 dosattrs = dos_mode(conn, smb_fname);
416 if (IS_DOS_READONLY(dosattrs)) {
417 return NT_STATUS_ACCESS_DENIED;
421 return smbd_check_access_rights(conn,
427 /****************************************************************************
428 Handle differing symlink errno's
429 ****************************************************************************/
431 static int link_errno_convert(int err)
433 #if defined(ENOTSUP) && defined(OSF1)
434 /* handle special Tru64 errno */
435 if (err == ENOTSUP) {
440 /* fix broken NetBSD errno */
445 /* fix broken FreeBSD errno */
452 static int non_widelink_open(struct connection_struct *conn,
453 const struct smb_filename *conn_rootdir_fname,
455 struct smb_filename *smb_fname,
458 unsigned int link_depth);
460 /****************************************************************************
461 Follow a symlink in userspace.
462 ****************************************************************************/
464 static int process_symlink_open(struct connection_struct *conn,
465 const struct smb_filename *conn_rootdir_fname,
467 struct smb_filename *smb_fname,
470 unsigned int link_depth)
473 char *link_target = NULL;
474 struct smb_filename target_fname = {0};
476 struct smb_filename *oldwd_fname = NULL;
477 size_t rootdir_len = 0;
478 struct smb_filename *resolved_fname = NULL;
479 char *resolved_name = NULL;
480 bool matched = false;
484 * Ensure we don't get stuck in a symlink loop.
487 if (link_depth >= 20) {
492 /* Allocate space for the link target. */
493 link_target = talloc_array(talloc_tos(), char, PATH_MAX);
494 if (link_target == NULL) {
499 /* Read the link target. */
500 link_len = SMB_VFS_READLINKAT(conn,
505 if (link_len == -1) {
509 /* Ensure it's at least null terminated. */
510 link_target[link_len] = '\0';
511 target_fname = (struct smb_filename){ .base_name = link_target };
513 /* Convert to an absolute path. */
514 resolved_fname = SMB_VFS_REALPATH(conn, talloc_tos(), &target_fname);
515 if (resolved_fname == NULL) {
518 resolved_name = resolved_fname->base_name;
521 * We know conn_rootdir starts with '/' and
522 * does not end in '/'. FIXME ! Should we
525 rootdir_len = strlen(conn_rootdir_fname->base_name);
527 matched = (strncmp(conn_rootdir_fname->base_name,
536 * Turn into a path relative to the share root.
538 if (resolved_name[rootdir_len] == '\0') {
539 /* Link to the root of the share. */
540 TALLOC_FREE(smb_fname->base_name);
541 smb_fname->base_name = talloc_strdup(smb_fname, ".");
542 } else if (resolved_name[rootdir_len] == '/') {
543 TALLOC_FREE(smb_fname->base_name);
544 smb_fname->base_name = talloc_strdup(smb_fname,
545 &resolved_name[rootdir_len+1]);
551 if (smb_fname->base_name == NULL) {
556 oldwd_fname = vfs_GetWd(talloc_tos(), conn);
557 if (oldwd_fname == NULL) {
561 /* Ensure we operate from the root of the share. */
562 if (vfs_ChDir(conn, conn_rootdir_fname) == -1) {
566 /* And do it all again.. */
567 fd = non_widelink_open(conn,
580 TALLOC_FREE(resolved_fname);
581 TALLOC_FREE(link_target);
582 if (oldwd_fname != NULL) {
583 int ret = vfs_ChDir(conn, oldwd_fname);
585 smb_panic("unable to get back to old directory\n");
587 TALLOC_FREE(oldwd_fname);
589 if (saved_errno != 0) {
595 /****************************************************************************
597 ****************************************************************************/
599 static int non_widelink_open(struct connection_struct *conn,
600 const struct smb_filename *conn_rootdir_fname,
602 struct smb_filename *smb_fname,
605 unsigned int link_depth)
609 struct smb_filename *smb_fname_rel = NULL;
611 struct smb_filename *oldwd_fname = NULL;
612 char *parent_dir = NULL;
613 struct smb_filename parent_dir_fname = {0};
614 const char *final_component = NULL;
615 bool is_directory = false;
619 if (flags & O_DIRECTORY) {
625 parent_dir = talloc_strdup(talloc_tos(), smb_fname->base_name);
626 if (parent_dir == NULL) {
631 final_component = ".";
633 ok = parent_dirname(talloc_tos(),
634 smb_fname->base_name,
643 parent_dir_fname = (struct smb_filename) { .base_name = parent_dir };
645 oldwd_fname = vfs_GetWd(talloc_tos(), conn);
646 if (oldwd_fname == NULL) {
650 /* Pin parent directory in place. */
651 if (vfs_ChDir(conn, &parent_dir_fname) == -1) {
655 smb_fname_rel = synthetic_smb_fname(talloc_tos(),
657 smb_fname->stream_name,
660 if (smb_fname_rel == NULL) {
661 saved_errno = ENOMEM;
665 /* Ensure the relative path is below the share. */
666 status = check_reduced_name(conn, &parent_dir_fname, smb_fname_rel);
667 if (!NT_STATUS_IS_OK(status)) {
668 saved_errno = map_errno_from_nt_status(status);
675 struct smb_filename *tmp_name = fsp->fsp_name;
676 fsp->fsp_name = smb_fname_rel;
677 fd = SMB_VFS_OPEN(conn, smb_fname_rel, fsp, flags, mode);
678 fsp->fsp_name = tmp_name;
682 saved_errno = link_errno_convert(errno);
684 * Trying to open a symlink to a directory with O_NOFOLLOW and
685 * O_DIRECTORY can return either of ELOOP and ENOTDIR. So
686 * ENOTDIR really means: might be a symlink, but we're not sure.
687 * In this case, we just assume there's a symlink. If we were
688 * wrong, process_symlink_open() will return EINVAL. We check
689 * this below, and fall back to returning the initial
692 * BUG: https://bugzilla.samba.org/show_bug.cgi?id=12860
694 if (saved_errno == ELOOP || saved_errno == ENOTDIR) {
695 if (fsp->posix_flags & FSP_POSIX_FLAGS_OPEN) {
696 /* Never follow symlinks on posix open. */
699 if (!lp_follow_symlinks(SNUM(conn))) {
700 /* Explicitly no symlinks. */
704 * We may have a symlink. Follow in userspace
705 * to ensure it's under the share definition.
707 fd = process_symlink_open(conn,
715 if (saved_errno == ENOTDIR &&
718 * O_DIRECTORY on neither a directory,
719 * nor a symlink. Just return
720 * saved_errno from initial open()
725 link_errno_convert(errno);
732 TALLOC_FREE(parent_dir);
733 TALLOC_FREE(smb_fname_rel);
735 if (oldwd_fname != NULL) {
736 int ret = vfs_ChDir(conn, oldwd_fname);
738 smb_panic("unable to get back to old directory\n");
740 TALLOC_FREE(oldwd_fname);
742 if (saved_errno != 0) {
748 /****************************************************************************
749 fd support routines - attempt to do a dos_open.
750 ****************************************************************************/
752 NTSTATUS fd_open(struct connection_struct *conn,
757 struct smb_filename *smb_fname = fsp->fsp_name;
758 NTSTATUS status = NT_STATUS_OK;
761 * Never follow symlinks on a POSIX client. The
762 * client should be doing this.
765 if ((fsp->posix_flags & FSP_POSIX_FLAGS_OPEN) || !lp_follow_symlinks(SNUM(conn))) {
769 /* Ensure path is below share definition. */
770 if (!lp_widelinks(SNUM(conn))) {
771 struct smb_filename *conn_rootdir_fname = NULL;
772 const char *conn_rootdir = SMB_VFS_CONNECTPATH(conn,
776 if (conn_rootdir == NULL) {
777 return NT_STATUS_NO_MEMORY;
779 conn_rootdir_fname = synthetic_smb_fname(talloc_tos(),
784 if (conn_rootdir_fname == NULL) {
785 return NT_STATUS_NO_MEMORY;
789 * Only follow symlinks within a share
792 fsp->fh->fd = non_widelink_open(conn,
799 if (fsp->fh->fd == -1) {
802 TALLOC_FREE(conn_rootdir_fname);
803 if (saved_errno != 0) {
807 fsp->fh->fd = SMB_VFS_OPEN(conn, smb_fname, fsp, flags, mode);
810 if (fsp->fh->fd == -1) {
811 int posix_errno = link_errno_convert(errno);
812 status = map_nt_error_from_unix(posix_errno);
813 if (errno == EMFILE) {
814 static time_t last_warned = 0L;
816 if (time((time_t *) NULL) > last_warned) {
817 DEBUG(0,("Too many open files, unable "
818 "to open more! smbd's max "
820 lp_max_open_files()));
821 last_warned = time((time_t *) NULL);
827 DEBUG(10,("fd_open: name %s, flags = 0%o mode = 0%o, fd = %d. %s\n",
828 smb_fname_str_dbg(smb_fname), flags, (int)mode, fsp->fh->fd,
829 (fsp->fh->fd == -1) ? strerror(errno) : "" ));
834 /****************************************************************************
835 Close the file associated with a fsp.
836 ****************************************************************************/
838 NTSTATUS fd_close(files_struct *fsp)
845 if (fsp->fh->fd == -1) {
847 * Either a directory where the dptr_CloseDir() already closed
848 * the fd or a stat open.
852 if (fsp->fh->ref_count > 1) {
853 return NT_STATUS_OK; /* Shared handle. Only close last reference. */
856 ret = SMB_VFS_CLOSE(fsp);
859 return map_nt_error_from_unix(errno);
864 /****************************************************************************
865 Change the ownership of a file to that of the parent directory.
866 Do this by fd if possible.
867 ****************************************************************************/
869 void change_file_owner_to_parent(connection_struct *conn,
870 const char *inherit_from_dir,
873 struct smb_filename *smb_fname_parent;
876 smb_fname_parent = synthetic_smb_fname(talloc_tos(),
881 if (smb_fname_parent == NULL) {
885 ret = SMB_VFS_STAT(conn, smb_fname_parent);
887 DEBUG(0,("change_file_owner_to_parent: failed to stat parent "
888 "directory %s. Error was %s\n",
889 smb_fname_str_dbg(smb_fname_parent),
891 TALLOC_FREE(smb_fname_parent);
895 if (smb_fname_parent->st.st_ex_uid == fsp->fsp_name->st.st_ex_uid) {
896 /* Already this uid - no need to change. */
897 DEBUG(10,("change_file_owner_to_parent: file %s "
898 "is already owned by uid %d\n",
900 (int)fsp->fsp_name->st.st_ex_uid ));
901 TALLOC_FREE(smb_fname_parent);
906 ret = SMB_VFS_FCHOWN(fsp, smb_fname_parent->st.st_ex_uid, (gid_t)-1);
909 DEBUG(0,("change_file_owner_to_parent: failed to fchown "
910 "file %s to parent directory uid %u. Error "
911 "was %s\n", fsp_str_dbg(fsp),
912 (unsigned int)smb_fname_parent->st.st_ex_uid,
915 DEBUG(10,("change_file_owner_to_parent: changed new file %s to "
916 "parent directory uid %u.\n", fsp_str_dbg(fsp),
917 (unsigned int)smb_fname_parent->st.st_ex_uid));
918 /* Ensure the uid entry is updated. */
919 fsp->fsp_name->st.st_ex_uid = smb_fname_parent->st.st_ex_uid;
922 TALLOC_FREE(smb_fname_parent);
925 static NTSTATUS change_dir_owner_to_parent(connection_struct *conn,
926 const char *inherit_from_dir,
927 struct smb_filename *smb_dname,
928 SMB_STRUCT_STAT *psbuf)
930 struct smb_filename *smb_fname_parent;
931 struct smb_filename *smb_fname_cwd = NULL;
932 struct smb_filename *saved_dir_fname = NULL;
933 TALLOC_CTX *ctx = talloc_tos();
934 NTSTATUS status = NT_STATUS_OK;
937 smb_fname_parent = synthetic_smb_fname(ctx,
942 if (smb_fname_parent == NULL) {
943 return NT_STATUS_NO_MEMORY;
946 ret = SMB_VFS_STAT(conn, smb_fname_parent);
948 status = map_nt_error_from_unix(errno);
949 DEBUG(0,("change_dir_owner_to_parent: failed to stat parent "
950 "directory %s. Error was %s\n",
951 smb_fname_str_dbg(smb_fname_parent),
956 /* We've already done an lstat into psbuf, and we know it's a
957 directory. If we can cd into the directory and the dev/ino
958 are the same then we can safely chown without races as
959 we're locking the directory in place by being in it. This
960 should work on any UNIX (thanks tridge :-). JRA.
963 saved_dir_fname = vfs_GetWd(ctx,conn);
964 if (!saved_dir_fname) {
965 status = map_nt_error_from_unix(errno);
966 DEBUG(0,("change_dir_owner_to_parent: failed to get "
967 "current working directory. Error was %s\n",
972 /* Chdir into the new path. */
973 if (vfs_ChDir(conn, smb_dname) == -1) {
974 status = map_nt_error_from_unix(errno);
975 DEBUG(0,("change_dir_owner_to_parent: failed to change "
976 "current working directory to %s. Error "
977 "was %s\n", smb_dname->base_name, strerror(errno) ));
981 smb_fname_cwd = synthetic_smb_fname(ctx, ".", NULL, NULL, 0);
982 if (smb_fname_cwd == NULL) {
983 status = NT_STATUS_NO_MEMORY;
987 ret = SMB_VFS_STAT(conn, smb_fname_cwd);
989 status = map_nt_error_from_unix(errno);
990 DEBUG(0,("change_dir_owner_to_parent: failed to stat "
991 "directory '.' (%s) Error was %s\n",
992 smb_dname->base_name, strerror(errno)));
996 /* Ensure we're pointing at the same place. */
997 if (smb_fname_cwd->st.st_ex_dev != psbuf->st_ex_dev ||
998 smb_fname_cwd->st.st_ex_ino != psbuf->st_ex_ino) {
999 DEBUG(0,("change_dir_owner_to_parent: "
1000 "device/inode on directory %s changed. "
1001 "Refusing to chown !\n",
1002 smb_dname->base_name ));
1003 status = NT_STATUS_ACCESS_DENIED;
1007 if (smb_fname_parent->st.st_ex_uid == smb_fname_cwd->st.st_ex_uid) {
1008 /* Already this uid - no need to change. */
1009 DEBUG(10,("change_dir_owner_to_parent: directory %s "
1010 "is already owned by uid %d\n",
1011 smb_dname->base_name,
1012 (int)smb_fname_cwd->st.st_ex_uid ));
1013 status = NT_STATUS_OK;
1018 ret = SMB_VFS_LCHOWN(conn,
1020 smb_fname_parent->st.st_ex_uid,
1024 status = map_nt_error_from_unix(errno);
1025 DEBUG(10,("change_dir_owner_to_parent: failed to chown "
1026 "directory %s to parent directory uid %u. "
1028 smb_dname->base_name,
1029 (unsigned int)smb_fname_parent->st.st_ex_uid,
1032 DEBUG(10,("change_dir_owner_to_parent: changed ownership of new "
1033 "directory %s to parent directory uid %u.\n",
1034 smb_dname->base_name,
1035 (unsigned int)smb_fname_parent->st.st_ex_uid ));
1036 /* Ensure the uid entry is updated. */
1037 psbuf->st_ex_uid = smb_fname_parent->st.st_ex_uid;
1041 vfs_ChDir(conn, saved_dir_fname);
1043 TALLOC_FREE(saved_dir_fname);
1044 TALLOC_FREE(smb_fname_parent);
1045 TALLOC_FREE(smb_fname_cwd);
1049 /****************************************************************************
1050 Open a file - returning a guaranteed ATOMIC indication of if the
1051 file was created or not.
1052 ****************************************************************************/
1054 static NTSTATUS fd_open_atomic(struct connection_struct *conn,
1060 NTSTATUS status = NT_STATUS_UNSUCCESSFUL;
1061 NTSTATUS retry_status;
1062 bool file_existed = VALID_STAT(fsp->fsp_name->st);
1065 if (!(flags & O_CREAT)) {
1067 * We're not creating the file, just pass through.
1069 status = fd_open(conn, fsp, flags, mode);
1070 *file_created = false;
1074 if (flags & O_EXCL) {
1076 * Fail if already exists, just pass through.
1078 status = fd_open(conn, fsp, flags, mode);
1081 * Here we've opened with O_CREAT|O_EXCL. If that went
1082 * NT_STATUS_OK, we *know* we created this file.
1084 *file_created = NT_STATUS_IS_OK(status);
1090 * Now it gets tricky. We have O_CREAT, but not O_EXCL.
1091 * To know absolutely if we created the file or not,
1092 * we can never call O_CREAT without O_EXCL. So if
1093 * we think the file existed, try without O_CREAT|O_EXCL.
1094 * If we think the file didn't exist, try with
1097 * The big problem here is dangling symlinks. Opening
1098 * without O_NOFOLLOW means both bad symlink
1099 * and missing path return -1, ENOENT from open(). As POSIX
1100 * is pathname based it's not possible to tell
1101 * the difference between these two cases in a
1102 * non-racy way, so change to try only two attempts before
1105 * We don't have this problem for the O_NOFOLLOW
1106 * case as it just returns NT_STATUS_OBJECT_PATH_NOT_FOUND
1107 * mapped from the ELOOP POSIX error.
1111 curr_flags = flags & ~(O_CREAT);
1112 retry_status = NT_STATUS_OBJECT_NAME_NOT_FOUND;
1114 curr_flags = flags | O_EXCL;
1115 retry_status = NT_STATUS_OBJECT_NAME_COLLISION;
1118 status = fd_open(conn, fsp, curr_flags, mode);
1119 if (NT_STATUS_IS_OK(status)) {
1120 *file_created = !file_existed;
1121 return NT_STATUS_OK;
1123 if (NT_STATUS_EQUAL(status, retry_status)) {
1125 file_existed = !file_existed;
1127 DBG_DEBUG("File %s %s. Retry.\n",
1129 file_existed ? "existed" : "did not exist");
1132 curr_flags = flags & ~(O_CREAT);
1134 curr_flags = flags | O_EXCL;
1137 status = fd_open(conn, fsp, curr_flags, mode);
1140 *file_created = (NT_STATUS_IS_OK(status) && !file_existed);
1144 /****************************************************************************
1146 ****************************************************************************/
1148 static NTSTATUS open_file(files_struct *fsp,
1149 connection_struct *conn,
1150 struct smb_request *req,
1151 const char *parent_dir,
1154 uint32_t access_mask, /* client requested access mask. */
1155 uint32_t open_access_mask, /* what we're actually using in the open. */
1156 bool *p_file_created)
1158 struct smb_filename *smb_fname = fsp->fsp_name;
1159 NTSTATUS status = NT_STATUS_OK;
1160 int accmode = (flags & O_ACCMODE);
1161 int local_flags = flags;
1162 bool file_existed = VALID_STAT(fsp->fsp_name->st);
1167 /* Check permissions */
1170 * This code was changed after seeing a client open request
1171 * containing the open mode of (DENY_WRITE/read-only) with
1172 * the 'create if not exist' bit set. The previous code
1173 * would fail to open the file read only on a read-only share
1174 * as it was checking the flags parameter directly against O_RDONLY,
1175 * this was failing as the flags parameter was set to O_RDONLY|O_CREAT.
1179 if (!CAN_WRITE(conn)) {
1180 /* It's a read-only share - fail if we wanted to write. */
1181 if(accmode != O_RDONLY || (flags & O_TRUNC) || (flags & O_APPEND)) {
1182 DEBUG(3,("Permission denied opening %s\n",
1183 smb_fname_str_dbg(smb_fname)));
1184 return NT_STATUS_ACCESS_DENIED;
1186 if (flags & O_CREAT) {
1187 /* We don't want to write - but we must make sure that
1188 O_CREAT doesn't create the file if we have write
1189 access into the directory.
1191 flags &= ~(O_CREAT|O_EXCL);
1192 local_flags &= ~(O_CREAT|O_EXCL);
1197 * This little piece of insanity is inspired by the
1198 * fact that an NT client can open a file for O_RDONLY,
1199 * but set the create disposition to FILE_EXISTS_TRUNCATE.
1200 * If the client *can* write to the file, then it expects to
1201 * truncate the file, even though it is opening for readonly.
1202 * Quicken uses this stupid trick in backup file creation...
1203 * Thanks *greatly* to "David W. Chapman Jr." <dwcjr@inethouston.net>
1204 * for helping track this one down. It didn't bite us in 2.0.x
1205 * as we always opened files read-write in that release. JRA.
1208 if ((accmode == O_RDONLY) && ((flags & O_TRUNC) == O_TRUNC)) {
1209 DEBUG(10,("open_file: truncate requested on read-only open "
1210 "for file %s\n", smb_fname_str_dbg(smb_fname)));
1211 local_flags = (flags & ~O_ACCMODE)|O_RDWR;
1214 if ((open_access_mask & (FILE_READ_DATA|FILE_WRITE_DATA|
1215 FILE_APPEND_DATA|FILE_EXECUTE|
1216 WRITE_DAC_ACCESS|WRITE_OWNER_ACCESS|
1217 READ_CONTROL_ACCESS))||
1218 (!file_existed && (local_flags & O_CREAT)) ||
1219 ((local_flags & O_TRUNC) == O_TRUNC) ) {
1223 #if defined(O_NONBLOCK) && defined(S_ISFIFO)
1225 * We would block on opening a FIFO with no one else on the
1226 * other end. Do what we used to do and add O_NONBLOCK to the
1230 if (file_existed && S_ISFIFO(smb_fname->st.st_ex_mode)) {
1231 local_flags &= ~O_TRUNC; /* Can't truncate a FIFO. */
1232 local_flags |= O_NONBLOCK;
1236 /* Don't create files with Microsoft wildcard characters. */
1237 if (fsp->base_fsp) {
1239 * wildcard characters are allowed in stream names
1240 * only test the basefilename
1242 wild = fsp->base_fsp->fsp_name->base_name;
1244 wild = smb_fname->base_name;
1246 if ((local_flags & O_CREAT) && !file_existed &&
1247 !(fsp->posix_flags & FSP_POSIX_FLAGS_PATHNAMES) &&
1248 ms_has_wild(wild)) {
1249 return NT_STATUS_OBJECT_NAME_INVALID;
1252 /* Can we access this file ? */
1253 if (!fsp->base_fsp) {
1254 /* Only do this check on non-stream open. */
1256 status = smbd_check_access_rights(conn,
1261 if (!NT_STATUS_IS_OK(status)) {
1262 DEBUG(10, ("open_file: "
1263 "smbd_check_access_rights "
1264 "on file %s returned %s\n",
1265 smb_fname_str_dbg(smb_fname),
1266 nt_errstr(status)));
1269 if (!NT_STATUS_IS_OK(status) &&
1270 !NT_STATUS_EQUAL(status,
1271 NT_STATUS_OBJECT_NAME_NOT_FOUND))
1276 if (NT_STATUS_EQUAL(status,
1277 NT_STATUS_OBJECT_NAME_NOT_FOUND))
1279 DEBUG(10, ("open_file: "
1280 "file %s vanished since we "
1281 "checked for existence.\n",
1282 smb_fname_str_dbg(smb_fname)));
1283 file_existed = false;
1284 SET_STAT_INVALID(fsp->fsp_name->st);
1288 if (!file_existed) {
1289 if (!(local_flags & O_CREAT)) {
1290 /* File didn't exist and no O_CREAT. */
1291 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
1294 status = check_parent_access(conn,
1297 if (!NT_STATUS_IS_OK(status)) {
1298 DEBUG(10, ("open_file: "
1299 "check_parent_access on "
1300 "file %s returned %s\n",
1301 smb_fname_str_dbg(smb_fname),
1302 nt_errstr(status) ));
1309 * Actually do the open - if O_TRUNC is needed handle it
1310 * below under the share mode lock.
1312 status = fd_open_atomic(conn, fsp, local_flags & ~O_TRUNC,
1313 unx_mode, p_file_created);
1314 if (!NT_STATUS_IS_OK(status)) {
1315 DEBUG(3,("Error opening file %s (%s) (local_flags=%d) "
1316 "(flags=%d)\n", smb_fname_str_dbg(smb_fname),
1317 nt_errstr(status),local_flags,flags));
1321 if (local_flags & O_NONBLOCK) {
1323 * GPFS can return ETIMEDOUT for pread on
1324 * nonblocking file descriptors when files
1325 * migrated to tape need to be recalled. I
1326 * could imagine this happens elsewhere
1327 * too. With blocking file descriptors this
1330 ret = vfs_set_blocking(fsp, true);
1332 status = map_nt_error_from_unix(errno);
1333 DBG_WARNING("Could not set fd to blocking: "
1334 "%s\n", strerror(errno));
1340 ret = SMB_VFS_FSTAT(fsp, &smb_fname->st);
1342 /* If we have an fd, this stat should succeed. */
1343 DEBUG(0,("Error doing fstat on open file %s "
1345 smb_fname_str_dbg(smb_fname),
1347 status = map_nt_error_from_unix(errno);
1352 if (*p_file_created) {
1353 /* We created this file. */
1355 bool need_re_stat = false;
1356 /* Do all inheritance work after we've
1357 done a successful fstat call and filled
1358 in the stat struct in fsp->fsp_name. */
1360 /* Inherit the ACL if required */
1361 if (lp_inherit_permissions(SNUM(conn))) {
1362 inherit_access_posix_acl(conn, parent_dir,
1365 need_re_stat = true;
1368 /* Change the owner if required. */
1369 if (lp_inherit_owner(SNUM(conn)) != INHERIT_OWNER_NO) {
1370 change_file_owner_to_parent(conn, parent_dir,
1372 need_re_stat = true;
1376 ret = SMB_VFS_FSTAT(fsp, &smb_fname->st);
1377 /* If we have an fd, this stat should succeed. */
1379 DEBUG(0,("Error doing fstat on open file %s "
1381 smb_fname_str_dbg(smb_fname),
1386 notify_fname(conn, NOTIFY_ACTION_ADDED,
1387 FILE_NOTIFY_CHANGE_FILE_NAME,
1388 smb_fname->base_name);
1391 fsp->fh->fd = -1; /* What we used to call a stat open. */
1392 if (!file_existed) {
1393 /* File must exist for a stat open. */
1394 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
1397 status = smbd_check_access_rights(conn,
1402 if (NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND) &&
1403 (fsp->posix_flags & FSP_POSIX_FLAGS_OPEN) &&
1404 S_ISLNK(smb_fname->st.st_ex_mode)) {
1405 /* This is a POSIX stat open for delete
1406 * or rename on a symlink that points
1407 * nowhere. Allow. */
1408 DEBUG(10,("open_file: allowing POSIX "
1409 "open on bad symlink %s\n",
1410 smb_fname_str_dbg(smb_fname)));
1411 status = NT_STATUS_OK;
1414 if (!NT_STATUS_IS_OK(status)) {
1415 DEBUG(10,("open_file: "
1416 "smbd_check_access_rights on file "
1418 smb_fname_str_dbg(smb_fname),
1419 nt_errstr(status) ));
1425 * POSIX allows read-only opens of directories. We don't
1426 * want to do this (we use a different code path for this)
1427 * so catch a directory open and return an EISDIR. JRA.
1430 if(S_ISDIR(smb_fname->st.st_ex_mode)) {
1433 return NT_STATUS_FILE_IS_A_DIRECTORY;
1436 fsp->file_id = vfs_file_id_from_sbuf(conn, &smb_fname->st);
1437 fsp->vuid = req ? req->vuid : UID_FIELD_INVALID;
1438 fsp->file_pid = req ? req->smbpid : 0;
1439 fsp->can_lock = True;
1440 fsp->can_read = ((access_mask & FILE_READ_DATA) != 0);
1443 ((access_mask & (FILE_WRITE_DATA | FILE_APPEND_DATA)) != 0);
1444 fsp->print_file = NULL;
1445 fsp->modified = False;
1446 fsp->sent_oplock_break = NO_BREAK_SENT;
1447 fsp->is_directory = False;
1448 if (conn->aio_write_behind_list &&
1449 is_in_path(smb_fname->base_name, conn->aio_write_behind_list,
1450 conn->case_sensitive)) {
1451 fsp->aio_write_behind = True;
1454 DEBUG(2,("%s opened file %s read=%s write=%s (numopen=%d)\n",
1455 conn->session_info->unix_info->unix_name,
1456 smb_fname_str_dbg(smb_fname),
1457 BOOLSTR(fsp->can_read), BOOLSTR(fsp->can_write),
1458 conn->num_files_open));
1461 return NT_STATUS_OK;
1464 static bool mask_conflict(
1465 uint32_t new_access,
1466 uint32_t existing_access,
1467 uint32_t access_mask,
1468 uint32_t new_sharemode,
1469 uint32_t existing_sharemode,
1470 uint32_t sharemode_mask)
1472 bool want_access = (new_access & access_mask);
1473 bool allow_existing = (existing_sharemode & sharemode_mask);
1474 bool have_access = (existing_access & access_mask);
1475 bool allow_new = (new_sharemode & sharemode_mask);
1477 if (want_access && !allow_existing) {
1478 DBG_DEBUG("Access request 0x%"PRIx32"/0x%"PRIx32" conflicts "
1479 "with existing sharemode 0x%"PRIx32"/0x%"PRIx32"\n",
1486 if (have_access && !allow_new) {
1487 DBG_DEBUG("Sharemode request 0x%"PRIx32"/0x%"PRIx32" conflicts "
1488 "with existing access 0x%"PRIx32"/0x%"PRIx32"\n",
1498 /****************************************************************************
1499 Check if we can open a file with a share mode.
1500 Returns True if conflict, False if not.
1501 ****************************************************************************/
1503 static bool share_conflict(uint32_t e_access_mask,
1504 uint32_t e_share_access,
1505 uint32_t access_mask,
1506 uint32_t share_access)
1508 const uint32_t conflicting_access =
1516 DBG_DEBUG("existing access_mask = 0x%"PRIx32", "
1517 "existing share access = 0x%"PRIx32", "
1518 "access_mask = 0x%"PRIx32", "
1519 "share_access = 0x%"PRIx32"\n",
1525 if ((e_access_mask & conflicting_access) == 0) {
1526 DBG_DEBUG("No conflict due to "
1527 "existing access_mask = 0x%"PRIx32"\n",
1531 if ((access_mask & conflicting_access) == 0) {
1532 DBG_DEBUG("No conflict due to access_mask = 0x%"PRIx32"\n",
1537 conflict = mask_conflict(
1538 access_mask, e_access_mask, FILE_WRITE_DATA | FILE_APPEND_DATA,
1539 share_access, e_share_access, FILE_SHARE_WRITE);
1540 conflict |= mask_conflict(
1541 access_mask, e_access_mask, FILE_READ_DATA | FILE_EXECUTE,
1542 share_access, e_share_access, FILE_SHARE_READ);
1543 conflict |= mask_conflict(
1544 access_mask, e_access_mask, DELETE_ACCESS,
1545 share_access, e_share_access, FILE_SHARE_DELETE);
1547 DBG_DEBUG("conflict=%s\n", conflict ? "true" : "false");
1551 #if defined(DEVELOPER)
1553 struct validate_my_share_entries_state {
1554 struct smbd_server_connection *sconn;
1556 struct server_id self;
1559 static bool validate_my_share_entries_fn(
1560 struct share_mode_entry *e,
1564 struct validate_my_share_entries_state *state = private_data;
1567 if (!server_id_equal(&state->self, &e->pid)) {
1571 if (e->op_mid == 0) {
1572 /* INTERNAL_OPEN_ONLY */
1576 fsp = file_find_dif(state->sconn, state->fid, e->share_file_id);
1578 DBG_ERR("PANIC : %s\n",
1579 share_mode_str(talloc_tos(), 0, &state->fid, e));
1580 smb_panic("validate_my_share_entries: Cannot match a "
1581 "share entry with an open file\n");
1584 if (((uint16_t)fsp->oplock_type) != e->op_type) {
1593 DBG_ERR("validate_my_share_entries: PANIC : %s\n",
1594 share_mode_str(talloc_tos(), 0, &state->fid, e));
1595 str = talloc_asprintf(talloc_tos(),
1596 "validate_my_share_entries: "
1597 "file %s, oplock_type = 0x%x, op_type = 0x%x\n",
1598 fsp->fsp_name->base_name,
1599 (unsigned int)fsp->oplock_type,
1600 (unsigned int)e->op_type);
1608 bool is_stat_open(uint32_t access_mask)
1610 const uint32_t stat_open_bits =
1611 (SYNCHRONIZE_ACCESS|
1612 FILE_READ_ATTRIBUTES|
1613 FILE_WRITE_ATTRIBUTES);
1615 return (((access_mask & stat_open_bits) != 0) &&
1616 ((access_mask & ~stat_open_bits) == 0));
1619 struct has_delete_on_close_state {
1623 static bool has_delete_on_close_fn(
1624 struct share_mode_entry *e,
1628 struct has_delete_on_close_state *state = private_data;
1629 state->ret = !share_entry_stale_pid(e);
1633 static bool has_delete_on_close(struct share_mode_lock *lck,
1636 struct has_delete_on_close_state state = { .ret = false };
1639 if (!is_delete_on_close_set(lck, name_hash)) {
1643 ok= share_mode_forall_entries(lck, has_delete_on_close_fn, &state);
1645 DBG_DEBUG("share_mode_forall_entries failed\n");
1651 static void share_mode_flags_get(
1653 uint32_t *access_mask,
1654 uint32_t *share_mode,
1655 uint32_t *lease_type)
1657 if (access_mask != NULL) {
1659 ((flags & SHARE_MODE_ACCESS_READ) ?
1660 FILE_READ_DATA : 0) |
1661 ((flags & SHARE_MODE_ACCESS_WRITE) ?
1662 FILE_WRITE_DATA : 0) |
1663 ((flags & SHARE_MODE_ACCESS_DELETE) ?
1666 if (share_mode != NULL) {
1668 ((flags & SHARE_MODE_SHARE_READ) ?
1669 FILE_SHARE_READ : 0) |
1670 ((flags & SHARE_MODE_SHARE_WRITE) ?
1671 FILE_SHARE_WRITE : 0) |
1672 ((flags & SHARE_MODE_SHARE_DELETE) ?
1673 FILE_SHARE_DELETE : 0);
1675 if (lease_type != NULL) {
1677 ((flags & SHARE_MODE_LEASE_READ) ?
1678 SMB2_LEASE_READ : 0) |
1679 ((flags & SHARE_MODE_LEASE_WRITE) ?
1680 SMB2_LEASE_WRITE : 0) |
1681 ((flags & SHARE_MODE_LEASE_HANDLE) ?
1682 SMB2_LEASE_HANDLE : 0);
1686 static uint16_t share_mode_flags_set(
1688 uint32_t access_mask,
1689 uint32_t share_mode,
1690 uint32_t lease_type)
1692 if (access_mask != UINT32_MAX) {
1693 flags &= ~(SHARE_MODE_ACCESS_READ|
1694 SHARE_MODE_ACCESS_WRITE|
1695 SHARE_MODE_ACCESS_DELETE);
1696 flags |= (access_mask & (FILE_READ_DATA | FILE_EXECUTE)) ?
1697 SHARE_MODE_ACCESS_READ : 0;
1698 flags |= (access_mask & (FILE_WRITE_DATA | FILE_APPEND_DATA)) ?
1699 SHARE_MODE_ACCESS_WRITE : 0;
1700 flags |= (access_mask & (DELETE_ACCESS)) ?
1701 SHARE_MODE_ACCESS_DELETE : 0;
1703 if (share_mode != UINT32_MAX) {
1704 flags &= ~(SHARE_MODE_SHARE_READ|
1705 SHARE_MODE_SHARE_WRITE|
1706 SHARE_MODE_SHARE_DELETE);
1707 flags |= (share_mode & FILE_SHARE_READ) ?
1708 SHARE_MODE_SHARE_READ : 0;
1709 flags |= (share_mode & FILE_SHARE_WRITE) ?
1710 SHARE_MODE_SHARE_WRITE : 0;
1711 flags |= (share_mode & FILE_SHARE_DELETE) ?
1712 SHARE_MODE_SHARE_DELETE : 0;
1714 if (lease_type != UINT32_MAX) {
1715 flags &= ~(SHARE_MODE_LEASE_READ|
1716 SHARE_MODE_LEASE_WRITE|
1717 SHARE_MODE_LEASE_HANDLE);
1718 flags |= (lease_type & SMB2_LEASE_READ) ?
1719 SHARE_MODE_LEASE_READ : 0;
1720 flags |= (lease_type & SMB2_LEASE_WRITE) ?
1721 SHARE_MODE_LEASE_WRITE : 0;
1722 flags |= (lease_type & SMB2_LEASE_HANDLE) ?
1723 SHARE_MODE_LEASE_HANDLE : 0;
1729 static uint16_t share_mode_flags_restrict(
1731 uint32_t access_mask,
1732 uint32_t share_mode,
1733 uint32_t lease_type)
1735 uint32_t existing_access_mask, existing_share_mode;
1736 uint32_t existing_lease_type;
1739 share_mode_flags_get(
1741 &existing_access_mask,
1742 &existing_share_mode,
1743 &existing_lease_type);
1745 existing_access_mask |= access_mask;
1746 existing_share_mode &= share_mode;
1747 existing_lease_type |= lease_type;
1749 ret = share_mode_flags_set(
1751 existing_access_mask,
1752 existing_share_mode,
1753 existing_lease_type);
1757 /****************************************************************************
1758 Deal with share modes
1759 Invariant: Share mode must be locked on entry and exit.
1760 Returns -1 on error, or number of share modes on success (may be zero).
1761 ****************************************************************************/
1763 struct open_mode_check_state {
1765 uint32_t access_mask;
1766 uint32_t share_access;
1767 uint32_t lease_type;
1770 static bool open_mode_check_fn(
1771 struct share_mode_entry *e,
1775 struct open_mode_check_state *state = private_data;
1776 bool disconnected, stale;
1777 uint32_t access_mask, share_access, lease_type;
1779 disconnected = server_id_is_disconnected(&e->pid);
1784 access_mask = state->access_mask | e->access_mask;
1785 share_access = state->share_access & e->share_access;
1786 lease_type = state->lease_type | get_lease_type(e, state->fid);
1788 if ((access_mask == state->access_mask) &&
1789 (share_access == state->share_access) &&
1790 (lease_type == state->lease_type)) {
1794 stale = share_entry_stale_pid(e);
1799 state->access_mask = access_mask;
1800 state->share_access = share_access;
1801 state->lease_type = lease_type;
1806 static NTSTATUS open_mode_check(connection_struct *conn,
1807 struct share_mode_lock *lck,
1808 uint32_t access_mask,
1809 uint32_t share_access)
1811 struct share_mode_data *d = lck->data;
1812 struct open_mode_check_state state;
1816 if (is_stat_open(access_mask)) {
1817 /* Stat open that doesn't trigger oplock breaks or share mode
1818 * checks... ! JRA. */
1819 return NT_STATUS_OK;
1823 * Check if the share modes will give us access.
1826 #if defined(DEVELOPER)
1828 struct validate_my_share_entries_state validate_state = {
1829 .sconn = conn->sconn,
1831 .self = messaging_server_id(conn->sconn->msg_ctx),
1833 ok = share_mode_forall_entries(
1834 lck, validate_my_share_entries_fn, &validate_state);
1839 if (d->num_share_modes == 0) {
1840 return NT_STATUS_OK;
1843 share_mode_flags_get(
1844 d->flags, &state.access_mask, &state.share_access, NULL);
1846 conflict = share_conflict(
1852 DBG_DEBUG("No conflict due to share_mode_flags access\n");
1853 return NT_STATUS_OK;
1856 state = (struct open_mode_check_state) {
1858 .share_access = (FILE_SHARE_READ|
1864 * Walk the share mode array to recalculate d->flags
1867 ok = share_mode_forall_entries(lck, open_mode_check_fn, &state);
1869 DBG_DEBUG("share_mode_forall_entries failed\n");
1870 return NT_STATUS_INTERNAL_ERROR;
1873 new_flags = share_mode_flags_set(
1874 0, state.access_mask, state.share_access, state.lease_type);
1875 if (new_flags == d->flags) {
1877 * We only end up here if we had a sharing violation
1878 * from d->flags and have recalculated it.
1880 return NT_STATUS_SHARING_VIOLATION;
1883 d->flags = new_flags;
1886 conflict = share_conflict(
1892 DBG_DEBUG("No conflict due to share_mode_flags access\n");
1893 return NT_STATUS_OK;
1896 return NT_STATUS_SHARING_VIOLATION;
1900 * Send a break message to the oplock holder and delay the open for
1904 NTSTATUS send_break_message(struct messaging_context *msg_ctx,
1905 const struct file_id *id,
1906 const struct share_mode_entry *exclusive,
1909 struct oplock_break_message msg = {
1911 .share_file_id = exclusive->share_file_id,
1912 .break_to = break_to,
1914 enum ndr_err_code ndr_err;
1919 struct server_id_buf buf;
1920 DBG_DEBUG("Sending break message to %s\n",
1921 server_id_str_buf(exclusive->pid, &buf));
1922 NDR_PRINT_DEBUG(oplock_break_message, &msg);
1925 ndr_err = ndr_push_struct_blob(
1929 (ndr_push_flags_fn_t)ndr_push_oplock_break_message);
1930 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
1931 DBG_WARNING("ndr_push_oplock_break_message failed: %s\n",
1932 ndr_errstr(ndr_err));
1933 return ndr_map_error2ntstatus(ndr_err);
1936 status = messaging_send(
1937 msg_ctx, exclusive->pid, MSG_SMB_BREAK_REQUEST, &blob);
1938 TALLOC_FREE(blob.data);
1939 if (!NT_STATUS_IS_OK(status)) {
1940 DEBUG(3, ("Could not send oplock break message: %s\n",
1941 nt_errstr(status)));
1947 struct validate_oplock_types_state {
1953 uint32_t num_non_stat_opens;
1956 static bool validate_oplock_types_fn(
1957 struct share_mode_entry *e,
1961 struct validate_oplock_types_state *state = private_data;
1963 if (e->op_mid == 0) {
1964 /* INTERNAL_OPEN_ONLY */
1968 if (e->op_type == NO_OPLOCK && is_stat_open(e->access_mask)) {
1970 * We ignore stat opens in the table - they always
1971 * have NO_OPLOCK and never get or cause breaks. JRA.
1976 state->num_non_stat_opens += 1;
1978 if (BATCH_OPLOCK_TYPE(e->op_type)) {
1979 /* batch - can only be one. */
1980 if (share_entry_stale_pid(e)) {
1981 DBG_DEBUG("Found stale batch oplock\n");
1984 if (state->ex_or_batch ||
1988 DBG_ERR("Bad batch oplock entry\n");
1989 state->valid = false;
1992 state->batch = true;
1995 if (EXCLUSIVE_OPLOCK_TYPE(e->op_type)) {
1996 if (share_entry_stale_pid(e)) {
1997 DBG_DEBUG("Found stale duplicate oplock\n");
2000 /* Exclusive or batch - can only be one. */
2001 if (state->ex_or_batch ||
2004 DBG_ERR("Bad exclusive or batch oplock entry\n");
2005 state->valid = false;
2008 state->ex_or_batch = true;
2011 if (LEVEL_II_OPLOCK_TYPE(e->op_type)) {
2012 if (state->batch || state->ex_or_batch) {
2013 if (share_entry_stale_pid(e)) {
2014 DBG_DEBUG("Found stale LevelII oplock\n");
2017 DBG_DEBUG("Bad levelII oplock entry\n");
2018 state->valid = false;
2021 state->level2 = true;
2024 if (e->op_type == NO_OPLOCK) {
2025 if (state->batch || state->ex_or_batch) {
2026 if (share_entry_stale_pid(e)) {
2027 DBG_DEBUG("Found stale NO_OPLOCK entry\n");
2030 DBG_ERR("Bad no oplock entry\n");
2031 state->valid = false;
2034 state->no_oplock = true;
2041 * Do internal consistency checks on the share mode for a file.
2044 static bool validate_oplock_types(struct share_mode_lock *lck)
2046 struct validate_oplock_types_state state = { .valid = true };
2049 ok = share_mode_forall_entries(lck, validate_oplock_types_fn, &state);
2051 DBG_DEBUG("share_mode_forall_entries failed\n");
2055 DBG_DEBUG("Got invalid oplock configuration\n");
2059 if ((state.batch || state.ex_or_batch) &&
2060 (state.num_non_stat_opens != 1)) {
2061 DBG_WARNING("got batch (%d) or ex (%d) non-exclusively "
2064 (int)state.ex_or_batch,
2065 state.num_non_stat_opens);
2072 static bool is_same_lease(const files_struct *fsp,
2073 const struct share_mode_entry *e,
2074 const struct smb2_lease *lease)
2076 if (e->op_type != LEASE_OPLOCK) {
2079 if (lease == NULL) {
2083 return smb2_lease_equal(fsp_client_guid(fsp),
2089 static bool file_has_brlocks(files_struct *fsp)
2091 struct byte_range_lock *br_lck;
2093 br_lck = brl_get_locks_readonly(fsp);
2097 return (brl_num_locks(br_lck) > 0);
2100 struct fsp_lease *find_fsp_lease(struct files_struct *new_fsp,
2101 const struct smb2_lease_key *key,
2102 uint32_t current_state,
2103 uint16_t lease_version,
2104 uint16_t lease_epoch)
2106 struct files_struct *fsp;
2109 * TODO: Measure how expensive this loop is with thousands of open
2113 for (fsp = file_find_di_first(new_fsp->conn->sconn, new_fsp->file_id);
2115 fsp = file_find_di_next(fsp)) {
2117 if (fsp == new_fsp) {
2120 if (fsp->oplock_type != LEASE_OPLOCK) {
2123 if (smb2_lease_key_equal(&fsp->lease->lease.lease_key, key)) {
2124 fsp->lease->ref_count += 1;
2129 /* Not found - must be leased in another smbd. */
2130 new_fsp->lease = talloc_zero(new_fsp->conn->sconn, struct fsp_lease);
2131 if (new_fsp->lease == NULL) {
2134 new_fsp->lease->ref_count = 1;
2135 new_fsp->lease->sconn = new_fsp->conn->sconn;
2136 new_fsp->lease->lease.lease_key = *key;
2137 new_fsp->lease->lease.lease_state = current_state;
2139 * We internally treat all leases as V2 and update
2140 * the epoch, but when sending breaks it matters if
2141 * the requesting lease was v1 or v2.
2143 new_fsp->lease->lease.lease_version = lease_version;
2144 new_fsp->lease->lease.lease_epoch = lease_epoch;
2145 return new_fsp->lease;
2148 static NTSTATUS try_lease_upgrade(struct files_struct *fsp,
2149 struct share_mode_lock *lck,
2150 const struct GUID *client_guid,
2151 const struct smb2_lease *lease,
2155 uint32_t current_state, breaking_to_requested, breaking_to_required;
2157 uint16_t lease_version, epoch;
2158 uint32_t existing, requested;
2161 status = leases_db_get(
2167 &breaking_to_requested,
2168 &breaking_to_required,
2171 if (!NT_STATUS_IS_OK(status)) {
2175 fsp->lease = find_fsp_lease(
2181 if (fsp->lease == NULL) {
2182 DEBUG(1, ("Did not find existing lease for file %s\n",
2184 return NT_STATUS_NO_MEMORY;
2188 * Upgrade only if the requested lease is a strict upgrade.
2190 existing = current_state;
2191 requested = lease->lease_state;
2194 * Tricky: This test makes sure that "requested" is a
2195 * strict bitwise superset of "existing".
2197 do_upgrade = ((existing & requested) == existing);
2200 * Upgrade only if there's a change.
2202 do_upgrade &= (granted != existing);
2205 * Upgrade only if other leases don't prevent what was asked
2208 do_upgrade &= (granted == requested);
2211 * only upgrade if we are not in breaking state
2213 do_upgrade &= !breaking;
2215 DEBUG(10, ("existing=%"PRIu32", requested=%"PRIu32", "
2216 "granted=%"PRIu32", do_upgrade=%d\n",
2217 existing, requested, granted, (int)do_upgrade));
2220 NTSTATUS set_status;
2222 current_state = granted;
2225 set_status = leases_db_set(
2230 breaking_to_requested,
2231 breaking_to_required,
2235 if (!NT_STATUS_IS_OK(set_status)) {
2236 DBG_DEBUG("leases_db_set failed: %s\n",
2237 nt_errstr(set_status));
2242 fsp_lease_update(fsp);
2244 return NT_STATUS_OK;
2247 static NTSTATUS grant_new_fsp_lease(struct files_struct *fsp,
2248 struct share_mode_lock *lck,
2249 const struct GUID *client_guid,
2250 const struct smb2_lease *lease,
2253 struct share_mode_data *d = lck->data;
2256 fsp->lease = talloc_zero(fsp->conn->sconn, struct fsp_lease);
2257 if (fsp->lease == NULL) {
2258 return NT_STATUS_INSUFFICIENT_RESOURCES;
2260 fsp->lease->ref_count = 1;
2261 fsp->lease->sconn = fsp->conn->sconn;
2262 fsp->lease->lease.lease_version = lease->lease_version;
2263 fsp->lease->lease.lease_key = lease->lease_key;
2264 fsp->lease->lease.lease_state = granted;
2265 fsp->lease->lease.lease_epoch = lease->lease_epoch + 1;
2267 status = leases_db_add(client_guid,
2270 fsp->lease->lease.lease_state,
2271 fsp->lease->lease.lease_version,
2272 fsp->lease->lease.lease_epoch,
2273 fsp->conn->connectpath,
2274 fsp->fsp_name->base_name,
2275 fsp->fsp_name->stream_name);
2276 if (!NT_STATUS_IS_OK(status)) {
2277 DEBUG(10, ("%s: leases_db_add failed: %s\n", __func__,
2278 nt_errstr(status)));
2279 TALLOC_FREE(fsp->lease);
2280 return NT_STATUS_INSUFFICIENT_RESOURCES;
2285 return NT_STATUS_OK;
2288 static NTSTATUS grant_fsp_lease(struct files_struct *fsp,
2289 struct share_mode_lock *lck,
2290 const struct smb2_lease *lease,
2293 const struct GUID *client_guid = fsp_client_guid(fsp);
2296 status = try_lease_upgrade(fsp, lck, client_guid, lease, granted);
2298 if (NT_STATUS_EQUAL(status, NT_STATUS_NOT_FOUND)) {
2299 status = grant_new_fsp_lease(
2300 fsp, lck, client_guid, lease, granted);
2306 static int map_lease_type_to_oplock(uint32_t lease_type)
2308 int result = NO_OPLOCK;
2310 switch (lease_type) {
2311 case SMB2_LEASE_READ|SMB2_LEASE_WRITE|SMB2_LEASE_HANDLE:
2312 result = BATCH_OPLOCK|EXCLUSIVE_OPLOCK;
2314 case SMB2_LEASE_READ|SMB2_LEASE_WRITE:
2315 result = EXCLUSIVE_OPLOCK;
2317 case SMB2_LEASE_READ|SMB2_LEASE_HANDLE:
2318 case SMB2_LEASE_READ:
2319 result = LEVEL_II_OPLOCK;
2326 struct delay_for_oplock_state {
2327 struct files_struct *fsp;
2328 const struct smb2_lease *lease;
2329 bool will_overwrite;
2330 uint32_t delay_mask;
2331 bool first_open_attempt;
2332 bool got_handle_lease;
2334 bool have_other_lease;
2338 static bool delay_for_oplock_fn(
2339 struct share_mode_entry *e,
2343 struct delay_for_oplock_state *state = private_data;
2344 struct files_struct *fsp = state->fsp;
2345 const struct smb2_lease *lease = state->lease;
2346 bool e_is_lease = (e->op_type == LEASE_OPLOCK);
2347 uint32_t e_lease_type = get_lease_type(e, fsp->file_id);
2349 bool lease_is_breaking = false;
2354 if (lease != NULL) {
2355 bool our_lease = is_same_lease(fsp, e, lease);
2357 DBG_DEBUG("Ignoring our own lease\n");
2362 status = leases_db_get(
2366 NULL, /* current_state */
2368 NULL, /* breaking_to_requested */
2369 NULL, /* breaking_to_required */
2370 NULL, /* lease_version */
2372 SMB_ASSERT(NT_STATUS_IS_OK(status));
2375 if (!state->got_handle_lease &&
2376 ((e_lease_type & SMB2_LEASE_HANDLE) != 0) &&
2377 !share_entry_stale_pid(e)) {
2378 state->got_handle_lease = true;
2381 if (!state->got_oplock &&
2382 (e->op_type != LEASE_OPLOCK) &&
2383 !share_entry_stale_pid(e)) {
2384 state->got_oplock = true;
2387 if (!state->have_other_lease &&
2388 !is_same_lease(fsp, e, lease) &&
2389 !share_entry_stale_pid(e)) {
2390 state->have_other_lease = true;
2393 break_to = e_lease_type & ~state->delay_mask;
2395 if (state->will_overwrite) {
2396 break_to &= ~(SMB2_LEASE_HANDLE|SMB2_LEASE_READ);
2399 DBG_DEBUG("e_lease_type %u, will_overwrite: %u\n",
2400 (unsigned)e_lease_type,
2401 (unsigned)state->will_overwrite);
2403 if ((e_lease_type & ~break_to) == 0) {
2404 if (lease_is_breaking) {
2405 state->delay = true;
2410 if (share_entry_stale_pid(e)) {
2414 if (state->will_overwrite) {
2416 * If we break anyway break to NONE directly.
2417 * Otherwise vfs_set_filelen() will trigger the
2420 break_to &= ~(SMB2_LEASE_READ|SMB2_LEASE_WRITE);
2425 * Oplocks only support breaking to R or NONE.
2427 break_to &= ~(SMB2_LEASE_HANDLE|SMB2_LEASE_WRITE);
2430 DBG_DEBUG("breaking from %d to %d\n",
2434 fsp->conn->sconn->msg_ctx, &fsp->file_id, e, break_to);
2435 if (e_lease_type & state->delay_mask) {
2436 state->delay = true;
2438 if (lease_is_breaking && !state->first_open_attempt) {
2439 state->delay = true;
2445 static NTSTATUS delay_for_oplock(files_struct *fsp,
2447 const struct smb2_lease *lease,
2448 struct share_mode_lock *lck,
2449 bool have_sharing_violation,
2450 uint32_t create_disposition,
2451 bool first_open_attempt)
2453 struct delay_for_oplock_state state = {
2456 .first_open_attempt = first_open_attempt,
2462 if (is_stat_open(fsp->access_mask)) {
2466 state.delay_mask = have_sharing_violation ?
2467 SMB2_LEASE_HANDLE : SMB2_LEASE_WRITE;
2469 switch (create_disposition) {
2470 case FILE_SUPERSEDE:
2471 case FILE_OVERWRITE:
2472 case FILE_OVERWRITE_IF:
2473 state.will_overwrite = true;
2476 state.will_overwrite = false;
2480 ok = share_mode_forall_entries(lck, delay_for_oplock_fn, &state);
2482 return NT_STATUS_INTERNAL_ERROR;
2486 return NT_STATUS_RETRY;
2490 if (have_sharing_violation) {
2491 return NT_STATUS_SHARING_VIOLATION;
2494 if (oplock_request == LEASE_OPLOCK) {
2495 if (lease == NULL) {
2497 * The SMB2 layer should have checked this
2499 return NT_STATUS_INTERNAL_ERROR;
2502 granted = lease->lease_state;
2504 if (lp_kernel_oplocks(SNUM(fsp->conn))) {
2505 DEBUG(10, ("No lease granted because kernel oplocks are enabled\n"));
2506 granted = SMB2_LEASE_NONE;
2508 if ((granted & (SMB2_LEASE_READ|SMB2_LEASE_WRITE)) == 0) {
2509 DEBUG(10, ("No read or write lease requested\n"));
2510 granted = SMB2_LEASE_NONE;
2512 if (granted == SMB2_LEASE_WRITE) {
2513 DEBUG(10, ("pure write lease requested\n"));
2514 granted = SMB2_LEASE_NONE;
2516 if (granted == (SMB2_LEASE_WRITE|SMB2_LEASE_HANDLE)) {
2517 DEBUG(10, ("write and handle lease requested\n"));
2518 granted = SMB2_LEASE_NONE;
2521 granted = map_oplock_to_lease_type(
2522 oplock_request & ~SAMBA_PRIVATE_OPLOCK_MASK);
2525 if (lp_locking(fsp->conn->params) && file_has_brlocks(fsp)) {
2526 DBG_DEBUG("file %s has byte range locks\n",
2528 granted &= ~SMB2_LEASE_READ;
2531 if (state.have_other_lease) {
2533 * Can grant only one writer
2535 granted &= ~SMB2_LEASE_WRITE;
2538 if ((granted & SMB2_LEASE_READ) && !(granted & SMB2_LEASE_WRITE)) {
2540 (global_client_caps & CAP_LEVEL_II_OPLOCKS) &&
2541 lp_level2_oplocks(SNUM(fsp->conn));
2543 if (!allow_level2) {
2544 granted = SMB2_LEASE_NONE;
2548 if (oplock_request == LEASE_OPLOCK) {
2549 if (state.got_oplock) {
2550 granted &= ~SMB2_LEASE_HANDLE;
2553 fsp->oplock_type = LEASE_OPLOCK;
2555 status = grant_fsp_lease(fsp, lck, lease, granted);
2556 if (!NT_STATUS_IS_OK(status)) {
2561 DBG_DEBUG("lease_state=%d\n", fsp->lease->lease.lease_state);
2563 if (state.got_handle_lease) {
2564 granted = SMB2_LEASE_NONE;
2567 fsp->oplock_type = map_lease_type_to_oplock(granted);
2569 status = set_file_oplock(fsp);
2570 if (!NT_STATUS_IS_OK(status)) {
2572 * Could not get the kernel oplock
2574 fsp->oplock_type = NO_OPLOCK;
2578 if (granted & SMB2_LEASE_READ) {
2579 lck->data->flags |= SHARE_MODE_LEASE_READ;
2582 DBG_DEBUG("oplock type 0x%x on file %s\n",
2583 fsp->oplock_type, fsp_str_dbg(fsp));
2585 return NT_STATUS_OK;
2588 static NTSTATUS handle_share_mode_lease(
2590 struct share_mode_lock *lck,
2591 uint32_t create_disposition,
2592 uint32_t access_mask,
2593 uint32_t share_access,
2595 const struct smb2_lease *lease,
2596 bool first_open_attempt)
2598 bool sharing_violation = false;
2601 status = open_mode_check(
2602 fsp->conn, lck, access_mask, share_access);
2603 if (NT_STATUS_EQUAL(status, NT_STATUS_SHARING_VIOLATION)) {
2604 sharing_violation = true;
2605 status = NT_STATUS_OK; /* handled later */
2608 if (!NT_STATUS_IS_OK(status)) {
2612 if (oplock_request == INTERNAL_OPEN_ONLY) {
2613 if (sharing_violation) {
2614 DBG_DEBUG("Sharing violation for internal open\n");
2615 return NT_STATUS_SHARING_VIOLATION;
2619 * Internal opens never do oplocks or leases. We don't
2620 * need to go through delay_for_oplock().
2622 fsp->oplock_type = NO_OPLOCK;
2624 return NT_STATUS_OK;
2627 status = delay_for_oplock(
2634 first_open_attempt);
2635 if (!NT_STATUS_IS_OK(status)) {
2639 return NT_STATUS_OK;
2642 static bool request_timed_out(struct smb_request *req, struct timeval timeout)
2644 struct timeval now, end_time;
2646 end_time = timeval_sum(&req->request_time, &timeout);
2647 return (timeval_compare(&end_time, &now) < 0);
2650 struct defer_open_state {
2651 struct smbXsrv_connection *xconn;
2655 static void defer_open_done(struct tevent_req *req);
2658 * Defer an open and watch a locking.tdb record
2660 * This defers an open that gets rescheduled once the locking.tdb record watch
2661 * is triggered by a change to the record.
2663 * It is used to defer opens that triggered an oplock break and for the SMB1
2664 * sharing violation delay.
2666 static void defer_open(struct share_mode_lock *lck,
2667 struct timeval timeout,
2668 struct smb_request *req,
2669 bool delayed_for_oplocks,
2672 struct deferred_open_record *open_rec = NULL;
2673 struct timeval abs_timeout;
2674 struct defer_open_state *watch_state;
2675 struct tevent_req *watch_req;
2676 struct timeval_buf tvbuf1, tvbuf2;
2677 struct file_id_buf fbuf;
2680 abs_timeout = timeval_sum(&req->request_time, &timeout);
2682 DBG_DEBUG("request time [%s] timeout [%s] mid [%" PRIu64 "] "
2683 "delayed_for_oplocks [%s] file_id [%s]\n",
2684 timeval_str_buf(&req->request_time, false, true, &tvbuf1),
2685 timeval_str_buf(&abs_timeout, false, true, &tvbuf2),
2687 delayed_for_oplocks ? "yes" : "no",
2688 file_id_str_buf(id, &fbuf));
2690 open_rec = talloc_zero(NULL, struct deferred_open_record);
2691 if (open_rec == NULL) {
2693 exit_server("talloc failed");
2696 watch_state = talloc(open_rec, struct defer_open_state);
2697 if (watch_state == NULL) {
2698 exit_server("talloc failed");
2700 watch_state->xconn = req->xconn;
2701 watch_state->mid = req->mid;
2703 DBG_DEBUG("defering mid %" PRIu64 "\n", req->mid);
2705 watch_req = share_mode_watch_send(
2709 (struct server_id){0});
2710 if (watch_req == NULL) {
2711 exit_server("Could not watch share mode record");
2713 tevent_req_set_callback(watch_req, defer_open_done, watch_state);
2715 ok = tevent_req_set_endtime(watch_req, req->sconn->ev_ctx, abs_timeout);
2717 exit_server("tevent_req_set_endtime failed");
2720 ok = push_deferred_open_message_smb(req, timeout, id, open_rec);
2723 exit_server("push_deferred_open_message_smb failed");
2727 static void defer_open_done(struct tevent_req *req)
2729 struct defer_open_state *state = tevent_req_callback_data(
2730 req, struct defer_open_state);
2734 status = share_mode_watch_recv(req, NULL, NULL);
2736 if (!NT_STATUS_IS_OK(status)) {
2737 DEBUG(5, ("dbwrap_watched_watch_recv returned %s\n",
2738 nt_errstr(status)));
2740 * Even if it failed, retry anyway. TODO: We need a way to
2741 * tell a re-scheduled open about that error.
2745 DEBUG(10, ("scheduling mid %llu\n", (unsigned long long)state->mid));
2747 ret = schedule_deferred_open_message_smb(state->xconn, state->mid);
2753 * Actually attempt the kernel oplock polling open.
2756 static void poll_open_fn(struct tevent_context *ev,
2757 struct tevent_timer *te,
2758 struct timeval current_time,
2761 struct deferred_open_record *open_rec = talloc_get_type_abort(
2762 private_data, struct deferred_open_record);
2765 TALLOC_FREE(open_rec->watch_req);
2767 ok = schedule_deferred_open_message_smb(
2768 open_rec->xconn, open_rec->mid);
2770 exit_server("schedule_deferred_open_message_smb failed");
2772 DBG_DEBUG("timer fired. Retrying open !\n");
2775 static void poll_open_done(struct tevent_req *subreq);
2778 * Reschedule an open for 1 second from now, if not timed out.
2780 static bool setup_poll_open(
2781 struct smb_request *req,
2782 struct share_mode_lock *lck,
2784 struct timeval max_timeout,
2785 struct timeval interval)
2788 struct deferred_open_record *open_rec = NULL;
2789 struct timeval endtime, next_interval;
2790 struct file_id_buf ftmp;
2792 if (request_timed_out(req, max_timeout)) {
2796 open_rec = talloc_zero(NULL, struct deferred_open_record);
2797 if (open_rec == NULL) {
2798 DBG_WARNING("talloc failed\n");
2801 open_rec->xconn = req->xconn;
2802 open_rec->mid = req->mid;
2805 * Make sure open_rec->te does not come later than the
2806 * request's maximum endtime.
2809 endtime = timeval_sum(&req->request_time, &max_timeout);
2810 next_interval = timeval_current_ofs(interval.tv_sec, interval.tv_usec);
2811 next_interval = timeval_min(&endtime, &next_interval);
2813 open_rec->te = tevent_add_timer(
2819 if (open_rec->te == NULL) {
2820 DBG_WARNING("tevent_add_timer failed\n");
2821 TALLOC_FREE(open_rec);
2826 open_rec->watch_req = share_mode_watch_send(
2830 (struct server_id) {0});
2831 if (open_rec->watch_req == NULL) {
2832 DBG_WARNING("share_mode_watch_send failed\n");
2833 TALLOC_FREE(open_rec);
2836 tevent_req_set_callback(
2837 open_rec->watch_req, poll_open_done, open_rec);
2840 ok = push_deferred_open_message_smb(req, max_timeout, id, open_rec);
2842 DBG_WARNING("push_deferred_open_message_smb failed\n");
2843 TALLOC_FREE(open_rec);
2847 DBG_DEBUG("poll request time [%s] mid [%" PRIu64 "] file_id [%s]\n",
2848 timeval_string(talloc_tos(), &req->request_time, false),
2850 file_id_str_buf(id, &ftmp));
2855 static void poll_open_done(struct tevent_req *subreq)
2857 struct deferred_open_record *open_rec = tevent_req_callback_data(
2858 subreq, struct deferred_open_record);
2862 status = share_mode_watch_recv(subreq, NULL, NULL);
2863 TALLOC_FREE(subreq);
2864 DBG_DEBUG("dbwrap_watched_watch_recv returned %s\n",
2867 ok = schedule_deferred_open_message_smb(
2868 open_rec->xconn, open_rec->mid);
2870 exit_server("schedule_deferred_open_message_smb failed");
2874 bool defer_smb1_sharing_violation(struct smb_request *req)
2879 if (!lp_defer_sharing_violations()) {
2884 * Try every 200msec up to (by default) one second. To be
2885 * precise, according to behaviour note <247> in [MS-CIFS],
2886 * the server tries 5 times. But up to one second should be
2890 timeout_usecs = lp_parm_int(
2894 SHARING_VIOLATION_USEC_WAIT);
2896 ok = setup_poll_open(
2899 (struct file_id) {0},
2900 (struct timeval) { .tv_usec = timeout_usecs },
2901 (struct timeval) { .tv_usec = 200000 });
2905 /****************************************************************************
2906 On overwrite open ensure that the attributes match.
2907 ****************************************************************************/
2909 static bool open_match_attributes(connection_struct *conn,
2910 uint32_t old_dos_attr,
2911 uint32_t new_dos_attr,
2912 mode_t new_unx_mode,
2913 mode_t *returned_unx_mode)
2915 uint32_t noarch_old_dos_attr, noarch_new_dos_attr;
2917 noarch_old_dos_attr = (old_dos_attr & ~FILE_ATTRIBUTE_ARCHIVE);
2918 noarch_new_dos_attr = (new_dos_attr & ~FILE_ATTRIBUTE_ARCHIVE);
2920 if((noarch_old_dos_attr == 0 && noarch_new_dos_attr != 0) ||
2921 (noarch_old_dos_attr != 0 && ((noarch_old_dos_attr & noarch_new_dos_attr) == noarch_old_dos_attr))) {
2922 *returned_unx_mode = new_unx_mode;
2924 *returned_unx_mode = (mode_t)0;
2927 DEBUG(10,("open_match_attributes: old_dos_attr = 0x%x, "
2928 "new_dos_attr = 0x%x "
2929 "returned_unx_mode = 0%o\n",
2930 (unsigned int)old_dos_attr,
2931 (unsigned int)new_dos_attr,
2932 (unsigned int)*returned_unx_mode ));
2934 /* If we're mapping SYSTEM and HIDDEN ensure they match. */
2935 if (lp_map_system(SNUM(conn)) || lp_store_dos_attributes(SNUM(conn))) {
2936 if ((old_dos_attr & FILE_ATTRIBUTE_SYSTEM) &&
2937 !(new_dos_attr & FILE_ATTRIBUTE_SYSTEM)) {
2941 if (lp_map_hidden(SNUM(conn)) || lp_store_dos_attributes(SNUM(conn))) {
2942 if ((old_dos_attr & FILE_ATTRIBUTE_HIDDEN) &&
2943 !(new_dos_attr & FILE_ATTRIBUTE_HIDDEN)) {
2950 static void schedule_defer_open(struct share_mode_lock *lck,
2952 struct smb_request *req)
2954 /* This is a relative time, added to the absolute
2955 request_time value to get the absolute timeout time.
2956 Note that if this is the second or greater time we enter
2957 this codepath for this particular request mid then
2958 request_time is left as the absolute time of the *first*
2959 time this request mid was processed. This is what allows
2960 the request to eventually time out. */
2962 struct timeval timeout;
2964 /* Normally the smbd we asked should respond within
2965 * OPLOCK_BREAK_TIMEOUT seconds regardless of whether
2966 * the client did, give twice the timeout as a safety
2967 * measure here in case the other smbd is stuck
2968 * somewhere else. */
2970 timeout = timeval_set(OPLOCK_BREAK_TIMEOUT*2, 0);
2972 if (request_timed_out(req, timeout)) {
2976 defer_open(lck, timeout, req, true, id);
2979 /****************************************************************************
2980 Reschedule an open call that went asynchronous.
2981 ****************************************************************************/
2983 static void schedule_async_open_timer(struct tevent_context *ev,
2984 struct tevent_timer *te,
2985 struct timeval current_time,
2988 exit_server("async open timeout");
2991 static void schedule_async_open(struct smb_request *req)
2993 struct deferred_open_record *open_rec = NULL;
2994 struct timeval timeout = timeval_set(20, 0);
2997 if (request_timed_out(req, timeout)) {
3001 open_rec = talloc_zero(NULL, struct deferred_open_record);
3002 if (open_rec == NULL) {
3003 exit_server("deferred_open_record_create failed");
3005 open_rec->async_open = true;
3007 ok = push_deferred_open_message_smb(
3008 req, timeout, (struct file_id){0}, open_rec);
3010 exit_server("push_deferred_open_message_smb failed");
3013 open_rec->te = tevent_add_timer(req->sconn->ev_ctx,
3015 timeval_current_ofs(20, 0),
3016 schedule_async_open_timer,
3018 if (open_rec->te == NULL) {
3019 exit_server("tevent_add_timer failed");
3023 /****************************************************************************
3024 Work out what access_mask to use from what the client sent us.
3025 ****************************************************************************/
3027 static NTSTATUS smbd_calculate_maximum_allowed_access(
3028 connection_struct *conn,
3029 const struct smb_filename *smb_fname,
3031 uint32_t *p_access_mask)
3033 struct security_descriptor *sd;
3034 uint32_t access_granted;
3037 if (!use_privs && (get_current_uid(conn) == (uid_t)0)) {
3038 *p_access_mask |= FILE_GENERIC_ALL;
3039 return NT_STATUS_OK;
3042 status = SMB_VFS_GET_NT_ACL(conn, smb_fname,
3048 if (NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
3050 * File did not exist
3052 *p_access_mask = FILE_GENERIC_ALL;
3053 return NT_STATUS_OK;
3055 if (!NT_STATUS_IS_OK(status)) {
3056 DEBUG(10,("Could not get acl on file %s: %s\n",
3057 smb_fname_str_dbg(smb_fname),
3058 nt_errstr(status)));
3059 return NT_STATUS_ACCESS_DENIED;
3063 * If we can access the path to this file, by
3064 * default we have FILE_READ_ATTRIBUTES from the
3065 * containing directory. See the section:
3066 * "Algorithm to Check Access to an Existing File"
3069 * se_file_access_check()
3070 * also takes care of owner WRITE_DAC and READ_CONTROL.
3072 status = se_file_access_check(sd,
3073 get_current_nttok(conn),
3075 (*p_access_mask & ~FILE_READ_ATTRIBUTES),
3080 if (!NT_STATUS_IS_OK(status)) {
3081 DEBUG(10, ("Access denied on file %s: "
3082 "when calculating maximum access\n",
3083 smb_fname_str_dbg(smb_fname)));
3084 return NT_STATUS_ACCESS_DENIED;
3086 *p_access_mask = (access_granted | FILE_READ_ATTRIBUTES);
3088 if (!(access_granted & DELETE_ACCESS)) {
3089 if (can_delete_file_in_directory(conn, smb_fname)) {
3090 *p_access_mask |= DELETE_ACCESS;
3094 return NT_STATUS_OK;
3097 NTSTATUS smbd_calculate_access_mask(connection_struct *conn,
3098 const struct smb_filename *smb_fname,
3100 uint32_t access_mask,
3101 uint32_t *access_mask_out)
3104 uint32_t orig_access_mask = access_mask;
3105 uint32_t rejected_share_access;
3107 if (access_mask & SEC_MASK_INVALID) {
3108 DBG_DEBUG("access_mask [%8x] contains invalid bits\n",
3110 return NT_STATUS_ACCESS_DENIED;
3114 * Convert GENERIC bits to specific bits.
3117 se_map_generic(&access_mask, &file_generic_mapping);
3119 /* Calculate MAXIMUM_ALLOWED_ACCESS if requested. */
3120 if (access_mask & MAXIMUM_ALLOWED_ACCESS) {
3122 status = smbd_calculate_maximum_allowed_access(
3123 conn, smb_fname, use_privs, &access_mask);
3125 if (!NT_STATUS_IS_OK(status)) {
3129 access_mask &= conn->share_access;
3132 rejected_share_access = access_mask & ~(conn->share_access);
3134 if (rejected_share_access) {
3135 DEBUG(10, ("smbd_calculate_access_mask: Access denied on "
3136 "file %s: rejected by share access mask[0x%08X] "
3137 "orig[0x%08X] mapped[0x%08X] reject[0x%08X]\n",
3138 smb_fname_str_dbg(smb_fname),
3140 orig_access_mask, access_mask,
3141 rejected_share_access));
3142 return NT_STATUS_ACCESS_DENIED;
3145 *access_mask_out = access_mask;
3146 return NT_STATUS_OK;
3149 /****************************************************************************
3150 Remove the deferred open entry under lock.
3151 ****************************************************************************/
3153 /****************************************************************************
3154 Return true if this is a state pointer to an asynchronous create.
3155 ****************************************************************************/
3157 bool is_deferred_open_async(const struct deferred_open_record *rec)
3159 return rec->async_open;
3162 static bool clear_ads(uint32_t create_disposition)
3166 switch (create_disposition) {
3167 case FILE_SUPERSEDE:
3168 case FILE_OVERWRITE_IF:
3169 case FILE_OVERWRITE:
3178 static int disposition_to_open_flags(uint32_t create_disposition)
3183 * Currently we're using FILE_SUPERSEDE as the same as
3184 * FILE_OVERWRITE_IF but they really are
3185 * different. FILE_SUPERSEDE deletes an existing file
3186 * (requiring delete access) then recreates it.
3189 switch (create_disposition) {
3190 case FILE_SUPERSEDE:
3191 case FILE_OVERWRITE_IF:
3193 * If file exists replace/overwrite. If file doesn't
3196 ret = O_CREAT|O_TRUNC;
3201 * If file exists open. If file doesn't exist error.
3206 case FILE_OVERWRITE:
3208 * If file exists overwrite. If file doesn't exist
3216 * If file exists error. If file doesn't exist create.
3218 ret = O_CREAT|O_EXCL;
3223 * If file exists open. If file doesn't exist create.
3231 static int calculate_open_access_flags(uint32_t access_mask,
3232 uint32_t private_flags)
3234 bool need_write, need_read;
3237 * Note that we ignore the append flag as append does not
3238 * mean the same thing under DOS and Unix.
3241 need_write = (access_mask & (FILE_WRITE_DATA | FILE_APPEND_DATA));
3246 /* DENY_DOS opens are always underlying read-write on the
3247 file handle, no matter what the requested access mask
3251 ((private_flags & NTCREATEX_OPTIONS_PRIVATE_DENY_DOS) ||
3252 access_mask & (FILE_READ_ATTRIBUTES|FILE_READ_DATA|
3253 FILE_READ_EA|FILE_EXECUTE));
3261 /****************************************************************************
3262 Open a file with a share mode. Passed in an already created files_struct *.
3263 ****************************************************************************/
3265 static NTSTATUS open_file_ntcreate(connection_struct *conn,
3266 struct smb_request *req,
3267 uint32_t access_mask, /* access bits (FILE_READ_DATA etc.) */
3268 uint32_t share_access, /* share constants (FILE_SHARE_READ etc) */
3269 uint32_t create_disposition, /* FILE_OPEN_IF etc. */
3270 uint32_t create_options, /* options such as delete on close. */
3271 uint32_t new_dos_attributes, /* attributes used for new file. */
3272 int oplock_request, /* internal Samba oplock codes. */
3273 const struct smb2_lease *lease,
3274 /* Information (FILE_EXISTS etc.) */
3275 uint32_t private_flags, /* Samba specific flags. */
3279 struct smb_filename *smb_fname = fsp->fsp_name;
3282 bool file_existed = VALID_STAT(smb_fname->st);
3283 bool def_acl = False;
3284 bool posix_open = False;
3285 bool new_file_created = False;
3286 bool first_open_attempt = true;
3287 NTSTATUS fsp_open = NT_STATUS_ACCESS_DENIED;
3288 mode_t new_unx_mode = (mode_t)0;
3289 mode_t unx_mode = (mode_t)0;
3291 uint32_t existing_dos_attributes = 0;
3292 struct share_mode_lock *lck = NULL;
3293 uint32_t open_access_mask = access_mask;
3296 SMB_STRUCT_STAT saved_stat = smb_fname->st;
3297 struct timespec old_write_time;
3301 if (conn->printer) {
3303 * Printers are handled completely differently.
3304 * Most of the passed parameters are ignored.
3308 *pinfo = FILE_WAS_CREATED;
3311 DEBUG(10, ("open_file_ntcreate: printer open fname=%s\n",
3312 smb_fname_str_dbg(smb_fname)));
3315 DEBUG(0,("open_file_ntcreate: printer open without "
3316 "an SMB request!\n"));
3317 return NT_STATUS_INTERNAL_ERROR;
3320 return print_spool_open(fsp, smb_fname->base_name,
3324 if (!parent_dirname(talloc_tos(), smb_fname->base_name, &parent_dir,
3326 return NT_STATUS_NO_MEMORY;
3329 if (new_dos_attributes & FILE_FLAG_POSIX_SEMANTICS) {
3331 unx_mode = (mode_t)(new_dos_attributes & ~FILE_FLAG_POSIX_SEMANTICS);
3332 new_dos_attributes = 0;
3334 /* Windows allows a new file to be created and
3335 silently removes a FILE_ATTRIBUTE_DIRECTORY
3336 sent by the client. Do the same. */
3338 new_dos_attributes &= ~FILE_ATTRIBUTE_DIRECTORY;
3340 /* We add FILE_ATTRIBUTE_ARCHIVE to this as this mode is only used if the file is
3342 unx_mode = unix_mode(conn, new_dos_attributes | FILE_ATTRIBUTE_ARCHIVE,
3343 smb_fname, parent_dir);
3346 DEBUG(10, ("open_file_ntcreate: fname=%s, dos_attrs=0x%x "
3347 "access_mask=0x%x share_access=0x%x "
3348 "create_disposition = 0x%x create_options=0x%x "
3349 "unix mode=0%o oplock_request=%d private_flags = 0x%x\n",
3350 smb_fname_str_dbg(smb_fname), new_dos_attributes,
3351 access_mask, share_access, create_disposition,
3352 create_options, (unsigned int)unx_mode, oplock_request,
3353 (unsigned int)private_flags));
3356 /* Ensure req == NULL means INTERNAL_OPEN_ONLY */
3357 SMB_ASSERT(oplock_request == INTERNAL_OPEN_ONLY);
3359 /* And req != NULL means no INTERNAL_OPEN_ONLY */
3360 SMB_ASSERT(((oplock_request & INTERNAL_OPEN_ONLY) == 0));
3364 * Only non-internal opens can be deferred at all
3368 struct deferred_open_record *open_rec;
3369 if (get_deferred_open_message_state(req, NULL, &open_rec)) {
3371 /* If it was an async create retry, the file
3374 if (is_deferred_open_async(open_rec)) {
3375 SET_STAT_INVALID(smb_fname->st);
3376 file_existed = false;
3379 /* Ensure we don't reprocess this message. */
3380 remove_deferred_open_message_smb(req->xconn, req->mid);
3382 first_open_attempt = false;
3387 new_dos_attributes &= SAMBA_ATTRIBUTES_MASK;
3390 * Only use stored DOS attributes for checks
3391 * against requested attributes (below via
3392 * open_match_attributes()), cf bug #11992
3393 * for details. -slow
3397 status = SMB_VFS_GET_DOS_ATTRIBUTES(conn, smb_fname, &attr);
3398 if (NT_STATUS_IS_OK(status)) {
3399 existing_dos_attributes = attr;
3404 /* ignore any oplock requests if oplocks are disabled */
3405 if (!lp_oplocks(SNUM(conn)) ||
3406 IS_VETO_OPLOCK_PATH(conn, smb_fname->base_name)) {
3407 /* Mask off everything except the private Samba bits. */
3408 oplock_request &= SAMBA_PRIVATE_OPLOCK_MASK;
3411 /* this is for OS/2 long file names - say we don't support them */
3412 if (req != NULL && !req->posix_pathnames &&
3413 strstr(smb_fname->base_name,".+,;=[].")) {
3414 /* OS/2 Workplace shell fix may be main code stream in a later
3416 DEBUG(5,("open_file_ntcreate: OS/2 long filenames are not "
3418 if (use_nt_status()) {
3419 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3421 return NT_STATUS_DOS(ERRDOS, ERRcannotopen);
3424 switch( create_disposition ) {
3426 /* If file exists open. If file doesn't exist error. */
3427 if (!file_existed) {
3428 DEBUG(5,("open_file_ntcreate: FILE_OPEN "
3429 "requested for file %s and file "
3431 smb_fname_str_dbg(smb_fname)));
3433 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3437 case FILE_OVERWRITE:
3438 /* If file exists overwrite. If file doesn't exist
3440 if (!file_existed) {
3441 DEBUG(5,("open_file_ntcreate: FILE_OVERWRITE "
3442 "requested for file %s and file "
3444 smb_fname_str_dbg(smb_fname) ));
3446 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3451 /* If file exists error. If file doesn't exist
3454 DEBUG(5,("open_file_ntcreate: FILE_CREATE "
3455 "requested for file %s and file "
3456 "already exists.\n",
3457 smb_fname_str_dbg(smb_fname)));
3458 if (S_ISDIR(smb_fname->st.st_ex_mode)) {
3463 return map_nt_error_from_unix(errno);
3467 case FILE_SUPERSEDE:
3468 case FILE_OVERWRITE_IF:
3472 return NT_STATUS_INVALID_PARAMETER;
3475 flags2 = disposition_to_open_flags(create_disposition);
3477 /* We only care about matching attributes on file exists and
3480 if (!posix_open && file_existed &&
3481 ((create_disposition == FILE_OVERWRITE) ||
3482 (create_disposition == FILE_OVERWRITE_IF))) {
3483 if (!open_match_attributes(conn, existing_dos_attributes,
3485 unx_mode, &new_unx_mode)) {
3486 DEBUG(5,("open_file_ntcreate: attributes mismatch "
3487 "for file %s (%x %x) (0%o, 0%o)\n",
3488 smb_fname_str_dbg(smb_fname),
3489 existing_dos_attributes,
3491 (unsigned int)smb_fname->st.st_ex_mode,
3492 (unsigned int)unx_mode ));
3494 return NT_STATUS_ACCESS_DENIED;
3498 status = smbd_calculate_access_mask(conn, smb_fname,
3502 if (!NT_STATUS_IS_OK(status)) {
3503 DEBUG(10, ("open_file_ntcreate: smbd_calculate_access_mask "
3504 "on file %s returned %s\n",
3505 smb_fname_str_dbg(smb_fname), nt_errstr(status)));
3509 open_access_mask = access_mask;
3511 if (flags2 & O_TRUNC) {
3512 open_access_mask |= FILE_WRITE_DATA; /* This will cause oplock breaks. */
3517 * stat opens on existing files don't get oplocks.
3518 * They can get leases.
3520 * Note that we check for stat open on the *open_access_mask*,
3521 * i.e. the access mask we actually used to do the open,
3522 * not the one the client asked for (which is in
3523 * fsp->access_mask). This is due to the fact that
3524 * FILE_OVERWRITE and FILE_OVERWRITE_IF add in O_TRUNC,
3525 * which adds FILE_WRITE_DATA to open_access_mask.
3527 if (is_stat_open(open_access_mask) && lease == NULL) {
3528 oplock_request = NO_OPLOCK;
3532 DEBUG(10, ("open_file_ntcreate: fname=%s, after mapping "
3533 "access_mask=0x%x\n", smb_fname_str_dbg(smb_fname),
3537 * Note that we ignore the append flag as append does not
3538 * mean the same thing under DOS and Unix.
3541 flags = calculate_open_access_flags(access_mask, private_flags);
3544 * Currently we only look at FILE_WRITE_THROUGH for create options.
3548 if ((create_options & FILE_WRITE_THROUGH) && lp_strict_sync(SNUM(conn))) {
3553 if (posix_open && (access_mask & FILE_APPEND_DATA)) {
3557 if (!posix_open && !CAN_WRITE(conn)) {
3559 * We should really return a permission denied error if either
3560 * O_CREAT or O_TRUNC are set, but for compatibility with
3561 * older versions of Samba we just AND them out.
3563 flags2 &= ~(O_CREAT|O_TRUNC);
3567 * With kernel oplocks the open breaking an oplock
3568 * blocks until the oplock holder has given up the
3569 * oplock or closed the file. We prevent this by always
3570 * trying to open the file with O_NONBLOCK (see "man
3573 * If a process that doesn't use the smbd open files
3574 * database or communication methods holds a kernel
3575 * oplock we must periodically poll for available open
3578 flags2 |= O_NONBLOCK;
3581 * Ensure we can't write on a read-only share or file.
3584 if (flags != O_RDONLY && file_existed &&
3585 (!CAN_WRITE(conn) || IS_DOS_READONLY(existing_dos_attributes))) {
3586 DEBUG(5,("open_file_ntcreate: write access requested for "
3587 "file %s on read only %s\n",
3588 smb_fname_str_dbg(smb_fname),
3589 !CAN_WRITE(conn) ? "share" : "file" ));
3591 return NT_STATUS_ACCESS_DENIED;
3594 fsp->file_id = vfs_file_id_from_sbuf(conn, &smb_fname->st);
3595 fsp->fh->private_options = private_flags;
3596 fsp->access_mask = open_access_mask; /* We change this to the
3597 * requested access_mask after
3598 * the open is done. */
3600 fsp->posix_flags |= FSP_POSIX_FLAGS_ALL;
3603 if ((create_options & FILE_DELETE_ON_CLOSE) &&
3604 (flags2 & O_CREAT) &&
3606 /* Delete on close semantics for new files. */
3607 status = can_set_delete_on_close(fsp,
3608 new_dos_attributes);
3609 if (!NT_STATUS_IS_OK(status)) {
3616 * Ensure we pay attention to default ACLs on directories if required.
3619 if ((flags2 & O_CREAT) && lp_inherit_acls(SNUM(conn)) &&
3620 (def_acl = directory_has_default_acl(conn, parent_dir))) {
3621 unx_mode = (0777 & lp_create_mask(SNUM(conn)));
3624 DEBUG(4,("calling open_file with flags=0x%X flags2=0x%X mode=0%o, "
3625 "access_mask = 0x%x, open_access_mask = 0x%x\n",
3626 (unsigned int)flags, (unsigned int)flags2,
3627 (unsigned int)unx_mode, (unsigned int)access_mask,
3628 (unsigned int)open_access_mask));
3630 fsp_open = open_file(fsp, conn, req, parent_dir,
3631 flags|flags2, unx_mode, access_mask,
3632 open_access_mask, &new_file_created);
3634 if (NT_STATUS_EQUAL(fsp_open, NT_STATUS_NETWORK_BUSY)) {
3636 * This handles the kernel oplock case:
3638 * the file has an active kernel oplock and the open() returned
3639 * EWOULDBLOCK/EAGAIN which maps to NETWORK_BUSY.
3641 * "Samba locking.tdb oplocks" are handled below after acquiring
3642 * the sharemode lock with get_share_mode_lock().
3644 if (file_existed && S_ISFIFO(fsp->fsp_name->st.st_ex_mode)) {
3645 DEBUG(10, ("FIFO busy\n"));
3646 return NT_STATUS_NETWORK_BUSY;
3649 DEBUG(10, ("Internal open busy\n"));
3650 return NT_STATUS_NETWORK_BUSY;
3654 * From here on we assume this is an oplock break triggered
3657 lck = get_existing_share_mode_lock(talloc_tos(), fsp->file_id);
3659 if ((lck != NULL) && !validate_oplock_types(lck)) {
3660 smb_panic("validate_oplock_types failed");
3664 * Retry once a second. If there's a share_mode_lock
3665 * around, also wait for it in case it was smbd
3666 * holding that kernel oplock that can quickly tell us
3667 * the oplock got removed.
3674 timeval_set(OPLOCK_BREAK_TIMEOUT*2, 0),
3679 return NT_STATUS_SHARING_VIOLATION;
3682 if (!NT_STATUS_IS_OK(fsp_open)) {
3683 if (NT_STATUS_EQUAL(fsp_open, NT_STATUS_RETRY)) {
3684 schedule_async_open(req);
3689 if (new_file_created) {
3691 * As we atomically create using O_CREAT|O_EXCL,
3692 * then if new_file_created is true, then
3693 * file_existed *MUST* have been false (even
3694 * if the file was previously detected as being
3697 file_existed = false;
3700 if (file_existed && !check_same_dev_ino(&saved_stat, &smb_fname->st)) {
3702 * The file did exist, but some other (local or NFS)
3703 * process either renamed/unlinked and re-created the
3704 * file with different dev/ino after we walked the path,
3705 * but before we did the open. We could retry the
3706 * open but it's a rare enough case it's easier to
3707 * just fail the open to prevent creating any problems
3708 * in the open file db having the wrong dev/ino key.
3711 DBG_WARNING("file %s - dev/ino mismatch. "
3712 "Old (dev=%ju, ino=%ju). "
3713 "New (dev=%ju, ino=%ju). Failing open "
3714 "with NT_STATUS_ACCESS_DENIED.\n",
3715 smb_fname_str_dbg(smb_fname),
3716 (uintmax_t)saved_stat.st_ex_dev,
3717 (uintmax_t)saved_stat.st_ex_ino,
3718 (uintmax_t)smb_fname->st.st_ex_dev,
3719 (uintmax_t)smb_fname->st.st_ex_ino);
3720 return NT_STATUS_ACCESS_DENIED;
3723 old_write_time = smb_fname->st.st_ex_mtime;
3726 * Deal with the race condition where two smbd's detect the
3727 * file doesn't exist and do the create at the same time. One
3728 * of them will win and set a share mode, the other (ie. this
3729 * one) should check if the requested share mode for this
3730 * create is allowed.
3734 * Now the file exists and fsp is successfully opened,
3735 * fsp->dev and fsp->inode are valid and should replace the
3736 * dev=0,inode=0 from a non existent file. Spotted by
3737 * Nadav Danieli <nadavd@exanet.com>. JRA.
3742 lck = get_share_mode_lock(talloc_tos(), id,
3744 smb_fname, &old_write_time);
3747 DEBUG(0, ("open_file_ntcreate: Could not get share "
3748 "mode lock for %s\n",
3749 smb_fname_str_dbg(smb_fname)));
3751 return NT_STATUS_SHARING_VIOLATION;
3754 /* Get the types we need to examine. */
3755 if (!validate_oplock_types(lck)) {
3756 smb_panic("validate_oplock_types failed");
3759 if (has_delete_on_close(lck, fsp->name_hash)) {
3762 return NT_STATUS_DELETE_PENDING;
3765 status = handle_share_mode_lease(
3773 first_open_attempt);
3775 if (NT_STATUS_EQUAL(status, NT_STATUS_RETRY)) {
3776 schedule_defer_open(lck, fsp->file_id, req);
3779 return NT_STATUS_SHARING_VIOLATION;
3782 if (!NT_STATUS_IS_OK(status)) {
3789 struct share_mode_data *d = lck->data;
3790 uint16_t new_flags = share_mode_flags_restrict(
3791 d->flags, access_mask, share_access, UINT32_MAX);
3793 if (new_flags != d->flags) {
3794 d->flags = new_flags;
3799 ok = set_share_mode(
3802 get_current_uid(fsp->conn),
3808 if (fsp->oplock_type == LEASE_OPLOCK) {
3809 status = remove_lease_if_stale(
3811 fsp_client_guid(fsp),
3812 &fsp->lease->lease.lease_key);
3813 if (!NT_STATUS_IS_OK(status)) {
3814 DBG_WARNING("remove_lease_if_stale "
3819 return NT_STATUS_NO_MEMORY;
3822 /* Should we atomically (to the client at least) truncate ? */
3823 if ((!new_file_created) &&
3824 (flags2 & O_TRUNC) &&
3825 (S_ISREG(fsp->fsp_name->st.st_ex_mode))) {
3828 ret = SMB_VFS_FTRUNCATE(fsp, 0);
3830 status = map_nt_error_from_unix(errno);
3831 del_share_mode(lck, fsp);
3836 notify_fname(fsp->conn, NOTIFY_ACTION_MODIFIED,
3837 FILE_NOTIFY_CHANGE_SIZE
3838 | FILE_NOTIFY_CHANGE_ATTRIBUTES,
3839 fsp->fsp_name->base_name);
3843 * We have the share entry *locked*.....
3846 /* Delete streams if create_disposition requires it */
3847 if (!new_file_created && clear_ads(create_disposition) &&
3848 !is_ntfs_stream_smb_fname(smb_fname)) {
3849 status = delete_all_streams(conn, smb_fname);
3850 if (!NT_STATUS_IS_OK(status)) {
3851 del_share_mode(lck, fsp);
3858 if (fsp->fh->fd != -1 && lp_kernel_share_modes(SNUM(conn))) {
3861 * Beware: streams implementing VFS modules may
3862 * implement streams in a way that fsp will have the
3863 * basefile open in the fsp fd, so lacking a distinct
3864 * fd for the stream kernel_flock will apply on the
3865 * basefile which is wrong. The actual check is
3866 * deferred to the VFS module implementing the
3867 * kernel_flock call.
3869 ret_flock = SMB_VFS_KERNEL_FLOCK(fsp, share_access, access_mask);
3870 if(ret_flock == -1 ){
3872 del_share_mode(lck, fsp);
3876 return NT_STATUS_SHARING_VIOLATION;
3879 fsp->kernel_share_modes_taken = true;
3883 * At this point onwards, we can guarantee that the share entry
3884 * is locked, whether we created the file or not, and that the
3885 * deny mode is compatible with all current opens.
3889 * According to Samba4, SEC_FILE_READ_ATTRIBUTE is always granted,
3890 * but we don't have to store this - just ignore it on access check.
3892 if (conn->sconn->using_smb2) {
3894 * SMB2 doesn't return it (according to Microsoft tests).
3895 * Test Case: TestSuite_ScenarioNo009GrantedAccessTestS0
3896 * File created with access = 0x7 (Read, Write, Delete)
3897 * Query Info on file returns 0x87 (Read, Write, Delete, Read Attributes)
3899 fsp->access_mask = access_mask;
3901 /* But SMB1 does. */
3902 fsp->access_mask = access_mask | FILE_READ_ATTRIBUTES;
3905 if (new_file_created) {
3906 info = FILE_WAS_CREATED;
3908 if (flags2 & O_TRUNC) {
3909 info = FILE_WAS_OVERWRITTEN;
3911 info = FILE_WAS_OPENED;
3919 /* Handle strange delete on close create semantics. */
3920 if (create_options & FILE_DELETE_ON_CLOSE) {
3921 if (!new_file_created) {
3922 status = can_set_delete_on_close(fsp,
3923 existing_dos_attributes);
3925 if (!NT_STATUS_IS_OK(status)) {
3926 /* Remember to delete the mode we just added. */
3927 del_share_mode(lck, fsp);
3933 /* Note that here we set the *initial* delete on close flag,
3934 not the regular one. The magic gets handled in close. */
3935 fsp->initial_delete_on_close = True;
3939 * If we created a file and it's not a stream, this is the point where
3940 * we set the itime (aka invented time) that get's stored in the DOS
3941 * attribute xattr. The value is going to be either what the filesystem
3942 * provided or a copy of the creation date.
3944 * Either way, we turn the itime into a File-ID, unless the filesystem
3945 * provided one (unlikely).
3947 if (info == FILE_WAS_CREATED && !is_named_stream(smb_fname)) {
3948 smb_fname->st.st_ex_iflags &= ~ST_EX_IFLAG_CALCULATED_ITIME;
3950 if (lp_store_dos_attributes(SNUM(conn)) &&
3951 smb_fname->st.st_ex_iflags & ST_EX_IFLAG_CALCULATED_FILE_ID)
3955 file_id = make_file_id_from_itime(&smb_fname->st);
3956 update_stat_ex_file_id(&smb_fname->st, file_id);
3960 if (info != FILE_WAS_OPENED) {
3961 /* Overwritten files should be initially set as archive */
3962 if ((info == FILE_WAS_OVERWRITTEN && lp_map_archive(SNUM(conn))) ||
3963 lp_store_dos_attributes(SNUM(conn))) {
3964 (void)dos_mode(conn, smb_fname);
3966 if (file_set_dosmode(conn, smb_fname,
3967 new_dos_attributes | FILE_ATTRIBUTE_ARCHIVE,
3968 parent_dir, true) == 0) {
3969 unx_mode = smb_fname->st.st_ex_mode;
3975 /* Determine sparse flag. */
3977 /* POSIX opens are sparse by default. */
3978 fsp->is_sparse = true;
3981 (existing_dos_attributes & FILE_ATTRIBUTE_SPARSE);
3985 * Take care of inherited ACLs on created files - if default ACL not
3989 if (!posix_open && new_file_created && !def_acl) {
3990 if (unx_mode != smb_fname->st.st_ex_mode) {
3991 int ret = SMB_VFS_FCHMOD(fsp, unx_mode);
3993 DBG_INFO("failed to reset "
3994 "attributes of file %s to 0%o\n",
3995 smb_fname_str_dbg(smb_fname),
3996 (unsigned int)unx_mode);
4000 } else if (new_unx_mode) {
4002 * We only get here in the case of:
4004 * a). Not a POSIX open.
4005 * b). File already existed.
4006 * c). File was overwritten.
4007 * d). Requested DOS attributes didn't match
4008 * the DOS attributes on the existing file.
4010 * In that case new_unx_mode has been set
4011 * equal to the calculated mode (including
4012 * possible inheritance of the mode from the
4013 * containing directory).
4015 * Note this mode was calculated with the
4016 * DOS attribute FILE_ATTRIBUTE_ARCHIVE added,
4017 * so the mode change here is suitable for
4018 * an overwritten file.
4021 if (new_unx_mode != smb_fname->st.st_ex_mode) {
4022 int ret = SMB_VFS_FCHMOD(fsp, new_unx_mode);
4024 DBG_INFO("failed to reset "
4025 "attributes of file %s to 0%o\n",
4026 smb_fname_str_dbg(smb_fname),
4027 (unsigned int)new_unx_mode);
4034 * Deal with other opens having a modified write time.
4036 struct timespec write_time = get_share_mode_write_time(lck);
4038 if (!null_timespec(write_time)) {
4039 update_stat_ex_mtime(&fsp->fsp_name->st, write_time);
4045 return NT_STATUS_OK;
4048 static NTSTATUS mkdir_internal(connection_struct *conn,
4049 struct smb_filename *smb_dname,
4050 uint32_t file_attributes)
4053 char *parent_dir = NULL;
4055 bool posix_open = false;
4056 bool need_re_stat = false;
4057 uint32_t access_mask = SEC_DIR_ADD_SUBDIR;
4060 if (!CAN_WRITE(conn) || (access_mask & ~(conn->share_access))) {
4061 DEBUG(5,("mkdir_internal: failing share access "
4062 "%s\n", lp_servicename(talloc_tos(), SNUM(conn))));
4063 return NT_STATUS_ACCESS_DENIED;
4066 if (!parent_dirname(talloc_tos(), smb_dname->base_name, &parent_dir,
4068 return NT_STATUS_NO_MEMORY;
4071 if (file_attributes & FILE_FLAG_POSIX_SEMANTICS) {
4073 mode = (mode_t)(file_attributes & ~FILE_FLAG_POSIX_SEMANTICS);
4075 mode = unix_mode(conn, FILE_ATTRIBUTE_DIRECTORY, smb_dname, parent_dir);
4078 status = check_parent_access(conn,
4081 if(!NT_STATUS_IS_OK(status)) {
4082 DEBUG(5,("mkdir_internal: check_parent_access "
4083 "on directory %s for path %s returned %s\n",
4085 smb_dname->base_name,
4086 nt_errstr(status) ));
4090 ret = SMB_VFS_MKDIRAT(conn,
4095 return map_nt_error_from_unix(errno);
4098 /* Ensure we're checking for a symlink here.... */
4099 /* We don't want to get caught by a symlink racer. */
4101 if (SMB_VFS_LSTAT(conn, smb_dname) == -1) {
4102 DEBUG(2, ("Could not stat directory '%s' just created: %s\n",
4103 smb_fname_str_dbg(smb_dname), strerror(errno)));
4104 return map_nt_error_from_unix(errno);
4107 if (!S_ISDIR(smb_dname->st.st_ex_mode)) {
4108 DEBUG(0, ("Directory '%s' just created is not a directory !\n",
4109 smb_fname_str_dbg(smb_dname)));
4110 return NT_STATUS_NOT_A_DIRECTORY;
4113 smb_dname->st.st_ex_iflags &= ~ST_EX_IFLAG_CALCULATED_ITIME;
4115 if (lp_store_dos_attributes(SNUM(conn))) {
4116 if (smb_dname->st.st_ex_iflags & ST_EX_IFLAG_CALCULATED_FILE_ID)
4120 file_id = make_file_id_from_itime(&smb_dname->st);
4121 update_stat_ex_file_id(&smb_dname->st, file_id);
4125 file_set_dosmode(conn, smb_dname,
4126 file_attributes | FILE_ATTRIBUTE_DIRECTORY,
4131 if (lp_inherit_permissions(SNUM(conn))) {
4132 inherit_access_posix_acl(conn, parent_dir,
4134 need_re_stat = true;
4139 * Check if high bits should have been set,
4140 * then (if bits are missing): add them.
4141 * Consider bits automagically set by UNIX, i.e. SGID bit from parent
4144 if ((mode & ~(S_IRWXU|S_IRWXG|S_IRWXO)) &&
4145 (mode & ~smb_dname->st.st_ex_mode)) {
4146 SMB_VFS_CHMOD(conn, smb_dname,
4147 (smb_dname->st.st_ex_mode |
4148 (mode & ~smb_dname->st.st_ex_mode)));
4149 need_re_stat = true;
4153 /* Change the owner if required. */
4154 if (lp_inherit_owner(SNUM(conn)) != INHERIT_OWNER_NO) {
4155 change_dir_owner_to_parent(conn, parent_dir,
4158 need_re_stat = true;
4162 if (SMB_VFS_LSTAT(conn, smb_dname) == -1) {
4163 DEBUG(2, ("Could not stat directory '%s' just created: %s\n",
4164 smb_fname_str_dbg(smb_dname), strerror(errno)));
4165 return map_nt_error_from_unix(errno);
4169 notify_fname(conn, NOTIFY_ACTION_ADDED, FILE_NOTIFY_CHANGE_DIR_NAME,
4170 smb_dname->base_name);
4172 return NT_STATUS_OK;
4175 /****************************************************************************
4176 Open a directory from an NT SMB call.
4177 ****************************************************************************/
4179 static NTSTATUS open_directory(connection_struct *conn,
4180 struct smb_request *req,
4181 struct smb_filename *smb_dname,
4182 uint32_t access_mask,
4183 uint32_t share_access,
4184 uint32_t create_disposition,
4185 uint32_t create_options,
4186 uint32_t file_attributes,
4188 files_struct **result)
4190 files_struct *fsp = NULL;
4191 bool dir_existed = VALID_STAT(smb_dname->st) ? True : False;
4192 struct share_mode_lock *lck = NULL;
4194 struct timespec mtimespec;
4198 if (is_ntfs_stream_smb_fname(smb_dname)) {
4199 DEBUG(2, ("open_directory: %s is a stream name!\n",
4200 smb_fname_str_dbg(smb_dname)));
4201 return NT_STATUS_NOT_A_DIRECTORY;
4204 if (!(file_attributes & FILE_FLAG_POSIX_SEMANTICS)) {
4205 /* Ensure we have a directory attribute. */
4206 file_attributes |= FILE_ATTRIBUTE_DIRECTORY;
4209 DEBUG(5,("open_directory: opening directory %s, access_mask = 0x%x, "
4210 "share_access = 0x%x create_options = 0x%x, "
4211 "create_disposition = 0x%x, file_attributes = 0x%x\n",
4212 smb_fname_str_dbg(smb_dname),
4213 (unsigned int)access_mask,
4214 (unsigned int)share_access,
4215 (unsigned int)create_options,
4216 (unsigned int)create_disposition,
4217 (unsigned int)file_attributes));
4219 status = smbd_calculate_access_mask(conn, smb_dname, false,
4220 access_mask, &access_mask);
4221 if (!NT_STATUS_IS_OK(status)) {
4222 DEBUG(10, ("open_directory: smbd_calculate_access_mask "
4223 "on file %s returned %s\n",
4224 smb_fname_str_dbg(smb_dname),
4225 nt_errstr(status)));
4229 if ((access_mask & SEC_FLAG_SYSTEM_SECURITY) &&
4230 !security_token_has_privilege(get_current_nttok(conn),
4231 SEC_PRIV_SECURITY)) {
4232 DEBUG(10, ("open_directory: open on %s "
4233 "failed - SEC_FLAG_SYSTEM_SECURITY denied.\n",
4234 smb_fname_str_dbg(smb_dname)));
4235 return NT_STATUS_PRIVILEGE_NOT_HELD;
4238 switch( create_disposition ) {
4242 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
4245 info = FILE_WAS_OPENED;
4250 /* If directory exists error. If directory doesn't
4254 status = NT_STATUS_OBJECT_NAME_COLLISION;
4255 DEBUG(2, ("open_directory: unable to create "
4256 "%s. Error was %s\n",
4257 smb_fname_str_dbg(smb_dname),
4258 nt_errstr(status)));
4262 status = mkdir_internal(conn, smb_dname,
4265 if (!NT_STATUS_IS_OK(status)) {
4266 DEBUG(2, ("open_directory: unable to create "
4267 "%s. Error was %s\n",
4268 smb_fname_str_dbg(smb_dname),
4269 nt_errstr(status)));
4273 info = FILE_WAS_CREATED;
4278 * If directory exists open. If directory doesn't
4283 status = NT_STATUS_OK;
4284 info = FILE_WAS_OPENED;
4286 status = mkdir_internal(conn, smb_dname,
4289 if (NT_STATUS_IS_OK(status)) {
4290 info = FILE_WAS_CREATED;
4292 /* Cope with create race. */
4293 if (!NT_STATUS_EQUAL(status,
4294 NT_STATUS_OBJECT_NAME_COLLISION)) {
4295 DEBUG(2, ("open_directory: unable to create "
4296 "%s. Error was %s\n",
4297 smb_fname_str_dbg(smb_dname),
4298 nt_errstr(status)));
4303 * If mkdir_internal() returned
4304 * NT_STATUS_OBJECT_NAME_COLLISION
4305 * we still must lstat the path.
4308 if (SMB_VFS_LSTAT(conn, smb_dname)
4310 DEBUG(2, ("Could not stat "
4311 "directory '%s' just "
4316 return map_nt_error_from_unix(
4320 info = FILE_WAS_OPENED;
4326 case FILE_SUPERSEDE:
4327 case FILE_OVERWRITE:
4328 case FILE_OVERWRITE_IF:
4330 DEBUG(5,("open_directory: invalid create_disposition "
4331 "0x%x for directory %s\n",
4332 (unsigned int)create_disposition,
4333 smb_fname_str_dbg(smb_dname)));
4334 return NT_STATUS_INVALID_PARAMETER;
4337 if(!S_ISDIR(smb_dname->st.st_ex_mode)) {
4338 DEBUG(5,("open_directory: %s is not a directory !\n",
4339 smb_fname_str_dbg(smb_dname)));
4340 return NT_STATUS_NOT_A_DIRECTORY;
4343 if (info == FILE_WAS_OPENED) {
4344 status = smbd_check_access_rights(conn,
4348 if (!NT_STATUS_IS_OK(status)) {
4349 DEBUG(10, ("open_directory: smbd_check_access_rights on "
4350 "file %s failed with %s\n",
4351 smb_fname_str_dbg(smb_dname),
4352 nt_errstr(status)));
4357 status = file_new(req, conn, &fsp);
4358 if(!NT_STATUS_IS_OK(status)) {
4363 * Setup the files_struct for it.
4366 fsp->file_id = vfs_file_id_from_sbuf(conn, &smb_dname->st);
4367 fsp->vuid = req ? req->vuid : UID_FIELD_INVALID;
4368 fsp->file_pid = req ? req->smbpid : 0;
4369 fsp->can_lock = False;
4370 fsp->can_read = False;
4371 fsp->can_write = False;
4373 fsp->fh->private_options = 0;
4375 * According to Samba4, SEC_FILE_READ_ATTRIBUTE is always granted,
4377 fsp->access_mask = access_mask | FILE_READ_ATTRIBUTES;
4378 fsp->print_file = NULL;
4379 fsp->modified = False;
4380 fsp->oplock_type = NO_OPLOCK;
4381 fsp->sent_oplock_break = NO_BREAK_SENT;
4382 fsp->is_directory = True;
4383 if (file_attributes & FILE_FLAG_POSIX_SEMANTICS) {
4384 fsp->posix_flags |= FSP_POSIX_FLAGS_ALL;
4386 status = fsp_set_smb_fname(fsp, smb_dname);
4387 if (!NT_STATUS_IS_OK(status)) {
4388 file_free(req, fsp);
4392 /* Don't store old timestamps for directory
4393 handles in the internal database. We don't
4394 update them in there if new objects
4395 are creaded in the directory. Currently
4396 we only update timestamps on file writes.
4399 ZERO_STRUCT(mtimespec);
4402 status = fd_open(conn, fsp, O_RDONLY|O_DIRECTORY, 0);
4404 /* POSIX allows us to open a directory with O_RDONLY. */
4405 status = fd_open(conn, fsp, O_RDONLY, 0);
4407 if (!NT_STATUS_IS_OK(status)) {
4408 DBG_INFO("Could not open fd for "
4410 smb_fname_str_dbg(smb_dname),
4412 file_free(req, fsp);
4416 status = vfs_stat_fsp(fsp);
4417 if (!NT_STATUS_IS_OK(status)) {
4419 file_free(req, fsp);
4423 if(!S_ISDIR(fsp->fsp_name->st.st_ex_mode)) {
4424 DEBUG(5,("open_directory: %s is not a directory !\n",
4425 smb_fname_str_dbg(smb_dname)));
4427 file_free(req, fsp);
4428 return NT_STATUS_NOT_A_DIRECTORY;
4431 /* Ensure there was no race condition. We need to check
4432 * dev/inode but not permissions, as these can change
4434 if (!check_same_dev_ino(&smb_dname->st, &fsp->fsp_name->st)) {
4435 DEBUG(5,("open_directory: stat struct differs for "
4437 smb_fname_str_dbg(smb_dname)));
4439 file_free(req, fsp);
4440 return NT_STATUS_ACCESS_DENIED;
4443 lck = get_share_mode_lock(talloc_tos(), fsp->file_id,
4444 conn->connectpath, smb_dname,
4448 DEBUG(0, ("open_directory: Could not get share mode lock for "
4449 "%s\n", smb_fname_str_dbg(smb_dname)));
4451 file_free(req, fsp);
4452 return NT_STATUS_SHARING_VIOLATION;
4455 if (has_delete_on_close(lck, fsp->name_hash)) {
4458 file_free(req, fsp);
4459 return NT_STATUS_DELETE_PENDING;
4462 status = open_mode_check(conn, lck,
4463 access_mask, share_access);
4465 if (!NT_STATUS_IS_OK(status)) {
4468 file_free(req, fsp);
4473 struct share_mode_data *d = lck->data;
4474 uint16_t new_flags = share_mode_flags_restrict(
4475 d->flags, access_mask, share_access, UINT32_MAX);
4477 if (new_flags != d->flags) {
4478 d->flags = new_flags;
4483 ok = set_share_mode(
4486 get_current_uid(conn),
4494 file_free(req, fsp);
4495 return NT_STATUS_NO_MEMORY;
4498 /* For directories the delete on close bit at open time seems
4499 always to be honored on close... See test 19 in Samba4 BASE-DELETE. */
4500 if (create_options & FILE_DELETE_ON_CLOSE) {
4501 status = can_set_delete_on_close(fsp, 0);
4502 if (!NT_STATUS_IS_OK(status) && !NT_STATUS_EQUAL(status, NT_STATUS_DIRECTORY_NOT_EMPTY)) {
4503 del_share_mode(lck, fsp);
4506 file_free(req, fsp);
4510 if (NT_STATUS_IS_OK(status)) {
4511 /* Note that here we set the *initial* delete on close flag,
4512 not the regular one. The magic gets handled in close. */
4513 fsp->initial_delete_on_close = True;
4519 * Deal with other opens having a modified write time. Is this
4520 * possible for directories?
4522 struct timespec write_time = get_share_mode_write_time(lck);
4524 if (!null_timespec(write_time)) {
4525 update_stat_ex_mtime(&fsp->fsp_name->st, write_time);
4536 return NT_STATUS_OK;
4539 NTSTATUS create_directory(connection_struct *conn, struct smb_request *req,
4540 struct smb_filename *smb_dname)
4545 status = SMB_VFS_CREATE_FILE(
4548 0, /* root_dir_fid */
4549 smb_dname, /* fname */
4550 FILE_READ_ATTRIBUTES, /* access_mask */
4551 FILE_SHARE_NONE, /* share_access */
4552 FILE_CREATE, /* create_disposition*/
4553 FILE_DIRECTORY_FILE, /* create_options */
4554 FILE_ATTRIBUTE_DIRECTORY, /* file_attributes */
4555 0, /* oplock_request */
4557 0, /* allocation_size */
4558 0, /* private_flags */
4563 NULL, NULL); /* create context */
4565 if (NT_STATUS_IS_OK(status)) {
4566 close_file(req, fsp, NORMAL_CLOSE);
4572 /****************************************************************************
4573 Receive notification that one of our open files has been renamed by another
4575 ****************************************************************************/
4577 void msg_file_was_renamed(struct messaging_context *msg_ctx,
4580 struct server_id src,
4583 struct file_rename_message *msg = NULL;
4584 enum ndr_err_code ndr_err;
4586 struct smb_filename *smb_fname = NULL;
4587 struct smbd_server_connection *sconn =
4588 talloc_get_type_abort(private_data,
4589 struct smbd_server_connection);
4591 msg = talloc(talloc_tos(), struct file_rename_message);
4593 DBG_WARNING("talloc failed\n");
4597 ndr_err = ndr_pull_struct_blob_all(
4601 (ndr_pull_flags_fn_t)ndr_pull_file_rename_message);
4602 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
4603 DBG_DEBUG("ndr_pull_oplock_break_message failed: %s\n",
4604 ndr_errstr(ndr_err));
4607 if (DEBUGLEVEL >= 10) {
4608 struct server_id_buf buf;
4609 DBG_DEBUG("Got rename message from %s\n",
4610 server_id_str_buf(src, &buf));
4611 NDR_PRINT_DEBUG(file_rename_message, msg);
4614 /* stream_name must always be NULL if there is no stream. */
4615 if ((msg->stream_name != NULL) && (msg->stream_name[0] == '\0')) {
4616 msg->stream_name = NULL;
4619 smb_fname = synthetic_smb_fname(
4620 msg, msg->base_name, msg->stream_name, NULL, 0);
4621 if (smb_fname == NULL) {
4622 DBG_DEBUG("synthetic_smb_fname failed\n");
4626 fsp = file_find_dif(sconn, msg->id, msg->share_file_id);
4628 DBG_DEBUG("fsp not found\n");
4632 if (strcmp(fsp->conn->connectpath, msg->servicepath) == 0) {
4634 DBG_DEBUG("renaming file %s from %s -> %s\n",
4637 smb_fname_str_dbg(smb_fname));
4638 status = fsp_set_smb_fname(fsp, smb_fname);
4639 if (!NT_STATUS_IS_OK(status)) {
4640 DBG_DEBUG("fsp_set_smb_fname failed: %s\n",
4646 * Now we have the complete path we can work out if
4647 * this is actually within this share and adjust
4648 * newname accordingly.
4650 DBG_DEBUG("share mismatch (sharepath %s not sharepath %s) "
4651 "%s from %s -> %s\n",
4652 fsp->conn->connectpath,
4656 smb_fname_str_dbg(smb_fname));
4663 * If a main file is opened for delete, all streams need to be checked for
4664 * !FILE_SHARE_DELETE. Do this by opening with DELETE_ACCESS.
4665 * If that works, delete them all by setting the delete on close and close.
4668 static NTSTATUS open_streams_for_delete(connection_struct *conn,
4669 const struct smb_filename *smb_fname)
4671 struct stream_struct *stream_info = NULL;
4672 files_struct **streams = NULL;
4674 unsigned int i, num_streams = 0;
4675 TALLOC_CTX *frame = talloc_stackframe();
4678 status = vfs_streaminfo(conn, NULL, smb_fname, talloc_tos(),
4679 &num_streams, &stream_info);
4681 if (NT_STATUS_EQUAL(status, NT_STATUS_NOT_IMPLEMENTED)
4682 || NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
4683 DEBUG(10, ("no streams around\n"));
4685 return NT_STATUS_OK;
4688 if (!NT_STATUS_IS_OK(status)) {
4689 DEBUG(10, ("vfs_streaminfo failed: %s\n",
4690 nt_errstr(status)));
4694 DEBUG(10, ("open_streams_for_delete found %d streams\n",
4697 if (num_streams == 0) {
4699 return NT_STATUS_OK;
4702 streams = talloc_array(talloc_tos(), files_struct *, num_streams);
4703 if (streams == NULL) {
4704 DEBUG(0, ("talloc failed\n"));
4705 status = NT_STATUS_NO_MEMORY;
4709 for (i=0; i<num_streams; i++) {
4710 struct smb_filename *smb_fname_cp;
4712 if (strequal(stream_info[i].name, "::$DATA")) {
4717 smb_fname_cp = synthetic_smb_fname(talloc_tos(),
4718 smb_fname->base_name,
4719 stream_info[i].name,
4722 ~SMB_FILENAME_POSIX_PATH));
4723 if (smb_fname_cp == NULL) {
4724 status = NT_STATUS_NO_MEMORY;
4728 if (SMB_VFS_STAT(conn, smb_fname_cp) == -1) {
4729 DEBUG(10, ("Unable to stat stream: %s\n",
4730 smb_fname_str_dbg(smb_fname_cp)));
4733 status = SMB_VFS_CREATE_FILE(
4736 0, /* root_dir_fid */
4737 smb_fname_cp, /* fname */
4738 DELETE_ACCESS, /* access_mask */
4739 (FILE_SHARE_READ | /* share_access */
4740 FILE_SHARE_WRITE | FILE_SHARE_DELETE),
4741 FILE_OPEN, /* create_disposition*/
4742 0, /* create_options */
4743 FILE_ATTRIBUTE_NORMAL, /* file_attributes */
4744 0, /* oplock_request */
4746 0, /* allocation_size */
4747 NTCREATEX_OPTIONS_PRIVATE_STREAM_DELETE, /* private_flags */
4750 &streams[i], /* result */
4752 NULL, NULL); /* create context */
4754 if (!NT_STATUS_IS_OK(status)) {
4755 DEBUG(10, ("Could not open stream %s: %s\n",
4756 smb_fname_str_dbg(smb_fname_cp),
4757 nt_errstr(status)));
4759 TALLOC_FREE(smb_fname_cp);
4762 TALLOC_FREE(smb_fname_cp);
4766 * don't touch the variable "status" beyond this point :-)
4769 for (j = i-1 ; j >= 0; j--) {
4770 if (streams[j] == NULL) {
4774 DEBUG(10, ("Closing stream # %d, %s\n", j,
4775 fsp_str_dbg(streams[j])));
4776 close_file(NULL, streams[j], NORMAL_CLOSE);
4784 /*********************************************************************
4785 Create a default ACL by inheriting from the parent. If no inheritance
4786 from the parent available, don't set anything. This will leave the actual
4787 permissions the new file or directory already got from the filesystem
4788 as the NT ACL when read.
4789 *********************************************************************/
4791 static NTSTATUS inherit_new_acl(files_struct *fsp)
4793 TALLOC_CTX *frame = talloc_stackframe();
4794 char *parent_name = NULL;
4795 struct security_descriptor *parent_desc = NULL;
4796 NTSTATUS status = NT_STATUS_OK;
4797 struct security_descriptor *psd = NULL;
4798 const struct dom_sid *owner_sid = NULL;
4799 const struct dom_sid *group_sid = NULL;
4800 uint32_t security_info_sent = (SECINFO_OWNER | SECINFO_GROUP | SECINFO_DACL);
4801 struct security_token *token = fsp->conn->session_info->security_token;
4802 bool inherit_owner =
4803 (lp_inherit_owner(SNUM(fsp->conn)) == INHERIT_OWNER_WINDOWS_AND_UNIX);
4804 bool inheritable_components = false;
4805 bool try_builtin_administrators = false;
4806 const struct dom_sid *BA_U_sid = NULL;
4807 const struct dom_sid *BA_G_sid = NULL;
4808 bool try_system = false;
4809 const struct dom_sid *SY_U_sid = NULL;
4810 const struct dom_sid *SY_G_sid = NULL;
4812 struct smb_filename *parent_smb_fname = NULL;
4814 if (!parent_dirname(frame, fsp->fsp_name->base_name, &parent_name, NULL)) {
4816 return NT_STATUS_NO_MEMORY;
4818 parent_smb_fname = synthetic_smb_fname(talloc_tos(),
4822 fsp->fsp_name->flags);
4824 if (parent_smb_fname == NULL) {
4826 return NT_STATUS_NO_MEMORY;
4829 status = SMB_VFS_GET_NT_ACL(fsp->conn,
4831 (SECINFO_OWNER | SECINFO_GROUP | SECINFO_DACL),
4834 if (!NT_STATUS_IS_OK(status)) {
4839 inheritable_components = sd_has_inheritable_components(parent_desc,
4842 if (!inheritable_components && !inherit_owner) {
4844 /* Nothing to inherit and not setting owner. */
4845 return NT_STATUS_OK;
4848 /* Create an inherited descriptor from the parent. */
4850 if (DEBUGLEVEL >= 10) {
4851 DEBUG(10,("inherit_new_acl: parent acl for %s is:\n",
4852 fsp_str_dbg(fsp) ));
4853 NDR_PRINT_DEBUG(security_descriptor, parent_desc);
4856 /* Inherit from parent descriptor if "inherit owner" set. */
4857 if (inherit_owner) {
4858 owner_sid = parent_desc->owner_sid;
4859 group_sid = parent_desc->group_sid;
4862 if (owner_sid == NULL) {
4863 if (security_token_has_builtin_administrators(token)) {
4864 try_builtin_administrators = true;
4865 } else if (security_token_is_system(token)) {
4866 try_builtin_administrators = true;
4871 if (group_sid == NULL &&
4872 token->num_sids == PRIMARY_GROUP_SID_INDEX)
4874 if (security_token_is_system(token)) {
4875 try_builtin_administrators = true;
4880 if (try_builtin_administrators) {
4885 ok = sids_to_unixids(&global_sid_Builtin_Administrators, 1, &ids);
4889 BA_U_sid = &global_sid_Builtin_Administrators;
4890 BA_G_sid = &global_sid_Builtin_Administrators;
4893 BA_U_sid = &global_sid_Builtin_Administrators;
4896 BA_G_sid = &global_sid_Builtin_Administrators;
4909 ok = sids_to_unixids(&global_sid_System, 1, &ids);
4913 SY_U_sid = &global_sid_System;
4914 SY_G_sid = &global_sid_System;
4917 SY_U_sid = &global_sid_System;
4920 SY_G_sid = &global_sid_System;
4928 if (owner_sid == NULL) {
4929 owner_sid = BA_U_sid;
4932 if (owner_sid == NULL) {
4933 owner_sid = SY_U_sid;
4936 if (group_sid == NULL) {
4937 group_sid = SY_G_sid;
4940 if (try_system && group_sid == NULL) {
4941 group_sid = BA_G_sid;
4944 if (owner_sid == NULL) {
4945 owner_sid = &token->sids[PRIMARY_USER_SID_INDEX];
4947 if (group_sid == NULL) {
4948 if (token->num_sids == PRIMARY_GROUP_SID_INDEX) {
4949 group_sid = &token->sids[PRIMARY_USER_SID_INDEX];
4951 group_sid = &token->sids[PRIMARY_GROUP_SID_INDEX];
4955 status = se_create_child_secdesc(frame,
4962 if (!NT_STATUS_IS_OK(status)) {
4967 /* If inheritable_components == false,
4968 se_create_child_secdesc()
4969 creates a security descriptor with a NULL dacl
4970 entry, but with SEC_DESC_DACL_PRESENT. We need
4971 to remove that flag. */
4973 if (!inheritable_components) {
4974 security_info_sent &= ~SECINFO_DACL;
4975 psd->type &= ~SEC_DESC_DACL_PRESENT;
4978 if (DEBUGLEVEL >= 10) {
4979 DEBUG(10,("inherit_new_acl: child acl for %s is:\n",
4980 fsp_str_dbg(fsp) ));
4981 NDR_PRINT_DEBUG(security_descriptor, psd);
4984 if (inherit_owner) {
4985 /* We need to be root to force this. */
4988 status = SMB_VFS_FSET_NT_ACL(fsp,
4991 if (inherit_owner) {
4999 * If we already have a lease, it must match the new file id. [MS-SMB2]
5000 * 3.3.5.9.8 speaks about INVALID_PARAMETER if an already used lease key is
5001 * used for a different file name.
5004 struct lease_match_state {
5005 /* Input parameters. */
5006 TALLOC_CTX *mem_ctx;
5007 const char *servicepath;
5008 const struct smb_filename *fname;
5011 /* Return parameters. */
5012 uint32_t num_file_ids;
5013 struct file_id *ids;
5014 NTSTATUS match_status;
5017 /*************************************************************
5018 File doesn't exist but this lease key+guid is already in use.
5020 This is only allowable in the dynamic share case where the
5021 service path must be different.
5023 There is a small race condition here in the multi-connection
5024 case where a client sends two create calls on different connections,
5025 where the file doesn't exist and one smbd creates the leases_db
5026 entry first, but this will get fixed by the multichannel cleanup
5027 when all identical client_guids get handled by a single smbd.
5028 **************************************************************/
5030 static void lease_match_parser_new_file(
5032 const struct leases_db_file *files,
5033 struct lease_match_state *state)
5037 for (i = 0; i < num_files; i++) {
5038 const struct leases_db_file *f = &files[i];
5039 if (strequal(state->servicepath, f->servicepath)) {
5040 state->match_status = NT_STATUS_INVALID_PARAMETER;
5045 /* Dynamic share case. Break leases on all other files. */
5046 state->match_status = leases_db_copy_file_ids(state->mem_ctx,
5050 if (!NT_STATUS_IS_OK(state->match_status)) {
5054 state->num_file_ids = num_files;
5055 state->match_status = NT_STATUS_OPLOCK_NOT_GRANTED;
5059 static void lease_match_parser(
5061 const struct leases_db_file *files,
5064 struct lease_match_state *state =
5065 (struct lease_match_state *)private_data;
5068 if (!state->file_existed) {
5070 * Deal with name mismatch or
5071 * possible dynamic share case separately
5072 * to make code clearer.
5074 lease_match_parser_new_file(num_files,
5081 state->match_status = NT_STATUS_OK;
5083 for (i = 0; i < num_files; i++) {
5084 const struct leases_db_file *f = &files[i];
5086 /* Everything should be the same. */
5087 if (!file_id_equal(&state->id, &f->id)) {
5088 /* This should catch all dynamic share cases. */
5089 state->match_status = NT_STATUS_OPLOCK_NOT_GRANTED;
5092 if (!strequal(f->servicepath, state->servicepath)) {
5093 state->match_status = NT_STATUS_INVALID_PARAMETER;
5096 if (!strequal(f->base_name, state->fname->base_name)) {
5097 state->match_status = NT_STATUS_INVALID_PARAMETER;
5100 if (!strequal(f->stream_name, state->fname->stream_name)) {
5101 state->match_status = NT_STATUS_INVALID_PARAMETER;
5106 if (NT_STATUS_IS_OK(state->match_status)) {
5108 * Common case - just opening another handle on a
5109 * file on a non-dynamic share.
5114 if (NT_STATUS_EQUAL(state->match_status, NT_STATUS_INVALID_PARAMETER)) {
5115 /* Mismatched path. Error back to client. */
5120 * File id mismatch. Dynamic share case NT_STATUS_OPLOCK_NOT_GRANTED.
5121 * Don't allow leases.
5124 state->match_status = leases_db_copy_file_ids(state->mem_ctx,
5128 if (!NT_STATUS_IS_OK(state->match_status)) {
5132 state->num_file_ids = num_files;
5133 state->match_status = NT_STATUS_OPLOCK_NOT_GRANTED;
5137 struct lease_match_break_state {
5138 struct messaging_context *msg_ctx;
5139 const struct smb2_lease_key *lease_key;
5147 static bool lease_match_break_fn(
5148 struct share_mode_entry *e,
5151 struct lease_match_break_state *state = private_data;
5153 uint32_t e_lease_type;
5156 stale = share_entry_stale_pid(e);
5161 equal = smb2_lease_key_equal(&e->lease_key, state->lease_key);
5166 status = leases_db_get(
5170 NULL, /* current_state */
5171 NULL, /* breaking */
5172 NULL, /* breaking_to_requested */
5173 NULL, /* breaking_to_required */
5174 &state->version, /* lease_version */
5175 &state->epoch); /* epoch */
5176 if (NT_STATUS_IS_OK(status)) {
5177 state->found_lease = true;
5179 DBG_WARNING("Could not find version/epoch: %s\n",
5183 e_lease_type = get_lease_type(e, state->id);
5184 if (e_lease_type == SMB2_LEASE_NONE) {
5187 send_break_message(state->msg_ctx, &state->id, e, SMB2_LEASE_NONE);
5190 * Windows 7 and 8 lease clients are broken in that they will
5191 * not respond to lease break requests whilst waiting for an
5192 * outstanding open request on that lease handle on the same
5193 * TCP connection, due to holding an internal inode lock.
5195 * This means we can't reschedule ourselves here, but must
5196 * return from the create.
5200 * Send the breaks and then return SMB2_LEASE_NONE in the
5201 * lease handle to cause them to acknowledge the lease
5202 * break. Consultation with Microsoft engineering confirmed
5203 * this approach is safe.
5209 static NTSTATUS lease_match(connection_struct *conn,
5210 struct smb_request *req,
5211 const struct smb2_lease_key *lease_key,
5212 const char *servicepath,
5213 const struct smb_filename *fname,
5214 uint16_t *p_version,
5217 struct smbd_server_connection *sconn = req->sconn;
5218 TALLOC_CTX *tos = talloc_tos();
5219 struct lease_match_state state = {
5221 .servicepath = servicepath,
5223 .match_status = NT_STATUS_OK
5228 state.file_existed = VALID_STAT(fname->st);
5229 if (state.file_existed) {
5230 state.id = vfs_file_id_from_sbuf(conn, &fname->st);
5233 status = leases_db_parse(&sconn->client->connections->smb2.client.guid,
5234 lease_key, lease_match_parser, &state);
5235 if (!NT_STATUS_IS_OK(status)) {
5237 * Not found or error means okay: We can make the lease pass
5239 return NT_STATUS_OK;
5241 if (!NT_STATUS_EQUAL(state.match_status, NT_STATUS_OPLOCK_NOT_GRANTED)) {
5243 * Anything but NT_STATUS_OPLOCK_NOT_GRANTED, let the caller
5246 return state.match_status;
5249 /* We have to break all existing leases. */
5250 for (i = 0; i < state.num_file_ids; i++) {
5251 struct lease_match_break_state break_state = {
5252 .msg_ctx = conn->sconn->msg_ctx,
5253 .lease_key = lease_key,
5255 struct share_mode_lock *lck;
5258 if (file_id_equal(&state.ids[i], &state.id)) {
5259 /* Don't need to break our own file. */
5263 break_state.id = state.ids[i];
5265 lck = get_existing_share_mode_lock(
5266 talloc_tos(), break_state.id);
5268 /* Race condition - file already closed. */
5272 ok = share_mode_forall_leases(
5273 lck, lease_match_break_fn, &break_state);
5275 DBG_DEBUG("share_mode_forall_leases failed\n");
5281 if (break_state.found_lease) {
5282 *p_version = break_state.version;
5283 *p_epoch = break_state.epoch;
5287 * Ensure we don't grant anything more so we
5290 return NT_STATUS_OPLOCK_NOT_GRANTED;
5294 * Wrapper around open_file_ntcreate and open_directory
5297 static NTSTATUS create_file_unixpath(connection_struct *conn,
5298 struct smb_request *req,
5299 struct smb_filename *smb_fname,
5300 uint32_t access_mask,
5301 uint32_t share_access,
5302 uint32_t create_disposition,
5303 uint32_t create_options,
5304 uint32_t file_attributes,
5305 uint32_t oplock_request,
5306 const struct smb2_lease *lease,
5307 uint64_t allocation_size,
5308 uint32_t private_flags,
5309 struct security_descriptor *sd,
5310 struct ea_list *ea_list,
5312 files_struct **result,
5315 struct smb2_lease none_lease;
5316 int info = FILE_WAS_OPENED;
5317 files_struct *base_fsp = NULL;
5318 files_struct *fsp = NULL;
5321 DBG_DEBUG("create_file_unixpath: access_mask = 0x%x "
5322 "file_attributes = 0x%x, share_access = 0x%x, "
5323 "create_disposition = 0x%x create_options = 0x%x "
5324 "oplock_request = 0x%x private_flags = 0x%x "
5325 "ea_list = %p, sd = %p, "
5327 (unsigned int)access_mask,
5328 (unsigned int)file_attributes,
5329 (unsigned int)share_access,
5330 (unsigned int)create_disposition,
5331 (unsigned int)create_options,
5332 (unsigned int)oplock_request,
5333 (unsigned int)private_flags,
5334 ea_list, sd, smb_fname_str_dbg(smb_fname));
5336 if (create_options & FILE_OPEN_BY_FILE_ID) {
5337 status = NT_STATUS_NOT_SUPPORTED;
5341 if (create_options & NTCREATEX_OPTIONS_INVALID_PARAM_MASK) {
5342 status = NT_STATUS_INVALID_PARAMETER;
5347 oplock_request |= INTERNAL_OPEN_ONLY;
5350 if (lease != NULL) {
5351 uint16_t epoch = lease->lease_epoch;
5352 uint16_t version = lease->lease_version;
5355 DBG_WARNING("Got lease on internal open\n");
5356 status = NT_STATUS_INTERNAL_ERROR;
5360 status = lease_match(conn,
5367 if (NT_STATUS_EQUAL(status, NT_STATUS_OPLOCK_NOT_GRANTED)) {
5368 /* Dynamic share file. No leases and update epoch... */
5369 none_lease = *lease;
5370 none_lease.lease_state = SMB2_LEASE_NONE;
5371 none_lease.lease_epoch = epoch;
5372 none_lease.lease_version = version;
5373 lease = &none_lease;
5374 } else if (!NT_STATUS_IS_OK(status)) {
5379 if ((conn->fs_capabilities & FILE_NAMED_STREAMS)
5380 && (access_mask & DELETE_ACCESS)
5381 && !is_ntfs_stream_smb_fname(smb_fname)) {
5383 * We can't open a file with DELETE access if any of the
5384 * streams is open without FILE_SHARE_DELETE
5386 status = open_streams_for_delete(conn, smb_fname);
5388 if (!NT_STATUS_IS_OK(status)) {
5393 if ((access_mask & SEC_FLAG_SYSTEM_SECURITY) &&
5394 !security_token_has_privilege(get_current_nttok(conn),
5395 SEC_PRIV_SECURITY)) {
5396 DEBUG(10, ("create_file_unixpath: open on %s "
5397 "failed - SEC_FLAG_SYSTEM_SECURITY denied.\n",
5398 smb_fname_str_dbg(smb_fname)));
5399 status = NT_STATUS_PRIVILEGE_NOT_HELD;
5404 * Files or directories can't be opened DELETE_ON_CLOSE without
5406 * BUG: https://bugzilla.samba.org/show_bug.cgi?id=13358
5408 if (create_options & FILE_DELETE_ON_CLOSE) {
5409 if ((access_mask & DELETE_ACCESS) == 0) {
5410 status = NT_STATUS_INVALID_PARAMETER;
5415 if ((conn->fs_capabilities & FILE_NAMED_STREAMS)
5416 && is_ntfs_stream_smb_fname(smb_fname)
5417 && (!(private_flags & NTCREATEX_OPTIONS_PRIVATE_STREAM_DELETE))) {
5418 uint32_t base_create_disposition;
5419 struct smb_filename *smb_fname_base = NULL;
5420 uint32_t base_privflags;
5422 if (create_options & FILE_DIRECTORY_FILE) {
5423 status = NT_STATUS_NOT_A_DIRECTORY;
5427 switch (create_disposition) {
5429 base_create_disposition = FILE_OPEN;
5432 base_create_disposition = FILE_OPEN_IF;
5436 /* Create an smb_filename with stream_name == NULL. */
5437 smb_fname_base = synthetic_smb_fname(talloc_tos(),
5438 smb_fname->base_name,
5442 if (smb_fname_base == NULL) {
5443 status = NT_STATUS_NO_MEMORY;
5447 if (SMB_VFS_STAT(conn, smb_fname_base) == -1) {
5448 DEBUG(10, ("Unable to stat stream: %s\n",
5449 smb_fname_str_dbg(smb_fname_base)));
5452 * https://bugzilla.samba.org/show_bug.cgi?id=10229
5453 * We need to check if the requested access mask
5454 * could be used to open the underlying file (if
5455 * it existed), as we're passing in zero for the
5456 * access mask to the base filename.
5458 status = check_base_file_access(conn,
5462 if (!NT_STATUS_IS_OK(status)) {
5463 DEBUG(10, ("Permission check "
5464 "for base %s failed: "
5465 "%s\n", smb_fname->base_name,
5466 nt_errstr(status)));
5471 base_privflags = NTCREATEX_OPTIONS_PRIVATE_STREAM_BASEOPEN;
5473 /* Open the base file. */
5474 status = create_file_unixpath(conn, NULL, smb_fname_base, 0,
5477 | FILE_SHARE_DELETE,
5478 base_create_disposition,
5483 TALLOC_FREE(smb_fname_base);
5485 if (!NT_STATUS_IS_OK(status)) {
5486 DEBUG(10, ("create_file_unixpath for base %s failed: "
5487 "%s\n", smb_fname->base_name,
5488 nt_errstr(status)));
5491 /* we don't need the low level fd */
5496 * If it's a request for a directory open, deal with it separately.
5499 if (create_options & FILE_DIRECTORY_FILE) {
5501 if (create_options & FILE_NON_DIRECTORY_FILE) {
5502 status = NT_STATUS_INVALID_PARAMETER;
5506 /* Can't open a temp directory. IFS kit test. */
5507 if (!(file_attributes & FILE_FLAG_POSIX_SEMANTICS) &&
5508 (file_attributes & FILE_ATTRIBUTE_TEMPORARY)) {
5509 status = NT_STATUS_INVALID_PARAMETER;
5514 * We will get a create directory here if the Win32
5515 * app specified a security descriptor in the
5516 * CreateDirectory() call.
5520 status = open_directory(
5521 conn, req, smb_fname, access_mask, share_access,
5522 create_disposition, create_options, file_attributes,
5527 * Ordinary file case.
5530 status = file_new(req, conn, &fsp);
5531 if(!NT_STATUS_IS_OK(status)) {
5535 status = fsp_set_smb_fname(fsp, smb_fname);
5536 if (!NT_STATUS_IS_OK(status)) {
5542 * We're opening the stream element of a
5543 * base_fsp we already opened. Set up the
5546 fsp->base_fsp = base_fsp;
5549 if (allocation_size) {
5550 fsp->initial_allocation_size = smb_roundup(fsp->conn,
5554 status = open_file_ntcreate(conn,
5567 if(!NT_STATUS_IS_OK(status)) {
5568 file_free(req, fsp);
5572 if (NT_STATUS_EQUAL(status, NT_STATUS_FILE_IS_A_DIRECTORY)) {
5574 /* A stream open never opens a directory */
5577 status = NT_STATUS_FILE_IS_A_DIRECTORY;
5582 * Fail the open if it was explicitly a non-directory
5586 if (create_options & FILE_NON_DIRECTORY_FILE) {
5587 status = NT_STATUS_FILE_IS_A_DIRECTORY;
5592 status = open_directory(
5593 conn, req, smb_fname, access_mask,
5594 share_access, create_disposition,
5595 create_options, file_attributes,
5600 if (!NT_STATUS_IS_OK(status)) {
5604 fsp->base_fsp = base_fsp;
5606 if ((ea_list != NULL) &&
5607 ((info == FILE_WAS_CREATED) || (info == FILE_WAS_OVERWRITTEN))) {
5608 status = set_ea(conn, fsp, fsp->fsp_name, ea_list);
5609 if (!NT_STATUS_IS_OK(status)) {
5614 if (!fsp->is_directory && S_ISDIR(fsp->fsp_name->st.st_ex_mode)) {
5615 status = NT_STATUS_ACCESS_DENIED;
5619 /* Save the requested allocation size. */
5620 if ((info == FILE_WAS_CREATED) || (info == FILE_WAS_OVERWRITTEN)) {
5621 if ((allocation_size > (uint64_t)fsp->fsp_name->st.st_ex_size)
5622 && !(fsp->is_directory))
5624 fsp->initial_allocation_size = smb_roundup(
5625 fsp->conn, allocation_size);
5626 if (vfs_allocate_file_space(
5627 fsp, fsp->initial_allocation_size) == -1) {
5628 status = NT_STATUS_DISK_FULL;
5632 fsp->initial_allocation_size = smb_roundup(
5633 fsp->conn, (uint64_t)fsp->fsp_name->st.st_ex_size);
5636 fsp->initial_allocation_size = 0;
5639 if ((info == FILE_WAS_CREATED) && lp_nt_acl_support(SNUM(conn)) &&
5640 fsp->base_fsp == NULL) {
5643 * According to the MS documentation, the only time the security
5644 * descriptor is applied to the opened file is iff we *created* the
5645 * file; an existing file stays the same.
5647 * Also, it seems (from observation) that you can open the file with
5648 * any access mask but you can still write the sd. We need to override
5649 * the granted access before we call set_sd
5650 * Patch for bug #2242 from Tom Lackemann <cessnatomny@yahoo.com>.
5653 uint32_t sec_info_sent;
5654 uint32_t saved_access_mask = fsp->access_mask;
5656 sec_info_sent = get_sec_info(sd);
5658 fsp->access_mask = FILE_GENERIC_ALL;
5660 if (sec_info_sent & (SECINFO_OWNER|
5664 status = set_sd(fsp, sd, sec_info_sent);
5667 fsp->access_mask = saved_access_mask;
5669 if (!NT_STATUS_IS_OK(status)) {
5672 } else if (lp_inherit_acls(SNUM(conn))) {
5673 /* Inherit from parent. Errors here are not fatal. */
5674 status = inherit_new_acl(fsp);
5675 if (!NT_STATUS_IS_OK(status)) {
5676 DEBUG(10,("inherit_new_acl: failed for %s with %s\n",
5678 nt_errstr(status) ));
5683 if ((conn->fs_capabilities & FILE_FILE_COMPRESSION)
5684 && (create_options & FILE_NO_COMPRESSION)
5685 && (info == FILE_WAS_CREATED)) {
5686 status = SMB_VFS_SET_COMPRESSION(conn, fsp, fsp,
5687 COMPRESSION_FORMAT_NONE);
5688 if (!NT_STATUS_IS_OK(status)) {
5689 DEBUG(1, ("failed to disable compression: %s\n",
5690 nt_errstr(status)));
5694 DEBUG(10, ("create_file_unixpath: info=%d\n", info));
5697 if (pinfo != NULL) {
5701 smb_fname->st = fsp->fsp_name->st;
5703 return NT_STATUS_OK;
5706 DEBUG(10, ("create_file_unixpath: %s\n", nt_errstr(status)));
5709 if (base_fsp && fsp->base_fsp == base_fsp) {
5711 * The close_file below will close
5716 close_file(req, fsp, ERROR_CLOSE);
5719 if (base_fsp != NULL) {
5720 close_file(req, base_fsp, ERROR_CLOSE);
5727 * Calculate the full path name given a relative fid.
5729 static NTSTATUS get_relative_fid_filename(
5730 connection_struct *conn,
5731 struct smb_request *req,
5732 uint16_t root_dir_fid,
5733 const struct smb_filename *smb_fname,
5734 struct smb_filename **smb_fname_out)
5736 files_struct *dir_fsp;
5737 char *parent_fname = NULL;
5738 char *new_base_name = NULL;
5739 uint32_t ucf_flags = ucf_flags_from_smb_request(req);
5742 if (root_dir_fid == 0 || !smb_fname) {
5743 status = NT_STATUS_INTERNAL_ERROR;
5747 dir_fsp = file_fsp(req, root_dir_fid);
5749 if (dir_fsp == NULL) {
5750 status = NT_STATUS_INVALID_HANDLE;
5754 if (is_ntfs_stream_smb_fname(dir_fsp->fsp_name)) {
5755 status = NT_STATUS_INVALID_HANDLE;
5759 if (!dir_fsp->is_directory) {
5762 * Check to see if this is a mac fork of some kind.
5765 if ((conn->fs_capabilities & FILE_NAMED_STREAMS) &&
5766 is_ntfs_stream_smb_fname(smb_fname)) {
5767 status = NT_STATUS_OBJECT_PATH_NOT_FOUND;
5772 we need to handle the case when we get a
5773 relative open relative to a file and the
5774 pathname is blank - this is a reopen!
5775 (hint from demyn plantenberg)
5778 status = NT_STATUS_INVALID_HANDLE;
5782 if (ISDOT(dir_fsp->fsp_name->base_name)) {
5784 * We're at the toplevel dir, the final file name
5785 * must not contain ./, as this is filtered out
5786 * normally by srvstr_get_path and unix_convert
5787 * explicitly rejects paths containing ./.
5789 parent_fname = talloc_strdup(talloc_tos(), "");
5790 if (parent_fname == NULL) {
5791 status = NT_STATUS_NO_MEMORY;
5795 size_t dir_name_len = strlen(dir_fsp->fsp_name->base_name);
5798 * Copy in the base directory name.
5801 parent_fname = talloc_array(talloc_tos(), char,
5803 if (parent_fname == NULL) {
5804 status = NT_STATUS_NO_MEMORY;
5807 memcpy(parent_fname, dir_fsp->fsp_name->base_name,
5811 * Ensure it ends in a '/'.
5812 * We used TALLOC_SIZE +2 to add space for the '/'.
5816 && (parent_fname[dir_name_len-1] != '\\')
5817 && (parent_fname[dir_name_len-1] != '/')) {
5818 parent_fname[dir_name_len] = '/';
5819 parent_fname[dir_name_len+1] = '\0';
5823 new_base_name = talloc_asprintf(talloc_tos(), "%s%s", parent_fname,
5824 smb_fname->base_name);
5825 if (new_base_name == NULL) {
5826 status = NT_STATUS_NO_MEMORY;
5830 status = filename_convert(req,
5837 if (!NT_STATUS_IS_OK(status)) {
5842 TALLOC_FREE(parent_fname);
5843 TALLOC_FREE(new_base_name);
5847 NTSTATUS create_file_default(connection_struct *conn,
5848 struct smb_request *req,
5849 uint16_t root_dir_fid,
5850 struct smb_filename *smb_fname,
5851 uint32_t access_mask,
5852 uint32_t share_access,
5853 uint32_t create_disposition,
5854 uint32_t create_options,
5855 uint32_t file_attributes,
5856 uint32_t oplock_request,
5857 const struct smb2_lease *lease,
5858 uint64_t allocation_size,
5859 uint32_t private_flags,
5860 struct security_descriptor *sd,
5861 struct ea_list *ea_list,
5862 files_struct **result,
5864 const struct smb2_create_blobs *in_context_blobs,
5865 struct smb2_create_blobs *out_context_blobs)
5867 int info = FILE_WAS_OPENED;
5868 files_struct *fsp = NULL;
5870 bool stream_name = false;
5872 DBG_DEBUG("create_file: access_mask = 0x%x "
5873 "file_attributes = 0x%x, share_access = 0x%x, "
5874 "create_disposition = 0x%x create_options = 0x%x "
5875 "oplock_request = 0x%x "
5876 "private_flags = 0x%x "
5877 "root_dir_fid = 0x%x, ea_list = %p, sd = %p, "
5879 (unsigned int)access_mask,
5880 (unsigned int)file_attributes,
5881 (unsigned int)share_access,
5882 (unsigned int)create_disposition,
5883 (unsigned int)create_options,
5884 (unsigned int)oplock_request,
5885 (unsigned int)private_flags,
5886 (unsigned int)root_dir_fid,
5887 ea_list, sd, smb_fname_str_dbg(smb_fname));
5891 * Remember the absolute time of the original request
5892 * with this mid. We'll use it later to see if this
5895 get_deferred_open_message_state(req, &req->request_time, NULL);
5899 * Calculate the filename from the root_dir_if if necessary.
5902 if (root_dir_fid != 0) {
5903 struct smb_filename *smb_fname_out = NULL;
5904 status = get_relative_fid_filename(conn, req, root_dir_fid,
5905 smb_fname, &smb_fname_out);
5906 if (!NT_STATUS_IS_OK(status)) {
5909 smb_fname = smb_fname_out;
5913 * Check to see if this is a mac fork of some kind.
5916 stream_name = is_ntfs_stream_smb_fname(smb_fname);
5918 enum FAKE_FILE_TYPE fake_file_type;
5920 fake_file_type = is_fake_file(smb_fname);
5922 if (fake_file_type != FAKE_FILE_TYPE_NONE) {
5925 * Here we go! support for changing the disk quotas
5928 * We need to fake up to open this MAGIC QUOTA file
5929 * and return a valid FID.
5931 * w2k close this file directly after openening xp
5932 * also tries a QUERY_FILE_INFO on the file and then
5935 status = open_fake_file(req, conn, req->vuid,
5936 fake_file_type, smb_fname,
5938 if (!NT_STATUS_IS_OK(status)) {
5942 ZERO_STRUCT(smb_fname->st);
5946 if (!(conn->fs_capabilities & FILE_NAMED_STREAMS)) {
5947 status = NT_STATUS_OBJECT_NAME_NOT_FOUND;
5952 if (is_ntfs_default_stream_smb_fname(smb_fname)) {
5954 smb_fname->stream_name = NULL;
5955 /* We have to handle this error here. */
5956 if (create_options & FILE_DIRECTORY_FILE) {
5957 status = NT_STATUS_NOT_A_DIRECTORY;
5960 if (req != NULL && req->posix_pathnames) {
5961 ret = SMB_VFS_LSTAT(conn, smb_fname);
5963 ret = SMB_VFS_STAT(conn, smb_fname);
5966 if (ret == 0 && VALID_STAT_OF_DIR(smb_fname->st)) {
5967 status = NT_STATUS_FILE_IS_A_DIRECTORY;
5972 status = create_file_unixpath(
5973 conn, req, smb_fname, access_mask, share_access,
5974 create_disposition, create_options, file_attributes,
5975 oplock_request, lease, allocation_size, private_flags,
5979 if (!NT_STATUS_IS_OK(status)) {
5984 DEBUG(10, ("create_file: info=%d\n", info));
5987 if (pinfo != NULL) {
5990 return NT_STATUS_OK;
5993 DEBUG(10, ("create_file: %s\n", nt_errstr(status)));
5996 close_file(req, fsp, ERROR_CLOSE);