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)
914 if (fsp->fh->fd == -1) {
916 * Either a directory where the dptr_CloseDir() already closed
917 * the fd or a stat open.
921 if (fsp->fh->ref_count > 1) {
922 return NT_STATUS_OK; /* Shared handle. Only close last reference. */
925 ret = SMB_VFS_CLOSE(fsp);
928 return map_nt_error_from_unix(errno);
933 /****************************************************************************
934 Change the ownership of a file to that of the parent directory.
935 Do this by fd if possible.
936 ****************************************************************************/
938 void change_file_owner_to_parent(connection_struct *conn,
939 struct smb_filename *smb_fname_parent,
944 ret = SMB_VFS_STAT(conn, smb_fname_parent);
946 DEBUG(0,("change_file_owner_to_parent: failed to stat parent "
947 "directory %s. Error was %s\n",
948 smb_fname_str_dbg(smb_fname_parent),
950 TALLOC_FREE(smb_fname_parent);
954 if (smb_fname_parent->st.st_ex_uid == fsp->fsp_name->st.st_ex_uid) {
955 /* Already this uid - no need to change. */
956 DEBUG(10,("change_file_owner_to_parent: file %s "
957 "is already owned by uid %d\n",
959 (int)fsp->fsp_name->st.st_ex_uid ));
960 TALLOC_FREE(smb_fname_parent);
965 ret = SMB_VFS_FCHOWN(fsp, smb_fname_parent->st.st_ex_uid, (gid_t)-1);
968 DEBUG(0,("change_file_owner_to_parent: failed to fchown "
969 "file %s to parent directory uid %u. Error "
970 "was %s\n", fsp_str_dbg(fsp),
971 (unsigned int)smb_fname_parent->st.st_ex_uid,
974 DEBUG(10,("change_file_owner_to_parent: changed new file %s to "
975 "parent directory uid %u.\n", fsp_str_dbg(fsp),
976 (unsigned int)smb_fname_parent->st.st_ex_uid));
977 /* Ensure the uid entry is updated. */
978 fsp->fsp_name->st.st_ex_uid = smb_fname_parent->st.st_ex_uid;
982 static NTSTATUS change_dir_owner_to_parent(connection_struct *conn,
983 struct smb_filename *smb_fname_parent,
984 struct smb_filename *smb_dname,
985 SMB_STRUCT_STAT *psbuf)
987 struct smb_filename *smb_fname_cwd = NULL;
988 struct smb_filename *saved_dir_fname = NULL;
989 TALLOC_CTX *ctx = talloc_tos();
990 NTSTATUS status = NT_STATUS_OK;
993 ret = SMB_VFS_STAT(conn, smb_fname_parent);
995 status = map_nt_error_from_unix(errno);
996 DEBUG(0,("change_dir_owner_to_parent: failed to stat parent "
997 "directory %s. Error was %s\n",
998 smb_fname_str_dbg(smb_fname_parent),
1003 /* We've already done an lstat into psbuf, and we know it's a
1004 directory. If we can cd into the directory and the dev/ino
1005 are the same then we can safely chown without races as
1006 we're locking the directory in place by being in it. This
1007 should work on any UNIX (thanks tridge :-). JRA.
1010 saved_dir_fname = vfs_GetWd(ctx,conn);
1011 if (!saved_dir_fname) {
1012 status = map_nt_error_from_unix(errno);
1013 DEBUG(0,("change_dir_owner_to_parent: failed to get "
1014 "current working directory. Error was %s\n",
1019 /* Chdir into the new path. */
1020 if (vfs_ChDir(conn, smb_dname) == -1) {
1021 status = map_nt_error_from_unix(errno);
1022 DEBUG(0,("change_dir_owner_to_parent: failed to change "
1023 "current working directory to %s. Error "
1024 "was %s\n", smb_dname->base_name, strerror(errno) ));
1028 smb_fname_cwd = synthetic_smb_fname(ctx,
1034 if (smb_fname_cwd == NULL) {
1035 status = NT_STATUS_NO_MEMORY;
1039 ret = SMB_VFS_STAT(conn, smb_fname_cwd);
1041 status = map_nt_error_from_unix(errno);
1042 DEBUG(0,("change_dir_owner_to_parent: failed to stat "
1043 "directory '.' (%s) Error was %s\n",
1044 smb_dname->base_name, strerror(errno)));
1048 /* Ensure we're pointing at the same place. */
1049 if (smb_fname_cwd->st.st_ex_dev != psbuf->st_ex_dev ||
1050 smb_fname_cwd->st.st_ex_ino != psbuf->st_ex_ino) {
1051 DEBUG(0,("change_dir_owner_to_parent: "
1052 "device/inode on directory %s changed. "
1053 "Refusing to chown !\n",
1054 smb_dname->base_name ));
1055 status = NT_STATUS_ACCESS_DENIED;
1059 if (smb_fname_parent->st.st_ex_uid == smb_fname_cwd->st.st_ex_uid) {
1060 /* Already this uid - no need to change. */
1061 DEBUG(10,("change_dir_owner_to_parent: directory %s "
1062 "is already owned by uid %d\n",
1063 smb_dname->base_name,
1064 (int)smb_fname_cwd->st.st_ex_uid ));
1065 status = NT_STATUS_OK;
1070 ret = SMB_VFS_LCHOWN(conn,
1072 smb_fname_parent->st.st_ex_uid,
1076 status = map_nt_error_from_unix(errno);
1077 DEBUG(10,("change_dir_owner_to_parent: failed to chown "
1078 "directory %s to parent directory uid %u. "
1080 smb_dname->base_name,
1081 (unsigned int)smb_fname_parent->st.st_ex_uid,
1084 DEBUG(10,("change_dir_owner_to_parent: changed ownership of new "
1085 "directory %s to parent directory uid %u.\n",
1086 smb_dname->base_name,
1087 (unsigned int)smb_fname_parent->st.st_ex_uid ));
1088 /* Ensure the uid entry is updated. */
1089 psbuf->st_ex_uid = smb_fname_parent->st.st_ex_uid;
1093 vfs_ChDir(conn, saved_dir_fname);
1095 TALLOC_FREE(saved_dir_fname);
1096 TALLOC_FREE(smb_fname_cwd);
1100 /****************************************************************************
1101 Open a file - returning a guaranteed ATOMIC indication of if the
1102 file was created or not.
1103 ****************************************************************************/
1105 static NTSTATUS fd_open_atomic(files_struct *fsp,
1110 NTSTATUS status = NT_STATUS_UNSUCCESSFUL;
1111 NTSTATUS retry_status;
1112 bool file_existed = VALID_STAT(fsp->fsp_name->st);
1115 if (!(flags & O_CREAT)) {
1117 * We're not creating the file, just pass through.
1119 status = fd_openat(fsp, flags, mode);
1120 *file_created = false;
1124 if (flags & O_EXCL) {
1126 * Fail if already exists, just pass through.
1128 status = fd_openat(fsp, flags, mode);
1131 * Here we've opened with O_CREAT|O_EXCL. If that went
1132 * NT_STATUS_OK, we *know* we created this file.
1134 *file_created = NT_STATUS_IS_OK(status);
1140 * Now it gets tricky. We have O_CREAT, but not O_EXCL.
1141 * To know absolutely if we created the file or not,
1142 * we can never call O_CREAT without O_EXCL. So if
1143 * we think the file existed, try without O_CREAT|O_EXCL.
1144 * If we think the file didn't exist, try with
1147 * The big problem here is dangling symlinks. Opening
1148 * without O_NOFOLLOW means both bad symlink
1149 * and missing path return -1, ENOENT from open(). As POSIX
1150 * is pathname based it's not possible to tell
1151 * the difference between these two cases in a
1152 * non-racy way, so change to try only two attempts before
1155 * We don't have this problem for the O_NOFOLLOW
1156 * case as it just returns NT_STATUS_OBJECT_PATH_NOT_FOUND
1157 * mapped from the ELOOP POSIX error.
1161 curr_flags = flags & ~(O_CREAT);
1162 retry_status = NT_STATUS_OBJECT_NAME_NOT_FOUND;
1164 curr_flags = flags | O_EXCL;
1165 retry_status = NT_STATUS_OBJECT_NAME_COLLISION;
1168 status = fd_openat(fsp, curr_flags, mode);
1169 if (NT_STATUS_IS_OK(status)) {
1170 *file_created = !file_existed;
1171 return NT_STATUS_OK;
1173 if (NT_STATUS_EQUAL(status, retry_status)) {
1175 file_existed = !file_existed;
1177 DBG_DEBUG("File %s %s. Retry.\n",
1179 file_existed ? "existed" : "did not exist");
1182 curr_flags = flags & ~(O_CREAT);
1184 curr_flags = flags | O_EXCL;
1187 status = fd_openat(fsp, curr_flags, mode);
1190 *file_created = (NT_STATUS_IS_OK(status) && !file_existed);
1194 /****************************************************************************
1196 ****************************************************************************/
1198 static NTSTATUS open_file(files_struct *fsp,
1199 struct smb_request *req,
1200 struct smb_filename *parent_dir,
1203 uint32_t access_mask, /* client requested access mask. */
1204 uint32_t open_access_mask, /* what we're actually using in the open. */
1205 bool *p_file_created)
1207 connection_struct *conn = fsp->conn;
1208 struct smb_filename *smb_fname = fsp->fsp_name;
1209 NTSTATUS status = NT_STATUS_OK;
1210 int accmode = (flags & O_ACCMODE);
1211 int local_flags = flags;
1212 bool file_existed = VALID_STAT(fsp->fsp_name->st);
1213 uint32_t need_fd_mask =
1219 WRITE_OWNER_ACCESS |
1220 SEC_FLAG_SYSTEM_SECURITY |
1221 READ_CONTROL_ACCESS;
1222 bool creating = !file_existed && (flags & O_CREAT);
1223 bool truncating = (flags & O_TRUNC);
1228 /* Check permissions */
1231 * This code was changed after seeing a client open request
1232 * containing the open mode of (DENY_WRITE/read-only) with
1233 * the 'create if not exist' bit set. The previous code
1234 * would fail to open the file read only on a read-only share
1235 * as it was checking the flags parameter directly against O_RDONLY,
1236 * this was failing as the flags parameter was set to O_RDONLY|O_CREAT.
1240 if (!CAN_WRITE(conn)) {
1241 /* It's a read-only share - fail if we wanted to write. */
1242 if(accmode != O_RDONLY || (flags & O_TRUNC) || (flags & O_APPEND)) {
1243 DEBUG(3,("Permission denied opening %s\n",
1244 smb_fname_str_dbg(smb_fname)));
1245 return NT_STATUS_ACCESS_DENIED;
1247 if (flags & O_CREAT) {
1248 /* We don't want to write - but we must make sure that
1249 O_CREAT doesn't create the file if we have write
1250 access into the directory.
1252 flags &= ~(O_CREAT|O_EXCL);
1253 local_flags &= ~(O_CREAT|O_EXCL);
1258 * This little piece of insanity is inspired by the
1259 * fact that an NT client can open a file for O_RDONLY,
1260 * but set the create disposition to FILE_EXISTS_TRUNCATE.
1261 * If the client *can* write to the file, then it expects to
1262 * truncate the file, even though it is opening for readonly.
1263 * Quicken uses this stupid trick in backup file creation...
1264 * Thanks *greatly* to "David W. Chapman Jr." <dwcjr@inethouston.net>
1265 * for helping track this one down. It didn't bite us in 2.0.x
1266 * as we always opened files read-write in that release. JRA.
1269 if ((accmode == O_RDONLY) && ((flags & O_TRUNC) == O_TRUNC)) {
1270 DEBUG(10,("open_file: truncate requested on read-only open "
1271 "for file %s\n", smb_fname_str_dbg(smb_fname)));
1272 local_flags = (flags & ~O_ACCMODE)|O_RDWR;
1275 if ((open_access_mask & need_fd_mask) || creating || truncating) {
1279 #if defined(O_NONBLOCK) && defined(S_ISFIFO)
1281 * We would block on opening a FIFO with no one else on the
1282 * other end. Do what we used to do and add O_NONBLOCK to the
1286 if (file_existed && S_ISFIFO(smb_fname->st.st_ex_mode)) {
1287 local_flags &= ~O_TRUNC; /* Can't truncate a FIFO. */
1288 local_flags |= O_NONBLOCK;
1293 /* Don't create files with Microsoft wildcard characters. */
1294 if (fsp->base_fsp) {
1296 * wildcard characters are allowed in stream names
1297 * only test the basefilename
1299 wild = fsp->base_fsp->fsp_name->base_name;
1301 wild = smb_fname->base_name;
1303 if ((local_flags & O_CREAT) && !file_existed &&
1304 !(fsp->posix_flags & FSP_POSIX_FLAGS_PATHNAMES) &&
1305 ms_has_wild(wild)) {
1306 return NT_STATUS_OBJECT_NAME_INVALID;
1309 /* Can we access this file ? */
1310 if (!fsp->base_fsp) {
1311 /* Only do this check on non-stream open. */
1313 status = smbd_check_access_rights(conn,
1319 if (!NT_STATUS_IS_OK(status)) {
1320 DEBUG(10, ("open_file: "
1321 "smbd_check_access_rights "
1322 "on file %s returned %s\n",
1323 smb_fname_str_dbg(smb_fname),
1324 nt_errstr(status)));
1327 if (!NT_STATUS_IS_OK(status) &&
1328 !NT_STATUS_EQUAL(status,
1329 NT_STATUS_OBJECT_NAME_NOT_FOUND))
1334 if (NT_STATUS_EQUAL(status,
1335 NT_STATUS_OBJECT_NAME_NOT_FOUND))
1337 DEBUG(10, ("open_file: "
1338 "file %s vanished since we "
1339 "checked for existence.\n",
1340 smb_fname_str_dbg(smb_fname)));
1341 file_existed = false;
1342 SET_STAT_INVALID(fsp->fsp_name->st);
1346 if (!file_existed) {
1347 if (!(local_flags & O_CREAT)) {
1348 /* File didn't exist and no O_CREAT. */
1349 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
1352 status = check_parent_access(conn,
1356 if (!NT_STATUS_IS_OK(status)) {
1357 DEBUG(10, ("open_file: "
1358 "check_parent_access on "
1359 "file %s returned %s\n",
1360 smb_fname_str_dbg(smb_fname),
1361 nt_errstr(status) ));
1368 * Actually do the open - if O_TRUNC is needed handle it
1369 * below under the share mode lock.
1371 status = fd_open_atomic(fsp,
1372 local_flags & ~O_TRUNC,
1375 if (!NT_STATUS_IS_OK(status)) {
1376 DEBUG(3,("Error opening file %s (%s) (local_flags=%d) "
1377 "(flags=%d)\n", smb_fname_str_dbg(smb_fname),
1378 nt_errstr(status),local_flags,flags));
1382 if (local_flags & O_NONBLOCK) {
1384 * GPFS can return ETIMEDOUT for pread on
1385 * nonblocking file descriptors when files
1386 * migrated to tape need to be recalled. I
1387 * could imagine this happens elsewhere
1388 * too. With blocking file descriptors this
1391 ret = vfs_set_blocking(fsp, true);
1393 status = map_nt_error_from_unix(errno);
1394 DBG_WARNING("Could not set fd to blocking: "
1395 "%s\n", strerror(errno));
1401 ret = SMB_VFS_FSTAT(fsp, &smb_fname->st);
1403 /* If we have an fd, this stat should succeed. */
1404 DEBUG(0,("Error doing fstat on open file %s "
1406 smb_fname_str_dbg(smb_fname),
1408 status = map_nt_error_from_unix(errno);
1413 if (*p_file_created) {
1414 /* We created this file. */
1416 bool need_re_stat = false;
1417 /* Do all inheritance work after we've
1418 done a successful fstat call and filled
1419 in the stat struct in fsp->fsp_name. */
1421 /* Inherit the ACL if required */
1422 if (lp_inherit_permissions(SNUM(conn))) {
1423 inherit_access_posix_acl(conn,
1427 need_re_stat = true;
1430 /* Change the owner if required. */
1431 if (lp_inherit_owner(SNUM(conn)) != INHERIT_OWNER_NO) {
1432 change_file_owner_to_parent(conn,
1435 need_re_stat = true;
1439 ret = SMB_VFS_FSTAT(fsp, &smb_fname->st);
1440 /* If we have an fd, this stat should succeed. */
1442 DEBUG(0,("Error doing fstat on open file %s "
1444 smb_fname_str_dbg(smb_fname),
1449 notify_fname(conn, NOTIFY_ACTION_ADDED,
1450 FILE_NOTIFY_CHANGE_FILE_NAME,
1451 smb_fname->base_name);
1454 fsp->fh->fd = -1; /* What we used to call a stat open. */
1455 if (!file_existed) {
1456 /* File must exist for a stat open. */
1457 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
1460 status = smbd_check_access_rights(conn,
1466 if (NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND) &&
1467 (fsp->posix_flags & FSP_POSIX_FLAGS_OPEN) &&
1468 S_ISLNK(smb_fname->st.st_ex_mode)) {
1469 /* This is a POSIX stat open for delete
1470 * or rename on a symlink that points
1471 * nowhere. Allow. */
1472 DEBUG(10,("open_file: allowing POSIX "
1473 "open on bad symlink %s\n",
1474 smb_fname_str_dbg(smb_fname)));
1475 status = NT_STATUS_OK;
1478 if (!NT_STATUS_IS_OK(status)) {
1479 DEBUG(10,("open_file: "
1480 "smbd_check_access_rights on file "
1482 smb_fname_str_dbg(smb_fname),
1483 nt_errstr(status) ));
1489 * POSIX allows read-only opens of directories. We don't
1490 * want to do this (we use a different code path for this)
1491 * so catch a directory open and return an EISDIR. JRA.
1494 if(S_ISDIR(smb_fname->st.st_ex_mode)) {
1497 return NT_STATUS_FILE_IS_A_DIRECTORY;
1500 fsp->file_id = vfs_file_id_from_sbuf(conn, &smb_fname->st);
1501 fsp->vuid = req ? req->vuid : UID_FIELD_INVALID;
1502 fsp->file_pid = req ? req->smbpid : 0;
1503 fsp->fsp_flags.can_lock = true;
1504 fsp->fsp_flags.can_read = ((access_mask & FILE_READ_DATA) != 0);
1505 fsp->fsp_flags.can_write =
1507 ((access_mask & (FILE_WRITE_DATA | FILE_APPEND_DATA)) != 0);
1508 fsp->print_file = NULL;
1509 fsp->fsp_flags.modified = false;
1510 fsp->sent_oplock_break = NO_BREAK_SENT;
1511 fsp->fsp_flags.is_directory = false;
1512 if (conn->aio_write_behind_list &&
1513 is_in_path(smb_fname->base_name, conn->aio_write_behind_list,
1514 conn->case_sensitive)) {
1515 fsp->fsp_flags.aio_write_behind = true;
1518 DEBUG(2,("%s opened file %s read=%s write=%s (numopen=%d)\n",
1519 conn->session_info->unix_info->unix_name,
1520 smb_fname_str_dbg(smb_fname),
1521 BOOLSTR(fsp->fsp_flags.can_read),
1522 BOOLSTR(fsp->fsp_flags.can_write),
1523 conn->num_files_open));
1526 return NT_STATUS_OK;
1529 static bool mask_conflict(
1530 uint32_t new_access,
1531 uint32_t existing_access,
1532 uint32_t access_mask,
1533 uint32_t new_sharemode,
1534 uint32_t existing_sharemode,
1535 uint32_t sharemode_mask)
1537 bool want_access = (new_access & access_mask);
1538 bool allow_existing = (existing_sharemode & sharemode_mask);
1539 bool have_access = (existing_access & access_mask);
1540 bool allow_new = (new_sharemode & sharemode_mask);
1542 if (want_access && !allow_existing) {
1543 DBG_DEBUG("Access request 0x%"PRIx32"/0x%"PRIx32" conflicts "
1544 "with existing sharemode 0x%"PRIx32"/0x%"PRIx32"\n",
1551 if (have_access && !allow_new) {
1552 DBG_DEBUG("Sharemode request 0x%"PRIx32"/0x%"PRIx32" conflicts "
1553 "with existing access 0x%"PRIx32"/0x%"PRIx32"\n",
1563 /****************************************************************************
1564 Check if we can open a file with a share mode.
1565 Returns True if conflict, False if not.
1566 ****************************************************************************/
1568 static const uint32_t conflicting_access =
1575 static bool share_conflict(uint32_t e_access_mask,
1576 uint32_t e_share_access,
1577 uint32_t access_mask,
1578 uint32_t share_access)
1582 DBG_DEBUG("existing access_mask = 0x%"PRIx32", "
1583 "existing share access = 0x%"PRIx32", "
1584 "access_mask = 0x%"PRIx32", "
1585 "share_access = 0x%"PRIx32"\n",
1591 if ((e_access_mask & conflicting_access) == 0) {
1592 DBG_DEBUG("No conflict due to "
1593 "existing access_mask = 0x%"PRIx32"\n",
1597 if ((access_mask & conflicting_access) == 0) {
1598 DBG_DEBUG("No conflict due to access_mask = 0x%"PRIx32"\n",
1603 conflict = mask_conflict(
1604 access_mask, e_access_mask, FILE_WRITE_DATA | FILE_APPEND_DATA,
1605 share_access, e_share_access, FILE_SHARE_WRITE);
1606 conflict |= mask_conflict(
1607 access_mask, e_access_mask, FILE_READ_DATA | FILE_EXECUTE,
1608 share_access, e_share_access, FILE_SHARE_READ);
1609 conflict |= mask_conflict(
1610 access_mask, e_access_mask, DELETE_ACCESS,
1611 share_access, e_share_access, FILE_SHARE_DELETE);
1613 DBG_DEBUG("conflict=%s\n", conflict ? "true" : "false");
1617 #if defined(DEVELOPER)
1619 struct validate_my_share_entries_state {
1620 struct smbd_server_connection *sconn;
1622 struct server_id self;
1625 static bool validate_my_share_entries_fn(
1626 struct share_mode_entry *e,
1630 struct validate_my_share_entries_state *state = private_data;
1633 if (!server_id_equal(&state->self, &e->pid)) {
1637 if (e->op_mid == 0) {
1638 /* INTERNAL_OPEN_ONLY */
1642 fsp = file_find_dif(state->sconn, state->fid, e->share_file_id);
1644 DBG_ERR("PANIC : %s\n",
1645 share_mode_str(talloc_tos(), 0, &state->fid, e));
1646 smb_panic("validate_my_share_entries: Cannot match a "
1647 "share entry with an open file\n");
1650 if (((uint16_t)fsp->oplock_type) != e->op_type) {
1659 DBG_ERR("validate_my_share_entries: PANIC : %s\n",
1660 share_mode_str(talloc_tos(), 0, &state->fid, e));
1661 str = talloc_asprintf(talloc_tos(),
1662 "validate_my_share_entries: "
1663 "file %s, oplock_type = 0x%x, op_type = 0x%x\n",
1664 fsp->fsp_name->base_name,
1665 (unsigned int)fsp->oplock_type,
1666 (unsigned int)e->op_type);
1675 * Allowed access mask for stat opens relevant to oplocks
1677 bool is_oplock_stat_open(uint32_t access_mask)
1679 const uint32_t stat_open_bits =
1680 (SYNCHRONIZE_ACCESS|
1681 FILE_READ_ATTRIBUTES|
1682 FILE_WRITE_ATTRIBUTES);
1684 return (((access_mask & stat_open_bits) != 0) &&
1685 ((access_mask & ~stat_open_bits) == 0));
1689 * Allowed access mask for stat opens relevant to leases
1691 bool is_lease_stat_open(uint32_t access_mask)
1693 const uint32_t stat_open_bits =
1694 (SYNCHRONIZE_ACCESS|
1695 FILE_READ_ATTRIBUTES|
1696 FILE_WRITE_ATTRIBUTES|
1697 READ_CONTROL_ACCESS);
1699 return (((access_mask & stat_open_bits) != 0) &&
1700 ((access_mask & ~stat_open_bits) == 0));
1703 struct has_delete_on_close_state {
1707 static bool has_delete_on_close_fn(
1708 struct share_mode_entry *e,
1712 struct has_delete_on_close_state *state = private_data;
1713 state->ret = !share_entry_stale_pid(e);
1717 static bool has_delete_on_close(struct share_mode_lock *lck,
1720 struct has_delete_on_close_state state = { .ret = false };
1723 if (!is_delete_on_close_set(lck, name_hash)) {
1727 ok= share_mode_forall_entries(lck, has_delete_on_close_fn, &state);
1729 DBG_DEBUG("share_mode_forall_entries failed\n");
1735 static void share_mode_flags_get(
1737 uint32_t *access_mask,
1738 uint32_t *share_mode,
1739 uint32_t *lease_type)
1741 if (access_mask != NULL) {
1743 ((flags & SHARE_MODE_ACCESS_READ) ?
1744 FILE_READ_DATA : 0) |
1745 ((flags & SHARE_MODE_ACCESS_WRITE) ?
1746 FILE_WRITE_DATA : 0) |
1747 ((flags & SHARE_MODE_ACCESS_DELETE) ?
1750 if (share_mode != NULL) {
1752 ((flags & SHARE_MODE_SHARE_READ) ?
1753 FILE_SHARE_READ : 0) |
1754 ((flags & SHARE_MODE_SHARE_WRITE) ?
1755 FILE_SHARE_WRITE : 0) |
1756 ((flags & SHARE_MODE_SHARE_DELETE) ?
1757 FILE_SHARE_DELETE : 0);
1759 if (lease_type != NULL) {
1761 ((flags & SHARE_MODE_LEASE_READ) ?
1762 SMB2_LEASE_READ : 0) |
1763 ((flags & SHARE_MODE_LEASE_WRITE) ?
1764 SMB2_LEASE_WRITE : 0) |
1765 ((flags & SHARE_MODE_LEASE_HANDLE) ?
1766 SMB2_LEASE_HANDLE : 0);
1770 static uint16_t share_mode_flags_set(
1772 uint32_t access_mask,
1773 uint32_t share_mode,
1774 uint32_t lease_type)
1776 if (access_mask != UINT32_MAX) {
1777 flags &= ~(SHARE_MODE_ACCESS_READ|
1778 SHARE_MODE_ACCESS_WRITE|
1779 SHARE_MODE_ACCESS_DELETE);
1780 flags |= (access_mask & (FILE_READ_DATA | FILE_EXECUTE)) ?
1781 SHARE_MODE_ACCESS_READ : 0;
1782 flags |= (access_mask & (FILE_WRITE_DATA | FILE_APPEND_DATA)) ?
1783 SHARE_MODE_ACCESS_WRITE : 0;
1784 flags |= (access_mask & (DELETE_ACCESS)) ?
1785 SHARE_MODE_ACCESS_DELETE : 0;
1787 if (share_mode != UINT32_MAX) {
1788 flags &= ~(SHARE_MODE_SHARE_READ|
1789 SHARE_MODE_SHARE_WRITE|
1790 SHARE_MODE_SHARE_DELETE);
1791 flags |= (share_mode & FILE_SHARE_READ) ?
1792 SHARE_MODE_SHARE_READ : 0;
1793 flags |= (share_mode & FILE_SHARE_WRITE) ?
1794 SHARE_MODE_SHARE_WRITE : 0;
1795 flags |= (share_mode & FILE_SHARE_DELETE) ?
1796 SHARE_MODE_SHARE_DELETE : 0;
1798 if (lease_type != UINT32_MAX) {
1799 flags &= ~(SHARE_MODE_LEASE_READ|
1800 SHARE_MODE_LEASE_WRITE|
1801 SHARE_MODE_LEASE_HANDLE);
1802 flags |= (lease_type & SMB2_LEASE_READ) ?
1803 SHARE_MODE_LEASE_READ : 0;
1804 flags |= (lease_type & SMB2_LEASE_WRITE) ?
1805 SHARE_MODE_LEASE_WRITE : 0;
1806 flags |= (lease_type & SMB2_LEASE_HANDLE) ?
1807 SHARE_MODE_LEASE_HANDLE : 0;
1813 static uint16_t share_mode_flags_restrict(
1815 uint32_t access_mask,
1816 uint32_t share_mode,
1817 uint32_t lease_type)
1819 uint32_t existing_access_mask, existing_share_mode;
1820 uint32_t existing_lease_type;
1823 share_mode_flags_get(
1825 &existing_access_mask,
1826 &existing_share_mode,
1827 &existing_lease_type);
1829 existing_access_mask |= access_mask;
1830 if (access_mask & conflicting_access) {
1831 existing_share_mode &= share_mode;
1833 existing_lease_type |= lease_type;
1835 ret = share_mode_flags_set(
1837 existing_access_mask,
1838 existing_share_mode,
1839 existing_lease_type);
1843 /****************************************************************************
1844 Deal with share modes
1845 Invariant: Share mode must be locked on entry and exit.
1846 Returns -1 on error, or number of share modes on success (may be zero).
1847 ****************************************************************************/
1849 struct open_mode_check_state {
1851 uint32_t access_mask;
1852 uint32_t share_access;
1853 uint32_t lease_type;
1856 static bool open_mode_check_fn(
1857 struct share_mode_entry *e,
1861 struct open_mode_check_state *state = private_data;
1862 bool disconnected, stale;
1863 uint32_t access_mask, share_access, lease_type;
1865 disconnected = server_id_is_disconnected(&e->pid);
1870 access_mask = state->access_mask | e->access_mask;
1871 share_access = state->share_access;
1872 if (e->access_mask & conflicting_access) {
1873 share_access &= e->share_access;
1875 lease_type = state->lease_type | get_lease_type(e, state->fid);
1877 if ((access_mask == state->access_mask) &&
1878 (share_access == state->share_access) &&
1879 (lease_type == state->lease_type)) {
1883 stale = share_entry_stale_pid(e);
1888 state->access_mask = access_mask;
1889 state->share_access = share_access;
1890 state->lease_type = lease_type;
1895 static NTSTATUS open_mode_check(connection_struct *conn,
1896 struct share_mode_lock *lck,
1897 uint32_t access_mask,
1898 uint32_t share_access)
1900 struct share_mode_data *d = lck->data;
1901 struct open_mode_check_state state;
1903 bool ok, conflict, have_share_entries;
1905 if (is_oplock_stat_open(access_mask)) {
1906 /* Stat open that doesn't trigger oplock breaks or share mode
1907 * checks... ! JRA. */
1908 return NT_STATUS_OK;
1912 * Check if the share modes will give us access.
1915 #if defined(DEVELOPER)
1917 struct validate_my_share_entries_state validate_state = {
1918 .sconn = conn->sconn,
1920 .self = messaging_server_id(conn->sconn->msg_ctx),
1922 ok = share_mode_forall_entries(
1923 lck, validate_my_share_entries_fn, &validate_state);
1928 have_share_entries = share_mode_have_entries(lck);
1929 if (!have_share_entries) {
1931 * This is a fresh share mode lock where no conflicts
1934 return NT_STATUS_OK;
1937 share_mode_flags_get(
1938 d->flags, &state.access_mask, &state.share_access, NULL);
1940 conflict = share_conflict(
1946 DBG_DEBUG("No conflict due to share_mode_flags access\n");
1947 return NT_STATUS_OK;
1950 state = (struct open_mode_check_state) {
1952 .share_access = (FILE_SHARE_READ|
1958 * Walk the share mode array to recalculate d->flags
1961 ok = share_mode_forall_entries(lck, open_mode_check_fn, &state);
1963 DBG_DEBUG("share_mode_forall_entries failed\n");
1964 return NT_STATUS_INTERNAL_ERROR;
1967 new_flags = share_mode_flags_set(
1968 0, state.access_mask, state.share_access, state.lease_type);
1969 if (new_flags == d->flags) {
1971 * We only end up here if we had a sharing violation
1972 * from d->flags and have recalculated it.
1974 return NT_STATUS_SHARING_VIOLATION;
1977 d->flags = new_flags;
1980 conflict = share_conflict(
1986 DBG_DEBUG("No conflict due to share_mode_flags access\n");
1987 return NT_STATUS_OK;
1990 return NT_STATUS_SHARING_VIOLATION;
1994 * Send a break message to the oplock holder and delay the open for
1998 NTSTATUS send_break_message(struct messaging_context *msg_ctx,
1999 const struct file_id *id,
2000 const struct share_mode_entry *exclusive,
2003 struct oplock_break_message msg = {
2005 .share_file_id = exclusive->share_file_id,
2006 .break_to = break_to,
2008 enum ndr_err_code ndr_err;
2013 struct server_id_buf buf;
2014 DBG_DEBUG("Sending break message to %s\n",
2015 server_id_str_buf(exclusive->pid, &buf));
2016 NDR_PRINT_DEBUG(oplock_break_message, &msg);
2019 ndr_err = ndr_push_struct_blob(
2023 (ndr_push_flags_fn_t)ndr_push_oplock_break_message);
2024 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
2025 DBG_WARNING("ndr_push_oplock_break_message failed: %s\n",
2026 ndr_errstr(ndr_err));
2027 return ndr_map_error2ntstatus(ndr_err);
2030 status = messaging_send(
2031 msg_ctx, exclusive->pid, MSG_SMB_BREAK_REQUEST, &blob);
2032 TALLOC_FREE(blob.data);
2033 if (!NT_STATUS_IS_OK(status)) {
2034 DEBUG(3, ("Could not send oplock break message: %s\n",
2035 nt_errstr(status)));
2041 struct validate_oplock_types_state {
2047 uint32_t num_non_stat_opens;
2050 static bool validate_oplock_types_fn(
2051 struct share_mode_entry *e,
2055 struct validate_oplock_types_state *state = private_data;
2057 if (e->op_mid == 0) {
2058 /* INTERNAL_OPEN_ONLY */
2062 if (e->op_type == NO_OPLOCK && is_oplock_stat_open(e->access_mask)) {
2064 * We ignore stat opens in the table - they always
2065 * have NO_OPLOCK and never get or cause breaks. JRA.
2070 state->num_non_stat_opens += 1;
2072 if (BATCH_OPLOCK_TYPE(e->op_type)) {
2073 /* batch - can only be one. */
2074 if (share_entry_stale_pid(e)) {
2075 DBG_DEBUG("Found stale batch oplock\n");
2078 if (state->ex_or_batch ||
2082 DBG_ERR("Bad batch oplock entry\n");
2083 state->valid = false;
2086 state->batch = true;
2089 if (EXCLUSIVE_OPLOCK_TYPE(e->op_type)) {
2090 if (share_entry_stale_pid(e)) {
2091 DBG_DEBUG("Found stale duplicate oplock\n");
2094 /* Exclusive or batch - can only be one. */
2095 if (state->ex_or_batch ||
2098 DBG_ERR("Bad exclusive or batch oplock entry\n");
2099 state->valid = false;
2102 state->ex_or_batch = true;
2105 if (LEVEL_II_OPLOCK_TYPE(e->op_type)) {
2106 if (state->batch || state->ex_or_batch) {
2107 if (share_entry_stale_pid(e)) {
2108 DBG_DEBUG("Found stale LevelII oplock\n");
2111 DBG_DEBUG("Bad levelII oplock entry\n");
2112 state->valid = false;
2115 state->level2 = true;
2118 if (e->op_type == NO_OPLOCK) {
2119 if (state->batch || state->ex_or_batch) {
2120 if (share_entry_stale_pid(e)) {
2121 DBG_DEBUG("Found stale NO_OPLOCK entry\n");
2124 DBG_ERR("Bad no oplock entry\n");
2125 state->valid = false;
2128 state->no_oplock = true;
2135 * Do internal consistency checks on the share mode for a file.
2138 static bool validate_oplock_types(struct share_mode_lock *lck)
2140 struct validate_oplock_types_state state = { .valid = true };
2143 ok = share_mode_forall_entries(lck, validate_oplock_types_fn, &state);
2145 DBG_DEBUG("share_mode_forall_entries failed\n");
2149 DBG_DEBUG("Got invalid oplock configuration\n");
2153 if ((state.batch || state.ex_or_batch) &&
2154 (state.num_non_stat_opens != 1)) {
2155 DBG_WARNING("got batch (%d) or ex (%d) non-exclusively "
2158 (int)state.ex_or_batch,
2159 state.num_non_stat_opens);
2166 static bool is_same_lease(const files_struct *fsp,
2167 const struct share_mode_entry *e,
2168 const struct smb2_lease *lease)
2170 if (e->op_type != LEASE_OPLOCK) {
2173 if (lease == NULL) {
2177 return smb2_lease_equal(fsp_client_guid(fsp),
2183 static bool file_has_brlocks(files_struct *fsp)
2185 struct byte_range_lock *br_lck;
2187 br_lck = brl_get_locks_readonly(fsp);
2191 return (brl_num_locks(br_lck) > 0);
2194 struct fsp_lease *find_fsp_lease(struct files_struct *new_fsp,
2195 const struct smb2_lease_key *key,
2196 uint32_t current_state,
2197 uint16_t lease_version,
2198 uint16_t lease_epoch)
2200 struct files_struct *fsp;
2203 * TODO: Measure how expensive this loop is with thousands of open
2207 for (fsp = file_find_di_first(new_fsp->conn->sconn, new_fsp->file_id);
2209 fsp = file_find_di_next(fsp)) {
2211 if (fsp == new_fsp) {
2214 if (fsp->oplock_type != LEASE_OPLOCK) {
2217 if (smb2_lease_key_equal(&fsp->lease->lease.lease_key, key)) {
2218 fsp->lease->ref_count += 1;
2223 /* Not found - must be leased in another smbd. */
2224 new_fsp->lease = talloc_zero(new_fsp->conn->sconn, struct fsp_lease);
2225 if (new_fsp->lease == NULL) {
2228 new_fsp->lease->ref_count = 1;
2229 new_fsp->lease->sconn = new_fsp->conn->sconn;
2230 new_fsp->lease->lease.lease_key = *key;
2231 new_fsp->lease->lease.lease_state = current_state;
2233 * We internally treat all leases as V2 and update
2234 * the epoch, but when sending breaks it matters if
2235 * the requesting lease was v1 or v2.
2237 new_fsp->lease->lease.lease_version = lease_version;
2238 new_fsp->lease->lease.lease_epoch = lease_epoch;
2239 return new_fsp->lease;
2242 static NTSTATUS try_lease_upgrade(struct files_struct *fsp,
2243 struct share_mode_lock *lck,
2244 const struct GUID *client_guid,
2245 const struct smb2_lease *lease,
2249 uint32_t current_state, breaking_to_requested, breaking_to_required;
2251 uint16_t lease_version, epoch;
2252 uint32_t existing, requested;
2255 status = leases_db_get(
2261 &breaking_to_requested,
2262 &breaking_to_required,
2265 if (!NT_STATUS_IS_OK(status)) {
2269 fsp->lease = find_fsp_lease(
2275 if (fsp->lease == NULL) {
2276 DEBUG(1, ("Did not find existing lease for file %s\n",
2278 return NT_STATUS_NO_MEMORY;
2282 * Upgrade only if the requested lease is a strict upgrade.
2284 existing = current_state;
2285 requested = lease->lease_state;
2288 * Tricky: This test makes sure that "requested" is a
2289 * strict bitwise superset of "existing".
2291 do_upgrade = ((existing & requested) == existing);
2294 * Upgrade only if there's a change.
2296 do_upgrade &= (granted != existing);
2299 * Upgrade only if other leases don't prevent what was asked
2302 do_upgrade &= (granted == requested);
2305 * only upgrade if we are not in breaking state
2307 do_upgrade &= !breaking;
2309 DEBUG(10, ("existing=%"PRIu32", requested=%"PRIu32", "
2310 "granted=%"PRIu32", do_upgrade=%d\n",
2311 existing, requested, granted, (int)do_upgrade));
2314 NTSTATUS set_status;
2316 current_state = granted;
2319 set_status = leases_db_set(
2324 breaking_to_requested,
2325 breaking_to_required,
2329 if (!NT_STATUS_IS_OK(set_status)) {
2330 DBG_DEBUG("leases_db_set failed: %s\n",
2331 nt_errstr(set_status));
2336 fsp_lease_update(fsp);
2338 return NT_STATUS_OK;
2341 static NTSTATUS grant_new_fsp_lease(struct files_struct *fsp,
2342 struct share_mode_lock *lck,
2343 const struct GUID *client_guid,
2344 const struct smb2_lease *lease,
2347 struct share_mode_data *d = lck->data;
2350 fsp->lease = talloc_zero(fsp->conn->sconn, struct fsp_lease);
2351 if (fsp->lease == NULL) {
2352 return NT_STATUS_INSUFFICIENT_RESOURCES;
2354 fsp->lease->ref_count = 1;
2355 fsp->lease->sconn = fsp->conn->sconn;
2356 fsp->lease->lease.lease_version = lease->lease_version;
2357 fsp->lease->lease.lease_key = lease->lease_key;
2358 fsp->lease->lease.lease_state = granted;
2359 fsp->lease->lease.lease_epoch = lease->lease_epoch + 1;
2361 status = leases_db_add(client_guid,
2364 fsp->lease->lease.lease_state,
2365 fsp->lease->lease.lease_version,
2366 fsp->lease->lease.lease_epoch,
2367 fsp->conn->connectpath,
2368 fsp->fsp_name->base_name,
2369 fsp->fsp_name->stream_name);
2370 if (!NT_STATUS_IS_OK(status)) {
2371 DEBUG(10, ("%s: leases_db_add failed: %s\n", __func__,
2372 nt_errstr(status)));
2373 TALLOC_FREE(fsp->lease);
2374 return NT_STATUS_INSUFFICIENT_RESOURCES;
2379 return NT_STATUS_OK;
2382 static NTSTATUS grant_fsp_lease(struct files_struct *fsp,
2383 struct share_mode_lock *lck,
2384 const struct smb2_lease *lease,
2387 const struct GUID *client_guid = fsp_client_guid(fsp);
2390 status = try_lease_upgrade(fsp, lck, client_guid, lease, granted);
2392 if (NT_STATUS_EQUAL(status, NT_STATUS_NOT_FOUND)) {
2393 status = grant_new_fsp_lease(
2394 fsp, lck, client_guid, lease, granted);
2400 static int map_lease_type_to_oplock(uint32_t lease_type)
2402 int result = NO_OPLOCK;
2404 switch (lease_type) {
2405 case SMB2_LEASE_READ|SMB2_LEASE_WRITE|SMB2_LEASE_HANDLE:
2406 result = BATCH_OPLOCK|EXCLUSIVE_OPLOCK;
2408 case SMB2_LEASE_READ|SMB2_LEASE_WRITE:
2409 result = EXCLUSIVE_OPLOCK;
2411 case SMB2_LEASE_READ|SMB2_LEASE_HANDLE:
2412 case SMB2_LEASE_READ:
2413 result = LEVEL_II_OPLOCK;
2420 struct delay_for_oplock_state {
2421 struct files_struct *fsp;
2422 const struct smb2_lease *lease;
2423 bool will_overwrite;
2424 uint32_t delay_mask;
2425 bool first_open_attempt;
2426 bool got_handle_lease;
2428 bool have_other_lease;
2432 static bool delay_for_oplock_fn(
2433 struct share_mode_entry *e,
2437 struct delay_for_oplock_state *state = private_data;
2438 struct files_struct *fsp = state->fsp;
2439 const struct smb2_lease *lease = state->lease;
2440 bool e_is_lease = (e->op_type == LEASE_OPLOCK);
2441 uint32_t e_lease_type = get_lease_type(e, fsp->file_id);
2443 bool lease_is_breaking = false;
2448 if (lease != NULL) {
2449 bool our_lease = is_same_lease(fsp, e, lease);
2451 DBG_DEBUG("Ignoring our own lease\n");
2456 status = leases_db_get(
2460 NULL, /* current_state */
2462 NULL, /* breaking_to_requested */
2463 NULL, /* breaking_to_required */
2464 NULL, /* lease_version */
2468 * leases_db_get() can return NT_STATUS_NOT_FOUND
2469 * if the share_mode_entry e is stale and the
2470 * lease record was already removed. In this case return
2471 * false so the traverse continues.
2474 if (NT_STATUS_EQUAL(status, NT_STATUS_NOT_FOUND) &&
2475 share_entry_stale_pid(e))
2477 struct GUID_txt_buf guid_strbuf;
2478 struct file_id_buf file_id_strbuf;
2479 DBG_DEBUG("leases_db_get for client_guid [%s] "
2480 "lease_key [%"PRIu64"/%"PRIu64"] "
2481 "file_id [%s] failed for stale "
2482 "share_mode_entry\n",
2483 GUID_buf_string(&e->client_guid, &guid_strbuf),
2484 e->lease_key.data[0],
2485 e->lease_key.data[1],
2486 file_id_str_buf(fsp->file_id, &file_id_strbuf));
2489 if (!NT_STATUS_IS_OK(status)) {
2490 struct GUID_txt_buf guid_strbuf;
2491 struct file_id_buf file_id_strbuf;
2492 DBG_ERR("leases_db_get for client_guid [%s] "
2493 "lease_key [%"PRIu64"/%"PRIu64"] "
2494 "file_id [%s] failed: %s\n",
2495 GUID_buf_string(&e->client_guid, &guid_strbuf),
2496 e->lease_key.data[0],
2497 e->lease_key.data[1],
2498 file_id_str_buf(fsp->file_id, &file_id_strbuf),
2500 smb_panic("leases_db_get() failed");
2504 if (!state->got_handle_lease &&
2505 ((e_lease_type & SMB2_LEASE_HANDLE) != 0) &&
2506 !share_entry_stale_pid(e)) {
2507 state->got_handle_lease = true;
2510 if (!state->got_oplock &&
2511 (e->op_type != LEASE_OPLOCK) &&
2512 !share_entry_stale_pid(e)) {
2513 state->got_oplock = true;
2516 if (!state->have_other_lease &&
2517 !is_same_lease(fsp, e, lease) &&
2518 !share_entry_stale_pid(e)) {
2519 state->have_other_lease = true;
2522 if (e_is_lease && is_lease_stat_open(fsp->access_mask)) {
2526 break_to = e_lease_type & ~state->delay_mask;
2528 if (state->will_overwrite) {
2529 break_to &= ~(SMB2_LEASE_HANDLE|SMB2_LEASE_READ);
2532 DBG_DEBUG("e_lease_type %u, will_overwrite: %u\n",
2533 (unsigned)e_lease_type,
2534 (unsigned)state->will_overwrite);
2536 if ((e_lease_type & ~break_to) == 0) {
2537 if (lease_is_breaking) {
2538 state->delay = true;
2543 if (share_entry_stale_pid(e)) {
2547 if (state->will_overwrite) {
2549 * If we break anyway break to NONE directly.
2550 * Otherwise vfs_set_filelen() will trigger the
2553 break_to &= ~(SMB2_LEASE_READ|SMB2_LEASE_WRITE);
2558 * Oplocks only support breaking to R or NONE.
2560 break_to &= ~(SMB2_LEASE_HANDLE|SMB2_LEASE_WRITE);
2563 DBG_DEBUG("breaking from %d to %d\n",
2567 fsp->conn->sconn->msg_ctx, &fsp->file_id, e, break_to);
2568 if (e_lease_type & state->delay_mask) {
2569 state->delay = true;
2571 if (lease_is_breaking && !state->first_open_attempt) {
2572 state->delay = true;
2578 static NTSTATUS delay_for_oplock(files_struct *fsp,
2580 const struct smb2_lease *lease,
2581 struct share_mode_lock *lck,
2582 bool have_sharing_violation,
2583 uint32_t create_disposition,
2584 bool first_open_attempt)
2586 struct delay_for_oplock_state state = {
2589 .first_open_attempt = first_open_attempt,
2595 if (is_oplock_stat_open(fsp->access_mask)) {
2599 state.delay_mask = have_sharing_violation ?
2600 SMB2_LEASE_HANDLE : SMB2_LEASE_WRITE;
2602 switch (create_disposition) {
2603 case FILE_SUPERSEDE:
2604 case FILE_OVERWRITE:
2605 case FILE_OVERWRITE_IF:
2606 state.will_overwrite = true;
2609 state.will_overwrite = false;
2613 ok = share_mode_forall_entries(lck, delay_for_oplock_fn, &state);
2615 return NT_STATUS_INTERNAL_ERROR;
2619 return NT_STATUS_RETRY;
2623 if (have_sharing_violation) {
2624 return NT_STATUS_SHARING_VIOLATION;
2627 if (oplock_request == LEASE_OPLOCK) {
2628 if (lease == NULL) {
2630 * The SMB2 layer should have checked this
2632 return NT_STATUS_INTERNAL_ERROR;
2635 granted = lease->lease_state;
2637 if (lp_kernel_oplocks(SNUM(fsp->conn))) {
2638 DEBUG(10, ("No lease granted because kernel oplocks are enabled\n"));
2639 granted = SMB2_LEASE_NONE;
2641 if ((granted & (SMB2_LEASE_READ|SMB2_LEASE_WRITE)) == 0) {
2642 DEBUG(10, ("No read or write lease requested\n"));
2643 granted = SMB2_LEASE_NONE;
2645 if (granted == SMB2_LEASE_WRITE) {
2646 DEBUG(10, ("pure write lease requested\n"));
2647 granted = SMB2_LEASE_NONE;
2649 if (granted == (SMB2_LEASE_WRITE|SMB2_LEASE_HANDLE)) {
2650 DEBUG(10, ("write and handle lease requested\n"));
2651 granted = SMB2_LEASE_NONE;
2654 granted = map_oplock_to_lease_type(
2655 oplock_request & ~SAMBA_PRIVATE_OPLOCK_MASK);
2658 if (lp_locking(fsp->conn->params) && file_has_brlocks(fsp)) {
2659 DBG_DEBUG("file %s has byte range locks\n",
2661 granted &= ~SMB2_LEASE_READ;
2664 if (state.have_other_lease) {
2666 * Can grant only one writer
2668 granted &= ~SMB2_LEASE_WRITE;
2671 if ((granted & SMB2_LEASE_READ) && !(granted & SMB2_LEASE_WRITE)) {
2673 (global_client_caps & CAP_LEVEL_II_OPLOCKS) &&
2674 lp_level2_oplocks(SNUM(fsp->conn));
2676 if (!allow_level2) {
2677 granted = SMB2_LEASE_NONE;
2681 if (oplock_request == LEASE_OPLOCK) {
2682 if (state.got_oplock) {
2683 granted &= ~SMB2_LEASE_HANDLE;
2686 fsp->oplock_type = LEASE_OPLOCK;
2688 status = grant_fsp_lease(fsp, lck, lease, granted);
2689 if (!NT_STATUS_IS_OK(status)) {
2694 DBG_DEBUG("lease_state=%d\n", fsp->lease->lease.lease_state);
2696 if (state.got_handle_lease) {
2697 granted = SMB2_LEASE_NONE;
2700 fsp->oplock_type = map_lease_type_to_oplock(granted);
2702 status = set_file_oplock(fsp);
2703 if (!NT_STATUS_IS_OK(status)) {
2705 * Could not get the kernel oplock
2707 fsp->oplock_type = NO_OPLOCK;
2711 if ((granted & SMB2_LEASE_READ) &&
2712 ((lck->data->flags & SHARE_MODE_LEASE_READ) == 0)) {
2713 lck->data->flags |= SHARE_MODE_LEASE_READ;
2714 lck->data->modified = true;
2717 DBG_DEBUG("oplock type 0x%x on file %s\n",
2718 fsp->oplock_type, fsp_str_dbg(fsp));
2720 return NT_STATUS_OK;
2723 static NTSTATUS handle_share_mode_lease(
2725 struct share_mode_lock *lck,
2726 uint32_t create_disposition,
2727 uint32_t access_mask,
2728 uint32_t share_access,
2730 const struct smb2_lease *lease,
2731 bool first_open_attempt)
2733 bool sharing_violation = false;
2736 status = open_mode_check(
2737 fsp->conn, lck, access_mask, share_access);
2738 if (NT_STATUS_EQUAL(status, NT_STATUS_SHARING_VIOLATION)) {
2739 sharing_violation = true;
2740 status = NT_STATUS_OK; /* handled later */
2743 if (!NT_STATUS_IS_OK(status)) {
2747 if (oplock_request == INTERNAL_OPEN_ONLY) {
2748 if (sharing_violation) {
2749 DBG_DEBUG("Sharing violation for internal open\n");
2750 return NT_STATUS_SHARING_VIOLATION;
2754 * Internal opens never do oplocks or leases. We don't
2755 * need to go through delay_for_oplock().
2757 fsp->oplock_type = NO_OPLOCK;
2759 return NT_STATUS_OK;
2762 status = delay_for_oplock(
2769 first_open_attempt);
2770 if (!NT_STATUS_IS_OK(status)) {
2774 return NT_STATUS_OK;
2777 static bool request_timed_out(struct smb_request *req, struct timeval timeout)
2779 struct timeval now, end_time;
2781 end_time = timeval_sum(&req->request_time, &timeout);
2782 return (timeval_compare(&end_time, &now) < 0);
2785 struct defer_open_state {
2786 struct smbXsrv_connection *xconn;
2790 static void defer_open_done(struct tevent_req *req);
2793 * Defer an open and watch a locking.tdb record
2795 * This defers an open that gets rescheduled once the locking.tdb record watch
2796 * is triggered by a change to the record.
2798 * It is used to defer opens that triggered an oplock break and for the SMB1
2799 * sharing violation delay.
2801 static void defer_open(struct share_mode_lock *lck,
2802 struct timeval timeout,
2803 struct smb_request *req,
2806 struct deferred_open_record *open_rec = NULL;
2807 struct timeval abs_timeout;
2808 struct defer_open_state *watch_state;
2809 struct tevent_req *watch_req;
2810 struct timeval_buf tvbuf1, tvbuf2;
2811 struct file_id_buf fbuf;
2814 abs_timeout = timeval_sum(&req->request_time, &timeout);
2816 DBG_DEBUG("request time [%s] timeout [%s] mid [%" PRIu64 "] "
2818 timeval_str_buf(&req->request_time, false, true, &tvbuf1),
2819 timeval_str_buf(&abs_timeout, false, true, &tvbuf2),
2821 file_id_str_buf(id, &fbuf));
2823 open_rec = talloc_zero(NULL, struct deferred_open_record);
2824 if (open_rec == NULL) {
2826 exit_server("talloc failed");
2829 watch_state = talloc(open_rec, struct defer_open_state);
2830 if (watch_state == NULL) {
2831 exit_server("talloc failed");
2833 watch_state->xconn = req->xconn;
2834 watch_state->mid = req->mid;
2836 DBG_DEBUG("defering mid %" PRIu64 "\n", req->mid);
2838 watch_req = share_mode_watch_send(
2842 (struct server_id){0});
2843 if (watch_req == NULL) {
2844 exit_server("Could not watch share mode record");
2846 tevent_req_set_callback(watch_req, defer_open_done, watch_state);
2848 ok = tevent_req_set_endtime(watch_req, req->sconn->ev_ctx, abs_timeout);
2850 exit_server("tevent_req_set_endtime failed");
2853 ok = push_deferred_open_message_smb(req, timeout, id, open_rec);
2856 exit_server("push_deferred_open_message_smb failed");
2860 static void defer_open_done(struct tevent_req *req)
2862 struct defer_open_state *state = tevent_req_callback_data(
2863 req, struct defer_open_state);
2867 status = share_mode_watch_recv(req, NULL, NULL);
2869 if (!NT_STATUS_IS_OK(status)) {
2870 DEBUG(5, ("dbwrap_watched_watch_recv returned %s\n",
2871 nt_errstr(status)));
2873 * Even if it failed, retry anyway. TODO: We need a way to
2874 * tell a re-scheduled open about that error.
2878 DEBUG(10, ("scheduling mid %llu\n", (unsigned long long)state->mid));
2880 ret = schedule_deferred_open_message_smb(state->xconn, state->mid);
2886 * Actually attempt the kernel oplock polling open.
2889 static void poll_open_fn(struct tevent_context *ev,
2890 struct tevent_timer *te,
2891 struct timeval current_time,
2894 struct deferred_open_record *open_rec = talloc_get_type_abort(
2895 private_data, struct deferred_open_record);
2898 TALLOC_FREE(open_rec->watch_req);
2900 ok = schedule_deferred_open_message_smb(
2901 open_rec->xconn, open_rec->mid);
2903 exit_server("schedule_deferred_open_message_smb failed");
2905 DBG_DEBUG("timer fired. Retrying open !\n");
2908 static void poll_open_done(struct tevent_req *subreq);
2911 * Reschedule an open for 1 second from now, if not timed out.
2913 static bool setup_poll_open(
2914 struct smb_request *req,
2915 struct share_mode_lock *lck,
2917 struct timeval max_timeout,
2918 struct timeval interval)
2921 struct deferred_open_record *open_rec = NULL;
2922 struct timeval endtime, next_interval;
2923 struct file_id_buf ftmp;
2925 if (request_timed_out(req, max_timeout)) {
2929 open_rec = talloc_zero(NULL, struct deferred_open_record);
2930 if (open_rec == NULL) {
2931 DBG_WARNING("talloc failed\n");
2934 open_rec->xconn = req->xconn;
2935 open_rec->mid = req->mid;
2938 * Make sure open_rec->te does not come later than the
2939 * request's maximum endtime.
2942 endtime = timeval_sum(&req->request_time, &max_timeout);
2943 next_interval = timeval_current_ofs(interval.tv_sec, interval.tv_usec);
2944 next_interval = timeval_min(&endtime, &next_interval);
2946 open_rec->te = tevent_add_timer(
2952 if (open_rec->te == NULL) {
2953 DBG_WARNING("tevent_add_timer failed\n");
2954 TALLOC_FREE(open_rec);
2959 open_rec->watch_req = share_mode_watch_send(
2963 (struct server_id) {0});
2964 if (open_rec->watch_req == NULL) {
2965 DBG_WARNING("share_mode_watch_send failed\n");
2966 TALLOC_FREE(open_rec);
2969 tevent_req_set_callback(
2970 open_rec->watch_req, poll_open_done, open_rec);
2973 ok = push_deferred_open_message_smb(req, max_timeout, id, open_rec);
2975 DBG_WARNING("push_deferred_open_message_smb failed\n");
2976 TALLOC_FREE(open_rec);
2980 DBG_DEBUG("poll request time [%s] mid [%" PRIu64 "] file_id [%s]\n",
2981 timeval_string(talloc_tos(), &req->request_time, false),
2983 file_id_str_buf(id, &ftmp));
2988 static void poll_open_done(struct tevent_req *subreq)
2990 struct deferred_open_record *open_rec = tevent_req_callback_data(
2991 subreq, struct deferred_open_record);
2995 status = share_mode_watch_recv(subreq, NULL, NULL);
2996 TALLOC_FREE(subreq);
2997 DBG_DEBUG("dbwrap_watched_watch_recv returned %s\n",
3000 ok = schedule_deferred_open_message_smb(
3001 open_rec->xconn, open_rec->mid);
3003 exit_server("schedule_deferred_open_message_smb failed");
3007 bool defer_smb1_sharing_violation(struct smb_request *req)
3012 if (!lp_defer_sharing_violations()) {
3017 * Try every 200msec up to (by default) one second. To be
3018 * precise, according to behaviour note <247> in [MS-CIFS],
3019 * the server tries 5 times. But up to one second should be
3023 timeout_usecs = lp_parm_int(
3027 SHARING_VIOLATION_USEC_WAIT);
3029 ok = setup_poll_open(
3032 (struct file_id) {0},
3033 (struct timeval) { .tv_usec = timeout_usecs },
3034 (struct timeval) { .tv_usec = 200000 });
3038 /****************************************************************************
3039 On overwrite open ensure that the attributes match.
3040 ****************************************************************************/
3042 static bool open_match_attributes(connection_struct *conn,
3043 uint32_t old_dos_attr,
3044 uint32_t new_dos_attr,
3045 mode_t new_unx_mode,
3046 mode_t *returned_unx_mode)
3048 uint32_t noarch_old_dos_attr, noarch_new_dos_attr;
3050 noarch_old_dos_attr = (old_dos_attr & ~FILE_ATTRIBUTE_ARCHIVE);
3051 noarch_new_dos_attr = (new_dos_attr & ~FILE_ATTRIBUTE_ARCHIVE);
3053 if((noarch_old_dos_attr == 0 && noarch_new_dos_attr != 0) ||
3054 (noarch_old_dos_attr != 0 && ((noarch_old_dos_attr & noarch_new_dos_attr) == noarch_old_dos_attr))) {
3055 *returned_unx_mode = new_unx_mode;
3057 *returned_unx_mode = (mode_t)0;
3060 DEBUG(10,("open_match_attributes: old_dos_attr = 0x%x, "
3061 "new_dos_attr = 0x%x "
3062 "returned_unx_mode = 0%o\n",
3063 (unsigned int)old_dos_attr,
3064 (unsigned int)new_dos_attr,
3065 (unsigned int)*returned_unx_mode ));
3067 /* If we're mapping SYSTEM and HIDDEN ensure they match. */
3068 if (lp_map_system(SNUM(conn)) || lp_store_dos_attributes(SNUM(conn))) {
3069 if ((old_dos_attr & FILE_ATTRIBUTE_SYSTEM) &&
3070 !(new_dos_attr & FILE_ATTRIBUTE_SYSTEM)) {
3074 if (lp_map_hidden(SNUM(conn)) || lp_store_dos_attributes(SNUM(conn))) {
3075 if ((old_dos_attr & FILE_ATTRIBUTE_HIDDEN) &&
3076 !(new_dos_attr & FILE_ATTRIBUTE_HIDDEN)) {
3083 static void schedule_defer_open(struct share_mode_lock *lck,
3085 struct smb_request *req)
3087 /* This is a relative time, added to the absolute
3088 request_time value to get the absolute timeout time.
3089 Note that if this is the second or greater time we enter
3090 this codepath for this particular request mid then
3091 request_time is left as the absolute time of the *first*
3092 time this request mid was processed. This is what allows
3093 the request to eventually time out. */
3095 struct timeval timeout;
3097 /* Normally the smbd we asked should respond within
3098 * OPLOCK_BREAK_TIMEOUT seconds regardless of whether
3099 * the client did, give twice the timeout as a safety
3100 * measure here in case the other smbd is stuck
3101 * somewhere else. */
3103 timeout = timeval_set(OPLOCK_BREAK_TIMEOUT*2, 0);
3105 if (request_timed_out(req, timeout)) {
3109 defer_open(lck, timeout, req, id);
3112 /****************************************************************************
3113 Reschedule an open call that went asynchronous.
3114 ****************************************************************************/
3116 static void schedule_async_open_timer(struct tevent_context *ev,
3117 struct tevent_timer *te,
3118 struct timeval current_time,
3121 exit_server("async open timeout");
3124 static void schedule_async_open(struct smb_request *req)
3126 struct deferred_open_record *open_rec = NULL;
3127 struct timeval timeout = timeval_set(20, 0);
3130 if (request_timed_out(req, timeout)) {
3134 open_rec = talloc_zero(NULL, struct deferred_open_record);
3135 if (open_rec == NULL) {
3136 exit_server("deferred_open_record_create failed");
3138 open_rec->async_open = true;
3140 ok = push_deferred_open_message_smb(
3141 req, timeout, (struct file_id){0}, open_rec);
3143 exit_server("push_deferred_open_message_smb failed");
3146 open_rec->te = tevent_add_timer(req->sconn->ev_ctx,
3148 timeval_current_ofs(20, 0),
3149 schedule_async_open_timer,
3151 if (open_rec->te == NULL) {
3152 exit_server("tevent_add_timer failed");
3156 /****************************************************************************
3157 Work out what access_mask to use from what the client sent us.
3158 ****************************************************************************/
3160 static NTSTATUS smbd_calculate_maximum_allowed_access(
3161 connection_struct *conn,
3162 struct files_struct *dirfsp,
3163 const struct smb_filename *smb_fname,
3165 uint32_t *p_access_mask)
3167 struct security_descriptor *sd;
3168 uint32_t access_granted;
3171 SMB_ASSERT(dirfsp == conn->cwd_fsp);
3173 if (!use_privs && (get_current_uid(conn) == (uid_t)0)) {
3174 *p_access_mask |= FILE_GENERIC_ALL;
3175 return NT_STATUS_OK;
3178 status = SMB_VFS_GET_NT_ACL_AT(conn,
3187 if (NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
3189 * File did not exist
3191 *p_access_mask = FILE_GENERIC_ALL;
3192 return NT_STATUS_OK;
3194 if (!NT_STATUS_IS_OK(status)) {
3195 DEBUG(10,("Could not get acl on file %s: %s\n",
3196 smb_fname_str_dbg(smb_fname),
3197 nt_errstr(status)));
3198 return NT_STATUS_ACCESS_DENIED;
3202 * If we can access the path to this file, by
3203 * default we have FILE_READ_ATTRIBUTES from the
3204 * containing directory. See the section:
3205 * "Algorithm to Check Access to an Existing File"
3208 * se_file_access_check()
3209 * also takes care of owner WRITE_DAC and READ_CONTROL.
3211 status = se_file_access_check(sd,
3212 get_current_nttok(conn),
3214 (*p_access_mask & ~FILE_READ_ATTRIBUTES),
3219 if (!NT_STATUS_IS_OK(status)) {
3220 DEBUG(10, ("Access denied on file %s: "
3221 "when calculating maximum access\n",
3222 smb_fname_str_dbg(smb_fname)));
3223 return NT_STATUS_ACCESS_DENIED;
3225 *p_access_mask = (access_granted | FILE_READ_ATTRIBUTES);
3227 if (!(access_granted & DELETE_ACCESS)) {
3228 if (can_delete_file_in_directory(conn,
3232 *p_access_mask |= DELETE_ACCESS;
3236 return NT_STATUS_OK;
3239 NTSTATUS smbd_calculate_access_mask(connection_struct *conn,
3240 struct files_struct *dirfsp,
3241 const struct smb_filename *smb_fname,
3243 uint32_t access_mask,
3244 uint32_t *access_mask_out)
3247 uint32_t orig_access_mask = access_mask;
3248 uint32_t rejected_share_access;
3250 SMB_ASSERT(dirfsp == conn->cwd_fsp);
3252 if (access_mask & SEC_MASK_INVALID) {
3253 DBG_DEBUG("access_mask [%8x] contains invalid bits\n",
3255 return NT_STATUS_ACCESS_DENIED;
3259 * Convert GENERIC bits to specific bits.
3262 se_map_generic(&access_mask, &file_generic_mapping);
3264 /* Calculate MAXIMUM_ALLOWED_ACCESS if requested. */
3265 if (access_mask & MAXIMUM_ALLOWED_ACCESS) {
3267 status = smbd_calculate_maximum_allowed_access(conn,
3273 if (!NT_STATUS_IS_OK(status)) {
3277 access_mask &= conn->share_access;
3280 rejected_share_access = access_mask & ~(conn->share_access);
3282 if (rejected_share_access) {
3283 DEBUG(10, ("smbd_calculate_access_mask: Access denied on "
3284 "file %s: rejected by share access mask[0x%08X] "
3285 "orig[0x%08X] mapped[0x%08X] reject[0x%08X]\n",
3286 smb_fname_str_dbg(smb_fname),
3288 orig_access_mask, access_mask,
3289 rejected_share_access));
3290 return NT_STATUS_ACCESS_DENIED;
3293 *access_mask_out = access_mask;
3294 return NT_STATUS_OK;
3297 /****************************************************************************
3298 Remove the deferred open entry under lock.
3299 ****************************************************************************/
3301 /****************************************************************************
3302 Return true if this is a state pointer to an asynchronous create.
3303 ****************************************************************************/
3305 bool is_deferred_open_async(const struct deferred_open_record *rec)
3307 return rec->async_open;
3310 static bool clear_ads(uint32_t create_disposition)
3314 switch (create_disposition) {
3315 case FILE_SUPERSEDE:
3316 case FILE_OVERWRITE_IF:
3317 case FILE_OVERWRITE:
3326 static int disposition_to_open_flags(uint32_t create_disposition)
3331 * Currently we're using FILE_SUPERSEDE as the same as
3332 * FILE_OVERWRITE_IF but they really are
3333 * different. FILE_SUPERSEDE deletes an existing file
3334 * (requiring delete access) then recreates it.
3337 switch (create_disposition) {
3338 case FILE_SUPERSEDE:
3339 case FILE_OVERWRITE_IF:
3341 * If file exists replace/overwrite. If file doesn't
3344 ret = O_CREAT|O_TRUNC;
3349 * If file exists open. If file doesn't exist error.
3354 case FILE_OVERWRITE:
3356 * If file exists overwrite. If file doesn't exist
3364 * If file exists error. If file doesn't exist create.
3366 ret = O_CREAT|O_EXCL;
3371 * If file exists open. If file doesn't exist create.
3379 static int calculate_open_access_flags(uint32_t access_mask,
3380 uint32_t private_flags)
3382 bool need_write, need_read;
3385 * Note that we ignore the append flag as append does not
3386 * mean the same thing under DOS and Unix.
3389 need_write = (access_mask & (FILE_WRITE_DATA | FILE_APPEND_DATA));
3394 /* DENY_DOS opens are always underlying read-write on the
3395 file handle, no matter what the requested access mask
3399 ((private_flags & NTCREATEX_OPTIONS_PRIVATE_DENY_DOS) ||
3400 access_mask & (FILE_READ_ATTRIBUTES|FILE_READ_DATA|
3401 FILE_READ_EA|FILE_EXECUTE));
3409 /****************************************************************************
3410 Open a file with a share mode. Passed in an already created files_struct *.
3411 ****************************************************************************/
3413 static NTSTATUS open_file_ntcreate(connection_struct *conn,
3414 struct smb_request *req,
3415 uint32_t access_mask, /* access bits (FILE_READ_DATA etc.) */
3416 uint32_t share_access, /* share constants (FILE_SHARE_READ etc) */
3417 uint32_t create_disposition, /* FILE_OPEN_IF etc. */
3418 uint32_t create_options, /* options such as delete on close. */
3419 uint32_t new_dos_attributes, /* attributes used for new file. */
3420 int oplock_request, /* internal Samba oplock codes. */
3421 const struct smb2_lease *lease,
3422 /* Information (FILE_EXISTS etc.) */
3423 uint32_t private_flags, /* Samba specific flags. */
3427 struct smb_filename *smb_fname = fsp->fsp_name;
3430 bool file_existed = VALID_STAT(smb_fname->st);
3431 bool def_acl = False;
3432 bool posix_open = False;
3433 bool new_file_created = False;
3434 bool first_open_attempt = true;
3435 NTSTATUS fsp_open = NT_STATUS_ACCESS_DENIED;
3436 mode_t new_unx_mode = (mode_t)0;
3437 mode_t unx_mode = (mode_t)0;
3439 uint32_t existing_dos_attributes = 0;
3440 struct share_mode_lock *lck = NULL;
3441 uint32_t open_access_mask = access_mask;
3443 struct smb_filename *parent_dir_fname = NULL;
3444 SMB_STRUCT_STAT saved_stat = smb_fname->st;
3445 struct timespec old_write_time;
3447 bool setup_poll = false;
3450 SMB_ASSERT(fsp->dirfsp == conn->cwd_fsp);
3452 if (conn->printer) {
3454 * Printers are handled completely differently.
3455 * Most of the passed parameters are ignored.
3459 *pinfo = FILE_WAS_CREATED;
3462 DEBUG(10, ("open_file_ntcreate: printer open fname=%s\n",
3463 smb_fname_str_dbg(smb_fname)));
3466 DEBUG(0,("open_file_ntcreate: printer open without "
3467 "an SMB request!\n"));
3468 return NT_STATUS_INTERNAL_ERROR;
3471 return print_spool_open(fsp, smb_fname->base_name,
3475 ok = parent_smb_fname(talloc_tos(),
3480 return NT_STATUS_NO_MEMORY;
3483 if (new_dos_attributes & FILE_FLAG_POSIX_SEMANTICS) {
3485 unx_mode = (mode_t)(new_dos_attributes & ~FILE_FLAG_POSIX_SEMANTICS);
3486 new_dos_attributes = 0;
3488 /* Windows allows a new file to be created and
3489 silently removes a FILE_ATTRIBUTE_DIRECTORY
3490 sent by the client. Do the same. */
3492 new_dos_attributes &= ~FILE_ATTRIBUTE_DIRECTORY;
3494 /* We add FILE_ATTRIBUTE_ARCHIVE to this as this mode is only used if the file is
3496 unx_mode = unix_mode(conn, new_dos_attributes | FILE_ATTRIBUTE_ARCHIVE,
3497 smb_fname, parent_dir_fname);
3500 DEBUG(10, ("open_file_ntcreate: fname=%s, dos_attrs=0x%x "
3501 "access_mask=0x%x share_access=0x%x "
3502 "create_disposition = 0x%x create_options=0x%x "
3503 "unix mode=0%o oplock_request=%d private_flags = 0x%x\n",
3504 smb_fname_str_dbg(smb_fname), new_dos_attributes,
3505 access_mask, share_access, create_disposition,
3506 create_options, (unsigned int)unx_mode, oplock_request,
3507 (unsigned int)private_flags));
3510 /* Ensure req == NULL means INTERNAL_OPEN_ONLY */
3511 SMB_ASSERT(oplock_request == INTERNAL_OPEN_ONLY);
3513 /* And req != NULL means no INTERNAL_OPEN_ONLY */
3514 SMB_ASSERT(((oplock_request & INTERNAL_OPEN_ONLY) == 0));
3518 * Only non-internal opens can be deferred at all
3522 struct deferred_open_record *open_rec;
3523 if (get_deferred_open_message_state(req, NULL, &open_rec)) {
3525 /* If it was an async create retry, the file
3528 if (is_deferred_open_async(open_rec)) {
3529 SET_STAT_INVALID(smb_fname->st);
3530 file_existed = false;
3533 /* Ensure we don't reprocess this message. */
3534 remove_deferred_open_message_smb(req->xconn, req->mid);
3536 first_open_attempt = false;
3541 new_dos_attributes &= SAMBA_ATTRIBUTES_MASK;
3544 * Only use stored DOS attributes for checks
3545 * against requested attributes (below via
3546 * open_match_attributes()), cf bug #11992
3547 * for details. -slow
3551 status = SMB_VFS_GET_DOS_ATTRIBUTES(conn, smb_fname, &attr);
3552 if (NT_STATUS_IS_OK(status)) {
3553 existing_dos_attributes = attr;
3558 /* ignore any oplock requests if oplocks are disabled */
3559 if (!lp_oplocks(SNUM(conn)) ||
3560 IS_VETO_OPLOCK_PATH(conn, smb_fname->base_name)) {
3561 /* Mask off everything except the private Samba bits. */
3562 oplock_request &= SAMBA_PRIVATE_OPLOCK_MASK;
3565 /* this is for OS/2 long file names - say we don't support them */
3566 if (req != NULL && !req->posix_pathnames &&
3567 strstr(smb_fname->base_name,".+,;=[].")) {
3568 /* OS/2 Workplace shell fix may be main code stream in a later
3570 DEBUG(5,("open_file_ntcreate: OS/2 long filenames are not "
3572 if (use_nt_status()) {
3573 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3575 return NT_STATUS_DOS(ERRDOS, ERRcannotopen);
3578 switch( create_disposition ) {
3580 /* If file exists open. If file doesn't exist error. */
3581 if (!file_existed) {
3582 DEBUG(5,("open_file_ntcreate: FILE_OPEN "
3583 "requested for file %s and file "
3585 smb_fname_str_dbg(smb_fname)));
3587 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3591 case FILE_OVERWRITE:
3592 /* If file exists overwrite. If file doesn't exist
3594 if (!file_existed) {
3595 DEBUG(5,("open_file_ntcreate: FILE_OVERWRITE "
3596 "requested for file %s and file "
3598 smb_fname_str_dbg(smb_fname) ));
3600 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3605 /* If file exists error. If file doesn't exist
3608 DEBUG(5,("open_file_ntcreate: FILE_CREATE "
3609 "requested for file %s and file "
3610 "already exists.\n",
3611 smb_fname_str_dbg(smb_fname)));
3612 if (S_ISDIR(smb_fname->st.st_ex_mode)) {
3617 return map_nt_error_from_unix(errno);
3621 case FILE_SUPERSEDE:
3622 case FILE_OVERWRITE_IF:
3626 return NT_STATUS_INVALID_PARAMETER;
3629 flags2 = disposition_to_open_flags(create_disposition);
3631 /* We only care about matching attributes on file exists and
3634 if (!posix_open && file_existed &&
3635 ((create_disposition == FILE_OVERWRITE) ||
3636 (create_disposition == FILE_OVERWRITE_IF))) {
3637 if (!open_match_attributes(conn, existing_dos_attributes,
3639 unx_mode, &new_unx_mode)) {
3640 DEBUG(5,("open_file_ntcreate: attributes mismatch "
3641 "for file %s (%x %x) (0%o, 0%o)\n",
3642 smb_fname_str_dbg(smb_fname),
3643 existing_dos_attributes,
3645 (unsigned int)smb_fname->st.st_ex_mode,
3646 (unsigned int)unx_mode ));
3648 return NT_STATUS_ACCESS_DENIED;
3652 status = smbd_calculate_access_mask(conn,
3658 if (!NT_STATUS_IS_OK(status)) {
3659 DEBUG(10, ("open_file_ntcreate: smbd_calculate_access_mask "
3660 "on file %s returned %s\n",
3661 smb_fname_str_dbg(smb_fname), nt_errstr(status)));
3665 open_access_mask = access_mask;
3667 if (flags2 & O_TRUNC) {
3668 open_access_mask |= FILE_WRITE_DATA; /* This will cause oplock breaks. */
3673 * stat opens on existing files don't get oplocks.
3674 * They can get leases.
3676 * Note that we check for stat open on the *open_access_mask*,
3677 * i.e. the access mask we actually used to do the open,
3678 * not the one the client asked for (which is in
3679 * fsp->access_mask). This is due to the fact that
3680 * FILE_OVERWRITE and FILE_OVERWRITE_IF add in O_TRUNC,
3681 * which adds FILE_WRITE_DATA to open_access_mask.
3683 if (is_oplock_stat_open(open_access_mask) && lease == NULL) {
3684 oplock_request = NO_OPLOCK;
3688 DEBUG(10, ("open_file_ntcreate: fname=%s, after mapping "
3689 "access_mask=0x%x\n", smb_fname_str_dbg(smb_fname),
3693 * Note that we ignore the append flag as append does not
3694 * mean the same thing under DOS and Unix.
3697 flags = calculate_open_access_flags(access_mask, private_flags);
3700 * Currently we only look at FILE_WRITE_THROUGH for create options.
3704 if ((create_options & FILE_WRITE_THROUGH) && lp_strict_sync(SNUM(conn))) {
3709 if (posix_open && (access_mask & FILE_APPEND_DATA)) {
3713 if (!posix_open && !CAN_WRITE(conn)) {
3715 * We should really return a permission denied error if either
3716 * O_CREAT or O_TRUNC are set, but for compatibility with
3717 * older versions of Samba we just AND them out.
3719 flags2 &= ~(O_CREAT|O_TRUNC);
3723 * With kernel oplocks the open breaking an oplock
3724 * blocks until the oplock holder has given up the
3725 * oplock or closed the file. We prevent this by always
3726 * trying to open the file with O_NONBLOCK (see "man
3729 * If a process that doesn't use the smbd open files
3730 * database or communication methods holds a kernel
3731 * oplock we must periodically poll for available open
3734 flags2 |= O_NONBLOCK;
3737 * Ensure we can't write on a read-only share or file.
3740 if (flags != O_RDONLY && file_existed &&
3741 (!CAN_WRITE(conn) || IS_DOS_READONLY(existing_dos_attributes))) {
3742 DEBUG(5,("open_file_ntcreate: write access requested for "
3743 "file %s on read only %s\n",
3744 smb_fname_str_dbg(smb_fname),
3745 !CAN_WRITE(conn) ? "share" : "file" ));
3747 return NT_STATUS_ACCESS_DENIED;
3750 if (VALID_STAT(smb_fname->st)) {
3752 * Only try and create a file id before open
3753 * for an existing file. For a file being created
3754 * this won't do anything useful until the file
3755 * exists and has a valid stat struct.
3757 fsp->file_id = vfs_file_id_from_sbuf(conn, &smb_fname->st);
3759 fsp->fh->private_options = private_flags;
3760 fsp->access_mask = open_access_mask; /* We change this to the
3761 * requested access_mask after
3762 * the open is done. */
3764 fsp->posix_flags |= FSP_POSIX_FLAGS_ALL;
3767 if ((create_options & FILE_DELETE_ON_CLOSE) &&
3768 (flags2 & O_CREAT) &&
3770 /* Delete on close semantics for new files. */
3771 status = can_set_delete_on_close(fsp,
3772 new_dos_attributes);
3773 if (!NT_STATUS_IS_OK(status)) {
3780 * Ensure we pay attention to default ACLs on directories if required.
3783 if ((flags2 & O_CREAT) && lp_inherit_acls(SNUM(conn)) &&
3784 (def_acl = directory_has_default_acl(conn,
3788 unx_mode = (0777 & lp_create_mask(SNUM(conn)));
3791 DEBUG(4,("calling open_file with flags=0x%X flags2=0x%X mode=0%o, "
3792 "access_mask = 0x%x, open_access_mask = 0x%x\n",
3793 (unsigned int)flags, (unsigned int)flags2,
3794 (unsigned int)unx_mode, (unsigned int)access_mask,
3795 (unsigned int)open_access_mask));
3797 fsp_open = open_file(fsp,
3805 if (NT_STATUS_EQUAL(fsp_open, NT_STATUS_NETWORK_BUSY)) {
3806 if (file_existed && S_ISFIFO(fsp->fsp_name->st.st_ex_mode)) {
3807 DEBUG(10, ("FIFO busy\n"));
3808 return NT_STATUS_NETWORK_BUSY;
3811 DEBUG(10, ("Internal open busy\n"));
3812 return NT_STATUS_NETWORK_BUSY;
3815 * This handles the kernel oplock case:
3817 * the file has an active kernel oplock and the open() returned
3818 * EWOULDBLOCK/EAGAIN which maps to NETWORK_BUSY.
3820 * "Samba locking.tdb oplocks" are handled below after acquiring
3821 * the sharemode lock with get_share_mode_lock().
3826 if (NT_STATUS_EQUAL(fsp_open, NT_STATUS_RETRY)) {
3828 * EINTR from the open(2) syscall. Just setup a retry
3829 * in a bit. We can't use the sys_write() tight retry
3830 * loop here, as we might have to actually deal with
3831 * lease-break signals to avoid a deadlock.
3838 * From here on we assume this is an oplock break triggered
3841 lck = get_existing_share_mode_lock(talloc_tos(), fsp->file_id);
3843 if ((lck != NULL) && !validate_oplock_types(lck)) {
3844 smb_panic("validate_oplock_types failed");
3848 * Retry once a second. If there's a share_mode_lock
3849 * around, also wait for it in case it was smbd
3850 * holding that kernel oplock that can quickly tell us
3851 * the oplock got removed.
3858 timeval_set(OPLOCK_BREAK_TIMEOUT*2, 0),
3863 return NT_STATUS_SHARING_VIOLATION;
3866 if (!NT_STATUS_IS_OK(fsp_open)) {
3867 bool wait_for_aio = NT_STATUS_EQUAL(
3868 fsp_open, NT_STATUS_MORE_PROCESSING_REQUIRED);
3870 schedule_async_open(req);
3875 if (new_file_created) {
3877 * As we atomically create using O_CREAT|O_EXCL,
3878 * then if new_file_created is true, then
3879 * file_existed *MUST* have been false (even
3880 * if the file was previously detected as being
3883 file_existed = false;
3886 if (file_existed && !check_same_dev_ino(&saved_stat, &smb_fname->st)) {
3888 * The file did exist, but some other (local or NFS)
3889 * process either renamed/unlinked and re-created the
3890 * file with different dev/ino after we walked the path,
3891 * but before we did the open. We could retry the
3892 * open but it's a rare enough case it's easier to
3893 * just fail the open to prevent creating any problems
3894 * in the open file db having the wrong dev/ino key.
3897 DBG_WARNING("file %s - dev/ino mismatch. "
3898 "Old (dev=%ju, ino=%ju). "
3899 "New (dev=%ju, ino=%ju). Failing open "
3900 "with NT_STATUS_ACCESS_DENIED.\n",
3901 smb_fname_str_dbg(smb_fname),
3902 (uintmax_t)saved_stat.st_ex_dev,
3903 (uintmax_t)saved_stat.st_ex_ino,
3904 (uintmax_t)smb_fname->st.st_ex_dev,
3905 (uintmax_t)smb_fname->st.st_ex_ino);
3906 return NT_STATUS_ACCESS_DENIED;
3909 old_write_time = smb_fname->st.st_ex_mtime;
3912 * Deal with the race condition where two smbd's detect the
3913 * file doesn't exist and do the create at the same time. One
3914 * of them will win and set a share mode, the other (ie. this
3915 * one) should check if the requested share mode for this
3916 * create is allowed.
3920 * Now the file exists and fsp is successfully opened,
3921 * fsp->dev and fsp->inode are valid and should replace the
3922 * dev=0,inode=0 from a non existent file. Spotted by
3923 * Nadav Danieli <nadavd@exanet.com>. JRA.
3928 lck = get_share_mode_lock(talloc_tos(), id,
3930 smb_fname, &old_write_time);
3933 DEBUG(0, ("open_file_ntcreate: Could not get share "
3934 "mode lock for %s\n",
3935 smb_fname_str_dbg(smb_fname)));
3937 return NT_STATUS_SHARING_VIOLATION;
3940 /* Get the types we need to examine. */
3941 if (!validate_oplock_types(lck)) {
3942 smb_panic("validate_oplock_types failed");
3945 if (has_delete_on_close(lck, fsp->name_hash)) {
3948 return NT_STATUS_DELETE_PENDING;
3951 status = handle_share_mode_lease(
3959 first_open_attempt);
3961 if (NT_STATUS_EQUAL(status, NT_STATUS_RETRY)) {
3962 schedule_defer_open(lck, fsp->file_id, req);
3965 return NT_STATUS_SHARING_VIOLATION;
3968 if (!NT_STATUS_IS_OK(status)) {
3975 struct share_mode_data *d = lck->data;
3976 uint16_t new_flags = share_mode_flags_restrict(
3977 d->flags, access_mask, share_access, UINT32_MAX);
3979 if (new_flags != d->flags) {
3980 d->flags = new_flags;
3985 ok = set_share_mode(
3988 get_current_uid(fsp->conn),
3994 if (fsp->oplock_type == LEASE_OPLOCK) {
3995 status = remove_lease_if_stale(
3997 fsp_client_guid(fsp),
3998 &fsp->lease->lease.lease_key);
3999 if (!NT_STATUS_IS_OK(status)) {
4000 DBG_WARNING("remove_lease_if_stale "
4005 return NT_STATUS_NO_MEMORY;
4008 /* Should we atomically (to the client at least) truncate ? */
4009 if ((!new_file_created) &&
4010 (flags2 & O_TRUNC) &&
4011 (S_ISREG(fsp->fsp_name->st.st_ex_mode))) {
4014 ret = SMB_VFS_FTRUNCATE(fsp, 0);
4016 status = map_nt_error_from_unix(errno);
4017 del_share_mode(lck, fsp);
4022 notify_fname(fsp->conn, NOTIFY_ACTION_MODIFIED,
4023 FILE_NOTIFY_CHANGE_SIZE
4024 | FILE_NOTIFY_CHANGE_ATTRIBUTES,
4025 fsp->fsp_name->base_name);
4029 * We have the share entry *locked*.....
4032 /* Delete streams if create_disposition requires it */
4033 if (!new_file_created && clear_ads(create_disposition) &&
4034 !is_ntfs_stream_smb_fname(smb_fname)) {
4035 status = delete_all_streams(conn, smb_fname);
4036 if (!NT_STATUS_IS_OK(status)) {
4037 del_share_mode(lck, fsp);
4044 if (fsp->fh->fd != -1 && lp_kernel_share_modes(SNUM(conn))) {
4047 * Beware: streams implementing VFS modules may
4048 * implement streams in a way that fsp will have the
4049 * basefile open in the fsp fd, so lacking a distinct
4050 * fd for the stream kernel_flock will apply on the
4051 * basefile which is wrong. The actual check is
4052 * deferred to the VFS module implementing the
4053 * kernel_flock call.
4055 ret_flock = SMB_VFS_KERNEL_FLOCK(fsp, share_access, access_mask);
4056 if(ret_flock == -1 ){
4058 del_share_mode(lck, fsp);
4062 return NT_STATUS_SHARING_VIOLATION;
4065 fsp->fsp_flags.kernel_share_modes_taken = true;
4069 * At this point onwards, we can guarantee that the share entry
4070 * is locked, whether we created the file or not, and that the
4071 * deny mode is compatible with all current opens.
4075 * According to Samba4, SEC_FILE_READ_ATTRIBUTE is always granted,
4076 * but we don't have to store this - just ignore it on access check.
4078 if (conn->sconn->using_smb2) {
4080 * SMB2 doesn't return it (according to Microsoft tests).
4081 * Test Case: TestSuite_ScenarioNo009GrantedAccessTestS0
4082 * File created with access = 0x7 (Read, Write, Delete)
4083 * Query Info on file returns 0x87 (Read, Write, Delete, Read Attributes)
4085 fsp->access_mask = access_mask;
4087 /* But SMB1 does. */
4088 fsp->access_mask = access_mask | FILE_READ_ATTRIBUTES;
4091 if (new_file_created) {
4092 info = FILE_WAS_CREATED;
4094 if (flags2 & O_TRUNC) {
4095 info = FILE_WAS_OVERWRITTEN;
4097 info = FILE_WAS_OPENED;
4105 /* Handle strange delete on close create semantics. */
4106 if (create_options & FILE_DELETE_ON_CLOSE) {
4107 if (!new_file_created) {
4108 status = can_set_delete_on_close(fsp,
4109 existing_dos_attributes);
4111 if (!NT_STATUS_IS_OK(status)) {
4112 /* Remember to delete the mode we just added. */
4113 del_share_mode(lck, fsp);
4119 /* Note that here we set the *initial* delete on close flag,
4120 not the regular one. The magic gets handled in close. */
4121 fsp->fsp_flags.initial_delete_on_close = true;
4125 * If we created a file and it's not a stream, this is the point where
4126 * we set the itime (aka invented time) that get's stored in the DOS
4127 * attribute xattr. The value is going to be either what the filesystem
4128 * provided or a copy of the creation date.
4130 * Either way, we turn the itime into a File-ID, unless the filesystem
4131 * provided one (unlikely).
4133 if (info == FILE_WAS_CREATED && !is_named_stream(smb_fname)) {
4134 smb_fname->st.st_ex_iflags &= ~ST_EX_IFLAG_CALCULATED_ITIME;
4136 if (lp_store_dos_attributes(SNUM(conn)) &&
4137 smb_fname->st.st_ex_iflags & ST_EX_IFLAG_CALCULATED_FILE_ID)
4141 file_id = make_file_id_from_itime(&smb_fname->st);
4142 update_stat_ex_file_id(&smb_fname->st, file_id);
4146 if (info != FILE_WAS_OPENED) {
4147 /* Overwritten files should be initially set as archive */
4148 if ((info == FILE_WAS_OVERWRITTEN && lp_map_archive(SNUM(conn))) ||
4149 lp_store_dos_attributes(SNUM(conn))) {
4150 (void)dos_mode(conn, smb_fname);
4152 if (file_set_dosmode(conn, smb_fname,
4153 new_dos_attributes | FILE_ATTRIBUTE_ARCHIVE,
4154 parent_dir_fname, true) == 0) {
4155 unx_mode = smb_fname->st.st_ex_mode;
4161 /* Determine sparse flag. */
4163 /* POSIX opens are sparse by default. */
4164 fsp->fsp_flags.is_sparse = true;
4166 fsp->fsp_flags.is_sparse =
4167 (existing_dos_attributes & FILE_ATTRIBUTE_SPARSE);
4171 * Take care of inherited ACLs on created files - if default ACL not
4175 if (!posix_open && new_file_created && !def_acl) {
4176 if (unx_mode != smb_fname->st.st_ex_mode) {
4177 int ret = SMB_VFS_FCHMOD(fsp, unx_mode);
4179 DBG_INFO("failed to reset "
4180 "attributes of file %s to 0%o\n",
4181 smb_fname_str_dbg(smb_fname),
4182 (unsigned int)unx_mode);
4186 } else if (new_unx_mode) {
4188 * We only get here in the case of:
4190 * a). Not a POSIX open.
4191 * b). File already existed.
4192 * c). File was overwritten.
4193 * d). Requested DOS attributes didn't match
4194 * the DOS attributes on the existing file.
4196 * In that case new_unx_mode has been set
4197 * equal to the calculated mode (including
4198 * possible inheritance of the mode from the
4199 * containing directory).
4201 * Note this mode was calculated with the
4202 * DOS attribute FILE_ATTRIBUTE_ARCHIVE added,
4203 * so the mode change here is suitable for
4204 * an overwritten file.
4207 if (new_unx_mode != smb_fname->st.st_ex_mode) {
4208 int ret = SMB_VFS_FCHMOD(fsp, new_unx_mode);
4210 DBG_INFO("failed to reset "
4211 "attributes of file %s to 0%o\n",
4212 smb_fname_str_dbg(smb_fname),
4213 (unsigned int)new_unx_mode);
4220 * Deal with other opens having a modified write time.
4222 struct timespec write_time = get_share_mode_write_time(lck);
4224 if (!is_omit_timespec(&write_time)) {
4225 update_stat_ex_mtime(&fsp->fsp_name->st, write_time);
4231 return NT_STATUS_OK;
4234 static NTSTATUS mkdir_internal(connection_struct *conn,
4235 struct files_struct **dirfsp,
4236 struct smb_filename *smb_dname,
4237 uint32_t file_attributes)
4239 const struct loadparm_substitution *lp_sub =
4240 loadparm_s3_global_substitution();
4242 struct smb_filename *parent_dir_fname = NULL;
4244 bool posix_open = false;
4245 bool need_re_stat = false;
4246 uint32_t access_mask = SEC_DIR_ADD_SUBDIR;
4250 SMB_ASSERT(*dirfsp == conn->cwd_fsp);
4252 if (!CAN_WRITE(conn) || (access_mask & ~(conn->share_access))) {
4253 DEBUG(5,("mkdir_internal: failing share access "
4254 "%s\n", lp_servicename(talloc_tos(), lp_sub, SNUM(conn))));
4255 return NT_STATUS_ACCESS_DENIED;
4258 ok = parent_smb_fname(talloc_tos(),
4263 return NT_STATUS_NO_MEMORY;
4266 if (file_attributes & FILE_FLAG_POSIX_SEMANTICS) {
4268 mode = (mode_t)(file_attributes & ~FILE_FLAG_POSIX_SEMANTICS);
4270 mode = unix_mode(conn,
4271 FILE_ATTRIBUTE_DIRECTORY,
4276 status = check_parent_access(conn,
4280 if(!NT_STATUS_IS_OK(status)) {
4281 DEBUG(5,("mkdir_internal: check_parent_access "
4282 "on directory %s for path %s returned %s\n",
4283 smb_fname_str_dbg(parent_dir_fname),
4284 smb_dname->base_name,
4285 nt_errstr(status) ));
4289 ret = SMB_VFS_MKDIRAT(conn,
4294 return map_nt_error_from_unix(errno);
4297 /* Ensure we're checking for a symlink here.... */
4298 /* We don't want to get caught by a symlink racer. */
4300 if (SMB_VFS_LSTAT(conn, smb_dname) == -1) {
4301 DEBUG(2, ("Could not stat directory '%s' just created: %s\n",
4302 smb_fname_str_dbg(smb_dname), strerror(errno)));
4303 return map_nt_error_from_unix(errno);
4306 if (!S_ISDIR(smb_dname->st.st_ex_mode)) {
4307 DEBUG(0, ("Directory '%s' just created is not a directory !\n",
4308 smb_fname_str_dbg(smb_dname)));
4309 return NT_STATUS_NOT_A_DIRECTORY;
4312 smb_dname->st.st_ex_iflags &= ~ST_EX_IFLAG_CALCULATED_ITIME;
4314 if (lp_store_dos_attributes(SNUM(conn))) {
4315 if (smb_dname->st.st_ex_iflags & ST_EX_IFLAG_CALCULATED_FILE_ID)
4319 file_id = make_file_id_from_itime(&smb_dname->st);
4320 update_stat_ex_file_id(&smb_dname->st, file_id);
4324 file_set_dosmode(conn, smb_dname,
4325 file_attributes | FILE_ATTRIBUTE_DIRECTORY,
4326 parent_dir_fname, true);
4330 if (lp_inherit_permissions(SNUM(conn))) {
4331 inherit_access_posix_acl(conn, parent_dir_fname,
4333 need_re_stat = true;
4338 * Check if high bits should have been set,
4339 * then (if bits are missing): add them.
4340 * Consider bits automagically set by UNIX, i.e. SGID bit from parent
4343 if ((mode & ~(S_IRWXU|S_IRWXG|S_IRWXO)) &&
4344 (mode & ~smb_dname->st.st_ex_mode)) {
4345 SMB_VFS_CHMOD(conn, smb_dname,
4346 (smb_dname->st.st_ex_mode |
4347 (mode & ~smb_dname->st.st_ex_mode)));
4348 need_re_stat = true;
4352 /* Change the owner if required. */
4353 if (lp_inherit_owner(SNUM(conn)) != INHERIT_OWNER_NO) {
4354 change_dir_owner_to_parent(conn, parent_dir_fname,
4357 need_re_stat = true;
4361 if (SMB_VFS_LSTAT(conn, smb_dname) == -1) {
4362 DEBUG(2, ("Could not stat directory '%s' just created: %s\n",
4363 smb_fname_str_dbg(smb_dname), strerror(errno)));
4364 return map_nt_error_from_unix(errno);
4368 notify_fname(conn, NOTIFY_ACTION_ADDED, FILE_NOTIFY_CHANGE_DIR_NAME,
4369 smb_dname->base_name);
4371 return NT_STATUS_OK;
4374 /****************************************************************************
4375 Open a directory from an NT SMB call.
4376 ****************************************************************************/
4378 static NTSTATUS open_directory(connection_struct *conn,
4379 struct smb_request *req,
4380 struct files_struct **dirfsp,
4381 struct smb_filename *smb_dname,
4382 uint32_t access_mask,
4383 uint32_t share_access,
4384 uint32_t create_disposition,
4385 uint32_t create_options,
4386 uint32_t file_attributes,
4388 files_struct **result)
4390 files_struct *fsp = NULL;
4391 bool dir_existed = VALID_STAT(smb_dname->st);
4392 struct share_mode_lock *lck = NULL;
4394 struct timespec mtimespec;
4399 SMB_ASSERT(*dirfsp == conn->cwd_fsp);
4401 if (is_ntfs_stream_smb_fname(smb_dname)) {
4402 DEBUG(2, ("open_directory: %s is a stream name!\n",
4403 smb_fname_str_dbg(smb_dname)));
4404 return NT_STATUS_NOT_A_DIRECTORY;
4407 if (!(file_attributes & FILE_FLAG_POSIX_SEMANTICS)) {
4408 /* Ensure we have a directory attribute. */
4409 file_attributes |= FILE_ATTRIBUTE_DIRECTORY;
4412 DBG_INFO("opening directory %s, access_mask = 0x%"PRIx32", "
4413 "share_access = 0x%"PRIx32" create_options = 0x%"PRIx32", "
4414 "create_disposition = 0x%"PRIx32", "
4415 "file_attributes = 0x%"PRIx32"\n",
4416 smb_fname_str_dbg(smb_dname),
4423 status = smbd_calculate_access_mask(conn,
4429 if (!NT_STATUS_IS_OK(status)) {
4430 DEBUG(10, ("open_directory: smbd_calculate_access_mask "
4431 "on file %s returned %s\n",
4432 smb_fname_str_dbg(smb_dname),
4433 nt_errstr(status)));
4437 if ((access_mask & SEC_FLAG_SYSTEM_SECURITY) &&
4438 !security_token_has_privilege(get_current_nttok(conn),
4439 SEC_PRIV_SECURITY)) {
4440 DEBUG(10, ("open_directory: open on %s "
4441 "failed - SEC_FLAG_SYSTEM_SECURITY denied.\n",
4442 smb_fname_str_dbg(smb_dname)));
4443 return NT_STATUS_PRIVILEGE_NOT_HELD;
4446 switch( create_disposition ) {
4450 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
4453 info = FILE_WAS_OPENED;
4458 /* If directory exists error. If directory doesn't
4462 status = NT_STATUS_OBJECT_NAME_COLLISION;
4463 DEBUG(2, ("open_directory: unable to create "
4464 "%s. Error was %s\n",
4465 smb_fname_str_dbg(smb_dname),
4466 nt_errstr(status)));
4470 status = mkdir_internal(conn, dirfsp, smb_dname,
4473 if (!NT_STATUS_IS_OK(status)) {
4474 DEBUG(2, ("open_directory: unable to create "
4475 "%s. Error was %s\n",
4476 smb_fname_str_dbg(smb_dname),
4477 nt_errstr(status)));
4481 info = FILE_WAS_CREATED;
4486 * If directory exists open. If directory doesn't
4491 status = NT_STATUS_OK;
4492 info = FILE_WAS_OPENED;
4494 status = mkdir_internal(conn, dirfsp, smb_dname,
4497 if (NT_STATUS_IS_OK(status)) {
4498 info = FILE_WAS_CREATED;
4500 /* Cope with create race. */
4501 if (!NT_STATUS_EQUAL(status,
4502 NT_STATUS_OBJECT_NAME_COLLISION)) {
4503 DEBUG(2, ("open_directory: unable to create "
4504 "%s. Error was %s\n",
4505 smb_fname_str_dbg(smb_dname),
4506 nt_errstr(status)));
4511 * If mkdir_internal() returned
4512 * NT_STATUS_OBJECT_NAME_COLLISION
4513 * we still must lstat the path.
4516 if (SMB_VFS_LSTAT(conn, smb_dname)
4518 DEBUG(2, ("Could not stat "
4519 "directory '%s' just "
4524 return map_nt_error_from_unix(
4528 info = FILE_WAS_OPENED;
4534 case FILE_SUPERSEDE:
4535 case FILE_OVERWRITE:
4536 case FILE_OVERWRITE_IF:
4538 DEBUG(5,("open_directory: invalid create_disposition "
4539 "0x%x for directory %s\n",
4540 (unsigned int)create_disposition,
4541 smb_fname_str_dbg(smb_dname)));
4542 return NT_STATUS_INVALID_PARAMETER;
4545 if(!S_ISDIR(smb_dname->st.st_ex_mode)) {
4546 DEBUG(5,("open_directory: %s is not a directory !\n",
4547 smb_fname_str_dbg(smb_dname)));
4548 return NT_STATUS_NOT_A_DIRECTORY;
4551 if (info == FILE_WAS_OPENED) {
4552 status = smbd_check_access_rights(conn,
4557 if (!NT_STATUS_IS_OK(status)) {
4558 DEBUG(10, ("open_directory: smbd_check_access_rights on "
4559 "file %s failed with %s\n",
4560 smb_fname_str_dbg(smb_dname),
4561 nt_errstr(status)));
4566 status = file_new(req, conn, &fsp);
4567 if(!NT_STATUS_IS_OK(status)) {
4572 * Setup the files_struct for it.
4575 fsp->file_id = vfs_file_id_from_sbuf(conn, &smb_dname->st);
4576 fsp->vuid = req ? req->vuid : UID_FIELD_INVALID;
4577 fsp->file_pid = req ? req->smbpid : 0;
4578 fsp->fsp_flags.can_lock = false;
4579 fsp->fsp_flags.can_read = false;
4580 fsp->fsp_flags.can_write = false;
4582 fsp->fh->private_options = 0;
4584 * According to Samba4, SEC_FILE_READ_ATTRIBUTE is always granted,
4586 fsp->access_mask = access_mask | FILE_READ_ATTRIBUTES;
4587 fsp->print_file = NULL;
4588 fsp->fsp_flags.modified = false;
4589 fsp->oplock_type = NO_OPLOCK;
4590 fsp->sent_oplock_break = NO_BREAK_SENT;
4591 fsp->fsp_flags.is_directory = true;
4592 if (file_attributes & FILE_FLAG_POSIX_SEMANTICS) {
4593 fsp->posix_flags |= FSP_POSIX_FLAGS_ALL;
4595 status = fsp_set_smb_fname(fsp, smb_dname);
4596 if (!NT_STATUS_IS_OK(status)) {
4597 file_free(req, fsp);
4601 if (*dirfsp == fsp->conn->cwd_fsp) {
4602 fsp->dirfsp = fsp->conn->cwd_fsp;
4604 fsp->dirfsp = talloc_move(fsp, dirfsp);
4607 /* Don't store old timestamps for directory
4608 handles in the internal database. We don't
4609 update them in there if new objects
4610 are created in the directory. Currently
4611 we only update timestamps on file writes.
4614 mtimespec = make_omit_timespec();
4616 /* POSIX allows us to open a directory with O_RDONLY. */
4619 flags |= O_DIRECTORY;
4622 status = fd_openat(fsp, flags, 0);
4623 if (!NT_STATUS_IS_OK(status)) {
4624 DBG_INFO("Could not open fd for "
4626 smb_fname_str_dbg(smb_dname),
4628 file_free(req, fsp);
4632 status = vfs_stat_fsp(fsp);
4633 if (!NT_STATUS_IS_OK(status)) {
4635 file_free(req, fsp);
4639 if(!S_ISDIR(fsp->fsp_name->st.st_ex_mode)) {
4640 DEBUG(5,("open_directory: %s is not a directory !\n",
4641 smb_fname_str_dbg(smb_dname)));
4643 file_free(req, fsp);
4644 return NT_STATUS_NOT_A_DIRECTORY;
4647 /* Ensure there was no race condition. We need to check
4648 * dev/inode but not permissions, as these can change
4650 if (!check_same_dev_ino(&smb_dname->st, &fsp->fsp_name->st)) {
4651 DEBUG(5,("open_directory: stat struct differs for "
4653 smb_fname_str_dbg(smb_dname)));
4655 file_free(req, fsp);
4656 return NT_STATUS_ACCESS_DENIED;
4659 lck = get_share_mode_lock(talloc_tos(), fsp->file_id,
4660 conn->connectpath, smb_dname,
4664 DEBUG(0, ("open_directory: Could not get share mode lock for "
4665 "%s\n", smb_fname_str_dbg(smb_dname)));
4667 file_free(req, fsp);
4668 return NT_STATUS_SHARING_VIOLATION;
4671 if (has_delete_on_close(lck, fsp->name_hash)) {
4674 file_free(req, fsp);
4675 return NT_STATUS_DELETE_PENDING;
4678 status = open_mode_check(conn, lck,
4679 access_mask, share_access);
4681 if (!NT_STATUS_IS_OK(status)) {
4684 file_free(req, fsp);
4689 struct share_mode_data *d = lck->data;
4690 uint16_t new_flags = share_mode_flags_restrict(
4691 d->flags, access_mask, share_access, UINT32_MAX);
4693 if (new_flags != d->flags) {
4694 d->flags = new_flags;
4699 ok = set_share_mode(
4702 get_current_uid(conn),
4710 file_free(req, fsp);
4711 return NT_STATUS_NO_MEMORY;
4714 /* For directories the delete on close bit at open time seems
4715 always to be honored on close... See test 19 in Samba4 BASE-DELETE. */
4716 if (create_options & FILE_DELETE_ON_CLOSE) {
4717 status = can_set_delete_on_close(fsp, 0);
4718 if (!NT_STATUS_IS_OK(status) && !NT_STATUS_EQUAL(status, NT_STATUS_DIRECTORY_NOT_EMPTY)) {
4719 del_share_mode(lck, fsp);
4722 file_free(req, fsp);
4726 if (NT_STATUS_IS_OK(status)) {
4727 /* Note that here we set the *initial* delete on close flag,
4728 not the regular one. The magic gets handled in close. */
4729 fsp->fsp_flags.initial_delete_on_close = true;
4735 * Deal with other opens having a modified write time. Is this
4736 * possible for directories?
4738 struct timespec write_time = get_share_mode_write_time(lck);
4740 if (!is_omit_timespec(&write_time)) {
4741 update_stat_ex_mtime(&fsp->fsp_name->st, write_time);
4752 return NT_STATUS_OK;
4755 NTSTATUS create_directory(connection_struct *conn, struct smb_request *req,
4756 struct smb_filename *smb_dname)
4761 status = SMB_VFS_CREATE_FILE(
4764 &conn->cwd_fsp, /* dirfsp */
4765 smb_dname, /* fname */
4766 FILE_READ_ATTRIBUTES, /* access_mask */
4767 FILE_SHARE_NONE, /* share_access */
4768 FILE_CREATE, /* create_disposition*/
4769 FILE_DIRECTORY_FILE, /* create_options */
4770 FILE_ATTRIBUTE_DIRECTORY, /* file_attributes */
4771 0, /* oplock_request */
4773 0, /* allocation_size */
4774 0, /* private_flags */
4779 NULL, NULL); /* create context */
4781 if (NT_STATUS_IS_OK(status)) {
4782 close_file(req, fsp, NORMAL_CLOSE);
4788 /****************************************************************************
4789 Receive notification that one of our open files has been renamed by another
4791 ****************************************************************************/
4793 void msg_file_was_renamed(struct messaging_context *msg_ctx,
4796 struct server_id src,
4799 struct file_rename_message *msg = NULL;
4800 enum ndr_err_code ndr_err;
4802 struct smb_filename *smb_fname = NULL;
4803 struct smbd_server_connection *sconn =
4804 talloc_get_type_abort(private_data,
4805 struct smbd_server_connection);
4807 msg = talloc(talloc_tos(), struct file_rename_message);
4809 DBG_WARNING("talloc failed\n");
4813 ndr_err = ndr_pull_struct_blob_all(
4817 (ndr_pull_flags_fn_t)ndr_pull_file_rename_message);
4818 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
4819 DBG_DEBUG("ndr_pull_oplock_break_message failed: %s\n",
4820 ndr_errstr(ndr_err));
4823 if (DEBUGLEVEL >= 10) {
4824 struct server_id_buf buf;
4825 DBG_DEBUG("Got rename message from %s\n",
4826 server_id_str_buf(src, &buf));
4827 NDR_PRINT_DEBUG(file_rename_message, msg);
4830 /* stream_name must always be NULL if there is no stream. */
4831 if ((msg->stream_name != NULL) && (msg->stream_name[0] == '\0')) {
4832 msg->stream_name = NULL;
4835 smb_fname = synthetic_smb_fname(msg,
4841 if (smb_fname == NULL) {
4842 DBG_DEBUG("synthetic_smb_fname failed\n");
4846 fsp = file_find_dif(sconn, msg->id, msg->share_file_id);
4848 DBG_DEBUG("fsp not found\n");
4852 if (strcmp(fsp->conn->connectpath, msg->servicepath) == 0) {
4854 DBG_DEBUG("renaming file %s from %s -> %s\n",
4857 smb_fname_str_dbg(smb_fname));
4858 status = fsp_set_smb_fname(fsp, smb_fname);
4859 if (!NT_STATUS_IS_OK(status)) {
4860 DBG_DEBUG("fsp_set_smb_fname failed: %s\n",
4866 * Now we have the complete path we can work out if
4867 * this is actually within this share and adjust
4868 * newname accordingly.
4870 DBG_DEBUG("share mismatch (sharepath %s not sharepath %s) "
4871 "%s from %s -> %s\n",
4872 fsp->conn->connectpath,
4876 smb_fname_str_dbg(smb_fname));
4883 * If a main file is opened for delete, all streams need to be checked for
4884 * !FILE_SHARE_DELETE. Do this by opening with DELETE_ACCESS.
4885 * If that works, delete them all by setting the delete on close and close.
4888 static NTSTATUS open_streams_for_delete(connection_struct *conn,
4889 const struct smb_filename *smb_fname)
4891 struct stream_struct *stream_info = NULL;
4892 files_struct **streams = NULL;
4894 unsigned int i, num_streams = 0;
4895 TALLOC_CTX *frame = talloc_stackframe();
4898 status = vfs_streaminfo(conn, NULL, smb_fname, talloc_tos(),
4899 &num_streams, &stream_info);
4901 if (NT_STATUS_EQUAL(status, NT_STATUS_NOT_IMPLEMENTED)
4902 || NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
4903 DEBUG(10, ("no streams around\n"));
4905 return NT_STATUS_OK;
4908 if (!NT_STATUS_IS_OK(status)) {
4909 DEBUG(10, ("vfs_streaminfo failed: %s\n",
4910 nt_errstr(status)));
4914 DEBUG(10, ("open_streams_for_delete found %d streams\n",
4917 if (num_streams == 0) {
4919 return NT_STATUS_OK;
4922 streams = talloc_array(talloc_tos(), files_struct *, num_streams);
4923 if (streams == NULL) {
4924 DEBUG(0, ("talloc failed\n"));
4925 status = NT_STATUS_NO_MEMORY;
4929 for (i=0; i<num_streams; i++) {
4930 struct smb_filename *smb_fname_cp;
4932 if (strequal(stream_info[i].name, "::$DATA")) {
4937 smb_fname_cp = synthetic_smb_fname(talloc_tos(),
4938 smb_fname->base_name,
4939 stream_info[i].name,
4943 ~SMB_FILENAME_POSIX_PATH));
4944 if (smb_fname_cp == NULL) {
4945 status = NT_STATUS_NO_MEMORY;
4949 if (SMB_VFS_STAT(conn, smb_fname_cp) == -1) {
4950 DEBUG(10, ("Unable to stat stream: %s\n",
4951 smb_fname_str_dbg(smb_fname_cp)));
4954 status = SMB_VFS_CREATE_FILE(
4957 &conn->cwd_fsp, /* dirfsp */
4958 smb_fname_cp, /* fname */
4959 DELETE_ACCESS, /* access_mask */
4960 (FILE_SHARE_READ | /* share_access */
4961 FILE_SHARE_WRITE | FILE_SHARE_DELETE),
4962 FILE_OPEN, /* create_disposition*/
4963 0, /* create_options */
4964 FILE_ATTRIBUTE_NORMAL, /* file_attributes */
4965 0, /* oplock_request */
4967 0, /* allocation_size */
4968 NTCREATEX_OPTIONS_PRIVATE_STREAM_DELETE, /* private_flags */
4971 &streams[i], /* result */
4973 NULL, NULL); /* create context */
4975 if (!NT_STATUS_IS_OK(status)) {
4976 DEBUG(10, ("Could not open stream %s: %s\n",
4977 smb_fname_str_dbg(smb_fname_cp),
4978 nt_errstr(status)));
4980 TALLOC_FREE(smb_fname_cp);
4983 TALLOC_FREE(smb_fname_cp);
4987 * don't touch the variable "status" beyond this point :-)
4990 for (j = i-1 ; j >= 0; j--) {
4991 if (streams[j] == NULL) {
4995 DEBUG(10, ("Closing stream # %d, %s\n", j,
4996 fsp_str_dbg(streams[j])));
4997 close_file(NULL, streams[j], NORMAL_CLOSE);
5005 /*********************************************************************
5006 Create a default ACL by inheriting from the parent. If no inheritance
5007 from the parent available, don't set anything. This will leave the actual
5008 permissions the new file or directory already got from the filesystem
5009 as the NT ACL when read.
5010 *********************************************************************/
5012 static NTSTATUS inherit_new_acl(files_struct *fsp)
5014 TALLOC_CTX *frame = talloc_stackframe();
5015 struct security_descriptor *parent_desc = NULL;
5016 NTSTATUS status = NT_STATUS_OK;
5017 struct security_descriptor *psd = NULL;
5018 const struct dom_sid *owner_sid = NULL;
5019 const struct dom_sid *group_sid = NULL;
5020 uint32_t security_info_sent = (SECINFO_OWNER | SECINFO_GROUP | SECINFO_DACL);
5021 struct security_token *token = fsp->conn->session_info->security_token;
5022 bool inherit_owner =
5023 (lp_inherit_owner(SNUM(fsp->conn)) == INHERIT_OWNER_WINDOWS_AND_UNIX);
5024 bool inheritable_components = false;
5025 bool try_builtin_administrators = false;
5026 const struct dom_sid *BA_U_sid = NULL;
5027 const struct dom_sid *BA_G_sid = NULL;
5028 bool try_system = false;
5029 const struct dom_sid *SY_U_sid = NULL;
5030 const struct dom_sid *SY_G_sid = NULL;
5032 struct smb_filename *parent_dir = NULL;
5035 ok = parent_smb_fname(frame,
5041 return NT_STATUS_NO_MEMORY;
5044 status = SMB_VFS_GET_NT_ACL_AT(fsp->conn,
5047 (SECINFO_OWNER | SECINFO_GROUP | SECINFO_DACL),
5050 if (!NT_STATUS_IS_OK(status)) {
5055 inheritable_components = sd_has_inheritable_components(parent_desc,
5056 fsp->fsp_flags.is_directory);
5058 if (!inheritable_components && !inherit_owner) {
5060 /* Nothing to inherit and not setting owner. */
5061 return NT_STATUS_OK;
5064 /* Create an inherited descriptor from the parent. */
5066 if (DEBUGLEVEL >= 10) {
5067 DEBUG(10,("inherit_new_acl: parent acl for %s is:\n",
5068 fsp_str_dbg(fsp) ));
5069 NDR_PRINT_DEBUG(security_descriptor, parent_desc);
5072 /* Inherit from parent descriptor if "inherit owner" set. */
5073 if (inherit_owner) {
5074 owner_sid = parent_desc->owner_sid;
5075 group_sid = parent_desc->group_sid;
5078 if (owner_sid == NULL) {
5079 if (security_token_has_builtin_administrators(token)) {
5080 try_builtin_administrators = true;
5081 } else if (security_token_is_system(token)) {
5082 try_builtin_administrators = true;
5087 if (group_sid == NULL &&
5088 token->num_sids == PRIMARY_GROUP_SID_INDEX)
5090 if (security_token_is_system(token)) {
5091 try_builtin_administrators = true;
5096 if (try_builtin_administrators) {
5100 ok = sids_to_unixids(&global_sid_Builtin_Administrators, 1, &ids);
5104 BA_U_sid = &global_sid_Builtin_Administrators;
5105 BA_G_sid = &global_sid_Builtin_Administrators;
5108 BA_U_sid = &global_sid_Builtin_Administrators;
5111 BA_G_sid = &global_sid_Builtin_Administrators;
5123 ok = sids_to_unixids(&global_sid_System, 1, &ids);
5127 SY_U_sid = &global_sid_System;
5128 SY_G_sid = &global_sid_System;
5131 SY_U_sid = &global_sid_System;
5134 SY_G_sid = &global_sid_System;
5142 if (owner_sid == NULL) {
5143 owner_sid = BA_U_sid;
5146 if (owner_sid == NULL) {
5147 owner_sid = SY_U_sid;
5150 if (group_sid == NULL) {
5151 group_sid = SY_G_sid;
5154 if (try_system && group_sid == NULL) {
5155 group_sid = BA_G_sid;
5158 if (owner_sid == NULL) {
5159 owner_sid = &token->sids[PRIMARY_USER_SID_INDEX];
5161 if (group_sid == NULL) {
5162 if (token->num_sids == PRIMARY_GROUP_SID_INDEX) {
5163 group_sid = &token->sids[PRIMARY_USER_SID_INDEX];
5165 group_sid = &token->sids[PRIMARY_GROUP_SID_INDEX];
5169 status = se_create_child_secdesc(frame,
5175 fsp->fsp_flags.is_directory);
5176 if (!NT_STATUS_IS_OK(status)) {
5181 /* If inheritable_components == false,
5182 se_create_child_secdesc()
5183 creates a security descriptor with a NULL dacl
5184 entry, but with SEC_DESC_DACL_PRESENT. We need
5185 to remove that flag. */
5187 if (!inheritable_components) {
5188 security_info_sent &= ~SECINFO_DACL;
5189 psd->type &= ~SEC_DESC_DACL_PRESENT;
5192 if (DEBUGLEVEL >= 10) {
5193 DEBUG(10,("inherit_new_acl: child acl for %s is:\n",
5194 fsp_str_dbg(fsp) ));
5195 NDR_PRINT_DEBUG(security_descriptor, psd);
5198 if (inherit_owner) {
5199 /* We need to be root to force this. */
5202 status = SMB_VFS_FSET_NT_ACL(fsp,
5205 if (inherit_owner) {
5213 * If we already have a lease, it must match the new file id. [MS-SMB2]
5214 * 3.3.5.9.8 speaks about INVALID_PARAMETER if an already used lease key is
5215 * used for a different file name.
5218 struct lease_match_state {
5219 /* Input parameters. */
5220 TALLOC_CTX *mem_ctx;
5221 const char *servicepath;
5222 const struct smb_filename *fname;
5225 /* Return parameters. */
5226 uint32_t num_file_ids;
5227 struct file_id *ids;
5228 NTSTATUS match_status;
5231 /*************************************************************
5232 File doesn't exist but this lease key+guid is already in use.
5234 This is only allowable in the dynamic share case where the
5235 service path must be different.
5237 There is a small race condition here in the multi-connection
5238 case where a client sends two create calls on different connections,
5239 where the file doesn't exist and one smbd creates the leases_db
5240 entry first, but this will get fixed by the multichannel cleanup
5241 when all identical client_guids get handled by a single smbd.
5242 **************************************************************/
5244 static void lease_match_parser_new_file(
5246 const struct leases_db_file *files,
5247 struct lease_match_state *state)
5251 for (i = 0; i < num_files; i++) {
5252 const struct leases_db_file *f = &files[i];
5253 if (strequal(state->servicepath, f->servicepath)) {
5254 state->match_status = NT_STATUS_INVALID_PARAMETER;
5259 /* Dynamic share case. Break leases on all other files. */
5260 state->match_status = leases_db_copy_file_ids(state->mem_ctx,
5264 if (!NT_STATUS_IS_OK(state->match_status)) {
5268 state->num_file_ids = num_files;
5269 state->match_status = NT_STATUS_OPLOCK_NOT_GRANTED;
5273 static void lease_match_parser(
5275 const struct leases_db_file *files,
5278 struct lease_match_state *state =
5279 (struct lease_match_state *)private_data;
5282 if (!state->file_existed) {
5284 * Deal with name mismatch or
5285 * possible dynamic share case separately
5286 * to make code clearer.
5288 lease_match_parser_new_file(num_files,
5295 state->match_status = NT_STATUS_OK;
5297 for (i = 0; i < num_files; i++) {
5298 const struct leases_db_file *f = &files[i];
5300 /* Everything should be the same. */
5301 if (!file_id_equal(&state->id, &f->id)) {
5302 /* This should catch all dynamic share cases. */
5303 state->match_status = NT_STATUS_OPLOCK_NOT_GRANTED;
5306 if (!strequal(f->servicepath, state->servicepath)) {
5307 state->match_status = NT_STATUS_INVALID_PARAMETER;
5310 if (!strequal(f->base_name, state->fname->base_name)) {
5311 state->match_status = NT_STATUS_INVALID_PARAMETER;
5314 if (!strequal(f->stream_name, state->fname->stream_name)) {
5315 state->match_status = NT_STATUS_INVALID_PARAMETER;
5320 if (NT_STATUS_IS_OK(state->match_status)) {
5322 * Common case - just opening another handle on a
5323 * file on a non-dynamic share.
5328 if (NT_STATUS_EQUAL(state->match_status, NT_STATUS_INVALID_PARAMETER)) {
5329 /* Mismatched path. Error back to client. */
5334 * File id mismatch. Dynamic share case NT_STATUS_OPLOCK_NOT_GRANTED.
5335 * Don't allow leases.
5338 state->match_status = leases_db_copy_file_ids(state->mem_ctx,
5342 if (!NT_STATUS_IS_OK(state->match_status)) {
5346 state->num_file_ids = num_files;
5347 state->match_status = NT_STATUS_OPLOCK_NOT_GRANTED;
5351 struct lease_match_break_state {
5352 struct messaging_context *msg_ctx;
5353 const struct smb2_lease_key *lease_key;
5361 static bool lease_match_break_fn(
5362 struct share_mode_entry *e,
5365 struct lease_match_break_state *state = private_data;
5367 uint32_t e_lease_type;
5370 stale = share_entry_stale_pid(e);
5375 equal = smb2_lease_key_equal(&e->lease_key, state->lease_key);
5380 status = leases_db_get(
5384 NULL, /* current_state */
5385 NULL, /* breaking */
5386 NULL, /* breaking_to_requested */
5387 NULL, /* breaking_to_required */
5388 &state->version, /* lease_version */
5389 &state->epoch); /* epoch */
5390 if (NT_STATUS_IS_OK(status)) {
5391 state->found_lease = true;
5393 DBG_WARNING("Could not find version/epoch: %s\n",
5397 e_lease_type = get_lease_type(e, state->id);
5398 if (e_lease_type == SMB2_LEASE_NONE) {
5401 send_break_message(state->msg_ctx, &state->id, e, SMB2_LEASE_NONE);
5404 * Windows 7 and 8 lease clients are broken in that they will
5405 * not respond to lease break requests whilst waiting for an
5406 * outstanding open request on that lease handle on the same
5407 * TCP connection, due to holding an internal inode lock.
5409 * This means we can't reschedule ourselves here, but must
5410 * return from the create.
5414 * Send the breaks and then return SMB2_LEASE_NONE in the
5415 * lease handle to cause them to acknowledge the lease
5416 * break. Consultation with Microsoft engineering confirmed
5417 * this approach is safe.
5423 static NTSTATUS lease_match(connection_struct *conn,
5424 struct smb_request *req,
5425 const struct smb2_lease_key *lease_key,
5426 const char *servicepath,
5427 const struct smb_filename *fname,
5428 uint16_t *p_version,
5431 struct smbd_server_connection *sconn = req->sconn;
5432 TALLOC_CTX *tos = talloc_tos();
5433 struct lease_match_state state = {
5435 .servicepath = servicepath,
5437 .match_status = NT_STATUS_OK
5442 state.file_existed = VALID_STAT(fname->st);
5443 if (state.file_existed) {
5444 state.id = vfs_file_id_from_sbuf(conn, &fname->st);
5447 status = leases_db_parse(&sconn->client->global->client_guid,
5448 lease_key, lease_match_parser, &state);
5449 if (!NT_STATUS_IS_OK(status)) {
5451 * Not found or error means okay: We can make the lease pass
5453 return NT_STATUS_OK;
5455 if (!NT_STATUS_EQUAL(state.match_status, NT_STATUS_OPLOCK_NOT_GRANTED)) {
5457 * Anything but NT_STATUS_OPLOCK_NOT_GRANTED, let the caller
5460 return state.match_status;
5463 /* We have to break all existing leases. */
5464 for (i = 0; i < state.num_file_ids; i++) {
5465 struct lease_match_break_state break_state = {
5466 .msg_ctx = conn->sconn->msg_ctx,
5467 .lease_key = lease_key,
5469 struct share_mode_lock *lck;
5472 if (file_id_equal(&state.ids[i], &state.id)) {
5473 /* Don't need to break our own file. */
5477 break_state.id = state.ids[i];
5479 lck = get_existing_share_mode_lock(
5480 talloc_tos(), break_state.id);
5482 /* Race condition - file already closed. */
5486 ok = share_mode_forall_leases(
5487 lck, lease_match_break_fn, &break_state);
5489 DBG_DEBUG("share_mode_forall_leases failed\n");
5495 if (break_state.found_lease) {
5496 *p_version = break_state.version;
5497 *p_epoch = break_state.epoch;
5501 * Ensure we don't grant anything more so we
5504 return NT_STATUS_OPLOCK_NOT_GRANTED;
5508 * Wrapper around open_file_ntcreate and open_directory
5511 static NTSTATUS create_file_unixpath(connection_struct *conn,
5512 struct smb_request *req,
5513 struct files_struct **dirfsp,
5514 struct smb_filename *smb_fname,
5515 uint32_t access_mask,
5516 uint32_t share_access,
5517 uint32_t create_disposition,
5518 uint32_t create_options,
5519 uint32_t file_attributes,
5520 uint32_t oplock_request,
5521 const struct smb2_lease *lease,
5522 uint64_t allocation_size,
5523 uint32_t private_flags,
5524 struct security_descriptor *sd,
5525 struct ea_list *ea_list,
5527 files_struct **result,
5530 struct smb2_lease none_lease;
5531 int info = FILE_WAS_OPENED;
5532 files_struct *base_fsp = NULL;
5533 files_struct *fsp = NULL;
5536 SMB_ASSERT(*dirfsp == conn->cwd_fsp);
5538 DBG_DEBUG("create_file_unixpath: access_mask = 0x%x "
5539 "file_attributes = 0x%x, share_access = 0x%x, "
5540 "create_disposition = 0x%x create_options = 0x%x "
5541 "oplock_request = 0x%x private_flags = 0x%x "
5542 "ea_list = %p, sd = %p, "
5544 (unsigned int)access_mask,
5545 (unsigned int)file_attributes,
5546 (unsigned int)share_access,
5547 (unsigned int)create_disposition,
5548 (unsigned int)create_options,
5549 (unsigned int)oplock_request,
5550 (unsigned int)private_flags,
5551 ea_list, sd, smb_fname_str_dbg(smb_fname));
5553 if (create_options & FILE_OPEN_BY_FILE_ID) {
5554 status = NT_STATUS_NOT_SUPPORTED;
5558 if (create_options & NTCREATEX_OPTIONS_INVALID_PARAM_MASK) {
5559 status = NT_STATUS_INVALID_PARAMETER;
5564 oplock_request |= INTERNAL_OPEN_ONLY;
5567 if (lease != NULL) {
5568 uint16_t epoch = lease->lease_epoch;
5569 uint16_t version = lease->lease_version;
5572 DBG_WARNING("Got lease on internal open\n");
5573 status = NT_STATUS_INTERNAL_ERROR;
5577 status = lease_match(conn,
5584 if (NT_STATUS_EQUAL(status, NT_STATUS_OPLOCK_NOT_GRANTED)) {
5585 /* Dynamic share file. No leases and update epoch... */
5586 none_lease = *lease;
5587 none_lease.lease_state = SMB2_LEASE_NONE;
5588 none_lease.lease_epoch = epoch;
5589 none_lease.lease_version = version;
5590 lease = &none_lease;
5591 } else if (!NT_STATUS_IS_OK(status)) {
5596 if ((conn->fs_capabilities & FILE_NAMED_STREAMS)
5597 && (access_mask & DELETE_ACCESS)
5598 && !is_ntfs_stream_smb_fname(smb_fname)) {
5600 * We can't open a file with DELETE access if any of the
5601 * streams is open without FILE_SHARE_DELETE
5603 status = open_streams_for_delete(conn, smb_fname);
5605 if (!NT_STATUS_IS_OK(status)) {
5610 if (access_mask & SEC_FLAG_SYSTEM_SECURITY) {
5613 ok = security_token_has_privilege(get_current_nttok(conn),
5616 DBG_DEBUG("open on %s failed - "
5617 "SEC_FLAG_SYSTEM_SECURITY denied.\n",
5618 smb_fname_str_dbg(smb_fname));
5619 status = NT_STATUS_PRIVILEGE_NOT_HELD;
5623 if (conn->sconn->using_smb2 &&
5624 (access_mask == SEC_FLAG_SYSTEM_SECURITY))
5627 * No other bits set. Windows SMB2 refuses this.
5628 * See smbtorture3 SMB2-SACL test.
5630 * Note this is an SMB2-only behavior,
5631 * smbtorture3 SMB1-SYSTEM-SECURITY already tests
5632 * that SMB1 allows this.
5634 status = NT_STATUS_ACCESS_DENIED;
5640 * Files or directories can't be opened DELETE_ON_CLOSE without
5642 * BUG: https://bugzilla.samba.org/show_bug.cgi?id=13358
5644 if (create_options & FILE_DELETE_ON_CLOSE) {
5645 if ((access_mask & DELETE_ACCESS) == 0) {
5646 status = NT_STATUS_INVALID_PARAMETER;
5651 if ((conn->fs_capabilities & FILE_NAMED_STREAMS)
5652 && is_ntfs_stream_smb_fname(smb_fname)
5653 && (!(private_flags & NTCREATEX_OPTIONS_PRIVATE_STREAM_DELETE))) {
5654 uint32_t base_create_disposition;
5655 struct smb_filename *smb_fname_base = NULL;
5656 uint32_t base_privflags;
5658 if (create_options & FILE_DIRECTORY_FILE) {
5659 status = NT_STATUS_NOT_A_DIRECTORY;
5663 switch (create_disposition) {
5665 base_create_disposition = FILE_OPEN;
5668 base_create_disposition = FILE_OPEN_IF;
5672 /* Create an smb_filename with stream_name == NULL. */
5673 smb_fname_base = synthetic_smb_fname(talloc_tos(),
5674 smb_fname->base_name,
5679 if (smb_fname_base == NULL) {
5680 status = NT_STATUS_NO_MEMORY;
5684 if (SMB_VFS_STAT(conn, smb_fname_base) == -1) {
5685 DEBUG(10, ("Unable to stat stream: %s\n",
5686 smb_fname_str_dbg(smb_fname_base)));
5689 * https://bugzilla.samba.org/show_bug.cgi?id=10229
5690 * We need to check if the requested access mask
5691 * could be used to open the underlying file (if
5692 * it existed), as we're passing in zero for the
5693 * access mask to the base filename.
5695 status = check_base_file_access(conn,
5699 if (!NT_STATUS_IS_OK(status)) {
5700 DEBUG(10, ("Permission check "
5701 "for base %s failed: "
5702 "%s\n", smb_fname->base_name,
5703 nt_errstr(status)));
5708 base_privflags = NTCREATEX_OPTIONS_PRIVATE_STREAM_BASEOPEN;
5710 /* Open the base file. */
5711 status = create_file_unixpath(conn,
5718 | FILE_SHARE_DELETE,
5719 base_create_disposition,
5730 TALLOC_FREE(smb_fname_base);
5732 if (!NT_STATUS_IS_OK(status)) {
5733 DEBUG(10, ("create_file_unixpath for base %s failed: "
5734 "%s\n", smb_fname->base_name,
5735 nt_errstr(status)));
5738 /* we don't need the low level fd */
5743 * If it's a request for a directory open, deal with it separately.
5746 if (create_options & FILE_DIRECTORY_FILE) {
5748 if (create_options & FILE_NON_DIRECTORY_FILE) {
5749 status = NT_STATUS_INVALID_PARAMETER;
5753 /* Can't open a temp directory. IFS kit test. */
5754 if (!(file_attributes & FILE_FLAG_POSIX_SEMANTICS) &&
5755 (file_attributes & FILE_ATTRIBUTE_TEMPORARY)) {
5756 status = NT_STATUS_INVALID_PARAMETER;
5761 * We will get a create directory here if the Win32
5762 * app specified a security descriptor in the
5763 * CreateDirectory() call.
5767 status = open_directory(conn,
5781 * Ordinary file case.
5784 status = file_new(req, conn, &fsp);
5785 if(!NT_STATUS_IS_OK(status)) {
5789 status = fsp_set_smb_fname(fsp, smb_fname);
5790 if (!NT_STATUS_IS_OK(status)) {
5794 if (*dirfsp == fsp->conn->cwd_fsp) {
5795 fsp->dirfsp = fsp->conn->cwd_fsp;
5797 fsp->dirfsp = talloc_move(fsp, dirfsp);
5802 * We're opening the stream element of a
5803 * base_fsp we already opened. Set up the
5806 fsp->base_fsp = base_fsp;
5809 if (allocation_size) {
5810 fsp->initial_allocation_size = smb_roundup(fsp->conn,
5814 status = open_file_ntcreate(conn,
5827 if(!NT_STATUS_IS_OK(status)) {
5828 file_free(req, fsp);
5832 if (NT_STATUS_EQUAL(status, NT_STATUS_FILE_IS_A_DIRECTORY)) {
5834 /* A stream open never opens a directory */
5837 status = NT_STATUS_FILE_IS_A_DIRECTORY;
5842 * Fail the open if it was explicitly a non-directory
5846 if (create_options & FILE_NON_DIRECTORY_FILE) {
5847 status = NT_STATUS_FILE_IS_A_DIRECTORY;
5852 status = open_directory(conn,
5866 if (!NT_STATUS_IS_OK(status)) {
5870 fsp->base_fsp = base_fsp;
5872 if ((ea_list != NULL) &&
5873 ((info == FILE_WAS_CREATED) || (info == FILE_WAS_OVERWRITTEN))) {
5874 status = set_ea(conn, fsp, fsp->fsp_name, ea_list);
5875 if (!NT_STATUS_IS_OK(status)) {
5880 if (!fsp->fsp_flags.is_directory &&
5881 S_ISDIR(fsp->fsp_name->st.st_ex_mode))
5883 status = NT_STATUS_ACCESS_DENIED;
5887 /* Save the requested allocation size. */
5888 if ((info == FILE_WAS_CREATED) || (info == FILE_WAS_OVERWRITTEN)) {
5889 if ((allocation_size > (uint64_t)fsp->fsp_name->st.st_ex_size)
5890 && !(fsp->fsp_flags.is_directory))
5892 fsp->initial_allocation_size = smb_roundup(
5893 fsp->conn, allocation_size);
5894 if (vfs_allocate_file_space(
5895 fsp, fsp->initial_allocation_size) == -1) {
5896 status = NT_STATUS_DISK_FULL;
5900 fsp->initial_allocation_size = smb_roundup(
5901 fsp->conn, (uint64_t)fsp->fsp_name->st.st_ex_size);
5904 fsp->initial_allocation_size = 0;
5907 if ((info == FILE_WAS_CREATED) && lp_nt_acl_support(SNUM(conn)) &&
5908 fsp->base_fsp == NULL) {
5911 * According to the MS documentation, the only time the security
5912 * descriptor is applied to the opened file is iff we *created* the
5913 * file; an existing file stays the same.
5915 * Also, it seems (from observation) that you can open the file with
5916 * any access mask but you can still write the sd. We need to override
5917 * the granted access before we call set_sd
5918 * Patch for bug #2242 from Tom Lackemann <cessnatomny@yahoo.com>.
5921 uint32_t sec_info_sent;
5922 uint32_t saved_access_mask = fsp->access_mask;
5924 sec_info_sent = get_sec_info(sd);
5926 fsp->access_mask = FILE_GENERIC_ALL;
5928 if (sec_info_sent & (SECINFO_OWNER|
5932 status = set_sd(fsp, sd, sec_info_sent);
5935 fsp->access_mask = saved_access_mask;
5937 if (!NT_STATUS_IS_OK(status)) {
5940 } else if (lp_inherit_acls(SNUM(conn))) {
5941 /* Inherit from parent. Errors here are not fatal. */
5942 status = inherit_new_acl(fsp);
5943 if (!NT_STATUS_IS_OK(status)) {
5944 DEBUG(10,("inherit_new_acl: failed for %s with %s\n",
5946 nt_errstr(status) ));
5951 if ((conn->fs_capabilities & FILE_FILE_COMPRESSION)
5952 && (create_options & FILE_NO_COMPRESSION)
5953 && (info == FILE_WAS_CREATED)) {
5954 status = SMB_VFS_SET_COMPRESSION(conn, fsp, fsp,
5955 COMPRESSION_FORMAT_NONE);
5956 if (!NT_STATUS_IS_OK(status)) {
5957 DEBUG(1, ("failed to disable compression: %s\n",
5958 nt_errstr(status)));
5962 DEBUG(10, ("create_file_unixpath: info=%d\n", info));
5965 if (pinfo != NULL) {
5969 smb_fname->st = fsp->fsp_name->st;
5971 return NT_STATUS_OK;
5974 DEBUG(10, ("create_file_unixpath: %s\n", nt_errstr(status)));
5977 if (base_fsp && fsp->base_fsp == base_fsp) {
5979 * The close_file below will close
5984 close_file(req, fsp, ERROR_CLOSE);
5987 if (base_fsp != NULL) {
5988 close_file(req, base_fsp, ERROR_CLOSE);
5994 NTSTATUS create_file_default(connection_struct *conn,
5995 struct smb_request *req,
5996 struct files_struct **_dirfsp,
5997 struct smb_filename *smb_fname,
5998 uint32_t access_mask,
5999 uint32_t share_access,
6000 uint32_t create_disposition,
6001 uint32_t create_options,
6002 uint32_t file_attributes,
6003 uint32_t oplock_request,
6004 const struct smb2_lease *lease,
6005 uint64_t allocation_size,
6006 uint32_t private_flags,
6007 struct security_descriptor *sd,
6008 struct ea_list *ea_list,
6009 files_struct **result,
6011 const struct smb2_create_blobs *in_context_blobs,
6012 struct smb2_create_blobs *out_context_blobs)
6014 int info = FILE_WAS_OPENED;
6015 files_struct *fsp = NULL;
6017 bool stream_name = false;
6018 struct smb2_create_blob *posx = NULL;
6019 struct files_struct *dirfsp = *_dirfsp;
6021 SMB_ASSERT(dirfsp == dirfsp->conn->cwd_fsp);
6023 DBG_DEBUG("create_file: access_mask = 0x%x "
6024 "file_attributes = 0x%x, share_access = 0x%x, "
6025 "create_disposition = 0x%x create_options = 0x%x "
6026 "oplock_request = 0x%x "
6027 "private_flags = 0x%x "
6028 "ea_list = %p, sd = %p, "
6031 (unsigned int)access_mask,
6032 (unsigned int)file_attributes,
6033 (unsigned int)share_access,
6034 (unsigned int)create_disposition,
6035 (unsigned int)create_options,
6036 (unsigned int)oplock_request,
6037 (unsigned int)private_flags,
6040 fsp_str_dbg(dirfsp),
6041 smb_fname_str_dbg(smb_fname));
6045 * Remember the absolute time of the original request
6046 * with this mid. We'll use it later to see if this
6049 get_deferred_open_message_state(req, &req->request_time, NULL);
6053 * Check to see if this is a mac fork of some kind.
6056 stream_name = is_ntfs_stream_smb_fname(smb_fname);
6058 enum FAKE_FILE_TYPE fake_file_type;
6060 fake_file_type = is_fake_file(smb_fname);
6062 if (req != NULL && fake_file_type != FAKE_FILE_TYPE_NONE) {
6065 * Here we go! support for changing the disk quotas
6068 * We need to fake up to open this MAGIC QUOTA file
6069 * and return a valid FID.
6071 * w2k close this file directly after openening xp
6072 * also tries a QUERY_FILE_INFO on the file and then
6075 status = open_fake_file(req, conn, req->vuid,
6076 fake_file_type, smb_fname,
6078 if (!NT_STATUS_IS_OK(status)) {
6082 ZERO_STRUCT(smb_fname->st);
6086 if (!(conn->fs_capabilities & FILE_NAMED_STREAMS)) {
6087 status = NT_STATUS_OBJECT_NAME_NOT_FOUND;
6092 if (is_ntfs_default_stream_smb_fname(smb_fname)) {
6094 smb_fname->stream_name = NULL;
6095 /* We have to handle this error here. */
6096 if (create_options & FILE_DIRECTORY_FILE) {
6097 status = NT_STATUS_NOT_A_DIRECTORY;
6100 if (req != NULL && req->posix_pathnames) {
6101 ret = SMB_VFS_LSTAT(conn, smb_fname);
6103 ret = SMB_VFS_STAT(conn, smb_fname);
6106 if (ret == 0 && VALID_STAT_OF_DIR(smb_fname->st)) {
6107 status = NT_STATUS_FILE_IS_A_DIRECTORY;
6112 posx = smb2_create_blob_find(
6113 in_context_blobs, SMB2_CREATE_TAG_POSIX);
6115 uint32_t wire_mode_bits = 0;
6116 mode_t mode_bits = 0;
6117 SMB_STRUCT_STAT sbuf = { 0 };
6118 enum perm_type ptype =
6119 (create_options & FILE_DIRECTORY_FILE) ?
6120 PERM_NEW_DIR : PERM_NEW_FILE;
6122 if (posx->data.length != 4) {
6123 status = NT_STATUS_INVALID_PARAMETER;
6127 wire_mode_bits = IVAL(posx->data.data, 0);
6128 status = unix_perms_from_wire(
6129 conn, &sbuf, wire_mode_bits, ptype, &mode_bits);
6130 if (!NT_STATUS_IS_OK(status)) {
6134 * Remove type info from mode, leaving only the
6135 * permissions and setuid/gid bits.
6137 mode_bits &= ~S_IFMT;
6139 file_attributes = (FILE_FLAG_POSIX_SEMANTICS | mode_bits);
6142 status = create_file_unixpath(conn,
6159 if (!NT_STATUS_IS_OK(status)) {
6164 DEBUG(10, ("create_file: info=%d\n", info));
6167 if (pinfo != NULL) {
6170 return NT_STATUS_OK;
6173 DEBUG(10, ("create_file: %s\n", nt_errstr(status)));
6176 close_file(req, fsp, ERROR_CLOSE);