2 Unix SMB/CIFS implementation.
3 file opening and share modes
4 Copyright (C) Andrew Tridgell 1992-1998
5 Copyright (C) Jeremy Allison 2001-2004
6 Copyright (C) Volker Lendecke 2005
7 Copyright (C) Ralph Boehme 2017
9 This program is free software; you can redistribute it and/or modify
10 it under the terms of the GNU General Public License as published by
11 the Free Software Foundation; either version 3 of the License, or
12 (at your option) any later version.
14 This program is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 GNU General Public License for more details.
19 You should have received a copy of the GNU General Public License
20 along with this program. If not, see <http://www.gnu.org/licenses/>.
24 #include "smb1_utils.h"
25 #include "system/filesys.h"
26 #include "lib/util/server_id.h"
28 #include "smbd/smbd.h"
29 #include "smbd/globals.h"
30 #include "fake_file.h"
31 #include "../libcli/security/security.h"
32 #include "../librpc/gen_ndr/ndr_security.h"
33 #include "../librpc/gen_ndr/ndr_open_files.h"
34 #include "../librpc/gen_ndr/idmap.h"
35 #include "../librpc/gen_ndr/ioctl.h"
36 #include "passdb/lookup_sid.h"
40 #include "source3/lib/dbwrap/dbwrap_watch.h"
41 #include "locking/leases_db.h"
42 #include "librpc/gen_ndr/ndr_leases_db.h"
43 #include "lib/util/time_basic.h"
45 extern const struct generic_mapping file_generic_mapping;
47 struct deferred_open_record {
48 struct smbXsrv_connection *xconn;
54 * Timer for async opens, needed because they don't use a watch on
55 * a locking.tdb record. This is currently only used for real async
56 * opens and just terminates smbd if the async open times out.
58 struct tevent_timer *te;
61 * For the samba kernel oplock case we use both a timeout and
62 * a watch on locking.tdb. This way in case it's smbd holding
63 * the kernel oplock we get directly notified for the retry
64 * once the kernel oplock is properly broken. Store the req
65 * here so that it can be timely discarded once the timer
68 struct tevent_req *watch_req;
71 /****************************************************************************
72 If the requester wanted DELETE_ACCESS and was rejected because
73 the file ACL didn't include DELETE_ACCESS, see if the parent ACL
75 ****************************************************************************/
77 static bool parent_override_delete(connection_struct *conn,
78 const struct smb_filename *smb_fname,
80 uint32_t rejected_mask)
82 if ((access_mask & DELETE_ACCESS) &&
83 (rejected_mask & DELETE_ACCESS) &&
84 can_delete_file_in_directory(conn,
93 /****************************************************************************
94 Check if we have open rights.
95 ****************************************************************************/
97 NTSTATUS smbd_check_access_rights(struct connection_struct *conn,
98 struct files_struct *dirfsp,
99 const struct smb_filename *smb_fname,
101 uint32_t access_mask)
103 /* Check if we have rights to open. */
105 struct security_descriptor *sd = NULL;
106 uint32_t rejected_share_access;
107 uint32_t rejected_mask = access_mask;
108 uint32_t do_not_check_mask = 0;
110 SMB_ASSERT(dirfsp == conn->cwd_fsp);
112 rejected_share_access = access_mask & ~(conn->share_access);
114 if (rejected_share_access) {
115 DEBUG(10, ("smbd_check_access_rights: rejected share access 0x%x "
117 (unsigned int)access_mask,
118 smb_fname_str_dbg(smb_fname),
119 (unsigned int)rejected_share_access ));
120 return NT_STATUS_ACCESS_DENIED;
123 if (!use_privs && get_current_uid(conn) == (uid_t)0) {
124 /* I'm sorry sir, I didn't know you were root... */
125 DEBUG(10,("smbd_check_access_rights: root override "
126 "on %s. Granting 0x%x\n",
127 smb_fname_str_dbg(smb_fname),
128 (unsigned int)access_mask ));
132 if ((access_mask & DELETE_ACCESS) && !lp_acl_check_permissions(SNUM(conn))) {
133 DEBUG(10,("smbd_check_access_rights: not checking ACL "
134 "on DELETE_ACCESS on file %s. Granting 0x%x\n",
135 smb_fname_str_dbg(smb_fname),
136 (unsigned int)access_mask ));
140 if (access_mask == DELETE_ACCESS &&
141 VALID_STAT(smb_fname->st) &&
142 S_ISLNK(smb_fname->st.st_ex_mode)) {
143 /* We can always delete a symlink. */
144 DEBUG(10,("smbd_check_access_rights: not checking ACL "
145 "on DELETE_ACCESS on symlink %s.\n",
146 smb_fname_str_dbg(smb_fname) ));
150 status = SMB_VFS_GET_NT_ACL_AT(conn,
159 if (!NT_STATUS_IS_OK(status)) {
160 DEBUG(10, ("smbd_check_access_rights: Could not get acl "
162 smb_fname_str_dbg(smb_fname),
165 if (NT_STATUS_EQUAL(status, NT_STATUS_ACCESS_DENIED)) {
173 * If we can access the path to this file, by
174 * default we have FILE_READ_ATTRIBUTES from the
175 * containing directory. See the section:
176 * "Algorithm to Check Access to an Existing File"
179 * se_file_access_check() also takes care of
180 * owner WRITE_DAC and READ_CONTROL.
182 do_not_check_mask = FILE_READ_ATTRIBUTES;
185 * Samba 3.6 and earlier granted execute access even
186 * if the ACL did not contain execute rights.
187 * Samba 4.0 is more correct and checks it.
188 * The compatibilty mode allows one to skip this check
189 * to smoothen upgrades.
191 if (lp_acl_allow_execute_always(SNUM(conn))) {
192 do_not_check_mask |= FILE_EXECUTE;
195 status = se_file_access_check(sd,
196 get_current_nttok(conn),
198 (access_mask & ~do_not_check_mask),
201 DEBUG(10,("smbd_check_access_rights: file %s requesting "
202 "0x%x returning 0x%x (%s)\n",
203 smb_fname_str_dbg(smb_fname),
204 (unsigned int)access_mask,
205 (unsigned int)rejected_mask,
206 nt_errstr(status) ));
208 if (!NT_STATUS_IS_OK(status)) {
209 if (DEBUGLEVEL >= 10) {
210 DEBUG(10,("smbd_check_access_rights: acl for %s is:\n",
211 smb_fname_str_dbg(smb_fname) ));
212 NDR_PRINT_DEBUG(security_descriptor, sd);
218 if (NT_STATUS_IS_OK(status) ||
219 !NT_STATUS_EQUAL(status, NT_STATUS_ACCESS_DENIED)) {
223 /* Here we know status == NT_STATUS_ACCESS_DENIED. */
227 if ((access_mask & FILE_WRITE_ATTRIBUTES) &&
228 (rejected_mask & FILE_WRITE_ATTRIBUTES) &&
229 !lp_store_dos_attributes(SNUM(conn)) &&
230 (lp_map_readonly(SNUM(conn)) ||
231 lp_map_archive(SNUM(conn)) ||
232 lp_map_hidden(SNUM(conn)) ||
233 lp_map_system(SNUM(conn)))) {
234 rejected_mask &= ~FILE_WRITE_ATTRIBUTES;
236 DEBUG(10,("smbd_check_access_rights: "
238 "FILE_WRITE_ATTRIBUTES "
240 smb_fname_str_dbg(smb_fname)));
243 if (parent_override_delete(conn,
247 /* Were we trying to do an open
248 * for delete and didn't get DELETE
249 * access (only) ? Check if the
250 * directory allows DELETE_CHILD.
252 * http://blogs.msdn.com/oldnewthing/archive/2004/06/04/148426.aspx
255 rejected_mask &= ~DELETE_ACCESS;
257 DEBUG(10,("smbd_check_access_rights: "
261 smb_fname_str_dbg(smb_fname)));
264 if (rejected_mask != 0) {
265 return NT_STATUS_ACCESS_DENIED;
270 NTSTATUS check_parent_access(struct connection_struct *conn,
271 struct files_struct *dirfsp,
272 struct smb_filename *smb_fname,
273 uint32_t access_mask)
276 struct security_descriptor *parent_sd = NULL;
277 uint32_t access_granted = 0;
278 struct smb_filename *parent_dir = NULL;
279 struct share_mode_lock *lck = NULL;
280 struct file_id id = {0};
282 bool delete_on_close_set;
284 TALLOC_CTX *frame = talloc_stackframe();
288 * NB. When dirfsp != conn->cwd_fsp, we must
289 * change parent_dir to be "." for the name here.
292 SMB_ASSERT(dirfsp == conn->cwd_fsp);
294 ok = parent_smb_fname(frame, smb_fname, &parent_dir, NULL);
296 status = NT_STATUS_NO_MEMORY;
300 if (get_current_uid(conn) == (uid_t)0) {
301 /* I'm sorry sir, I didn't know you were root... */
302 DEBUG(10,("check_parent_access: root override "
303 "on %s. Granting 0x%x\n",
304 smb_fname_str_dbg(smb_fname),
305 (unsigned int)access_mask ));
306 status = NT_STATUS_OK;
310 status = SMB_VFS_GET_NT_ACL_AT(conn,
317 if (!NT_STATUS_IS_OK(status)) {
318 DBG_INFO("SMB_VFS_GET_NT_ACL_AT failed for "
319 "%s with error %s\n",
320 smb_fname_str_dbg(parent_dir),
326 * If we can access the path to this file, by
327 * default we have FILE_READ_ATTRIBUTES from the
328 * containing directory. See the section:
329 * "Algorithm to Check Access to an Existing File"
332 * se_file_access_check() also takes care of
333 * owner WRITE_DAC and READ_CONTROL.
335 status = se_file_access_check(parent_sd,
336 get_current_nttok(conn),
338 (access_mask & ~FILE_READ_ATTRIBUTES),
340 if(!NT_STATUS_IS_OK(status)) {
341 DEBUG(5,("check_parent_access: access check "
342 "on directory %s for "
343 "path %s for mask 0x%x returned (0x%x) %s\n",
344 smb_fname_str_dbg(parent_dir),
345 smb_fname->base_name,
348 nt_errstr(status) ));
352 if (!(access_mask & (SEC_DIR_ADD_FILE | SEC_DIR_ADD_SUBDIR))) {
353 status = NT_STATUS_OK;
356 if (!lp_check_parent_directory_delete_on_close(SNUM(conn))) {
357 status = NT_STATUS_OK;
361 /* Check if the directory has delete-on-close set */
362 ret = SMB_VFS_STAT(conn, parent_dir);
364 status = map_nt_error_from_unix(errno);
368 id = SMB_VFS_FILE_ID_CREATE(conn, &parent_dir->st);
370 status = file_name_hash(conn, parent_dir->base_name, &name_hash);
371 if (!NT_STATUS_IS_OK(status)) {
375 lck = get_existing_share_mode_lock(frame, id);
377 status = NT_STATUS_OK;
381 delete_on_close_set = is_delete_on_close_set(lck, name_hash);
382 if (delete_on_close_set) {
383 status = NT_STATUS_DELETE_PENDING;
387 status = NT_STATUS_OK;
394 /****************************************************************************
395 Ensure when opening a base file for a stream open that we have permissions
396 to do so given the access mask on the base file.
397 ****************************************************************************/
399 static NTSTATUS check_base_file_access(struct connection_struct *conn,
400 struct smb_filename *smb_fname,
401 uint32_t access_mask)
405 status = smbd_calculate_access_mask(conn,
411 if (!NT_STATUS_IS_OK(status)) {
412 DEBUG(10, ("smbd_calculate_access_mask "
413 "on file %s returned %s\n",
414 smb_fname_str_dbg(smb_fname),
419 if (access_mask & (FILE_WRITE_DATA|FILE_APPEND_DATA)) {
421 if (!CAN_WRITE(conn)) {
422 return NT_STATUS_ACCESS_DENIED;
424 dosattrs = dos_mode(conn, smb_fname);
425 if (IS_DOS_READONLY(dosattrs)) {
426 return NT_STATUS_ACCESS_DENIED;
430 return smbd_check_access_rights(conn,
437 /****************************************************************************
438 Handle differing symlink errno's
439 ****************************************************************************/
441 static int link_errno_convert(int err)
443 #if defined(ENOTSUP) && defined(OSF1)
444 /* handle special Tru64 errno */
445 if (err == ENOTSUP) {
450 /* fix broken NetBSD errno */
455 /* fix broken FreeBSD errno */
462 static int non_widelink_open(struct connection_struct *conn,
464 struct smb_filename *smb_fname,
467 unsigned int link_depth);
469 /****************************************************************************
470 Follow a symlink in userspace.
471 ****************************************************************************/
473 static int process_symlink_open(struct connection_struct *conn,
475 struct smb_filename *smb_fname,
478 unsigned int link_depth)
480 const char *conn_rootdir = NULL;
481 struct smb_filename conn_rootdir_fname;
483 char *link_target = NULL;
485 struct smb_filename *oldwd_fname = NULL;
486 size_t rootdir_len = 0;
487 struct smb_filename *resolved_fname = NULL;
488 char *resolved_name = NULL;
489 bool matched = false;
492 conn_rootdir = SMB_VFS_CONNECTPATH(conn, smb_fname);
493 if (conn_rootdir == NULL) {
497 conn_rootdir_fname = (struct smb_filename) {
498 .base_name = discard_const_p(char, conn_rootdir),
502 * Ensure we don't get stuck in a symlink loop.
505 if (link_depth >= 20) {
510 /* Allocate space for the link target. */
511 link_target = talloc_array(talloc_tos(), char, PATH_MAX);
512 if (link_target == NULL) {
518 * Read the link target. We do this just to verify that smb_fname indeed
519 * points at a symbolic link and return the SMB_VFS_READLINKAT() errno
520 * and failure in case smb_fname is NOT a symlink.
522 * The caller needs this piece of information to distinguish two cases
523 * where open() fails with errno=ENOTDIR, cf the comment in
524 * non_widelink_open().
526 * We rely on SMB_VFS_REALPATH() to resolve the path including the
527 * symlink. Once we have SMB_VFS_STATX() or something similar in our VFS
528 * we may want to use that instead of SMB_VFS_READLINKAT().
530 link_len = SMB_VFS_READLINKAT(conn,
535 if (link_len == -1) {
539 /* Convert to an absolute path. */
540 resolved_fname = SMB_VFS_REALPATH(conn, talloc_tos(), smb_fname);
541 if (resolved_fname == NULL) {
544 resolved_name = resolved_fname->base_name;
547 * We know conn_rootdir starts with '/' and
548 * does not end in '/'. FIXME ! Should we
551 rootdir_len = strlen(conn_rootdir_fname.base_name);
553 matched = (strncmp(conn_rootdir_fname.base_name,
562 * Turn into a path relative to the share root.
564 if (resolved_name[rootdir_len] == '\0') {
565 /* Link to the root of the share. */
566 TALLOC_FREE(smb_fname->base_name);
567 smb_fname->base_name = talloc_strdup(smb_fname, ".");
568 } else if (resolved_name[rootdir_len] == '/') {
569 TALLOC_FREE(smb_fname->base_name);
570 smb_fname->base_name = talloc_strdup(smb_fname,
571 &resolved_name[rootdir_len+1]);
577 if (smb_fname->base_name == NULL) {
582 oldwd_fname = vfs_GetWd(talloc_tos(), conn);
583 if (oldwd_fname == NULL) {
587 /* Ensure we operate from the root of the share. */
588 if (vfs_ChDir(conn, &conn_rootdir_fname) == -1) {
592 /* And do it all again.. */
593 fd = non_widelink_open(conn,
605 TALLOC_FREE(resolved_fname);
606 TALLOC_FREE(link_target);
607 if (oldwd_fname != NULL) {
608 int ret = vfs_ChDir(conn, oldwd_fname);
610 smb_panic("unable to get back to old directory\n");
612 TALLOC_FREE(oldwd_fname);
614 if (saved_errno != 0) {
620 /****************************************************************************
622 ****************************************************************************/
624 static int non_widelink_open(struct connection_struct *conn,
626 struct smb_filename *smb_fname,
629 unsigned int link_depth)
633 struct smb_filename *smb_fname_rel = NULL;
635 struct smb_filename *oldwd_fname = NULL;
636 struct smb_filename *parent_dir_fname = NULL;
639 if (fsp->fsp_flags.is_directory) {
640 parent_dir_fname = cp_smb_filename(talloc_tos(), smb_fname);
641 if (parent_dir_fname == NULL) {
646 smb_fname_rel = synthetic_smb_fname(parent_dir_fname,
648 smb_fname->stream_name,
652 if (smb_fname_rel == NULL) {
657 ok = parent_smb_fname(talloc_tos(),
667 oldwd_fname = vfs_GetWd(talloc_tos(), conn);
668 if (oldwd_fname == NULL) {
672 /* Pin parent directory in place. */
673 if (vfs_ChDir(conn, parent_dir_fname) == -1) {
677 /* Ensure the relative path is below the share. */
678 status = check_reduced_name(conn, parent_dir_fname, smb_fname_rel);
679 if (!NT_STATUS_IS_OK(status)) {
680 saved_errno = map_errno_from_nt_status(status);
687 struct smb_filename *tmp_name = fsp->fsp_name;
688 fsp->fsp_name = smb_fname_rel;
689 fd = SMB_VFS_OPEN(conn, smb_fname_rel, fsp, flags, mode);
690 fsp->fsp_name = tmp_name;
694 saved_errno = link_errno_convert(errno);
696 * Trying to open a symlink to a directory with O_NOFOLLOW and
697 * O_DIRECTORY can return either of ELOOP and ENOTDIR. So
698 * ENOTDIR really means: might be a symlink, but we're not sure.
699 * In this case, we just assume there's a symlink. If we were
700 * wrong, process_symlink_open() will return EINVAL. We check
701 * this below, and fall back to returning the initial
704 * BUG: https://bugzilla.samba.org/show_bug.cgi?id=12860
706 if (saved_errno == ELOOP || saved_errno == ENOTDIR) {
707 if (fsp->posix_flags & FSP_POSIX_FLAGS_OPEN) {
708 /* Never follow symlinks on posix open. */
711 if (!lp_follow_symlinks(SNUM(conn))) {
712 /* Explicitly no symlinks. */
716 * We may have a symlink. Follow in userspace
717 * to ensure it's under the share definition.
719 fd = process_symlink_open(conn,
726 if (saved_errno == ENOTDIR &&
729 * O_DIRECTORY on neither a directory,
730 * nor a symlink. Just return
731 * saved_errno from initial open()
736 link_errno_convert(errno);
743 TALLOC_FREE(parent_dir_fname);
745 if (oldwd_fname != NULL) {
746 int ret = vfs_ChDir(conn, oldwd_fname);
748 smb_panic("unable to get back to old directory\n");
750 TALLOC_FREE(oldwd_fname);
752 if (saved_errno != 0) {
758 /****************************************************************************
759 fd support routines - attempt to do a dos_open.
760 ****************************************************************************/
762 NTSTATUS fd_open(struct connection_struct *conn,
767 struct smb_filename *smb_fname = fsp->fsp_name;
768 NTSTATUS status = NT_STATUS_OK;
772 * Never follow symlinks on a POSIX client. The
773 * client should be doing this.
776 if ((fsp->posix_flags & FSP_POSIX_FLAGS_OPEN) || !lp_follow_symlinks(SNUM(conn))) {
781 * Only follow symlinks within a share
784 fsp->fh->fd = non_widelink_open(conn,
790 if (fsp->fh->fd == -1) {
793 if (saved_errno != 0) {
797 if (fsp->fh->fd == -1) {
798 int posix_errno = link_errno_convert(errno);
799 status = map_nt_error_from_unix(posix_errno);
800 if (errno == EMFILE) {
801 static time_t last_warned = 0L;
803 if (time((time_t *) NULL) > last_warned) {
804 DEBUG(0,("Too many open files, unable "
805 "to open more! smbd's max "
807 lp_max_open_files()));
808 last_warned = time((time_t *) NULL);
812 DBG_DEBUG("name %s, flags = 0%o mode = 0%o, fd = %d. %s\n",
813 smb_fname_str_dbg(smb_fname), flags, (int)mode,
814 fsp->fh->fd, strerror(errno));
818 DBG_DEBUG("name %s, flags = 0%o mode = 0%o, fd = %d\n",
819 smb_fname_str_dbg(smb_fname), flags, (int)mode, fsp->fh->fd);
824 /****************************************************************************
825 Close the file associated with a fsp.
826 ****************************************************************************/
828 NTSTATUS fd_close(files_struct *fsp)
835 if (fsp->fh->fd == -1) {
837 * Either a directory where the dptr_CloseDir() already closed
838 * the fd or a stat open.
842 if (fsp->fh->ref_count > 1) {
843 return NT_STATUS_OK; /* Shared handle. Only close last reference. */
846 ret = SMB_VFS_CLOSE(fsp);
849 return map_nt_error_from_unix(errno);
854 /****************************************************************************
855 Change the ownership of a file to that of the parent directory.
856 Do this by fd if possible.
857 ****************************************************************************/
859 void change_file_owner_to_parent(connection_struct *conn,
860 struct smb_filename *smb_fname_parent,
865 ret = SMB_VFS_STAT(conn, smb_fname_parent);
867 DEBUG(0,("change_file_owner_to_parent: failed to stat parent "
868 "directory %s. Error was %s\n",
869 smb_fname_str_dbg(smb_fname_parent),
871 TALLOC_FREE(smb_fname_parent);
875 if (smb_fname_parent->st.st_ex_uid == fsp->fsp_name->st.st_ex_uid) {
876 /* Already this uid - no need to change. */
877 DEBUG(10,("change_file_owner_to_parent: file %s "
878 "is already owned by uid %d\n",
880 (int)fsp->fsp_name->st.st_ex_uid ));
881 TALLOC_FREE(smb_fname_parent);
886 ret = SMB_VFS_FCHOWN(fsp, smb_fname_parent->st.st_ex_uid, (gid_t)-1);
889 DEBUG(0,("change_file_owner_to_parent: failed to fchown "
890 "file %s to parent directory uid %u. Error "
891 "was %s\n", fsp_str_dbg(fsp),
892 (unsigned int)smb_fname_parent->st.st_ex_uid,
895 DEBUG(10,("change_file_owner_to_parent: changed new file %s to "
896 "parent directory uid %u.\n", fsp_str_dbg(fsp),
897 (unsigned int)smb_fname_parent->st.st_ex_uid));
898 /* Ensure the uid entry is updated. */
899 fsp->fsp_name->st.st_ex_uid = smb_fname_parent->st.st_ex_uid;
903 static NTSTATUS change_dir_owner_to_parent(connection_struct *conn,
904 struct smb_filename *smb_fname_parent,
905 struct smb_filename *smb_dname,
906 SMB_STRUCT_STAT *psbuf)
908 struct smb_filename *smb_fname_cwd = NULL;
909 struct smb_filename *saved_dir_fname = NULL;
910 TALLOC_CTX *ctx = talloc_tos();
911 NTSTATUS status = NT_STATUS_OK;
914 ret = SMB_VFS_STAT(conn, smb_fname_parent);
916 status = map_nt_error_from_unix(errno);
917 DEBUG(0,("change_dir_owner_to_parent: failed to stat parent "
918 "directory %s. Error was %s\n",
919 smb_fname_str_dbg(smb_fname_parent),
924 /* We've already done an lstat into psbuf, and we know it's a
925 directory. If we can cd into the directory and the dev/ino
926 are the same then we can safely chown without races as
927 we're locking the directory in place by being in it. This
928 should work on any UNIX (thanks tridge :-). JRA.
931 saved_dir_fname = vfs_GetWd(ctx,conn);
932 if (!saved_dir_fname) {
933 status = map_nt_error_from_unix(errno);
934 DEBUG(0,("change_dir_owner_to_parent: failed to get "
935 "current working directory. Error was %s\n",
940 /* Chdir into the new path. */
941 if (vfs_ChDir(conn, smb_dname) == -1) {
942 status = map_nt_error_from_unix(errno);
943 DEBUG(0,("change_dir_owner_to_parent: failed to change "
944 "current working directory to %s. Error "
945 "was %s\n", smb_dname->base_name, strerror(errno) ));
949 smb_fname_cwd = synthetic_smb_fname(ctx,
955 if (smb_fname_cwd == NULL) {
956 status = NT_STATUS_NO_MEMORY;
960 ret = SMB_VFS_STAT(conn, smb_fname_cwd);
962 status = map_nt_error_from_unix(errno);
963 DEBUG(0,("change_dir_owner_to_parent: failed to stat "
964 "directory '.' (%s) Error was %s\n",
965 smb_dname->base_name, strerror(errno)));
969 /* Ensure we're pointing at the same place. */
970 if (smb_fname_cwd->st.st_ex_dev != psbuf->st_ex_dev ||
971 smb_fname_cwd->st.st_ex_ino != psbuf->st_ex_ino) {
972 DEBUG(0,("change_dir_owner_to_parent: "
973 "device/inode on directory %s changed. "
974 "Refusing to chown !\n",
975 smb_dname->base_name ));
976 status = NT_STATUS_ACCESS_DENIED;
980 if (smb_fname_parent->st.st_ex_uid == smb_fname_cwd->st.st_ex_uid) {
981 /* Already this uid - no need to change. */
982 DEBUG(10,("change_dir_owner_to_parent: directory %s "
983 "is already owned by uid %d\n",
984 smb_dname->base_name,
985 (int)smb_fname_cwd->st.st_ex_uid ));
986 status = NT_STATUS_OK;
991 ret = SMB_VFS_LCHOWN(conn,
993 smb_fname_parent->st.st_ex_uid,
997 status = map_nt_error_from_unix(errno);
998 DEBUG(10,("change_dir_owner_to_parent: failed to chown "
999 "directory %s to parent directory uid %u. "
1001 smb_dname->base_name,
1002 (unsigned int)smb_fname_parent->st.st_ex_uid,
1005 DEBUG(10,("change_dir_owner_to_parent: changed ownership of new "
1006 "directory %s to parent directory uid %u.\n",
1007 smb_dname->base_name,
1008 (unsigned int)smb_fname_parent->st.st_ex_uid ));
1009 /* Ensure the uid entry is updated. */
1010 psbuf->st_ex_uid = smb_fname_parent->st.st_ex_uid;
1014 vfs_ChDir(conn, saved_dir_fname);
1016 TALLOC_FREE(saved_dir_fname);
1017 TALLOC_FREE(smb_fname_cwd);
1021 /****************************************************************************
1022 Open a file - returning a guaranteed ATOMIC indication of if the
1023 file was created or not.
1024 ****************************************************************************/
1026 static NTSTATUS fd_open_atomic(struct connection_struct *conn,
1032 NTSTATUS status = NT_STATUS_UNSUCCESSFUL;
1033 NTSTATUS retry_status;
1034 bool file_existed = VALID_STAT(fsp->fsp_name->st);
1037 if (!(flags & O_CREAT)) {
1039 * We're not creating the file, just pass through.
1041 status = fd_open(conn, fsp, flags, mode);
1042 *file_created = false;
1046 if (flags & O_EXCL) {
1048 * Fail if already exists, just pass through.
1050 status = fd_open(conn, fsp, flags, mode);
1053 * Here we've opened with O_CREAT|O_EXCL. If that went
1054 * NT_STATUS_OK, we *know* we created this file.
1056 *file_created = NT_STATUS_IS_OK(status);
1062 * Now it gets tricky. We have O_CREAT, but not O_EXCL.
1063 * To know absolutely if we created the file or not,
1064 * we can never call O_CREAT without O_EXCL. So if
1065 * we think the file existed, try without O_CREAT|O_EXCL.
1066 * If we think the file didn't exist, try with
1069 * The big problem here is dangling symlinks. Opening
1070 * without O_NOFOLLOW means both bad symlink
1071 * and missing path return -1, ENOENT from open(). As POSIX
1072 * is pathname based it's not possible to tell
1073 * the difference between these two cases in a
1074 * non-racy way, so change to try only two attempts before
1077 * We don't have this problem for the O_NOFOLLOW
1078 * case as it just returns NT_STATUS_OBJECT_PATH_NOT_FOUND
1079 * mapped from the ELOOP POSIX error.
1083 curr_flags = flags & ~(O_CREAT);
1084 retry_status = NT_STATUS_OBJECT_NAME_NOT_FOUND;
1086 curr_flags = flags | O_EXCL;
1087 retry_status = NT_STATUS_OBJECT_NAME_COLLISION;
1090 status = fd_open(conn, fsp, curr_flags, mode);
1091 if (NT_STATUS_IS_OK(status)) {
1092 *file_created = !file_existed;
1093 return NT_STATUS_OK;
1095 if (NT_STATUS_EQUAL(status, retry_status)) {
1097 file_existed = !file_existed;
1099 DBG_DEBUG("File %s %s. Retry.\n",
1101 file_existed ? "existed" : "did not exist");
1104 curr_flags = flags & ~(O_CREAT);
1106 curr_flags = flags | O_EXCL;
1109 status = fd_open(conn, fsp, curr_flags, mode);
1112 *file_created = (NT_STATUS_IS_OK(status) && !file_existed);
1116 /****************************************************************************
1118 ****************************************************************************/
1120 static NTSTATUS open_file(files_struct *fsp,
1121 connection_struct *conn,
1122 struct smb_request *req,
1123 struct smb_filename *parent_dir,
1126 uint32_t access_mask, /* client requested access mask. */
1127 uint32_t open_access_mask, /* what we're actually using in the open. */
1128 bool *p_file_created)
1130 struct smb_filename *smb_fname = fsp->fsp_name;
1131 NTSTATUS status = NT_STATUS_OK;
1132 int accmode = (flags & O_ACCMODE);
1133 int local_flags = flags;
1134 bool file_existed = VALID_STAT(fsp->fsp_name->st);
1135 uint32_t need_fd_mask =
1141 WRITE_OWNER_ACCESS |
1142 SEC_FLAG_SYSTEM_SECURITY |
1143 READ_CONTROL_ACCESS;
1144 bool creating = !file_existed && (flags & O_CREAT);
1145 bool truncating = (flags & O_TRUNC);
1150 /* Check permissions */
1153 * This code was changed after seeing a client open request
1154 * containing the open mode of (DENY_WRITE/read-only) with
1155 * the 'create if not exist' bit set. The previous code
1156 * would fail to open the file read only on a read-only share
1157 * as it was checking the flags parameter directly against O_RDONLY,
1158 * this was failing as the flags parameter was set to O_RDONLY|O_CREAT.
1162 if (!CAN_WRITE(conn)) {
1163 /* It's a read-only share - fail if we wanted to write. */
1164 if(accmode != O_RDONLY || (flags & O_TRUNC) || (flags & O_APPEND)) {
1165 DEBUG(3,("Permission denied opening %s\n",
1166 smb_fname_str_dbg(smb_fname)));
1167 return NT_STATUS_ACCESS_DENIED;
1169 if (flags & O_CREAT) {
1170 /* We don't want to write - but we must make sure that
1171 O_CREAT doesn't create the file if we have write
1172 access into the directory.
1174 flags &= ~(O_CREAT|O_EXCL);
1175 local_flags &= ~(O_CREAT|O_EXCL);
1180 * This little piece of insanity is inspired by the
1181 * fact that an NT client can open a file for O_RDONLY,
1182 * but set the create disposition to FILE_EXISTS_TRUNCATE.
1183 * If the client *can* write to the file, then it expects to
1184 * truncate the file, even though it is opening for readonly.
1185 * Quicken uses this stupid trick in backup file creation...
1186 * Thanks *greatly* to "David W. Chapman Jr." <dwcjr@inethouston.net>
1187 * for helping track this one down. It didn't bite us in 2.0.x
1188 * as we always opened files read-write in that release. JRA.
1191 if ((accmode == O_RDONLY) && ((flags & O_TRUNC) == O_TRUNC)) {
1192 DEBUG(10,("open_file: truncate requested on read-only open "
1193 "for file %s\n", smb_fname_str_dbg(smb_fname)));
1194 local_flags = (flags & ~O_ACCMODE)|O_RDWR;
1197 if ((open_access_mask & need_fd_mask) || creating || truncating) {
1201 #if defined(O_NONBLOCK) && defined(S_ISFIFO)
1203 * We would block on opening a FIFO with no one else on the
1204 * other end. Do what we used to do and add O_NONBLOCK to the
1208 if (file_existed && S_ISFIFO(smb_fname->st.st_ex_mode)) {
1209 local_flags &= ~O_TRUNC; /* Can't truncate a FIFO. */
1210 local_flags |= O_NONBLOCK;
1215 /* Don't create files with Microsoft wildcard characters. */
1216 if (fsp->base_fsp) {
1218 * wildcard characters are allowed in stream names
1219 * only test the basefilename
1221 wild = fsp->base_fsp->fsp_name->base_name;
1223 wild = smb_fname->base_name;
1225 if ((local_flags & O_CREAT) && !file_existed &&
1226 !(fsp->posix_flags & FSP_POSIX_FLAGS_PATHNAMES) &&
1227 ms_has_wild(wild)) {
1228 return NT_STATUS_OBJECT_NAME_INVALID;
1231 /* Can we access this file ? */
1232 if (!fsp->base_fsp) {
1233 /* Only do this check on non-stream open. */
1235 status = smbd_check_access_rights(conn,
1241 if (!NT_STATUS_IS_OK(status)) {
1242 DEBUG(10, ("open_file: "
1243 "smbd_check_access_rights "
1244 "on file %s returned %s\n",
1245 smb_fname_str_dbg(smb_fname),
1246 nt_errstr(status)));
1249 if (!NT_STATUS_IS_OK(status) &&
1250 !NT_STATUS_EQUAL(status,
1251 NT_STATUS_OBJECT_NAME_NOT_FOUND))
1256 if (NT_STATUS_EQUAL(status,
1257 NT_STATUS_OBJECT_NAME_NOT_FOUND))
1259 DEBUG(10, ("open_file: "
1260 "file %s vanished since we "
1261 "checked for existence.\n",
1262 smb_fname_str_dbg(smb_fname)));
1263 file_existed = false;
1264 SET_STAT_INVALID(fsp->fsp_name->st);
1268 if (!file_existed) {
1269 if (!(local_flags & O_CREAT)) {
1270 /* File didn't exist and no O_CREAT. */
1271 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
1274 status = check_parent_access(conn,
1278 if (!NT_STATUS_IS_OK(status)) {
1279 DEBUG(10, ("open_file: "
1280 "check_parent_access on "
1281 "file %s returned %s\n",
1282 smb_fname_str_dbg(smb_fname),
1283 nt_errstr(status) ));
1290 * Actually do the open - if O_TRUNC is needed handle it
1291 * below under the share mode lock.
1293 status = fd_open_atomic(conn, fsp, local_flags & ~O_TRUNC,
1294 unx_mode, p_file_created);
1295 if (!NT_STATUS_IS_OK(status)) {
1296 DEBUG(3,("Error opening file %s (%s) (local_flags=%d) "
1297 "(flags=%d)\n", smb_fname_str_dbg(smb_fname),
1298 nt_errstr(status),local_flags,flags));
1302 if (local_flags & O_NONBLOCK) {
1304 * GPFS can return ETIMEDOUT for pread on
1305 * nonblocking file descriptors when files
1306 * migrated to tape need to be recalled. I
1307 * could imagine this happens elsewhere
1308 * too. With blocking file descriptors this
1311 ret = vfs_set_blocking(fsp, true);
1313 status = map_nt_error_from_unix(errno);
1314 DBG_WARNING("Could not set fd to blocking: "
1315 "%s\n", strerror(errno));
1321 ret = SMB_VFS_FSTAT(fsp, &smb_fname->st);
1323 /* If we have an fd, this stat should succeed. */
1324 DEBUG(0,("Error doing fstat on open file %s "
1326 smb_fname_str_dbg(smb_fname),
1328 status = map_nt_error_from_unix(errno);
1333 if (*p_file_created) {
1334 /* We created this file. */
1336 bool need_re_stat = false;
1337 /* Do all inheritance work after we've
1338 done a successful fstat call and filled
1339 in the stat struct in fsp->fsp_name. */
1341 /* Inherit the ACL if required */
1342 if (lp_inherit_permissions(SNUM(conn))) {
1343 inherit_access_posix_acl(conn,
1347 need_re_stat = true;
1350 /* Change the owner if required. */
1351 if (lp_inherit_owner(SNUM(conn)) != INHERIT_OWNER_NO) {
1352 change_file_owner_to_parent(conn,
1355 need_re_stat = true;
1359 ret = SMB_VFS_FSTAT(fsp, &smb_fname->st);
1360 /* If we have an fd, this stat should succeed. */
1362 DEBUG(0,("Error doing fstat on open file %s "
1364 smb_fname_str_dbg(smb_fname),
1369 notify_fname(conn, NOTIFY_ACTION_ADDED,
1370 FILE_NOTIFY_CHANGE_FILE_NAME,
1371 smb_fname->base_name);
1374 fsp->fh->fd = -1; /* What we used to call a stat open. */
1375 if (!file_existed) {
1376 /* File must exist for a stat open. */
1377 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
1380 status = smbd_check_access_rights(conn,
1386 if (NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND) &&
1387 (fsp->posix_flags & FSP_POSIX_FLAGS_OPEN) &&
1388 S_ISLNK(smb_fname->st.st_ex_mode)) {
1389 /* This is a POSIX stat open for delete
1390 * or rename on a symlink that points
1391 * nowhere. Allow. */
1392 DEBUG(10,("open_file: allowing POSIX "
1393 "open on bad symlink %s\n",
1394 smb_fname_str_dbg(smb_fname)));
1395 status = NT_STATUS_OK;
1398 if (!NT_STATUS_IS_OK(status)) {
1399 DEBUG(10,("open_file: "
1400 "smbd_check_access_rights on file "
1402 smb_fname_str_dbg(smb_fname),
1403 nt_errstr(status) ));
1409 * POSIX allows read-only opens of directories. We don't
1410 * want to do this (we use a different code path for this)
1411 * so catch a directory open and return an EISDIR. JRA.
1414 if(S_ISDIR(smb_fname->st.st_ex_mode)) {
1417 return NT_STATUS_FILE_IS_A_DIRECTORY;
1420 fsp->file_id = vfs_file_id_from_sbuf(conn, &smb_fname->st);
1421 fsp->vuid = req ? req->vuid : UID_FIELD_INVALID;
1422 fsp->file_pid = req ? req->smbpid : 0;
1423 fsp->fsp_flags.can_lock = true;
1424 fsp->fsp_flags.can_read = ((access_mask & FILE_READ_DATA) != 0);
1425 fsp->fsp_flags.can_write =
1427 ((access_mask & (FILE_WRITE_DATA | FILE_APPEND_DATA)) != 0);
1428 fsp->print_file = NULL;
1429 fsp->fsp_flags.modified = false;
1430 fsp->sent_oplock_break = NO_BREAK_SENT;
1431 fsp->fsp_flags.is_directory = false;
1432 if (conn->aio_write_behind_list &&
1433 is_in_path(smb_fname->base_name, conn->aio_write_behind_list,
1434 conn->case_sensitive)) {
1435 fsp->fsp_flags.aio_write_behind = true;
1438 DEBUG(2,("%s opened file %s read=%s write=%s (numopen=%d)\n",
1439 conn->session_info->unix_info->unix_name,
1440 smb_fname_str_dbg(smb_fname),
1441 BOOLSTR(fsp->fsp_flags.can_read),
1442 BOOLSTR(fsp->fsp_flags.can_write),
1443 conn->num_files_open));
1446 return NT_STATUS_OK;
1449 static bool mask_conflict(
1450 uint32_t new_access,
1451 uint32_t existing_access,
1452 uint32_t access_mask,
1453 uint32_t new_sharemode,
1454 uint32_t existing_sharemode,
1455 uint32_t sharemode_mask)
1457 bool want_access = (new_access & access_mask);
1458 bool allow_existing = (existing_sharemode & sharemode_mask);
1459 bool have_access = (existing_access & access_mask);
1460 bool allow_new = (new_sharemode & sharemode_mask);
1462 if (want_access && !allow_existing) {
1463 DBG_DEBUG("Access request 0x%"PRIx32"/0x%"PRIx32" conflicts "
1464 "with existing sharemode 0x%"PRIx32"/0x%"PRIx32"\n",
1471 if (have_access && !allow_new) {
1472 DBG_DEBUG("Sharemode request 0x%"PRIx32"/0x%"PRIx32" conflicts "
1473 "with existing access 0x%"PRIx32"/0x%"PRIx32"\n",
1483 /****************************************************************************
1484 Check if we can open a file with a share mode.
1485 Returns True if conflict, False if not.
1486 ****************************************************************************/
1488 static const uint32_t conflicting_access =
1495 static bool share_conflict(uint32_t e_access_mask,
1496 uint32_t e_share_access,
1497 uint32_t access_mask,
1498 uint32_t share_access)
1502 DBG_DEBUG("existing access_mask = 0x%"PRIx32", "
1503 "existing share access = 0x%"PRIx32", "
1504 "access_mask = 0x%"PRIx32", "
1505 "share_access = 0x%"PRIx32"\n",
1511 if ((e_access_mask & conflicting_access) == 0) {
1512 DBG_DEBUG("No conflict due to "
1513 "existing access_mask = 0x%"PRIx32"\n",
1517 if ((access_mask & conflicting_access) == 0) {
1518 DBG_DEBUG("No conflict due to access_mask = 0x%"PRIx32"\n",
1523 conflict = mask_conflict(
1524 access_mask, e_access_mask, FILE_WRITE_DATA | FILE_APPEND_DATA,
1525 share_access, e_share_access, FILE_SHARE_WRITE);
1526 conflict |= mask_conflict(
1527 access_mask, e_access_mask, FILE_READ_DATA | FILE_EXECUTE,
1528 share_access, e_share_access, FILE_SHARE_READ);
1529 conflict |= mask_conflict(
1530 access_mask, e_access_mask, DELETE_ACCESS,
1531 share_access, e_share_access, FILE_SHARE_DELETE);
1533 DBG_DEBUG("conflict=%s\n", conflict ? "true" : "false");
1537 #if defined(DEVELOPER)
1539 struct validate_my_share_entries_state {
1540 struct smbd_server_connection *sconn;
1542 struct server_id self;
1545 static bool validate_my_share_entries_fn(
1546 struct share_mode_entry *e,
1550 struct validate_my_share_entries_state *state = private_data;
1553 if (!server_id_equal(&state->self, &e->pid)) {
1557 if (e->op_mid == 0) {
1558 /* INTERNAL_OPEN_ONLY */
1562 fsp = file_find_dif(state->sconn, state->fid, e->share_file_id);
1564 DBG_ERR("PANIC : %s\n",
1565 share_mode_str(talloc_tos(), 0, &state->fid, e));
1566 smb_panic("validate_my_share_entries: Cannot match a "
1567 "share entry with an open file\n");
1570 if (((uint16_t)fsp->oplock_type) != e->op_type) {
1579 DBG_ERR("validate_my_share_entries: PANIC : %s\n",
1580 share_mode_str(talloc_tos(), 0, &state->fid, e));
1581 str = talloc_asprintf(talloc_tos(),
1582 "validate_my_share_entries: "
1583 "file %s, oplock_type = 0x%x, op_type = 0x%x\n",
1584 fsp->fsp_name->base_name,
1585 (unsigned int)fsp->oplock_type,
1586 (unsigned int)e->op_type);
1595 * Allowed access mask for stat opens relevant to oplocks
1597 bool is_oplock_stat_open(uint32_t access_mask)
1599 const uint32_t stat_open_bits =
1600 (SYNCHRONIZE_ACCESS|
1601 FILE_READ_ATTRIBUTES|
1602 FILE_WRITE_ATTRIBUTES);
1604 return (((access_mask & stat_open_bits) != 0) &&
1605 ((access_mask & ~stat_open_bits) == 0));
1609 * Allowed access mask for stat opens relevant to leases
1611 bool is_lease_stat_open(uint32_t access_mask)
1613 const uint32_t stat_open_bits =
1614 (SYNCHRONIZE_ACCESS|
1615 FILE_READ_ATTRIBUTES|
1616 FILE_WRITE_ATTRIBUTES|
1617 READ_CONTROL_ACCESS);
1619 return (((access_mask & stat_open_bits) != 0) &&
1620 ((access_mask & ~stat_open_bits) == 0));
1623 struct has_delete_on_close_state {
1627 static bool has_delete_on_close_fn(
1628 struct share_mode_entry *e,
1632 struct has_delete_on_close_state *state = private_data;
1633 state->ret = !share_entry_stale_pid(e);
1637 static bool has_delete_on_close(struct share_mode_lock *lck,
1640 struct has_delete_on_close_state state = { .ret = false };
1643 if (!is_delete_on_close_set(lck, name_hash)) {
1647 ok= share_mode_forall_entries(lck, has_delete_on_close_fn, &state);
1649 DBG_DEBUG("share_mode_forall_entries failed\n");
1655 static void share_mode_flags_get(
1657 uint32_t *access_mask,
1658 uint32_t *share_mode,
1659 uint32_t *lease_type)
1661 if (access_mask != NULL) {
1663 ((flags & SHARE_MODE_ACCESS_READ) ?
1664 FILE_READ_DATA : 0) |
1665 ((flags & SHARE_MODE_ACCESS_WRITE) ?
1666 FILE_WRITE_DATA : 0) |
1667 ((flags & SHARE_MODE_ACCESS_DELETE) ?
1670 if (share_mode != NULL) {
1672 ((flags & SHARE_MODE_SHARE_READ) ?
1673 FILE_SHARE_READ : 0) |
1674 ((flags & SHARE_MODE_SHARE_WRITE) ?
1675 FILE_SHARE_WRITE : 0) |
1676 ((flags & SHARE_MODE_SHARE_DELETE) ?
1677 FILE_SHARE_DELETE : 0);
1679 if (lease_type != NULL) {
1681 ((flags & SHARE_MODE_LEASE_READ) ?
1682 SMB2_LEASE_READ : 0) |
1683 ((flags & SHARE_MODE_LEASE_WRITE) ?
1684 SMB2_LEASE_WRITE : 0) |
1685 ((flags & SHARE_MODE_LEASE_HANDLE) ?
1686 SMB2_LEASE_HANDLE : 0);
1690 static uint16_t share_mode_flags_set(
1692 uint32_t access_mask,
1693 uint32_t share_mode,
1694 uint32_t lease_type)
1696 if (access_mask != UINT32_MAX) {
1697 flags &= ~(SHARE_MODE_ACCESS_READ|
1698 SHARE_MODE_ACCESS_WRITE|
1699 SHARE_MODE_ACCESS_DELETE);
1700 flags |= (access_mask & (FILE_READ_DATA | FILE_EXECUTE)) ?
1701 SHARE_MODE_ACCESS_READ : 0;
1702 flags |= (access_mask & (FILE_WRITE_DATA | FILE_APPEND_DATA)) ?
1703 SHARE_MODE_ACCESS_WRITE : 0;
1704 flags |= (access_mask & (DELETE_ACCESS)) ?
1705 SHARE_MODE_ACCESS_DELETE : 0;
1707 if (share_mode != UINT32_MAX) {
1708 flags &= ~(SHARE_MODE_SHARE_READ|
1709 SHARE_MODE_SHARE_WRITE|
1710 SHARE_MODE_SHARE_DELETE);
1711 flags |= (share_mode & FILE_SHARE_READ) ?
1712 SHARE_MODE_SHARE_READ : 0;
1713 flags |= (share_mode & FILE_SHARE_WRITE) ?
1714 SHARE_MODE_SHARE_WRITE : 0;
1715 flags |= (share_mode & FILE_SHARE_DELETE) ?
1716 SHARE_MODE_SHARE_DELETE : 0;
1718 if (lease_type != UINT32_MAX) {
1719 flags &= ~(SHARE_MODE_LEASE_READ|
1720 SHARE_MODE_LEASE_WRITE|
1721 SHARE_MODE_LEASE_HANDLE);
1722 flags |= (lease_type & SMB2_LEASE_READ) ?
1723 SHARE_MODE_LEASE_READ : 0;
1724 flags |= (lease_type & SMB2_LEASE_WRITE) ?
1725 SHARE_MODE_LEASE_WRITE : 0;
1726 flags |= (lease_type & SMB2_LEASE_HANDLE) ?
1727 SHARE_MODE_LEASE_HANDLE : 0;
1733 static uint16_t share_mode_flags_restrict(
1735 uint32_t access_mask,
1736 uint32_t share_mode,
1737 uint32_t lease_type)
1739 uint32_t existing_access_mask, existing_share_mode;
1740 uint32_t existing_lease_type;
1743 share_mode_flags_get(
1745 &existing_access_mask,
1746 &existing_share_mode,
1747 &existing_lease_type);
1749 existing_access_mask |= access_mask;
1750 if (access_mask & conflicting_access) {
1751 existing_share_mode &= share_mode;
1753 existing_lease_type |= lease_type;
1755 ret = share_mode_flags_set(
1757 existing_access_mask,
1758 existing_share_mode,
1759 existing_lease_type);
1763 /****************************************************************************
1764 Deal with share modes
1765 Invariant: Share mode must be locked on entry and exit.
1766 Returns -1 on error, or number of share modes on success (may be zero).
1767 ****************************************************************************/
1769 struct open_mode_check_state {
1771 uint32_t access_mask;
1772 uint32_t share_access;
1773 uint32_t lease_type;
1776 static bool open_mode_check_fn(
1777 struct share_mode_entry *e,
1781 struct open_mode_check_state *state = private_data;
1782 bool disconnected, stale;
1783 uint32_t access_mask, share_access, lease_type;
1785 disconnected = server_id_is_disconnected(&e->pid);
1790 access_mask = state->access_mask | e->access_mask;
1791 share_access = state->share_access;
1792 if (e->access_mask & conflicting_access) {
1793 share_access &= e->share_access;
1795 lease_type = state->lease_type | get_lease_type(e, state->fid);
1797 if ((access_mask == state->access_mask) &&
1798 (share_access == state->share_access) &&
1799 (lease_type == state->lease_type)) {
1803 stale = share_entry_stale_pid(e);
1808 state->access_mask = access_mask;
1809 state->share_access = share_access;
1810 state->lease_type = lease_type;
1815 static NTSTATUS open_mode_check(connection_struct *conn,
1816 struct share_mode_lock *lck,
1817 uint32_t access_mask,
1818 uint32_t share_access)
1820 struct share_mode_data *d = lck->data;
1821 struct open_mode_check_state state;
1823 bool ok, conflict, have_share_entries;
1825 if (is_oplock_stat_open(access_mask)) {
1826 /* Stat open that doesn't trigger oplock breaks or share mode
1827 * checks... ! JRA. */
1828 return NT_STATUS_OK;
1832 * Check if the share modes will give us access.
1835 #if defined(DEVELOPER)
1837 struct validate_my_share_entries_state validate_state = {
1838 .sconn = conn->sconn,
1840 .self = messaging_server_id(conn->sconn->msg_ctx),
1842 ok = share_mode_forall_entries(
1843 lck, validate_my_share_entries_fn, &validate_state);
1848 have_share_entries = share_mode_have_entries(lck);
1849 if (!have_share_entries) {
1851 * This is a fresh share mode lock where no conflicts
1854 return NT_STATUS_OK;
1857 share_mode_flags_get(
1858 d->flags, &state.access_mask, &state.share_access, NULL);
1860 conflict = share_conflict(
1866 DBG_DEBUG("No conflict due to share_mode_flags access\n");
1867 return NT_STATUS_OK;
1870 state = (struct open_mode_check_state) {
1872 .share_access = (FILE_SHARE_READ|
1878 * Walk the share mode array to recalculate d->flags
1881 ok = share_mode_forall_entries(lck, open_mode_check_fn, &state);
1883 DBG_DEBUG("share_mode_forall_entries failed\n");
1884 return NT_STATUS_INTERNAL_ERROR;
1887 new_flags = share_mode_flags_set(
1888 0, state.access_mask, state.share_access, state.lease_type);
1889 if (new_flags == d->flags) {
1891 * We only end up here if we had a sharing violation
1892 * from d->flags and have recalculated it.
1894 return NT_STATUS_SHARING_VIOLATION;
1897 d->flags = new_flags;
1900 conflict = share_conflict(
1906 DBG_DEBUG("No conflict due to share_mode_flags access\n");
1907 return NT_STATUS_OK;
1910 return NT_STATUS_SHARING_VIOLATION;
1914 * Send a break message to the oplock holder and delay the open for
1918 NTSTATUS send_break_message(struct messaging_context *msg_ctx,
1919 const struct file_id *id,
1920 const struct share_mode_entry *exclusive,
1923 struct oplock_break_message msg = {
1925 .share_file_id = exclusive->share_file_id,
1926 .break_to = break_to,
1928 enum ndr_err_code ndr_err;
1933 struct server_id_buf buf;
1934 DBG_DEBUG("Sending break message to %s\n",
1935 server_id_str_buf(exclusive->pid, &buf));
1936 NDR_PRINT_DEBUG(oplock_break_message, &msg);
1939 ndr_err = ndr_push_struct_blob(
1943 (ndr_push_flags_fn_t)ndr_push_oplock_break_message);
1944 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
1945 DBG_WARNING("ndr_push_oplock_break_message failed: %s\n",
1946 ndr_errstr(ndr_err));
1947 return ndr_map_error2ntstatus(ndr_err);
1950 status = messaging_send(
1951 msg_ctx, exclusive->pid, MSG_SMB_BREAK_REQUEST, &blob);
1952 TALLOC_FREE(blob.data);
1953 if (!NT_STATUS_IS_OK(status)) {
1954 DEBUG(3, ("Could not send oplock break message: %s\n",
1955 nt_errstr(status)));
1961 struct validate_oplock_types_state {
1967 uint32_t num_non_stat_opens;
1970 static bool validate_oplock_types_fn(
1971 struct share_mode_entry *e,
1975 struct validate_oplock_types_state *state = private_data;
1977 if (e->op_mid == 0) {
1978 /* INTERNAL_OPEN_ONLY */
1982 if (e->op_type == NO_OPLOCK && is_oplock_stat_open(e->access_mask)) {
1984 * We ignore stat opens in the table - they always
1985 * have NO_OPLOCK and never get or cause breaks. JRA.
1990 state->num_non_stat_opens += 1;
1992 if (BATCH_OPLOCK_TYPE(e->op_type)) {
1993 /* batch - can only be one. */
1994 if (share_entry_stale_pid(e)) {
1995 DBG_DEBUG("Found stale batch oplock\n");
1998 if (state->ex_or_batch ||
2002 DBG_ERR("Bad batch oplock entry\n");
2003 state->valid = false;
2006 state->batch = true;
2009 if (EXCLUSIVE_OPLOCK_TYPE(e->op_type)) {
2010 if (share_entry_stale_pid(e)) {
2011 DBG_DEBUG("Found stale duplicate oplock\n");
2014 /* Exclusive or batch - can only be one. */
2015 if (state->ex_or_batch ||
2018 DBG_ERR("Bad exclusive or batch oplock entry\n");
2019 state->valid = false;
2022 state->ex_or_batch = true;
2025 if (LEVEL_II_OPLOCK_TYPE(e->op_type)) {
2026 if (state->batch || state->ex_or_batch) {
2027 if (share_entry_stale_pid(e)) {
2028 DBG_DEBUG("Found stale LevelII oplock\n");
2031 DBG_DEBUG("Bad levelII oplock entry\n");
2032 state->valid = false;
2035 state->level2 = true;
2038 if (e->op_type == NO_OPLOCK) {
2039 if (state->batch || state->ex_or_batch) {
2040 if (share_entry_stale_pid(e)) {
2041 DBG_DEBUG("Found stale NO_OPLOCK entry\n");
2044 DBG_ERR("Bad no oplock entry\n");
2045 state->valid = false;
2048 state->no_oplock = true;
2055 * Do internal consistency checks on the share mode for a file.
2058 static bool validate_oplock_types(struct share_mode_lock *lck)
2060 struct validate_oplock_types_state state = { .valid = true };
2063 ok = share_mode_forall_entries(lck, validate_oplock_types_fn, &state);
2065 DBG_DEBUG("share_mode_forall_entries failed\n");
2069 DBG_DEBUG("Got invalid oplock configuration\n");
2073 if ((state.batch || state.ex_or_batch) &&
2074 (state.num_non_stat_opens != 1)) {
2075 DBG_WARNING("got batch (%d) or ex (%d) non-exclusively "
2078 (int)state.ex_or_batch,
2079 state.num_non_stat_opens);
2086 static bool is_same_lease(const files_struct *fsp,
2087 const struct share_mode_entry *e,
2088 const struct smb2_lease *lease)
2090 if (e->op_type != LEASE_OPLOCK) {
2093 if (lease == NULL) {
2097 return smb2_lease_equal(fsp_client_guid(fsp),
2103 static bool file_has_brlocks(files_struct *fsp)
2105 struct byte_range_lock *br_lck;
2107 br_lck = brl_get_locks_readonly(fsp);
2111 return (brl_num_locks(br_lck) > 0);
2114 struct fsp_lease *find_fsp_lease(struct files_struct *new_fsp,
2115 const struct smb2_lease_key *key,
2116 uint32_t current_state,
2117 uint16_t lease_version,
2118 uint16_t lease_epoch)
2120 struct files_struct *fsp;
2123 * TODO: Measure how expensive this loop is with thousands of open
2127 for (fsp = file_find_di_first(new_fsp->conn->sconn, new_fsp->file_id);
2129 fsp = file_find_di_next(fsp)) {
2131 if (fsp == new_fsp) {
2134 if (fsp->oplock_type != LEASE_OPLOCK) {
2137 if (smb2_lease_key_equal(&fsp->lease->lease.lease_key, key)) {
2138 fsp->lease->ref_count += 1;
2143 /* Not found - must be leased in another smbd. */
2144 new_fsp->lease = talloc_zero(new_fsp->conn->sconn, struct fsp_lease);
2145 if (new_fsp->lease == NULL) {
2148 new_fsp->lease->ref_count = 1;
2149 new_fsp->lease->sconn = new_fsp->conn->sconn;
2150 new_fsp->lease->lease.lease_key = *key;
2151 new_fsp->lease->lease.lease_state = current_state;
2153 * We internally treat all leases as V2 and update
2154 * the epoch, but when sending breaks it matters if
2155 * the requesting lease was v1 or v2.
2157 new_fsp->lease->lease.lease_version = lease_version;
2158 new_fsp->lease->lease.lease_epoch = lease_epoch;
2159 return new_fsp->lease;
2162 static NTSTATUS try_lease_upgrade(struct files_struct *fsp,
2163 struct share_mode_lock *lck,
2164 const struct GUID *client_guid,
2165 const struct smb2_lease *lease,
2169 uint32_t current_state, breaking_to_requested, breaking_to_required;
2171 uint16_t lease_version, epoch;
2172 uint32_t existing, requested;
2175 status = leases_db_get(
2181 &breaking_to_requested,
2182 &breaking_to_required,
2185 if (!NT_STATUS_IS_OK(status)) {
2189 fsp->lease = find_fsp_lease(
2195 if (fsp->lease == NULL) {
2196 DEBUG(1, ("Did not find existing lease for file %s\n",
2198 return NT_STATUS_NO_MEMORY;
2202 * Upgrade only if the requested lease is a strict upgrade.
2204 existing = current_state;
2205 requested = lease->lease_state;
2208 * Tricky: This test makes sure that "requested" is a
2209 * strict bitwise superset of "existing".
2211 do_upgrade = ((existing & requested) == existing);
2214 * Upgrade only if there's a change.
2216 do_upgrade &= (granted != existing);
2219 * Upgrade only if other leases don't prevent what was asked
2222 do_upgrade &= (granted == requested);
2225 * only upgrade if we are not in breaking state
2227 do_upgrade &= !breaking;
2229 DEBUG(10, ("existing=%"PRIu32", requested=%"PRIu32", "
2230 "granted=%"PRIu32", do_upgrade=%d\n",
2231 existing, requested, granted, (int)do_upgrade));
2234 NTSTATUS set_status;
2236 current_state = granted;
2239 set_status = leases_db_set(
2244 breaking_to_requested,
2245 breaking_to_required,
2249 if (!NT_STATUS_IS_OK(set_status)) {
2250 DBG_DEBUG("leases_db_set failed: %s\n",
2251 nt_errstr(set_status));
2256 fsp_lease_update(fsp);
2258 return NT_STATUS_OK;
2261 static NTSTATUS grant_new_fsp_lease(struct files_struct *fsp,
2262 struct share_mode_lock *lck,
2263 const struct GUID *client_guid,
2264 const struct smb2_lease *lease,
2267 struct share_mode_data *d = lck->data;
2270 fsp->lease = talloc_zero(fsp->conn->sconn, struct fsp_lease);
2271 if (fsp->lease == NULL) {
2272 return NT_STATUS_INSUFFICIENT_RESOURCES;
2274 fsp->lease->ref_count = 1;
2275 fsp->lease->sconn = fsp->conn->sconn;
2276 fsp->lease->lease.lease_version = lease->lease_version;
2277 fsp->lease->lease.lease_key = lease->lease_key;
2278 fsp->lease->lease.lease_state = granted;
2279 fsp->lease->lease.lease_epoch = lease->lease_epoch + 1;
2281 status = leases_db_add(client_guid,
2284 fsp->lease->lease.lease_state,
2285 fsp->lease->lease.lease_version,
2286 fsp->lease->lease.lease_epoch,
2287 fsp->conn->connectpath,
2288 fsp->fsp_name->base_name,
2289 fsp->fsp_name->stream_name);
2290 if (!NT_STATUS_IS_OK(status)) {
2291 DEBUG(10, ("%s: leases_db_add failed: %s\n", __func__,
2292 nt_errstr(status)));
2293 TALLOC_FREE(fsp->lease);
2294 return NT_STATUS_INSUFFICIENT_RESOURCES;
2299 return NT_STATUS_OK;
2302 static NTSTATUS grant_fsp_lease(struct files_struct *fsp,
2303 struct share_mode_lock *lck,
2304 const struct smb2_lease *lease,
2307 const struct GUID *client_guid = fsp_client_guid(fsp);
2310 status = try_lease_upgrade(fsp, lck, client_guid, lease, granted);
2312 if (NT_STATUS_EQUAL(status, NT_STATUS_NOT_FOUND)) {
2313 status = grant_new_fsp_lease(
2314 fsp, lck, client_guid, lease, granted);
2320 static int map_lease_type_to_oplock(uint32_t lease_type)
2322 int result = NO_OPLOCK;
2324 switch (lease_type) {
2325 case SMB2_LEASE_READ|SMB2_LEASE_WRITE|SMB2_LEASE_HANDLE:
2326 result = BATCH_OPLOCK|EXCLUSIVE_OPLOCK;
2328 case SMB2_LEASE_READ|SMB2_LEASE_WRITE:
2329 result = EXCLUSIVE_OPLOCK;
2331 case SMB2_LEASE_READ|SMB2_LEASE_HANDLE:
2332 case SMB2_LEASE_READ:
2333 result = LEVEL_II_OPLOCK;
2340 struct delay_for_oplock_state {
2341 struct files_struct *fsp;
2342 const struct smb2_lease *lease;
2343 bool will_overwrite;
2344 uint32_t delay_mask;
2345 bool first_open_attempt;
2346 bool got_handle_lease;
2348 bool have_other_lease;
2352 static bool delay_for_oplock_fn(
2353 struct share_mode_entry *e,
2357 struct delay_for_oplock_state *state = private_data;
2358 struct files_struct *fsp = state->fsp;
2359 const struct smb2_lease *lease = state->lease;
2360 bool e_is_lease = (e->op_type == LEASE_OPLOCK);
2361 uint32_t e_lease_type = get_lease_type(e, fsp->file_id);
2363 bool lease_is_breaking = false;
2368 if (lease != NULL) {
2369 bool our_lease = is_same_lease(fsp, e, lease);
2371 DBG_DEBUG("Ignoring our own lease\n");
2376 status = leases_db_get(
2380 NULL, /* current_state */
2382 NULL, /* breaking_to_requested */
2383 NULL, /* breaking_to_required */
2384 NULL, /* lease_version */
2386 SMB_ASSERT(NT_STATUS_IS_OK(status));
2389 if (!state->got_handle_lease &&
2390 ((e_lease_type & SMB2_LEASE_HANDLE) != 0) &&
2391 !share_entry_stale_pid(e)) {
2392 state->got_handle_lease = true;
2395 if (!state->got_oplock &&
2396 (e->op_type != LEASE_OPLOCK) &&
2397 !share_entry_stale_pid(e)) {
2398 state->got_oplock = true;
2401 if (!state->have_other_lease &&
2402 !is_same_lease(fsp, e, lease) &&
2403 !share_entry_stale_pid(e)) {
2404 state->have_other_lease = true;
2407 if (e_is_lease && is_lease_stat_open(fsp->access_mask)) {
2411 break_to = e_lease_type & ~state->delay_mask;
2413 if (state->will_overwrite) {
2414 break_to &= ~(SMB2_LEASE_HANDLE|SMB2_LEASE_READ);
2417 DBG_DEBUG("e_lease_type %u, will_overwrite: %u\n",
2418 (unsigned)e_lease_type,
2419 (unsigned)state->will_overwrite);
2421 if ((e_lease_type & ~break_to) == 0) {
2422 if (lease_is_breaking) {
2423 state->delay = true;
2428 if (share_entry_stale_pid(e)) {
2432 if (state->will_overwrite) {
2434 * If we break anyway break to NONE directly.
2435 * Otherwise vfs_set_filelen() will trigger the
2438 break_to &= ~(SMB2_LEASE_READ|SMB2_LEASE_WRITE);
2443 * Oplocks only support breaking to R or NONE.
2445 break_to &= ~(SMB2_LEASE_HANDLE|SMB2_LEASE_WRITE);
2448 DBG_DEBUG("breaking from %d to %d\n",
2452 fsp->conn->sconn->msg_ctx, &fsp->file_id, e, break_to);
2453 if (e_lease_type & state->delay_mask) {
2454 state->delay = true;
2456 if (lease_is_breaking && !state->first_open_attempt) {
2457 state->delay = true;
2463 static NTSTATUS delay_for_oplock(files_struct *fsp,
2465 const struct smb2_lease *lease,
2466 struct share_mode_lock *lck,
2467 bool have_sharing_violation,
2468 uint32_t create_disposition,
2469 bool first_open_attempt)
2471 struct delay_for_oplock_state state = {
2474 .first_open_attempt = first_open_attempt,
2480 if (is_oplock_stat_open(fsp->access_mask)) {
2484 state.delay_mask = have_sharing_violation ?
2485 SMB2_LEASE_HANDLE : SMB2_LEASE_WRITE;
2487 switch (create_disposition) {
2488 case FILE_SUPERSEDE:
2489 case FILE_OVERWRITE:
2490 case FILE_OVERWRITE_IF:
2491 state.will_overwrite = true;
2494 state.will_overwrite = false;
2498 ok = share_mode_forall_entries(lck, delay_for_oplock_fn, &state);
2500 return NT_STATUS_INTERNAL_ERROR;
2504 return NT_STATUS_RETRY;
2508 if (have_sharing_violation) {
2509 return NT_STATUS_SHARING_VIOLATION;
2512 if (oplock_request == LEASE_OPLOCK) {
2513 if (lease == NULL) {
2515 * The SMB2 layer should have checked this
2517 return NT_STATUS_INTERNAL_ERROR;
2520 granted = lease->lease_state;
2522 if (lp_kernel_oplocks(SNUM(fsp->conn))) {
2523 DEBUG(10, ("No lease granted because kernel oplocks are enabled\n"));
2524 granted = SMB2_LEASE_NONE;
2526 if ((granted & (SMB2_LEASE_READ|SMB2_LEASE_WRITE)) == 0) {
2527 DEBUG(10, ("No read or write lease requested\n"));
2528 granted = SMB2_LEASE_NONE;
2530 if (granted == SMB2_LEASE_WRITE) {
2531 DEBUG(10, ("pure write lease requested\n"));
2532 granted = SMB2_LEASE_NONE;
2534 if (granted == (SMB2_LEASE_WRITE|SMB2_LEASE_HANDLE)) {
2535 DEBUG(10, ("write and handle lease requested\n"));
2536 granted = SMB2_LEASE_NONE;
2539 granted = map_oplock_to_lease_type(
2540 oplock_request & ~SAMBA_PRIVATE_OPLOCK_MASK);
2543 if (lp_locking(fsp->conn->params) && file_has_brlocks(fsp)) {
2544 DBG_DEBUG("file %s has byte range locks\n",
2546 granted &= ~SMB2_LEASE_READ;
2549 if (state.have_other_lease) {
2551 * Can grant only one writer
2553 granted &= ~SMB2_LEASE_WRITE;
2556 if ((granted & SMB2_LEASE_READ) && !(granted & SMB2_LEASE_WRITE)) {
2558 (global_client_caps & CAP_LEVEL_II_OPLOCKS) &&
2559 lp_level2_oplocks(SNUM(fsp->conn));
2561 if (!allow_level2) {
2562 granted = SMB2_LEASE_NONE;
2566 if (oplock_request == LEASE_OPLOCK) {
2567 if (state.got_oplock) {
2568 granted &= ~SMB2_LEASE_HANDLE;
2571 fsp->oplock_type = LEASE_OPLOCK;
2573 status = grant_fsp_lease(fsp, lck, lease, granted);
2574 if (!NT_STATUS_IS_OK(status)) {
2579 DBG_DEBUG("lease_state=%d\n", fsp->lease->lease.lease_state);
2581 if (state.got_handle_lease) {
2582 granted = SMB2_LEASE_NONE;
2585 fsp->oplock_type = map_lease_type_to_oplock(granted);
2587 status = set_file_oplock(fsp);
2588 if (!NT_STATUS_IS_OK(status)) {
2590 * Could not get the kernel oplock
2592 fsp->oplock_type = NO_OPLOCK;
2596 if ((granted & SMB2_LEASE_READ) &&
2597 ((lck->data->flags & SHARE_MODE_LEASE_READ) == 0)) {
2598 lck->data->flags |= SHARE_MODE_LEASE_READ;
2599 lck->data->modified = true;
2602 DBG_DEBUG("oplock type 0x%x on file %s\n",
2603 fsp->oplock_type, fsp_str_dbg(fsp));
2605 return NT_STATUS_OK;
2608 static NTSTATUS handle_share_mode_lease(
2610 struct share_mode_lock *lck,
2611 uint32_t create_disposition,
2612 uint32_t access_mask,
2613 uint32_t share_access,
2615 const struct smb2_lease *lease,
2616 bool first_open_attempt)
2618 bool sharing_violation = false;
2621 status = open_mode_check(
2622 fsp->conn, lck, access_mask, share_access);
2623 if (NT_STATUS_EQUAL(status, NT_STATUS_SHARING_VIOLATION)) {
2624 sharing_violation = true;
2625 status = NT_STATUS_OK; /* handled later */
2628 if (!NT_STATUS_IS_OK(status)) {
2632 if (oplock_request == INTERNAL_OPEN_ONLY) {
2633 if (sharing_violation) {
2634 DBG_DEBUG("Sharing violation for internal open\n");
2635 return NT_STATUS_SHARING_VIOLATION;
2639 * Internal opens never do oplocks or leases. We don't
2640 * need to go through delay_for_oplock().
2642 fsp->oplock_type = NO_OPLOCK;
2644 return NT_STATUS_OK;
2647 status = delay_for_oplock(
2654 first_open_attempt);
2655 if (!NT_STATUS_IS_OK(status)) {
2659 return NT_STATUS_OK;
2662 static bool request_timed_out(struct smb_request *req, struct timeval timeout)
2664 struct timeval now, end_time;
2666 end_time = timeval_sum(&req->request_time, &timeout);
2667 return (timeval_compare(&end_time, &now) < 0);
2670 struct defer_open_state {
2671 struct smbXsrv_connection *xconn;
2675 static void defer_open_done(struct tevent_req *req);
2678 * Defer an open and watch a locking.tdb record
2680 * This defers an open that gets rescheduled once the locking.tdb record watch
2681 * is triggered by a change to the record.
2683 * It is used to defer opens that triggered an oplock break and for the SMB1
2684 * sharing violation delay.
2686 static void defer_open(struct share_mode_lock *lck,
2687 struct timeval timeout,
2688 struct smb_request *req,
2691 struct deferred_open_record *open_rec = NULL;
2692 struct timeval abs_timeout;
2693 struct defer_open_state *watch_state;
2694 struct tevent_req *watch_req;
2695 struct timeval_buf tvbuf1, tvbuf2;
2696 struct file_id_buf fbuf;
2699 abs_timeout = timeval_sum(&req->request_time, &timeout);
2701 DBG_DEBUG("request time [%s] timeout [%s] mid [%" PRIu64 "] "
2703 timeval_str_buf(&req->request_time, false, true, &tvbuf1),
2704 timeval_str_buf(&abs_timeout, false, true, &tvbuf2),
2706 file_id_str_buf(id, &fbuf));
2708 open_rec = talloc_zero(NULL, struct deferred_open_record);
2709 if (open_rec == NULL) {
2711 exit_server("talloc failed");
2714 watch_state = talloc(open_rec, struct defer_open_state);
2715 if (watch_state == NULL) {
2716 exit_server("talloc failed");
2718 watch_state->xconn = req->xconn;
2719 watch_state->mid = req->mid;
2721 DBG_DEBUG("defering mid %" PRIu64 "\n", req->mid);
2723 watch_req = share_mode_watch_send(
2727 (struct server_id){0});
2728 if (watch_req == NULL) {
2729 exit_server("Could not watch share mode record");
2731 tevent_req_set_callback(watch_req, defer_open_done, watch_state);
2733 ok = tevent_req_set_endtime(watch_req, req->sconn->ev_ctx, abs_timeout);
2735 exit_server("tevent_req_set_endtime failed");
2738 ok = push_deferred_open_message_smb(req, timeout, id, open_rec);
2741 exit_server("push_deferred_open_message_smb failed");
2745 static void defer_open_done(struct tevent_req *req)
2747 struct defer_open_state *state = tevent_req_callback_data(
2748 req, struct defer_open_state);
2752 status = share_mode_watch_recv(req, NULL, NULL);
2754 if (!NT_STATUS_IS_OK(status)) {
2755 DEBUG(5, ("dbwrap_watched_watch_recv returned %s\n",
2756 nt_errstr(status)));
2758 * Even if it failed, retry anyway. TODO: We need a way to
2759 * tell a re-scheduled open about that error.
2763 DEBUG(10, ("scheduling mid %llu\n", (unsigned long long)state->mid));
2765 ret = schedule_deferred_open_message_smb(state->xconn, state->mid);
2771 * Actually attempt the kernel oplock polling open.
2774 static void poll_open_fn(struct tevent_context *ev,
2775 struct tevent_timer *te,
2776 struct timeval current_time,
2779 struct deferred_open_record *open_rec = talloc_get_type_abort(
2780 private_data, struct deferred_open_record);
2783 TALLOC_FREE(open_rec->watch_req);
2785 ok = schedule_deferred_open_message_smb(
2786 open_rec->xconn, open_rec->mid);
2788 exit_server("schedule_deferred_open_message_smb failed");
2790 DBG_DEBUG("timer fired. Retrying open !\n");
2793 static void poll_open_done(struct tevent_req *subreq);
2796 * Reschedule an open for 1 second from now, if not timed out.
2798 static bool setup_poll_open(
2799 struct smb_request *req,
2800 struct share_mode_lock *lck,
2802 struct timeval max_timeout,
2803 struct timeval interval)
2806 struct deferred_open_record *open_rec = NULL;
2807 struct timeval endtime, next_interval;
2808 struct file_id_buf ftmp;
2810 if (request_timed_out(req, max_timeout)) {
2814 open_rec = talloc_zero(NULL, struct deferred_open_record);
2815 if (open_rec == NULL) {
2816 DBG_WARNING("talloc failed\n");
2819 open_rec->xconn = req->xconn;
2820 open_rec->mid = req->mid;
2823 * Make sure open_rec->te does not come later than the
2824 * request's maximum endtime.
2827 endtime = timeval_sum(&req->request_time, &max_timeout);
2828 next_interval = timeval_current_ofs(interval.tv_sec, interval.tv_usec);
2829 next_interval = timeval_min(&endtime, &next_interval);
2831 open_rec->te = tevent_add_timer(
2837 if (open_rec->te == NULL) {
2838 DBG_WARNING("tevent_add_timer failed\n");
2839 TALLOC_FREE(open_rec);
2844 open_rec->watch_req = share_mode_watch_send(
2848 (struct server_id) {0});
2849 if (open_rec->watch_req == NULL) {
2850 DBG_WARNING("share_mode_watch_send failed\n");
2851 TALLOC_FREE(open_rec);
2854 tevent_req_set_callback(
2855 open_rec->watch_req, poll_open_done, open_rec);
2858 ok = push_deferred_open_message_smb(req, max_timeout, id, open_rec);
2860 DBG_WARNING("push_deferred_open_message_smb failed\n");
2861 TALLOC_FREE(open_rec);
2865 DBG_DEBUG("poll request time [%s] mid [%" PRIu64 "] file_id [%s]\n",
2866 timeval_string(talloc_tos(), &req->request_time, false),
2868 file_id_str_buf(id, &ftmp));
2873 static void poll_open_done(struct tevent_req *subreq)
2875 struct deferred_open_record *open_rec = tevent_req_callback_data(
2876 subreq, struct deferred_open_record);
2880 status = share_mode_watch_recv(subreq, NULL, NULL);
2881 TALLOC_FREE(subreq);
2882 DBG_DEBUG("dbwrap_watched_watch_recv returned %s\n",
2885 ok = schedule_deferred_open_message_smb(
2886 open_rec->xconn, open_rec->mid);
2888 exit_server("schedule_deferred_open_message_smb failed");
2892 bool defer_smb1_sharing_violation(struct smb_request *req)
2897 if (!lp_defer_sharing_violations()) {
2902 * Try every 200msec up to (by default) one second. To be
2903 * precise, according to behaviour note <247> in [MS-CIFS],
2904 * the server tries 5 times. But up to one second should be
2908 timeout_usecs = lp_parm_int(
2912 SHARING_VIOLATION_USEC_WAIT);
2914 ok = setup_poll_open(
2917 (struct file_id) {0},
2918 (struct timeval) { .tv_usec = timeout_usecs },
2919 (struct timeval) { .tv_usec = 200000 });
2923 /****************************************************************************
2924 On overwrite open ensure that the attributes match.
2925 ****************************************************************************/
2927 static bool open_match_attributes(connection_struct *conn,
2928 uint32_t old_dos_attr,
2929 uint32_t new_dos_attr,
2930 mode_t new_unx_mode,
2931 mode_t *returned_unx_mode)
2933 uint32_t noarch_old_dos_attr, noarch_new_dos_attr;
2935 noarch_old_dos_attr = (old_dos_attr & ~FILE_ATTRIBUTE_ARCHIVE);
2936 noarch_new_dos_attr = (new_dos_attr & ~FILE_ATTRIBUTE_ARCHIVE);
2938 if((noarch_old_dos_attr == 0 && noarch_new_dos_attr != 0) ||
2939 (noarch_old_dos_attr != 0 && ((noarch_old_dos_attr & noarch_new_dos_attr) == noarch_old_dos_attr))) {
2940 *returned_unx_mode = new_unx_mode;
2942 *returned_unx_mode = (mode_t)0;
2945 DEBUG(10,("open_match_attributes: old_dos_attr = 0x%x, "
2946 "new_dos_attr = 0x%x "
2947 "returned_unx_mode = 0%o\n",
2948 (unsigned int)old_dos_attr,
2949 (unsigned int)new_dos_attr,
2950 (unsigned int)*returned_unx_mode ));
2952 /* If we're mapping SYSTEM and HIDDEN ensure they match. */
2953 if (lp_map_system(SNUM(conn)) || lp_store_dos_attributes(SNUM(conn))) {
2954 if ((old_dos_attr & FILE_ATTRIBUTE_SYSTEM) &&
2955 !(new_dos_attr & FILE_ATTRIBUTE_SYSTEM)) {
2959 if (lp_map_hidden(SNUM(conn)) || lp_store_dos_attributes(SNUM(conn))) {
2960 if ((old_dos_attr & FILE_ATTRIBUTE_HIDDEN) &&
2961 !(new_dos_attr & FILE_ATTRIBUTE_HIDDEN)) {
2968 static void schedule_defer_open(struct share_mode_lock *lck,
2970 struct smb_request *req)
2972 /* This is a relative time, added to the absolute
2973 request_time value to get the absolute timeout time.
2974 Note that if this is the second or greater time we enter
2975 this codepath for this particular request mid then
2976 request_time is left as the absolute time of the *first*
2977 time this request mid was processed. This is what allows
2978 the request to eventually time out. */
2980 struct timeval timeout;
2982 /* Normally the smbd we asked should respond within
2983 * OPLOCK_BREAK_TIMEOUT seconds regardless of whether
2984 * the client did, give twice the timeout as a safety
2985 * measure here in case the other smbd is stuck
2986 * somewhere else. */
2988 timeout = timeval_set(OPLOCK_BREAK_TIMEOUT*2, 0);
2990 if (request_timed_out(req, timeout)) {
2994 defer_open(lck, timeout, req, id);
2997 /****************************************************************************
2998 Reschedule an open call that went asynchronous.
2999 ****************************************************************************/
3001 static void schedule_async_open_timer(struct tevent_context *ev,
3002 struct tevent_timer *te,
3003 struct timeval current_time,
3006 exit_server("async open timeout");
3009 static void schedule_async_open(struct smb_request *req)
3011 struct deferred_open_record *open_rec = NULL;
3012 struct timeval timeout = timeval_set(20, 0);
3015 if (request_timed_out(req, timeout)) {
3019 open_rec = talloc_zero(NULL, struct deferred_open_record);
3020 if (open_rec == NULL) {
3021 exit_server("deferred_open_record_create failed");
3023 open_rec->async_open = true;
3025 ok = push_deferred_open_message_smb(
3026 req, timeout, (struct file_id){0}, open_rec);
3028 exit_server("push_deferred_open_message_smb failed");
3031 open_rec->te = tevent_add_timer(req->sconn->ev_ctx,
3033 timeval_current_ofs(20, 0),
3034 schedule_async_open_timer,
3036 if (open_rec->te == NULL) {
3037 exit_server("tevent_add_timer failed");
3041 /****************************************************************************
3042 Work out what access_mask to use from what the client sent us.
3043 ****************************************************************************/
3045 static NTSTATUS smbd_calculate_maximum_allowed_access(
3046 connection_struct *conn,
3047 struct files_struct *dirfsp,
3048 const struct smb_filename *smb_fname,
3050 uint32_t *p_access_mask)
3052 struct security_descriptor *sd;
3053 uint32_t access_granted;
3056 SMB_ASSERT(dirfsp == conn->cwd_fsp);
3058 if (!use_privs && (get_current_uid(conn) == (uid_t)0)) {
3059 *p_access_mask |= FILE_GENERIC_ALL;
3060 return NT_STATUS_OK;
3063 status = SMB_VFS_GET_NT_ACL_AT(conn,
3072 if (NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
3074 * File did not exist
3076 *p_access_mask = FILE_GENERIC_ALL;
3077 return NT_STATUS_OK;
3079 if (!NT_STATUS_IS_OK(status)) {
3080 DEBUG(10,("Could not get acl on file %s: %s\n",
3081 smb_fname_str_dbg(smb_fname),
3082 nt_errstr(status)));
3083 return NT_STATUS_ACCESS_DENIED;
3087 * If we can access the path to this file, by
3088 * default we have FILE_READ_ATTRIBUTES from the
3089 * containing directory. See the section:
3090 * "Algorithm to Check Access to an Existing File"
3093 * se_file_access_check()
3094 * also takes care of owner WRITE_DAC and READ_CONTROL.
3096 status = se_file_access_check(sd,
3097 get_current_nttok(conn),
3099 (*p_access_mask & ~FILE_READ_ATTRIBUTES),
3104 if (!NT_STATUS_IS_OK(status)) {
3105 DEBUG(10, ("Access denied on file %s: "
3106 "when calculating maximum access\n",
3107 smb_fname_str_dbg(smb_fname)));
3108 return NT_STATUS_ACCESS_DENIED;
3110 *p_access_mask = (access_granted | FILE_READ_ATTRIBUTES);
3112 if (!(access_granted & DELETE_ACCESS)) {
3113 if (can_delete_file_in_directory(conn,
3117 *p_access_mask |= DELETE_ACCESS;
3121 return NT_STATUS_OK;
3124 NTSTATUS smbd_calculate_access_mask(connection_struct *conn,
3125 struct files_struct *dirfsp,
3126 const struct smb_filename *smb_fname,
3128 uint32_t access_mask,
3129 uint32_t *access_mask_out)
3132 uint32_t orig_access_mask = access_mask;
3133 uint32_t rejected_share_access;
3135 SMB_ASSERT(dirfsp == conn->cwd_fsp);
3137 if (access_mask & SEC_MASK_INVALID) {
3138 DBG_DEBUG("access_mask [%8x] contains invalid bits\n",
3140 return NT_STATUS_ACCESS_DENIED;
3144 * Convert GENERIC bits to specific bits.
3147 se_map_generic(&access_mask, &file_generic_mapping);
3149 /* Calculate MAXIMUM_ALLOWED_ACCESS if requested. */
3150 if (access_mask & MAXIMUM_ALLOWED_ACCESS) {
3152 status = smbd_calculate_maximum_allowed_access(conn,
3158 if (!NT_STATUS_IS_OK(status)) {
3162 access_mask &= conn->share_access;
3165 rejected_share_access = access_mask & ~(conn->share_access);
3167 if (rejected_share_access) {
3168 DEBUG(10, ("smbd_calculate_access_mask: Access denied on "
3169 "file %s: rejected by share access mask[0x%08X] "
3170 "orig[0x%08X] mapped[0x%08X] reject[0x%08X]\n",
3171 smb_fname_str_dbg(smb_fname),
3173 orig_access_mask, access_mask,
3174 rejected_share_access));
3175 return NT_STATUS_ACCESS_DENIED;
3178 *access_mask_out = access_mask;
3179 return NT_STATUS_OK;
3182 /****************************************************************************
3183 Remove the deferred open entry under lock.
3184 ****************************************************************************/
3186 /****************************************************************************
3187 Return true if this is a state pointer to an asynchronous create.
3188 ****************************************************************************/
3190 bool is_deferred_open_async(const struct deferred_open_record *rec)
3192 return rec->async_open;
3195 static bool clear_ads(uint32_t create_disposition)
3199 switch (create_disposition) {
3200 case FILE_SUPERSEDE:
3201 case FILE_OVERWRITE_IF:
3202 case FILE_OVERWRITE:
3211 static int disposition_to_open_flags(uint32_t create_disposition)
3216 * Currently we're using FILE_SUPERSEDE as the same as
3217 * FILE_OVERWRITE_IF but they really are
3218 * different. FILE_SUPERSEDE deletes an existing file
3219 * (requiring delete access) then recreates it.
3222 switch (create_disposition) {
3223 case FILE_SUPERSEDE:
3224 case FILE_OVERWRITE_IF:
3226 * If file exists replace/overwrite. If file doesn't
3229 ret = O_CREAT|O_TRUNC;
3234 * If file exists open. If file doesn't exist error.
3239 case FILE_OVERWRITE:
3241 * If file exists overwrite. If file doesn't exist
3249 * If file exists error. If file doesn't exist create.
3251 ret = O_CREAT|O_EXCL;
3256 * If file exists open. If file doesn't exist create.
3264 static int calculate_open_access_flags(uint32_t access_mask,
3265 uint32_t private_flags)
3267 bool need_write, need_read;
3270 * Note that we ignore the append flag as append does not
3271 * mean the same thing under DOS and Unix.
3274 need_write = (access_mask & (FILE_WRITE_DATA | FILE_APPEND_DATA));
3279 /* DENY_DOS opens are always underlying read-write on the
3280 file handle, no matter what the requested access mask
3284 ((private_flags & NTCREATEX_OPTIONS_PRIVATE_DENY_DOS) ||
3285 access_mask & (FILE_READ_ATTRIBUTES|FILE_READ_DATA|
3286 FILE_READ_EA|FILE_EXECUTE));
3294 /****************************************************************************
3295 Open a file with a share mode. Passed in an already created files_struct *.
3296 ****************************************************************************/
3298 static NTSTATUS open_file_ntcreate(connection_struct *conn,
3299 struct smb_request *req,
3300 uint32_t access_mask, /* access bits (FILE_READ_DATA etc.) */
3301 uint32_t share_access, /* share constants (FILE_SHARE_READ etc) */
3302 uint32_t create_disposition, /* FILE_OPEN_IF etc. */
3303 uint32_t create_options, /* options such as delete on close. */
3304 uint32_t new_dos_attributes, /* attributes used for new file. */
3305 int oplock_request, /* internal Samba oplock codes. */
3306 const struct smb2_lease *lease,
3307 /* Information (FILE_EXISTS etc.) */
3308 uint32_t private_flags, /* Samba specific flags. */
3312 struct smb_filename *smb_fname = fsp->fsp_name;
3315 bool file_existed = VALID_STAT(smb_fname->st);
3316 bool def_acl = False;
3317 bool posix_open = False;
3318 bool new_file_created = False;
3319 bool first_open_attempt = true;
3320 NTSTATUS fsp_open = NT_STATUS_ACCESS_DENIED;
3321 mode_t new_unx_mode = (mode_t)0;
3322 mode_t unx_mode = (mode_t)0;
3324 uint32_t existing_dos_attributes = 0;
3325 struct share_mode_lock *lck = NULL;
3326 uint32_t open_access_mask = access_mask;
3328 struct smb_filename *parent_dir_fname = NULL;
3329 SMB_STRUCT_STAT saved_stat = smb_fname->st;
3330 struct timespec old_write_time;
3332 bool setup_poll = false;
3335 if (conn->printer) {
3337 * Printers are handled completely differently.
3338 * Most of the passed parameters are ignored.
3342 *pinfo = FILE_WAS_CREATED;
3345 DEBUG(10, ("open_file_ntcreate: printer open fname=%s\n",
3346 smb_fname_str_dbg(smb_fname)));
3349 DEBUG(0,("open_file_ntcreate: printer open without "
3350 "an SMB request!\n"));
3351 return NT_STATUS_INTERNAL_ERROR;
3354 return print_spool_open(fsp, smb_fname->base_name,
3358 ok = parent_smb_fname(talloc_tos(),
3363 return NT_STATUS_NO_MEMORY;
3366 if (new_dos_attributes & FILE_FLAG_POSIX_SEMANTICS) {
3368 unx_mode = (mode_t)(new_dos_attributes & ~FILE_FLAG_POSIX_SEMANTICS);
3369 new_dos_attributes = 0;
3371 /* Windows allows a new file to be created and
3372 silently removes a FILE_ATTRIBUTE_DIRECTORY
3373 sent by the client. Do the same. */
3375 new_dos_attributes &= ~FILE_ATTRIBUTE_DIRECTORY;
3377 /* We add FILE_ATTRIBUTE_ARCHIVE to this as this mode is only used if the file is
3379 unx_mode = unix_mode(conn, new_dos_attributes | FILE_ATTRIBUTE_ARCHIVE,
3380 smb_fname, parent_dir_fname);
3383 DEBUG(10, ("open_file_ntcreate: fname=%s, dos_attrs=0x%x "
3384 "access_mask=0x%x share_access=0x%x "
3385 "create_disposition = 0x%x create_options=0x%x "
3386 "unix mode=0%o oplock_request=%d private_flags = 0x%x\n",
3387 smb_fname_str_dbg(smb_fname), new_dos_attributes,
3388 access_mask, share_access, create_disposition,
3389 create_options, (unsigned int)unx_mode, oplock_request,
3390 (unsigned int)private_flags));
3393 /* Ensure req == NULL means INTERNAL_OPEN_ONLY */
3394 SMB_ASSERT(oplock_request == INTERNAL_OPEN_ONLY);
3396 /* And req != NULL means no INTERNAL_OPEN_ONLY */
3397 SMB_ASSERT(((oplock_request & INTERNAL_OPEN_ONLY) == 0));
3401 * Only non-internal opens can be deferred at all
3405 struct deferred_open_record *open_rec;
3406 if (get_deferred_open_message_state(req, NULL, &open_rec)) {
3408 /* If it was an async create retry, the file
3411 if (is_deferred_open_async(open_rec)) {
3412 SET_STAT_INVALID(smb_fname->st);
3413 file_existed = false;
3416 /* Ensure we don't reprocess this message. */
3417 remove_deferred_open_message_smb(req->xconn, req->mid);
3419 first_open_attempt = false;
3424 new_dos_attributes &= SAMBA_ATTRIBUTES_MASK;
3427 * Only use stored DOS attributes for checks
3428 * against requested attributes (below via
3429 * open_match_attributes()), cf bug #11992
3430 * for details. -slow
3434 status = SMB_VFS_GET_DOS_ATTRIBUTES(conn, smb_fname, &attr);
3435 if (NT_STATUS_IS_OK(status)) {
3436 existing_dos_attributes = attr;
3441 /* ignore any oplock requests if oplocks are disabled */
3442 if (!lp_oplocks(SNUM(conn)) ||
3443 IS_VETO_OPLOCK_PATH(conn, smb_fname->base_name)) {
3444 /* Mask off everything except the private Samba bits. */
3445 oplock_request &= SAMBA_PRIVATE_OPLOCK_MASK;
3448 /* this is for OS/2 long file names - say we don't support them */
3449 if (req != NULL && !req->posix_pathnames &&
3450 strstr(smb_fname->base_name,".+,;=[].")) {
3451 /* OS/2 Workplace shell fix may be main code stream in a later
3453 DEBUG(5,("open_file_ntcreate: OS/2 long filenames are not "
3455 if (use_nt_status()) {
3456 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3458 return NT_STATUS_DOS(ERRDOS, ERRcannotopen);
3461 switch( create_disposition ) {
3463 /* If file exists open. If file doesn't exist error. */
3464 if (!file_existed) {
3465 DEBUG(5,("open_file_ntcreate: FILE_OPEN "
3466 "requested for file %s and file "
3468 smb_fname_str_dbg(smb_fname)));
3470 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3474 case FILE_OVERWRITE:
3475 /* If file exists overwrite. If file doesn't exist
3477 if (!file_existed) {
3478 DEBUG(5,("open_file_ntcreate: FILE_OVERWRITE "
3479 "requested for file %s and file "
3481 smb_fname_str_dbg(smb_fname) ));
3483 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3488 /* If file exists error. If file doesn't exist
3491 DEBUG(5,("open_file_ntcreate: FILE_CREATE "
3492 "requested for file %s and file "
3493 "already exists.\n",
3494 smb_fname_str_dbg(smb_fname)));
3495 if (S_ISDIR(smb_fname->st.st_ex_mode)) {
3500 return map_nt_error_from_unix(errno);
3504 case FILE_SUPERSEDE:
3505 case FILE_OVERWRITE_IF:
3509 return NT_STATUS_INVALID_PARAMETER;
3512 flags2 = disposition_to_open_flags(create_disposition);
3514 /* We only care about matching attributes on file exists and
3517 if (!posix_open && file_existed &&
3518 ((create_disposition == FILE_OVERWRITE) ||
3519 (create_disposition == FILE_OVERWRITE_IF))) {
3520 if (!open_match_attributes(conn, existing_dos_attributes,
3522 unx_mode, &new_unx_mode)) {
3523 DEBUG(5,("open_file_ntcreate: attributes mismatch "
3524 "for file %s (%x %x) (0%o, 0%o)\n",
3525 smb_fname_str_dbg(smb_fname),
3526 existing_dos_attributes,
3528 (unsigned int)smb_fname->st.st_ex_mode,
3529 (unsigned int)unx_mode ));
3531 return NT_STATUS_ACCESS_DENIED;
3535 status = smbd_calculate_access_mask(conn,
3541 if (!NT_STATUS_IS_OK(status)) {
3542 DEBUG(10, ("open_file_ntcreate: smbd_calculate_access_mask "
3543 "on file %s returned %s\n",
3544 smb_fname_str_dbg(smb_fname), nt_errstr(status)));
3548 open_access_mask = access_mask;
3550 if (flags2 & O_TRUNC) {
3551 open_access_mask |= FILE_WRITE_DATA; /* This will cause oplock breaks. */
3556 * stat opens on existing files don't get oplocks.
3557 * They can get leases.
3559 * Note that we check for stat open on the *open_access_mask*,
3560 * i.e. the access mask we actually used to do the open,
3561 * not the one the client asked for (which is in
3562 * fsp->access_mask). This is due to the fact that
3563 * FILE_OVERWRITE and FILE_OVERWRITE_IF add in O_TRUNC,
3564 * which adds FILE_WRITE_DATA to open_access_mask.
3566 if (is_oplock_stat_open(open_access_mask) && lease == NULL) {
3567 oplock_request = NO_OPLOCK;
3571 DEBUG(10, ("open_file_ntcreate: fname=%s, after mapping "
3572 "access_mask=0x%x\n", smb_fname_str_dbg(smb_fname),
3576 * Note that we ignore the append flag as append does not
3577 * mean the same thing under DOS and Unix.
3580 flags = calculate_open_access_flags(access_mask, private_flags);
3583 * Currently we only look at FILE_WRITE_THROUGH for create options.
3587 if ((create_options & FILE_WRITE_THROUGH) && lp_strict_sync(SNUM(conn))) {
3592 if (posix_open && (access_mask & FILE_APPEND_DATA)) {
3596 if (!posix_open && !CAN_WRITE(conn)) {
3598 * We should really return a permission denied error if either
3599 * O_CREAT or O_TRUNC are set, but for compatibility with
3600 * older versions of Samba we just AND them out.
3602 flags2 &= ~(O_CREAT|O_TRUNC);
3606 * With kernel oplocks the open breaking an oplock
3607 * blocks until the oplock holder has given up the
3608 * oplock or closed the file. We prevent this by always
3609 * trying to open the file with O_NONBLOCK (see "man
3612 * If a process that doesn't use the smbd open files
3613 * database or communication methods holds a kernel
3614 * oplock we must periodically poll for available open
3617 flags2 |= O_NONBLOCK;
3620 * Ensure we can't write on a read-only share or file.
3623 if (flags != O_RDONLY && file_existed &&
3624 (!CAN_WRITE(conn) || IS_DOS_READONLY(existing_dos_attributes))) {
3625 DEBUG(5,("open_file_ntcreate: write access requested for "
3626 "file %s on read only %s\n",
3627 smb_fname_str_dbg(smb_fname),
3628 !CAN_WRITE(conn) ? "share" : "file" ));
3630 return NT_STATUS_ACCESS_DENIED;
3633 if (VALID_STAT(smb_fname->st)) {
3635 * Only try and create a file id before open
3636 * for an existing file. For a file being created
3637 * this won't do anything useful until the file
3638 * exists and has a valid stat struct.
3640 fsp->file_id = vfs_file_id_from_sbuf(conn, &smb_fname->st);
3642 fsp->fh->private_options = private_flags;
3643 fsp->access_mask = open_access_mask; /* We change this to the
3644 * requested access_mask after
3645 * the open is done. */
3647 fsp->posix_flags |= FSP_POSIX_FLAGS_ALL;
3650 if ((create_options & FILE_DELETE_ON_CLOSE) &&
3651 (flags2 & O_CREAT) &&
3653 /* Delete on close semantics for new files. */
3654 status = can_set_delete_on_close(fsp,
3655 new_dos_attributes);
3656 if (!NT_STATUS_IS_OK(status)) {
3663 * Ensure we pay attention to default ACLs on directories if required.
3666 if ((flags2 & O_CREAT) && lp_inherit_acls(SNUM(conn)) &&
3667 (def_acl = directory_has_default_acl(conn,
3671 unx_mode = (0777 & lp_create_mask(SNUM(conn)));
3674 DEBUG(4,("calling open_file with flags=0x%X flags2=0x%X mode=0%o, "
3675 "access_mask = 0x%x, open_access_mask = 0x%x\n",
3676 (unsigned int)flags, (unsigned int)flags2,
3677 (unsigned int)unx_mode, (unsigned int)access_mask,
3678 (unsigned int)open_access_mask));
3680 fsp_open = open_file(fsp, conn, req, parent_dir_fname,
3681 flags|flags2, unx_mode, access_mask,
3682 open_access_mask, &new_file_created);
3684 if (NT_STATUS_EQUAL(fsp_open, NT_STATUS_NETWORK_BUSY)) {
3685 if (file_existed && S_ISFIFO(fsp->fsp_name->st.st_ex_mode)) {
3686 DEBUG(10, ("FIFO busy\n"));
3687 return NT_STATUS_NETWORK_BUSY;
3690 DEBUG(10, ("Internal open busy\n"));
3691 return NT_STATUS_NETWORK_BUSY;
3694 * This handles the kernel oplock case:
3696 * the file has an active kernel oplock and the open() returned
3697 * EWOULDBLOCK/EAGAIN which maps to NETWORK_BUSY.
3699 * "Samba locking.tdb oplocks" are handled below after acquiring
3700 * the sharemode lock with get_share_mode_lock().
3705 if (NT_STATUS_EQUAL(fsp_open, NT_STATUS_RETRY)) {
3707 * EINTR from the open(2) syscall. Just setup a retry
3708 * in a bit. We can't use the sys_write() tight retry
3709 * loop here, as we might have to actually deal with
3710 * lease-break signals to avoid a deadlock.
3717 * From here on we assume this is an oplock break triggered
3720 lck = get_existing_share_mode_lock(talloc_tos(), fsp->file_id);
3722 if ((lck != NULL) && !validate_oplock_types(lck)) {
3723 smb_panic("validate_oplock_types failed");
3727 * Retry once a second. If there's a share_mode_lock
3728 * around, also wait for it in case it was smbd
3729 * holding that kernel oplock that can quickly tell us
3730 * the oplock got removed.
3737 timeval_set(OPLOCK_BREAK_TIMEOUT*2, 0),
3742 return NT_STATUS_SHARING_VIOLATION;
3745 if (!NT_STATUS_IS_OK(fsp_open)) {
3746 bool wait_for_aio = NT_STATUS_EQUAL(
3747 fsp_open, NT_STATUS_MORE_PROCESSING_REQUIRED);
3749 schedule_async_open(req);
3754 if (new_file_created) {
3756 * As we atomically create using O_CREAT|O_EXCL,
3757 * then if new_file_created is true, then
3758 * file_existed *MUST* have been false (even
3759 * if the file was previously detected as being
3762 file_existed = false;
3765 if (file_existed && !check_same_dev_ino(&saved_stat, &smb_fname->st)) {
3767 * The file did exist, but some other (local or NFS)
3768 * process either renamed/unlinked and re-created the
3769 * file with different dev/ino after we walked the path,
3770 * but before we did the open. We could retry the
3771 * open but it's a rare enough case it's easier to
3772 * just fail the open to prevent creating any problems
3773 * in the open file db having the wrong dev/ino key.
3776 DBG_WARNING("file %s - dev/ino mismatch. "
3777 "Old (dev=%ju, ino=%ju). "
3778 "New (dev=%ju, ino=%ju). Failing open "
3779 "with NT_STATUS_ACCESS_DENIED.\n",
3780 smb_fname_str_dbg(smb_fname),
3781 (uintmax_t)saved_stat.st_ex_dev,
3782 (uintmax_t)saved_stat.st_ex_ino,
3783 (uintmax_t)smb_fname->st.st_ex_dev,
3784 (uintmax_t)smb_fname->st.st_ex_ino);
3785 return NT_STATUS_ACCESS_DENIED;
3788 old_write_time = smb_fname->st.st_ex_mtime;
3791 * Deal with the race condition where two smbd's detect the
3792 * file doesn't exist and do the create at the same time. One
3793 * of them will win and set a share mode, the other (ie. this
3794 * one) should check if the requested share mode for this
3795 * create is allowed.
3799 * Now the file exists and fsp is successfully opened,
3800 * fsp->dev and fsp->inode are valid and should replace the
3801 * dev=0,inode=0 from a non existent file. Spotted by
3802 * Nadav Danieli <nadavd@exanet.com>. JRA.
3807 lck = get_share_mode_lock(talloc_tos(), id,
3809 smb_fname, &old_write_time);
3812 DEBUG(0, ("open_file_ntcreate: Could not get share "
3813 "mode lock for %s\n",
3814 smb_fname_str_dbg(smb_fname)));
3816 return NT_STATUS_SHARING_VIOLATION;
3819 /* Get the types we need to examine. */
3820 if (!validate_oplock_types(lck)) {
3821 smb_panic("validate_oplock_types failed");
3824 if (has_delete_on_close(lck, fsp->name_hash)) {
3827 return NT_STATUS_DELETE_PENDING;
3830 status = handle_share_mode_lease(
3838 first_open_attempt);
3840 if (NT_STATUS_EQUAL(status, NT_STATUS_RETRY)) {
3841 schedule_defer_open(lck, fsp->file_id, req);
3844 return NT_STATUS_SHARING_VIOLATION;
3847 if (!NT_STATUS_IS_OK(status)) {
3854 struct share_mode_data *d = lck->data;
3855 uint16_t new_flags = share_mode_flags_restrict(
3856 d->flags, access_mask, share_access, UINT32_MAX);
3858 if (new_flags != d->flags) {
3859 d->flags = new_flags;
3864 ok = set_share_mode(
3867 get_current_uid(fsp->conn),
3873 if (fsp->oplock_type == LEASE_OPLOCK) {
3874 status = remove_lease_if_stale(
3876 fsp_client_guid(fsp),
3877 &fsp->lease->lease.lease_key);
3878 if (!NT_STATUS_IS_OK(status)) {
3879 DBG_WARNING("remove_lease_if_stale "
3884 return NT_STATUS_NO_MEMORY;
3887 /* Should we atomically (to the client at least) truncate ? */
3888 if ((!new_file_created) &&
3889 (flags2 & O_TRUNC) &&
3890 (S_ISREG(fsp->fsp_name->st.st_ex_mode))) {
3893 ret = SMB_VFS_FTRUNCATE(fsp, 0);
3895 status = map_nt_error_from_unix(errno);
3896 del_share_mode(lck, fsp);
3901 notify_fname(fsp->conn, NOTIFY_ACTION_MODIFIED,
3902 FILE_NOTIFY_CHANGE_SIZE
3903 | FILE_NOTIFY_CHANGE_ATTRIBUTES,
3904 fsp->fsp_name->base_name);
3908 * We have the share entry *locked*.....
3911 /* Delete streams if create_disposition requires it */
3912 if (!new_file_created && clear_ads(create_disposition) &&
3913 !is_ntfs_stream_smb_fname(smb_fname)) {
3914 status = delete_all_streams(conn, smb_fname);
3915 if (!NT_STATUS_IS_OK(status)) {
3916 del_share_mode(lck, fsp);
3923 if (fsp->fh->fd != -1 && lp_kernel_share_modes(SNUM(conn))) {
3926 * Beware: streams implementing VFS modules may
3927 * implement streams in a way that fsp will have the
3928 * basefile open in the fsp fd, so lacking a distinct
3929 * fd for the stream kernel_flock will apply on the
3930 * basefile which is wrong. The actual check is
3931 * deferred to the VFS module implementing the
3932 * kernel_flock call.
3934 ret_flock = SMB_VFS_KERNEL_FLOCK(fsp, share_access, access_mask);
3935 if(ret_flock == -1 ){
3937 del_share_mode(lck, fsp);
3941 return NT_STATUS_SHARING_VIOLATION;
3944 fsp->fsp_flags.kernel_share_modes_taken = true;
3948 * At this point onwards, we can guarantee that the share entry
3949 * is locked, whether we created the file or not, and that the
3950 * deny mode is compatible with all current opens.
3954 * According to Samba4, SEC_FILE_READ_ATTRIBUTE is always granted,
3955 * but we don't have to store this - just ignore it on access check.
3957 if (conn->sconn->using_smb2) {
3959 * SMB2 doesn't return it (according to Microsoft tests).
3960 * Test Case: TestSuite_ScenarioNo009GrantedAccessTestS0
3961 * File created with access = 0x7 (Read, Write, Delete)
3962 * Query Info on file returns 0x87 (Read, Write, Delete, Read Attributes)
3964 fsp->access_mask = access_mask;
3966 /* But SMB1 does. */
3967 fsp->access_mask = access_mask | FILE_READ_ATTRIBUTES;
3970 if (new_file_created) {
3971 info = FILE_WAS_CREATED;
3973 if (flags2 & O_TRUNC) {
3974 info = FILE_WAS_OVERWRITTEN;
3976 info = FILE_WAS_OPENED;
3984 /* Handle strange delete on close create semantics. */
3985 if (create_options & FILE_DELETE_ON_CLOSE) {
3986 if (!new_file_created) {
3987 status = can_set_delete_on_close(fsp,
3988 existing_dos_attributes);
3990 if (!NT_STATUS_IS_OK(status)) {
3991 /* Remember to delete the mode we just added. */
3992 del_share_mode(lck, fsp);
3998 /* Note that here we set the *initial* delete on close flag,
3999 not the regular one. The magic gets handled in close. */
4000 fsp->fsp_flags.initial_delete_on_close = true;
4004 * If we created a file and it's not a stream, this is the point where
4005 * we set the itime (aka invented time) that get's stored in the DOS
4006 * attribute xattr. The value is going to be either what the filesystem
4007 * provided or a copy of the creation date.
4009 * Either way, we turn the itime into a File-ID, unless the filesystem
4010 * provided one (unlikely).
4012 if (info == FILE_WAS_CREATED && !is_named_stream(smb_fname)) {
4013 smb_fname->st.st_ex_iflags &= ~ST_EX_IFLAG_CALCULATED_ITIME;
4015 if (lp_store_dos_attributes(SNUM(conn)) &&
4016 smb_fname->st.st_ex_iflags & ST_EX_IFLAG_CALCULATED_FILE_ID)
4020 file_id = make_file_id_from_itime(&smb_fname->st);
4021 update_stat_ex_file_id(&smb_fname->st, file_id);
4025 if (info != FILE_WAS_OPENED) {
4026 /* Overwritten files should be initially set as archive */
4027 if ((info == FILE_WAS_OVERWRITTEN && lp_map_archive(SNUM(conn))) ||
4028 lp_store_dos_attributes(SNUM(conn))) {
4029 (void)dos_mode(conn, smb_fname);
4031 if (file_set_dosmode(conn, smb_fname,
4032 new_dos_attributes | FILE_ATTRIBUTE_ARCHIVE,
4033 parent_dir_fname, true) == 0) {
4034 unx_mode = smb_fname->st.st_ex_mode;
4040 /* Determine sparse flag. */
4042 /* POSIX opens are sparse by default. */
4043 fsp->fsp_flags.is_sparse = true;
4045 fsp->fsp_flags.is_sparse =
4046 (existing_dos_attributes & FILE_ATTRIBUTE_SPARSE);
4050 * Take care of inherited ACLs on created files - if default ACL not
4054 if (!posix_open && new_file_created && !def_acl) {
4055 if (unx_mode != smb_fname->st.st_ex_mode) {
4056 int ret = SMB_VFS_FCHMOD(fsp, unx_mode);
4058 DBG_INFO("failed to reset "
4059 "attributes of file %s to 0%o\n",
4060 smb_fname_str_dbg(smb_fname),
4061 (unsigned int)unx_mode);
4065 } else if (new_unx_mode) {
4067 * We only get here in the case of:
4069 * a). Not a POSIX open.
4070 * b). File already existed.
4071 * c). File was overwritten.
4072 * d). Requested DOS attributes didn't match
4073 * the DOS attributes on the existing file.
4075 * In that case new_unx_mode has been set
4076 * equal to the calculated mode (including
4077 * possible inheritance of the mode from the
4078 * containing directory).
4080 * Note this mode was calculated with the
4081 * DOS attribute FILE_ATTRIBUTE_ARCHIVE added,
4082 * so the mode change here is suitable for
4083 * an overwritten file.
4086 if (new_unx_mode != smb_fname->st.st_ex_mode) {
4087 int ret = SMB_VFS_FCHMOD(fsp, new_unx_mode);
4089 DBG_INFO("failed to reset "
4090 "attributes of file %s to 0%o\n",
4091 smb_fname_str_dbg(smb_fname),
4092 (unsigned int)new_unx_mode);
4099 * Deal with other opens having a modified write time.
4101 struct timespec write_time = get_share_mode_write_time(lck);
4103 if (!is_omit_timespec(&write_time)) {
4104 update_stat_ex_mtime(&fsp->fsp_name->st, write_time);
4110 return NT_STATUS_OK;
4113 static NTSTATUS mkdir_internal(connection_struct *conn,
4114 struct smb_filename *smb_dname,
4115 uint32_t file_attributes)
4117 const struct loadparm_substitution *lp_sub =
4118 loadparm_s3_global_substitution();
4120 struct smb_filename *parent_dir_fname = NULL;
4122 bool posix_open = false;
4123 bool need_re_stat = false;
4124 uint32_t access_mask = SEC_DIR_ADD_SUBDIR;
4128 if (!CAN_WRITE(conn) || (access_mask & ~(conn->share_access))) {
4129 DEBUG(5,("mkdir_internal: failing share access "
4130 "%s\n", lp_servicename(talloc_tos(), lp_sub, SNUM(conn))));
4131 return NT_STATUS_ACCESS_DENIED;
4134 ok = parent_smb_fname(talloc_tos(),
4139 return NT_STATUS_NO_MEMORY;
4142 if (file_attributes & FILE_FLAG_POSIX_SEMANTICS) {
4144 mode = (mode_t)(file_attributes & ~FILE_FLAG_POSIX_SEMANTICS);
4146 mode = unix_mode(conn,
4147 FILE_ATTRIBUTE_DIRECTORY,
4152 status = check_parent_access(conn,
4156 if(!NT_STATUS_IS_OK(status)) {
4157 DEBUG(5,("mkdir_internal: check_parent_access "
4158 "on directory %s for path %s returned %s\n",
4159 smb_fname_str_dbg(parent_dir_fname),
4160 smb_dname->base_name,
4161 nt_errstr(status) ));
4165 ret = SMB_VFS_MKDIRAT(conn,
4170 return map_nt_error_from_unix(errno);
4173 /* Ensure we're checking for a symlink here.... */
4174 /* We don't want to get caught by a symlink racer. */
4176 if (SMB_VFS_LSTAT(conn, smb_dname) == -1) {
4177 DEBUG(2, ("Could not stat directory '%s' just created: %s\n",
4178 smb_fname_str_dbg(smb_dname), strerror(errno)));
4179 return map_nt_error_from_unix(errno);
4182 if (!S_ISDIR(smb_dname->st.st_ex_mode)) {
4183 DEBUG(0, ("Directory '%s' just created is not a directory !\n",
4184 smb_fname_str_dbg(smb_dname)));
4185 return NT_STATUS_NOT_A_DIRECTORY;
4188 smb_dname->st.st_ex_iflags &= ~ST_EX_IFLAG_CALCULATED_ITIME;
4190 if (lp_store_dos_attributes(SNUM(conn))) {
4191 if (smb_dname->st.st_ex_iflags & ST_EX_IFLAG_CALCULATED_FILE_ID)
4195 file_id = make_file_id_from_itime(&smb_dname->st);
4196 update_stat_ex_file_id(&smb_dname->st, file_id);
4200 file_set_dosmode(conn, smb_dname,
4201 file_attributes | FILE_ATTRIBUTE_DIRECTORY,
4202 parent_dir_fname, true);
4206 if (lp_inherit_permissions(SNUM(conn))) {
4207 inherit_access_posix_acl(conn, parent_dir_fname,
4209 need_re_stat = true;
4214 * Check if high bits should have been set,
4215 * then (if bits are missing): add them.
4216 * Consider bits automagically set by UNIX, i.e. SGID bit from parent
4219 if ((mode & ~(S_IRWXU|S_IRWXG|S_IRWXO)) &&
4220 (mode & ~smb_dname->st.st_ex_mode)) {
4221 SMB_VFS_CHMOD(conn, smb_dname,
4222 (smb_dname->st.st_ex_mode |
4223 (mode & ~smb_dname->st.st_ex_mode)));
4224 need_re_stat = true;
4228 /* Change the owner if required. */
4229 if (lp_inherit_owner(SNUM(conn)) != INHERIT_OWNER_NO) {
4230 change_dir_owner_to_parent(conn, parent_dir_fname,
4233 need_re_stat = true;
4237 if (SMB_VFS_LSTAT(conn, smb_dname) == -1) {
4238 DEBUG(2, ("Could not stat directory '%s' just created: %s\n",
4239 smb_fname_str_dbg(smb_dname), strerror(errno)));
4240 return map_nt_error_from_unix(errno);
4244 notify_fname(conn, NOTIFY_ACTION_ADDED, FILE_NOTIFY_CHANGE_DIR_NAME,
4245 smb_dname->base_name);
4247 return NT_STATUS_OK;
4250 /****************************************************************************
4251 Open a directory from an NT SMB call.
4252 ****************************************************************************/
4254 static NTSTATUS open_directory(connection_struct *conn,
4255 struct smb_request *req,
4256 struct files_struct **dirfsp,
4257 struct smb_filename *smb_dname,
4258 uint32_t access_mask,
4259 uint32_t share_access,
4260 uint32_t create_disposition,
4261 uint32_t create_options,
4262 uint32_t file_attributes,
4264 files_struct **result)
4266 files_struct *fsp = NULL;
4267 bool dir_existed = VALID_STAT(smb_dname->st);
4268 struct share_mode_lock *lck = NULL;
4270 struct timespec mtimespec;
4275 SMB_ASSERT(*dirfsp == conn->cwd_fsp);
4277 if (is_ntfs_stream_smb_fname(smb_dname)) {
4278 DEBUG(2, ("open_directory: %s is a stream name!\n",
4279 smb_fname_str_dbg(smb_dname)));
4280 return NT_STATUS_NOT_A_DIRECTORY;
4283 if (!(file_attributes & FILE_FLAG_POSIX_SEMANTICS)) {
4284 /* Ensure we have a directory attribute. */
4285 file_attributes |= FILE_ATTRIBUTE_DIRECTORY;
4288 DBG_INFO("opening directory %s, access_mask = 0x%"PRIx32", "
4289 "share_access = 0x%"PRIx32" create_options = 0x%"PRIx32", "
4290 "create_disposition = 0x%"PRIx32", "
4291 "file_attributes = 0x%"PRIx32"\n",
4292 smb_fname_str_dbg(smb_dname),
4299 status = smbd_calculate_access_mask(conn,
4305 if (!NT_STATUS_IS_OK(status)) {
4306 DEBUG(10, ("open_directory: smbd_calculate_access_mask "
4307 "on file %s returned %s\n",
4308 smb_fname_str_dbg(smb_dname),
4309 nt_errstr(status)));
4313 if ((access_mask & SEC_FLAG_SYSTEM_SECURITY) &&
4314 !security_token_has_privilege(get_current_nttok(conn),
4315 SEC_PRIV_SECURITY)) {
4316 DEBUG(10, ("open_directory: open on %s "
4317 "failed - SEC_FLAG_SYSTEM_SECURITY denied.\n",
4318 smb_fname_str_dbg(smb_dname)));
4319 return NT_STATUS_PRIVILEGE_NOT_HELD;
4322 switch( create_disposition ) {
4326 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
4329 info = FILE_WAS_OPENED;
4334 /* If directory exists error. If directory doesn't
4338 status = NT_STATUS_OBJECT_NAME_COLLISION;
4339 DEBUG(2, ("open_directory: unable to create "
4340 "%s. Error was %s\n",
4341 smb_fname_str_dbg(smb_dname),
4342 nt_errstr(status)));
4346 status = mkdir_internal(conn, smb_dname,
4349 if (!NT_STATUS_IS_OK(status)) {
4350 DEBUG(2, ("open_directory: unable to create "
4351 "%s. Error was %s\n",
4352 smb_fname_str_dbg(smb_dname),
4353 nt_errstr(status)));
4357 info = FILE_WAS_CREATED;
4362 * If directory exists open. If directory doesn't
4367 status = NT_STATUS_OK;
4368 info = FILE_WAS_OPENED;
4370 status = mkdir_internal(conn, smb_dname,
4373 if (NT_STATUS_IS_OK(status)) {
4374 info = FILE_WAS_CREATED;
4376 /* Cope with create race. */
4377 if (!NT_STATUS_EQUAL(status,
4378 NT_STATUS_OBJECT_NAME_COLLISION)) {
4379 DEBUG(2, ("open_directory: unable to create "
4380 "%s. Error was %s\n",
4381 smb_fname_str_dbg(smb_dname),
4382 nt_errstr(status)));
4387 * If mkdir_internal() returned
4388 * NT_STATUS_OBJECT_NAME_COLLISION
4389 * we still must lstat the path.
4392 if (SMB_VFS_LSTAT(conn, smb_dname)
4394 DEBUG(2, ("Could not stat "
4395 "directory '%s' just "
4400 return map_nt_error_from_unix(
4404 info = FILE_WAS_OPENED;
4410 case FILE_SUPERSEDE:
4411 case FILE_OVERWRITE:
4412 case FILE_OVERWRITE_IF:
4414 DEBUG(5,("open_directory: invalid create_disposition "
4415 "0x%x for directory %s\n",
4416 (unsigned int)create_disposition,
4417 smb_fname_str_dbg(smb_dname)));
4418 return NT_STATUS_INVALID_PARAMETER;
4421 if(!S_ISDIR(smb_dname->st.st_ex_mode)) {
4422 DEBUG(5,("open_directory: %s is not a directory !\n",
4423 smb_fname_str_dbg(smb_dname)));
4424 return NT_STATUS_NOT_A_DIRECTORY;
4427 if (info == FILE_WAS_OPENED) {
4428 status = smbd_check_access_rights(conn,
4433 if (!NT_STATUS_IS_OK(status)) {
4434 DEBUG(10, ("open_directory: smbd_check_access_rights on "
4435 "file %s failed with %s\n",
4436 smb_fname_str_dbg(smb_dname),
4437 nt_errstr(status)));
4442 status = file_new(req, conn, &fsp);
4443 if(!NT_STATUS_IS_OK(status)) {
4448 * Setup the files_struct for it.
4451 fsp->file_id = vfs_file_id_from_sbuf(conn, &smb_dname->st);
4452 fsp->vuid = req ? req->vuid : UID_FIELD_INVALID;
4453 fsp->file_pid = req ? req->smbpid : 0;
4454 fsp->fsp_flags.can_lock = false;
4455 fsp->fsp_flags.can_read = false;
4456 fsp->fsp_flags.can_write = false;
4458 fsp->fh->private_options = 0;
4460 * According to Samba4, SEC_FILE_READ_ATTRIBUTE is always granted,
4462 fsp->access_mask = access_mask | FILE_READ_ATTRIBUTES;
4463 fsp->print_file = NULL;
4464 fsp->fsp_flags.modified = false;
4465 fsp->oplock_type = NO_OPLOCK;
4466 fsp->sent_oplock_break = NO_BREAK_SENT;
4467 fsp->fsp_flags.is_directory = true;
4468 if (file_attributes & FILE_FLAG_POSIX_SEMANTICS) {
4469 fsp->posix_flags |= FSP_POSIX_FLAGS_ALL;
4471 status = fsp_set_smb_fname(fsp, smb_dname);
4472 if (!NT_STATUS_IS_OK(status)) {
4473 file_free(req, fsp);
4477 /* Don't store old timestamps for directory
4478 handles in the internal database. We don't
4479 update them in there if new objects
4480 are created in the directory. Currently
4481 we only update timestamps on file writes.
4484 mtimespec = make_omit_timespec();
4486 /* POSIX allows us to open a directory with O_RDONLY. */
4489 flags |= O_DIRECTORY;
4492 status = fd_open(conn, fsp, flags, 0);
4493 if (!NT_STATUS_IS_OK(status)) {
4494 DBG_INFO("Could not open fd for "
4496 smb_fname_str_dbg(smb_dname),
4498 file_free(req, fsp);
4502 status = vfs_stat_fsp(fsp);
4503 if (!NT_STATUS_IS_OK(status)) {
4505 file_free(req, fsp);
4509 if(!S_ISDIR(fsp->fsp_name->st.st_ex_mode)) {
4510 DEBUG(5,("open_directory: %s is not a directory !\n",
4511 smb_fname_str_dbg(smb_dname)));
4513 file_free(req, fsp);
4514 return NT_STATUS_NOT_A_DIRECTORY;
4517 /* Ensure there was no race condition. We need to check
4518 * dev/inode but not permissions, as these can change
4520 if (!check_same_dev_ino(&smb_dname->st, &fsp->fsp_name->st)) {
4521 DEBUG(5,("open_directory: stat struct differs for "
4523 smb_fname_str_dbg(smb_dname)));
4525 file_free(req, fsp);
4526 return NT_STATUS_ACCESS_DENIED;
4529 lck = get_share_mode_lock(talloc_tos(), fsp->file_id,
4530 conn->connectpath, smb_dname,
4534 DEBUG(0, ("open_directory: Could not get share mode lock for "
4535 "%s\n", smb_fname_str_dbg(smb_dname)));
4537 file_free(req, fsp);
4538 return NT_STATUS_SHARING_VIOLATION;
4541 if (has_delete_on_close(lck, fsp->name_hash)) {
4544 file_free(req, fsp);
4545 return NT_STATUS_DELETE_PENDING;
4548 status = open_mode_check(conn, lck,
4549 access_mask, share_access);
4551 if (!NT_STATUS_IS_OK(status)) {
4554 file_free(req, fsp);
4559 struct share_mode_data *d = lck->data;
4560 uint16_t new_flags = share_mode_flags_restrict(
4561 d->flags, access_mask, share_access, UINT32_MAX);
4563 if (new_flags != d->flags) {
4564 d->flags = new_flags;
4569 ok = set_share_mode(
4572 get_current_uid(conn),
4580 file_free(req, fsp);
4581 return NT_STATUS_NO_MEMORY;
4584 /* For directories the delete on close bit at open time seems
4585 always to be honored on close... See test 19 in Samba4 BASE-DELETE. */
4586 if (create_options & FILE_DELETE_ON_CLOSE) {
4587 status = can_set_delete_on_close(fsp, 0);
4588 if (!NT_STATUS_IS_OK(status) && !NT_STATUS_EQUAL(status, NT_STATUS_DIRECTORY_NOT_EMPTY)) {
4589 del_share_mode(lck, fsp);
4592 file_free(req, fsp);
4596 if (NT_STATUS_IS_OK(status)) {
4597 /* Note that here we set the *initial* delete on close flag,
4598 not the regular one. The magic gets handled in close. */
4599 fsp->fsp_flags.initial_delete_on_close = true;
4605 * Deal with other opens having a modified write time. Is this
4606 * possible for directories?
4608 struct timespec write_time = get_share_mode_write_time(lck);
4610 if (!is_omit_timespec(&write_time)) {
4611 update_stat_ex_mtime(&fsp->fsp_name->st, write_time);
4622 return NT_STATUS_OK;
4625 NTSTATUS create_directory(connection_struct *conn, struct smb_request *req,
4626 struct smb_filename *smb_dname)
4631 status = SMB_VFS_CREATE_FILE(
4634 &conn->cwd_fsp, /* dirfsp */
4635 smb_dname, /* fname */
4636 FILE_READ_ATTRIBUTES, /* access_mask */
4637 FILE_SHARE_NONE, /* share_access */
4638 FILE_CREATE, /* create_disposition*/
4639 FILE_DIRECTORY_FILE, /* create_options */
4640 FILE_ATTRIBUTE_DIRECTORY, /* file_attributes */
4641 0, /* oplock_request */
4643 0, /* allocation_size */
4644 0, /* private_flags */
4649 NULL, NULL); /* create context */
4651 if (NT_STATUS_IS_OK(status)) {
4652 close_file(req, fsp, NORMAL_CLOSE);
4658 /****************************************************************************
4659 Receive notification that one of our open files has been renamed by another
4661 ****************************************************************************/
4663 void msg_file_was_renamed(struct messaging_context *msg_ctx,
4666 struct server_id src,
4669 struct file_rename_message *msg = NULL;
4670 enum ndr_err_code ndr_err;
4672 struct smb_filename *smb_fname = NULL;
4673 struct smbd_server_connection *sconn =
4674 talloc_get_type_abort(private_data,
4675 struct smbd_server_connection);
4677 msg = talloc(talloc_tos(), struct file_rename_message);
4679 DBG_WARNING("talloc failed\n");
4683 ndr_err = ndr_pull_struct_blob_all(
4687 (ndr_pull_flags_fn_t)ndr_pull_file_rename_message);
4688 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
4689 DBG_DEBUG("ndr_pull_oplock_break_message failed: %s\n",
4690 ndr_errstr(ndr_err));
4693 if (DEBUGLEVEL >= 10) {
4694 struct server_id_buf buf;
4695 DBG_DEBUG("Got rename message from %s\n",
4696 server_id_str_buf(src, &buf));
4697 NDR_PRINT_DEBUG(file_rename_message, msg);
4700 /* stream_name must always be NULL if there is no stream. */
4701 if ((msg->stream_name != NULL) && (msg->stream_name[0] == '\0')) {
4702 msg->stream_name = NULL;
4705 smb_fname = synthetic_smb_fname(msg,
4711 if (smb_fname == NULL) {
4712 DBG_DEBUG("synthetic_smb_fname failed\n");
4716 fsp = file_find_dif(sconn, msg->id, msg->share_file_id);
4718 DBG_DEBUG("fsp not found\n");
4722 if (strcmp(fsp->conn->connectpath, msg->servicepath) == 0) {
4724 DBG_DEBUG("renaming file %s from %s -> %s\n",
4727 smb_fname_str_dbg(smb_fname));
4728 status = fsp_set_smb_fname(fsp, smb_fname);
4729 if (!NT_STATUS_IS_OK(status)) {
4730 DBG_DEBUG("fsp_set_smb_fname failed: %s\n",
4736 * Now we have the complete path we can work out if
4737 * this is actually within this share and adjust
4738 * newname accordingly.
4740 DBG_DEBUG("share mismatch (sharepath %s not sharepath %s) "
4741 "%s from %s -> %s\n",
4742 fsp->conn->connectpath,
4746 smb_fname_str_dbg(smb_fname));
4753 * If a main file is opened for delete, all streams need to be checked for
4754 * !FILE_SHARE_DELETE. Do this by opening with DELETE_ACCESS.
4755 * If that works, delete them all by setting the delete on close and close.
4758 static NTSTATUS open_streams_for_delete(connection_struct *conn,
4759 const struct smb_filename *smb_fname)
4761 struct stream_struct *stream_info = NULL;
4762 files_struct **streams = NULL;
4764 unsigned int i, num_streams = 0;
4765 TALLOC_CTX *frame = talloc_stackframe();
4768 status = vfs_streaminfo(conn, NULL, smb_fname, talloc_tos(),
4769 &num_streams, &stream_info);
4771 if (NT_STATUS_EQUAL(status, NT_STATUS_NOT_IMPLEMENTED)
4772 || NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
4773 DEBUG(10, ("no streams around\n"));
4775 return NT_STATUS_OK;
4778 if (!NT_STATUS_IS_OK(status)) {
4779 DEBUG(10, ("vfs_streaminfo failed: %s\n",
4780 nt_errstr(status)));
4784 DEBUG(10, ("open_streams_for_delete found %d streams\n",
4787 if (num_streams == 0) {
4789 return NT_STATUS_OK;
4792 streams = talloc_array(talloc_tos(), files_struct *, num_streams);
4793 if (streams == NULL) {
4794 DEBUG(0, ("talloc failed\n"));
4795 status = NT_STATUS_NO_MEMORY;
4799 for (i=0; i<num_streams; i++) {
4800 struct smb_filename *smb_fname_cp;
4802 if (strequal(stream_info[i].name, "::$DATA")) {
4807 smb_fname_cp = synthetic_smb_fname(talloc_tos(),
4808 smb_fname->base_name,
4809 stream_info[i].name,
4813 ~SMB_FILENAME_POSIX_PATH));
4814 if (smb_fname_cp == NULL) {
4815 status = NT_STATUS_NO_MEMORY;
4819 if (SMB_VFS_STAT(conn, smb_fname_cp) == -1) {
4820 DEBUG(10, ("Unable to stat stream: %s\n",
4821 smb_fname_str_dbg(smb_fname_cp)));
4824 status = SMB_VFS_CREATE_FILE(
4827 &conn->cwd_fsp, /* dirfsp */
4828 smb_fname_cp, /* fname */
4829 DELETE_ACCESS, /* access_mask */
4830 (FILE_SHARE_READ | /* share_access */
4831 FILE_SHARE_WRITE | FILE_SHARE_DELETE),
4832 FILE_OPEN, /* create_disposition*/
4833 0, /* create_options */
4834 FILE_ATTRIBUTE_NORMAL, /* file_attributes */
4835 0, /* oplock_request */
4837 0, /* allocation_size */
4838 NTCREATEX_OPTIONS_PRIVATE_STREAM_DELETE, /* private_flags */
4841 &streams[i], /* result */
4843 NULL, NULL); /* create context */
4845 if (!NT_STATUS_IS_OK(status)) {
4846 DEBUG(10, ("Could not open stream %s: %s\n",
4847 smb_fname_str_dbg(smb_fname_cp),
4848 nt_errstr(status)));
4850 TALLOC_FREE(smb_fname_cp);
4853 TALLOC_FREE(smb_fname_cp);
4857 * don't touch the variable "status" beyond this point :-)
4860 for (j = i-1 ; j >= 0; j--) {
4861 if (streams[j] == NULL) {
4865 DEBUG(10, ("Closing stream # %d, %s\n", j,
4866 fsp_str_dbg(streams[j])));
4867 close_file(NULL, streams[j], NORMAL_CLOSE);
4875 /*********************************************************************
4876 Create a default ACL by inheriting from the parent. If no inheritance
4877 from the parent available, don't set anything. This will leave the actual
4878 permissions the new file or directory already got from the filesystem
4879 as the NT ACL when read.
4880 *********************************************************************/
4882 static NTSTATUS inherit_new_acl(files_struct *fsp)
4884 TALLOC_CTX *frame = talloc_stackframe();
4885 struct security_descriptor *parent_desc = NULL;
4886 NTSTATUS status = NT_STATUS_OK;
4887 struct security_descriptor *psd = NULL;
4888 const struct dom_sid *owner_sid = NULL;
4889 const struct dom_sid *group_sid = NULL;
4890 uint32_t security_info_sent = (SECINFO_OWNER | SECINFO_GROUP | SECINFO_DACL);
4891 struct security_token *token = fsp->conn->session_info->security_token;
4892 bool inherit_owner =
4893 (lp_inherit_owner(SNUM(fsp->conn)) == INHERIT_OWNER_WINDOWS_AND_UNIX);
4894 bool inheritable_components = false;
4895 bool try_builtin_administrators = false;
4896 const struct dom_sid *BA_U_sid = NULL;
4897 const struct dom_sid *BA_G_sid = NULL;
4898 bool try_system = false;
4899 const struct dom_sid *SY_U_sid = NULL;
4900 const struct dom_sid *SY_G_sid = NULL;
4902 struct smb_filename *parent_dir = NULL;
4905 ok = parent_smb_fname(frame,
4911 return NT_STATUS_NO_MEMORY;
4914 status = SMB_VFS_GET_NT_ACL_AT(fsp->conn,
4917 (SECINFO_OWNER | SECINFO_GROUP | SECINFO_DACL),
4920 if (!NT_STATUS_IS_OK(status)) {
4925 inheritable_components = sd_has_inheritable_components(parent_desc,
4926 fsp->fsp_flags.is_directory);
4928 if (!inheritable_components && !inherit_owner) {
4930 /* Nothing to inherit and not setting owner. */
4931 return NT_STATUS_OK;
4934 /* Create an inherited descriptor from the parent. */
4936 if (DEBUGLEVEL >= 10) {
4937 DEBUG(10,("inherit_new_acl: parent acl for %s is:\n",
4938 fsp_str_dbg(fsp) ));
4939 NDR_PRINT_DEBUG(security_descriptor, parent_desc);
4942 /* Inherit from parent descriptor if "inherit owner" set. */
4943 if (inherit_owner) {
4944 owner_sid = parent_desc->owner_sid;
4945 group_sid = parent_desc->group_sid;
4948 if (owner_sid == NULL) {
4949 if (security_token_has_builtin_administrators(token)) {
4950 try_builtin_administrators = true;
4951 } else if (security_token_is_system(token)) {
4952 try_builtin_administrators = true;
4957 if (group_sid == NULL &&
4958 token->num_sids == PRIMARY_GROUP_SID_INDEX)
4960 if (security_token_is_system(token)) {
4961 try_builtin_administrators = true;
4966 if (try_builtin_administrators) {
4970 ok = sids_to_unixids(&global_sid_Builtin_Administrators, 1, &ids);
4974 BA_U_sid = &global_sid_Builtin_Administrators;
4975 BA_G_sid = &global_sid_Builtin_Administrators;
4978 BA_U_sid = &global_sid_Builtin_Administrators;
4981 BA_G_sid = &global_sid_Builtin_Administrators;
4993 ok = sids_to_unixids(&global_sid_System, 1, &ids);
4997 SY_U_sid = &global_sid_System;
4998 SY_G_sid = &global_sid_System;
5001 SY_U_sid = &global_sid_System;
5004 SY_G_sid = &global_sid_System;
5012 if (owner_sid == NULL) {
5013 owner_sid = BA_U_sid;
5016 if (owner_sid == NULL) {
5017 owner_sid = SY_U_sid;
5020 if (group_sid == NULL) {
5021 group_sid = SY_G_sid;
5024 if (try_system && group_sid == NULL) {
5025 group_sid = BA_G_sid;
5028 if (owner_sid == NULL) {
5029 owner_sid = &token->sids[PRIMARY_USER_SID_INDEX];
5031 if (group_sid == NULL) {
5032 if (token->num_sids == PRIMARY_GROUP_SID_INDEX) {
5033 group_sid = &token->sids[PRIMARY_USER_SID_INDEX];
5035 group_sid = &token->sids[PRIMARY_GROUP_SID_INDEX];
5039 status = se_create_child_secdesc(frame,
5045 fsp->fsp_flags.is_directory);
5046 if (!NT_STATUS_IS_OK(status)) {
5051 /* If inheritable_components == false,
5052 se_create_child_secdesc()
5053 creates a security descriptor with a NULL dacl
5054 entry, but with SEC_DESC_DACL_PRESENT. We need
5055 to remove that flag. */
5057 if (!inheritable_components) {
5058 security_info_sent &= ~SECINFO_DACL;
5059 psd->type &= ~SEC_DESC_DACL_PRESENT;
5062 if (DEBUGLEVEL >= 10) {
5063 DEBUG(10,("inherit_new_acl: child acl for %s is:\n",
5064 fsp_str_dbg(fsp) ));
5065 NDR_PRINT_DEBUG(security_descriptor, psd);
5068 if (inherit_owner) {
5069 /* We need to be root to force this. */
5072 status = SMB_VFS_FSET_NT_ACL(fsp,
5075 if (inherit_owner) {
5083 * If we already have a lease, it must match the new file id. [MS-SMB2]
5084 * 3.3.5.9.8 speaks about INVALID_PARAMETER if an already used lease key is
5085 * used for a different file name.
5088 struct lease_match_state {
5089 /* Input parameters. */
5090 TALLOC_CTX *mem_ctx;
5091 const char *servicepath;
5092 const struct smb_filename *fname;
5095 /* Return parameters. */
5096 uint32_t num_file_ids;
5097 struct file_id *ids;
5098 NTSTATUS match_status;
5101 /*************************************************************
5102 File doesn't exist but this lease key+guid is already in use.
5104 This is only allowable in the dynamic share case where the
5105 service path must be different.
5107 There is a small race condition here in the multi-connection
5108 case where a client sends two create calls on different connections,
5109 where the file doesn't exist and one smbd creates the leases_db
5110 entry first, but this will get fixed by the multichannel cleanup
5111 when all identical client_guids get handled by a single smbd.
5112 **************************************************************/
5114 static void lease_match_parser_new_file(
5116 const struct leases_db_file *files,
5117 struct lease_match_state *state)
5121 for (i = 0; i < num_files; i++) {
5122 const struct leases_db_file *f = &files[i];
5123 if (strequal(state->servicepath, f->servicepath)) {
5124 state->match_status = NT_STATUS_INVALID_PARAMETER;
5129 /* Dynamic share case. Break leases on all other files. */
5130 state->match_status = leases_db_copy_file_ids(state->mem_ctx,
5134 if (!NT_STATUS_IS_OK(state->match_status)) {
5138 state->num_file_ids = num_files;
5139 state->match_status = NT_STATUS_OPLOCK_NOT_GRANTED;
5143 static void lease_match_parser(
5145 const struct leases_db_file *files,
5148 struct lease_match_state *state =
5149 (struct lease_match_state *)private_data;
5152 if (!state->file_existed) {
5154 * Deal with name mismatch or
5155 * possible dynamic share case separately
5156 * to make code clearer.
5158 lease_match_parser_new_file(num_files,
5165 state->match_status = NT_STATUS_OK;
5167 for (i = 0; i < num_files; i++) {
5168 const struct leases_db_file *f = &files[i];
5170 /* Everything should be the same. */
5171 if (!file_id_equal(&state->id, &f->id)) {
5172 /* This should catch all dynamic share cases. */
5173 state->match_status = NT_STATUS_OPLOCK_NOT_GRANTED;
5176 if (!strequal(f->servicepath, state->servicepath)) {
5177 state->match_status = NT_STATUS_INVALID_PARAMETER;
5180 if (!strequal(f->base_name, state->fname->base_name)) {
5181 state->match_status = NT_STATUS_INVALID_PARAMETER;
5184 if (!strequal(f->stream_name, state->fname->stream_name)) {
5185 state->match_status = NT_STATUS_INVALID_PARAMETER;
5190 if (NT_STATUS_IS_OK(state->match_status)) {
5192 * Common case - just opening another handle on a
5193 * file on a non-dynamic share.
5198 if (NT_STATUS_EQUAL(state->match_status, NT_STATUS_INVALID_PARAMETER)) {
5199 /* Mismatched path. Error back to client. */
5204 * File id mismatch. Dynamic share case NT_STATUS_OPLOCK_NOT_GRANTED.
5205 * Don't allow leases.
5208 state->match_status = leases_db_copy_file_ids(state->mem_ctx,
5212 if (!NT_STATUS_IS_OK(state->match_status)) {
5216 state->num_file_ids = num_files;
5217 state->match_status = NT_STATUS_OPLOCK_NOT_GRANTED;
5221 struct lease_match_break_state {
5222 struct messaging_context *msg_ctx;
5223 const struct smb2_lease_key *lease_key;
5231 static bool lease_match_break_fn(
5232 struct share_mode_entry *e,
5235 struct lease_match_break_state *state = private_data;
5237 uint32_t e_lease_type;
5240 stale = share_entry_stale_pid(e);
5245 equal = smb2_lease_key_equal(&e->lease_key, state->lease_key);
5250 status = leases_db_get(
5254 NULL, /* current_state */
5255 NULL, /* breaking */
5256 NULL, /* breaking_to_requested */
5257 NULL, /* breaking_to_required */
5258 &state->version, /* lease_version */
5259 &state->epoch); /* epoch */
5260 if (NT_STATUS_IS_OK(status)) {
5261 state->found_lease = true;
5263 DBG_WARNING("Could not find version/epoch: %s\n",
5267 e_lease_type = get_lease_type(e, state->id);
5268 if (e_lease_type == SMB2_LEASE_NONE) {
5271 send_break_message(state->msg_ctx, &state->id, e, SMB2_LEASE_NONE);
5274 * Windows 7 and 8 lease clients are broken in that they will
5275 * not respond to lease break requests whilst waiting for an
5276 * outstanding open request on that lease handle on the same
5277 * TCP connection, due to holding an internal inode lock.
5279 * This means we can't reschedule ourselves here, but must
5280 * return from the create.
5284 * Send the breaks and then return SMB2_LEASE_NONE in the
5285 * lease handle to cause them to acknowledge the lease
5286 * break. Consultation with Microsoft engineering confirmed
5287 * this approach is safe.
5293 static NTSTATUS lease_match(connection_struct *conn,
5294 struct smb_request *req,
5295 const struct smb2_lease_key *lease_key,
5296 const char *servicepath,
5297 const struct smb_filename *fname,
5298 uint16_t *p_version,
5301 struct smbd_server_connection *sconn = req->sconn;
5302 TALLOC_CTX *tos = talloc_tos();
5303 struct lease_match_state state = {
5305 .servicepath = servicepath,
5307 .match_status = NT_STATUS_OK
5312 state.file_existed = VALID_STAT(fname->st);
5313 if (state.file_existed) {
5314 state.id = vfs_file_id_from_sbuf(conn, &fname->st);
5317 status = leases_db_parse(&sconn->client->connections->smb2.client.guid,
5318 lease_key, lease_match_parser, &state);
5319 if (!NT_STATUS_IS_OK(status)) {
5321 * Not found or error means okay: We can make the lease pass
5323 return NT_STATUS_OK;
5325 if (!NT_STATUS_EQUAL(state.match_status, NT_STATUS_OPLOCK_NOT_GRANTED)) {
5327 * Anything but NT_STATUS_OPLOCK_NOT_GRANTED, let the caller
5330 return state.match_status;
5333 /* We have to break all existing leases. */
5334 for (i = 0; i < state.num_file_ids; i++) {
5335 struct lease_match_break_state break_state = {
5336 .msg_ctx = conn->sconn->msg_ctx,
5337 .lease_key = lease_key,
5339 struct share_mode_lock *lck;
5342 if (file_id_equal(&state.ids[i], &state.id)) {
5343 /* Don't need to break our own file. */
5347 break_state.id = state.ids[i];
5349 lck = get_existing_share_mode_lock(
5350 talloc_tos(), break_state.id);
5352 /* Race condition - file already closed. */
5356 ok = share_mode_forall_leases(
5357 lck, lease_match_break_fn, &break_state);
5359 DBG_DEBUG("share_mode_forall_leases failed\n");
5365 if (break_state.found_lease) {
5366 *p_version = break_state.version;
5367 *p_epoch = break_state.epoch;
5371 * Ensure we don't grant anything more so we
5374 return NT_STATUS_OPLOCK_NOT_GRANTED;
5378 * Wrapper around open_file_ntcreate and open_directory
5381 static NTSTATUS create_file_unixpath(connection_struct *conn,
5382 struct smb_request *req,
5383 struct files_struct **dirfsp,
5384 struct smb_filename *smb_fname,
5385 uint32_t access_mask,
5386 uint32_t share_access,
5387 uint32_t create_disposition,
5388 uint32_t create_options,
5389 uint32_t file_attributes,
5390 uint32_t oplock_request,
5391 const struct smb2_lease *lease,
5392 uint64_t allocation_size,
5393 uint32_t private_flags,
5394 struct security_descriptor *sd,
5395 struct ea_list *ea_list,
5397 files_struct **result,
5400 struct smb2_lease none_lease;
5401 int info = FILE_WAS_OPENED;
5402 files_struct *base_fsp = NULL;
5403 files_struct *fsp = NULL;
5406 SMB_ASSERT(*dirfsp == conn->cwd_fsp);
5408 DBG_DEBUG("create_file_unixpath: access_mask = 0x%x "
5409 "file_attributes = 0x%x, share_access = 0x%x, "
5410 "create_disposition = 0x%x create_options = 0x%x "
5411 "oplock_request = 0x%x private_flags = 0x%x "
5412 "ea_list = %p, sd = %p, "
5414 (unsigned int)access_mask,
5415 (unsigned int)file_attributes,
5416 (unsigned int)share_access,
5417 (unsigned int)create_disposition,
5418 (unsigned int)create_options,
5419 (unsigned int)oplock_request,
5420 (unsigned int)private_flags,
5421 ea_list, sd, smb_fname_str_dbg(smb_fname));
5423 if (create_options & FILE_OPEN_BY_FILE_ID) {
5424 status = NT_STATUS_NOT_SUPPORTED;
5428 if (create_options & NTCREATEX_OPTIONS_INVALID_PARAM_MASK) {
5429 status = NT_STATUS_INVALID_PARAMETER;
5434 oplock_request |= INTERNAL_OPEN_ONLY;
5437 if (lease != NULL) {
5438 uint16_t epoch = lease->lease_epoch;
5439 uint16_t version = lease->lease_version;
5442 DBG_WARNING("Got lease on internal open\n");
5443 status = NT_STATUS_INTERNAL_ERROR;
5447 status = lease_match(conn,
5454 if (NT_STATUS_EQUAL(status, NT_STATUS_OPLOCK_NOT_GRANTED)) {
5455 /* Dynamic share file. No leases and update epoch... */
5456 none_lease = *lease;
5457 none_lease.lease_state = SMB2_LEASE_NONE;
5458 none_lease.lease_epoch = epoch;
5459 none_lease.lease_version = version;
5460 lease = &none_lease;
5461 } else if (!NT_STATUS_IS_OK(status)) {
5466 if ((conn->fs_capabilities & FILE_NAMED_STREAMS)
5467 && (access_mask & DELETE_ACCESS)
5468 && !is_ntfs_stream_smb_fname(smb_fname)) {
5470 * We can't open a file with DELETE access if any of the
5471 * streams is open without FILE_SHARE_DELETE
5473 status = open_streams_for_delete(conn, smb_fname);
5475 if (!NT_STATUS_IS_OK(status)) {
5480 if (access_mask & SEC_FLAG_SYSTEM_SECURITY) {
5483 ok = security_token_has_privilege(get_current_nttok(conn),
5486 DBG_DEBUG("open on %s failed - "
5487 "SEC_FLAG_SYSTEM_SECURITY denied.\n",
5488 smb_fname_str_dbg(smb_fname));
5489 status = NT_STATUS_PRIVILEGE_NOT_HELD;
5493 if (conn->sconn->using_smb2 &&
5494 (access_mask == SEC_FLAG_SYSTEM_SECURITY))
5497 * No other bits set. Windows SMB2 refuses this.
5498 * See smbtorture3 SMB2-SACL test.
5500 * Note this is an SMB2-only behavior,
5501 * smbtorture3 SMB1-SYSTEM-SECURITY already tests
5502 * that SMB1 allows this.
5504 status = NT_STATUS_ACCESS_DENIED;
5510 * Files or directories can't be opened DELETE_ON_CLOSE without
5512 * BUG: https://bugzilla.samba.org/show_bug.cgi?id=13358
5514 if (create_options & FILE_DELETE_ON_CLOSE) {
5515 if ((access_mask & DELETE_ACCESS) == 0) {
5516 status = NT_STATUS_INVALID_PARAMETER;
5521 if ((conn->fs_capabilities & FILE_NAMED_STREAMS)
5522 && is_ntfs_stream_smb_fname(smb_fname)
5523 && (!(private_flags & NTCREATEX_OPTIONS_PRIVATE_STREAM_DELETE))) {
5524 uint32_t base_create_disposition;
5525 struct smb_filename *smb_fname_base = NULL;
5526 uint32_t base_privflags;
5528 if (create_options & FILE_DIRECTORY_FILE) {
5529 status = NT_STATUS_NOT_A_DIRECTORY;
5533 switch (create_disposition) {
5535 base_create_disposition = FILE_OPEN;
5538 base_create_disposition = FILE_OPEN_IF;
5542 /* Create an smb_filename with stream_name == NULL. */
5543 smb_fname_base = synthetic_smb_fname(talloc_tos(),
5544 smb_fname->base_name,
5549 if (smb_fname_base == NULL) {
5550 status = NT_STATUS_NO_MEMORY;
5554 if (SMB_VFS_STAT(conn, smb_fname_base) == -1) {
5555 DEBUG(10, ("Unable to stat stream: %s\n",
5556 smb_fname_str_dbg(smb_fname_base)));
5559 * https://bugzilla.samba.org/show_bug.cgi?id=10229
5560 * We need to check if the requested access mask
5561 * could be used to open the underlying file (if
5562 * it existed), as we're passing in zero for the
5563 * access mask to the base filename.
5565 status = check_base_file_access(conn,
5569 if (!NT_STATUS_IS_OK(status)) {
5570 DEBUG(10, ("Permission check "
5571 "for base %s failed: "
5572 "%s\n", smb_fname->base_name,
5573 nt_errstr(status)));
5578 base_privflags = NTCREATEX_OPTIONS_PRIVATE_STREAM_BASEOPEN;
5580 /* Open the base file. */
5581 status = create_file_unixpath(conn,
5588 | FILE_SHARE_DELETE,
5589 base_create_disposition,
5600 TALLOC_FREE(smb_fname_base);
5602 if (!NT_STATUS_IS_OK(status)) {
5603 DEBUG(10, ("create_file_unixpath for base %s failed: "
5604 "%s\n", smb_fname->base_name,
5605 nt_errstr(status)));
5608 /* we don't need the low level fd */
5613 * If it's a request for a directory open, deal with it separately.
5616 if (create_options & FILE_DIRECTORY_FILE) {
5618 if (create_options & FILE_NON_DIRECTORY_FILE) {
5619 status = NT_STATUS_INVALID_PARAMETER;
5623 /* Can't open a temp directory. IFS kit test. */
5624 if (!(file_attributes & FILE_FLAG_POSIX_SEMANTICS) &&
5625 (file_attributes & FILE_ATTRIBUTE_TEMPORARY)) {
5626 status = NT_STATUS_INVALID_PARAMETER;
5631 * We will get a create directory here if the Win32
5632 * app specified a security descriptor in the
5633 * CreateDirectory() call.
5637 status = open_directory(conn,
5651 * Ordinary file case.
5654 status = file_new(req, conn, &fsp);
5655 if(!NT_STATUS_IS_OK(status)) {
5659 status = fsp_set_smb_fname(fsp, smb_fname);
5660 if (!NT_STATUS_IS_OK(status)) {
5666 * We're opening the stream element of a
5667 * base_fsp we already opened. Set up the
5670 fsp->base_fsp = base_fsp;
5673 if (allocation_size) {
5674 fsp->initial_allocation_size = smb_roundup(fsp->conn,
5678 status = open_file_ntcreate(conn,
5691 if(!NT_STATUS_IS_OK(status)) {
5692 file_free(req, fsp);
5696 if (NT_STATUS_EQUAL(status, NT_STATUS_FILE_IS_A_DIRECTORY)) {
5698 /* A stream open never opens a directory */
5701 status = NT_STATUS_FILE_IS_A_DIRECTORY;
5706 * Fail the open if it was explicitly a non-directory
5710 if (create_options & FILE_NON_DIRECTORY_FILE) {
5711 status = NT_STATUS_FILE_IS_A_DIRECTORY;
5716 status = open_directory(conn,
5730 if (!NT_STATUS_IS_OK(status)) {
5734 fsp->base_fsp = base_fsp;
5736 if ((ea_list != NULL) &&
5737 ((info == FILE_WAS_CREATED) || (info == FILE_WAS_OVERWRITTEN))) {
5738 status = set_ea(conn, fsp, fsp->fsp_name, ea_list);
5739 if (!NT_STATUS_IS_OK(status)) {
5744 if (!fsp->fsp_flags.is_directory &&
5745 S_ISDIR(fsp->fsp_name->st.st_ex_mode))
5747 status = NT_STATUS_ACCESS_DENIED;
5751 /* Save the requested allocation size. */
5752 if ((info == FILE_WAS_CREATED) || (info == FILE_WAS_OVERWRITTEN)) {
5753 if ((allocation_size > (uint64_t)fsp->fsp_name->st.st_ex_size)
5754 && !(fsp->fsp_flags.is_directory))
5756 fsp->initial_allocation_size = smb_roundup(
5757 fsp->conn, allocation_size);
5758 if (vfs_allocate_file_space(
5759 fsp, fsp->initial_allocation_size) == -1) {
5760 status = NT_STATUS_DISK_FULL;
5764 fsp->initial_allocation_size = smb_roundup(
5765 fsp->conn, (uint64_t)fsp->fsp_name->st.st_ex_size);
5768 fsp->initial_allocation_size = 0;
5771 if ((info == FILE_WAS_CREATED) && lp_nt_acl_support(SNUM(conn)) &&
5772 fsp->base_fsp == NULL) {
5775 * According to the MS documentation, the only time the security
5776 * descriptor is applied to the opened file is iff we *created* the
5777 * file; an existing file stays the same.
5779 * Also, it seems (from observation) that you can open the file with
5780 * any access mask but you can still write the sd. We need to override
5781 * the granted access before we call set_sd
5782 * Patch for bug #2242 from Tom Lackemann <cessnatomny@yahoo.com>.
5785 uint32_t sec_info_sent;
5786 uint32_t saved_access_mask = fsp->access_mask;
5788 sec_info_sent = get_sec_info(sd);
5790 fsp->access_mask = FILE_GENERIC_ALL;
5792 if (sec_info_sent & (SECINFO_OWNER|
5796 status = set_sd(fsp, sd, sec_info_sent);
5799 fsp->access_mask = saved_access_mask;
5801 if (!NT_STATUS_IS_OK(status)) {
5804 } else if (lp_inherit_acls(SNUM(conn))) {
5805 /* Inherit from parent. Errors here are not fatal. */
5806 status = inherit_new_acl(fsp);
5807 if (!NT_STATUS_IS_OK(status)) {
5808 DEBUG(10,("inherit_new_acl: failed for %s with %s\n",
5810 nt_errstr(status) ));
5815 if ((conn->fs_capabilities & FILE_FILE_COMPRESSION)
5816 && (create_options & FILE_NO_COMPRESSION)
5817 && (info == FILE_WAS_CREATED)) {
5818 status = SMB_VFS_SET_COMPRESSION(conn, fsp, fsp,
5819 COMPRESSION_FORMAT_NONE);
5820 if (!NT_STATUS_IS_OK(status)) {
5821 DEBUG(1, ("failed to disable compression: %s\n",
5822 nt_errstr(status)));
5826 DEBUG(10, ("create_file_unixpath: info=%d\n", info));
5829 if (pinfo != NULL) {
5833 smb_fname->st = fsp->fsp_name->st;
5835 return NT_STATUS_OK;
5838 DEBUG(10, ("create_file_unixpath: %s\n", nt_errstr(status)));
5841 if (base_fsp && fsp->base_fsp == base_fsp) {
5843 * The close_file below will close
5848 close_file(req, fsp, ERROR_CLOSE);
5851 if (base_fsp != NULL) {
5852 close_file(req, base_fsp, ERROR_CLOSE);
5858 NTSTATUS create_file_default(connection_struct *conn,
5859 struct smb_request *req,
5860 struct files_struct **_dirfsp,
5861 struct smb_filename *smb_fname,
5862 uint32_t access_mask,
5863 uint32_t share_access,
5864 uint32_t create_disposition,
5865 uint32_t create_options,
5866 uint32_t file_attributes,
5867 uint32_t oplock_request,
5868 const struct smb2_lease *lease,
5869 uint64_t allocation_size,
5870 uint32_t private_flags,
5871 struct security_descriptor *sd,
5872 struct ea_list *ea_list,
5873 files_struct **result,
5875 const struct smb2_create_blobs *in_context_blobs,
5876 struct smb2_create_blobs *out_context_blobs)
5878 int info = FILE_WAS_OPENED;
5879 files_struct *fsp = NULL;
5881 bool stream_name = false;
5882 struct smb2_create_blob *posx = NULL;
5883 struct files_struct *dirfsp = *_dirfsp;
5885 SMB_ASSERT(dirfsp == dirfsp->conn->cwd_fsp);
5887 DBG_DEBUG("create_file: access_mask = 0x%x "
5888 "file_attributes = 0x%x, share_access = 0x%x, "
5889 "create_disposition = 0x%x create_options = 0x%x "
5890 "oplock_request = 0x%x "
5891 "private_flags = 0x%x "
5892 "ea_list = %p, sd = %p, "
5895 (unsigned int)access_mask,
5896 (unsigned int)file_attributes,
5897 (unsigned int)share_access,
5898 (unsigned int)create_disposition,
5899 (unsigned int)create_options,
5900 (unsigned int)oplock_request,
5901 (unsigned int)private_flags,
5904 fsp_str_dbg(dirfsp),
5905 smb_fname_str_dbg(smb_fname));
5909 * Remember the absolute time of the original request
5910 * with this mid. We'll use it later to see if this
5913 get_deferred_open_message_state(req, &req->request_time, NULL);
5917 * Check to see if this is a mac fork of some kind.
5920 stream_name = is_ntfs_stream_smb_fname(smb_fname);
5922 enum FAKE_FILE_TYPE fake_file_type;
5924 fake_file_type = is_fake_file(smb_fname);
5926 if (fake_file_type != FAKE_FILE_TYPE_NONE) {
5929 * Here we go! support for changing the disk quotas
5932 * We need to fake up to open this MAGIC QUOTA file
5933 * and return a valid FID.
5935 * w2k close this file directly after openening xp
5936 * also tries a QUERY_FILE_INFO on the file and then
5939 status = open_fake_file(req, conn, req->vuid,
5940 fake_file_type, smb_fname,
5942 if (!NT_STATUS_IS_OK(status)) {
5946 ZERO_STRUCT(smb_fname->st);
5950 if (!(conn->fs_capabilities & FILE_NAMED_STREAMS)) {
5951 status = NT_STATUS_OBJECT_NAME_NOT_FOUND;
5956 if (is_ntfs_default_stream_smb_fname(smb_fname)) {
5958 smb_fname->stream_name = NULL;
5959 /* We have to handle this error here. */
5960 if (create_options & FILE_DIRECTORY_FILE) {
5961 status = NT_STATUS_NOT_A_DIRECTORY;
5964 if (req != NULL && req->posix_pathnames) {
5965 ret = SMB_VFS_LSTAT(conn, smb_fname);
5967 ret = SMB_VFS_STAT(conn, smb_fname);
5970 if (ret == 0 && VALID_STAT_OF_DIR(smb_fname->st)) {
5971 status = NT_STATUS_FILE_IS_A_DIRECTORY;
5976 posx = smb2_create_blob_find(
5977 in_context_blobs, SMB2_CREATE_TAG_POSIX);
5979 uint32_t wire_mode_bits = 0;
5980 mode_t mode_bits = 0;
5981 SMB_STRUCT_STAT sbuf = { 0 };
5982 enum perm_type ptype =
5983 (create_options & FILE_DIRECTORY_FILE) ?
5984 PERM_NEW_DIR : PERM_NEW_FILE;
5986 if (posx->data.length != 4) {
5987 status = NT_STATUS_INVALID_PARAMETER;
5991 wire_mode_bits = IVAL(posx->data.data, 0);
5992 status = unix_perms_from_wire(
5993 conn, &sbuf, wire_mode_bits, ptype, &mode_bits);
5994 if (!NT_STATUS_IS_OK(status)) {
5998 * Remove type info from mode, leaving only the
5999 * permissions and setuid/gid bits.
6001 mode_bits &= ~S_IFMT;
6003 file_attributes = (FILE_FLAG_POSIX_SEMANTICS | mode_bits);
6006 status = create_file_unixpath(conn,
6023 if (!NT_STATUS_IS_OK(status)) {
6028 DEBUG(10, ("create_file: info=%d\n", info));
6031 if (pinfo != NULL) {
6034 return NT_STATUS_OK;
6037 DEBUG(10, ("create_file: %s\n", nt_errstr(status)));
6040 close_file(req, fsp, ERROR_CLOSE);