2 Unix SMB/CIFS implementation.
3 file opening and share modes
4 Copyright (C) Andrew Tridgell 1992-1998
5 Copyright (C) Jeremy Allison 2001-2004
6 Copyright (C) Volker Lendecke 2005
7 Copyright (C) Ralph Boehme 2017
9 This program is free software; you can redistribute it and/or modify
10 it under the terms of the GNU General Public License as published by
11 the Free Software Foundation; either version 3 of the License, or
12 (at your option) any later version.
14 This program is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 GNU General Public License for more details.
19 You should have received a copy of the GNU General Public License
20 along with this program. If not, see <http://www.gnu.org/licenses/>.
24 #include "smb1_utils.h"
25 #include "system/filesys.h"
26 #include "lib/util/server_id.h"
28 #include "smbd/smbd.h"
29 #include "smbd/globals.h"
30 #include "fake_file.h"
31 #include "../libcli/security/security.h"
32 #include "../librpc/gen_ndr/ndr_security.h"
33 #include "../librpc/gen_ndr/ndr_open_files.h"
34 #include "../librpc/gen_ndr/idmap.h"
35 #include "../librpc/gen_ndr/ioctl.h"
36 #include "passdb/lookup_sid.h"
40 #include "source3/lib/dbwrap/dbwrap_watch.h"
41 #include "locking/leases_db.h"
42 #include "librpc/gen_ndr/ndr_leases_db.h"
43 #include "lib/util/time_basic.h"
45 extern const struct generic_mapping file_generic_mapping;
47 struct deferred_open_record {
48 struct smbXsrv_connection *xconn;
54 * Timer for async opens, needed because they don't use a watch on
55 * a locking.tdb record. This is currently only used for real async
56 * opens and just terminates smbd if the async open times out.
58 struct tevent_timer *te;
61 * For the samba kernel oplock case we use both a timeout and
62 * a watch on locking.tdb. This way in case it's smbd holding
63 * the kernel oplock we get directly notified for the retry
64 * once the kernel oplock is properly broken. Store the req
65 * here so that it can be timely discarded once the timer
68 struct tevent_req *watch_req;
71 /****************************************************************************
72 If the requester wanted DELETE_ACCESS and was rejected because
73 the file ACL didn't include DELETE_ACCESS, see if the parent ACL
75 ****************************************************************************/
77 static bool parent_override_delete(connection_struct *conn,
78 const struct smb_filename *smb_fname,
80 uint32_t rejected_mask)
82 if ((access_mask & DELETE_ACCESS) &&
83 (rejected_mask & DELETE_ACCESS) &&
84 can_delete_file_in_directory(conn,
93 /****************************************************************************
94 Check if we have open rights.
95 ****************************************************************************/
97 NTSTATUS smbd_check_access_rights(struct connection_struct *conn,
98 struct files_struct *dirfsp,
99 const struct smb_filename *smb_fname,
101 uint32_t access_mask)
103 /* Check if we have rights to open. */
105 struct security_descriptor *sd = NULL;
106 uint32_t rejected_share_access;
107 uint32_t rejected_mask = access_mask;
108 uint32_t do_not_check_mask = 0;
110 SMB_ASSERT(dirfsp == conn->cwd_fsp);
112 rejected_share_access = access_mask & ~(conn->share_access);
114 if (rejected_share_access) {
115 DEBUG(10, ("smbd_check_access_rights: rejected share access 0x%x "
117 (unsigned int)access_mask,
118 smb_fname_str_dbg(smb_fname),
119 (unsigned int)rejected_share_access ));
120 return NT_STATUS_ACCESS_DENIED;
123 if (!use_privs && get_current_uid(conn) == (uid_t)0) {
124 /* I'm sorry sir, I didn't know you were root... */
125 DEBUG(10,("smbd_check_access_rights: root override "
126 "on %s. Granting 0x%x\n",
127 smb_fname_str_dbg(smb_fname),
128 (unsigned int)access_mask ));
132 if ((access_mask & DELETE_ACCESS) && !lp_acl_check_permissions(SNUM(conn))) {
133 DEBUG(10,("smbd_check_access_rights: not checking ACL "
134 "on DELETE_ACCESS on file %s. Granting 0x%x\n",
135 smb_fname_str_dbg(smb_fname),
136 (unsigned int)access_mask ));
140 if (access_mask == DELETE_ACCESS &&
141 VALID_STAT(smb_fname->st) &&
142 S_ISLNK(smb_fname->st.st_ex_mode)) {
143 /* We can always delete a symlink. */
144 DEBUG(10,("smbd_check_access_rights: not checking ACL "
145 "on DELETE_ACCESS on symlink %s.\n",
146 smb_fname_str_dbg(smb_fname) ));
150 status = SMB_VFS_GET_NT_ACL_AT(conn,
159 if (!NT_STATUS_IS_OK(status)) {
160 DEBUG(10, ("smbd_check_access_rights: Could not get acl "
162 smb_fname_str_dbg(smb_fname),
165 if (NT_STATUS_EQUAL(status, NT_STATUS_ACCESS_DENIED)) {
173 * If we can access the path to this file, by
174 * default we have FILE_READ_ATTRIBUTES from the
175 * containing directory. See the section:
176 * "Algorithm to Check Access to an Existing File"
179 * se_file_access_check() also takes care of
180 * owner WRITE_DAC and READ_CONTROL.
182 do_not_check_mask = FILE_READ_ATTRIBUTES;
185 * Samba 3.6 and earlier granted execute access even
186 * if the ACL did not contain execute rights.
187 * Samba 4.0 is more correct and checks it.
188 * The compatibilty mode allows one to skip this check
189 * to smoothen upgrades.
191 if (lp_acl_allow_execute_always(SNUM(conn))) {
192 do_not_check_mask |= FILE_EXECUTE;
195 status = se_file_access_check(sd,
196 get_current_nttok(conn),
198 (access_mask & ~do_not_check_mask),
201 DEBUG(10,("smbd_check_access_rights: file %s requesting "
202 "0x%x returning 0x%x (%s)\n",
203 smb_fname_str_dbg(smb_fname),
204 (unsigned int)access_mask,
205 (unsigned int)rejected_mask,
206 nt_errstr(status) ));
208 if (!NT_STATUS_IS_OK(status)) {
209 if (DEBUGLEVEL >= 10) {
210 DEBUG(10,("smbd_check_access_rights: acl for %s is:\n",
211 smb_fname_str_dbg(smb_fname) ));
212 NDR_PRINT_DEBUG(security_descriptor, sd);
218 if (NT_STATUS_IS_OK(status) ||
219 !NT_STATUS_EQUAL(status, NT_STATUS_ACCESS_DENIED)) {
223 /* Here we know status == NT_STATUS_ACCESS_DENIED. */
227 if ((access_mask & FILE_WRITE_ATTRIBUTES) &&
228 (rejected_mask & FILE_WRITE_ATTRIBUTES) &&
229 !lp_store_dos_attributes(SNUM(conn)) &&
230 (lp_map_readonly(SNUM(conn)) ||
231 lp_map_archive(SNUM(conn)) ||
232 lp_map_hidden(SNUM(conn)) ||
233 lp_map_system(SNUM(conn)))) {
234 rejected_mask &= ~FILE_WRITE_ATTRIBUTES;
236 DEBUG(10,("smbd_check_access_rights: "
238 "FILE_WRITE_ATTRIBUTES "
240 smb_fname_str_dbg(smb_fname)));
243 if (parent_override_delete(conn,
247 /* Were we trying to do an open
248 * for delete and didn't get DELETE
249 * access (only) ? Check if the
250 * directory allows DELETE_CHILD.
252 * http://blogs.msdn.com/oldnewthing/archive/2004/06/04/148426.aspx
255 rejected_mask &= ~DELETE_ACCESS;
257 DEBUG(10,("smbd_check_access_rights: "
261 smb_fname_str_dbg(smb_fname)));
264 if (rejected_mask != 0) {
265 return NT_STATUS_ACCESS_DENIED;
270 NTSTATUS check_parent_access(struct connection_struct *conn,
271 struct files_struct *dirfsp,
272 struct smb_filename *smb_fname,
273 uint32_t access_mask)
276 struct security_descriptor *parent_sd = NULL;
277 uint32_t access_granted = 0;
278 struct smb_filename *parent_dir = NULL;
279 struct share_mode_lock *lck = NULL;
280 struct file_id id = {0};
282 bool delete_on_close_set;
284 TALLOC_CTX *frame = talloc_stackframe();
288 * NB. When dirfsp != conn->cwd_fsp, we must
289 * change parent_dir to be "." for the name here.
292 SMB_ASSERT(dirfsp == conn->cwd_fsp);
294 ok = parent_smb_fname(frame, smb_fname, &parent_dir, NULL);
296 status = NT_STATUS_NO_MEMORY;
300 if (get_current_uid(conn) == (uid_t)0) {
301 /* I'm sorry sir, I didn't know you were root... */
302 DEBUG(10,("check_parent_access: root override "
303 "on %s. Granting 0x%x\n",
304 smb_fname_str_dbg(smb_fname),
305 (unsigned int)access_mask ));
306 status = NT_STATUS_OK;
310 status = SMB_VFS_GET_NT_ACL_AT(conn,
317 if (!NT_STATUS_IS_OK(status)) {
318 DBG_INFO("SMB_VFS_GET_NT_ACL_AT failed for "
319 "%s with error %s\n",
320 smb_fname_str_dbg(parent_dir),
326 * If we can access the path to this file, by
327 * default we have FILE_READ_ATTRIBUTES from the
328 * containing directory. See the section:
329 * "Algorithm to Check Access to an Existing File"
332 * se_file_access_check() also takes care of
333 * owner WRITE_DAC and READ_CONTROL.
335 status = se_file_access_check(parent_sd,
336 get_current_nttok(conn),
338 (access_mask & ~FILE_READ_ATTRIBUTES),
340 if(!NT_STATUS_IS_OK(status)) {
341 DEBUG(5,("check_parent_access: access check "
342 "on directory %s for "
343 "path %s for mask 0x%x returned (0x%x) %s\n",
344 smb_fname_str_dbg(parent_dir),
345 smb_fname->base_name,
348 nt_errstr(status) ));
352 if (!(access_mask & (SEC_DIR_ADD_FILE | SEC_DIR_ADD_SUBDIR))) {
353 status = NT_STATUS_OK;
356 if (!lp_check_parent_directory_delete_on_close(SNUM(conn))) {
357 status = NT_STATUS_OK;
361 /* Check if the directory has delete-on-close set */
362 ret = SMB_VFS_STAT(conn, parent_dir);
364 status = map_nt_error_from_unix(errno);
368 id = SMB_VFS_FILE_ID_CREATE(conn, &parent_dir->st);
370 status = file_name_hash(conn, parent_dir->base_name, &name_hash);
371 if (!NT_STATUS_IS_OK(status)) {
375 lck = get_existing_share_mode_lock(frame, id);
377 status = NT_STATUS_OK;
381 delete_on_close_set = is_delete_on_close_set(lck, name_hash);
382 if (delete_on_close_set) {
383 status = NT_STATUS_DELETE_PENDING;
387 status = NT_STATUS_OK;
394 /****************************************************************************
395 Ensure when opening a base file for a stream open that we have permissions
396 to do so given the access mask on the base file.
397 ****************************************************************************/
399 static NTSTATUS check_base_file_access(struct connection_struct *conn,
400 struct smb_filename *smb_fname,
401 uint32_t access_mask)
405 status = smbd_calculate_access_mask(conn,
411 if (!NT_STATUS_IS_OK(status)) {
412 DEBUG(10, ("smbd_calculate_access_mask "
413 "on file %s returned %s\n",
414 smb_fname_str_dbg(smb_fname),
419 if (access_mask & (FILE_WRITE_DATA|FILE_APPEND_DATA)) {
421 if (!CAN_WRITE(conn)) {
422 return NT_STATUS_ACCESS_DENIED;
424 dosattrs = dos_mode(conn, smb_fname);
425 if (IS_DOS_READONLY(dosattrs)) {
426 return NT_STATUS_ACCESS_DENIED;
430 return smbd_check_access_rights(conn,
437 /****************************************************************************
438 Handle differing symlink errno's
439 ****************************************************************************/
441 static int link_errno_convert(int err)
443 #if defined(ENOTSUP) && defined(OSF1)
444 /* handle special Tru64 errno */
445 if (err == ENOTSUP) {
450 /* fix broken NetBSD errno */
455 /* fix broken FreeBSD errno */
462 static int non_widelink_open(files_struct *fsp,
463 struct smb_filename *smb_fname,
466 unsigned int link_depth);
468 /****************************************************************************
469 Follow a symlink in userspace.
470 ****************************************************************************/
472 static int process_symlink_open(struct connection_struct *conn,
474 struct smb_filename *smb_fname,
477 unsigned int link_depth)
479 const char *conn_rootdir = NULL;
480 struct smb_filename conn_rootdir_fname;
482 char *link_target = NULL;
484 struct smb_filename *oldwd_fname = NULL;
485 size_t rootdir_len = 0;
486 struct smb_filename *resolved_fname = NULL;
487 char *resolved_name = NULL;
488 bool matched = false;
491 conn_rootdir = SMB_VFS_CONNECTPATH(conn, smb_fname);
492 if (conn_rootdir == NULL) {
496 conn_rootdir_fname = (struct smb_filename) {
497 .base_name = discard_const_p(char, conn_rootdir),
501 * Ensure we don't get stuck in a symlink loop.
504 if (link_depth >= 20) {
509 /* Allocate space for the link target. */
510 link_target = talloc_array(talloc_tos(), char, PATH_MAX);
511 if (link_target == NULL) {
517 * Read the link target. We do this just to verify that smb_fname indeed
518 * points at a symbolic link and return the SMB_VFS_READLINKAT() errno
519 * and failure in case smb_fname is NOT a symlink.
521 * The caller needs this piece of information to distinguish two cases
522 * where open() fails with errno=ENOTDIR, cf the comment in
523 * non_widelink_open().
525 * We rely on SMB_VFS_REALPATH() to resolve the path including the
526 * symlink. Once we have SMB_VFS_STATX() or something similar in our VFS
527 * we may want to use that instead of SMB_VFS_READLINKAT().
529 link_len = SMB_VFS_READLINKAT(conn,
534 if (link_len == -1) {
538 /* Convert to an absolute path. */
539 resolved_fname = SMB_VFS_REALPATH(conn, talloc_tos(), smb_fname);
540 if (resolved_fname == NULL) {
543 resolved_name = resolved_fname->base_name;
546 * We know conn_rootdir starts with '/' and
547 * does not end in '/'. FIXME ! Should we
550 rootdir_len = strlen(conn_rootdir_fname.base_name);
552 matched = (strncmp(conn_rootdir_fname.base_name,
561 * Turn into a path relative to the share root.
563 if (resolved_name[rootdir_len] == '\0') {
564 /* Link to the root of the share. */
565 TALLOC_FREE(smb_fname->base_name);
566 smb_fname->base_name = talloc_strdup(smb_fname, ".");
567 } else if (resolved_name[rootdir_len] == '/') {
568 TALLOC_FREE(smb_fname->base_name);
569 smb_fname->base_name = talloc_strdup(smb_fname,
570 &resolved_name[rootdir_len+1]);
576 if (smb_fname->base_name == NULL) {
581 oldwd_fname = vfs_GetWd(talloc_tos(), conn);
582 if (oldwd_fname == NULL) {
586 /* Ensure we operate from the root of the share. */
587 if (vfs_ChDir(conn, &conn_rootdir_fname) == -1) {
591 /* And do it all again.. */
592 fd = non_widelink_open(fsp,
603 TALLOC_FREE(resolved_fname);
604 TALLOC_FREE(link_target);
605 if (oldwd_fname != NULL) {
606 int ret = vfs_ChDir(conn, oldwd_fname);
608 smb_panic("unable to get back to old directory\n");
610 TALLOC_FREE(oldwd_fname);
612 if (saved_errno != 0) {
618 /****************************************************************************
620 ****************************************************************************/
622 static int non_widelink_open(files_struct *fsp,
623 struct smb_filename *smb_fname,
626 unsigned int link_depth)
628 struct connection_struct *conn = fsp->conn;
631 struct smb_filename *smb_fname_rel = NULL;
633 struct smb_filename *oldwd_fname = NULL;
634 struct smb_filename *parent_dir_fname = NULL;
635 struct files_struct *cwdfsp = NULL;
638 if (fsp->fsp_flags.is_directory) {
639 parent_dir_fname = cp_smb_filename(talloc_tos(), smb_fname);
640 if (parent_dir_fname == NULL) {
645 smb_fname_rel = synthetic_smb_fname(parent_dir_fname,
647 smb_fname->stream_name,
651 if (smb_fname_rel == NULL) {
656 ok = parent_smb_fname(talloc_tos(),
666 oldwd_fname = vfs_GetWd(talloc_tos(), conn);
667 if (oldwd_fname == NULL) {
671 /* Pin parent directory in place. */
672 if (vfs_ChDir(conn, parent_dir_fname) == -1) {
676 /* Ensure the relative path is below the share. */
677 status = check_reduced_name(conn, parent_dir_fname, smb_fname_rel);
678 if (!NT_STATUS_IS_OK(status)) {
679 saved_errno = map_errno_from_nt_status(status);
683 status = vfs_at_fspcwd(talloc_tos(),
686 if (!NT_STATUS_IS_OK(status)) {
687 saved_errno = map_errno_from_nt_status(status);
694 struct smb_filename *tmp_name = fsp->fsp_name;
696 fsp->fsp_name = smb_fname_rel;
698 fd = SMB_VFS_OPENAT(conn,
705 fsp->fsp_name = tmp_name;
709 saved_errno = link_errno_convert(errno);
711 * Trying to open a symlink to a directory with O_NOFOLLOW and
712 * O_DIRECTORY can return either of ELOOP and ENOTDIR. So
713 * ENOTDIR really means: might be a symlink, but we're not sure.
714 * In this case, we just assume there's a symlink. If we were
715 * wrong, process_symlink_open() will return EINVAL. We check
716 * this below, and fall back to returning the initial
719 * BUG: https://bugzilla.samba.org/show_bug.cgi?id=12860
721 if (saved_errno == ELOOP || saved_errno == ENOTDIR) {
722 if (fsp->posix_flags & FSP_POSIX_FLAGS_OPEN) {
723 /* Never follow symlinks on posix open. */
726 if (!lp_follow_symlinks(SNUM(conn))) {
727 /* Explicitly no symlinks. */
731 * We may have a symlink. Follow in userspace
732 * to ensure it's under the share definition.
734 fd = process_symlink_open(conn,
741 if (saved_errno == ENOTDIR &&
744 * O_DIRECTORY on neither a directory,
745 * nor a symlink. Just return
746 * saved_errno from initial open()
751 link_errno_convert(errno);
758 TALLOC_FREE(parent_dir_fname);
761 if (oldwd_fname != NULL) {
762 int ret = vfs_ChDir(conn, oldwd_fname);
764 smb_panic("unable to get back to old directory\n");
766 TALLOC_FREE(oldwd_fname);
768 if (saved_errno != 0) {
774 /****************************************************************************
775 fd support routines - attempt to do a dos_open.
776 ****************************************************************************/
778 NTSTATUS fd_open(files_struct *fsp,
782 struct connection_struct *conn = fsp->conn;
783 struct smb_filename *smb_fname = fsp->fsp_name;
784 NTSTATUS status = NT_STATUS_OK;
788 * Never follow symlinks on a POSIX client. The
789 * client should be doing this.
792 if ((fsp->posix_flags & FSP_POSIX_FLAGS_OPEN) || !lp_follow_symlinks(SNUM(conn))) {
797 * Only follow symlinks within a share
800 fsp->fh->fd = non_widelink_open(fsp,
805 if (fsp->fh->fd == -1) {
808 if (saved_errno != 0) {
812 if (fsp->fh->fd == -1) {
813 int posix_errno = link_errno_convert(errno);
814 status = map_nt_error_from_unix(posix_errno);
815 if (errno == EMFILE) {
816 static time_t last_warned = 0L;
818 if (time((time_t *) NULL) > last_warned) {
819 DEBUG(0,("Too many open files, unable "
820 "to open more! smbd's max "
822 lp_max_open_files()));
823 last_warned = time((time_t *) NULL);
827 DBG_DEBUG("name %s, flags = 0%o mode = 0%o, fd = %d. %s\n",
828 smb_fname_str_dbg(smb_fname), flags, (int)mode,
829 fsp->fh->fd, strerror(errno));
833 DBG_DEBUG("name %s, flags = 0%o mode = 0%o, fd = %d\n",
834 smb_fname_str_dbg(smb_fname), flags, (int)mode, fsp->fh->fd);
839 NTSTATUS fd_openat(files_struct *fsp,
843 NTSTATUS status = NT_STATUS_OK;
846 if (fsp->dirfsp == fsp->conn->cwd_fsp) {
847 return fd_open(fsp, flags, mode);
851 * Never follow symlinks at this point, filename_convert() should have
852 * resolved any symlink.
858 * Only follow symlinks within a share
861 fsp->fh->fd = SMB_VFS_OPENAT(fsp->conn,
867 if (fsp->fh->fd == -1) {
870 if (saved_errno != 0) {
874 if (fsp->fh->fd == -1) {
875 int posix_errno = link_errno_convert(errno);
877 status = map_nt_error_from_unix(posix_errno);
879 if (errno == EMFILE) {
880 static time_t last_warned = 0L;
882 if (time((time_t *) NULL) > last_warned) {
883 DEBUG(0,("Too many open files, unable "
884 "to open more! smbd's max "
886 lp_max_open_files()));
887 last_warned = time((time_t *) NULL);
891 DBG_DEBUG("name %s, flags = 0%o mode = 0%o, fd = %d. %s\n",
892 fsp_str_dbg(fsp), flags, (int)mode,
893 fsp->fh->fd, strerror(errno));
897 DBG_DEBUG("name %s, flags = 0%o mode = 0%o, fd = %d\n",
898 fsp_str_dbg(fsp), flags, (int)mode, fsp->fh->fd);
903 /****************************************************************************
904 Close the file associated with a fsp.
905 ****************************************************************************/
907 NTSTATUS fd_close(files_struct *fsp)
911 if (fsp == fsp->conn->cwd_fsp) {
918 if (fsp->fh->fd == -1) {
920 * Either a directory where the dptr_CloseDir() already closed
921 * the fd or a stat open.
925 if (fsp->fh->ref_count > 1) {
926 return NT_STATUS_OK; /* Shared handle. Only close last reference. */
929 ret = SMB_VFS_CLOSE(fsp);
932 return map_nt_error_from_unix(errno);
937 /****************************************************************************
938 Change the ownership of a file to that of the parent directory.
939 Do this by fd if possible.
940 ****************************************************************************/
942 void change_file_owner_to_parent(connection_struct *conn,
943 struct smb_filename *smb_fname_parent,
948 ret = SMB_VFS_STAT(conn, smb_fname_parent);
950 DEBUG(0,("change_file_owner_to_parent: failed to stat parent "
951 "directory %s. Error was %s\n",
952 smb_fname_str_dbg(smb_fname_parent),
954 TALLOC_FREE(smb_fname_parent);
958 if (smb_fname_parent->st.st_ex_uid == fsp->fsp_name->st.st_ex_uid) {
959 /* Already this uid - no need to change. */
960 DEBUG(10,("change_file_owner_to_parent: file %s "
961 "is already owned by uid %d\n",
963 (int)fsp->fsp_name->st.st_ex_uid ));
964 TALLOC_FREE(smb_fname_parent);
969 ret = SMB_VFS_FCHOWN(fsp, smb_fname_parent->st.st_ex_uid, (gid_t)-1);
972 DEBUG(0,("change_file_owner_to_parent: failed to fchown "
973 "file %s to parent directory uid %u. Error "
974 "was %s\n", fsp_str_dbg(fsp),
975 (unsigned int)smb_fname_parent->st.st_ex_uid,
978 DEBUG(10,("change_file_owner_to_parent: changed new file %s to "
979 "parent directory uid %u.\n", fsp_str_dbg(fsp),
980 (unsigned int)smb_fname_parent->st.st_ex_uid));
981 /* Ensure the uid entry is updated. */
982 fsp->fsp_name->st.st_ex_uid = smb_fname_parent->st.st_ex_uid;
986 static NTSTATUS change_dir_owner_to_parent(connection_struct *conn,
987 struct smb_filename *smb_fname_parent,
988 struct smb_filename *smb_dname,
989 SMB_STRUCT_STAT *psbuf)
991 struct smb_filename *smb_fname_cwd = NULL;
992 struct smb_filename *saved_dir_fname = NULL;
993 TALLOC_CTX *ctx = talloc_tos();
994 NTSTATUS status = NT_STATUS_OK;
997 ret = SMB_VFS_STAT(conn, smb_fname_parent);
999 status = map_nt_error_from_unix(errno);
1000 DEBUG(0,("change_dir_owner_to_parent: failed to stat parent "
1001 "directory %s. Error was %s\n",
1002 smb_fname_str_dbg(smb_fname_parent),
1007 /* We've already done an lstat into psbuf, and we know it's a
1008 directory. If we can cd into the directory and the dev/ino
1009 are the same then we can safely chown without races as
1010 we're locking the directory in place by being in it. This
1011 should work on any UNIX (thanks tridge :-). JRA.
1014 saved_dir_fname = vfs_GetWd(ctx,conn);
1015 if (!saved_dir_fname) {
1016 status = map_nt_error_from_unix(errno);
1017 DEBUG(0,("change_dir_owner_to_parent: failed to get "
1018 "current working directory. Error was %s\n",
1023 /* Chdir into the new path. */
1024 if (vfs_ChDir(conn, smb_dname) == -1) {
1025 status = map_nt_error_from_unix(errno);
1026 DEBUG(0,("change_dir_owner_to_parent: failed to change "
1027 "current working directory to %s. Error "
1028 "was %s\n", smb_dname->base_name, strerror(errno) ));
1032 smb_fname_cwd = synthetic_smb_fname(ctx,
1038 if (smb_fname_cwd == NULL) {
1039 status = NT_STATUS_NO_MEMORY;
1043 ret = SMB_VFS_STAT(conn, smb_fname_cwd);
1045 status = map_nt_error_from_unix(errno);
1046 DEBUG(0,("change_dir_owner_to_parent: failed to stat "
1047 "directory '.' (%s) Error was %s\n",
1048 smb_dname->base_name, strerror(errno)));
1052 /* Ensure we're pointing at the same place. */
1053 if (smb_fname_cwd->st.st_ex_dev != psbuf->st_ex_dev ||
1054 smb_fname_cwd->st.st_ex_ino != psbuf->st_ex_ino) {
1055 DEBUG(0,("change_dir_owner_to_parent: "
1056 "device/inode on directory %s changed. "
1057 "Refusing to chown !\n",
1058 smb_dname->base_name ));
1059 status = NT_STATUS_ACCESS_DENIED;
1063 if (smb_fname_parent->st.st_ex_uid == smb_fname_cwd->st.st_ex_uid) {
1064 /* Already this uid - no need to change. */
1065 DEBUG(10,("change_dir_owner_to_parent: directory %s "
1066 "is already owned by uid %d\n",
1067 smb_dname->base_name,
1068 (int)smb_fname_cwd->st.st_ex_uid ));
1069 status = NT_STATUS_OK;
1074 ret = SMB_VFS_LCHOWN(conn,
1076 smb_fname_parent->st.st_ex_uid,
1080 status = map_nt_error_from_unix(errno);
1081 DEBUG(10,("change_dir_owner_to_parent: failed to chown "
1082 "directory %s to parent directory uid %u. "
1084 smb_dname->base_name,
1085 (unsigned int)smb_fname_parent->st.st_ex_uid,
1088 DEBUG(10,("change_dir_owner_to_parent: changed ownership of new "
1089 "directory %s to parent directory uid %u.\n",
1090 smb_dname->base_name,
1091 (unsigned int)smb_fname_parent->st.st_ex_uid ));
1092 /* Ensure the uid entry is updated. */
1093 psbuf->st_ex_uid = smb_fname_parent->st.st_ex_uid;
1097 vfs_ChDir(conn, saved_dir_fname);
1099 TALLOC_FREE(saved_dir_fname);
1100 TALLOC_FREE(smb_fname_cwd);
1104 /****************************************************************************
1105 Open a file - returning a guaranteed ATOMIC indication of if the
1106 file was created or not.
1107 ****************************************************************************/
1109 static NTSTATUS fd_open_atomic(files_struct *fsp,
1114 NTSTATUS status = NT_STATUS_UNSUCCESSFUL;
1115 NTSTATUS retry_status;
1116 bool file_existed = VALID_STAT(fsp->fsp_name->st);
1119 if (!(flags & O_CREAT)) {
1121 * We're not creating the file, just pass through.
1123 status = fd_openat(fsp, flags, mode);
1124 *file_created = false;
1128 if (flags & O_EXCL) {
1130 * Fail if already exists, just pass through.
1132 status = fd_openat(fsp, flags, mode);
1135 * Here we've opened with O_CREAT|O_EXCL. If that went
1136 * NT_STATUS_OK, we *know* we created this file.
1138 *file_created = NT_STATUS_IS_OK(status);
1144 * Now it gets tricky. We have O_CREAT, but not O_EXCL.
1145 * To know absolutely if we created the file or not,
1146 * we can never call O_CREAT without O_EXCL. So if
1147 * we think the file existed, try without O_CREAT|O_EXCL.
1148 * If we think the file didn't exist, try with
1151 * The big problem here is dangling symlinks. Opening
1152 * without O_NOFOLLOW means both bad symlink
1153 * and missing path return -1, ENOENT from open(). As POSIX
1154 * is pathname based it's not possible to tell
1155 * the difference between these two cases in a
1156 * non-racy way, so change to try only two attempts before
1159 * We don't have this problem for the O_NOFOLLOW
1160 * case as it just returns NT_STATUS_OBJECT_PATH_NOT_FOUND
1161 * mapped from the ELOOP POSIX error.
1165 curr_flags = flags & ~(O_CREAT);
1166 retry_status = NT_STATUS_OBJECT_NAME_NOT_FOUND;
1168 curr_flags = flags | O_EXCL;
1169 retry_status = NT_STATUS_OBJECT_NAME_COLLISION;
1172 status = fd_openat(fsp, curr_flags, mode);
1173 if (NT_STATUS_IS_OK(status)) {
1174 *file_created = !file_existed;
1175 return NT_STATUS_OK;
1177 if (NT_STATUS_EQUAL(status, retry_status)) {
1179 file_existed = !file_existed;
1181 DBG_DEBUG("File %s %s. Retry.\n",
1183 file_existed ? "existed" : "did not exist");
1186 curr_flags = flags & ~(O_CREAT);
1188 curr_flags = flags | O_EXCL;
1191 status = fd_openat(fsp, curr_flags, mode);
1194 *file_created = (NT_STATUS_IS_OK(status) && !file_existed);
1198 /****************************************************************************
1200 ****************************************************************************/
1202 static NTSTATUS open_file(files_struct *fsp,
1203 struct smb_request *req,
1204 struct smb_filename *parent_dir,
1207 uint32_t access_mask, /* client requested access mask. */
1208 uint32_t open_access_mask, /* what we're actually using in the open. */
1209 bool *p_file_created)
1211 connection_struct *conn = fsp->conn;
1212 struct smb_filename *smb_fname = fsp->fsp_name;
1213 NTSTATUS status = NT_STATUS_OK;
1214 int accmode = (flags & O_ACCMODE);
1215 int local_flags = flags;
1216 bool file_existed = VALID_STAT(fsp->fsp_name->st);
1217 uint32_t need_fd_mask =
1223 WRITE_OWNER_ACCESS |
1224 SEC_FLAG_SYSTEM_SECURITY |
1225 READ_CONTROL_ACCESS;
1226 bool creating = !file_existed && (flags & O_CREAT);
1227 bool truncating = (flags & O_TRUNC);
1228 bool open_fd = false;
1233 /* Check permissions */
1236 * This code was changed after seeing a client open request
1237 * containing the open mode of (DENY_WRITE/read-only) with
1238 * the 'create if not exist' bit set. The previous code
1239 * would fail to open the file read only on a read-only share
1240 * as it was checking the flags parameter directly against O_RDONLY,
1241 * this was failing as the flags parameter was set to O_RDONLY|O_CREAT.
1245 if (!CAN_WRITE(conn)) {
1246 /* It's a read-only share - fail if we wanted to write. */
1247 if(accmode != O_RDONLY || (flags & O_TRUNC) || (flags & O_APPEND)) {
1248 DEBUG(3,("Permission denied opening %s\n",
1249 smb_fname_str_dbg(smb_fname)));
1250 return NT_STATUS_ACCESS_DENIED;
1252 if (flags & O_CREAT) {
1253 /* We don't want to write - but we must make sure that
1254 O_CREAT doesn't create the file if we have write
1255 access into the directory.
1257 flags &= ~(O_CREAT|O_EXCL);
1258 local_flags &= ~(O_CREAT|O_EXCL);
1263 * This little piece of insanity is inspired by the
1264 * fact that an NT client can open a file for O_RDONLY,
1265 * but set the create disposition to FILE_EXISTS_TRUNCATE.
1266 * If the client *can* write to the file, then it expects to
1267 * truncate the file, even though it is opening for readonly.
1268 * Quicken uses this stupid trick in backup file creation...
1269 * Thanks *greatly* to "David W. Chapman Jr." <dwcjr@inethouston.net>
1270 * for helping track this one down. It didn't bite us in 2.0.x
1271 * as we always opened files read-write in that release. JRA.
1274 if ((accmode == O_RDONLY) && ((flags & O_TRUNC) == O_TRUNC)) {
1275 DEBUG(10,("open_file: truncate requested on read-only open "
1276 "for file %s\n", smb_fname_str_dbg(smb_fname)));
1277 local_flags = (flags & ~O_ACCMODE)|O_RDWR;
1280 if ((open_access_mask & need_fd_mask) || creating || truncating) {
1288 #if defined(O_NONBLOCK) && defined(S_ISFIFO)
1290 * We would block on opening a FIFO with no one else on the
1291 * other end. Do what we used to do and add O_NONBLOCK to the
1295 if (file_existed && S_ISFIFO(smb_fname->st.st_ex_mode)) {
1296 local_flags &= ~O_TRUNC; /* Can't truncate a FIFO. */
1297 local_flags |= O_NONBLOCK;
1302 /* Don't create files with Microsoft wildcard characters. */
1303 if (fsp->base_fsp) {
1305 * wildcard characters are allowed in stream names
1306 * only test the basefilename
1308 wild = fsp->base_fsp->fsp_name->base_name;
1310 wild = smb_fname->base_name;
1312 if ((local_flags & O_CREAT) && !file_existed &&
1313 !(fsp->posix_flags & FSP_POSIX_FLAGS_PATHNAMES) &&
1314 ms_has_wild(wild)) {
1315 return NT_STATUS_OBJECT_NAME_INVALID;
1318 /* Can we access this file ? */
1319 if (!fsp->base_fsp) {
1320 /* Only do this check on non-stream open. */
1322 status = smbd_check_access_rights(conn,
1328 if (!NT_STATUS_IS_OK(status)) {
1329 DEBUG(10, ("open_file: "
1330 "smbd_check_access_rights "
1331 "on file %s returned %s\n",
1332 smb_fname_str_dbg(smb_fname),
1333 nt_errstr(status)));
1336 if (!NT_STATUS_IS_OK(status) &&
1337 !NT_STATUS_EQUAL(status,
1338 NT_STATUS_OBJECT_NAME_NOT_FOUND))
1343 if (NT_STATUS_EQUAL(status,
1344 NT_STATUS_OBJECT_NAME_NOT_FOUND))
1346 DEBUG(10, ("open_file: "
1347 "file %s vanished since we "
1348 "checked for existence.\n",
1349 smb_fname_str_dbg(smb_fname)));
1350 file_existed = false;
1351 SET_STAT_INVALID(fsp->fsp_name->st);
1355 if (!file_existed) {
1356 if (!(local_flags & O_CREAT)) {
1357 /* File didn't exist and no O_CREAT. */
1358 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
1361 status = check_parent_access(conn,
1365 if (!NT_STATUS_IS_OK(status)) {
1366 DEBUG(10, ("open_file: "
1367 "check_parent_access on "
1368 "file %s returned %s\n",
1369 smb_fname_str_dbg(smb_fname),
1370 nt_errstr(status) ));
1377 * Actually do the open - if O_TRUNC is needed handle it
1378 * below under the share mode lock.
1380 status = fd_open_atomic(fsp,
1381 local_flags & ~O_TRUNC,
1384 if (!NT_STATUS_IS_OK(status)) {
1385 DEBUG(3,("Error opening file %s (%s) (local_flags=%d) "
1386 "(flags=%d)\n", smb_fname_str_dbg(smb_fname),
1387 nt_errstr(status),local_flags,flags));
1391 if (local_flags & O_NONBLOCK) {
1393 * GPFS can return ETIMEDOUT for pread on
1394 * nonblocking file descriptors when files
1395 * migrated to tape need to be recalled. I
1396 * could imagine this happens elsewhere
1397 * too. With blocking file descriptors this
1400 ret = vfs_set_blocking(fsp, true);
1402 status = map_nt_error_from_unix(errno);
1403 DBG_WARNING("Could not set fd to blocking: "
1404 "%s\n", strerror(errno));
1410 ret = SMB_VFS_FSTAT(fsp, &smb_fname->st);
1412 /* If we have an fd, this stat should succeed. */
1413 DEBUG(0,("Error doing fstat on open file %s "
1415 smb_fname_str_dbg(smb_fname),
1417 status = map_nt_error_from_unix(errno);
1422 if (*p_file_created) {
1423 /* We created this file. */
1425 bool need_re_stat = false;
1426 /* Do all inheritance work after we've
1427 done a successful fstat call and filled
1428 in the stat struct in fsp->fsp_name. */
1430 /* Inherit the ACL if required */
1431 if (lp_inherit_permissions(SNUM(conn))) {
1432 inherit_access_posix_acl(conn,
1436 need_re_stat = true;
1439 /* Change the owner if required. */
1440 if (lp_inherit_owner(SNUM(conn)) != INHERIT_OWNER_NO) {
1441 change_file_owner_to_parent(conn,
1444 need_re_stat = true;
1448 ret = SMB_VFS_FSTAT(fsp, &smb_fname->st);
1449 /* If we have an fd, this stat should succeed. */
1451 DEBUG(0,("Error doing fstat on open file %s "
1453 smb_fname_str_dbg(smb_fname),
1458 notify_fname(conn, NOTIFY_ACTION_ADDED,
1459 FILE_NOTIFY_CHANGE_FILE_NAME,
1460 smb_fname->base_name);
1463 fsp->fh->fd = -1; /* What we used to call a stat open. */
1464 if (!file_existed) {
1465 /* File must exist for a stat open. */
1466 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
1469 status = smbd_check_access_rights(conn,
1475 if (NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND) &&
1476 (fsp->posix_flags & FSP_POSIX_FLAGS_OPEN) &&
1477 S_ISLNK(smb_fname->st.st_ex_mode)) {
1478 /* This is a POSIX stat open for delete
1479 * or rename on a symlink that points
1480 * nowhere. Allow. */
1481 DEBUG(10,("open_file: allowing POSIX "
1482 "open on bad symlink %s\n",
1483 smb_fname_str_dbg(smb_fname)));
1484 status = NT_STATUS_OK;
1487 if (!NT_STATUS_IS_OK(status)) {
1488 DEBUG(10,("open_file: "
1489 "smbd_check_access_rights on file "
1491 smb_fname_str_dbg(smb_fname),
1492 nt_errstr(status) ));
1498 * POSIX allows read-only opens of directories. We don't
1499 * want to do this (we use a different code path for this)
1500 * so catch a directory open and return an EISDIR. JRA.
1503 if(S_ISDIR(smb_fname->st.st_ex_mode)) {
1506 return NT_STATUS_FILE_IS_A_DIRECTORY;
1509 fsp->file_id = vfs_file_id_from_sbuf(conn, &smb_fname->st);
1510 fsp->vuid = req ? req->vuid : UID_FIELD_INVALID;
1511 fsp->file_pid = req ? req->smbpid : 0;
1512 fsp->fsp_flags.can_lock = true;
1513 fsp->fsp_flags.can_read = ((access_mask & FILE_READ_DATA) != 0);
1514 fsp->fsp_flags.can_write =
1516 ((access_mask & (FILE_WRITE_DATA | FILE_APPEND_DATA)) != 0);
1517 fsp->print_file = NULL;
1518 fsp->fsp_flags.modified = false;
1519 fsp->sent_oplock_break = NO_BREAK_SENT;
1520 fsp->fsp_flags.is_directory = false;
1521 if (conn->aio_write_behind_list &&
1522 is_in_path(smb_fname->base_name, conn->aio_write_behind_list,
1523 conn->case_sensitive)) {
1524 fsp->fsp_flags.aio_write_behind = true;
1527 DEBUG(2,("%s opened file %s read=%s write=%s (numopen=%d)\n",
1528 conn->session_info->unix_info->unix_name,
1529 smb_fname_str_dbg(smb_fname),
1530 BOOLSTR(fsp->fsp_flags.can_read),
1531 BOOLSTR(fsp->fsp_flags.can_write),
1532 conn->num_files_open));
1535 return NT_STATUS_OK;
1538 static bool mask_conflict(
1539 uint32_t new_access,
1540 uint32_t existing_access,
1541 uint32_t access_mask,
1542 uint32_t new_sharemode,
1543 uint32_t existing_sharemode,
1544 uint32_t sharemode_mask)
1546 bool want_access = (new_access & access_mask);
1547 bool allow_existing = (existing_sharemode & sharemode_mask);
1548 bool have_access = (existing_access & access_mask);
1549 bool allow_new = (new_sharemode & sharemode_mask);
1551 if (want_access && !allow_existing) {
1552 DBG_DEBUG("Access request 0x%"PRIx32"/0x%"PRIx32" conflicts "
1553 "with existing sharemode 0x%"PRIx32"/0x%"PRIx32"\n",
1560 if (have_access && !allow_new) {
1561 DBG_DEBUG("Sharemode request 0x%"PRIx32"/0x%"PRIx32" conflicts "
1562 "with existing access 0x%"PRIx32"/0x%"PRIx32"\n",
1572 /****************************************************************************
1573 Check if we can open a file with a share mode.
1574 Returns True if conflict, False if not.
1575 ****************************************************************************/
1577 static const uint32_t conflicting_access =
1584 static bool share_conflict(uint32_t e_access_mask,
1585 uint32_t e_share_access,
1586 uint32_t access_mask,
1587 uint32_t share_access)
1591 DBG_DEBUG("existing access_mask = 0x%"PRIx32", "
1592 "existing share access = 0x%"PRIx32", "
1593 "access_mask = 0x%"PRIx32", "
1594 "share_access = 0x%"PRIx32"\n",
1600 if ((e_access_mask & conflicting_access) == 0) {
1601 DBG_DEBUG("No conflict due to "
1602 "existing access_mask = 0x%"PRIx32"\n",
1606 if ((access_mask & conflicting_access) == 0) {
1607 DBG_DEBUG("No conflict due to access_mask = 0x%"PRIx32"\n",
1612 conflict = mask_conflict(
1613 access_mask, e_access_mask, FILE_WRITE_DATA | FILE_APPEND_DATA,
1614 share_access, e_share_access, FILE_SHARE_WRITE);
1615 conflict |= mask_conflict(
1616 access_mask, e_access_mask, FILE_READ_DATA | FILE_EXECUTE,
1617 share_access, e_share_access, FILE_SHARE_READ);
1618 conflict |= mask_conflict(
1619 access_mask, e_access_mask, DELETE_ACCESS,
1620 share_access, e_share_access, FILE_SHARE_DELETE);
1622 DBG_DEBUG("conflict=%s\n", conflict ? "true" : "false");
1626 #if defined(DEVELOPER)
1628 struct validate_my_share_entries_state {
1629 struct smbd_server_connection *sconn;
1631 struct server_id self;
1634 static bool validate_my_share_entries_fn(
1635 struct share_mode_entry *e,
1639 struct validate_my_share_entries_state *state = private_data;
1642 if (!server_id_equal(&state->self, &e->pid)) {
1646 if (e->op_mid == 0) {
1647 /* INTERNAL_OPEN_ONLY */
1651 fsp = file_find_dif(state->sconn, state->fid, e->share_file_id);
1653 DBG_ERR("PANIC : %s\n",
1654 share_mode_str(talloc_tos(), 0, &state->fid, e));
1655 smb_panic("validate_my_share_entries: Cannot match a "
1656 "share entry with an open file\n");
1659 if (((uint16_t)fsp->oplock_type) != e->op_type) {
1668 DBG_ERR("validate_my_share_entries: PANIC : %s\n",
1669 share_mode_str(talloc_tos(), 0, &state->fid, e));
1670 str = talloc_asprintf(talloc_tos(),
1671 "validate_my_share_entries: "
1672 "file %s, oplock_type = 0x%x, op_type = 0x%x\n",
1673 fsp->fsp_name->base_name,
1674 (unsigned int)fsp->oplock_type,
1675 (unsigned int)e->op_type);
1684 * Allowed access mask for stat opens relevant to oplocks
1686 bool is_oplock_stat_open(uint32_t access_mask)
1688 const uint32_t stat_open_bits =
1689 (SYNCHRONIZE_ACCESS|
1690 FILE_READ_ATTRIBUTES|
1691 FILE_WRITE_ATTRIBUTES);
1693 return (((access_mask & stat_open_bits) != 0) &&
1694 ((access_mask & ~stat_open_bits) == 0));
1698 * Allowed access mask for stat opens relevant to leases
1700 bool is_lease_stat_open(uint32_t access_mask)
1702 const uint32_t stat_open_bits =
1703 (SYNCHRONIZE_ACCESS|
1704 FILE_READ_ATTRIBUTES|
1705 FILE_WRITE_ATTRIBUTES|
1706 READ_CONTROL_ACCESS);
1708 return (((access_mask & stat_open_bits) != 0) &&
1709 ((access_mask & ~stat_open_bits) == 0));
1712 struct has_delete_on_close_state {
1716 static bool has_delete_on_close_fn(
1717 struct share_mode_entry *e,
1721 struct has_delete_on_close_state *state = private_data;
1722 state->ret = !share_entry_stale_pid(e);
1726 static bool has_delete_on_close(struct share_mode_lock *lck,
1729 struct has_delete_on_close_state state = { .ret = false };
1732 if (!is_delete_on_close_set(lck, name_hash)) {
1736 ok= share_mode_forall_entries(lck, has_delete_on_close_fn, &state);
1738 DBG_DEBUG("share_mode_forall_entries failed\n");
1744 static void share_mode_flags_get(
1746 uint32_t *access_mask,
1747 uint32_t *share_mode,
1748 uint32_t *lease_type)
1750 if (access_mask != NULL) {
1752 ((flags & SHARE_MODE_ACCESS_READ) ?
1753 FILE_READ_DATA : 0) |
1754 ((flags & SHARE_MODE_ACCESS_WRITE) ?
1755 FILE_WRITE_DATA : 0) |
1756 ((flags & SHARE_MODE_ACCESS_DELETE) ?
1759 if (share_mode != NULL) {
1761 ((flags & SHARE_MODE_SHARE_READ) ?
1762 FILE_SHARE_READ : 0) |
1763 ((flags & SHARE_MODE_SHARE_WRITE) ?
1764 FILE_SHARE_WRITE : 0) |
1765 ((flags & SHARE_MODE_SHARE_DELETE) ?
1766 FILE_SHARE_DELETE : 0);
1768 if (lease_type != NULL) {
1770 ((flags & SHARE_MODE_LEASE_READ) ?
1771 SMB2_LEASE_READ : 0) |
1772 ((flags & SHARE_MODE_LEASE_WRITE) ?
1773 SMB2_LEASE_WRITE : 0) |
1774 ((flags & SHARE_MODE_LEASE_HANDLE) ?
1775 SMB2_LEASE_HANDLE : 0);
1779 static uint16_t share_mode_flags_set(
1781 uint32_t access_mask,
1782 uint32_t share_mode,
1783 uint32_t lease_type)
1785 if (access_mask != UINT32_MAX) {
1786 flags &= ~(SHARE_MODE_ACCESS_READ|
1787 SHARE_MODE_ACCESS_WRITE|
1788 SHARE_MODE_ACCESS_DELETE);
1789 flags |= (access_mask & (FILE_READ_DATA | FILE_EXECUTE)) ?
1790 SHARE_MODE_ACCESS_READ : 0;
1791 flags |= (access_mask & (FILE_WRITE_DATA | FILE_APPEND_DATA)) ?
1792 SHARE_MODE_ACCESS_WRITE : 0;
1793 flags |= (access_mask & (DELETE_ACCESS)) ?
1794 SHARE_MODE_ACCESS_DELETE : 0;
1796 if (share_mode != UINT32_MAX) {
1797 flags &= ~(SHARE_MODE_SHARE_READ|
1798 SHARE_MODE_SHARE_WRITE|
1799 SHARE_MODE_SHARE_DELETE);
1800 flags |= (share_mode & FILE_SHARE_READ) ?
1801 SHARE_MODE_SHARE_READ : 0;
1802 flags |= (share_mode & FILE_SHARE_WRITE) ?
1803 SHARE_MODE_SHARE_WRITE : 0;
1804 flags |= (share_mode & FILE_SHARE_DELETE) ?
1805 SHARE_MODE_SHARE_DELETE : 0;
1807 if (lease_type != UINT32_MAX) {
1808 flags &= ~(SHARE_MODE_LEASE_READ|
1809 SHARE_MODE_LEASE_WRITE|
1810 SHARE_MODE_LEASE_HANDLE);
1811 flags |= (lease_type & SMB2_LEASE_READ) ?
1812 SHARE_MODE_LEASE_READ : 0;
1813 flags |= (lease_type & SMB2_LEASE_WRITE) ?
1814 SHARE_MODE_LEASE_WRITE : 0;
1815 flags |= (lease_type & SMB2_LEASE_HANDLE) ?
1816 SHARE_MODE_LEASE_HANDLE : 0;
1822 static uint16_t share_mode_flags_restrict(
1824 uint32_t access_mask,
1825 uint32_t share_mode,
1826 uint32_t lease_type)
1828 uint32_t existing_access_mask, existing_share_mode;
1829 uint32_t existing_lease_type;
1832 share_mode_flags_get(
1834 &existing_access_mask,
1835 &existing_share_mode,
1836 &existing_lease_type);
1838 existing_access_mask |= access_mask;
1839 if (access_mask & conflicting_access) {
1840 existing_share_mode &= share_mode;
1842 existing_lease_type |= lease_type;
1844 ret = share_mode_flags_set(
1846 existing_access_mask,
1847 existing_share_mode,
1848 existing_lease_type);
1852 /****************************************************************************
1853 Deal with share modes
1854 Invariant: Share mode must be locked on entry and exit.
1855 Returns -1 on error, or number of share modes on success (may be zero).
1856 ****************************************************************************/
1858 struct open_mode_check_state {
1860 uint32_t access_mask;
1861 uint32_t share_access;
1862 uint32_t lease_type;
1865 static bool open_mode_check_fn(
1866 struct share_mode_entry *e,
1870 struct open_mode_check_state *state = private_data;
1871 bool disconnected, stale;
1872 uint32_t access_mask, share_access, lease_type;
1874 disconnected = server_id_is_disconnected(&e->pid);
1879 access_mask = state->access_mask | e->access_mask;
1880 share_access = state->share_access;
1881 if (e->access_mask & conflicting_access) {
1882 share_access &= e->share_access;
1884 lease_type = state->lease_type | get_lease_type(e, state->fid);
1886 if ((access_mask == state->access_mask) &&
1887 (share_access == state->share_access) &&
1888 (lease_type == state->lease_type)) {
1892 stale = share_entry_stale_pid(e);
1897 state->access_mask = access_mask;
1898 state->share_access = share_access;
1899 state->lease_type = lease_type;
1904 static NTSTATUS open_mode_check(connection_struct *conn,
1905 struct share_mode_lock *lck,
1906 uint32_t access_mask,
1907 uint32_t share_access)
1909 struct share_mode_data *d = lck->data;
1910 struct open_mode_check_state state;
1912 bool ok, conflict, have_share_entries;
1914 if (is_oplock_stat_open(access_mask)) {
1915 /* Stat open that doesn't trigger oplock breaks or share mode
1916 * checks... ! JRA. */
1917 return NT_STATUS_OK;
1921 * Check if the share modes will give us access.
1924 #if defined(DEVELOPER)
1926 struct validate_my_share_entries_state validate_state = {
1927 .sconn = conn->sconn,
1929 .self = messaging_server_id(conn->sconn->msg_ctx),
1931 ok = share_mode_forall_entries(
1932 lck, validate_my_share_entries_fn, &validate_state);
1937 have_share_entries = share_mode_have_entries(lck);
1938 if (!have_share_entries) {
1940 * This is a fresh share mode lock where no conflicts
1943 return NT_STATUS_OK;
1946 share_mode_flags_get(
1947 d->flags, &state.access_mask, &state.share_access, NULL);
1949 conflict = share_conflict(
1955 DBG_DEBUG("No conflict due to share_mode_flags access\n");
1956 return NT_STATUS_OK;
1959 state = (struct open_mode_check_state) {
1961 .share_access = (FILE_SHARE_READ|
1967 * Walk the share mode array to recalculate d->flags
1970 ok = share_mode_forall_entries(lck, open_mode_check_fn, &state);
1972 DBG_DEBUG("share_mode_forall_entries failed\n");
1973 return NT_STATUS_INTERNAL_ERROR;
1976 new_flags = share_mode_flags_set(
1977 0, state.access_mask, state.share_access, state.lease_type);
1978 if (new_flags == d->flags) {
1980 * We only end up here if we had a sharing violation
1981 * from d->flags and have recalculated it.
1983 return NT_STATUS_SHARING_VIOLATION;
1986 d->flags = new_flags;
1989 conflict = share_conflict(
1995 DBG_DEBUG("No conflict due to share_mode_flags access\n");
1996 return NT_STATUS_OK;
1999 return NT_STATUS_SHARING_VIOLATION;
2003 * Send a break message to the oplock holder and delay the open for
2007 NTSTATUS send_break_message(struct messaging_context *msg_ctx,
2008 const struct file_id *id,
2009 const struct share_mode_entry *exclusive,
2012 struct oplock_break_message msg = {
2014 .share_file_id = exclusive->share_file_id,
2015 .break_to = break_to,
2017 enum ndr_err_code ndr_err;
2022 struct server_id_buf buf;
2023 DBG_DEBUG("Sending break message to %s\n",
2024 server_id_str_buf(exclusive->pid, &buf));
2025 NDR_PRINT_DEBUG(oplock_break_message, &msg);
2028 ndr_err = ndr_push_struct_blob(
2032 (ndr_push_flags_fn_t)ndr_push_oplock_break_message);
2033 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
2034 DBG_WARNING("ndr_push_oplock_break_message failed: %s\n",
2035 ndr_errstr(ndr_err));
2036 return ndr_map_error2ntstatus(ndr_err);
2039 status = messaging_send(
2040 msg_ctx, exclusive->pid, MSG_SMB_BREAK_REQUEST, &blob);
2041 TALLOC_FREE(blob.data);
2042 if (!NT_STATUS_IS_OK(status)) {
2043 DEBUG(3, ("Could not send oplock break message: %s\n",
2044 nt_errstr(status)));
2050 struct validate_oplock_types_state {
2056 uint32_t num_non_stat_opens;
2059 static bool validate_oplock_types_fn(
2060 struct share_mode_entry *e,
2064 struct validate_oplock_types_state *state = private_data;
2066 if (e->op_mid == 0) {
2067 /* INTERNAL_OPEN_ONLY */
2071 if (e->op_type == NO_OPLOCK && is_oplock_stat_open(e->access_mask)) {
2073 * We ignore stat opens in the table - they always
2074 * have NO_OPLOCK and never get or cause breaks. JRA.
2079 state->num_non_stat_opens += 1;
2081 if (BATCH_OPLOCK_TYPE(e->op_type)) {
2082 /* batch - can only be one. */
2083 if (share_entry_stale_pid(e)) {
2084 DBG_DEBUG("Found stale batch oplock\n");
2087 if (state->ex_or_batch ||
2091 DBG_ERR("Bad batch oplock entry\n");
2092 state->valid = false;
2095 state->batch = true;
2098 if (EXCLUSIVE_OPLOCK_TYPE(e->op_type)) {
2099 if (share_entry_stale_pid(e)) {
2100 DBG_DEBUG("Found stale duplicate oplock\n");
2103 /* Exclusive or batch - can only be one. */
2104 if (state->ex_or_batch ||
2107 DBG_ERR("Bad exclusive or batch oplock entry\n");
2108 state->valid = false;
2111 state->ex_or_batch = true;
2114 if (LEVEL_II_OPLOCK_TYPE(e->op_type)) {
2115 if (state->batch || state->ex_or_batch) {
2116 if (share_entry_stale_pid(e)) {
2117 DBG_DEBUG("Found stale LevelII oplock\n");
2120 DBG_DEBUG("Bad levelII oplock entry\n");
2121 state->valid = false;
2124 state->level2 = true;
2127 if (e->op_type == NO_OPLOCK) {
2128 if (state->batch || state->ex_or_batch) {
2129 if (share_entry_stale_pid(e)) {
2130 DBG_DEBUG("Found stale NO_OPLOCK entry\n");
2133 DBG_ERR("Bad no oplock entry\n");
2134 state->valid = false;
2137 state->no_oplock = true;
2144 * Do internal consistency checks on the share mode for a file.
2147 static bool validate_oplock_types(struct share_mode_lock *lck)
2149 struct validate_oplock_types_state state = { .valid = true };
2152 ok = share_mode_forall_entries(lck, validate_oplock_types_fn, &state);
2154 DBG_DEBUG("share_mode_forall_entries failed\n");
2158 DBG_DEBUG("Got invalid oplock configuration\n");
2162 if ((state.batch || state.ex_or_batch) &&
2163 (state.num_non_stat_opens != 1)) {
2164 DBG_WARNING("got batch (%d) or ex (%d) non-exclusively "
2167 (int)state.ex_or_batch,
2168 state.num_non_stat_opens);
2175 static bool is_same_lease(const files_struct *fsp,
2176 const struct share_mode_entry *e,
2177 const struct smb2_lease *lease)
2179 if (e->op_type != LEASE_OPLOCK) {
2182 if (lease == NULL) {
2186 return smb2_lease_equal(fsp_client_guid(fsp),
2192 static bool file_has_brlocks(files_struct *fsp)
2194 struct byte_range_lock *br_lck;
2196 br_lck = brl_get_locks_readonly(fsp);
2200 return (brl_num_locks(br_lck) > 0);
2203 struct fsp_lease *find_fsp_lease(struct files_struct *new_fsp,
2204 const struct smb2_lease_key *key,
2205 uint32_t current_state,
2206 uint16_t lease_version,
2207 uint16_t lease_epoch)
2209 struct files_struct *fsp;
2212 * TODO: Measure how expensive this loop is with thousands of open
2216 for (fsp = file_find_di_first(new_fsp->conn->sconn, new_fsp->file_id);
2218 fsp = file_find_di_next(fsp)) {
2220 if (fsp == new_fsp) {
2223 if (fsp->oplock_type != LEASE_OPLOCK) {
2226 if (smb2_lease_key_equal(&fsp->lease->lease.lease_key, key)) {
2227 fsp->lease->ref_count += 1;
2232 /* Not found - must be leased in another smbd. */
2233 new_fsp->lease = talloc_zero(new_fsp->conn->sconn, struct fsp_lease);
2234 if (new_fsp->lease == NULL) {
2237 new_fsp->lease->ref_count = 1;
2238 new_fsp->lease->sconn = new_fsp->conn->sconn;
2239 new_fsp->lease->lease.lease_key = *key;
2240 new_fsp->lease->lease.lease_state = current_state;
2242 * We internally treat all leases as V2 and update
2243 * the epoch, but when sending breaks it matters if
2244 * the requesting lease was v1 or v2.
2246 new_fsp->lease->lease.lease_version = lease_version;
2247 new_fsp->lease->lease.lease_epoch = lease_epoch;
2248 return new_fsp->lease;
2251 static NTSTATUS try_lease_upgrade(struct files_struct *fsp,
2252 struct share_mode_lock *lck,
2253 const struct GUID *client_guid,
2254 const struct smb2_lease *lease,
2258 uint32_t current_state, breaking_to_requested, breaking_to_required;
2260 uint16_t lease_version, epoch;
2261 uint32_t existing, requested;
2264 status = leases_db_get(
2270 &breaking_to_requested,
2271 &breaking_to_required,
2274 if (!NT_STATUS_IS_OK(status)) {
2278 fsp->lease = find_fsp_lease(
2284 if (fsp->lease == NULL) {
2285 DEBUG(1, ("Did not find existing lease for file %s\n",
2287 return NT_STATUS_NO_MEMORY;
2291 * Upgrade only if the requested lease is a strict upgrade.
2293 existing = current_state;
2294 requested = lease->lease_state;
2297 * Tricky: This test makes sure that "requested" is a
2298 * strict bitwise superset of "existing".
2300 do_upgrade = ((existing & requested) == existing);
2303 * Upgrade only if there's a change.
2305 do_upgrade &= (granted != existing);
2308 * Upgrade only if other leases don't prevent what was asked
2311 do_upgrade &= (granted == requested);
2314 * only upgrade if we are not in breaking state
2316 do_upgrade &= !breaking;
2318 DEBUG(10, ("existing=%"PRIu32", requested=%"PRIu32", "
2319 "granted=%"PRIu32", do_upgrade=%d\n",
2320 existing, requested, granted, (int)do_upgrade));
2323 NTSTATUS set_status;
2325 current_state = granted;
2328 set_status = leases_db_set(
2333 breaking_to_requested,
2334 breaking_to_required,
2338 if (!NT_STATUS_IS_OK(set_status)) {
2339 DBG_DEBUG("leases_db_set failed: %s\n",
2340 nt_errstr(set_status));
2345 fsp_lease_update(fsp);
2347 return NT_STATUS_OK;
2350 static NTSTATUS grant_new_fsp_lease(struct files_struct *fsp,
2351 struct share_mode_lock *lck,
2352 const struct GUID *client_guid,
2353 const struct smb2_lease *lease,
2356 struct share_mode_data *d = lck->data;
2359 fsp->lease = talloc_zero(fsp->conn->sconn, struct fsp_lease);
2360 if (fsp->lease == NULL) {
2361 return NT_STATUS_INSUFFICIENT_RESOURCES;
2363 fsp->lease->ref_count = 1;
2364 fsp->lease->sconn = fsp->conn->sconn;
2365 fsp->lease->lease.lease_version = lease->lease_version;
2366 fsp->lease->lease.lease_key = lease->lease_key;
2367 fsp->lease->lease.lease_state = granted;
2368 fsp->lease->lease.lease_epoch = lease->lease_epoch + 1;
2370 status = leases_db_add(client_guid,
2373 fsp->lease->lease.lease_state,
2374 fsp->lease->lease.lease_version,
2375 fsp->lease->lease.lease_epoch,
2376 fsp->conn->connectpath,
2377 fsp->fsp_name->base_name,
2378 fsp->fsp_name->stream_name);
2379 if (!NT_STATUS_IS_OK(status)) {
2380 DEBUG(10, ("%s: leases_db_add failed: %s\n", __func__,
2381 nt_errstr(status)));
2382 TALLOC_FREE(fsp->lease);
2383 return NT_STATUS_INSUFFICIENT_RESOURCES;
2388 return NT_STATUS_OK;
2391 static NTSTATUS grant_fsp_lease(struct files_struct *fsp,
2392 struct share_mode_lock *lck,
2393 const struct smb2_lease *lease,
2396 const struct GUID *client_guid = fsp_client_guid(fsp);
2399 status = try_lease_upgrade(fsp, lck, client_guid, lease, granted);
2401 if (NT_STATUS_EQUAL(status, NT_STATUS_NOT_FOUND)) {
2402 status = grant_new_fsp_lease(
2403 fsp, lck, client_guid, lease, granted);
2409 static int map_lease_type_to_oplock(uint32_t lease_type)
2411 int result = NO_OPLOCK;
2413 switch (lease_type) {
2414 case SMB2_LEASE_READ|SMB2_LEASE_WRITE|SMB2_LEASE_HANDLE:
2415 result = BATCH_OPLOCK|EXCLUSIVE_OPLOCK;
2417 case SMB2_LEASE_READ|SMB2_LEASE_WRITE:
2418 result = EXCLUSIVE_OPLOCK;
2420 case SMB2_LEASE_READ|SMB2_LEASE_HANDLE:
2421 case SMB2_LEASE_READ:
2422 result = LEVEL_II_OPLOCK;
2429 struct delay_for_oplock_state {
2430 struct files_struct *fsp;
2431 const struct smb2_lease *lease;
2432 bool will_overwrite;
2433 uint32_t delay_mask;
2434 bool first_open_attempt;
2435 bool got_handle_lease;
2437 bool have_other_lease;
2441 static bool delay_for_oplock_fn(
2442 struct share_mode_entry *e,
2446 struct delay_for_oplock_state *state = private_data;
2447 struct files_struct *fsp = state->fsp;
2448 const struct smb2_lease *lease = state->lease;
2449 bool e_is_lease = (e->op_type == LEASE_OPLOCK);
2450 uint32_t e_lease_type = get_lease_type(e, fsp->file_id);
2452 bool lease_is_breaking = false;
2457 if (lease != NULL) {
2458 bool our_lease = is_same_lease(fsp, e, lease);
2460 DBG_DEBUG("Ignoring our own lease\n");
2465 status = leases_db_get(
2469 NULL, /* current_state */
2471 NULL, /* breaking_to_requested */
2472 NULL, /* breaking_to_required */
2473 NULL, /* lease_version */
2477 * leases_db_get() can return NT_STATUS_NOT_FOUND
2478 * if the share_mode_entry e is stale and the
2479 * lease record was already removed. In this case return
2480 * false so the traverse continues.
2483 if (NT_STATUS_EQUAL(status, NT_STATUS_NOT_FOUND) &&
2484 share_entry_stale_pid(e))
2486 struct GUID_txt_buf guid_strbuf;
2487 struct file_id_buf file_id_strbuf;
2488 DBG_DEBUG("leases_db_get for client_guid [%s] "
2489 "lease_key [%"PRIu64"/%"PRIu64"] "
2490 "file_id [%s] failed for stale "
2491 "share_mode_entry\n",
2492 GUID_buf_string(&e->client_guid, &guid_strbuf),
2493 e->lease_key.data[0],
2494 e->lease_key.data[1],
2495 file_id_str_buf(fsp->file_id, &file_id_strbuf));
2498 if (!NT_STATUS_IS_OK(status)) {
2499 struct GUID_txt_buf guid_strbuf;
2500 struct file_id_buf file_id_strbuf;
2501 DBG_ERR("leases_db_get for client_guid [%s] "
2502 "lease_key [%"PRIu64"/%"PRIu64"] "
2503 "file_id [%s] failed: %s\n",
2504 GUID_buf_string(&e->client_guid, &guid_strbuf),
2505 e->lease_key.data[0],
2506 e->lease_key.data[1],
2507 file_id_str_buf(fsp->file_id, &file_id_strbuf),
2509 smb_panic("leases_db_get() failed");
2513 if (!state->got_handle_lease &&
2514 ((e_lease_type & SMB2_LEASE_HANDLE) != 0) &&
2515 !share_entry_stale_pid(e)) {
2516 state->got_handle_lease = true;
2519 if (!state->got_oplock &&
2520 (e->op_type != LEASE_OPLOCK) &&
2521 !share_entry_stale_pid(e)) {
2522 state->got_oplock = true;
2525 if (!state->have_other_lease &&
2526 !is_same_lease(fsp, e, lease) &&
2527 !share_entry_stale_pid(e)) {
2528 state->have_other_lease = true;
2531 if (e_is_lease && is_lease_stat_open(fsp->access_mask)) {
2535 break_to = e_lease_type & ~state->delay_mask;
2537 if (state->will_overwrite) {
2538 break_to &= ~(SMB2_LEASE_HANDLE|SMB2_LEASE_READ);
2541 DBG_DEBUG("e_lease_type %u, will_overwrite: %u\n",
2542 (unsigned)e_lease_type,
2543 (unsigned)state->will_overwrite);
2545 if ((e_lease_type & ~break_to) == 0) {
2546 if (lease_is_breaking) {
2547 state->delay = true;
2552 if (share_entry_stale_pid(e)) {
2556 if (state->will_overwrite) {
2558 * If we break anyway break to NONE directly.
2559 * Otherwise vfs_set_filelen() will trigger the
2562 break_to &= ~(SMB2_LEASE_READ|SMB2_LEASE_WRITE);
2567 * Oplocks only support breaking to R or NONE.
2569 break_to &= ~(SMB2_LEASE_HANDLE|SMB2_LEASE_WRITE);
2572 DBG_DEBUG("breaking from %d to %d\n",
2576 fsp->conn->sconn->msg_ctx, &fsp->file_id, e, break_to);
2577 if (e_lease_type & state->delay_mask) {
2578 state->delay = true;
2580 if (lease_is_breaking && !state->first_open_attempt) {
2581 state->delay = true;
2587 static NTSTATUS delay_for_oplock(files_struct *fsp,
2589 const struct smb2_lease *lease,
2590 struct share_mode_lock *lck,
2591 bool have_sharing_violation,
2592 uint32_t create_disposition,
2593 bool first_open_attempt)
2595 struct delay_for_oplock_state state = {
2598 .first_open_attempt = first_open_attempt,
2604 if (is_oplock_stat_open(fsp->access_mask)) {
2608 state.delay_mask = have_sharing_violation ?
2609 SMB2_LEASE_HANDLE : SMB2_LEASE_WRITE;
2611 switch (create_disposition) {
2612 case FILE_SUPERSEDE:
2613 case FILE_OVERWRITE:
2614 case FILE_OVERWRITE_IF:
2615 state.will_overwrite = true;
2618 state.will_overwrite = false;
2622 ok = share_mode_forall_entries(lck, delay_for_oplock_fn, &state);
2624 return NT_STATUS_INTERNAL_ERROR;
2628 return NT_STATUS_RETRY;
2632 if (have_sharing_violation) {
2633 return NT_STATUS_SHARING_VIOLATION;
2636 if (oplock_request == LEASE_OPLOCK) {
2637 if (lease == NULL) {
2639 * The SMB2 layer should have checked this
2641 return NT_STATUS_INTERNAL_ERROR;
2644 granted = lease->lease_state;
2646 if (lp_kernel_oplocks(SNUM(fsp->conn))) {
2647 DEBUG(10, ("No lease granted because kernel oplocks are enabled\n"));
2648 granted = SMB2_LEASE_NONE;
2650 if ((granted & (SMB2_LEASE_READ|SMB2_LEASE_WRITE)) == 0) {
2651 DEBUG(10, ("No read or write lease requested\n"));
2652 granted = SMB2_LEASE_NONE;
2654 if (granted == SMB2_LEASE_WRITE) {
2655 DEBUG(10, ("pure write lease requested\n"));
2656 granted = SMB2_LEASE_NONE;
2658 if (granted == (SMB2_LEASE_WRITE|SMB2_LEASE_HANDLE)) {
2659 DEBUG(10, ("write and handle lease requested\n"));
2660 granted = SMB2_LEASE_NONE;
2663 granted = map_oplock_to_lease_type(
2664 oplock_request & ~SAMBA_PRIVATE_OPLOCK_MASK);
2667 if (lp_locking(fsp->conn->params) && file_has_brlocks(fsp)) {
2668 DBG_DEBUG("file %s has byte range locks\n",
2670 granted &= ~SMB2_LEASE_READ;
2673 if (state.have_other_lease) {
2675 * Can grant only one writer
2677 granted &= ~SMB2_LEASE_WRITE;
2680 if ((granted & SMB2_LEASE_READ) && !(granted & SMB2_LEASE_WRITE)) {
2682 (global_client_caps & CAP_LEVEL_II_OPLOCKS) &&
2683 lp_level2_oplocks(SNUM(fsp->conn));
2685 if (!allow_level2) {
2686 granted = SMB2_LEASE_NONE;
2690 if (oplock_request == LEASE_OPLOCK) {
2691 if (state.got_oplock) {
2692 granted &= ~SMB2_LEASE_HANDLE;
2695 fsp->oplock_type = LEASE_OPLOCK;
2697 status = grant_fsp_lease(fsp, lck, lease, granted);
2698 if (!NT_STATUS_IS_OK(status)) {
2703 DBG_DEBUG("lease_state=%d\n", fsp->lease->lease.lease_state);
2705 if (state.got_handle_lease) {
2706 granted = SMB2_LEASE_NONE;
2709 fsp->oplock_type = map_lease_type_to_oplock(granted);
2711 status = set_file_oplock(fsp);
2712 if (!NT_STATUS_IS_OK(status)) {
2714 * Could not get the kernel oplock
2716 fsp->oplock_type = NO_OPLOCK;
2720 if ((granted & SMB2_LEASE_READ) &&
2721 ((lck->data->flags & SHARE_MODE_LEASE_READ) == 0)) {
2722 lck->data->flags |= SHARE_MODE_LEASE_READ;
2723 lck->data->modified = true;
2726 DBG_DEBUG("oplock type 0x%x on file %s\n",
2727 fsp->oplock_type, fsp_str_dbg(fsp));
2729 return NT_STATUS_OK;
2732 static NTSTATUS handle_share_mode_lease(
2734 struct share_mode_lock *lck,
2735 uint32_t create_disposition,
2736 uint32_t access_mask,
2737 uint32_t share_access,
2739 const struct smb2_lease *lease,
2740 bool first_open_attempt)
2742 bool sharing_violation = false;
2745 status = open_mode_check(
2746 fsp->conn, lck, access_mask, share_access);
2747 if (NT_STATUS_EQUAL(status, NT_STATUS_SHARING_VIOLATION)) {
2748 sharing_violation = true;
2749 status = NT_STATUS_OK; /* handled later */
2752 if (!NT_STATUS_IS_OK(status)) {
2756 if (oplock_request == INTERNAL_OPEN_ONLY) {
2757 if (sharing_violation) {
2758 DBG_DEBUG("Sharing violation for internal open\n");
2759 return NT_STATUS_SHARING_VIOLATION;
2763 * Internal opens never do oplocks or leases. We don't
2764 * need to go through delay_for_oplock().
2766 fsp->oplock_type = NO_OPLOCK;
2768 return NT_STATUS_OK;
2771 status = delay_for_oplock(
2778 first_open_attempt);
2779 if (!NT_STATUS_IS_OK(status)) {
2783 return NT_STATUS_OK;
2786 static bool request_timed_out(struct smb_request *req, struct timeval timeout)
2788 struct timeval now, end_time;
2790 end_time = timeval_sum(&req->request_time, &timeout);
2791 return (timeval_compare(&end_time, &now) < 0);
2794 struct defer_open_state {
2795 struct smbXsrv_connection *xconn;
2799 static void defer_open_done(struct tevent_req *req);
2802 * Defer an open and watch a locking.tdb record
2804 * This defers an open that gets rescheduled once the locking.tdb record watch
2805 * is triggered by a change to the record.
2807 * It is used to defer opens that triggered an oplock break and for the SMB1
2808 * sharing violation delay.
2810 static void defer_open(struct share_mode_lock *lck,
2811 struct timeval timeout,
2812 struct smb_request *req,
2815 struct deferred_open_record *open_rec = NULL;
2816 struct timeval abs_timeout;
2817 struct defer_open_state *watch_state;
2818 struct tevent_req *watch_req;
2819 struct timeval_buf tvbuf1, tvbuf2;
2820 struct file_id_buf fbuf;
2823 abs_timeout = timeval_sum(&req->request_time, &timeout);
2825 DBG_DEBUG("request time [%s] timeout [%s] mid [%" PRIu64 "] "
2827 timeval_str_buf(&req->request_time, false, true, &tvbuf1),
2828 timeval_str_buf(&abs_timeout, false, true, &tvbuf2),
2830 file_id_str_buf(id, &fbuf));
2832 open_rec = talloc_zero(NULL, struct deferred_open_record);
2833 if (open_rec == NULL) {
2835 exit_server("talloc failed");
2838 watch_state = talloc(open_rec, struct defer_open_state);
2839 if (watch_state == NULL) {
2840 exit_server("talloc failed");
2842 watch_state->xconn = req->xconn;
2843 watch_state->mid = req->mid;
2845 DBG_DEBUG("defering mid %" PRIu64 "\n", req->mid);
2847 watch_req = share_mode_watch_send(
2851 (struct server_id){0});
2852 if (watch_req == NULL) {
2853 exit_server("Could not watch share mode record");
2855 tevent_req_set_callback(watch_req, defer_open_done, watch_state);
2857 ok = tevent_req_set_endtime(watch_req, req->sconn->ev_ctx, abs_timeout);
2859 exit_server("tevent_req_set_endtime failed");
2862 ok = push_deferred_open_message_smb(req, timeout, id, open_rec);
2865 exit_server("push_deferred_open_message_smb failed");
2869 static void defer_open_done(struct tevent_req *req)
2871 struct defer_open_state *state = tevent_req_callback_data(
2872 req, struct defer_open_state);
2876 status = share_mode_watch_recv(req, NULL, NULL);
2878 if (!NT_STATUS_IS_OK(status)) {
2879 DEBUG(5, ("dbwrap_watched_watch_recv returned %s\n",
2880 nt_errstr(status)));
2882 * Even if it failed, retry anyway. TODO: We need a way to
2883 * tell a re-scheduled open about that error.
2887 DEBUG(10, ("scheduling mid %llu\n", (unsigned long long)state->mid));
2889 ret = schedule_deferred_open_message_smb(state->xconn, state->mid);
2895 * Actually attempt the kernel oplock polling open.
2898 static void poll_open_fn(struct tevent_context *ev,
2899 struct tevent_timer *te,
2900 struct timeval current_time,
2903 struct deferred_open_record *open_rec = talloc_get_type_abort(
2904 private_data, struct deferred_open_record);
2907 TALLOC_FREE(open_rec->watch_req);
2909 ok = schedule_deferred_open_message_smb(
2910 open_rec->xconn, open_rec->mid);
2912 exit_server("schedule_deferred_open_message_smb failed");
2914 DBG_DEBUG("timer fired. Retrying open !\n");
2917 static void poll_open_done(struct tevent_req *subreq);
2920 * Reschedule an open for 1 second from now, if not timed out.
2922 static bool setup_poll_open(
2923 struct smb_request *req,
2924 struct share_mode_lock *lck,
2926 struct timeval max_timeout,
2927 struct timeval interval)
2930 struct deferred_open_record *open_rec = NULL;
2931 struct timeval endtime, next_interval;
2932 struct file_id_buf ftmp;
2934 if (request_timed_out(req, max_timeout)) {
2938 open_rec = talloc_zero(NULL, struct deferred_open_record);
2939 if (open_rec == NULL) {
2940 DBG_WARNING("talloc failed\n");
2943 open_rec->xconn = req->xconn;
2944 open_rec->mid = req->mid;
2947 * Make sure open_rec->te does not come later than the
2948 * request's maximum endtime.
2951 endtime = timeval_sum(&req->request_time, &max_timeout);
2952 next_interval = timeval_current_ofs(interval.tv_sec, interval.tv_usec);
2953 next_interval = timeval_min(&endtime, &next_interval);
2955 open_rec->te = tevent_add_timer(
2961 if (open_rec->te == NULL) {
2962 DBG_WARNING("tevent_add_timer failed\n");
2963 TALLOC_FREE(open_rec);
2968 open_rec->watch_req = share_mode_watch_send(
2972 (struct server_id) {0});
2973 if (open_rec->watch_req == NULL) {
2974 DBG_WARNING("share_mode_watch_send failed\n");
2975 TALLOC_FREE(open_rec);
2978 tevent_req_set_callback(
2979 open_rec->watch_req, poll_open_done, open_rec);
2982 ok = push_deferred_open_message_smb(req, max_timeout, id, open_rec);
2984 DBG_WARNING("push_deferred_open_message_smb failed\n");
2985 TALLOC_FREE(open_rec);
2989 DBG_DEBUG("poll request time [%s] mid [%" PRIu64 "] file_id [%s]\n",
2990 timeval_string(talloc_tos(), &req->request_time, false),
2992 file_id_str_buf(id, &ftmp));
2997 static void poll_open_done(struct tevent_req *subreq)
2999 struct deferred_open_record *open_rec = tevent_req_callback_data(
3000 subreq, struct deferred_open_record);
3004 status = share_mode_watch_recv(subreq, NULL, NULL);
3005 TALLOC_FREE(subreq);
3006 DBG_DEBUG("dbwrap_watched_watch_recv returned %s\n",
3009 ok = schedule_deferred_open_message_smb(
3010 open_rec->xconn, open_rec->mid);
3012 exit_server("schedule_deferred_open_message_smb failed");
3016 bool defer_smb1_sharing_violation(struct smb_request *req)
3021 if (!lp_defer_sharing_violations()) {
3026 * Try every 200msec up to (by default) one second. To be
3027 * precise, according to behaviour note <247> in [MS-CIFS],
3028 * the server tries 5 times. But up to one second should be
3032 timeout_usecs = lp_parm_int(
3036 SHARING_VIOLATION_USEC_WAIT);
3038 ok = setup_poll_open(
3041 (struct file_id) {0},
3042 (struct timeval) { .tv_usec = timeout_usecs },
3043 (struct timeval) { .tv_usec = 200000 });
3047 /****************************************************************************
3048 On overwrite open ensure that the attributes match.
3049 ****************************************************************************/
3051 static bool open_match_attributes(connection_struct *conn,
3052 uint32_t old_dos_attr,
3053 uint32_t new_dos_attr,
3054 mode_t new_unx_mode,
3055 mode_t *returned_unx_mode)
3057 uint32_t noarch_old_dos_attr, noarch_new_dos_attr;
3059 noarch_old_dos_attr = (old_dos_attr & ~FILE_ATTRIBUTE_ARCHIVE);
3060 noarch_new_dos_attr = (new_dos_attr & ~FILE_ATTRIBUTE_ARCHIVE);
3062 if((noarch_old_dos_attr == 0 && noarch_new_dos_attr != 0) ||
3063 (noarch_old_dos_attr != 0 && ((noarch_old_dos_attr & noarch_new_dos_attr) == noarch_old_dos_attr))) {
3064 *returned_unx_mode = new_unx_mode;
3066 *returned_unx_mode = (mode_t)0;
3069 DEBUG(10,("open_match_attributes: old_dos_attr = 0x%x, "
3070 "new_dos_attr = 0x%x "
3071 "returned_unx_mode = 0%o\n",
3072 (unsigned int)old_dos_attr,
3073 (unsigned int)new_dos_attr,
3074 (unsigned int)*returned_unx_mode ));
3076 /* If we're mapping SYSTEM and HIDDEN ensure they match. */
3077 if (lp_map_system(SNUM(conn)) || lp_store_dos_attributes(SNUM(conn))) {
3078 if ((old_dos_attr & FILE_ATTRIBUTE_SYSTEM) &&
3079 !(new_dos_attr & FILE_ATTRIBUTE_SYSTEM)) {
3083 if (lp_map_hidden(SNUM(conn)) || lp_store_dos_attributes(SNUM(conn))) {
3084 if ((old_dos_attr & FILE_ATTRIBUTE_HIDDEN) &&
3085 !(new_dos_attr & FILE_ATTRIBUTE_HIDDEN)) {
3092 static void schedule_defer_open(struct share_mode_lock *lck,
3094 struct smb_request *req)
3096 /* This is a relative time, added to the absolute
3097 request_time value to get the absolute timeout time.
3098 Note that if this is the second or greater time we enter
3099 this codepath for this particular request mid then
3100 request_time is left as the absolute time of the *first*
3101 time this request mid was processed. This is what allows
3102 the request to eventually time out. */
3104 struct timeval timeout;
3106 /* Normally the smbd we asked should respond within
3107 * OPLOCK_BREAK_TIMEOUT seconds regardless of whether
3108 * the client did, give twice the timeout as a safety
3109 * measure here in case the other smbd is stuck
3110 * somewhere else. */
3112 timeout = timeval_set(OPLOCK_BREAK_TIMEOUT*2, 0);
3114 if (request_timed_out(req, timeout)) {
3118 defer_open(lck, timeout, req, id);
3121 /****************************************************************************
3122 Reschedule an open call that went asynchronous.
3123 ****************************************************************************/
3125 static void schedule_async_open_timer(struct tevent_context *ev,
3126 struct tevent_timer *te,
3127 struct timeval current_time,
3130 exit_server("async open timeout");
3133 static void schedule_async_open(struct smb_request *req)
3135 struct deferred_open_record *open_rec = NULL;
3136 struct timeval timeout = timeval_set(20, 0);
3139 if (request_timed_out(req, timeout)) {
3143 open_rec = talloc_zero(NULL, struct deferred_open_record);
3144 if (open_rec == NULL) {
3145 exit_server("deferred_open_record_create failed");
3147 open_rec->async_open = true;
3149 ok = push_deferred_open_message_smb(
3150 req, timeout, (struct file_id){0}, open_rec);
3152 exit_server("push_deferred_open_message_smb failed");
3155 open_rec->te = tevent_add_timer(req->sconn->ev_ctx,
3157 timeval_current_ofs(20, 0),
3158 schedule_async_open_timer,
3160 if (open_rec->te == NULL) {
3161 exit_server("tevent_add_timer failed");
3165 /****************************************************************************
3166 Work out what access_mask to use from what the client sent us.
3167 ****************************************************************************/
3169 static NTSTATUS smbd_calculate_maximum_allowed_access(
3170 connection_struct *conn,
3171 struct files_struct *dirfsp,
3172 const struct smb_filename *smb_fname,
3174 uint32_t *p_access_mask)
3176 struct security_descriptor *sd;
3177 uint32_t access_granted;
3180 SMB_ASSERT(dirfsp == conn->cwd_fsp);
3182 if (!use_privs && (get_current_uid(conn) == (uid_t)0)) {
3183 *p_access_mask |= FILE_GENERIC_ALL;
3184 return NT_STATUS_OK;
3187 status = SMB_VFS_GET_NT_ACL_AT(conn,
3196 if (NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
3198 * File did not exist
3200 *p_access_mask = FILE_GENERIC_ALL;
3201 return NT_STATUS_OK;
3203 if (!NT_STATUS_IS_OK(status)) {
3204 DEBUG(10,("Could not get acl on file %s: %s\n",
3205 smb_fname_str_dbg(smb_fname),
3206 nt_errstr(status)));
3207 return NT_STATUS_ACCESS_DENIED;
3211 * If we can access the path to this file, by
3212 * default we have FILE_READ_ATTRIBUTES from the
3213 * containing directory. See the section:
3214 * "Algorithm to Check Access to an Existing File"
3217 * se_file_access_check()
3218 * also takes care of owner WRITE_DAC and READ_CONTROL.
3220 status = se_file_access_check(sd,
3221 get_current_nttok(conn),
3223 (*p_access_mask & ~FILE_READ_ATTRIBUTES),
3228 if (!NT_STATUS_IS_OK(status)) {
3229 DEBUG(10, ("Access denied on file %s: "
3230 "when calculating maximum access\n",
3231 smb_fname_str_dbg(smb_fname)));
3232 return NT_STATUS_ACCESS_DENIED;
3234 *p_access_mask = (access_granted | FILE_READ_ATTRIBUTES);
3236 if (!(access_granted & DELETE_ACCESS)) {
3237 if (can_delete_file_in_directory(conn,
3241 *p_access_mask |= DELETE_ACCESS;
3245 return NT_STATUS_OK;
3248 NTSTATUS smbd_calculate_access_mask(connection_struct *conn,
3249 struct files_struct *dirfsp,
3250 const struct smb_filename *smb_fname,
3252 uint32_t access_mask,
3253 uint32_t *access_mask_out)
3256 uint32_t orig_access_mask = access_mask;
3257 uint32_t rejected_share_access;
3259 SMB_ASSERT(dirfsp == conn->cwd_fsp);
3261 if (access_mask & SEC_MASK_INVALID) {
3262 DBG_DEBUG("access_mask [%8x] contains invalid bits\n",
3264 return NT_STATUS_ACCESS_DENIED;
3268 * Convert GENERIC bits to specific bits.
3271 se_map_generic(&access_mask, &file_generic_mapping);
3273 /* Calculate MAXIMUM_ALLOWED_ACCESS if requested. */
3274 if (access_mask & MAXIMUM_ALLOWED_ACCESS) {
3276 status = smbd_calculate_maximum_allowed_access(conn,
3282 if (!NT_STATUS_IS_OK(status)) {
3286 access_mask &= conn->share_access;
3289 rejected_share_access = access_mask & ~(conn->share_access);
3291 if (rejected_share_access) {
3292 DEBUG(10, ("smbd_calculate_access_mask: Access denied on "
3293 "file %s: rejected by share access mask[0x%08X] "
3294 "orig[0x%08X] mapped[0x%08X] reject[0x%08X]\n",
3295 smb_fname_str_dbg(smb_fname),
3297 orig_access_mask, access_mask,
3298 rejected_share_access));
3299 return NT_STATUS_ACCESS_DENIED;
3302 *access_mask_out = access_mask;
3303 return NT_STATUS_OK;
3306 /****************************************************************************
3307 Remove the deferred open entry under lock.
3308 ****************************************************************************/
3310 /****************************************************************************
3311 Return true if this is a state pointer to an asynchronous create.
3312 ****************************************************************************/
3314 bool is_deferred_open_async(const struct deferred_open_record *rec)
3316 return rec->async_open;
3319 static bool clear_ads(uint32_t create_disposition)
3323 switch (create_disposition) {
3324 case FILE_SUPERSEDE:
3325 case FILE_OVERWRITE_IF:
3326 case FILE_OVERWRITE:
3335 static int disposition_to_open_flags(uint32_t create_disposition)
3340 * Currently we're using FILE_SUPERSEDE as the same as
3341 * FILE_OVERWRITE_IF but they really are
3342 * different. FILE_SUPERSEDE deletes an existing file
3343 * (requiring delete access) then recreates it.
3346 switch (create_disposition) {
3347 case FILE_SUPERSEDE:
3348 case FILE_OVERWRITE_IF:
3350 * If file exists replace/overwrite. If file doesn't
3353 ret = O_CREAT|O_TRUNC;
3358 * If file exists open. If file doesn't exist error.
3363 case FILE_OVERWRITE:
3365 * If file exists overwrite. If file doesn't exist
3373 * If file exists error. If file doesn't exist create.
3375 ret = O_CREAT|O_EXCL;
3380 * If file exists open. If file doesn't exist create.
3388 static int calculate_open_access_flags(uint32_t access_mask,
3389 uint32_t private_flags)
3391 bool need_write, need_read;
3394 * Note that we ignore the append flag as append does not
3395 * mean the same thing under DOS and Unix.
3398 need_write = (access_mask & (FILE_WRITE_DATA | FILE_APPEND_DATA));
3403 /* DENY_DOS opens are always underlying read-write on the
3404 file handle, no matter what the requested access mask
3408 ((private_flags & NTCREATEX_OPTIONS_PRIVATE_DENY_DOS) ||
3409 access_mask & (FILE_READ_ATTRIBUTES|FILE_READ_DATA|
3410 FILE_READ_EA|FILE_EXECUTE));
3418 /****************************************************************************
3419 Open a file with a share mode. Passed in an already created files_struct *.
3420 ****************************************************************************/
3422 static NTSTATUS open_file_ntcreate(connection_struct *conn,
3423 struct smb_request *req,
3424 uint32_t access_mask, /* access bits (FILE_READ_DATA etc.) */
3425 uint32_t share_access, /* share constants (FILE_SHARE_READ etc) */
3426 uint32_t create_disposition, /* FILE_OPEN_IF etc. */
3427 uint32_t create_options, /* options such as delete on close. */
3428 uint32_t new_dos_attributes, /* attributes used for new file. */
3429 int oplock_request, /* internal Samba oplock codes. */
3430 const struct smb2_lease *lease,
3431 /* Information (FILE_EXISTS etc.) */
3432 uint32_t private_flags, /* Samba specific flags. */
3436 struct smb_filename *smb_fname = fsp->fsp_name;
3439 bool file_existed = VALID_STAT(smb_fname->st);
3440 bool def_acl = False;
3441 bool posix_open = False;
3442 bool new_file_created = False;
3443 bool first_open_attempt = true;
3444 NTSTATUS fsp_open = NT_STATUS_ACCESS_DENIED;
3445 mode_t new_unx_mode = (mode_t)0;
3446 mode_t unx_mode = (mode_t)0;
3448 uint32_t existing_dos_attributes = 0;
3449 struct share_mode_lock *lck = NULL;
3450 uint32_t open_access_mask = access_mask;
3452 struct smb_filename *parent_dir_fname = NULL;
3453 SMB_STRUCT_STAT saved_stat = smb_fname->st;
3454 struct timespec old_write_time;
3456 bool setup_poll = false;
3459 SMB_ASSERT(fsp->dirfsp == conn->cwd_fsp);
3461 if (conn->printer) {
3463 * Printers are handled completely differently.
3464 * Most of the passed parameters are ignored.
3468 *pinfo = FILE_WAS_CREATED;
3471 DEBUG(10, ("open_file_ntcreate: printer open fname=%s\n",
3472 smb_fname_str_dbg(smb_fname)));
3475 DEBUG(0,("open_file_ntcreate: printer open without "
3476 "an SMB request!\n"));
3477 return NT_STATUS_INTERNAL_ERROR;
3480 return print_spool_open(fsp, smb_fname->base_name,
3484 ok = parent_smb_fname(talloc_tos(),
3489 return NT_STATUS_NO_MEMORY;
3492 if (new_dos_attributes & FILE_FLAG_POSIX_SEMANTICS) {
3494 unx_mode = (mode_t)(new_dos_attributes & ~FILE_FLAG_POSIX_SEMANTICS);
3495 new_dos_attributes = 0;
3497 /* Windows allows a new file to be created and
3498 silently removes a FILE_ATTRIBUTE_DIRECTORY
3499 sent by the client. Do the same. */
3501 new_dos_attributes &= ~FILE_ATTRIBUTE_DIRECTORY;
3503 /* We add FILE_ATTRIBUTE_ARCHIVE to this as this mode is only used if the file is
3505 unx_mode = unix_mode(conn, new_dos_attributes | FILE_ATTRIBUTE_ARCHIVE,
3506 smb_fname, parent_dir_fname);
3509 DEBUG(10, ("open_file_ntcreate: fname=%s, dos_attrs=0x%x "
3510 "access_mask=0x%x share_access=0x%x "
3511 "create_disposition = 0x%x create_options=0x%x "
3512 "unix mode=0%o oplock_request=%d private_flags = 0x%x\n",
3513 smb_fname_str_dbg(smb_fname), new_dos_attributes,
3514 access_mask, share_access, create_disposition,
3515 create_options, (unsigned int)unx_mode, oplock_request,
3516 (unsigned int)private_flags));
3519 /* Ensure req == NULL means INTERNAL_OPEN_ONLY */
3520 SMB_ASSERT(oplock_request == INTERNAL_OPEN_ONLY);
3522 /* And req != NULL means no INTERNAL_OPEN_ONLY */
3523 SMB_ASSERT(((oplock_request & INTERNAL_OPEN_ONLY) == 0));
3527 * Only non-internal opens can be deferred at all
3531 struct deferred_open_record *open_rec;
3532 if (get_deferred_open_message_state(req, NULL, &open_rec)) {
3534 /* If it was an async create retry, the file
3537 if (is_deferred_open_async(open_rec)) {
3538 SET_STAT_INVALID(smb_fname->st);
3539 file_existed = false;
3542 /* Ensure we don't reprocess this message. */
3543 remove_deferred_open_message_smb(req->xconn, req->mid);
3545 first_open_attempt = false;
3550 new_dos_attributes &= SAMBA_ATTRIBUTES_MASK;
3553 * Only use stored DOS attributes for checks
3554 * against requested attributes (below via
3555 * open_match_attributes()), cf bug #11992
3556 * for details. -slow
3560 status = SMB_VFS_GET_DOS_ATTRIBUTES(conn, smb_fname, &attr);
3561 if (NT_STATUS_IS_OK(status)) {
3562 existing_dos_attributes = attr;
3567 /* ignore any oplock requests if oplocks are disabled */
3568 if (!lp_oplocks(SNUM(conn)) ||
3569 IS_VETO_OPLOCK_PATH(conn, smb_fname->base_name)) {
3570 /* Mask off everything except the private Samba bits. */
3571 oplock_request &= SAMBA_PRIVATE_OPLOCK_MASK;
3574 /* this is for OS/2 long file names - say we don't support them */
3575 if (req != NULL && !req->posix_pathnames &&
3576 strstr(smb_fname->base_name,".+,;=[].")) {
3577 /* OS/2 Workplace shell fix may be main code stream in a later
3579 DEBUG(5,("open_file_ntcreate: OS/2 long filenames are not "
3581 if (use_nt_status()) {
3582 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3584 return NT_STATUS_DOS(ERRDOS, ERRcannotopen);
3587 switch( create_disposition ) {
3589 /* If file exists open. If file doesn't exist error. */
3590 if (!file_existed) {
3591 DEBUG(5,("open_file_ntcreate: FILE_OPEN "
3592 "requested for file %s and file "
3594 smb_fname_str_dbg(smb_fname)));
3596 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3600 case FILE_OVERWRITE:
3601 /* If file exists overwrite. If file doesn't exist
3603 if (!file_existed) {
3604 DEBUG(5,("open_file_ntcreate: FILE_OVERWRITE "
3605 "requested for file %s and file "
3607 smb_fname_str_dbg(smb_fname) ));
3609 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3614 /* If file exists error. If file doesn't exist
3617 DEBUG(5,("open_file_ntcreate: FILE_CREATE "
3618 "requested for file %s and file "
3619 "already exists.\n",
3620 smb_fname_str_dbg(smb_fname)));
3621 if (S_ISDIR(smb_fname->st.st_ex_mode)) {
3626 return map_nt_error_from_unix(errno);
3630 case FILE_SUPERSEDE:
3631 case FILE_OVERWRITE_IF:
3635 return NT_STATUS_INVALID_PARAMETER;
3638 flags2 = disposition_to_open_flags(create_disposition);
3640 /* We only care about matching attributes on file exists and
3643 if (!posix_open && file_existed &&
3644 ((create_disposition == FILE_OVERWRITE) ||
3645 (create_disposition == FILE_OVERWRITE_IF))) {
3646 if (!open_match_attributes(conn, existing_dos_attributes,
3648 unx_mode, &new_unx_mode)) {
3649 DEBUG(5,("open_file_ntcreate: attributes mismatch "
3650 "for file %s (%x %x) (0%o, 0%o)\n",
3651 smb_fname_str_dbg(smb_fname),
3652 existing_dos_attributes,
3654 (unsigned int)smb_fname->st.st_ex_mode,
3655 (unsigned int)unx_mode ));
3657 return NT_STATUS_ACCESS_DENIED;
3661 status = smbd_calculate_access_mask(conn,
3667 if (!NT_STATUS_IS_OK(status)) {
3668 DEBUG(10, ("open_file_ntcreate: smbd_calculate_access_mask "
3669 "on file %s returned %s\n",
3670 smb_fname_str_dbg(smb_fname), nt_errstr(status)));
3674 open_access_mask = access_mask;
3676 if (flags2 & O_TRUNC) {
3677 open_access_mask |= FILE_WRITE_DATA; /* This will cause oplock breaks. */
3682 * stat opens on existing files don't get oplocks.
3683 * They can get leases.
3685 * Note that we check for stat open on the *open_access_mask*,
3686 * i.e. the access mask we actually used to do the open,
3687 * not the one the client asked for (which is in
3688 * fsp->access_mask). This is due to the fact that
3689 * FILE_OVERWRITE and FILE_OVERWRITE_IF add in O_TRUNC,
3690 * which adds FILE_WRITE_DATA to open_access_mask.
3692 if (is_oplock_stat_open(open_access_mask) && lease == NULL) {
3693 oplock_request = NO_OPLOCK;
3697 DEBUG(10, ("open_file_ntcreate: fname=%s, after mapping "
3698 "access_mask=0x%x\n", smb_fname_str_dbg(smb_fname),
3702 * Note that we ignore the append flag as append does not
3703 * mean the same thing under DOS and Unix.
3706 flags = calculate_open_access_flags(access_mask, private_flags);
3709 * Currently we only look at FILE_WRITE_THROUGH for create options.
3713 if ((create_options & FILE_WRITE_THROUGH) && lp_strict_sync(SNUM(conn))) {
3718 if (posix_open && (access_mask & FILE_APPEND_DATA)) {
3722 if (!posix_open && !CAN_WRITE(conn)) {
3724 * We should really return a permission denied error if either
3725 * O_CREAT or O_TRUNC are set, but for compatibility with
3726 * older versions of Samba we just AND them out.
3728 flags2 &= ~(O_CREAT|O_TRUNC);
3732 * With kernel oplocks the open breaking an oplock
3733 * blocks until the oplock holder has given up the
3734 * oplock or closed the file. We prevent this by always
3735 * trying to open the file with O_NONBLOCK (see "man
3738 * If a process that doesn't use the smbd open files
3739 * database or communication methods holds a kernel
3740 * oplock we must periodically poll for available open
3743 flags2 |= O_NONBLOCK;
3746 * Ensure we can't write on a read-only share or file.
3749 if (flags != O_RDONLY && file_existed &&
3750 (!CAN_WRITE(conn) || IS_DOS_READONLY(existing_dos_attributes))) {
3751 DEBUG(5,("open_file_ntcreate: write access requested for "
3752 "file %s on read only %s\n",
3753 smb_fname_str_dbg(smb_fname),
3754 !CAN_WRITE(conn) ? "share" : "file" ));
3756 return NT_STATUS_ACCESS_DENIED;
3759 if (VALID_STAT(smb_fname->st)) {
3761 * Only try and create a file id before open
3762 * for an existing file. For a file being created
3763 * this won't do anything useful until the file
3764 * exists and has a valid stat struct.
3766 fsp->file_id = vfs_file_id_from_sbuf(conn, &smb_fname->st);
3768 fsp->fh->private_options = private_flags;
3769 fsp->access_mask = open_access_mask; /* We change this to the
3770 * requested access_mask after
3771 * the open is done. */
3773 fsp->posix_flags |= FSP_POSIX_FLAGS_ALL;
3776 if ((create_options & FILE_DELETE_ON_CLOSE) &&
3777 (flags2 & O_CREAT) &&
3779 /* Delete on close semantics for new files. */
3780 status = can_set_delete_on_close(fsp,
3781 new_dos_attributes);
3782 if (!NT_STATUS_IS_OK(status)) {
3789 * Ensure we pay attention to default ACLs on directories if required.
3792 if ((flags2 & O_CREAT) && lp_inherit_acls(SNUM(conn)) &&
3793 (def_acl = directory_has_default_acl(conn,
3797 unx_mode = (0777 & lp_create_mask(SNUM(conn)));
3800 DEBUG(4,("calling open_file with flags=0x%X flags2=0x%X mode=0%o, "
3801 "access_mask = 0x%x, open_access_mask = 0x%x\n",
3802 (unsigned int)flags, (unsigned int)flags2,
3803 (unsigned int)unx_mode, (unsigned int)access_mask,
3804 (unsigned int)open_access_mask));
3806 fsp_open = open_file(fsp,
3814 if (NT_STATUS_EQUAL(fsp_open, NT_STATUS_NETWORK_BUSY)) {
3815 if (file_existed && S_ISFIFO(fsp->fsp_name->st.st_ex_mode)) {
3816 DEBUG(10, ("FIFO busy\n"));
3817 return NT_STATUS_NETWORK_BUSY;
3820 DEBUG(10, ("Internal open busy\n"));
3821 return NT_STATUS_NETWORK_BUSY;
3824 * This handles the kernel oplock case:
3826 * the file has an active kernel oplock and the open() returned
3827 * EWOULDBLOCK/EAGAIN which maps to NETWORK_BUSY.
3829 * "Samba locking.tdb oplocks" are handled below after acquiring
3830 * the sharemode lock with get_share_mode_lock().
3835 if (NT_STATUS_EQUAL(fsp_open, NT_STATUS_RETRY)) {
3837 * EINTR from the open(2) syscall. Just setup a retry
3838 * in a bit. We can't use the sys_write() tight retry
3839 * loop here, as we might have to actually deal with
3840 * lease-break signals to avoid a deadlock.
3847 * From here on we assume this is an oplock break triggered
3850 lck = get_existing_share_mode_lock(talloc_tos(), fsp->file_id);
3852 if ((lck != NULL) && !validate_oplock_types(lck)) {
3853 smb_panic("validate_oplock_types failed");
3857 * Retry once a second. If there's a share_mode_lock
3858 * around, also wait for it in case it was smbd
3859 * holding that kernel oplock that can quickly tell us
3860 * the oplock got removed.
3867 timeval_set(OPLOCK_BREAK_TIMEOUT*2, 0),
3872 return NT_STATUS_SHARING_VIOLATION;
3875 if (!NT_STATUS_IS_OK(fsp_open)) {
3876 bool wait_for_aio = NT_STATUS_EQUAL(
3877 fsp_open, NT_STATUS_MORE_PROCESSING_REQUIRED);
3879 schedule_async_open(req);
3884 if (new_file_created) {
3886 * As we atomically create using O_CREAT|O_EXCL,
3887 * then if new_file_created is true, then
3888 * file_existed *MUST* have been false (even
3889 * if the file was previously detected as being
3892 file_existed = false;
3895 if (file_existed && !check_same_dev_ino(&saved_stat, &smb_fname->st)) {
3897 * The file did exist, but some other (local or NFS)
3898 * process either renamed/unlinked and re-created the
3899 * file with different dev/ino after we walked the path,
3900 * but before we did the open. We could retry the
3901 * open but it's a rare enough case it's easier to
3902 * just fail the open to prevent creating any problems
3903 * in the open file db having the wrong dev/ino key.
3906 DBG_WARNING("file %s - dev/ino mismatch. "
3907 "Old (dev=%ju, ino=%ju). "
3908 "New (dev=%ju, ino=%ju). Failing open "
3909 "with NT_STATUS_ACCESS_DENIED.\n",
3910 smb_fname_str_dbg(smb_fname),
3911 (uintmax_t)saved_stat.st_ex_dev,
3912 (uintmax_t)saved_stat.st_ex_ino,
3913 (uintmax_t)smb_fname->st.st_ex_dev,
3914 (uintmax_t)smb_fname->st.st_ex_ino);
3915 return NT_STATUS_ACCESS_DENIED;
3918 old_write_time = smb_fname->st.st_ex_mtime;
3921 * Deal with the race condition where two smbd's detect the
3922 * file doesn't exist and do the create at the same time. One
3923 * of them will win and set a share mode, the other (ie. this
3924 * one) should check if the requested share mode for this
3925 * create is allowed.
3929 * Now the file exists and fsp is successfully opened,
3930 * fsp->dev and fsp->inode are valid and should replace the
3931 * dev=0,inode=0 from a non existent file. Spotted by
3932 * Nadav Danieli <nadavd@exanet.com>. JRA.
3937 lck = get_share_mode_lock(talloc_tos(), id,
3939 smb_fname, &old_write_time);
3942 DEBUG(0, ("open_file_ntcreate: Could not get share "
3943 "mode lock for %s\n",
3944 smb_fname_str_dbg(smb_fname)));
3946 return NT_STATUS_SHARING_VIOLATION;
3949 /* Get the types we need to examine. */
3950 if (!validate_oplock_types(lck)) {
3951 smb_panic("validate_oplock_types failed");
3954 if (has_delete_on_close(lck, fsp->name_hash)) {
3957 return NT_STATUS_DELETE_PENDING;
3960 status = handle_share_mode_lease(
3968 first_open_attempt);
3970 if (NT_STATUS_EQUAL(status, NT_STATUS_RETRY)) {
3971 schedule_defer_open(lck, fsp->file_id, req);
3974 return NT_STATUS_SHARING_VIOLATION;
3977 if (!NT_STATUS_IS_OK(status)) {
3984 struct share_mode_data *d = lck->data;
3985 uint16_t new_flags = share_mode_flags_restrict(
3986 d->flags, access_mask, share_access, UINT32_MAX);
3988 if (new_flags != d->flags) {
3989 d->flags = new_flags;
3994 ok = set_share_mode(
3997 get_current_uid(fsp->conn),
4003 if (fsp->oplock_type == LEASE_OPLOCK) {
4004 status = remove_lease_if_stale(
4006 fsp_client_guid(fsp),
4007 &fsp->lease->lease.lease_key);
4008 if (!NT_STATUS_IS_OK(status)) {
4009 DBG_WARNING("remove_lease_if_stale "
4014 return NT_STATUS_NO_MEMORY;
4017 /* Should we atomically (to the client at least) truncate ? */
4018 if ((!new_file_created) &&
4019 (flags2 & O_TRUNC) &&
4020 (S_ISREG(fsp->fsp_name->st.st_ex_mode))) {
4023 ret = SMB_VFS_FTRUNCATE(fsp, 0);
4025 status = map_nt_error_from_unix(errno);
4026 del_share_mode(lck, fsp);
4031 notify_fname(fsp->conn, NOTIFY_ACTION_MODIFIED,
4032 FILE_NOTIFY_CHANGE_SIZE
4033 | FILE_NOTIFY_CHANGE_ATTRIBUTES,
4034 fsp->fsp_name->base_name);
4038 * We have the share entry *locked*.....
4041 /* Delete streams if create_disposition requires it */
4042 if (!new_file_created && clear_ads(create_disposition) &&
4043 !is_ntfs_stream_smb_fname(smb_fname)) {
4044 status = delete_all_streams(conn, smb_fname);
4045 if (!NT_STATUS_IS_OK(status)) {
4046 del_share_mode(lck, fsp);
4053 if (fsp->fh->fd != -1 && lp_kernel_share_modes(SNUM(conn))) {
4056 * Beware: streams implementing VFS modules may
4057 * implement streams in a way that fsp will have the
4058 * basefile open in the fsp fd, so lacking a distinct
4059 * fd for the stream kernel_flock will apply on the
4060 * basefile which is wrong. The actual check is
4061 * deferred to the VFS module implementing the
4062 * kernel_flock call.
4064 ret_flock = SMB_VFS_KERNEL_FLOCK(fsp, share_access, access_mask);
4065 if(ret_flock == -1 ){
4067 del_share_mode(lck, fsp);
4071 return NT_STATUS_SHARING_VIOLATION;
4074 fsp->fsp_flags.kernel_share_modes_taken = true;
4078 * At this point onwards, we can guarantee that the share entry
4079 * is locked, whether we created the file or not, and that the
4080 * deny mode is compatible with all current opens.
4084 * According to Samba4, SEC_FILE_READ_ATTRIBUTE is always granted,
4085 * but we don't have to store this - just ignore it on access check.
4087 if (conn->sconn->using_smb2) {
4089 * SMB2 doesn't return it (according to Microsoft tests).
4090 * Test Case: TestSuite_ScenarioNo009GrantedAccessTestS0
4091 * File created with access = 0x7 (Read, Write, Delete)
4092 * Query Info on file returns 0x87 (Read, Write, Delete, Read Attributes)
4094 fsp->access_mask = access_mask;
4096 /* But SMB1 does. */
4097 fsp->access_mask = access_mask | FILE_READ_ATTRIBUTES;
4100 if (new_file_created) {
4101 info = FILE_WAS_CREATED;
4103 if (flags2 & O_TRUNC) {
4104 info = FILE_WAS_OVERWRITTEN;
4106 info = FILE_WAS_OPENED;
4114 /* Handle strange delete on close create semantics. */
4115 if (create_options & FILE_DELETE_ON_CLOSE) {
4116 if (!new_file_created) {
4117 status = can_set_delete_on_close(fsp,
4118 existing_dos_attributes);
4120 if (!NT_STATUS_IS_OK(status)) {
4121 /* Remember to delete the mode we just added. */
4122 del_share_mode(lck, fsp);
4128 /* Note that here we set the *initial* delete on close flag,
4129 not the regular one. The magic gets handled in close. */
4130 fsp->fsp_flags.initial_delete_on_close = true;
4134 * If we created a file and it's not a stream, this is the point where
4135 * we set the itime (aka invented time) that get's stored in the DOS
4136 * attribute xattr. The value is going to be either what the filesystem
4137 * provided or a copy of the creation date.
4139 * Either way, we turn the itime into a File-ID, unless the filesystem
4140 * provided one (unlikely).
4142 if (info == FILE_WAS_CREATED && !is_named_stream(smb_fname)) {
4143 smb_fname->st.st_ex_iflags &= ~ST_EX_IFLAG_CALCULATED_ITIME;
4145 if (lp_store_dos_attributes(SNUM(conn)) &&
4146 smb_fname->st.st_ex_iflags & ST_EX_IFLAG_CALCULATED_FILE_ID)
4150 file_id = make_file_id_from_itime(&smb_fname->st);
4151 update_stat_ex_file_id(&smb_fname->st, file_id);
4155 if (info != FILE_WAS_OPENED) {
4156 /* Overwritten files should be initially set as archive */
4157 if ((info == FILE_WAS_OVERWRITTEN && lp_map_archive(SNUM(conn))) ||
4158 lp_store_dos_attributes(SNUM(conn))) {
4159 (void)dos_mode(conn, smb_fname);
4161 if (file_set_dosmode(conn, smb_fname,
4162 new_dos_attributes | FILE_ATTRIBUTE_ARCHIVE,
4163 parent_dir_fname, true) == 0) {
4164 unx_mode = smb_fname->st.st_ex_mode;
4170 /* Determine sparse flag. */
4172 /* POSIX opens are sparse by default. */
4173 fsp->fsp_flags.is_sparse = true;
4175 fsp->fsp_flags.is_sparse =
4176 (existing_dos_attributes & FILE_ATTRIBUTE_SPARSE);
4180 * Take care of inherited ACLs on created files - if default ACL not
4184 if (!posix_open && new_file_created && !def_acl) {
4185 if (unx_mode != smb_fname->st.st_ex_mode) {
4186 int ret = SMB_VFS_FCHMOD(fsp, unx_mode);
4188 DBG_INFO("failed to reset "
4189 "attributes of file %s to 0%o\n",
4190 smb_fname_str_dbg(smb_fname),
4191 (unsigned int)unx_mode);
4195 } else if (new_unx_mode) {
4197 * We only get here in the case of:
4199 * a). Not a POSIX open.
4200 * b). File already existed.
4201 * c). File was overwritten.
4202 * d). Requested DOS attributes didn't match
4203 * the DOS attributes on the existing file.
4205 * In that case new_unx_mode has been set
4206 * equal to the calculated mode (including
4207 * possible inheritance of the mode from the
4208 * containing directory).
4210 * Note this mode was calculated with the
4211 * DOS attribute FILE_ATTRIBUTE_ARCHIVE added,
4212 * so the mode change here is suitable for
4213 * an overwritten file.
4216 if (new_unx_mode != smb_fname->st.st_ex_mode) {
4217 int ret = SMB_VFS_FCHMOD(fsp, new_unx_mode);
4219 DBG_INFO("failed to reset "
4220 "attributes of file %s to 0%o\n",
4221 smb_fname_str_dbg(smb_fname),
4222 (unsigned int)new_unx_mode);
4229 * Deal with other opens having a modified write time.
4231 struct timespec write_time = get_share_mode_write_time(lck);
4233 if (!is_omit_timespec(&write_time)) {
4234 update_stat_ex_mtime(&fsp->fsp_name->st, write_time);
4240 return NT_STATUS_OK;
4243 static NTSTATUS mkdir_internal(connection_struct *conn,
4244 struct files_struct **dirfsp,
4245 struct smb_filename *smb_dname,
4246 uint32_t file_attributes)
4248 const struct loadparm_substitution *lp_sub =
4249 loadparm_s3_global_substitution();
4251 struct smb_filename *parent_dir_fname = NULL;
4253 bool posix_open = false;
4254 bool need_re_stat = false;
4255 uint32_t access_mask = SEC_DIR_ADD_SUBDIR;
4259 SMB_ASSERT(*dirfsp == conn->cwd_fsp);
4261 if (!CAN_WRITE(conn) || (access_mask & ~(conn->share_access))) {
4262 DEBUG(5,("mkdir_internal: failing share access "
4263 "%s\n", lp_servicename(talloc_tos(), lp_sub, SNUM(conn))));
4264 return NT_STATUS_ACCESS_DENIED;
4267 ok = parent_smb_fname(talloc_tos(),
4272 return NT_STATUS_NO_MEMORY;
4275 if (file_attributes & FILE_FLAG_POSIX_SEMANTICS) {
4277 mode = (mode_t)(file_attributes & ~FILE_FLAG_POSIX_SEMANTICS);
4279 mode = unix_mode(conn,
4280 FILE_ATTRIBUTE_DIRECTORY,
4285 status = check_parent_access(conn,
4289 if(!NT_STATUS_IS_OK(status)) {
4290 DEBUG(5,("mkdir_internal: check_parent_access "
4291 "on directory %s for path %s returned %s\n",
4292 smb_fname_str_dbg(parent_dir_fname),
4293 smb_dname->base_name,
4294 nt_errstr(status) ));
4298 ret = SMB_VFS_MKDIRAT(conn,
4303 return map_nt_error_from_unix(errno);
4306 /* Ensure we're checking for a symlink here.... */
4307 /* We don't want to get caught by a symlink racer. */
4309 if (SMB_VFS_LSTAT(conn, smb_dname) == -1) {
4310 DEBUG(2, ("Could not stat directory '%s' just created: %s\n",
4311 smb_fname_str_dbg(smb_dname), strerror(errno)));
4312 return map_nt_error_from_unix(errno);
4315 if (!S_ISDIR(smb_dname->st.st_ex_mode)) {
4316 DEBUG(0, ("Directory '%s' just created is not a directory !\n",
4317 smb_fname_str_dbg(smb_dname)));
4318 return NT_STATUS_NOT_A_DIRECTORY;
4321 smb_dname->st.st_ex_iflags &= ~ST_EX_IFLAG_CALCULATED_ITIME;
4323 if (lp_store_dos_attributes(SNUM(conn))) {
4324 if (smb_dname->st.st_ex_iflags & ST_EX_IFLAG_CALCULATED_FILE_ID)
4328 file_id = make_file_id_from_itime(&smb_dname->st);
4329 update_stat_ex_file_id(&smb_dname->st, file_id);
4333 file_set_dosmode(conn, smb_dname,
4334 file_attributes | FILE_ATTRIBUTE_DIRECTORY,
4335 parent_dir_fname, true);
4339 if (lp_inherit_permissions(SNUM(conn))) {
4340 inherit_access_posix_acl(conn, parent_dir_fname,
4342 need_re_stat = true;
4347 * Check if high bits should have been set,
4348 * then (if bits are missing): add them.
4349 * Consider bits automagically set by UNIX, i.e. SGID bit from parent
4352 if ((mode & ~(S_IRWXU|S_IRWXG|S_IRWXO)) &&
4353 (mode & ~smb_dname->st.st_ex_mode)) {
4354 SMB_VFS_CHMOD(conn, smb_dname,
4355 (smb_dname->st.st_ex_mode |
4356 (mode & ~smb_dname->st.st_ex_mode)));
4357 need_re_stat = true;
4361 /* Change the owner if required. */
4362 if (lp_inherit_owner(SNUM(conn)) != INHERIT_OWNER_NO) {
4363 change_dir_owner_to_parent(conn, parent_dir_fname,
4366 need_re_stat = true;
4370 if (SMB_VFS_LSTAT(conn, smb_dname) == -1) {
4371 DEBUG(2, ("Could not stat directory '%s' just created: %s\n",
4372 smb_fname_str_dbg(smb_dname), strerror(errno)));
4373 return map_nt_error_from_unix(errno);
4377 notify_fname(conn, NOTIFY_ACTION_ADDED, FILE_NOTIFY_CHANGE_DIR_NAME,
4378 smb_dname->base_name);
4380 return NT_STATUS_OK;
4383 /****************************************************************************
4384 Open a directory from an NT SMB call.
4385 ****************************************************************************/
4387 static NTSTATUS open_directory(connection_struct *conn,
4388 struct smb_request *req,
4389 struct files_struct **dirfsp,
4390 struct smb_filename *smb_dname,
4391 uint32_t access_mask,
4392 uint32_t share_access,
4393 uint32_t create_disposition,
4394 uint32_t create_options,
4395 uint32_t file_attributes,
4397 files_struct **result)
4399 files_struct *fsp = NULL;
4400 bool dir_existed = VALID_STAT(smb_dname->st);
4401 struct share_mode_lock *lck = NULL;
4403 struct timespec mtimespec;
4408 SMB_ASSERT(*dirfsp == conn->cwd_fsp);
4410 if (is_ntfs_stream_smb_fname(smb_dname)) {
4411 DEBUG(2, ("open_directory: %s is a stream name!\n",
4412 smb_fname_str_dbg(smb_dname)));
4413 return NT_STATUS_NOT_A_DIRECTORY;
4416 if (!(file_attributes & FILE_FLAG_POSIX_SEMANTICS)) {
4417 /* Ensure we have a directory attribute. */
4418 file_attributes |= FILE_ATTRIBUTE_DIRECTORY;
4421 DBG_INFO("opening directory %s, access_mask = 0x%"PRIx32", "
4422 "share_access = 0x%"PRIx32" create_options = 0x%"PRIx32", "
4423 "create_disposition = 0x%"PRIx32", "
4424 "file_attributes = 0x%"PRIx32"\n",
4425 smb_fname_str_dbg(smb_dname),
4432 status = smbd_calculate_access_mask(conn,
4438 if (!NT_STATUS_IS_OK(status)) {
4439 DEBUG(10, ("open_directory: smbd_calculate_access_mask "
4440 "on file %s returned %s\n",
4441 smb_fname_str_dbg(smb_dname),
4442 nt_errstr(status)));
4446 if ((access_mask & SEC_FLAG_SYSTEM_SECURITY) &&
4447 !security_token_has_privilege(get_current_nttok(conn),
4448 SEC_PRIV_SECURITY)) {
4449 DEBUG(10, ("open_directory: open on %s "
4450 "failed - SEC_FLAG_SYSTEM_SECURITY denied.\n",
4451 smb_fname_str_dbg(smb_dname)));
4452 return NT_STATUS_PRIVILEGE_NOT_HELD;
4455 switch( create_disposition ) {
4459 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
4462 info = FILE_WAS_OPENED;
4467 /* If directory exists error. If directory doesn't
4471 status = NT_STATUS_OBJECT_NAME_COLLISION;
4472 DEBUG(2, ("open_directory: unable to create "
4473 "%s. Error was %s\n",
4474 smb_fname_str_dbg(smb_dname),
4475 nt_errstr(status)));
4479 status = mkdir_internal(conn, dirfsp, smb_dname,
4482 if (!NT_STATUS_IS_OK(status)) {
4483 DEBUG(2, ("open_directory: unable to create "
4484 "%s. Error was %s\n",
4485 smb_fname_str_dbg(smb_dname),
4486 nt_errstr(status)));
4490 info = FILE_WAS_CREATED;
4495 * If directory exists open. If directory doesn't
4500 status = NT_STATUS_OK;
4501 info = FILE_WAS_OPENED;
4503 status = mkdir_internal(conn, dirfsp, smb_dname,
4506 if (NT_STATUS_IS_OK(status)) {
4507 info = FILE_WAS_CREATED;
4509 /* Cope with create race. */
4510 if (!NT_STATUS_EQUAL(status,
4511 NT_STATUS_OBJECT_NAME_COLLISION)) {
4512 DEBUG(2, ("open_directory: unable to create "
4513 "%s. Error was %s\n",
4514 smb_fname_str_dbg(smb_dname),
4515 nt_errstr(status)));
4520 * If mkdir_internal() returned
4521 * NT_STATUS_OBJECT_NAME_COLLISION
4522 * we still must lstat the path.
4525 if (SMB_VFS_LSTAT(conn, smb_dname)
4527 DEBUG(2, ("Could not stat "
4528 "directory '%s' just "
4533 return map_nt_error_from_unix(
4537 info = FILE_WAS_OPENED;
4543 case FILE_SUPERSEDE:
4544 case FILE_OVERWRITE:
4545 case FILE_OVERWRITE_IF:
4547 DEBUG(5,("open_directory: invalid create_disposition "
4548 "0x%x for directory %s\n",
4549 (unsigned int)create_disposition,
4550 smb_fname_str_dbg(smb_dname)));
4551 return NT_STATUS_INVALID_PARAMETER;
4554 if(!S_ISDIR(smb_dname->st.st_ex_mode)) {
4555 DEBUG(5,("open_directory: %s is not a directory !\n",
4556 smb_fname_str_dbg(smb_dname)));
4557 return NT_STATUS_NOT_A_DIRECTORY;
4560 if (info == FILE_WAS_OPENED) {
4561 status = smbd_check_access_rights(conn,
4566 if (!NT_STATUS_IS_OK(status)) {
4567 DEBUG(10, ("open_directory: smbd_check_access_rights on "
4568 "file %s failed with %s\n",
4569 smb_fname_str_dbg(smb_dname),
4570 nt_errstr(status)));
4575 status = file_new(req, conn, &fsp);
4576 if(!NT_STATUS_IS_OK(status)) {
4581 * Setup the files_struct for it.
4584 fsp->file_id = vfs_file_id_from_sbuf(conn, &smb_dname->st);
4585 fsp->vuid = req ? req->vuid : UID_FIELD_INVALID;
4586 fsp->file_pid = req ? req->smbpid : 0;
4587 fsp->fsp_flags.can_lock = false;
4588 fsp->fsp_flags.can_read = false;
4589 fsp->fsp_flags.can_write = false;
4591 fsp->fh->private_options = 0;
4593 * According to Samba4, SEC_FILE_READ_ATTRIBUTE is always granted,
4595 fsp->access_mask = access_mask | FILE_READ_ATTRIBUTES;
4596 fsp->print_file = NULL;
4597 fsp->fsp_flags.modified = false;
4598 fsp->oplock_type = NO_OPLOCK;
4599 fsp->sent_oplock_break = NO_BREAK_SENT;
4600 fsp->fsp_flags.is_directory = true;
4601 if (file_attributes & FILE_FLAG_POSIX_SEMANTICS) {
4602 fsp->posix_flags |= FSP_POSIX_FLAGS_ALL;
4604 status = fsp_set_smb_fname(fsp, smb_dname);
4605 if (!NT_STATUS_IS_OK(status)) {
4606 file_free(req, fsp);
4610 if (*dirfsp == fsp->conn->cwd_fsp) {
4611 fsp->dirfsp = fsp->conn->cwd_fsp;
4613 fsp->dirfsp = talloc_move(fsp, dirfsp);
4616 /* Don't store old timestamps for directory
4617 handles in the internal database. We don't
4618 update them in there if new objects
4619 are created in the directory. Currently
4620 we only update timestamps on file writes.
4623 mtimespec = make_omit_timespec();
4625 /* POSIX allows us to open a directory with O_RDONLY. */
4628 flags |= O_DIRECTORY;
4631 status = fd_openat(fsp, flags, 0);
4632 if (!NT_STATUS_IS_OK(status)) {
4633 DBG_INFO("Could not open fd for "
4635 smb_fname_str_dbg(smb_dname),
4637 file_free(req, fsp);
4641 status = vfs_stat_fsp(fsp);
4642 if (!NT_STATUS_IS_OK(status)) {
4644 file_free(req, fsp);
4648 if(!S_ISDIR(fsp->fsp_name->st.st_ex_mode)) {
4649 DEBUG(5,("open_directory: %s is not a directory !\n",
4650 smb_fname_str_dbg(smb_dname)));
4652 file_free(req, fsp);
4653 return NT_STATUS_NOT_A_DIRECTORY;
4656 /* Ensure there was no race condition. We need to check
4657 * dev/inode but not permissions, as these can change
4659 if (!check_same_dev_ino(&smb_dname->st, &fsp->fsp_name->st)) {
4660 DEBUG(5,("open_directory: stat struct differs for "
4662 smb_fname_str_dbg(smb_dname)));
4664 file_free(req, fsp);
4665 return NT_STATUS_ACCESS_DENIED;
4668 lck = get_share_mode_lock(talloc_tos(), fsp->file_id,
4669 conn->connectpath, smb_dname,
4673 DEBUG(0, ("open_directory: Could not get share mode lock for "
4674 "%s\n", smb_fname_str_dbg(smb_dname)));
4676 file_free(req, fsp);
4677 return NT_STATUS_SHARING_VIOLATION;
4680 if (has_delete_on_close(lck, fsp->name_hash)) {
4683 file_free(req, fsp);
4684 return NT_STATUS_DELETE_PENDING;
4687 status = open_mode_check(conn, lck,
4688 access_mask, share_access);
4690 if (!NT_STATUS_IS_OK(status)) {
4693 file_free(req, fsp);
4698 struct share_mode_data *d = lck->data;
4699 uint16_t new_flags = share_mode_flags_restrict(
4700 d->flags, access_mask, share_access, UINT32_MAX);
4702 if (new_flags != d->flags) {
4703 d->flags = new_flags;
4708 ok = set_share_mode(
4711 get_current_uid(conn),
4719 file_free(req, fsp);
4720 return NT_STATUS_NO_MEMORY;
4723 /* For directories the delete on close bit at open time seems
4724 always to be honored on close... See test 19 in Samba4 BASE-DELETE. */
4725 if (create_options & FILE_DELETE_ON_CLOSE) {
4726 status = can_set_delete_on_close(fsp, 0);
4727 if (!NT_STATUS_IS_OK(status) && !NT_STATUS_EQUAL(status, NT_STATUS_DIRECTORY_NOT_EMPTY)) {
4728 del_share_mode(lck, fsp);
4731 file_free(req, fsp);
4735 if (NT_STATUS_IS_OK(status)) {
4736 /* Note that here we set the *initial* delete on close flag,
4737 not the regular one. The magic gets handled in close. */
4738 fsp->fsp_flags.initial_delete_on_close = true;
4744 * Deal with other opens having a modified write time. Is this
4745 * possible for directories?
4747 struct timespec write_time = get_share_mode_write_time(lck);
4749 if (!is_omit_timespec(&write_time)) {
4750 update_stat_ex_mtime(&fsp->fsp_name->st, write_time);
4761 return NT_STATUS_OK;
4764 NTSTATUS create_directory(connection_struct *conn, struct smb_request *req,
4765 struct smb_filename *smb_dname)
4770 status = SMB_VFS_CREATE_FILE(
4773 &conn->cwd_fsp, /* dirfsp */
4774 smb_dname, /* fname */
4775 FILE_READ_ATTRIBUTES, /* access_mask */
4776 FILE_SHARE_NONE, /* share_access */
4777 FILE_CREATE, /* create_disposition*/
4778 FILE_DIRECTORY_FILE, /* create_options */
4779 FILE_ATTRIBUTE_DIRECTORY, /* file_attributes */
4780 0, /* oplock_request */
4782 0, /* allocation_size */
4783 0, /* private_flags */
4788 NULL, NULL); /* create context */
4790 if (NT_STATUS_IS_OK(status)) {
4791 close_file(req, fsp, NORMAL_CLOSE);
4797 /****************************************************************************
4798 Receive notification that one of our open files has been renamed by another
4800 ****************************************************************************/
4802 void msg_file_was_renamed(struct messaging_context *msg_ctx,
4805 struct server_id src,
4808 struct file_rename_message *msg = NULL;
4809 enum ndr_err_code ndr_err;
4811 struct smb_filename *smb_fname = NULL;
4812 struct smbd_server_connection *sconn =
4813 talloc_get_type_abort(private_data,
4814 struct smbd_server_connection);
4816 msg = talloc(talloc_tos(), struct file_rename_message);
4818 DBG_WARNING("talloc failed\n");
4822 ndr_err = ndr_pull_struct_blob_all(
4826 (ndr_pull_flags_fn_t)ndr_pull_file_rename_message);
4827 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
4828 DBG_DEBUG("ndr_pull_oplock_break_message failed: %s\n",
4829 ndr_errstr(ndr_err));
4832 if (DEBUGLEVEL >= 10) {
4833 struct server_id_buf buf;
4834 DBG_DEBUG("Got rename message from %s\n",
4835 server_id_str_buf(src, &buf));
4836 NDR_PRINT_DEBUG(file_rename_message, msg);
4839 /* stream_name must always be NULL if there is no stream. */
4840 if ((msg->stream_name != NULL) && (msg->stream_name[0] == '\0')) {
4841 msg->stream_name = NULL;
4844 smb_fname = synthetic_smb_fname(msg,
4850 if (smb_fname == NULL) {
4851 DBG_DEBUG("synthetic_smb_fname failed\n");
4855 fsp = file_find_dif(sconn, msg->id, msg->share_file_id);
4857 DBG_DEBUG("fsp not found\n");
4861 if (strcmp(fsp->conn->connectpath, msg->servicepath) == 0) {
4863 DBG_DEBUG("renaming file %s from %s -> %s\n",
4866 smb_fname_str_dbg(smb_fname));
4867 status = fsp_set_smb_fname(fsp, smb_fname);
4868 if (!NT_STATUS_IS_OK(status)) {
4869 DBG_DEBUG("fsp_set_smb_fname failed: %s\n",
4875 * Now we have the complete path we can work out if
4876 * this is actually within this share and adjust
4877 * newname accordingly.
4879 DBG_DEBUG("share mismatch (sharepath %s not sharepath %s) "
4880 "%s from %s -> %s\n",
4881 fsp->conn->connectpath,
4885 smb_fname_str_dbg(smb_fname));
4892 * If a main file is opened for delete, all streams need to be checked for
4893 * !FILE_SHARE_DELETE. Do this by opening with DELETE_ACCESS.
4894 * If that works, delete them all by setting the delete on close and close.
4897 static NTSTATUS open_streams_for_delete(connection_struct *conn,
4898 const struct smb_filename *smb_fname)
4900 struct stream_struct *stream_info = NULL;
4901 files_struct **streams = NULL;
4903 unsigned int i, num_streams = 0;
4904 TALLOC_CTX *frame = talloc_stackframe();
4907 status = vfs_streaminfo(conn, NULL, smb_fname, talloc_tos(),
4908 &num_streams, &stream_info);
4910 if (NT_STATUS_EQUAL(status, NT_STATUS_NOT_IMPLEMENTED)
4911 || NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
4912 DEBUG(10, ("no streams around\n"));
4914 return NT_STATUS_OK;
4917 if (!NT_STATUS_IS_OK(status)) {
4918 DEBUG(10, ("vfs_streaminfo failed: %s\n",
4919 nt_errstr(status)));
4923 DEBUG(10, ("open_streams_for_delete found %d streams\n",
4926 if (num_streams == 0) {
4928 return NT_STATUS_OK;
4931 streams = talloc_array(talloc_tos(), files_struct *, num_streams);
4932 if (streams == NULL) {
4933 DEBUG(0, ("talloc failed\n"));
4934 status = NT_STATUS_NO_MEMORY;
4938 for (i=0; i<num_streams; i++) {
4939 struct smb_filename *smb_fname_cp;
4941 if (strequal(stream_info[i].name, "::$DATA")) {
4946 smb_fname_cp = synthetic_smb_fname(talloc_tos(),
4947 smb_fname->base_name,
4948 stream_info[i].name,
4952 ~SMB_FILENAME_POSIX_PATH));
4953 if (smb_fname_cp == NULL) {
4954 status = NT_STATUS_NO_MEMORY;
4958 if (SMB_VFS_STAT(conn, smb_fname_cp) == -1) {
4959 DEBUG(10, ("Unable to stat stream: %s\n",
4960 smb_fname_str_dbg(smb_fname_cp)));
4963 status = SMB_VFS_CREATE_FILE(
4966 &conn->cwd_fsp, /* dirfsp */
4967 smb_fname_cp, /* fname */
4968 DELETE_ACCESS, /* access_mask */
4969 (FILE_SHARE_READ | /* share_access */
4970 FILE_SHARE_WRITE | FILE_SHARE_DELETE),
4971 FILE_OPEN, /* create_disposition*/
4972 0, /* create_options */
4973 FILE_ATTRIBUTE_NORMAL, /* file_attributes */
4974 0, /* oplock_request */
4976 0, /* allocation_size */
4977 0, /* private_flags */
4980 &streams[i], /* result */
4982 NULL, NULL); /* create context */
4984 if (!NT_STATUS_IS_OK(status)) {
4985 DEBUG(10, ("Could not open stream %s: %s\n",
4986 smb_fname_str_dbg(smb_fname_cp),
4987 nt_errstr(status)));
4989 TALLOC_FREE(smb_fname_cp);
4992 TALLOC_FREE(smb_fname_cp);
4996 * don't touch the variable "status" beyond this point :-)
4999 for (j = i-1 ; j >= 0; j--) {
5000 if (streams[j] == NULL) {
5004 DEBUG(10, ("Closing stream # %d, %s\n", j,
5005 fsp_str_dbg(streams[j])));
5006 close_file(NULL, streams[j], NORMAL_CLOSE);
5014 /*********************************************************************
5015 Create a default ACL by inheriting from the parent. If no inheritance
5016 from the parent available, don't set anything. This will leave the actual
5017 permissions the new file or directory already got from the filesystem
5018 as the NT ACL when read.
5019 *********************************************************************/
5021 static NTSTATUS inherit_new_acl(files_struct *fsp)
5023 TALLOC_CTX *frame = talloc_stackframe();
5024 struct security_descriptor *parent_desc = NULL;
5025 NTSTATUS status = NT_STATUS_OK;
5026 struct security_descriptor *psd = NULL;
5027 const struct dom_sid *owner_sid = NULL;
5028 const struct dom_sid *group_sid = NULL;
5029 uint32_t security_info_sent = (SECINFO_OWNER | SECINFO_GROUP | SECINFO_DACL);
5030 struct security_token *token = fsp->conn->session_info->security_token;
5031 bool inherit_owner =
5032 (lp_inherit_owner(SNUM(fsp->conn)) == INHERIT_OWNER_WINDOWS_AND_UNIX);
5033 bool inheritable_components = false;
5034 bool try_builtin_administrators = false;
5035 const struct dom_sid *BA_U_sid = NULL;
5036 const struct dom_sid *BA_G_sid = NULL;
5037 bool try_system = false;
5038 const struct dom_sid *SY_U_sid = NULL;
5039 const struct dom_sid *SY_G_sid = NULL;
5041 struct smb_filename *parent_dir = NULL;
5044 ok = parent_smb_fname(frame,
5050 return NT_STATUS_NO_MEMORY;
5053 status = SMB_VFS_GET_NT_ACL_AT(fsp->conn,
5056 (SECINFO_OWNER | SECINFO_GROUP | SECINFO_DACL),
5059 if (!NT_STATUS_IS_OK(status)) {
5064 inheritable_components = sd_has_inheritable_components(parent_desc,
5065 fsp->fsp_flags.is_directory);
5067 if (!inheritable_components && !inherit_owner) {
5069 /* Nothing to inherit and not setting owner. */
5070 return NT_STATUS_OK;
5073 /* Create an inherited descriptor from the parent. */
5075 if (DEBUGLEVEL >= 10) {
5076 DEBUG(10,("inherit_new_acl: parent acl for %s is:\n",
5077 fsp_str_dbg(fsp) ));
5078 NDR_PRINT_DEBUG(security_descriptor, parent_desc);
5081 /* Inherit from parent descriptor if "inherit owner" set. */
5082 if (inherit_owner) {
5083 owner_sid = parent_desc->owner_sid;
5084 group_sid = parent_desc->group_sid;
5087 if (owner_sid == NULL) {
5088 if (security_token_has_builtin_administrators(token)) {
5089 try_builtin_administrators = true;
5090 } else if (security_token_is_system(token)) {
5091 try_builtin_administrators = true;
5096 if (group_sid == NULL &&
5097 token->num_sids == PRIMARY_GROUP_SID_INDEX)
5099 if (security_token_is_system(token)) {
5100 try_builtin_administrators = true;
5105 if (try_builtin_administrators) {
5109 ok = sids_to_unixids(&global_sid_Builtin_Administrators, 1, &ids);
5113 BA_U_sid = &global_sid_Builtin_Administrators;
5114 BA_G_sid = &global_sid_Builtin_Administrators;
5117 BA_U_sid = &global_sid_Builtin_Administrators;
5120 BA_G_sid = &global_sid_Builtin_Administrators;
5132 ok = sids_to_unixids(&global_sid_System, 1, &ids);
5136 SY_U_sid = &global_sid_System;
5137 SY_G_sid = &global_sid_System;
5140 SY_U_sid = &global_sid_System;
5143 SY_G_sid = &global_sid_System;
5151 if (owner_sid == NULL) {
5152 owner_sid = BA_U_sid;
5155 if (owner_sid == NULL) {
5156 owner_sid = SY_U_sid;
5159 if (group_sid == NULL) {
5160 group_sid = SY_G_sid;
5163 if (try_system && group_sid == NULL) {
5164 group_sid = BA_G_sid;
5167 if (owner_sid == NULL) {
5168 owner_sid = &token->sids[PRIMARY_USER_SID_INDEX];
5170 if (group_sid == NULL) {
5171 if (token->num_sids == PRIMARY_GROUP_SID_INDEX) {
5172 group_sid = &token->sids[PRIMARY_USER_SID_INDEX];
5174 group_sid = &token->sids[PRIMARY_GROUP_SID_INDEX];
5178 status = se_create_child_secdesc(frame,
5184 fsp->fsp_flags.is_directory);
5185 if (!NT_STATUS_IS_OK(status)) {
5190 /* If inheritable_components == false,
5191 se_create_child_secdesc()
5192 creates a security descriptor with a NULL dacl
5193 entry, but with SEC_DESC_DACL_PRESENT. We need
5194 to remove that flag. */
5196 if (!inheritable_components) {
5197 security_info_sent &= ~SECINFO_DACL;
5198 psd->type &= ~SEC_DESC_DACL_PRESENT;
5201 if (DEBUGLEVEL >= 10) {
5202 DEBUG(10,("inherit_new_acl: child acl for %s is:\n",
5203 fsp_str_dbg(fsp) ));
5204 NDR_PRINT_DEBUG(security_descriptor, psd);
5207 if (inherit_owner) {
5208 /* We need to be root to force this. */
5211 status = SMB_VFS_FSET_NT_ACL(fsp,
5214 if (inherit_owner) {
5222 * If we already have a lease, it must match the new file id. [MS-SMB2]
5223 * 3.3.5.9.8 speaks about INVALID_PARAMETER if an already used lease key is
5224 * used for a different file name.
5227 struct lease_match_state {
5228 /* Input parameters. */
5229 TALLOC_CTX *mem_ctx;
5230 const char *servicepath;
5231 const struct smb_filename *fname;
5234 /* Return parameters. */
5235 uint32_t num_file_ids;
5236 struct file_id *ids;
5237 NTSTATUS match_status;
5240 /*************************************************************
5241 File doesn't exist but this lease key+guid is already in use.
5243 This is only allowable in the dynamic share case where the
5244 service path must be different.
5246 There is a small race condition here in the multi-connection
5247 case where a client sends two create calls on different connections,
5248 where the file doesn't exist and one smbd creates the leases_db
5249 entry first, but this will get fixed by the multichannel cleanup
5250 when all identical client_guids get handled by a single smbd.
5251 **************************************************************/
5253 static void lease_match_parser_new_file(
5255 const struct leases_db_file *files,
5256 struct lease_match_state *state)
5260 for (i = 0; i < num_files; i++) {
5261 const struct leases_db_file *f = &files[i];
5262 if (strequal(state->servicepath, f->servicepath)) {
5263 state->match_status = NT_STATUS_INVALID_PARAMETER;
5268 /* Dynamic share case. Break leases on all other files. */
5269 state->match_status = leases_db_copy_file_ids(state->mem_ctx,
5273 if (!NT_STATUS_IS_OK(state->match_status)) {
5277 state->num_file_ids = num_files;
5278 state->match_status = NT_STATUS_OPLOCK_NOT_GRANTED;
5282 static void lease_match_parser(
5284 const struct leases_db_file *files,
5287 struct lease_match_state *state =
5288 (struct lease_match_state *)private_data;
5291 if (!state->file_existed) {
5293 * Deal with name mismatch or
5294 * possible dynamic share case separately
5295 * to make code clearer.
5297 lease_match_parser_new_file(num_files,
5304 state->match_status = NT_STATUS_OK;
5306 for (i = 0; i < num_files; i++) {
5307 const struct leases_db_file *f = &files[i];
5309 /* Everything should be the same. */
5310 if (!file_id_equal(&state->id, &f->id)) {
5311 /* This should catch all dynamic share cases. */
5312 state->match_status = NT_STATUS_OPLOCK_NOT_GRANTED;
5315 if (!strequal(f->servicepath, state->servicepath)) {
5316 state->match_status = NT_STATUS_INVALID_PARAMETER;
5319 if (!strequal(f->base_name, state->fname->base_name)) {
5320 state->match_status = NT_STATUS_INVALID_PARAMETER;
5323 if (!strequal(f->stream_name, state->fname->stream_name)) {
5324 state->match_status = NT_STATUS_INVALID_PARAMETER;
5329 if (NT_STATUS_IS_OK(state->match_status)) {
5331 * Common case - just opening another handle on a
5332 * file on a non-dynamic share.
5337 if (NT_STATUS_EQUAL(state->match_status, NT_STATUS_INVALID_PARAMETER)) {
5338 /* Mismatched path. Error back to client. */
5343 * File id mismatch. Dynamic share case NT_STATUS_OPLOCK_NOT_GRANTED.
5344 * Don't allow leases.
5347 state->match_status = leases_db_copy_file_ids(state->mem_ctx,
5351 if (!NT_STATUS_IS_OK(state->match_status)) {
5355 state->num_file_ids = num_files;
5356 state->match_status = NT_STATUS_OPLOCK_NOT_GRANTED;
5360 struct lease_match_break_state {
5361 struct messaging_context *msg_ctx;
5362 const struct smb2_lease_key *lease_key;
5370 static bool lease_match_break_fn(
5371 struct share_mode_entry *e,
5374 struct lease_match_break_state *state = private_data;
5376 uint32_t e_lease_type;
5379 stale = share_entry_stale_pid(e);
5384 equal = smb2_lease_key_equal(&e->lease_key, state->lease_key);
5389 status = leases_db_get(
5393 NULL, /* current_state */
5394 NULL, /* breaking */
5395 NULL, /* breaking_to_requested */
5396 NULL, /* breaking_to_required */
5397 &state->version, /* lease_version */
5398 &state->epoch); /* epoch */
5399 if (NT_STATUS_IS_OK(status)) {
5400 state->found_lease = true;
5402 DBG_WARNING("Could not find version/epoch: %s\n",
5406 e_lease_type = get_lease_type(e, state->id);
5407 if (e_lease_type == SMB2_LEASE_NONE) {
5410 send_break_message(state->msg_ctx, &state->id, e, SMB2_LEASE_NONE);
5413 * Windows 7 and 8 lease clients are broken in that they will
5414 * not respond to lease break requests whilst waiting for an
5415 * outstanding open request on that lease handle on the same
5416 * TCP connection, due to holding an internal inode lock.
5418 * This means we can't reschedule ourselves here, but must
5419 * return from the create.
5423 * Send the breaks and then return SMB2_LEASE_NONE in the
5424 * lease handle to cause them to acknowledge the lease
5425 * break. Consultation with Microsoft engineering confirmed
5426 * this approach is safe.
5432 static NTSTATUS lease_match(connection_struct *conn,
5433 struct smb_request *req,
5434 const struct smb2_lease_key *lease_key,
5435 const char *servicepath,
5436 const struct smb_filename *fname,
5437 uint16_t *p_version,
5440 struct smbd_server_connection *sconn = req->sconn;
5441 TALLOC_CTX *tos = talloc_tos();
5442 struct lease_match_state state = {
5444 .servicepath = servicepath,
5446 .match_status = NT_STATUS_OK
5451 state.file_existed = VALID_STAT(fname->st);
5452 if (state.file_existed) {
5453 state.id = vfs_file_id_from_sbuf(conn, &fname->st);
5456 status = leases_db_parse(&sconn->client->global->client_guid,
5457 lease_key, lease_match_parser, &state);
5458 if (!NT_STATUS_IS_OK(status)) {
5460 * Not found or error means okay: We can make the lease pass
5462 return NT_STATUS_OK;
5464 if (!NT_STATUS_EQUAL(state.match_status, NT_STATUS_OPLOCK_NOT_GRANTED)) {
5466 * Anything but NT_STATUS_OPLOCK_NOT_GRANTED, let the caller
5469 return state.match_status;
5472 /* We have to break all existing leases. */
5473 for (i = 0; i < state.num_file_ids; i++) {
5474 struct lease_match_break_state break_state = {
5475 .msg_ctx = conn->sconn->msg_ctx,
5476 .lease_key = lease_key,
5478 struct share_mode_lock *lck;
5481 if (file_id_equal(&state.ids[i], &state.id)) {
5482 /* Don't need to break our own file. */
5486 break_state.id = state.ids[i];
5488 lck = get_existing_share_mode_lock(
5489 talloc_tos(), break_state.id);
5491 /* Race condition - file already closed. */
5495 ok = share_mode_forall_leases(
5496 lck, lease_match_break_fn, &break_state);
5498 DBG_DEBUG("share_mode_forall_leases failed\n");
5504 if (break_state.found_lease) {
5505 *p_version = break_state.version;
5506 *p_epoch = break_state.epoch;
5510 * Ensure we don't grant anything more so we
5513 return NT_STATUS_OPLOCK_NOT_GRANTED;
5517 * Wrapper around open_file_ntcreate and open_directory
5520 static NTSTATUS create_file_unixpath(connection_struct *conn,
5521 struct smb_request *req,
5522 struct files_struct **dirfsp,
5523 struct smb_filename *smb_fname,
5524 uint32_t access_mask,
5525 uint32_t share_access,
5526 uint32_t create_disposition,
5527 uint32_t create_options,
5528 uint32_t file_attributes,
5529 uint32_t oplock_request,
5530 const struct smb2_lease *lease,
5531 uint64_t allocation_size,
5532 uint32_t private_flags,
5533 struct security_descriptor *sd,
5534 struct ea_list *ea_list,
5536 files_struct **result,
5539 struct smb2_lease none_lease;
5540 int info = FILE_WAS_OPENED;
5541 files_struct *base_fsp = NULL;
5542 files_struct *fsp = NULL;
5545 SMB_ASSERT(*dirfsp == conn->cwd_fsp);
5547 DBG_DEBUG("create_file_unixpath: access_mask = 0x%x "
5548 "file_attributes = 0x%x, share_access = 0x%x, "
5549 "create_disposition = 0x%x create_options = 0x%x "
5550 "oplock_request = 0x%x private_flags = 0x%x "
5551 "ea_list = %p, sd = %p, "
5553 (unsigned int)access_mask,
5554 (unsigned int)file_attributes,
5555 (unsigned int)share_access,
5556 (unsigned int)create_disposition,
5557 (unsigned int)create_options,
5558 (unsigned int)oplock_request,
5559 (unsigned int)private_flags,
5560 ea_list, sd, smb_fname_str_dbg(smb_fname));
5562 if (create_options & FILE_OPEN_BY_FILE_ID) {
5563 status = NT_STATUS_NOT_SUPPORTED;
5567 if (create_options & NTCREATEX_OPTIONS_INVALID_PARAM_MASK) {
5568 status = NT_STATUS_INVALID_PARAMETER;
5573 oplock_request |= INTERNAL_OPEN_ONLY;
5576 if (lease != NULL) {
5577 uint16_t epoch = lease->lease_epoch;
5578 uint16_t version = lease->lease_version;
5581 DBG_WARNING("Got lease on internal open\n");
5582 status = NT_STATUS_INTERNAL_ERROR;
5586 status = lease_match(conn,
5593 if (NT_STATUS_EQUAL(status, NT_STATUS_OPLOCK_NOT_GRANTED)) {
5594 /* Dynamic share file. No leases and update epoch... */
5595 none_lease = *lease;
5596 none_lease.lease_state = SMB2_LEASE_NONE;
5597 none_lease.lease_epoch = epoch;
5598 none_lease.lease_version = version;
5599 lease = &none_lease;
5600 } else if (!NT_STATUS_IS_OK(status)) {
5605 if ((conn->fs_capabilities & FILE_NAMED_STREAMS)
5606 && (access_mask & DELETE_ACCESS)
5607 && !is_ntfs_stream_smb_fname(smb_fname)) {
5609 * We can't open a file with DELETE access if any of the
5610 * streams is open without FILE_SHARE_DELETE
5612 status = open_streams_for_delete(conn, smb_fname);
5614 if (!NT_STATUS_IS_OK(status)) {
5619 if (access_mask & SEC_FLAG_SYSTEM_SECURITY) {
5622 ok = security_token_has_privilege(get_current_nttok(conn),
5625 DBG_DEBUG("open on %s failed - "
5626 "SEC_FLAG_SYSTEM_SECURITY denied.\n",
5627 smb_fname_str_dbg(smb_fname));
5628 status = NT_STATUS_PRIVILEGE_NOT_HELD;
5632 if (conn->sconn->using_smb2 &&
5633 (access_mask == SEC_FLAG_SYSTEM_SECURITY))
5636 * No other bits set. Windows SMB2 refuses this.
5637 * See smbtorture3 SMB2-SACL test.
5639 * Note this is an SMB2-only behavior,
5640 * smbtorture3 SMB1-SYSTEM-SECURITY already tests
5641 * that SMB1 allows this.
5643 status = NT_STATUS_ACCESS_DENIED;
5649 * Files or directories can't be opened DELETE_ON_CLOSE without
5651 * BUG: https://bugzilla.samba.org/show_bug.cgi?id=13358
5653 if (create_options & FILE_DELETE_ON_CLOSE) {
5654 if ((access_mask & DELETE_ACCESS) == 0) {
5655 status = NT_STATUS_INVALID_PARAMETER;
5660 if ((conn->fs_capabilities & FILE_NAMED_STREAMS)
5661 && is_ntfs_stream_smb_fname(smb_fname))
5663 uint32_t base_create_disposition;
5664 struct smb_filename *smb_fname_base = NULL;
5665 uint32_t base_privflags;
5667 if (create_options & FILE_DIRECTORY_FILE) {
5668 status = NT_STATUS_NOT_A_DIRECTORY;
5672 switch (create_disposition) {
5674 base_create_disposition = FILE_OPEN;
5677 base_create_disposition = FILE_OPEN_IF;
5681 /* Create an smb_filename with stream_name == NULL. */
5682 smb_fname_base = synthetic_smb_fname(talloc_tos(),
5683 smb_fname->base_name,
5688 if (smb_fname_base == NULL) {
5689 status = NT_STATUS_NO_MEMORY;
5693 if (SMB_VFS_STAT(conn, smb_fname_base) == -1) {
5694 DEBUG(10, ("Unable to stat stream: %s\n",
5695 smb_fname_str_dbg(smb_fname_base)));
5698 * https://bugzilla.samba.org/show_bug.cgi?id=10229
5699 * We need to check if the requested access mask
5700 * could be used to open the underlying file (if
5701 * it existed), as we're passing in zero for the
5702 * access mask to the base filename.
5704 status = check_base_file_access(conn,
5708 if (!NT_STATUS_IS_OK(status)) {
5709 DEBUG(10, ("Permission check "
5710 "for base %s failed: "
5711 "%s\n", smb_fname->base_name,
5712 nt_errstr(status)));
5717 base_privflags = NTCREATEX_OPTIONS_PRIVATE_STREAM_BASEOPEN;
5719 /* Open the base file. */
5720 status = create_file_unixpath(conn,
5727 | FILE_SHARE_DELETE,
5728 base_create_disposition,
5739 TALLOC_FREE(smb_fname_base);
5741 if (!NT_STATUS_IS_OK(status)) {
5742 DEBUG(10, ("create_file_unixpath for base %s failed: "
5743 "%s\n", smb_fname->base_name,
5744 nt_errstr(status)));
5747 /* we don't need the low level fd */
5752 * If it's a request for a directory open, deal with it separately.
5755 if (create_options & FILE_DIRECTORY_FILE) {
5757 if (create_options & FILE_NON_DIRECTORY_FILE) {
5758 status = NT_STATUS_INVALID_PARAMETER;
5762 /* Can't open a temp directory. IFS kit test. */
5763 if (!(file_attributes & FILE_FLAG_POSIX_SEMANTICS) &&
5764 (file_attributes & FILE_ATTRIBUTE_TEMPORARY)) {
5765 status = NT_STATUS_INVALID_PARAMETER;
5770 * We will get a create directory here if the Win32
5771 * app specified a security descriptor in the
5772 * CreateDirectory() call.
5776 status = open_directory(conn,
5790 * Ordinary file case.
5793 status = file_new(req, conn, &fsp);
5794 if(!NT_STATUS_IS_OK(status)) {
5798 status = fsp_set_smb_fname(fsp, smb_fname);
5799 if (!NT_STATUS_IS_OK(status)) {
5803 if (*dirfsp == fsp->conn->cwd_fsp) {
5804 fsp->dirfsp = fsp->conn->cwd_fsp;
5806 fsp->dirfsp = talloc_move(fsp, dirfsp);
5811 * We're opening the stream element of a
5812 * base_fsp we already opened. Set up the
5815 fsp->base_fsp = base_fsp;
5818 if (allocation_size) {
5819 fsp->initial_allocation_size = smb_roundup(fsp->conn,
5823 status = open_file_ntcreate(conn,
5836 if(!NT_STATUS_IS_OK(status)) {
5837 file_free(req, fsp);
5841 if (NT_STATUS_EQUAL(status, NT_STATUS_FILE_IS_A_DIRECTORY)) {
5843 /* A stream open never opens a directory */
5846 status = NT_STATUS_FILE_IS_A_DIRECTORY;
5851 * Fail the open if it was explicitly a non-directory
5855 if (create_options & FILE_NON_DIRECTORY_FILE) {
5856 status = NT_STATUS_FILE_IS_A_DIRECTORY;
5861 status = open_directory(conn,
5875 if (!NT_STATUS_IS_OK(status)) {
5879 fsp->base_fsp = base_fsp;
5881 if ((ea_list != NULL) &&
5882 ((info == FILE_WAS_CREATED) || (info == FILE_WAS_OVERWRITTEN))) {
5883 status = set_ea(conn, fsp, fsp->fsp_name, ea_list);
5884 if (!NT_STATUS_IS_OK(status)) {
5889 if (!fsp->fsp_flags.is_directory &&
5890 S_ISDIR(fsp->fsp_name->st.st_ex_mode))
5892 status = NT_STATUS_ACCESS_DENIED;
5896 /* Save the requested allocation size. */
5897 if ((info == FILE_WAS_CREATED) || (info == FILE_WAS_OVERWRITTEN)) {
5898 if ((allocation_size > (uint64_t)fsp->fsp_name->st.st_ex_size)
5899 && !(fsp->fsp_flags.is_directory))
5901 fsp->initial_allocation_size = smb_roundup(
5902 fsp->conn, allocation_size);
5903 if (vfs_allocate_file_space(
5904 fsp, fsp->initial_allocation_size) == -1) {
5905 status = NT_STATUS_DISK_FULL;
5909 fsp->initial_allocation_size = smb_roundup(
5910 fsp->conn, (uint64_t)fsp->fsp_name->st.st_ex_size);
5913 fsp->initial_allocation_size = 0;
5916 if ((info == FILE_WAS_CREATED) && lp_nt_acl_support(SNUM(conn)) &&
5917 fsp->base_fsp == NULL) {
5920 * According to the MS documentation, the only time the security
5921 * descriptor is applied to the opened file is iff we *created* the
5922 * file; an existing file stays the same.
5924 * Also, it seems (from observation) that you can open the file with
5925 * any access mask but you can still write the sd. We need to override
5926 * the granted access before we call set_sd
5927 * Patch for bug #2242 from Tom Lackemann <cessnatomny@yahoo.com>.
5930 uint32_t sec_info_sent;
5931 uint32_t saved_access_mask = fsp->access_mask;
5933 sec_info_sent = get_sec_info(sd);
5935 fsp->access_mask = FILE_GENERIC_ALL;
5937 if (sec_info_sent & (SECINFO_OWNER|
5941 status = set_sd(fsp, sd, sec_info_sent);
5944 fsp->access_mask = saved_access_mask;
5946 if (!NT_STATUS_IS_OK(status)) {
5949 } else if (lp_inherit_acls(SNUM(conn))) {
5950 /* Inherit from parent. Errors here are not fatal. */
5951 status = inherit_new_acl(fsp);
5952 if (!NT_STATUS_IS_OK(status)) {
5953 DEBUG(10,("inherit_new_acl: failed for %s with %s\n",
5955 nt_errstr(status) ));
5960 if ((conn->fs_capabilities & FILE_FILE_COMPRESSION)
5961 && (create_options & FILE_NO_COMPRESSION)
5962 && (info == FILE_WAS_CREATED)) {
5963 status = SMB_VFS_SET_COMPRESSION(conn, fsp, fsp,
5964 COMPRESSION_FORMAT_NONE);
5965 if (!NT_STATUS_IS_OK(status)) {
5966 DEBUG(1, ("failed to disable compression: %s\n",
5967 nt_errstr(status)));
5971 DEBUG(10, ("create_file_unixpath: info=%d\n", info));
5974 if (pinfo != NULL) {
5978 smb_fname->st = fsp->fsp_name->st;
5980 return NT_STATUS_OK;
5983 DEBUG(10, ("create_file_unixpath: %s\n", nt_errstr(status)));
5986 if (base_fsp && fsp->base_fsp == base_fsp) {
5988 * The close_file below will close
5993 close_file(req, fsp, ERROR_CLOSE);
5996 if (base_fsp != NULL) {
5997 close_file(req, base_fsp, ERROR_CLOSE);
6003 NTSTATUS create_file_default(connection_struct *conn,
6004 struct smb_request *req,
6005 struct files_struct **_dirfsp,
6006 struct smb_filename *smb_fname,
6007 uint32_t access_mask,
6008 uint32_t share_access,
6009 uint32_t create_disposition,
6010 uint32_t create_options,
6011 uint32_t file_attributes,
6012 uint32_t oplock_request,
6013 const struct smb2_lease *lease,
6014 uint64_t allocation_size,
6015 uint32_t private_flags,
6016 struct security_descriptor *sd,
6017 struct ea_list *ea_list,
6018 files_struct **result,
6020 const struct smb2_create_blobs *in_context_blobs,
6021 struct smb2_create_blobs *out_context_blobs)
6023 int info = FILE_WAS_OPENED;
6024 files_struct *fsp = NULL;
6026 bool stream_name = false;
6027 struct smb2_create_blob *posx = NULL;
6028 struct files_struct *dirfsp = *_dirfsp;
6030 SMB_ASSERT(dirfsp == dirfsp->conn->cwd_fsp);
6032 DBG_DEBUG("create_file: access_mask = 0x%x "
6033 "file_attributes = 0x%x, share_access = 0x%x, "
6034 "create_disposition = 0x%x create_options = 0x%x "
6035 "oplock_request = 0x%x "
6036 "private_flags = 0x%x "
6037 "ea_list = %p, sd = %p, "
6040 (unsigned int)access_mask,
6041 (unsigned int)file_attributes,
6042 (unsigned int)share_access,
6043 (unsigned int)create_disposition,
6044 (unsigned int)create_options,
6045 (unsigned int)oplock_request,
6046 (unsigned int)private_flags,
6049 fsp_str_dbg(dirfsp),
6050 smb_fname_str_dbg(smb_fname));
6054 * Remember the absolute time of the original request
6055 * with this mid. We'll use it later to see if this
6058 get_deferred_open_message_state(req, &req->request_time, NULL);
6062 * Check to see if this is a mac fork of some kind.
6065 stream_name = is_ntfs_stream_smb_fname(smb_fname);
6067 enum FAKE_FILE_TYPE fake_file_type;
6069 fake_file_type = is_fake_file(smb_fname);
6071 if (req != NULL && fake_file_type != FAKE_FILE_TYPE_NONE) {
6074 * Here we go! support for changing the disk quotas
6077 * We need to fake up to open this MAGIC QUOTA file
6078 * and return a valid FID.
6080 * w2k close this file directly after openening xp
6081 * also tries a QUERY_FILE_INFO on the file and then
6084 status = open_fake_file(req, conn, req->vuid,
6085 fake_file_type, smb_fname,
6087 if (!NT_STATUS_IS_OK(status)) {
6091 ZERO_STRUCT(smb_fname->st);
6095 if (!(conn->fs_capabilities & FILE_NAMED_STREAMS)) {
6096 status = NT_STATUS_OBJECT_NAME_NOT_FOUND;
6101 if (is_ntfs_default_stream_smb_fname(smb_fname)) {
6103 smb_fname->stream_name = NULL;
6104 /* We have to handle this error here. */
6105 if (create_options & FILE_DIRECTORY_FILE) {
6106 status = NT_STATUS_NOT_A_DIRECTORY;
6109 if (req != NULL && req->posix_pathnames) {
6110 ret = SMB_VFS_LSTAT(conn, smb_fname);
6112 ret = SMB_VFS_STAT(conn, smb_fname);
6115 if (ret == 0 && VALID_STAT_OF_DIR(smb_fname->st)) {
6116 status = NT_STATUS_FILE_IS_A_DIRECTORY;
6121 posx = smb2_create_blob_find(
6122 in_context_blobs, SMB2_CREATE_TAG_POSIX);
6124 uint32_t wire_mode_bits = 0;
6125 mode_t mode_bits = 0;
6126 SMB_STRUCT_STAT sbuf = { 0 };
6127 enum perm_type ptype =
6128 (create_options & FILE_DIRECTORY_FILE) ?
6129 PERM_NEW_DIR : PERM_NEW_FILE;
6131 if (posx->data.length != 4) {
6132 status = NT_STATUS_INVALID_PARAMETER;
6136 wire_mode_bits = IVAL(posx->data.data, 0);
6137 status = unix_perms_from_wire(
6138 conn, &sbuf, wire_mode_bits, ptype, &mode_bits);
6139 if (!NT_STATUS_IS_OK(status)) {
6143 * Remove type info from mode, leaving only the
6144 * permissions and setuid/gid bits.
6146 mode_bits &= ~S_IFMT;
6148 file_attributes = (FILE_FLAG_POSIX_SEMANTICS | mode_bits);
6151 status = create_file_unixpath(conn,
6168 if (!NT_STATUS_IS_OK(status)) {
6173 DEBUG(10, ("create_file: info=%d\n", info));
6176 if (pinfo != NULL) {
6179 return NT_STATUS_OK;
6182 DEBUG(10, ("create_file: %s\n", nt_errstr(status)));
6185 close_file(req, fsp, ERROR_CLOSE);