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(conn,
316 if (!NT_STATUS_IS_OK(status)) {
317 DEBUG(5,("check_parent_access: SMB_VFS_GET_NT_ACL failed for "
318 "%s with error %s\n",
319 smb_fname_str_dbg(parent_dir),
325 * If we can access the path to this file, by
326 * default we have FILE_READ_ATTRIBUTES from the
327 * containing directory. See the section:
328 * "Algorithm to Check Access to an Existing File"
331 * se_file_access_check() also takes care of
332 * owner WRITE_DAC and READ_CONTROL.
334 status = se_file_access_check(parent_sd,
335 get_current_nttok(conn),
337 (access_mask & ~FILE_READ_ATTRIBUTES),
339 if(!NT_STATUS_IS_OK(status)) {
340 DEBUG(5,("check_parent_access: access check "
341 "on directory %s for "
342 "path %s for mask 0x%x returned (0x%x) %s\n",
343 smb_fname_str_dbg(parent_dir),
344 smb_fname->base_name,
347 nt_errstr(status) ));
351 if (!(access_mask & (SEC_DIR_ADD_FILE | SEC_DIR_ADD_SUBDIR))) {
352 status = NT_STATUS_OK;
355 if (!lp_check_parent_directory_delete_on_close(SNUM(conn))) {
356 status = NT_STATUS_OK;
360 /* Check if the directory has delete-on-close set */
361 ret = SMB_VFS_STAT(conn, parent_dir);
363 status = map_nt_error_from_unix(errno);
367 id = SMB_VFS_FILE_ID_CREATE(conn, &parent_dir->st);
369 status = file_name_hash(conn, parent_dir->base_name, &name_hash);
370 if (!NT_STATUS_IS_OK(status)) {
374 lck = get_existing_share_mode_lock(frame, id);
376 status = NT_STATUS_OK;
380 delete_on_close_set = is_delete_on_close_set(lck, name_hash);
381 if (delete_on_close_set) {
382 status = NT_STATUS_DELETE_PENDING;
386 status = NT_STATUS_OK;
393 /****************************************************************************
394 Ensure when opening a base file for a stream open that we have permissions
395 to do so given the access mask on the base file.
396 ****************************************************************************/
398 static NTSTATUS check_base_file_access(struct connection_struct *conn,
399 struct smb_filename *smb_fname,
400 uint32_t access_mask)
404 status = smbd_calculate_access_mask(conn,
410 if (!NT_STATUS_IS_OK(status)) {
411 DEBUG(10, ("smbd_calculate_access_mask "
412 "on file %s returned %s\n",
413 smb_fname_str_dbg(smb_fname),
418 if (access_mask & (FILE_WRITE_DATA|FILE_APPEND_DATA)) {
420 if (!CAN_WRITE(conn)) {
421 return NT_STATUS_ACCESS_DENIED;
423 dosattrs = dos_mode(conn, smb_fname);
424 if (IS_DOS_READONLY(dosattrs)) {
425 return NT_STATUS_ACCESS_DENIED;
429 return smbd_check_access_rights(conn,
436 /****************************************************************************
437 Handle differing symlink errno's
438 ****************************************************************************/
440 static int link_errno_convert(int err)
442 #if defined(ENOTSUP) && defined(OSF1)
443 /* handle special Tru64 errno */
444 if (err == ENOTSUP) {
449 /* fix broken NetBSD errno */
454 /* fix broken FreeBSD errno */
461 static int non_widelink_open(struct connection_struct *conn,
462 const struct smb_filename *conn_rootdir_fname,
464 struct smb_filename *smb_fname,
467 unsigned int link_depth);
469 /****************************************************************************
470 Follow a symlink in userspace.
471 ****************************************************************************/
473 static int process_symlink_open(struct connection_struct *conn,
474 const struct smb_filename *conn_rootdir_fname,
476 struct smb_filename *smb_fname,
479 unsigned int link_depth)
482 char *link_target = NULL;
483 struct smb_filename target_fname = {0};
485 struct smb_filename *oldwd_fname = NULL;
486 size_t rootdir_len = 0;
487 struct smb_filename *resolved_fname = NULL;
488 char *resolved_name = NULL;
489 bool matched = false;
493 * Ensure we don't get stuck in a symlink loop.
496 if (link_depth >= 20) {
501 /* Allocate space for the link target. */
502 link_target = talloc_array(talloc_tos(), char, PATH_MAX);
503 if (link_target == NULL) {
508 /* Read the link target. */
509 link_len = SMB_VFS_READLINKAT(conn,
514 if (link_len == -1) {
518 /* Ensure it's at least null terminated. */
519 link_target[link_len] = '\0';
520 target_fname = (struct smb_filename) {
521 .base_name = link_target,
522 .twrp = smb_fname->twrp,
525 /* Convert to an absolute path. */
526 resolved_fname = SMB_VFS_REALPATH(conn, talloc_tos(), &target_fname);
527 if (resolved_fname == NULL) {
530 resolved_name = resolved_fname->base_name;
533 * We know conn_rootdir starts with '/' and
534 * does not end in '/'. FIXME ! Should we
537 rootdir_len = strlen(conn_rootdir_fname->base_name);
539 matched = (strncmp(conn_rootdir_fname->base_name,
548 * Turn into a path relative to the share root.
550 if (resolved_name[rootdir_len] == '\0') {
551 /* Link to the root of the share. */
552 TALLOC_FREE(smb_fname->base_name);
553 smb_fname->base_name = talloc_strdup(smb_fname, ".");
554 } else if (resolved_name[rootdir_len] == '/') {
555 TALLOC_FREE(smb_fname->base_name);
556 smb_fname->base_name = talloc_strdup(smb_fname,
557 &resolved_name[rootdir_len+1]);
563 if (smb_fname->base_name == NULL) {
568 oldwd_fname = vfs_GetWd(talloc_tos(), conn);
569 if (oldwd_fname == NULL) {
573 /* Ensure we operate from the root of the share. */
574 if (vfs_ChDir(conn, conn_rootdir_fname) == -1) {
578 /* And do it all again.. */
579 fd = non_widelink_open(conn,
592 TALLOC_FREE(resolved_fname);
593 TALLOC_FREE(link_target);
594 if (oldwd_fname != NULL) {
595 int ret = vfs_ChDir(conn, oldwd_fname);
597 smb_panic("unable to get back to old directory\n");
599 TALLOC_FREE(oldwd_fname);
601 if (saved_errno != 0) {
607 /****************************************************************************
609 ****************************************************************************/
611 static int non_widelink_open(struct connection_struct *conn,
612 const struct smb_filename *conn_rootdir_fname,
614 struct smb_filename *smb_fname,
617 unsigned int link_depth)
621 struct smb_filename *smb_fname_rel = NULL;
623 struct smb_filename *oldwd_fname = NULL;
624 struct smb_filename *parent_dir_fname = NULL;
627 if (fsp->fsp_flags.is_directory) {
628 parent_dir_fname = cp_smb_filename(talloc_tos(), smb_fname);
629 if (parent_dir_fname == NULL) {
634 smb_fname_rel = synthetic_smb_fname(parent_dir_fname,
636 smb_fname->stream_name,
640 if (smb_fname_rel == NULL) {
645 ok = parent_smb_fname(talloc_tos(),
655 oldwd_fname = vfs_GetWd(talloc_tos(), conn);
656 if (oldwd_fname == NULL) {
660 /* Pin parent directory in place. */
661 if (vfs_ChDir(conn, parent_dir_fname) == -1) {
665 /* Ensure the relative path is below the share. */
666 status = check_reduced_name(conn, parent_dir_fname, smb_fname_rel);
667 if (!NT_STATUS_IS_OK(status)) {
668 saved_errno = map_errno_from_nt_status(status);
675 struct smb_filename *tmp_name = fsp->fsp_name;
676 fsp->fsp_name = smb_fname_rel;
677 fd = SMB_VFS_OPEN(conn, smb_fname_rel, fsp, flags, mode);
678 fsp->fsp_name = tmp_name;
682 saved_errno = link_errno_convert(errno);
684 * Trying to open a symlink to a directory with O_NOFOLLOW and
685 * O_DIRECTORY can return either of ELOOP and ENOTDIR. So
686 * ENOTDIR really means: might be a symlink, but we're not sure.
687 * In this case, we just assume there's a symlink. If we were
688 * wrong, process_symlink_open() will return EINVAL. We check
689 * this below, and fall back to returning the initial
692 * BUG: https://bugzilla.samba.org/show_bug.cgi?id=12860
694 if (saved_errno == ELOOP || saved_errno == ENOTDIR) {
695 if (fsp->posix_flags & FSP_POSIX_FLAGS_OPEN) {
696 /* Never follow symlinks on posix open. */
699 if (!lp_follow_symlinks(SNUM(conn))) {
700 /* Explicitly no symlinks. */
704 * We may have a symlink. Follow in userspace
705 * to ensure it's under the share definition.
707 fd = process_symlink_open(conn,
715 if (saved_errno == ENOTDIR &&
718 * O_DIRECTORY on neither a directory,
719 * nor a symlink. Just return
720 * saved_errno from initial open()
725 link_errno_convert(errno);
732 TALLOC_FREE(parent_dir_fname);
734 if (oldwd_fname != NULL) {
735 int ret = vfs_ChDir(conn, oldwd_fname);
737 smb_panic("unable to get back to old directory\n");
739 TALLOC_FREE(oldwd_fname);
741 if (saved_errno != 0) {
747 /****************************************************************************
748 fd support routines - attempt to do a dos_open.
749 ****************************************************************************/
751 NTSTATUS fd_open(struct connection_struct *conn,
756 struct smb_filename *smb_fname = fsp->fsp_name;
757 NTSTATUS status = NT_STATUS_OK;
758 struct smb_filename *conn_rootdir_fname = NULL;
759 const char *conn_rootdir;
763 * Never follow symlinks on a POSIX client. The
764 * client should be doing this.
767 if ((fsp->posix_flags & FSP_POSIX_FLAGS_OPEN) || !lp_follow_symlinks(SNUM(conn))) {
771 /* Ensure path is below share definition. */
772 conn_rootdir = SMB_VFS_CONNECTPATH(conn,
775 if (conn_rootdir == NULL) {
776 return NT_STATUS_NO_MEMORY;
778 conn_rootdir_fname = synthetic_smb_fname(talloc_tos(),
784 if (conn_rootdir_fname == NULL) {
785 return NT_STATUS_NO_MEMORY;
789 * Only follow symlinks within a share
792 fsp->fh->fd = non_widelink_open(conn,
799 if (fsp->fh->fd == -1) {
802 TALLOC_FREE(conn_rootdir_fname);
803 if (saved_errno != 0) {
807 if (fsp->fh->fd == -1) {
808 int posix_errno = link_errno_convert(errno);
809 status = map_nt_error_from_unix(posix_errno);
810 if (errno == EMFILE) {
811 static time_t last_warned = 0L;
813 if (time((time_t *) NULL) > last_warned) {
814 DEBUG(0,("Too many open files, unable "
815 "to open more! smbd's max "
817 lp_max_open_files()));
818 last_warned = time((time_t *) NULL);
824 DEBUG(10,("fd_open: name %s, flags = 0%o mode = 0%o, fd = %d. %s\n",
825 smb_fname_str_dbg(smb_fname), flags, (int)mode, fsp->fh->fd,
826 (fsp->fh->fd == -1) ? strerror(errno) : "" ));
831 /****************************************************************************
832 Close the file associated with a fsp.
833 ****************************************************************************/
835 NTSTATUS fd_close(files_struct *fsp)
842 if (fsp->fh->fd == -1) {
844 * Either a directory where the dptr_CloseDir() already closed
845 * the fd or a stat open.
849 if (fsp->fh->ref_count > 1) {
850 return NT_STATUS_OK; /* Shared handle. Only close last reference. */
853 ret = SMB_VFS_CLOSE(fsp);
856 return map_nt_error_from_unix(errno);
861 /****************************************************************************
862 Change the ownership of a file to that of the parent directory.
863 Do this by fd if possible.
864 ****************************************************************************/
866 void change_file_owner_to_parent(connection_struct *conn,
867 struct smb_filename *smb_fname_parent,
872 ret = SMB_VFS_STAT(conn, smb_fname_parent);
874 DEBUG(0,("change_file_owner_to_parent: failed to stat parent "
875 "directory %s. Error was %s\n",
876 smb_fname_str_dbg(smb_fname_parent),
878 TALLOC_FREE(smb_fname_parent);
882 if (smb_fname_parent->st.st_ex_uid == fsp->fsp_name->st.st_ex_uid) {
883 /* Already this uid - no need to change. */
884 DEBUG(10,("change_file_owner_to_parent: file %s "
885 "is already owned by uid %d\n",
887 (int)fsp->fsp_name->st.st_ex_uid ));
888 TALLOC_FREE(smb_fname_parent);
893 ret = SMB_VFS_FCHOWN(fsp, smb_fname_parent->st.st_ex_uid, (gid_t)-1);
896 DEBUG(0,("change_file_owner_to_parent: failed to fchown "
897 "file %s to parent directory uid %u. Error "
898 "was %s\n", fsp_str_dbg(fsp),
899 (unsigned int)smb_fname_parent->st.st_ex_uid,
902 DEBUG(10,("change_file_owner_to_parent: changed new file %s to "
903 "parent directory uid %u.\n", fsp_str_dbg(fsp),
904 (unsigned int)smb_fname_parent->st.st_ex_uid));
905 /* Ensure the uid entry is updated. */
906 fsp->fsp_name->st.st_ex_uid = smb_fname_parent->st.st_ex_uid;
910 static NTSTATUS change_dir_owner_to_parent(connection_struct *conn,
911 struct smb_filename *smb_fname_parent,
912 struct smb_filename *smb_dname,
913 SMB_STRUCT_STAT *psbuf)
915 struct smb_filename *smb_fname_cwd = NULL;
916 struct smb_filename *saved_dir_fname = NULL;
917 TALLOC_CTX *ctx = talloc_tos();
918 NTSTATUS status = NT_STATUS_OK;
921 ret = SMB_VFS_STAT(conn, smb_fname_parent);
923 status = map_nt_error_from_unix(errno);
924 DEBUG(0,("change_dir_owner_to_parent: failed to stat parent "
925 "directory %s. Error was %s\n",
926 smb_fname_str_dbg(smb_fname_parent),
931 /* We've already done an lstat into psbuf, and we know it's a
932 directory. If we can cd into the directory and the dev/ino
933 are the same then we can safely chown without races as
934 we're locking the directory in place by being in it. This
935 should work on any UNIX (thanks tridge :-). JRA.
938 saved_dir_fname = vfs_GetWd(ctx,conn);
939 if (!saved_dir_fname) {
940 status = map_nt_error_from_unix(errno);
941 DEBUG(0,("change_dir_owner_to_parent: failed to get "
942 "current working directory. Error was %s\n",
947 /* Chdir into the new path. */
948 if (vfs_ChDir(conn, smb_dname) == -1) {
949 status = map_nt_error_from_unix(errno);
950 DEBUG(0,("change_dir_owner_to_parent: failed to change "
951 "current working directory to %s. Error "
952 "was %s\n", smb_dname->base_name, strerror(errno) ));
956 smb_fname_cwd = synthetic_smb_fname(ctx,
962 if (smb_fname_cwd == NULL) {
963 status = NT_STATUS_NO_MEMORY;
967 ret = SMB_VFS_STAT(conn, smb_fname_cwd);
969 status = map_nt_error_from_unix(errno);
970 DEBUG(0,("change_dir_owner_to_parent: failed to stat "
971 "directory '.' (%s) Error was %s\n",
972 smb_dname->base_name, strerror(errno)));
976 /* Ensure we're pointing at the same place. */
977 if (smb_fname_cwd->st.st_ex_dev != psbuf->st_ex_dev ||
978 smb_fname_cwd->st.st_ex_ino != psbuf->st_ex_ino) {
979 DEBUG(0,("change_dir_owner_to_parent: "
980 "device/inode on directory %s changed. "
981 "Refusing to chown !\n",
982 smb_dname->base_name ));
983 status = NT_STATUS_ACCESS_DENIED;
987 if (smb_fname_parent->st.st_ex_uid == smb_fname_cwd->st.st_ex_uid) {
988 /* Already this uid - no need to change. */
989 DEBUG(10,("change_dir_owner_to_parent: directory %s "
990 "is already owned by uid %d\n",
991 smb_dname->base_name,
992 (int)smb_fname_cwd->st.st_ex_uid ));
993 status = NT_STATUS_OK;
998 ret = SMB_VFS_LCHOWN(conn,
1000 smb_fname_parent->st.st_ex_uid,
1004 status = map_nt_error_from_unix(errno);
1005 DEBUG(10,("change_dir_owner_to_parent: failed to chown "
1006 "directory %s to parent directory uid %u. "
1008 smb_dname->base_name,
1009 (unsigned int)smb_fname_parent->st.st_ex_uid,
1012 DEBUG(10,("change_dir_owner_to_parent: changed ownership of new "
1013 "directory %s to parent directory uid %u.\n",
1014 smb_dname->base_name,
1015 (unsigned int)smb_fname_parent->st.st_ex_uid ));
1016 /* Ensure the uid entry is updated. */
1017 psbuf->st_ex_uid = smb_fname_parent->st.st_ex_uid;
1021 vfs_ChDir(conn, saved_dir_fname);
1023 TALLOC_FREE(saved_dir_fname);
1024 TALLOC_FREE(smb_fname_cwd);
1028 /****************************************************************************
1029 Open a file - returning a guaranteed ATOMIC indication of if the
1030 file was created or not.
1031 ****************************************************************************/
1033 static NTSTATUS fd_open_atomic(struct connection_struct *conn,
1039 NTSTATUS status = NT_STATUS_UNSUCCESSFUL;
1040 NTSTATUS retry_status;
1041 bool file_existed = VALID_STAT(fsp->fsp_name->st);
1044 if (!(flags & O_CREAT)) {
1046 * We're not creating the file, just pass through.
1048 status = fd_open(conn, fsp, flags, mode);
1049 *file_created = false;
1053 if (flags & O_EXCL) {
1055 * Fail if already exists, just pass through.
1057 status = fd_open(conn, fsp, flags, mode);
1060 * Here we've opened with O_CREAT|O_EXCL. If that went
1061 * NT_STATUS_OK, we *know* we created this file.
1063 *file_created = NT_STATUS_IS_OK(status);
1069 * Now it gets tricky. We have O_CREAT, but not O_EXCL.
1070 * To know absolutely if we created the file or not,
1071 * we can never call O_CREAT without O_EXCL. So if
1072 * we think the file existed, try without O_CREAT|O_EXCL.
1073 * If we think the file didn't exist, try with
1076 * The big problem here is dangling symlinks. Opening
1077 * without O_NOFOLLOW means both bad symlink
1078 * and missing path return -1, ENOENT from open(). As POSIX
1079 * is pathname based it's not possible to tell
1080 * the difference between these two cases in a
1081 * non-racy way, so change to try only two attempts before
1084 * We don't have this problem for the O_NOFOLLOW
1085 * case as it just returns NT_STATUS_OBJECT_PATH_NOT_FOUND
1086 * mapped from the ELOOP POSIX error.
1090 curr_flags = flags & ~(O_CREAT);
1091 retry_status = NT_STATUS_OBJECT_NAME_NOT_FOUND;
1093 curr_flags = flags | O_EXCL;
1094 retry_status = NT_STATUS_OBJECT_NAME_COLLISION;
1097 status = fd_open(conn, fsp, curr_flags, mode);
1098 if (NT_STATUS_IS_OK(status)) {
1099 *file_created = !file_existed;
1100 return NT_STATUS_OK;
1102 if (NT_STATUS_EQUAL(status, retry_status)) {
1104 file_existed = !file_existed;
1106 DBG_DEBUG("File %s %s. Retry.\n",
1108 file_existed ? "existed" : "did not exist");
1111 curr_flags = flags & ~(O_CREAT);
1113 curr_flags = flags | O_EXCL;
1116 status = fd_open(conn, fsp, curr_flags, mode);
1119 *file_created = (NT_STATUS_IS_OK(status) && !file_existed);
1123 /****************************************************************************
1125 ****************************************************************************/
1127 static NTSTATUS open_file(files_struct *fsp,
1128 connection_struct *conn,
1129 struct smb_request *req,
1130 struct smb_filename *parent_dir,
1133 uint32_t access_mask, /* client requested access mask. */
1134 uint32_t open_access_mask, /* what we're actually using in the open. */
1135 bool *p_file_created)
1137 struct smb_filename *smb_fname = fsp->fsp_name;
1138 NTSTATUS status = NT_STATUS_OK;
1139 int accmode = (flags & O_ACCMODE);
1140 int local_flags = flags;
1141 bool file_existed = VALID_STAT(fsp->fsp_name->st);
1142 uint32_t need_fd_mask =
1148 WRITE_OWNER_ACCESS |
1149 SEC_FLAG_SYSTEM_SECURITY |
1150 READ_CONTROL_ACCESS;
1151 bool creating = !file_existed && (flags & O_CREAT);
1152 bool truncating = (flags & O_TRUNC);
1157 /* Check permissions */
1160 * This code was changed after seeing a client open request
1161 * containing the open mode of (DENY_WRITE/read-only) with
1162 * the 'create if not exist' bit set. The previous code
1163 * would fail to open the file read only on a read-only share
1164 * as it was checking the flags parameter directly against O_RDONLY,
1165 * this was failing as the flags parameter was set to O_RDONLY|O_CREAT.
1169 if (!CAN_WRITE(conn)) {
1170 /* It's a read-only share - fail if we wanted to write. */
1171 if(accmode != O_RDONLY || (flags & O_TRUNC) || (flags & O_APPEND)) {
1172 DEBUG(3,("Permission denied opening %s\n",
1173 smb_fname_str_dbg(smb_fname)));
1174 return NT_STATUS_ACCESS_DENIED;
1176 if (flags & O_CREAT) {
1177 /* We don't want to write - but we must make sure that
1178 O_CREAT doesn't create the file if we have write
1179 access into the directory.
1181 flags &= ~(O_CREAT|O_EXCL);
1182 local_flags &= ~(O_CREAT|O_EXCL);
1187 * This little piece of insanity is inspired by the
1188 * fact that an NT client can open a file for O_RDONLY,
1189 * but set the create disposition to FILE_EXISTS_TRUNCATE.
1190 * If the client *can* write to the file, then it expects to
1191 * truncate the file, even though it is opening for readonly.
1192 * Quicken uses this stupid trick in backup file creation...
1193 * Thanks *greatly* to "David W. Chapman Jr." <dwcjr@inethouston.net>
1194 * for helping track this one down. It didn't bite us in 2.0.x
1195 * as we always opened files read-write in that release. JRA.
1198 if ((accmode == O_RDONLY) && ((flags & O_TRUNC) == O_TRUNC)) {
1199 DEBUG(10,("open_file: truncate requested on read-only open "
1200 "for file %s\n", smb_fname_str_dbg(smb_fname)));
1201 local_flags = (flags & ~O_ACCMODE)|O_RDWR;
1204 if ((open_access_mask & need_fd_mask) || creating || truncating) {
1208 #if defined(O_NONBLOCK) && defined(S_ISFIFO)
1210 * We would block on opening a FIFO with no one else on the
1211 * other end. Do what we used to do and add O_NONBLOCK to the
1215 if (file_existed && S_ISFIFO(smb_fname->st.st_ex_mode)) {
1216 local_flags &= ~O_TRUNC; /* Can't truncate a FIFO. */
1217 local_flags |= O_NONBLOCK;
1222 /* Don't create files with Microsoft wildcard characters. */
1223 if (fsp->base_fsp) {
1225 * wildcard characters are allowed in stream names
1226 * only test the basefilename
1228 wild = fsp->base_fsp->fsp_name->base_name;
1230 wild = smb_fname->base_name;
1232 if ((local_flags & O_CREAT) && !file_existed &&
1233 !(fsp->posix_flags & FSP_POSIX_FLAGS_PATHNAMES) &&
1234 ms_has_wild(wild)) {
1235 return NT_STATUS_OBJECT_NAME_INVALID;
1238 /* Can we access this file ? */
1239 if (!fsp->base_fsp) {
1240 /* Only do this check on non-stream open. */
1242 status = smbd_check_access_rights(conn,
1248 if (!NT_STATUS_IS_OK(status)) {
1249 DEBUG(10, ("open_file: "
1250 "smbd_check_access_rights "
1251 "on file %s returned %s\n",
1252 smb_fname_str_dbg(smb_fname),
1253 nt_errstr(status)));
1256 if (!NT_STATUS_IS_OK(status) &&
1257 !NT_STATUS_EQUAL(status,
1258 NT_STATUS_OBJECT_NAME_NOT_FOUND))
1263 if (NT_STATUS_EQUAL(status,
1264 NT_STATUS_OBJECT_NAME_NOT_FOUND))
1266 DEBUG(10, ("open_file: "
1267 "file %s vanished since we "
1268 "checked for existence.\n",
1269 smb_fname_str_dbg(smb_fname)));
1270 file_existed = false;
1271 SET_STAT_INVALID(fsp->fsp_name->st);
1275 if (!file_existed) {
1276 if (!(local_flags & O_CREAT)) {
1277 /* File didn't exist and no O_CREAT. */
1278 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
1281 status = check_parent_access(conn,
1285 if (!NT_STATUS_IS_OK(status)) {
1286 DEBUG(10, ("open_file: "
1287 "check_parent_access on "
1288 "file %s returned %s\n",
1289 smb_fname_str_dbg(smb_fname),
1290 nt_errstr(status) ));
1297 * Actually do the open - if O_TRUNC is needed handle it
1298 * below under the share mode lock.
1300 status = fd_open_atomic(conn, fsp, local_flags & ~O_TRUNC,
1301 unx_mode, p_file_created);
1302 if (!NT_STATUS_IS_OK(status)) {
1303 DEBUG(3,("Error opening file %s (%s) (local_flags=%d) "
1304 "(flags=%d)\n", smb_fname_str_dbg(smb_fname),
1305 nt_errstr(status),local_flags,flags));
1309 if (local_flags & O_NONBLOCK) {
1311 * GPFS can return ETIMEDOUT for pread on
1312 * nonblocking file descriptors when files
1313 * migrated to tape need to be recalled. I
1314 * could imagine this happens elsewhere
1315 * too. With blocking file descriptors this
1318 ret = vfs_set_blocking(fsp, true);
1320 status = map_nt_error_from_unix(errno);
1321 DBG_WARNING("Could not set fd to blocking: "
1322 "%s\n", strerror(errno));
1328 ret = SMB_VFS_FSTAT(fsp, &smb_fname->st);
1330 /* If we have an fd, this stat should succeed. */
1331 DEBUG(0,("Error doing fstat on open file %s "
1333 smb_fname_str_dbg(smb_fname),
1335 status = map_nt_error_from_unix(errno);
1340 if (*p_file_created) {
1341 /* We created this file. */
1343 bool need_re_stat = false;
1344 /* Do all inheritance work after we've
1345 done a successful fstat call and filled
1346 in the stat struct in fsp->fsp_name. */
1348 /* Inherit the ACL if required */
1349 if (lp_inherit_permissions(SNUM(conn))) {
1350 inherit_access_posix_acl(conn,
1354 need_re_stat = true;
1357 /* Change the owner if required. */
1358 if (lp_inherit_owner(SNUM(conn)) != INHERIT_OWNER_NO) {
1359 change_file_owner_to_parent(conn,
1362 need_re_stat = true;
1366 ret = SMB_VFS_FSTAT(fsp, &smb_fname->st);
1367 /* If we have an fd, this stat should succeed. */
1369 DEBUG(0,("Error doing fstat on open file %s "
1371 smb_fname_str_dbg(smb_fname),
1376 notify_fname(conn, NOTIFY_ACTION_ADDED,
1377 FILE_NOTIFY_CHANGE_FILE_NAME,
1378 smb_fname->base_name);
1381 fsp->fh->fd = -1; /* What we used to call a stat open. */
1382 if (!file_existed) {
1383 /* File must exist for a stat open. */
1384 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
1387 status = smbd_check_access_rights(conn,
1393 if (NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND) &&
1394 (fsp->posix_flags & FSP_POSIX_FLAGS_OPEN) &&
1395 S_ISLNK(smb_fname->st.st_ex_mode)) {
1396 /* This is a POSIX stat open for delete
1397 * or rename on a symlink that points
1398 * nowhere. Allow. */
1399 DEBUG(10,("open_file: allowing POSIX "
1400 "open on bad symlink %s\n",
1401 smb_fname_str_dbg(smb_fname)));
1402 status = NT_STATUS_OK;
1405 if (!NT_STATUS_IS_OK(status)) {
1406 DEBUG(10,("open_file: "
1407 "smbd_check_access_rights on file "
1409 smb_fname_str_dbg(smb_fname),
1410 nt_errstr(status) ));
1416 * POSIX allows read-only opens of directories. We don't
1417 * want to do this (we use a different code path for this)
1418 * so catch a directory open and return an EISDIR. JRA.
1421 if(S_ISDIR(smb_fname->st.st_ex_mode)) {
1424 return NT_STATUS_FILE_IS_A_DIRECTORY;
1427 fsp->file_id = vfs_file_id_from_sbuf(conn, &smb_fname->st);
1428 fsp->vuid = req ? req->vuid : UID_FIELD_INVALID;
1429 fsp->file_pid = req ? req->smbpid : 0;
1430 fsp->fsp_flags.can_lock = true;
1431 fsp->fsp_flags.can_read = ((access_mask & FILE_READ_DATA) != 0);
1432 fsp->fsp_flags.can_write =
1434 ((access_mask & (FILE_WRITE_DATA | FILE_APPEND_DATA)) != 0);
1435 fsp->print_file = NULL;
1436 fsp->fsp_flags.modified = false;
1437 fsp->sent_oplock_break = NO_BREAK_SENT;
1438 fsp->fsp_flags.is_directory = false;
1439 if (conn->aio_write_behind_list &&
1440 is_in_path(smb_fname->base_name, conn->aio_write_behind_list,
1441 conn->case_sensitive)) {
1442 fsp->fsp_flags.aio_write_behind = true;
1445 DEBUG(2,("%s opened file %s read=%s write=%s (numopen=%d)\n",
1446 conn->session_info->unix_info->unix_name,
1447 smb_fname_str_dbg(smb_fname),
1448 BOOLSTR(fsp->fsp_flags.can_read),
1449 BOOLSTR(fsp->fsp_flags.can_write),
1450 conn->num_files_open));
1453 return NT_STATUS_OK;
1456 static bool mask_conflict(
1457 uint32_t new_access,
1458 uint32_t existing_access,
1459 uint32_t access_mask,
1460 uint32_t new_sharemode,
1461 uint32_t existing_sharemode,
1462 uint32_t sharemode_mask)
1464 bool want_access = (new_access & access_mask);
1465 bool allow_existing = (existing_sharemode & sharemode_mask);
1466 bool have_access = (existing_access & access_mask);
1467 bool allow_new = (new_sharemode & sharemode_mask);
1469 if (want_access && !allow_existing) {
1470 DBG_DEBUG("Access request 0x%"PRIx32"/0x%"PRIx32" conflicts "
1471 "with existing sharemode 0x%"PRIx32"/0x%"PRIx32"\n",
1478 if (have_access && !allow_new) {
1479 DBG_DEBUG("Sharemode request 0x%"PRIx32"/0x%"PRIx32" conflicts "
1480 "with existing access 0x%"PRIx32"/0x%"PRIx32"\n",
1490 /****************************************************************************
1491 Check if we can open a file with a share mode.
1492 Returns True if conflict, False if not.
1493 ****************************************************************************/
1495 static bool share_conflict(uint32_t e_access_mask,
1496 uint32_t e_share_access,
1497 uint32_t access_mask,
1498 uint32_t share_access)
1500 const uint32_t conflicting_access =
1508 DBG_DEBUG("existing access_mask = 0x%"PRIx32", "
1509 "existing share access = 0x%"PRIx32", "
1510 "access_mask = 0x%"PRIx32", "
1511 "share_access = 0x%"PRIx32"\n",
1517 if ((e_access_mask & conflicting_access) == 0) {
1518 DBG_DEBUG("No conflict due to "
1519 "existing access_mask = 0x%"PRIx32"\n",
1523 if ((access_mask & conflicting_access) == 0) {
1524 DBG_DEBUG("No conflict due to access_mask = 0x%"PRIx32"\n",
1529 conflict = mask_conflict(
1530 access_mask, e_access_mask, FILE_WRITE_DATA | FILE_APPEND_DATA,
1531 share_access, e_share_access, FILE_SHARE_WRITE);
1532 conflict |= mask_conflict(
1533 access_mask, e_access_mask, FILE_READ_DATA | FILE_EXECUTE,
1534 share_access, e_share_access, FILE_SHARE_READ);
1535 conflict |= mask_conflict(
1536 access_mask, e_access_mask, DELETE_ACCESS,
1537 share_access, e_share_access, FILE_SHARE_DELETE);
1539 DBG_DEBUG("conflict=%s\n", conflict ? "true" : "false");
1543 #if defined(DEVELOPER)
1545 struct validate_my_share_entries_state {
1546 struct smbd_server_connection *sconn;
1548 struct server_id self;
1551 static bool validate_my_share_entries_fn(
1552 struct share_mode_entry *e,
1556 struct validate_my_share_entries_state *state = private_data;
1559 if (!server_id_equal(&state->self, &e->pid)) {
1563 if (e->op_mid == 0) {
1564 /* INTERNAL_OPEN_ONLY */
1568 fsp = file_find_dif(state->sconn, state->fid, e->share_file_id);
1570 DBG_ERR("PANIC : %s\n",
1571 share_mode_str(talloc_tos(), 0, &state->fid, e));
1572 smb_panic("validate_my_share_entries: Cannot match a "
1573 "share entry with an open file\n");
1576 if (((uint16_t)fsp->oplock_type) != e->op_type) {
1585 DBG_ERR("validate_my_share_entries: PANIC : %s\n",
1586 share_mode_str(talloc_tos(), 0, &state->fid, e));
1587 str = talloc_asprintf(talloc_tos(),
1588 "validate_my_share_entries: "
1589 "file %s, oplock_type = 0x%x, op_type = 0x%x\n",
1590 fsp->fsp_name->base_name,
1591 (unsigned int)fsp->oplock_type,
1592 (unsigned int)e->op_type);
1601 * Allowed access mask for stat opens relevant to oplocks
1603 bool is_oplock_stat_open(uint32_t access_mask)
1605 const uint32_t stat_open_bits =
1606 (SYNCHRONIZE_ACCESS|
1607 FILE_READ_ATTRIBUTES|
1608 FILE_WRITE_ATTRIBUTES);
1610 return (((access_mask & stat_open_bits) != 0) &&
1611 ((access_mask & ~stat_open_bits) == 0));
1615 * Allowed access mask for stat opens relevant to leases
1617 bool is_lease_stat_open(uint32_t access_mask)
1619 const uint32_t stat_open_bits =
1620 (SYNCHRONIZE_ACCESS|
1621 FILE_READ_ATTRIBUTES|
1622 FILE_WRITE_ATTRIBUTES|
1623 READ_CONTROL_ACCESS);
1625 return (((access_mask & stat_open_bits) != 0) &&
1626 ((access_mask & ~stat_open_bits) == 0));
1629 struct has_delete_on_close_state {
1633 static bool has_delete_on_close_fn(
1634 struct share_mode_entry *e,
1638 struct has_delete_on_close_state *state = private_data;
1639 state->ret = !share_entry_stale_pid(e);
1643 static bool has_delete_on_close(struct share_mode_lock *lck,
1646 struct has_delete_on_close_state state = { .ret = false };
1649 if (!is_delete_on_close_set(lck, name_hash)) {
1653 ok= share_mode_forall_entries(lck, has_delete_on_close_fn, &state);
1655 DBG_DEBUG("share_mode_forall_entries failed\n");
1661 static void share_mode_flags_get(
1663 uint32_t *access_mask,
1664 uint32_t *share_mode,
1665 uint32_t *lease_type)
1667 if (access_mask != NULL) {
1669 ((flags & SHARE_MODE_ACCESS_READ) ?
1670 FILE_READ_DATA : 0) |
1671 ((flags & SHARE_MODE_ACCESS_WRITE) ?
1672 FILE_WRITE_DATA : 0) |
1673 ((flags & SHARE_MODE_ACCESS_DELETE) ?
1676 if (share_mode != NULL) {
1678 ((flags & SHARE_MODE_SHARE_READ) ?
1679 FILE_SHARE_READ : 0) |
1680 ((flags & SHARE_MODE_SHARE_WRITE) ?
1681 FILE_SHARE_WRITE : 0) |
1682 ((flags & SHARE_MODE_SHARE_DELETE) ?
1683 FILE_SHARE_DELETE : 0);
1685 if (lease_type != NULL) {
1687 ((flags & SHARE_MODE_LEASE_READ) ?
1688 SMB2_LEASE_READ : 0) |
1689 ((flags & SHARE_MODE_LEASE_WRITE) ?
1690 SMB2_LEASE_WRITE : 0) |
1691 ((flags & SHARE_MODE_LEASE_HANDLE) ?
1692 SMB2_LEASE_HANDLE : 0);
1696 static uint16_t share_mode_flags_set(
1698 uint32_t access_mask,
1699 uint32_t share_mode,
1700 uint32_t lease_type)
1702 if (access_mask != UINT32_MAX) {
1703 flags &= ~(SHARE_MODE_ACCESS_READ|
1704 SHARE_MODE_ACCESS_WRITE|
1705 SHARE_MODE_ACCESS_DELETE);
1706 flags |= (access_mask & (FILE_READ_DATA | FILE_EXECUTE)) ?
1707 SHARE_MODE_ACCESS_READ : 0;
1708 flags |= (access_mask & (FILE_WRITE_DATA | FILE_APPEND_DATA)) ?
1709 SHARE_MODE_ACCESS_WRITE : 0;
1710 flags |= (access_mask & (DELETE_ACCESS)) ?
1711 SHARE_MODE_ACCESS_DELETE : 0;
1713 if (share_mode != UINT32_MAX) {
1714 flags &= ~(SHARE_MODE_SHARE_READ|
1715 SHARE_MODE_SHARE_WRITE|
1716 SHARE_MODE_SHARE_DELETE);
1717 flags |= (share_mode & FILE_SHARE_READ) ?
1718 SHARE_MODE_SHARE_READ : 0;
1719 flags |= (share_mode & FILE_SHARE_WRITE) ?
1720 SHARE_MODE_SHARE_WRITE : 0;
1721 flags |= (share_mode & FILE_SHARE_DELETE) ?
1722 SHARE_MODE_SHARE_DELETE : 0;
1724 if (lease_type != UINT32_MAX) {
1725 flags &= ~(SHARE_MODE_LEASE_READ|
1726 SHARE_MODE_LEASE_WRITE|
1727 SHARE_MODE_LEASE_HANDLE);
1728 flags |= (lease_type & SMB2_LEASE_READ) ?
1729 SHARE_MODE_LEASE_READ : 0;
1730 flags |= (lease_type & SMB2_LEASE_WRITE) ?
1731 SHARE_MODE_LEASE_WRITE : 0;
1732 flags |= (lease_type & SMB2_LEASE_HANDLE) ?
1733 SHARE_MODE_LEASE_HANDLE : 0;
1739 static uint16_t share_mode_flags_restrict(
1741 uint32_t access_mask,
1742 uint32_t share_mode,
1743 uint32_t lease_type)
1745 uint32_t existing_access_mask, existing_share_mode;
1746 uint32_t existing_lease_type;
1749 share_mode_flags_get(
1751 &existing_access_mask,
1752 &existing_share_mode,
1753 &existing_lease_type);
1755 existing_access_mask |= access_mask;
1756 existing_share_mode &= share_mode;
1757 existing_lease_type |= lease_type;
1759 ret = share_mode_flags_set(
1761 existing_access_mask,
1762 existing_share_mode,
1763 existing_lease_type);
1767 /****************************************************************************
1768 Deal with share modes
1769 Invariant: Share mode must be locked on entry and exit.
1770 Returns -1 on error, or number of share modes on success (may be zero).
1771 ****************************************************************************/
1773 struct open_mode_check_state {
1775 uint32_t access_mask;
1776 uint32_t share_access;
1777 uint32_t lease_type;
1780 static bool open_mode_check_fn(
1781 struct share_mode_entry *e,
1785 struct open_mode_check_state *state = private_data;
1786 bool disconnected, stale;
1787 uint32_t access_mask, share_access, lease_type;
1789 disconnected = server_id_is_disconnected(&e->pid);
1794 access_mask = state->access_mask | e->access_mask;
1795 share_access = state->share_access & e->share_access;
1796 lease_type = state->lease_type | get_lease_type(e, state->fid);
1798 if ((access_mask == state->access_mask) &&
1799 (share_access == state->share_access) &&
1800 (lease_type == state->lease_type)) {
1804 stale = share_entry_stale_pid(e);
1809 state->access_mask = access_mask;
1810 state->share_access = share_access;
1811 state->lease_type = lease_type;
1816 static NTSTATUS open_mode_check(connection_struct *conn,
1817 struct share_mode_lock *lck,
1818 uint32_t access_mask,
1819 uint32_t share_access)
1821 struct share_mode_data *d = lck->data;
1822 struct open_mode_check_state state;
1824 bool ok, conflict, have_share_entries;
1826 if (is_oplock_stat_open(access_mask)) {
1827 /* Stat open that doesn't trigger oplock breaks or share mode
1828 * checks... ! JRA. */
1829 return NT_STATUS_OK;
1833 * Check if the share modes will give us access.
1836 #if defined(DEVELOPER)
1838 struct validate_my_share_entries_state validate_state = {
1839 .sconn = conn->sconn,
1841 .self = messaging_server_id(conn->sconn->msg_ctx),
1843 ok = share_mode_forall_entries(
1844 lck, validate_my_share_entries_fn, &validate_state);
1849 have_share_entries = share_mode_have_entries(lck);
1850 if (!have_share_entries) {
1852 * This is a fresh share mode lock where no conflicts
1855 return NT_STATUS_OK;
1858 share_mode_flags_get(
1859 d->flags, &state.access_mask, &state.share_access, NULL);
1861 conflict = share_conflict(
1867 DBG_DEBUG("No conflict due to share_mode_flags access\n");
1868 return NT_STATUS_OK;
1871 state = (struct open_mode_check_state) {
1873 .share_access = (FILE_SHARE_READ|
1879 * Walk the share mode array to recalculate d->flags
1882 ok = share_mode_forall_entries(lck, open_mode_check_fn, &state);
1884 DBG_DEBUG("share_mode_forall_entries failed\n");
1885 return NT_STATUS_INTERNAL_ERROR;
1888 new_flags = share_mode_flags_set(
1889 0, state.access_mask, state.share_access, state.lease_type);
1890 if (new_flags == d->flags) {
1892 * We only end up here if we had a sharing violation
1893 * from d->flags and have recalculated it.
1895 return NT_STATUS_SHARING_VIOLATION;
1898 d->flags = new_flags;
1901 conflict = share_conflict(
1907 DBG_DEBUG("No conflict due to share_mode_flags access\n");
1908 return NT_STATUS_OK;
1911 return NT_STATUS_SHARING_VIOLATION;
1915 * Send a break message to the oplock holder and delay the open for
1919 NTSTATUS send_break_message(struct messaging_context *msg_ctx,
1920 const struct file_id *id,
1921 const struct share_mode_entry *exclusive,
1924 struct oplock_break_message msg = {
1926 .share_file_id = exclusive->share_file_id,
1927 .break_to = break_to,
1929 enum ndr_err_code ndr_err;
1934 struct server_id_buf buf;
1935 DBG_DEBUG("Sending break message to %s\n",
1936 server_id_str_buf(exclusive->pid, &buf));
1937 NDR_PRINT_DEBUG(oplock_break_message, &msg);
1940 ndr_err = ndr_push_struct_blob(
1944 (ndr_push_flags_fn_t)ndr_push_oplock_break_message);
1945 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
1946 DBG_WARNING("ndr_push_oplock_break_message failed: %s\n",
1947 ndr_errstr(ndr_err));
1948 return ndr_map_error2ntstatus(ndr_err);
1951 status = messaging_send(
1952 msg_ctx, exclusive->pid, MSG_SMB_BREAK_REQUEST, &blob);
1953 TALLOC_FREE(blob.data);
1954 if (!NT_STATUS_IS_OK(status)) {
1955 DEBUG(3, ("Could not send oplock break message: %s\n",
1956 nt_errstr(status)));
1962 struct validate_oplock_types_state {
1968 uint32_t num_non_stat_opens;
1971 static bool validate_oplock_types_fn(
1972 struct share_mode_entry *e,
1976 struct validate_oplock_types_state *state = private_data;
1978 if (e->op_mid == 0) {
1979 /* INTERNAL_OPEN_ONLY */
1983 if (e->op_type == NO_OPLOCK && is_oplock_stat_open(e->access_mask)) {
1985 * We ignore stat opens in the table - they always
1986 * have NO_OPLOCK and never get or cause breaks. JRA.
1991 state->num_non_stat_opens += 1;
1993 if (BATCH_OPLOCK_TYPE(e->op_type)) {
1994 /* batch - can only be one. */
1995 if (share_entry_stale_pid(e)) {
1996 DBG_DEBUG("Found stale batch oplock\n");
1999 if (state->ex_or_batch ||
2003 DBG_ERR("Bad batch oplock entry\n");
2004 state->valid = false;
2007 state->batch = true;
2010 if (EXCLUSIVE_OPLOCK_TYPE(e->op_type)) {
2011 if (share_entry_stale_pid(e)) {
2012 DBG_DEBUG("Found stale duplicate oplock\n");
2015 /* Exclusive or batch - can only be one. */
2016 if (state->ex_or_batch ||
2019 DBG_ERR("Bad exclusive or batch oplock entry\n");
2020 state->valid = false;
2023 state->ex_or_batch = true;
2026 if (LEVEL_II_OPLOCK_TYPE(e->op_type)) {
2027 if (state->batch || state->ex_or_batch) {
2028 if (share_entry_stale_pid(e)) {
2029 DBG_DEBUG("Found stale LevelII oplock\n");
2032 DBG_DEBUG("Bad levelII oplock entry\n");
2033 state->valid = false;
2036 state->level2 = true;
2039 if (e->op_type == NO_OPLOCK) {
2040 if (state->batch || state->ex_or_batch) {
2041 if (share_entry_stale_pid(e)) {
2042 DBG_DEBUG("Found stale NO_OPLOCK entry\n");
2045 DBG_ERR("Bad no oplock entry\n");
2046 state->valid = false;
2049 state->no_oplock = true;
2056 * Do internal consistency checks on the share mode for a file.
2059 static bool validate_oplock_types(struct share_mode_lock *lck)
2061 struct validate_oplock_types_state state = { .valid = true };
2064 ok = share_mode_forall_entries(lck, validate_oplock_types_fn, &state);
2066 DBG_DEBUG("share_mode_forall_entries failed\n");
2070 DBG_DEBUG("Got invalid oplock configuration\n");
2074 if ((state.batch || state.ex_or_batch) &&
2075 (state.num_non_stat_opens != 1)) {
2076 DBG_WARNING("got batch (%d) or ex (%d) non-exclusively "
2079 (int)state.ex_or_batch,
2080 state.num_non_stat_opens);
2087 static bool is_same_lease(const files_struct *fsp,
2088 const struct share_mode_entry *e,
2089 const struct smb2_lease *lease)
2091 if (e->op_type != LEASE_OPLOCK) {
2094 if (lease == NULL) {
2098 return smb2_lease_equal(fsp_client_guid(fsp),
2104 static bool file_has_brlocks(files_struct *fsp)
2106 struct byte_range_lock *br_lck;
2108 br_lck = brl_get_locks_readonly(fsp);
2112 return (brl_num_locks(br_lck) > 0);
2115 struct fsp_lease *find_fsp_lease(struct files_struct *new_fsp,
2116 const struct smb2_lease_key *key,
2117 uint32_t current_state,
2118 uint16_t lease_version,
2119 uint16_t lease_epoch)
2121 struct files_struct *fsp;
2124 * TODO: Measure how expensive this loop is with thousands of open
2128 for (fsp = file_find_di_first(new_fsp->conn->sconn, new_fsp->file_id);
2130 fsp = file_find_di_next(fsp)) {
2132 if (fsp == new_fsp) {
2135 if (fsp->oplock_type != LEASE_OPLOCK) {
2138 if (smb2_lease_key_equal(&fsp->lease->lease.lease_key, key)) {
2139 fsp->lease->ref_count += 1;
2144 /* Not found - must be leased in another smbd. */
2145 new_fsp->lease = talloc_zero(new_fsp->conn->sconn, struct fsp_lease);
2146 if (new_fsp->lease == NULL) {
2149 new_fsp->lease->ref_count = 1;
2150 new_fsp->lease->sconn = new_fsp->conn->sconn;
2151 new_fsp->lease->lease.lease_key = *key;
2152 new_fsp->lease->lease.lease_state = current_state;
2154 * We internally treat all leases as V2 and update
2155 * the epoch, but when sending breaks it matters if
2156 * the requesting lease was v1 or v2.
2158 new_fsp->lease->lease.lease_version = lease_version;
2159 new_fsp->lease->lease.lease_epoch = lease_epoch;
2160 return new_fsp->lease;
2163 static NTSTATUS try_lease_upgrade(struct files_struct *fsp,
2164 struct share_mode_lock *lck,
2165 const struct GUID *client_guid,
2166 const struct smb2_lease *lease,
2170 uint32_t current_state, breaking_to_requested, breaking_to_required;
2172 uint16_t lease_version, epoch;
2173 uint32_t existing, requested;
2176 status = leases_db_get(
2182 &breaking_to_requested,
2183 &breaking_to_required,
2186 if (!NT_STATUS_IS_OK(status)) {
2190 fsp->lease = find_fsp_lease(
2196 if (fsp->lease == NULL) {
2197 DEBUG(1, ("Did not find existing lease for file %s\n",
2199 return NT_STATUS_NO_MEMORY;
2203 * Upgrade only if the requested lease is a strict upgrade.
2205 existing = current_state;
2206 requested = lease->lease_state;
2209 * Tricky: This test makes sure that "requested" is a
2210 * strict bitwise superset of "existing".
2212 do_upgrade = ((existing & requested) == existing);
2215 * Upgrade only if there's a change.
2217 do_upgrade &= (granted != existing);
2220 * Upgrade only if other leases don't prevent what was asked
2223 do_upgrade &= (granted == requested);
2226 * only upgrade if we are not in breaking state
2228 do_upgrade &= !breaking;
2230 DEBUG(10, ("existing=%"PRIu32", requested=%"PRIu32", "
2231 "granted=%"PRIu32", do_upgrade=%d\n",
2232 existing, requested, granted, (int)do_upgrade));
2235 NTSTATUS set_status;
2237 current_state = granted;
2240 set_status = leases_db_set(
2245 breaking_to_requested,
2246 breaking_to_required,
2250 if (!NT_STATUS_IS_OK(set_status)) {
2251 DBG_DEBUG("leases_db_set failed: %s\n",
2252 nt_errstr(set_status));
2257 fsp_lease_update(fsp);
2259 return NT_STATUS_OK;
2262 static NTSTATUS grant_new_fsp_lease(struct files_struct *fsp,
2263 struct share_mode_lock *lck,
2264 const struct GUID *client_guid,
2265 const struct smb2_lease *lease,
2268 struct share_mode_data *d = lck->data;
2271 fsp->lease = talloc_zero(fsp->conn->sconn, struct fsp_lease);
2272 if (fsp->lease == NULL) {
2273 return NT_STATUS_INSUFFICIENT_RESOURCES;
2275 fsp->lease->ref_count = 1;
2276 fsp->lease->sconn = fsp->conn->sconn;
2277 fsp->lease->lease.lease_version = lease->lease_version;
2278 fsp->lease->lease.lease_key = lease->lease_key;
2279 fsp->lease->lease.lease_state = granted;
2280 fsp->lease->lease.lease_epoch = lease->lease_epoch + 1;
2282 status = leases_db_add(client_guid,
2285 fsp->lease->lease.lease_state,
2286 fsp->lease->lease.lease_version,
2287 fsp->lease->lease.lease_epoch,
2288 fsp->conn->connectpath,
2289 fsp->fsp_name->base_name,
2290 fsp->fsp_name->stream_name);
2291 if (!NT_STATUS_IS_OK(status)) {
2292 DEBUG(10, ("%s: leases_db_add failed: %s\n", __func__,
2293 nt_errstr(status)));
2294 TALLOC_FREE(fsp->lease);
2295 return NT_STATUS_INSUFFICIENT_RESOURCES;
2300 return NT_STATUS_OK;
2303 static NTSTATUS grant_fsp_lease(struct files_struct *fsp,
2304 struct share_mode_lock *lck,
2305 const struct smb2_lease *lease,
2308 const struct GUID *client_guid = fsp_client_guid(fsp);
2311 status = try_lease_upgrade(fsp, lck, client_guid, lease, granted);
2313 if (NT_STATUS_EQUAL(status, NT_STATUS_NOT_FOUND)) {
2314 status = grant_new_fsp_lease(
2315 fsp, lck, client_guid, lease, granted);
2321 static int map_lease_type_to_oplock(uint32_t lease_type)
2323 int result = NO_OPLOCK;
2325 switch (lease_type) {
2326 case SMB2_LEASE_READ|SMB2_LEASE_WRITE|SMB2_LEASE_HANDLE:
2327 result = BATCH_OPLOCK|EXCLUSIVE_OPLOCK;
2329 case SMB2_LEASE_READ|SMB2_LEASE_WRITE:
2330 result = EXCLUSIVE_OPLOCK;
2332 case SMB2_LEASE_READ|SMB2_LEASE_HANDLE:
2333 case SMB2_LEASE_READ:
2334 result = LEVEL_II_OPLOCK;
2341 struct delay_for_oplock_state {
2342 struct files_struct *fsp;
2343 const struct smb2_lease *lease;
2344 bool will_overwrite;
2345 uint32_t delay_mask;
2346 bool first_open_attempt;
2347 bool got_handle_lease;
2349 bool have_other_lease;
2353 static bool delay_for_oplock_fn(
2354 struct share_mode_entry *e,
2358 struct delay_for_oplock_state *state = private_data;
2359 struct files_struct *fsp = state->fsp;
2360 const struct smb2_lease *lease = state->lease;
2361 bool e_is_lease = (e->op_type == LEASE_OPLOCK);
2362 uint32_t e_lease_type = get_lease_type(e, fsp->file_id);
2364 bool lease_is_breaking = false;
2369 if (lease != NULL) {
2370 bool our_lease = is_same_lease(fsp, e, lease);
2372 DBG_DEBUG("Ignoring our own lease\n");
2377 status = leases_db_get(
2381 NULL, /* current_state */
2383 NULL, /* breaking_to_requested */
2384 NULL, /* breaking_to_required */
2385 NULL, /* lease_version */
2387 SMB_ASSERT(NT_STATUS_IS_OK(status));
2390 if (!state->got_handle_lease &&
2391 ((e_lease_type & SMB2_LEASE_HANDLE) != 0) &&
2392 !share_entry_stale_pid(e)) {
2393 state->got_handle_lease = true;
2396 if (!state->got_oplock &&
2397 (e->op_type != LEASE_OPLOCK) &&
2398 !share_entry_stale_pid(e)) {
2399 state->got_oplock = true;
2402 if (!state->have_other_lease &&
2403 !is_same_lease(fsp, e, lease) &&
2404 !share_entry_stale_pid(e)) {
2405 state->have_other_lease = true;
2408 if (e_is_lease && is_lease_stat_open(fsp->access_mask)) {
2412 break_to = e_lease_type & ~state->delay_mask;
2414 if (state->will_overwrite) {
2415 break_to &= ~(SMB2_LEASE_HANDLE|SMB2_LEASE_READ);
2418 DBG_DEBUG("e_lease_type %u, will_overwrite: %u\n",
2419 (unsigned)e_lease_type,
2420 (unsigned)state->will_overwrite);
2422 if ((e_lease_type & ~break_to) == 0) {
2423 if (lease_is_breaking) {
2424 state->delay = true;
2429 if (share_entry_stale_pid(e)) {
2433 if (state->will_overwrite) {
2435 * If we break anyway break to NONE directly.
2436 * Otherwise vfs_set_filelen() will trigger the
2439 break_to &= ~(SMB2_LEASE_READ|SMB2_LEASE_WRITE);
2444 * Oplocks only support breaking to R or NONE.
2446 break_to &= ~(SMB2_LEASE_HANDLE|SMB2_LEASE_WRITE);
2449 DBG_DEBUG("breaking from %d to %d\n",
2453 fsp->conn->sconn->msg_ctx, &fsp->file_id, e, break_to);
2454 if (e_lease_type & state->delay_mask) {
2455 state->delay = true;
2457 if (lease_is_breaking && !state->first_open_attempt) {
2458 state->delay = true;
2464 static NTSTATUS delay_for_oplock(files_struct *fsp,
2466 const struct smb2_lease *lease,
2467 struct share_mode_lock *lck,
2468 bool have_sharing_violation,
2469 uint32_t create_disposition,
2470 bool first_open_attempt)
2472 struct delay_for_oplock_state state = {
2475 .first_open_attempt = first_open_attempt,
2481 if (is_oplock_stat_open(fsp->access_mask)) {
2485 state.delay_mask = have_sharing_violation ?
2486 SMB2_LEASE_HANDLE : SMB2_LEASE_WRITE;
2488 switch (create_disposition) {
2489 case FILE_SUPERSEDE:
2490 case FILE_OVERWRITE:
2491 case FILE_OVERWRITE_IF:
2492 state.will_overwrite = true;
2495 state.will_overwrite = false;
2499 ok = share_mode_forall_entries(lck, delay_for_oplock_fn, &state);
2501 return NT_STATUS_INTERNAL_ERROR;
2505 return NT_STATUS_RETRY;
2509 if (have_sharing_violation) {
2510 return NT_STATUS_SHARING_VIOLATION;
2513 if (oplock_request == LEASE_OPLOCK) {
2514 if (lease == NULL) {
2516 * The SMB2 layer should have checked this
2518 return NT_STATUS_INTERNAL_ERROR;
2521 granted = lease->lease_state;
2523 if (lp_kernel_oplocks(SNUM(fsp->conn))) {
2524 DEBUG(10, ("No lease granted because kernel oplocks are enabled\n"));
2525 granted = SMB2_LEASE_NONE;
2527 if ((granted & (SMB2_LEASE_READ|SMB2_LEASE_WRITE)) == 0) {
2528 DEBUG(10, ("No read or write lease requested\n"));
2529 granted = SMB2_LEASE_NONE;
2531 if (granted == SMB2_LEASE_WRITE) {
2532 DEBUG(10, ("pure write lease requested\n"));
2533 granted = SMB2_LEASE_NONE;
2535 if (granted == (SMB2_LEASE_WRITE|SMB2_LEASE_HANDLE)) {
2536 DEBUG(10, ("write and handle lease requested\n"));
2537 granted = SMB2_LEASE_NONE;
2540 granted = map_oplock_to_lease_type(
2541 oplock_request & ~SAMBA_PRIVATE_OPLOCK_MASK);
2544 if (lp_locking(fsp->conn->params) && file_has_brlocks(fsp)) {
2545 DBG_DEBUG("file %s has byte range locks\n",
2547 granted &= ~SMB2_LEASE_READ;
2550 if (state.have_other_lease) {
2552 * Can grant only one writer
2554 granted &= ~SMB2_LEASE_WRITE;
2557 if ((granted & SMB2_LEASE_READ) && !(granted & SMB2_LEASE_WRITE)) {
2559 (global_client_caps & CAP_LEVEL_II_OPLOCKS) &&
2560 lp_level2_oplocks(SNUM(fsp->conn));
2562 if (!allow_level2) {
2563 granted = SMB2_LEASE_NONE;
2567 if (oplock_request == LEASE_OPLOCK) {
2568 if (state.got_oplock) {
2569 granted &= ~SMB2_LEASE_HANDLE;
2572 fsp->oplock_type = LEASE_OPLOCK;
2574 status = grant_fsp_lease(fsp, lck, lease, granted);
2575 if (!NT_STATUS_IS_OK(status)) {
2580 DBG_DEBUG("lease_state=%d\n", fsp->lease->lease.lease_state);
2582 if (state.got_handle_lease) {
2583 granted = SMB2_LEASE_NONE;
2586 fsp->oplock_type = map_lease_type_to_oplock(granted);
2588 status = set_file_oplock(fsp);
2589 if (!NT_STATUS_IS_OK(status)) {
2591 * Could not get the kernel oplock
2593 fsp->oplock_type = NO_OPLOCK;
2597 if ((granted & SMB2_LEASE_READ) &&
2598 ((lck->data->flags & SHARE_MODE_LEASE_READ) == 0)) {
2599 lck->data->flags |= SHARE_MODE_LEASE_READ;
2600 lck->data->modified = true;
2603 DBG_DEBUG("oplock type 0x%x on file %s\n",
2604 fsp->oplock_type, fsp_str_dbg(fsp));
2606 return NT_STATUS_OK;
2609 static NTSTATUS handle_share_mode_lease(
2611 struct share_mode_lock *lck,
2612 uint32_t create_disposition,
2613 uint32_t access_mask,
2614 uint32_t share_access,
2616 const struct smb2_lease *lease,
2617 bool first_open_attempt)
2619 bool sharing_violation = false;
2622 status = open_mode_check(
2623 fsp->conn, lck, access_mask, share_access);
2624 if (NT_STATUS_EQUAL(status, NT_STATUS_SHARING_VIOLATION)) {
2625 sharing_violation = true;
2626 status = NT_STATUS_OK; /* handled later */
2629 if (!NT_STATUS_IS_OK(status)) {
2633 if (oplock_request == INTERNAL_OPEN_ONLY) {
2634 if (sharing_violation) {
2635 DBG_DEBUG("Sharing violation for internal open\n");
2636 return NT_STATUS_SHARING_VIOLATION;
2640 * Internal opens never do oplocks or leases. We don't
2641 * need to go through delay_for_oplock().
2643 fsp->oplock_type = NO_OPLOCK;
2645 return NT_STATUS_OK;
2648 status = delay_for_oplock(
2655 first_open_attempt);
2656 if (!NT_STATUS_IS_OK(status)) {
2660 return NT_STATUS_OK;
2663 static bool request_timed_out(struct smb_request *req, struct timeval timeout)
2665 struct timeval now, end_time;
2667 end_time = timeval_sum(&req->request_time, &timeout);
2668 return (timeval_compare(&end_time, &now) < 0);
2671 struct defer_open_state {
2672 struct smbXsrv_connection *xconn;
2676 static void defer_open_done(struct tevent_req *req);
2679 * Defer an open and watch a locking.tdb record
2681 * This defers an open that gets rescheduled once the locking.tdb record watch
2682 * is triggered by a change to the record.
2684 * It is used to defer opens that triggered an oplock break and for the SMB1
2685 * sharing violation delay.
2687 static void defer_open(struct share_mode_lock *lck,
2688 struct timeval timeout,
2689 struct smb_request *req,
2692 struct deferred_open_record *open_rec = NULL;
2693 struct timeval abs_timeout;
2694 struct defer_open_state *watch_state;
2695 struct tevent_req *watch_req;
2696 struct timeval_buf tvbuf1, tvbuf2;
2697 struct file_id_buf fbuf;
2700 abs_timeout = timeval_sum(&req->request_time, &timeout);
2702 DBG_DEBUG("request time [%s] timeout [%s] mid [%" PRIu64 "] "
2704 timeval_str_buf(&req->request_time, false, true, &tvbuf1),
2705 timeval_str_buf(&abs_timeout, false, true, &tvbuf2),
2707 file_id_str_buf(id, &fbuf));
2709 open_rec = talloc_zero(NULL, struct deferred_open_record);
2710 if (open_rec == NULL) {
2712 exit_server("talloc failed");
2715 watch_state = talloc(open_rec, struct defer_open_state);
2716 if (watch_state == NULL) {
2717 exit_server("talloc failed");
2719 watch_state->xconn = req->xconn;
2720 watch_state->mid = req->mid;
2722 DBG_DEBUG("defering mid %" PRIu64 "\n", req->mid);
2724 watch_req = share_mode_watch_send(
2728 (struct server_id){0});
2729 if (watch_req == NULL) {
2730 exit_server("Could not watch share mode record");
2732 tevent_req_set_callback(watch_req, defer_open_done, watch_state);
2734 ok = tevent_req_set_endtime(watch_req, req->sconn->ev_ctx, abs_timeout);
2736 exit_server("tevent_req_set_endtime failed");
2739 ok = push_deferred_open_message_smb(req, timeout, id, open_rec);
2742 exit_server("push_deferred_open_message_smb failed");
2746 static void defer_open_done(struct tevent_req *req)
2748 struct defer_open_state *state = tevent_req_callback_data(
2749 req, struct defer_open_state);
2753 status = share_mode_watch_recv(req, NULL, NULL);
2755 if (!NT_STATUS_IS_OK(status)) {
2756 DEBUG(5, ("dbwrap_watched_watch_recv returned %s\n",
2757 nt_errstr(status)));
2759 * Even if it failed, retry anyway. TODO: We need a way to
2760 * tell a re-scheduled open about that error.
2764 DEBUG(10, ("scheduling mid %llu\n", (unsigned long long)state->mid));
2766 ret = schedule_deferred_open_message_smb(state->xconn, state->mid);
2772 * Actually attempt the kernel oplock polling open.
2775 static void poll_open_fn(struct tevent_context *ev,
2776 struct tevent_timer *te,
2777 struct timeval current_time,
2780 struct deferred_open_record *open_rec = talloc_get_type_abort(
2781 private_data, struct deferred_open_record);
2784 TALLOC_FREE(open_rec->watch_req);
2786 ok = schedule_deferred_open_message_smb(
2787 open_rec->xconn, open_rec->mid);
2789 exit_server("schedule_deferred_open_message_smb failed");
2791 DBG_DEBUG("timer fired. Retrying open !\n");
2794 static void poll_open_done(struct tevent_req *subreq);
2797 * Reschedule an open for 1 second from now, if not timed out.
2799 static bool setup_poll_open(
2800 struct smb_request *req,
2801 struct share_mode_lock *lck,
2803 struct timeval max_timeout,
2804 struct timeval interval)
2807 struct deferred_open_record *open_rec = NULL;
2808 struct timeval endtime, next_interval;
2809 struct file_id_buf ftmp;
2811 if (request_timed_out(req, max_timeout)) {
2815 open_rec = talloc_zero(NULL, struct deferred_open_record);
2816 if (open_rec == NULL) {
2817 DBG_WARNING("talloc failed\n");
2820 open_rec->xconn = req->xconn;
2821 open_rec->mid = req->mid;
2824 * Make sure open_rec->te does not come later than the
2825 * request's maximum endtime.
2828 endtime = timeval_sum(&req->request_time, &max_timeout);
2829 next_interval = timeval_current_ofs(interval.tv_sec, interval.tv_usec);
2830 next_interval = timeval_min(&endtime, &next_interval);
2832 open_rec->te = tevent_add_timer(
2838 if (open_rec->te == NULL) {
2839 DBG_WARNING("tevent_add_timer failed\n");
2840 TALLOC_FREE(open_rec);
2845 open_rec->watch_req = share_mode_watch_send(
2849 (struct server_id) {0});
2850 if (open_rec->watch_req == NULL) {
2851 DBG_WARNING("share_mode_watch_send failed\n");
2852 TALLOC_FREE(open_rec);
2855 tevent_req_set_callback(
2856 open_rec->watch_req, poll_open_done, open_rec);
2859 ok = push_deferred_open_message_smb(req, max_timeout, id, open_rec);
2861 DBG_WARNING("push_deferred_open_message_smb failed\n");
2862 TALLOC_FREE(open_rec);
2866 DBG_DEBUG("poll request time [%s] mid [%" PRIu64 "] file_id [%s]\n",
2867 timeval_string(talloc_tos(), &req->request_time, false),
2869 file_id_str_buf(id, &ftmp));
2874 static void poll_open_done(struct tevent_req *subreq)
2876 struct deferred_open_record *open_rec = tevent_req_callback_data(
2877 subreq, struct deferred_open_record);
2881 status = share_mode_watch_recv(subreq, NULL, NULL);
2882 TALLOC_FREE(subreq);
2883 DBG_DEBUG("dbwrap_watched_watch_recv returned %s\n",
2886 ok = schedule_deferred_open_message_smb(
2887 open_rec->xconn, open_rec->mid);
2889 exit_server("schedule_deferred_open_message_smb failed");
2893 bool defer_smb1_sharing_violation(struct smb_request *req)
2898 if (!lp_defer_sharing_violations()) {
2903 * Try every 200msec up to (by default) one second. To be
2904 * precise, according to behaviour note <247> in [MS-CIFS],
2905 * the server tries 5 times. But up to one second should be
2909 timeout_usecs = lp_parm_int(
2913 SHARING_VIOLATION_USEC_WAIT);
2915 ok = setup_poll_open(
2918 (struct file_id) {0},
2919 (struct timeval) { .tv_usec = timeout_usecs },
2920 (struct timeval) { .tv_usec = 200000 });
2924 /****************************************************************************
2925 On overwrite open ensure that the attributes match.
2926 ****************************************************************************/
2928 static bool open_match_attributes(connection_struct *conn,
2929 uint32_t old_dos_attr,
2930 uint32_t new_dos_attr,
2931 mode_t new_unx_mode,
2932 mode_t *returned_unx_mode)
2934 uint32_t noarch_old_dos_attr, noarch_new_dos_attr;
2936 noarch_old_dos_attr = (old_dos_attr & ~FILE_ATTRIBUTE_ARCHIVE);
2937 noarch_new_dos_attr = (new_dos_attr & ~FILE_ATTRIBUTE_ARCHIVE);
2939 if((noarch_old_dos_attr == 0 && noarch_new_dos_attr != 0) ||
2940 (noarch_old_dos_attr != 0 && ((noarch_old_dos_attr & noarch_new_dos_attr) == noarch_old_dos_attr))) {
2941 *returned_unx_mode = new_unx_mode;
2943 *returned_unx_mode = (mode_t)0;
2946 DEBUG(10,("open_match_attributes: old_dos_attr = 0x%x, "
2947 "new_dos_attr = 0x%x "
2948 "returned_unx_mode = 0%o\n",
2949 (unsigned int)old_dos_attr,
2950 (unsigned int)new_dos_attr,
2951 (unsigned int)*returned_unx_mode ));
2953 /* If we're mapping SYSTEM and HIDDEN ensure they match. */
2954 if (lp_map_system(SNUM(conn)) || lp_store_dos_attributes(SNUM(conn))) {
2955 if ((old_dos_attr & FILE_ATTRIBUTE_SYSTEM) &&
2956 !(new_dos_attr & FILE_ATTRIBUTE_SYSTEM)) {
2960 if (lp_map_hidden(SNUM(conn)) || lp_store_dos_attributes(SNUM(conn))) {
2961 if ((old_dos_attr & FILE_ATTRIBUTE_HIDDEN) &&
2962 !(new_dos_attr & FILE_ATTRIBUTE_HIDDEN)) {
2969 static void schedule_defer_open(struct share_mode_lock *lck,
2971 struct smb_request *req)
2973 /* This is a relative time, added to the absolute
2974 request_time value to get the absolute timeout time.
2975 Note that if this is the second or greater time we enter
2976 this codepath for this particular request mid then
2977 request_time is left as the absolute time of the *first*
2978 time this request mid was processed. This is what allows
2979 the request to eventually time out. */
2981 struct timeval timeout;
2983 /* Normally the smbd we asked should respond within
2984 * OPLOCK_BREAK_TIMEOUT seconds regardless of whether
2985 * the client did, give twice the timeout as a safety
2986 * measure here in case the other smbd is stuck
2987 * somewhere else. */
2989 timeout = timeval_set(OPLOCK_BREAK_TIMEOUT*2, 0);
2991 if (request_timed_out(req, timeout)) {
2995 defer_open(lck, timeout, req, id);
2998 /****************************************************************************
2999 Reschedule an open call that went asynchronous.
3000 ****************************************************************************/
3002 static void schedule_async_open_timer(struct tevent_context *ev,
3003 struct tevent_timer *te,
3004 struct timeval current_time,
3007 exit_server("async open timeout");
3010 static void schedule_async_open(struct smb_request *req)
3012 struct deferred_open_record *open_rec = NULL;
3013 struct timeval timeout = timeval_set(20, 0);
3016 if (request_timed_out(req, timeout)) {
3020 open_rec = talloc_zero(NULL, struct deferred_open_record);
3021 if (open_rec == NULL) {
3022 exit_server("deferred_open_record_create failed");
3024 open_rec->async_open = true;
3026 ok = push_deferred_open_message_smb(
3027 req, timeout, (struct file_id){0}, open_rec);
3029 exit_server("push_deferred_open_message_smb failed");
3032 open_rec->te = tevent_add_timer(req->sconn->ev_ctx,
3034 timeval_current_ofs(20, 0),
3035 schedule_async_open_timer,
3037 if (open_rec->te == NULL) {
3038 exit_server("tevent_add_timer failed");
3042 /****************************************************************************
3043 Work out what access_mask to use from what the client sent us.
3044 ****************************************************************************/
3046 static NTSTATUS smbd_calculate_maximum_allowed_access(
3047 connection_struct *conn,
3048 struct files_struct *dirfsp,
3049 const struct smb_filename *smb_fname,
3051 uint32_t *p_access_mask)
3053 struct security_descriptor *sd;
3054 uint32_t access_granted;
3057 SMB_ASSERT(dirfsp == conn->cwd_fsp);
3059 if (!use_privs && (get_current_uid(conn) == (uid_t)0)) {
3060 *p_access_mask |= FILE_GENERIC_ALL;
3061 return NT_STATUS_OK;
3064 status = SMB_VFS_GET_NT_ACL(conn, smb_fname,
3070 if (NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
3072 * File did not exist
3074 *p_access_mask = FILE_GENERIC_ALL;
3075 return NT_STATUS_OK;
3077 if (!NT_STATUS_IS_OK(status)) {
3078 DEBUG(10,("Could not get acl on file %s: %s\n",
3079 smb_fname_str_dbg(smb_fname),
3080 nt_errstr(status)));
3081 return NT_STATUS_ACCESS_DENIED;
3085 * If we can access the path to this file, by
3086 * default we have FILE_READ_ATTRIBUTES from the
3087 * containing directory. See the section:
3088 * "Algorithm to Check Access to an Existing File"
3091 * se_file_access_check()
3092 * also takes care of owner WRITE_DAC and READ_CONTROL.
3094 status = se_file_access_check(sd,
3095 get_current_nttok(conn),
3097 (*p_access_mask & ~FILE_READ_ATTRIBUTES),
3102 if (!NT_STATUS_IS_OK(status)) {
3103 DEBUG(10, ("Access denied on file %s: "
3104 "when calculating maximum access\n",
3105 smb_fname_str_dbg(smb_fname)));
3106 return NT_STATUS_ACCESS_DENIED;
3108 *p_access_mask = (access_granted | FILE_READ_ATTRIBUTES);
3110 if (!(access_granted & DELETE_ACCESS)) {
3111 if (can_delete_file_in_directory(conn,
3115 *p_access_mask |= DELETE_ACCESS;
3119 return NT_STATUS_OK;
3122 NTSTATUS smbd_calculate_access_mask(connection_struct *conn,
3123 struct files_struct *dirfsp,
3124 const struct smb_filename *smb_fname,
3126 uint32_t access_mask,
3127 uint32_t *access_mask_out)
3130 uint32_t orig_access_mask = access_mask;
3131 uint32_t rejected_share_access;
3133 SMB_ASSERT(dirfsp == conn->cwd_fsp);
3135 if (access_mask & SEC_MASK_INVALID) {
3136 DBG_DEBUG("access_mask [%8x] contains invalid bits\n",
3138 return NT_STATUS_ACCESS_DENIED;
3142 * Convert GENERIC bits to specific bits.
3145 se_map_generic(&access_mask, &file_generic_mapping);
3147 /* Calculate MAXIMUM_ALLOWED_ACCESS if requested. */
3148 if (access_mask & MAXIMUM_ALLOWED_ACCESS) {
3150 status = smbd_calculate_maximum_allowed_access(conn,
3156 if (!NT_STATUS_IS_OK(status)) {
3160 access_mask &= conn->share_access;
3163 rejected_share_access = access_mask & ~(conn->share_access);
3165 if (rejected_share_access) {
3166 DEBUG(10, ("smbd_calculate_access_mask: Access denied on "
3167 "file %s: rejected by share access mask[0x%08X] "
3168 "orig[0x%08X] mapped[0x%08X] reject[0x%08X]\n",
3169 smb_fname_str_dbg(smb_fname),
3171 orig_access_mask, access_mask,
3172 rejected_share_access));
3173 return NT_STATUS_ACCESS_DENIED;
3176 *access_mask_out = access_mask;
3177 return NT_STATUS_OK;
3180 /****************************************************************************
3181 Remove the deferred open entry under lock.
3182 ****************************************************************************/
3184 /****************************************************************************
3185 Return true if this is a state pointer to an asynchronous create.
3186 ****************************************************************************/
3188 bool is_deferred_open_async(const struct deferred_open_record *rec)
3190 return rec->async_open;
3193 static bool clear_ads(uint32_t create_disposition)
3197 switch (create_disposition) {
3198 case FILE_SUPERSEDE:
3199 case FILE_OVERWRITE_IF:
3200 case FILE_OVERWRITE:
3209 static int disposition_to_open_flags(uint32_t create_disposition)
3214 * Currently we're using FILE_SUPERSEDE as the same as
3215 * FILE_OVERWRITE_IF but they really are
3216 * different. FILE_SUPERSEDE deletes an existing file
3217 * (requiring delete access) then recreates it.
3220 switch (create_disposition) {
3221 case FILE_SUPERSEDE:
3222 case FILE_OVERWRITE_IF:
3224 * If file exists replace/overwrite. If file doesn't
3227 ret = O_CREAT|O_TRUNC;
3232 * If file exists open. If file doesn't exist error.
3237 case FILE_OVERWRITE:
3239 * If file exists overwrite. If file doesn't exist
3247 * If file exists error. If file doesn't exist create.
3249 ret = O_CREAT|O_EXCL;
3254 * If file exists open. If file doesn't exist create.
3262 static int calculate_open_access_flags(uint32_t access_mask,
3263 uint32_t private_flags)
3265 bool need_write, need_read;
3268 * Note that we ignore the append flag as append does not
3269 * mean the same thing under DOS and Unix.
3272 need_write = (access_mask & (FILE_WRITE_DATA | FILE_APPEND_DATA));
3277 /* DENY_DOS opens are always underlying read-write on the
3278 file handle, no matter what the requested access mask
3282 ((private_flags & NTCREATEX_OPTIONS_PRIVATE_DENY_DOS) ||
3283 access_mask & (FILE_READ_ATTRIBUTES|FILE_READ_DATA|
3284 FILE_READ_EA|FILE_EXECUTE));
3292 /****************************************************************************
3293 Open a file with a share mode. Passed in an already created files_struct *.
3294 ****************************************************************************/
3296 static NTSTATUS open_file_ntcreate(connection_struct *conn,
3297 struct smb_request *req,
3298 uint32_t access_mask, /* access bits (FILE_READ_DATA etc.) */
3299 uint32_t share_access, /* share constants (FILE_SHARE_READ etc) */
3300 uint32_t create_disposition, /* FILE_OPEN_IF etc. */
3301 uint32_t create_options, /* options such as delete on close. */
3302 uint32_t new_dos_attributes, /* attributes used for new file. */
3303 int oplock_request, /* internal Samba oplock codes. */
3304 const struct smb2_lease *lease,
3305 /* Information (FILE_EXISTS etc.) */
3306 uint32_t private_flags, /* Samba specific flags. */
3310 struct smb_filename *smb_fname = fsp->fsp_name;
3313 bool file_existed = VALID_STAT(smb_fname->st);
3314 bool def_acl = False;
3315 bool posix_open = False;
3316 bool new_file_created = False;
3317 bool first_open_attempt = true;
3318 NTSTATUS fsp_open = NT_STATUS_ACCESS_DENIED;
3319 mode_t new_unx_mode = (mode_t)0;
3320 mode_t unx_mode = (mode_t)0;
3322 uint32_t existing_dos_attributes = 0;
3323 struct share_mode_lock *lck = NULL;
3324 uint32_t open_access_mask = access_mask;
3326 struct smb_filename *parent_dir_fname = NULL;
3327 SMB_STRUCT_STAT saved_stat = smb_fname->st;
3328 struct timespec old_write_time;
3330 bool setup_poll = false;
3333 if (conn->printer) {
3335 * Printers are handled completely differently.
3336 * Most of the passed parameters are ignored.
3340 *pinfo = FILE_WAS_CREATED;
3343 DEBUG(10, ("open_file_ntcreate: printer open fname=%s\n",
3344 smb_fname_str_dbg(smb_fname)));
3347 DEBUG(0,("open_file_ntcreate: printer open without "
3348 "an SMB request!\n"));
3349 return NT_STATUS_INTERNAL_ERROR;
3352 return print_spool_open(fsp, smb_fname->base_name,
3356 ok = parent_smb_fname(talloc_tos(),
3361 return NT_STATUS_NO_MEMORY;
3364 if (new_dos_attributes & FILE_FLAG_POSIX_SEMANTICS) {
3366 unx_mode = (mode_t)(new_dos_attributes & ~FILE_FLAG_POSIX_SEMANTICS);
3367 new_dos_attributes = 0;
3369 /* Windows allows a new file to be created and
3370 silently removes a FILE_ATTRIBUTE_DIRECTORY
3371 sent by the client. Do the same. */
3373 new_dos_attributes &= ~FILE_ATTRIBUTE_DIRECTORY;
3375 /* We add FILE_ATTRIBUTE_ARCHIVE to this as this mode is only used if the file is
3377 unx_mode = unix_mode(conn, new_dos_attributes | FILE_ATTRIBUTE_ARCHIVE,
3378 smb_fname, parent_dir_fname);
3381 DEBUG(10, ("open_file_ntcreate: fname=%s, dos_attrs=0x%x "
3382 "access_mask=0x%x share_access=0x%x "
3383 "create_disposition = 0x%x create_options=0x%x "
3384 "unix mode=0%o oplock_request=%d private_flags = 0x%x\n",
3385 smb_fname_str_dbg(smb_fname), new_dos_attributes,
3386 access_mask, share_access, create_disposition,
3387 create_options, (unsigned int)unx_mode, oplock_request,
3388 (unsigned int)private_flags));
3391 /* Ensure req == NULL means INTERNAL_OPEN_ONLY */
3392 SMB_ASSERT(oplock_request == INTERNAL_OPEN_ONLY);
3394 /* And req != NULL means no INTERNAL_OPEN_ONLY */
3395 SMB_ASSERT(((oplock_request & INTERNAL_OPEN_ONLY) == 0));
3399 * Only non-internal opens can be deferred at all
3403 struct deferred_open_record *open_rec;
3404 if (get_deferred_open_message_state(req, NULL, &open_rec)) {
3406 /* If it was an async create retry, the file
3409 if (is_deferred_open_async(open_rec)) {
3410 SET_STAT_INVALID(smb_fname->st);
3411 file_existed = false;
3414 /* Ensure we don't reprocess this message. */
3415 remove_deferred_open_message_smb(req->xconn, req->mid);
3417 first_open_attempt = false;
3422 new_dos_attributes &= SAMBA_ATTRIBUTES_MASK;
3425 * Only use stored DOS attributes for checks
3426 * against requested attributes (below via
3427 * open_match_attributes()), cf bug #11992
3428 * for details. -slow
3432 status = SMB_VFS_GET_DOS_ATTRIBUTES(conn, smb_fname, &attr);
3433 if (NT_STATUS_IS_OK(status)) {
3434 existing_dos_attributes = attr;
3439 /* ignore any oplock requests if oplocks are disabled */
3440 if (!lp_oplocks(SNUM(conn)) ||
3441 IS_VETO_OPLOCK_PATH(conn, smb_fname->base_name)) {
3442 /* Mask off everything except the private Samba bits. */
3443 oplock_request &= SAMBA_PRIVATE_OPLOCK_MASK;
3446 /* this is for OS/2 long file names - say we don't support them */
3447 if (req != NULL && !req->posix_pathnames &&
3448 strstr(smb_fname->base_name,".+,;=[].")) {
3449 /* OS/2 Workplace shell fix may be main code stream in a later
3451 DEBUG(5,("open_file_ntcreate: OS/2 long filenames are not "
3453 if (use_nt_status()) {
3454 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3456 return NT_STATUS_DOS(ERRDOS, ERRcannotopen);
3459 switch( create_disposition ) {
3461 /* If file exists open. If file doesn't exist error. */
3462 if (!file_existed) {
3463 DEBUG(5,("open_file_ntcreate: FILE_OPEN "
3464 "requested for file %s and file "
3466 smb_fname_str_dbg(smb_fname)));
3468 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3472 case FILE_OVERWRITE:
3473 /* If file exists overwrite. If file doesn't exist
3475 if (!file_existed) {
3476 DEBUG(5,("open_file_ntcreate: FILE_OVERWRITE "
3477 "requested for file %s and file "
3479 smb_fname_str_dbg(smb_fname) ));
3481 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3486 /* If file exists error. If file doesn't exist
3489 DEBUG(5,("open_file_ntcreate: FILE_CREATE "
3490 "requested for file %s and file "
3491 "already exists.\n",
3492 smb_fname_str_dbg(smb_fname)));
3493 if (S_ISDIR(smb_fname->st.st_ex_mode)) {
3498 return map_nt_error_from_unix(errno);
3502 case FILE_SUPERSEDE:
3503 case FILE_OVERWRITE_IF:
3507 return NT_STATUS_INVALID_PARAMETER;
3510 flags2 = disposition_to_open_flags(create_disposition);
3512 /* We only care about matching attributes on file exists and
3515 if (!posix_open && file_existed &&
3516 ((create_disposition == FILE_OVERWRITE) ||
3517 (create_disposition == FILE_OVERWRITE_IF))) {
3518 if (!open_match_attributes(conn, existing_dos_attributes,
3520 unx_mode, &new_unx_mode)) {
3521 DEBUG(5,("open_file_ntcreate: attributes mismatch "
3522 "for file %s (%x %x) (0%o, 0%o)\n",
3523 smb_fname_str_dbg(smb_fname),
3524 existing_dos_attributes,
3526 (unsigned int)smb_fname->st.st_ex_mode,
3527 (unsigned int)unx_mode ));
3529 return NT_STATUS_ACCESS_DENIED;
3533 status = smbd_calculate_access_mask(conn,
3539 if (!NT_STATUS_IS_OK(status)) {
3540 DEBUG(10, ("open_file_ntcreate: smbd_calculate_access_mask "
3541 "on file %s returned %s\n",
3542 smb_fname_str_dbg(smb_fname), nt_errstr(status)));
3546 open_access_mask = access_mask;
3548 if (flags2 & O_TRUNC) {
3549 open_access_mask |= FILE_WRITE_DATA; /* This will cause oplock breaks. */
3554 * stat opens on existing files don't get oplocks.
3555 * They can get leases.
3557 * Note that we check for stat open on the *open_access_mask*,
3558 * i.e. the access mask we actually used to do the open,
3559 * not the one the client asked for (which is in
3560 * fsp->access_mask). This is due to the fact that
3561 * FILE_OVERWRITE and FILE_OVERWRITE_IF add in O_TRUNC,
3562 * which adds FILE_WRITE_DATA to open_access_mask.
3564 if (is_oplock_stat_open(open_access_mask) && lease == NULL) {
3565 oplock_request = NO_OPLOCK;
3569 DEBUG(10, ("open_file_ntcreate: fname=%s, after mapping "
3570 "access_mask=0x%x\n", smb_fname_str_dbg(smb_fname),
3574 * Note that we ignore the append flag as append does not
3575 * mean the same thing under DOS and Unix.
3578 flags = calculate_open_access_flags(access_mask, private_flags);
3581 * Currently we only look at FILE_WRITE_THROUGH for create options.
3585 if ((create_options & FILE_WRITE_THROUGH) && lp_strict_sync(SNUM(conn))) {
3590 if (posix_open && (access_mask & FILE_APPEND_DATA)) {
3594 if (!posix_open && !CAN_WRITE(conn)) {
3596 * We should really return a permission denied error if either
3597 * O_CREAT or O_TRUNC are set, but for compatibility with
3598 * older versions of Samba we just AND them out.
3600 flags2 &= ~(O_CREAT|O_TRUNC);
3604 * With kernel oplocks the open breaking an oplock
3605 * blocks until the oplock holder has given up the
3606 * oplock or closed the file. We prevent this by always
3607 * trying to open the file with O_NONBLOCK (see "man
3610 * If a process that doesn't use the smbd open files
3611 * database or communication methods holds a kernel
3612 * oplock we must periodically poll for available open
3615 flags2 |= O_NONBLOCK;
3618 * Ensure we can't write on a read-only share or file.
3621 if (flags != O_RDONLY && file_existed &&
3622 (!CAN_WRITE(conn) || IS_DOS_READONLY(existing_dos_attributes))) {
3623 DEBUG(5,("open_file_ntcreate: write access requested for "
3624 "file %s on read only %s\n",
3625 smb_fname_str_dbg(smb_fname),
3626 !CAN_WRITE(conn) ? "share" : "file" ));
3628 return NT_STATUS_ACCESS_DENIED;
3631 if (VALID_STAT(smb_fname->st)) {
3633 * Only try and create a file id before open
3634 * for an existing file. For a file being created
3635 * this won't do anything useful until the file
3636 * exists and has a valid stat struct.
3638 fsp->file_id = vfs_file_id_from_sbuf(conn, &smb_fname->st);
3640 fsp->fh->private_options = private_flags;
3641 fsp->access_mask = open_access_mask; /* We change this to the
3642 * requested access_mask after
3643 * the open is done. */
3645 fsp->posix_flags |= FSP_POSIX_FLAGS_ALL;
3648 if ((create_options & FILE_DELETE_ON_CLOSE) &&
3649 (flags2 & O_CREAT) &&
3651 /* Delete on close semantics for new files. */
3652 status = can_set_delete_on_close(fsp,
3653 new_dos_attributes);
3654 if (!NT_STATUS_IS_OK(status)) {
3661 * Ensure we pay attention to default ACLs on directories if required.
3664 if ((flags2 & O_CREAT) && lp_inherit_acls(SNUM(conn)) &&
3665 (def_acl = directory_has_default_acl(conn,
3669 unx_mode = (0777 & lp_create_mask(SNUM(conn)));
3672 DEBUG(4,("calling open_file with flags=0x%X flags2=0x%X mode=0%o, "
3673 "access_mask = 0x%x, open_access_mask = 0x%x\n",
3674 (unsigned int)flags, (unsigned int)flags2,
3675 (unsigned int)unx_mode, (unsigned int)access_mask,
3676 (unsigned int)open_access_mask));
3678 fsp_open = open_file(fsp, conn, req, parent_dir_fname,
3679 flags|flags2, unx_mode, access_mask,
3680 open_access_mask, &new_file_created);
3682 if (NT_STATUS_EQUAL(fsp_open, NT_STATUS_NETWORK_BUSY)) {
3683 if (file_existed && S_ISFIFO(fsp->fsp_name->st.st_ex_mode)) {
3684 DEBUG(10, ("FIFO busy\n"));
3685 return NT_STATUS_NETWORK_BUSY;
3688 DEBUG(10, ("Internal open busy\n"));
3689 return NT_STATUS_NETWORK_BUSY;
3692 * This handles the kernel oplock case:
3694 * the file has an active kernel oplock and the open() returned
3695 * EWOULDBLOCK/EAGAIN which maps to NETWORK_BUSY.
3697 * "Samba locking.tdb oplocks" are handled below after acquiring
3698 * the sharemode lock with get_share_mode_lock().
3703 if (NT_STATUS_EQUAL(fsp_open, NT_STATUS_RETRY)) {
3705 * EINTR from the open(2) syscall. Just setup a retry
3706 * in a bit. We can't use the sys_write() tight retry
3707 * loop here, as we might have to actually deal with
3708 * lease-break signals to avoid a deadlock.
3715 * From here on we assume this is an oplock break triggered
3718 lck = get_existing_share_mode_lock(talloc_tos(), fsp->file_id);
3720 if ((lck != NULL) && !validate_oplock_types(lck)) {
3721 smb_panic("validate_oplock_types failed");
3725 * Retry once a second. If there's a share_mode_lock
3726 * around, also wait for it in case it was smbd
3727 * holding that kernel oplock that can quickly tell us
3728 * the oplock got removed.
3735 timeval_set(OPLOCK_BREAK_TIMEOUT*2, 0),
3740 return NT_STATUS_SHARING_VIOLATION;
3743 if (!NT_STATUS_IS_OK(fsp_open)) {
3744 bool wait_for_aio = NT_STATUS_EQUAL(
3745 fsp_open, NT_STATUS_MORE_PROCESSING_REQUIRED);
3747 schedule_async_open(req);
3752 if (new_file_created) {
3754 * As we atomically create using O_CREAT|O_EXCL,
3755 * then if new_file_created is true, then
3756 * file_existed *MUST* have been false (even
3757 * if the file was previously detected as being
3760 file_existed = false;
3763 if (file_existed && !check_same_dev_ino(&saved_stat, &smb_fname->st)) {
3765 * The file did exist, but some other (local or NFS)
3766 * process either renamed/unlinked and re-created the
3767 * file with different dev/ino after we walked the path,
3768 * but before we did the open. We could retry the
3769 * open but it's a rare enough case it's easier to
3770 * just fail the open to prevent creating any problems
3771 * in the open file db having the wrong dev/ino key.
3774 DBG_WARNING("file %s - dev/ino mismatch. "
3775 "Old (dev=%ju, ino=%ju). "
3776 "New (dev=%ju, ino=%ju). Failing open "
3777 "with NT_STATUS_ACCESS_DENIED.\n",
3778 smb_fname_str_dbg(smb_fname),
3779 (uintmax_t)saved_stat.st_ex_dev,
3780 (uintmax_t)saved_stat.st_ex_ino,
3781 (uintmax_t)smb_fname->st.st_ex_dev,
3782 (uintmax_t)smb_fname->st.st_ex_ino);
3783 return NT_STATUS_ACCESS_DENIED;
3786 old_write_time = smb_fname->st.st_ex_mtime;
3789 * Deal with the race condition where two smbd's detect the
3790 * file doesn't exist and do the create at the same time. One
3791 * of them will win and set a share mode, the other (ie. this
3792 * one) should check if the requested share mode for this
3793 * create is allowed.
3797 * Now the file exists and fsp is successfully opened,
3798 * fsp->dev and fsp->inode are valid and should replace the
3799 * dev=0,inode=0 from a non existent file. Spotted by
3800 * Nadav Danieli <nadavd@exanet.com>. JRA.
3805 lck = get_share_mode_lock(talloc_tos(), id,
3807 smb_fname, &old_write_time);
3810 DEBUG(0, ("open_file_ntcreate: Could not get share "
3811 "mode lock for %s\n",
3812 smb_fname_str_dbg(smb_fname)));
3814 return NT_STATUS_SHARING_VIOLATION;
3817 /* Get the types we need to examine. */
3818 if (!validate_oplock_types(lck)) {
3819 smb_panic("validate_oplock_types failed");
3822 if (has_delete_on_close(lck, fsp->name_hash)) {
3825 return NT_STATUS_DELETE_PENDING;
3828 status = handle_share_mode_lease(
3836 first_open_attempt);
3838 if (NT_STATUS_EQUAL(status, NT_STATUS_RETRY)) {
3839 schedule_defer_open(lck, fsp->file_id, req);
3842 return NT_STATUS_SHARING_VIOLATION;
3845 if (!NT_STATUS_IS_OK(status)) {
3852 struct share_mode_data *d = lck->data;
3853 uint16_t new_flags = share_mode_flags_restrict(
3854 d->flags, access_mask, share_access, UINT32_MAX);
3856 if (new_flags != d->flags) {
3857 d->flags = new_flags;
3862 ok = set_share_mode(
3865 get_current_uid(fsp->conn),
3871 if (fsp->oplock_type == LEASE_OPLOCK) {
3872 status = remove_lease_if_stale(
3874 fsp_client_guid(fsp),
3875 &fsp->lease->lease.lease_key);
3876 if (!NT_STATUS_IS_OK(status)) {
3877 DBG_WARNING("remove_lease_if_stale "
3882 return NT_STATUS_NO_MEMORY;
3885 /* Should we atomically (to the client at least) truncate ? */
3886 if ((!new_file_created) &&
3887 (flags2 & O_TRUNC) &&
3888 (S_ISREG(fsp->fsp_name->st.st_ex_mode))) {
3891 ret = SMB_VFS_FTRUNCATE(fsp, 0);
3893 status = map_nt_error_from_unix(errno);
3894 del_share_mode(lck, fsp);
3899 notify_fname(fsp->conn, NOTIFY_ACTION_MODIFIED,
3900 FILE_NOTIFY_CHANGE_SIZE
3901 | FILE_NOTIFY_CHANGE_ATTRIBUTES,
3902 fsp->fsp_name->base_name);
3906 * We have the share entry *locked*.....
3909 /* Delete streams if create_disposition requires it */
3910 if (!new_file_created && clear_ads(create_disposition) &&
3911 !is_ntfs_stream_smb_fname(smb_fname)) {
3912 status = delete_all_streams(conn, smb_fname);
3913 if (!NT_STATUS_IS_OK(status)) {
3914 del_share_mode(lck, fsp);
3921 if (fsp->fh->fd != -1 && lp_kernel_share_modes(SNUM(conn))) {
3924 * Beware: streams implementing VFS modules may
3925 * implement streams in a way that fsp will have the
3926 * basefile open in the fsp fd, so lacking a distinct
3927 * fd for the stream kernel_flock will apply on the
3928 * basefile which is wrong. The actual check is
3929 * deferred to the VFS module implementing the
3930 * kernel_flock call.
3932 ret_flock = SMB_VFS_KERNEL_FLOCK(fsp, share_access, access_mask);
3933 if(ret_flock == -1 ){
3935 del_share_mode(lck, fsp);
3939 return NT_STATUS_SHARING_VIOLATION;
3942 fsp->fsp_flags.kernel_share_modes_taken = true;
3946 * At this point onwards, we can guarantee that the share entry
3947 * is locked, whether we created the file or not, and that the
3948 * deny mode is compatible with all current opens.
3952 * According to Samba4, SEC_FILE_READ_ATTRIBUTE is always granted,
3953 * but we don't have to store this - just ignore it on access check.
3955 if (conn->sconn->using_smb2) {
3957 * SMB2 doesn't return it (according to Microsoft tests).
3958 * Test Case: TestSuite_ScenarioNo009GrantedAccessTestS0
3959 * File created with access = 0x7 (Read, Write, Delete)
3960 * Query Info on file returns 0x87 (Read, Write, Delete, Read Attributes)
3962 fsp->access_mask = access_mask;
3964 /* But SMB1 does. */
3965 fsp->access_mask = access_mask | FILE_READ_ATTRIBUTES;
3968 if (new_file_created) {
3969 info = FILE_WAS_CREATED;
3971 if (flags2 & O_TRUNC) {
3972 info = FILE_WAS_OVERWRITTEN;
3974 info = FILE_WAS_OPENED;
3982 /* Handle strange delete on close create semantics. */
3983 if (create_options & FILE_DELETE_ON_CLOSE) {
3984 if (!new_file_created) {
3985 status = can_set_delete_on_close(fsp,
3986 existing_dos_attributes);
3988 if (!NT_STATUS_IS_OK(status)) {
3989 /* Remember to delete the mode we just added. */
3990 del_share_mode(lck, fsp);
3996 /* Note that here we set the *initial* delete on close flag,
3997 not the regular one. The magic gets handled in close. */
3998 fsp->fsp_flags.initial_delete_on_close = true;
4002 * If we created a file and it's not a stream, this is the point where
4003 * we set the itime (aka invented time) that get's stored in the DOS
4004 * attribute xattr. The value is going to be either what the filesystem
4005 * provided or a copy of the creation date.
4007 * Either way, we turn the itime into a File-ID, unless the filesystem
4008 * provided one (unlikely).
4010 if (info == FILE_WAS_CREATED && !is_named_stream(smb_fname)) {
4011 smb_fname->st.st_ex_iflags &= ~ST_EX_IFLAG_CALCULATED_ITIME;
4013 if (lp_store_dos_attributes(SNUM(conn)) &&
4014 smb_fname->st.st_ex_iflags & ST_EX_IFLAG_CALCULATED_FILE_ID)
4018 file_id = make_file_id_from_itime(&smb_fname->st);
4019 update_stat_ex_file_id(&smb_fname->st, file_id);
4023 if (info != FILE_WAS_OPENED) {
4024 /* Overwritten files should be initially set as archive */
4025 if ((info == FILE_WAS_OVERWRITTEN && lp_map_archive(SNUM(conn))) ||
4026 lp_store_dos_attributes(SNUM(conn))) {
4027 (void)dos_mode(conn, smb_fname);
4029 if (file_set_dosmode(conn, smb_fname,
4030 new_dos_attributes | FILE_ATTRIBUTE_ARCHIVE,
4031 parent_dir_fname, true) == 0) {
4032 unx_mode = smb_fname->st.st_ex_mode;
4038 /* Determine sparse flag. */
4040 /* POSIX opens are sparse by default. */
4041 fsp->fsp_flags.is_sparse = true;
4043 fsp->fsp_flags.is_sparse =
4044 (existing_dos_attributes & FILE_ATTRIBUTE_SPARSE);
4048 * Take care of inherited ACLs on created files - if default ACL not
4052 if (!posix_open && new_file_created && !def_acl) {
4053 if (unx_mode != smb_fname->st.st_ex_mode) {
4054 int ret = SMB_VFS_FCHMOD(fsp, unx_mode);
4056 DBG_INFO("failed to reset "
4057 "attributes of file %s to 0%o\n",
4058 smb_fname_str_dbg(smb_fname),
4059 (unsigned int)unx_mode);
4063 } else if (new_unx_mode) {
4065 * We only get here in the case of:
4067 * a). Not a POSIX open.
4068 * b). File already existed.
4069 * c). File was overwritten.
4070 * d). Requested DOS attributes didn't match
4071 * the DOS attributes on the existing file.
4073 * In that case new_unx_mode has been set
4074 * equal to the calculated mode (including
4075 * possible inheritance of the mode from the
4076 * containing directory).
4078 * Note this mode was calculated with the
4079 * DOS attribute FILE_ATTRIBUTE_ARCHIVE added,
4080 * so the mode change here is suitable for
4081 * an overwritten file.
4084 if (new_unx_mode != smb_fname->st.st_ex_mode) {
4085 int ret = SMB_VFS_FCHMOD(fsp, new_unx_mode);
4087 DBG_INFO("failed to reset "
4088 "attributes of file %s to 0%o\n",
4089 smb_fname_str_dbg(smb_fname),
4090 (unsigned int)new_unx_mode);
4097 * Deal with other opens having a modified write time.
4099 struct timespec write_time = get_share_mode_write_time(lck);
4101 if (!is_omit_timespec(&write_time)) {
4102 update_stat_ex_mtime(&fsp->fsp_name->st, write_time);
4108 return NT_STATUS_OK;
4111 static NTSTATUS mkdir_internal(connection_struct *conn,
4112 struct smb_filename *smb_dname,
4113 uint32_t file_attributes)
4115 const struct loadparm_substitution *lp_sub =
4116 loadparm_s3_global_substitution();
4118 struct smb_filename *parent_dir_fname = NULL;
4120 bool posix_open = false;
4121 bool need_re_stat = false;
4122 uint32_t access_mask = SEC_DIR_ADD_SUBDIR;
4126 if (!CAN_WRITE(conn) || (access_mask & ~(conn->share_access))) {
4127 DEBUG(5,("mkdir_internal: failing share access "
4128 "%s\n", lp_servicename(talloc_tos(), lp_sub, SNUM(conn))));
4129 return NT_STATUS_ACCESS_DENIED;
4132 ok = parent_smb_fname(talloc_tos(),
4137 return NT_STATUS_NO_MEMORY;
4140 if (file_attributes & FILE_FLAG_POSIX_SEMANTICS) {
4142 mode = (mode_t)(file_attributes & ~FILE_FLAG_POSIX_SEMANTICS);
4144 mode = unix_mode(conn,
4145 FILE_ATTRIBUTE_DIRECTORY,
4150 status = check_parent_access(conn,
4154 if(!NT_STATUS_IS_OK(status)) {
4155 DEBUG(5,("mkdir_internal: check_parent_access "
4156 "on directory %s for path %s returned %s\n",
4157 smb_fname_str_dbg(parent_dir_fname),
4158 smb_dname->base_name,
4159 nt_errstr(status) ));
4163 ret = SMB_VFS_MKDIRAT(conn,
4168 return map_nt_error_from_unix(errno);
4171 /* Ensure we're checking for a symlink here.... */
4172 /* We don't want to get caught by a symlink racer. */
4174 if (SMB_VFS_LSTAT(conn, smb_dname) == -1) {
4175 DEBUG(2, ("Could not stat directory '%s' just created: %s\n",
4176 smb_fname_str_dbg(smb_dname), strerror(errno)));
4177 return map_nt_error_from_unix(errno);
4180 if (!S_ISDIR(smb_dname->st.st_ex_mode)) {
4181 DEBUG(0, ("Directory '%s' just created is not a directory !\n",
4182 smb_fname_str_dbg(smb_dname)));
4183 return NT_STATUS_NOT_A_DIRECTORY;
4186 smb_dname->st.st_ex_iflags &= ~ST_EX_IFLAG_CALCULATED_ITIME;
4188 if (lp_store_dos_attributes(SNUM(conn))) {
4189 if (smb_dname->st.st_ex_iflags & ST_EX_IFLAG_CALCULATED_FILE_ID)
4193 file_id = make_file_id_from_itime(&smb_dname->st);
4194 update_stat_ex_file_id(&smb_dname->st, file_id);
4198 file_set_dosmode(conn, smb_dname,
4199 file_attributes | FILE_ATTRIBUTE_DIRECTORY,
4200 parent_dir_fname, true);
4204 if (lp_inherit_permissions(SNUM(conn))) {
4205 inherit_access_posix_acl(conn, parent_dir_fname,
4207 need_re_stat = true;
4212 * Check if high bits should have been set,
4213 * then (if bits are missing): add them.
4214 * Consider bits automagically set by UNIX, i.e. SGID bit from parent
4217 if ((mode & ~(S_IRWXU|S_IRWXG|S_IRWXO)) &&
4218 (mode & ~smb_dname->st.st_ex_mode)) {
4219 SMB_VFS_CHMOD(conn, smb_dname,
4220 (smb_dname->st.st_ex_mode |
4221 (mode & ~smb_dname->st.st_ex_mode)));
4222 need_re_stat = true;
4226 /* Change the owner if required. */
4227 if (lp_inherit_owner(SNUM(conn)) != INHERIT_OWNER_NO) {
4228 change_dir_owner_to_parent(conn, parent_dir_fname,
4231 need_re_stat = true;
4235 if (SMB_VFS_LSTAT(conn, smb_dname) == -1) {
4236 DEBUG(2, ("Could not stat directory '%s' just created: %s\n",
4237 smb_fname_str_dbg(smb_dname), strerror(errno)));
4238 return map_nt_error_from_unix(errno);
4242 notify_fname(conn, NOTIFY_ACTION_ADDED, FILE_NOTIFY_CHANGE_DIR_NAME,
4243 smb_dname->base_name);
4245 return NT_STATUS_OK;
4248 /****************************************************************************
4249 Open a directory from an NT SMB call.
4250 ****************************************************************************/
4252 static NTSTATUS open_directory(connection_struct *conn,
4253 struct smb_request *req,
4254 struct smb_filename *smb_dname,
4255 uint32_t access_mask,
4256 uint32_t share_access,
4257 uint32_t create_disposition,
4258 uint32_t create_options,
4259 uint32_t file_attributes,
4261 files_struct **result)
4263 files_struct *fsp = NULL;
4264 bool dir_existed = VALID_STAT(smb_dname->st);
4265 struct share_mode_lock *lck = NULL;
4267 struct timespec mtimespec;
4271 if (is_ntfs_stream_smb_fname(smb_dname)) {
4272 DEBUG(2, ("open_directory: %s is a stream name!\n",
4273 smb_fname_str_dbg(smb_dname)));
4274 return NT_STATUS_NOT_A_DIRECTORY;
4277 if (!(file_attributes & FILE_FLAG_POSIX_SEMANTICS)) {
4278 /* Ensure we have a directory attribute. */
4279 file_attributes |= FILE_ATTRIBUTE_DIRECTORY;
4282 DBG_INFO("opening directory %s, access_mask = 0x%"PRIx32", "
4283 "share_access = 0x%"PRIx32" create_options = 0x%"PRIx32", "
4284 "create_disposition = 0x%"PRIx32", "
4285 "file_attributes = 0x%"PRIx32"\n",
4286 smb_fname_str_dbg(smb_dname),
4293 status = smbd_calculate_access_mask(conn,
4299 if (!NT_STATUS_IS_OK(status)) {
4300 DEBUG(10, ("open_directory: smbd_calculate_access_mask "
4301 "on file %s returned %s\n",
4302 smb_fname_str_dbg(smb_dname),
4303 nt_errstr(status)));
4307 if ((access_mask & SEC_FLAG_SYSTEM_SECURITY) &&
4308 !security_token_has_privilege(get_current_nttok(conn),
4309 SEC_PRIV_SECURITY)) {
4310 DEBUG(10, ("open_directory: open on %s "
4311 "failed - SEC_FLAG_SYSTEM_SECURITY denied.\n",
4312 smb_fname_str_dbg(smb_dname)));
4313 return NT_STATUS_PRIVILEGE_NOT_HELD;
4316 switch( create_disposition ) {
4320 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
4323 info = FILE_WAS_OPENED;
4328 /* If directory exists error. If directory doesn't
4332 status = NT_STATUS_OBJECT_NAME_COLLISION;
4333 DEBUG(2, ("open_directory: unable to create "
4334 "%s. Error was %s\n",
4335 smb_fname_str_dbg(smb_dname),
4336 nt_errstr(status)));
4340 status = mkdir_internal(conn, smb_dname,
4343 if (!NT_STATUS_IS_OK(status)) {
4344 DEBUG(2, ("open_directory: unable to create "
4345 "%s. Error was %s\n",
4346 smb_fname_str_dbg(smb_dname),
4347 nt_errstr(status)));
4351 info = FILE_WAS_CREATED;
4356 * If directory exists open. If directory doesn't
4361 status = NT_STATUS_OK;
4362 info = FILE_WAS_OPENED;
4364 status = mkdir_internal(conn, smb_dname,
4367 if (NT_STATUS_IS_OK(status)) {
4368 info = FILE_WAS_CREATED;
4370 /* Cope with create race. */
4371 if (!NT_STATUS_EQUAL(status,
4372 NT_STATUS_OBJECT_NAME_COLLISION)) {
4373 DEBUG(2, ("open_directory: unable to create "
4374 "%s. Error was %s\n",
4375 smb_fname_str_dbg(smb_dname),
4376 nt_errstr(status)));
4381 * If mkdir_internal() returned
4382 * NT_STATUS_OBJECT_NAME_COLLISION
4383 * we still must lstat the path.
4386 if (SMB_VFS_LSTAT(conn, smb_dname)
4388 DEBUG(2, ("Could not stat "
4389 "directory '%s' just "
4394 return map_nt_error_from_unix(
4398 info = FILE_WAS_OPENED;
4404 case FILE_SUPERSEDE:
4405 case FILE_OVERWRITE:
4406 case FILE_OVERWRITE_IF:
4408 DEBUG(5,("open_directory: invalid create_disposition "
4409 "0x%x for directory %s\n",
4410 (unsigned int)create_disposition,
4411 smb_fname_str_dbg(smb_dname)));
4412 return NT_STATUS_INVALID_PARAMETER;
4415 if(!S_ISDIR(smb_dname->st.st_ex_mode)) {
4416 DEBUG(5,("open_directory: %s is not a directory !\n",
4417 smb_fname_str_dbg(smb_dname)));
4418 return NT_STATUS_NOT_A_DIRECTORY;
4421 if (info == FILE_WAS_OPENED) {
4422 status = smbd_check_access_rights(conn,
4427 if (!NT_STATUS_IS_OK(status)) {
4428 DEBUG(10, ("open_directory: smbd_check_access_rights on "
4429 "file %s failed with %s\n",
4430 smb_fname_str_dbg(smb_dname),
4431 nt_errstr(status)));
4436 status = file_new(req, conn, &fsp);
4437 if(!NT_STATUS_IS_OK(status)) {
4442 * Setup the files_struct for it.
4445 fsp->file_id = vfs_file_id_from_sbuf(conn, &smb_dname->st);
4446 fsp->vuid = req ? req->vuid : UID_FIELD_INVALID;
4447 fsp->file_pid = req ? req->smbpid : 0;
4448 fsp->fsp_flags.can_lock = false;
4449 fsp->fsp_flags.can_read = false;
4450 fsp->fsp_flags.can_write = false;
4452 fsp->fh->private_options = 0;
4454 * According to Samba4, SEC_FILE_READ_ATTRIBUTE is always granted,
4456 fsp->access_mask = access_mask | FILE_READ_ATTRIBUTES;
4457 fsp->print_file = NULL;
4458 fsp->fsp_flags.modified = false;
4459 fsp->oplock_type = NO_OPLOCK;
4460 fsp->sent_oplock_break = NO_BREAK_SENT;
4461 fsp->fsp_flags.is_directory = true;
4462 if (file_attributes & FILE_FLAG_POSIX_SEMANTICS) {
4463 fsp->posix_flags |= FSP_POSIX_FLAGS_ALL;
4465 status = fsp_set_smb_fname(fsp, smb_dname);
4466 if (!NT_STATUS_IS_OK(status)) {
4467 file_free(req, fsp);
4471 /* Don't store old timestamps for directory
4472 handles in the internal database. We don't
4473 update them in there if new objects
4474 are created in the directory. Currently
4475 we only update timestamps on file writes.
4478 mtimespec = make_omit_timespec();
4481 status = fd_open(conn, fsp, O_RDONLY|O_DIRECTORY, 0);
4483 /* POSIX allows us to open a directory with O_RDONLY. */
4484 status = fd_open(conn, fsp, O_RDONLY, 0);
4486 if (!NT_STATUS_IS_OK(status)) {
4487 DBG_INFO("Could not open fd for "
4489 smb_fname_str_dbg(smb_dname),
4491 file_free(req, fsp);
4495 status = vfs_stat_fsp(fsp);
4496 if (!NT_STATUS_IS_OK(status)) {
4498 file_free(req, fsp);
4502 if(!S_ISDIR(fsp->fsp_name->st.st_ex_mode)) {
4503 DEBUG(5,("open_directory: %s is not a directory !\n",
4504 smb_fname_str_dbg(smb_dname)));
4506 file_free(req, fsp);
4507 return NT_STATUS_NOT_A_DIRECTORY;
4510 /* Ensure there was no race condition. We need to check
4511 * dev/inode but not permissions, as these can change
4513 if (!check_same_dev_ino(&smb_dname->st, &fsp->fsp_name->st)) {
4514 DEBUG(5,("open_directory: stat struct differs for "
4516 smb_fname_str_dbg(smb_dname)));
4518 file_free(req, fsp);
4519 return NT_STATUS_ACCESS_DENIED;
4522 lck = get_share_mode_lock(talloc_tos(), fsp->file_id,
4523 conn->connectpath, smb_dname,
4527 DEBUG(0, ("open_directory: Could not get share mode lock for "
4528 "%s\n", smb_fname_str_dbg(smb_dname)));
4530 file_free(req, fsp);
4531 return NT_STATUS_SHARING_VIOLATION;
4534 if (has_delete_on_close(lck, fsp->name_hash)) {
4537 file_free(req, fsp);
4538 return NT_STATUS_DELETE_PENDING;
4541 status = open_mode_check(conn, lck,
4542 access_mask, share_access);
4544 if (!NT_STATUS_IS_OK(status)) {
4547 file_free(req, fsp);
4552 struct share_mode_data *d = lck->data;
4553 uint16_t new_flags = share_mode_flags_restrict(
4554 d->flags, access_mask, share_access, UINT32_MAX);
4556 if (new_flags != d->flags) {
4557 d->flags = new_flags;
4562 ok = set_share_mode(
4565 get_current_uid(conn),
4573 file_free(req, fsp);
4574 return NT_STATUS_NO_MEMORY;
4577 /* For directories the delete on close bit at open time seems
4578 always to be honored on close... See test 19 in Samba4 BASE-DELETE. */
4579 if (create_options & FILE_DELETE_ON_CLOSE) {
4580 status = can_set_delete_on_close(fsp, 0);
4581 if (!NT_STATUS_IS_OK(status) && !NT_STATUS_EQUAL(status, NT_STATUS_DIRECTORY_NOT_EMPTY)) {
4582 del_share_mode(lck, fsp);
4585 file_free(req, fsp);
4589 if (NT_STATUS_IS_OK(status)) {
4590 /* Note that here we set the *initial* delete on close flag,
4591 not the regular one. The magic gets handled in close. */
4592 fsp->fsp_flags.initial_delete_on_close = true;
4598 * Deal with other opens having a modified write time. Is this
4599 * possible for directories?
4601 struct timespec write_time = get_share_mode_write_time(lck);
4603 if (!is_omit_timespec(&write_time)) {
4604 update_stat_ex_mtime(&fsp->fsp_name->st, write_time);
4615 return NT_STATUS_OK;
4618 NTSTATUS create_directory(connection_struct *conn, struct smb_request *req,
4619 struct smb_filename *smb_dname)
4624 status = SMB_VFS_CREATE_FILE(
4627 0, /* root_dir_fid */
4628 smb_dname, /* fname */
4629 FILE_READ_ATTRIBUTES, /* access_mask */
4630 FILE_SHARE_NONE, /* share_access */
4631 FILE_CREATE, /* create_disposition*/
4632 FILE_DIRECTORY_FILE, /* create_options */
4633 FILE_ATTRIBUTE_DIRECTORY, /* file_attributes */
4634 0, /* oplock_request */
4636 0, /* allocation_size */
4637 0, /* private_flags */
4642 NULL, NULL); /* create context */
4644 if (NT_STATUS_IS_OK(status)) {
4645 close_file(req, fsp, NORMAL_CLOSE);
4651 /****************************************************************************
4652 Receive notification that one of our open files has been renamed by another
4654 ****************************************************************************/
4656 void msg_file_was_renamed(struct messaging_context *msg_ctx,
4659 struct server_id src,
4662 struct file_rename_message *msg = NULL;
4663 enum ndr_err_code ndr_err;
4665 struct smb_filename *smb_fname = NULL;
4666 struct smbd_server_connection *sconn =
4667 talloc_get_type_abort(private_data,
4668 struct smbd_server_connection);
4670 msg = talloc(talloc_tos(), struct file_rename_message);
4672 DBG_WARNING("talloc failed\n");
4676 ndr_err = ndr_pull_struct_blob_all(
4680 (ndr_pull_flags_fn_t)ndr_pull_file_rename_message);
4681 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
4682 DBG_DEBUG("ndr_pull_oplock_break_message failed: %s\n",
4683 ndr_errstr(ndr_err));
4686 if (DEBUGLEVEL >= 10) {
4687 struct server_id_buf buf;
4688 DBG_DEBUG("Got rename message from %s\n",
4689 server_id_str_buf(src, &buf));
4690 NDR_PRINT_DEBUG(file_rename_message, msg);
4693 /* stream_name must always be NULL if there is no stream. */
4694 if ((msg->stream_name != NULL) && (msg->stream_name[0] == '\0')) {
4695 msg->stream_name = NULL;
4698 smb_fname = synthetic_smb_fname(msg,
4704 if (smb_fname == NULL) {
4705 DBG_DEBUG("synthetic_smb_fname failed\n");
4709 fsp = file_find_dif(sconn, msg->id, msg->share_file_id);
4711 DBG_DEBUG("fsp not found\n");
4715 if (strcmp(fsp->conn->connectpath, msg->servicepath) == 0) {
4717 DBG_DEBUG("renaming file %s from %s -> %s\n",
4720 smb_fname_str_dbg(smb_fname));
4721 status = fsp_set_smb_fname(fsp, smb_fname);
4722 if (!NT_STATUS_IS_OK(status)) {
4723 DBG_DEBUG("fsp_set_smb_fname failed: %s\n",
4729 * Now we have the complete path we can work out if
4730 * this is actually within this share and adjust
4731 * newname accordingly.
4733 DBG_DEBUG("share mismatch (sharepath %s not sharepath %s) "
4734 "%s from %s -> %s\n",
4735 fsp->conn->connectpath,
4739 smb_fname_str_dbg(smb_fname));
4746 * If a main file is opened for delete, all streams need to be checked for
4747 * !FILE_SHARE_DELETE. Do this by opening with DELETE_ACCESS.
4748 * If that works, delete them all by setting the delete on close and close.
4751 static NTSTATUS open_streams_for_delete(connection_struct *conn,
4752 const struct smb_filename *smb_fname)
4754 struct stream_struct *stream_info = NULL;
4755 files_struct **streams = NULL;
4757 unsigned int i, num_streams = 0;
4758 TALLOC_CTX *frame = talloc_stackframe();
4761 status = vfs_streaminfo(conn, NULL, smb_fname, talloc_tos(),
4762 &num_streams, &stream_info);
4764 if (NT_STATUS_EQUAL(status, NT_STATUS_NOT_IMPLEMENTED)
4765 || NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
4766 DEBUG(10, ("no streams around\n"));
4768 return NT_STATUS_OK;
4771 if (!NT_STATUS_IS_OK(status)) {
4772 DEBUG(10, ("vfs_streaminfo failed: %s\n",
4773 nt_errstr(status)));
4777 DEBUG(10, ("open_streams_for_delete found %d streams\n",
4780 if (num_streams == 0) {
4782 return NT_STATUS_OK;
4785 streams = talloc_array(talloc_tos(), files_struct *, num_streams);
4786 if (streams == NULL) {
4787 DEBUG(0, ("talloc failed\n"));
4788 status = NT_STATUS_NO_MEMORY;
4792 for (i=0; i<num_streams; i++) {
4793 struct smb_filename *smb_fname_cp;
4795 if (strequal(stream_info[i].name, "::$DATA")) {
4800 smb_fname_cp = synthetic_smb_fname(talloc_tos(),
4801 smb_fname->base_name,
4802 stream_info[i].name,
4806 ~SMB_FILENAME_POSIX_PATH));
4807 if (smb_fname_cp == NULL) {
4808 status = NT_STATUS_NO_MEMORY;
4812 if (SMB_VFS_STAT(conn, smb_fname_cp) == -1) {
4813 DEBUG(10, ("Unable to stat stream: %s\n",
4814 smb_fname_str_dbg(smb_fname_cp)));
4817 status = SMB_VFS_CREATE_FILE(
4820 0, /* root_dir_fid */
4821 smb_fname_cp, /* fname */
4822 DELETE_ACCESS, /* access_mask */
4823 (FILE_SHARE_READ | /* share_access */
4824 FILE_SHARE_WRITE | FILE_SHARE_DELETE),
4825 FILE_OPEN, /* create_disposition*/
4826 0, /* create_options */
4827 FILE_ATTRIBUTE_NORMAL, /* file_attributes */
4828 0, /* oplock_request */
4830 0, /* allocation_size */
4831 NTCREATEX_OPTIONS_PRIVATE_STREAM_DELETE, /* private_flags */
4834 &streams[i], /* result */
4836 NULL, NULL); /* create context */
4838 if (!NT_STATUS_IS_OK(status)) {
4839 DEBUG(10, ("Could not open stream %s: %s\n",
4840 smb_fname_str_dbg(smb_fname_cp),
4841 nt_errstr(status)));
4843 TALLOC_FREE(smb_fname_cp);
4846 TALLOC_FREE(smb_fname_cp);
4850 * don't touch the variable "status" beyond this point :-)
4853 for (j = i-1 ; j >= 0; j--) {
4854 if (streams[j] == NULL) {
4858 DEBUG(10, ("Closing stream # %d, %s\n", j,
4859 fsp_str_dbg(streams[j])));
4860 close_file(NULL, streams[j], NORMAL_CLOSE);
4868 /*********************************************************************
4869 Create a default ACL by inheriting from the parent. If no inheritance
4870 from the parent available, don't set anything. This will leave the actual
4871 permissions the new file or directory already got from the filesystem
4872 as the NT ACL when read.
4873 *********************************************************************/
4875 static NTSTATUS inherit_new_acl(files_struct *fsp)
4877 TALLOC_CTX *frame = talloc_stackframe();
4878 struct security_descriptor *parent_desc = NULL;
4879 NTSTATUS status = NT_STATUS_OK;
4880 struct security_descriptor *psd = NULL;
4881 const struct dom_sid *owner_sid = NULL;
4882 const struct dom_sid *group_sid = NULL;
4883 uint32_t security_info_sent = (SECINFO_OWNER | SECINFO_GROUP | SECINFO_DACL);
4884 struct security_token *token = fsp->conn->session_info->security_token;
4885 bool inherit_owner =
4886 (lp_inherit_owner(SNUM(fsp->conn)) == INHERIT_OWNER_WINDOWS_AND_UNIX);
4887 bool inheritable_components = false;
4888 bool try_builtin_administrators = false;
4889 const struct dom_sid *BA_U_sid = NULL;
4890 const struct dom_sid *BA_G_sid = NULL;
4891 bool try_system = false;
4892 const struct dom_sid *SY_U_sid = NULL;
4893 const struct dom_sid *SY_G_sid = NULL;
4895 struct smb_filename *parent_dir = NULL;
4898 ok = parent_smb_fname(frame,
4904 return NT_STATUS_NO_MEMORY;
4907 status = SMB_VFS_GET_NT_ACL(fsp->conn,
4909 (SECINFO_OWNER | SECINFO_GROUP | SECINFO_DACL),
4912 if (!NT_STATUS_IS_OK(status)) {
4917 inheritable_components = sd_has_inheritable_components(parent_desc,
4918 fsp->fsp_flags.is_directory);
4920 if (!inheritable_components && !inherit_owner) {
4922 /* Nothing to inherit and not setting owner. */
4923 return NT_STATUS_OK;
4926 /* Create an inherited descriptor from the parent. */
4928 if (DEBUGLEVEL >= 10) {
4929 DEBUG(10,("inherit_new_acl: parent acl for %s is:\n",
4930 fsp_str_dbg(fsp) ));
4931 NDR_PRINT_DEBUG(security_descriptor, parent_desc);
4934 /* Inherit from parent descriptor if "inherit owner" set. */
4935 if (inherit_owner) {
4936 owner_sid = parent_desc->owner_sid;
4937 group_sid = parent_desc->group_sid;
4940 if (owner_sid == NULL) {
4941 if (security_token_has_builtin_administrators(token)) {
4942 try_builtin_administrators = true;
4943 } else if (security_token_is_system(token)) {
4944 try_builtin_administrators = true;
4949 if (group_sid == NULL &&
4950 token->num_sids == PRIMARY_GROUP_SID_INDEX)
4952 if (security_token_is_system(token)) {
4953 try_builtin_administrators = true;
4958 if (try_builtin_administrators) {
4962 ok = sids_to_unixids(&global_sid_Builtin_Administrators, 1, &ids);
4966 BA_U_sid = &global_sid_Builtin_Administrators;
4967 BA_G_sid = &global_sid_Builtin_Administrators;
4970 BA_U_sid = &global_sid_Builtin_Administrators;
4973 BA_G_sid = &global_sid_Builtin_Administrators;
4985 ok = sids_to_unixids(&global_sid_System, 1, &ids);
4989 SY_U_sid = &global_sid_System;
4990 SY_G_sid = &global_sid_System;
4993 SY_U_sid = &global_sid_System;
4996 SY_G_sid = &global_sid_System;
5004 if (owner_sid == NULL) {
5005 owner_sid = BA_U_sid;
5008 if (owner_sid == NULL) {
5009 owner_sid = SY_U_sid;
5012 if (group_sid == NULL) {
5013 group_sid = SY_G_sid;
5016 if (try_system && group_sid == NULL) {
5017 group_sid = BA_G_sid;
5020 if (owner_sid == NULL) {
5021 owner_sid = &token->sids[PRIMARY_USER_SID_INDEX];
5023 if (group_sid == NULL) {
5024 if (token->num_sids == PRIMARY_GROUP_SID_INDEX) {
5025 group_sid = &token->sids[PRIMARY_USER_SID_INDEX];
5027 group_sid = &token->sids[PRIMARY_GROUP_SID_INDEX];
5031 status = se_create_child_secdesc(frame,
5037 fsp->fsp_flags.is_directory);
5038 if (!NT_STATUS_IS_OK(status)) {
5043 /* If inheritable_components == false,
5044 se_create_child_secdesc()
5045 creates a security descriptor with a NULL dacl
5046 entry, but with SEC_DESC_DACL_PRESENT. We need
5047 to remove that flag. */
5049 if (!inheritable_components) {
5050 security_info_sent &= ~SECINFO_DACL;
5051 psd->type &= ~SEC_DESC_DACL_PRESENT;
5054 if (DEBUGLEVEL >= 10) {
5055 DEBUG(10,("inherit_new_acl: child acl for %s is:\n",
5056 fsp_str_dbg(fsp) ));
5057 NDR_PRINT_DEBUG(security_descriptor, psd);
5060 if (inherit_owner) {
5061 /* We need to be root to force this. */
5064 status = SMB_VFS_FSET_NT_ACL(fsp,
5067 if (inherit_owner) {
5075 * If we already have a lease, it must match the new file id. [MS-SMB2]
5076 * 3.3.5.9.8 speaks about INVALID_PARAMETER if an already used lease key is
5077 * used for a different file name.
5080 struct lease_match_state {
5081 /* Input parameters. */
5082 TALLOC_CTX *mem_ctx;
5083 const char *servicepath;
5084 const struct smb_filename *fname;
5087 /* Return parameters. */
5088 uint32_t num_file_ids;
5089 struct file_id *ids;
5090 NTSTATUS match_status;
5093 /*************************************************************
5094 File doesn't exist but this lease key+guid is already in use.
5096 This is only allowable in the dynamic share case where the
5097 service path must be different.
5099 There is a small race condition here in the multi-connection
5100 case where a client sends two create calls on different connections,
5101 where the file doesn't exist and one smbd creates the leases_db
5102 entry first, but this will get fixed by the multichannel cleanup
5103 when all identical client_guids get handled by a single smbd.
5104 **************************************************************/
5106 static void lease_match_parser_new_file(
5108 const struct leases_db_file *files,
5109 struct lease_match_state *state)
5113 for (i = 0; i < num_files; i++) {
5114 const struct leases_db_file *f = &files[i];
5115 if (strequal(state->servicepath, f->servicepath)) {
5116 state->match_status = NT_STATUS_INVALID_PARAMETER;
5121 /* Dynamic share case. Break leases on all other files. */
5122 state->match_status = leases_db_copy_file_ids(state->mem_ctx,
5126 if (!NT_STATUS_IS_OK(state->match_status)) {
5130 state->num_file_ids = num_files;
5131 state->match_status = NT_STATUS_OPLOCK_NOT_GRANTED;
5135 static void lease_match_parser(
5137 const struct leases_db_file *files,
5140 struct lease_match_state *state =
5141 (struct lease_match_state *)private_data;
5144 if (!state->file_existed) {
5146 * Deal with name mismatch or
5147 * possible dynamic share case separately
5148 * to make code clearer.
5150 lease_match_parser_new_file(num_files,
5157 state->match_status = NT_STATUS_OK;
5159 for (i = 0; i < num_files; i++) {
5160 const struct leases_db_file *f = &files[i];
5162 /* Everything should be the same. */
5163 if (!file_id_equal(&state->id, &f->id)) {
5164 /* This should catch all dynamic share cases. */
5165 state->match_status = NT_STATUS_OPLOCK_NOT_GRANTED;
5168 if (!strequal(f->servicepath, state->servicepath)) {
5169 state->match_status = NT_STATUS_INVALID_PARAMETER;
5172 if (!strequal(f->base_name, state->fname->base_name)) {
5173 state->match_status = NT_STATUS_INVALID_PARAMETER;
5176 if (!strequal(f->stream_name, state->fname->stream_name)) {
5177 state->match_status = NT_STATUS_INVALID_PARAMETER;
5182 if (NT_STATUS_IS_OK(state->match_status)) {
5184 * Common case - just opening another handle on a
5185 * file on a non-dynamic share.
5190 if (NT_STATUS_EQUAL(state->match_status, NT_STATUS_INVALID_PARAMETER)) {
5191 /* Mismatched path. Error back to client. */
5196 * File id mismatch. Dynamic share case NT_STATUS_OPLOCK_NOT_GRANTED.
5197 * Don't allow leases.
5200 state->match_status = leases_db_copy_file_ids(state->mem_ctx,
5204 if (!NT_STATUS_IS_OK(state->match_status)) {
5208 state->num_file_ids = num_files;
5209 state->match_status = NT_STATUS_OPLOCK_NOT_GRANTED;
5213 struct lease_match_break_state {
5214 struct messaging_context *msg_ctx;
5215 const struct smb2_lease_key *lease_key;
5223 static bool lease_match_break_fn(
5224 struct share_mode_entry *e,
5227 struct lease_match_break_state *state = private_data;
5229 uint32_t e_lease_type;
5232 stale = share_entry_stale_pid(e);
5237 equal = smb2_lease_key_equal(&e->lease_key, state->lease_key);
5242 status = leases_db_get(
5246 NULL, /* current_state */
5247 NULL, /* breaking */
5248 NULL, /* breaking_to_requested */
5249 NULL, /* breaking_to_required */
5250 &state->version, /* lease_version */
5251 &state->epoch); /* epoch */
5252 if (NT_STATUS_IS_OK(status)) {
5253 state->found_lease = true;
5255 DBG_WARNING("Could not find version/epoch: %s\n",
5259 e_lease_type = get_lease_type(e, state->id);
5260 if (e_lease_type == SMB2_LEASE_NONE) {
5263 send_break_message(state->msg_ctx, &state->id, e, SMB2_LEASE_NONE);
5266 * Windows 7 and 8 lease clients are broken in that they will
5267 * not respond to lease break requests whilst waiting for an
5268 * outstanding open request on that lease handle on the same
5269 * TCP connection, due to holding an internal inode lock.
5271 * This means we can't reschedule ourselves here, but must
5272 * return from the create.
5276 * Send the breaks and then return SMB2_LEASE_NONE in the
5277 * lease handle to cause them to acknowledge the lease
5278 * break. Consultation with Microsoft engineering confirmed
5279 * this approach is safe.
5285 static NTSTATUS lease_match(connection_struct *conn,
5286 struct smb_request *req,
5287 const struct smb2_lease_key *lease_key,
5288 const char *servicepath,
5289 const struct smb_filename *fname,
5290 uint16_t *p_version,
5293 struct smbd_server_connection *sconn = req->sconn;
5294 TALLOC_CTX *tos = talloc_tos();
5295 struct lease_match_state state = {
5297 .servicepath = servicepath,
5299 .match_status = NT_STATUS_OK
5304 state.file_existed = VALID_STAT(fname->st);
5305 if (state.file_existed) {
5306 state.id = vfs_file_id_from_sbuf(conn, &fname->st);
5309 status = leases_db_parse(&sconn->client->connections->smb2.client.guid,
5310 lease_key, lease_match_parser, &state);
5311 if (!NT_STATUS_IS_OK(status)) {
5313 * Not found or error means okay: We can make the lease pass
5315 return NT_STATUS_OK;
5317 if (!NT_STATUS_EQUAL(state.match_status, NT_STATUS_OPLOCK_NOT_GRANTED)) {
5319 * Anything but NT_STATUS_OPLOCK_NOT_GRANTED, let the caller
5322 return state.match_status;
5325 /* We have to break all existing leases. */
5326 for (i = 0; i < state.num_file_ids; i++) {
5327 struct lease_match_break_state break_state = {
5328 .msg_ctx = conn->sconn->msg_ctx,
5329 .lease_key = lease_key,
5331 struct share_mode_lock *lck;
5334 if (file_id_equal(&state.ids[i], &state.id)) {
5335 /* Don't need to break our own file. */
5339 break_state.id = state.ids[i];
5341 lck = get_existing_share_mode_lock(
5342 talloc_tos(), break_state.id);
5344 /* Race condition - file already closed. */
5348 ok = share_mode_forall_leases(
5349 lck, lease_match_break_fn, &break_state);
5351 DBG_DEBUG("share_mode_forall_leases failed\n");
5357 if (break_state.found_lease) {
5358 *p_version = break_state.version;
5359 *p_epoch = break_state.epoch;
5363 * Ensure we don't grant anything more so we
5366 return NT_STATUS_OPLOCK_NOT_GRANTED;
5370 * Wrapper around open_file_ntcreate and open_directory
5373 static NTSTATUS create_file_unixpath(connection_struct *conn,
5374 struct smb_request *req,
5375 struct smb_filename *smb_fname,
5376 uint32_t access_mask,
5377 uint32_t share_access,
5378 uint32_t create_disposition,
5379 uint32_t create_options,
5380 uint32_t file_attributes,
5381 uint32_t oplock_request,
5382 const struct smb2_lease *lease,
5383 uint64_t allocation_size,
5384 uint32_t private_flags,
5385 struct security_descriptor *sd,
5386 struct ea_list *ea_list,
5388 files_struct **result,
5391 struct smb2_lease none_lease;
5392 int info = FILE_WAS_OPENED;
5393 files_struct *base_fsp = NULL;
5394 files_struct *fsp = NULL;
5397 DBG_DEBUG("create_file_unixpath: access_mask = 0x%x "
5398 "file_attributes = 0x%x, share_access = 0x%x, "
5399 "create_disposition = 0x%x create_options = 0x%x "
5400 "oplock_request = 0x%x private_flags = 0x%x "
5401 "ea_list = %p, sd = %p, "
5403 (unsigned int)access_mask,
5404 (unsigned int)file_attributes,
5405 (unsigned int)share_access,
5406 (unsigned int)create_disposition,
5407 (unsigned int)create_options,
5408 (unsigned int)oplock_request,
5409 (unsigned int)private_flags,
5410 ea_list, sd, smb_fname_str_dbg(smb_fname));
5412 if (create_options & FILE_OPEN_BY_FILE_ID) {
5413 status = NT_STATUS_NOT_SUPPORTED;
5417 if (create_options & NTCREATEX_OPTIONS_INVALID_PARAM_MASK) {
5418 status = NT_STATUS_INVALID_PARAMETER;
5423 oplock_request |= INTERNAL_OPEN_ONLY;
5426 if (lease != NULL) {
5427 uint16_t epoch = lease->lease_epoch;
5428 uint16_t version = lease->lease_version;
5431 DBG_WARNING("Got lease on internal open\n");
5432 status = NT_STATUS_INTERNAL_ERROR;
5436 status = lease_match(conn,
5443 if (NT_STATUS_EQUAL(status, NT_STATUS_OPLOCK_NOT_GRANTED)) {
5444 /* Dynamic share file. No leases and update epoch... */
5445 none_lease = *lease;
5446 none_lease.lease_state = SMB2_LEASE_NONE;
5447 none_lease.lease_epoch = epoch;
5448 none_lease.lease_version = version;
5449 lease = &none_lease;
5450 } else if (!NT_STATUS_IS_OK(status)) {
5455 if ((conn->fs_capabilities & FILE_NAMED_STREAMS)
5456 && (access_mask & DELETE_ACCESS)
5457 && !is_ntfs_stream_smb_fname(smb_fname)) {
5459 * We can't open a file with DELETE access if any of the
5460 * streams is open without FILE_SHARE_DELETE
5462 status = open_streams_for_delete(conn, smb_fname);
5464 if (!NT_STATUS_IS_OK(status)) {
5469 if (access_mask & SEC_FLAG_SYSTEM_SECURITY) {
5472 ok = security_token_has_privilege(get_current_nttok(conn),
5475 DBG_DEBUG("open on %s failed - "
5476 "SEC_FLAG_SYSTEM_SECURITY denied.\n",
5477 smb_fname_str_dbg(smb_fname));
5478 status = NT_STATUS_PRIVILEGE_NOT_HELD;
5482 if (conn->sconn->using_smb2 &&
5483 (access_mask == SEC_FLAG_SYSTEM_SECURITY))
5486 * No other bits set. Windows SMB2 refuses this.
5487 * See smbtorture3 SMB2-SACL test.
5489 * Note this is an SMB2-only behavior,
5490 * smbtorture3 SMB1-SYSTEM-SECURITY already tests
5491 * that SMB1 allows this.
5493 status = NT_STATUS_ACCESS_DENIED;
5499 * Files or directories can't be opened DELETE_ON_CLOSE without
5501 * BUG: https://bugzilla.samba.org/show_bug.cgi?id=13358
5503 if (create_options & FILE_DELETE_ON_CLOSE) {
5504 if ((access_mask & DELETE_ACCESS) == 0) {
5505 status = NT_STATUS_INVALID_PARAMETER;
5510 if ((conn->fs_capabilities & FILE_NAMED_STREAMS)
5511 && is_ntfs_stream_smb_fname(smb_fname)
5512 && (!(private_flags & NTCREATEX_OPTIONS_PRIVATE_STREAM_DELETE))) {
5513 uint32_t base_create_disposition;
5514 struct smb_filename *smb_fname_base = NULL;
5515 uint32_t base_privflags;
5517 if (create_options & FILE_DIRECTORY_FILE) {
5518 status = NT_STATUS_NOT_A_DIRECTORY;
5522 switch (create_disposition) {
5524 base_create_disposition = FILE_OPEN;
5527 base_create_disposition = FILE_OPEN_IF;
5531 /* Create an smb_filename with stream_name == NULL. */
5532 smb_fname_base = synthetic_smb_fname(talloc_tos(),
5533 smb_fname->base_name,
5538 if (smb_fname_base == NULL) {
5539 status = NT_STATUS_NO_MEMORY;
5543 if (SMB_VFS_STAT(conn, smb_fname_base) == -1) {
5544 DEBUG(10, ("Unable to stat stream: %s\n",
5545 smb_fname_str_dbg(smb_fname_base)));
5548 * https://bugzilla.samba.org/show_bug.cgi?id=10229
5549 * We need to check if the requested access mask
5550 * could be used to open the underlying file (if
5551 * it existed), as we're passing in zero for the
5552 * access mask to the base filename.
5554 status = check_base_file_access(conn,
5558 if (!NT_STATUS_IS_OK(status)) {
5559 DEBUG(10, ("Permission check "
5560 "for base %s failed: "
5561 "%s\n", smb_fname->base_name,
5562 nt_errstr(status)));
5567 base_privflags = NTCREATEX_OPTIONS_PRIVATE_STREAM_BASEOPEN;
5569 /* Open the base file. */
5570 status = create_file_unixpath(conn, NULL, smb_fname_base, 0,
5573 | FILE_SHARE_DELETE,
5574 base_create_disposition,
5579 TALLOC_FREE(smb_fname_base);
5581 if (!NT_STATUS_IS_OK(status)) {
5582 DEBUG(10, ("create_file_unixpath for base %s failed: "
5583 "%s\n", smb_fname->base_name,
5584 nt_errstr(status)));
5587 /* we don't need the low level fd */
5592 * If it's a request for a directory open, deal with it separately.
5595 if (create_options & FILE_DIRECTORY_FILE) {
5597 if (create_options & FILE_NON_DIRECTORY_FILE) {
5598 status = NT_STATUS_INVALID_PARAMETER;
5602 /* Can't open a temp directory. IFS kit test. */
5603 if (!(file_attributes & FILE_FLAG_POSIX_SEMANTICS) &&
5604 (file_attributes & FILE_ATTRIBUTE_TEMPORARY)) {
5605 status = NT_STATUS_INVALID_PARAMETER;
5610 * We will get a create directory here if the Win32
5611 * app specified a security descriptor in the
5612 * CreateDirectory() call.
5616 status = open_directory(
5617 conn, req, smb_fname, access_mask, share_access,
5618 create_disposition, create_options, file_attributes,
5623 * Ordinary file case.
5626 status = file_new(req, conn, &fsp);
5627 if(!NT_STATUS_IS_OK(status)) {
5631 status = fsp_set_smb_fname(fsp, smb_fname);
5632 if (!NT_STATUS_IS_OK(status)) {
5638 * We're opening the stream element of a
5639 * base_fsp we already opened. Set up the
5642 fsp->base_fsp = base_fsp;
5645 if (allocation_size) {
5646 fsp->initial_allocation_size = smb_roundup(fsp->conn,
5650 status = open_file_ntcreate(conn,
5663 if(!NT_STATUS_IS_OK(status)) {
5664 file_free(req, fsp);
5668 if (NT_STATUS_EQUAL(status, NT_STATUS_FILE_IS_A_DIRECTORY)) {
5670 /* A stream open never opens a directory */
5673 status = NT_STATUS_FILE_IS_A_DIRECTORY;
5678 * Fail the open if it was explicitly a non-directory
5682 if (create_options & FILE_NON_DIRECTORY_FILE) {
5683 status = NT_STATUS_FILE_IS_A_DIRECTORY;
5688 status = open_directory(
5689 conn, req, smb_fname, access_mask,
5690 share_access, create_disposition,
5691 create_options, file_attributes,
5696 if (!NT_STATUS_IS_OK(status)) {
5700 fsp->base_fsp = base_fsp;
5702 if ((ea_list != NULL) &&
5703 ((info == FILE_WAS_CREATED) || (info == FILE_WAS_OVERWRITTEN))) {
5704 status = set_ea(conn, fsp, fsp->fsp_name, ea_list);
5705 if (!NT_STATUS_IS_OK(status)) {
5710 if (!fsp->fsp_flags.is_directory &&
5711 S_ISDIR(fsp->fsp_name->st.st_ex_mode))
5713 status = NT_STATUS_ACCESS_DENIED;
5717 /* Save the requested allocation size. */
5718 if ((info == FILE_WAS_CREATED) || (info == FILE_WAS_OVERWRITTEN)) {
5719 if ((allocation_size > (uint64_t)fsp->fsp_name->st.st_ex_size)
5720 && !(fsp->fsp_flags.is_directory))
5722 fsp->initial_allocation_size = smb_roundup(
5723 fsp->conn, allocation_size);
5724 if (vfs_allocate_file_space(
5725 fsp, fsp->initial_allocation_size) == -1) {
5726 status = NT_STATUS_DISK_FULL;
5730 fsp->initial_allocation_size = smb_roundup(
5731 fsp->conn, (uint64_t)fsp->fsp_name->st.st_ex_size);
5734 fsp->initial_allocation_size = 0;
5737 if ((info == FILE_WAS_CREATED) && lp_nt_acl_support(SNUM(conn)) &&
5738 fsp->base_fsp == NULL) {
5741 * According to the MS documentation, the only time the security
5742 * descriptor is applied to the opened file is iff we *created* the
5743 * file; an existing file stays the same.
5745 * Also, it seems (from observation) that you can open the file with
5746 * any access mask but you can still write the sd. We need to override
5747 * the granted access before we call set_sd
5748 * Patch for bug #2242 from Tom Lackemann <cessnatomny@yahoo.com>.
5751 uint32_t sec_info_sent;
5752 uint32_t saved_access_mask = fsp->access_mask;
5754 sec_info_sent = get_sec_info(sd);
5756 fsp->access_mask = FILE_GENERIC_ALL;
5758 if (sec_info_sent & (SECINFO_OWNER|
5762 status = set_sd(fsp, sd, sec_info_sent);
5765 fsp->access_mask = saved_access_mask;
5767 if (!NT_STATUS_IS_OK(status)) {
5770 } else if (lp_inherit_acls(SNUM(conn))) {
5771 /* Inherit from parent. Errors here are not fatal. */
5772 status = inherit_new_acl(fsp);
5773 if (!NT_STATUS_IS_OK(status)) {
5774 DEBUG(10,("inherit_new_acl: failed for %s with %s\n",
5776 nt_errstr(status) ));
5781 if ((conn->fs_capabilities & FILE_FILE_COMPRESSION)
5782 && (create_options & FILE_NO_COMPRESSION)
5783 && (info == FILE_WAS_CREATED)) {
5784 status = SMB_VFS_SET_COMPRESSION(conn, fsp, fsp,
5785 COMPRESSION_FORMAT_NONE);
5786 if (!NT_STATUS_IS_OK(status)) {
5787 DEBUG(1, ("failed to disable compression: %s\n",
5788 nt_errstr(status)));
5792 DEBUG(10, ("create_file_unixpath: info=%d\n", info));
5795 if (pinfo != NULL) {
5799 smb_fname->st = fsp->fsp_name->st;
5801 return NT_STATUS_OK;
5804 DEBUG(10, ("create_file_unixpath: %s\n", nt_errstr(status)));
5807 if (base_fsp && fsp->base_fsp == base_fsp) {
5809 * The close_file below will close
5814 close_file(req, fsp, ERROR_CLOSE);
5817 if (base_fsp != NULL) {
5818 close_file(req, base_fsp, ERROR_CLOSE);
5825 * Calculate the full path name given a relative fid.
5827 static NTSTATUS get_relative_fid_filename(
5828 connection_struct *conn,
5829 struct smb_request *req,
5830 uint16_t root_dir_fid,
5831 const struct smb_filename *smb_fname,
5832 struct smb_filename **smb_fname_out)
5834 files_struct *dir_fsp;
5835 char *parent_fname = NULL;
5836 char *new_base_name = NULL;
5837 uint32_t ucf_flags = ucf_flags_from_smb_request(req);
5840 if (root_dir_fid == 0 || !smb_fname) {
5841 status = NT_STATUS_INTERNAL_ERROR;
5845 dir_fsp = file_fsp(req, root_dir_fid);
5847 if (dir_fsp == NULL) {
5848 status = NT_STATUS_INVALID_HANDLE;
5852 if (is_ntfs_stream_smb_fname(dir_fsp->fsp_name)) {
5853 status = NT_STATUS_INVALID_HANDLE;
5857 if (!dir_fsp->fsp_flags.is_directory) {
5860 * Check to see if this is a mac fork of some kind.
5863 if ((conn->fs_capabilities & FILE_NAMED_STREAMS) &&
5864 is_ntfs_stream_smb_fname(smb_fname)) {
5865 status = NT_STATUS_OBJECT_PATH_NOT_FOUND;
5870 we need to handle the case when we get a
5871 relative open relative to a file and the
5872 pathname is blank - this is a reopen!
5873 (hint from demyn plantenberg)
5876 status = NT_STATUS_INVALID_HANDLE;
5880 if (ISDOT(dir_fsp->fsp_name->base_name)) {
5882 * We're at the toplevel dir, the final file name
5883 * must not contain ./, as this is filtered out
5884 * normally by srvstr_get_path and unix_convert
5885 * explicitly rejects paths containing ./.
5887 parent_fname = talloc_strdup(talloc_tos(), "");
5888 if (parent_fname == NULL) {
5889 status = NT_STATUS_NO_MEMORY;
5893 size_t dir_name_len = strlen(dir_fsp->fsp_name->base_name);
5896 * Copy in the base directory name.
5899 parent_fname = talloc_array(talloc_tos(), char,
5901 if (parent_fname == NULL) {
5902 status = NT_STATUS_NO_MEMORY;
5905 memcpy(parent_fname, dir_fsp->fsp_name->base_name,
5909 * Ensure it ends in a '/'.
5910 * We used TALLOC_SIZE +2 to add space for the '/'.
5914 && (parent_fname[dir_name_len-1] != '\\')
5915 && (parent_fname[dir_name_len-1] != '/')) {
5916 parent_fname[dir_name_len] = '/';
5917 parent_fname[dir_name_len+1] = '\0';
5921 new_base_name = talloc_asprintf(talloc_tos(), "%s%s", parent_fname,
5922 smb_fname->base_name);
5923 if (new_base_name == NULL) {
5924 status = NT_STATUS_NO_MEMORY;
5928 status = filename_convert(req,
5935 if (!NT_STATUS_IS_OK(status)) {
5940 TALLOC_FREE(parent_fname);
5941 TALLOC_FREE(new_base_name);
5945 NTSTATUS create_file_default(connection_struct *conn,
5946 struct smb_request *req,
5947 uint16_t root_dir_fid,
5948 struct smb_filename *smb_fname,
5949 uint32_t access_mask,
5950 uint32_t share_access,
5951 uint32_t create_disposition,
5952 uint32_t create_options,
5953 uint32_t file_attributes,
5954 uint32_t oplock_request,
5955 const struct smb2_lease *lease,
5956 uint64_t allocation_size,
5957 uint32_t private_flags,
5958 struct security_descriptor *sd,
5959 struct ea_list *ea_list,
5960 files_struct **result,
5962 const struct smb2_create_blobs *in_context_blobs,
5963 struct smb2_create_blobs *out_context_blobs)
5965 int info = FILE_WAS_OPENED;
5966 files_struct *fsp = NULL;
5968 bool stream_name = false;
5969 struct smb2_create_blob *posx = NULL;
5971 DBG_DEBUG("create_file: access_mask = 0x%x "
5972 "file_attributes = 0x%x, share_access = 0x%x, "
5973 "create_disposition = 0x%x create_options = 0x%x "
5974 "oplock_request = 0x%x "
5975 "private_flags = 0x%x "
5976 "root_dir_fid = 0x%x, ea_list = %p, sd = %p, "
5978 (unsigned int)access_mask,
5979 (unsigned int)file_attributes,
5980 (unsigned int)share_access,
5981 (unsigned int)create_disposition,
5982 (unsigned int)create_options,
5983 (unsigned int)oplock_request,
5984 (unsigned int)private_flags,
5985 (unsigned int)root_dir_fid,
5986 ea_list, sd, smb_fname_str_dbg(smb_fname));
5990 * Remember the absolute time of the original request
5991 * with this mid. We'll use it later to see if this
5994 get_deferred_open_message_state(req, &req->request_time, NULL);
5998 * Calculate the filename from the root_dir_if if necessary.
6001 if (root_dir_fid != 0) {
6002 struct smb_filename *smb_fname_out = NULL;
6003 status = get_relative_fid_filename(conn, req, root_dir_fid,
6004 smb_fname, &smb_fname_out);
6005 if (!NT_STATUS_IS_OK(status)) {
6008 smb_fname = smb_fname_out;
6012 * Check to see if this is a mac fork of some kind.
6015 stream_name = is_ntfs_stream_smb_fname(smb_fname);
6017 enum FAKE_FILE_TYPE fake_file_type;
6019 fake_file_type = is_fake_file(smb_fname);
6021 if (fake_file_type != FAKE_FILE_TYPE_NONE) {
6024 * Here we go! support for changing the disk quotas
6027 * We need to fake up to open this MAGIC QUOTA file
6028 * and return a valid FID.
6030 * w2k close this file directly after openening xp
6031 * also tries a QUERY_FILE_INFO on the file and then
6034 status = open_fake_file(req, conn, req->vuid,
6035 fake_file_type, smb_fname,
6037 if (!NT_STATUS_IS_OK(status)) {
6041 ZERO_STRUCT(smb_fname->st);
6045 if (!(conn->fs_capabilities & FILE_NAMED_STREAMS)) {
6046 status = NT_STATUS_OBJECT_NAME_NOT_FOUND;
6051 if (is_ntfs_default_stream_smb_fname(smb_fname)) {
6053 smb_fname->stream_name = NULL;
6054 /* We have to handle this error here. */
6055 if (create_options & FILE_DIRECTORY_FILE) {
6056 status = NT_STATUS_NOT_A_DIRECTORY;
6059 if (req != NULL && req->posix_pathnames) {
6060 ret = SMB_VFS_LSTAT(conn, smb_fname);
6062 ret = SMB_VFS_STAT(conn, smb_fname);
6065 if (ret == 0 && VALID_STAT_OF_DIR(smb_fname->st)) {
6066 status = NT_STATUS_FILE_IS_A_DIRECTORY;
6071 posx = smb2_create_blob_find(
6072 in_context_blobs, SMB2_CREATE_TAG_POSIX);
6074 uint32_t wire_mode_bits = 0;
6075 mode_t mode_bits = 0;
6076 SMB_STRUCT_STAT sbuf = { 0 };
6077 enum perm_type ptype =
6078 (create_options & FILE_DIRECTORY_FILE) ?
6079 PERM_NEW_DIR : PERM_NEW_FILE;
6081 if (posx->data.length != 4) {
6082 status = NT_STATUS_INVALID_PARAMETER;
6086 wire_mode_bits = IVAL(posx->data.data, 0);
6087 status = unix_perms_from_wire(
6088 conn, &sbuf, wire_mode_bits, ptype, &mode_bits);
6089 if (!NT_STATUS_IS_OK(status)) {
6093 * Remove type info from mode, leaving only the
6094 * permissions and setuid/gid bits.
6096 mode_bits &= ~S_IFMT;
6098 file_attributes = (FILE_FLAG_POSIX_SEMANTICS | mode_bits);
6101 status = create_file_unixpath(
6102 conn, req, smb_fname, access_mask, share_access,
6103 create_disposition, create_options, file_attributes,
6104 oplock_request, lease, allocation_size, private_flags,
6108 if (!NT_STATUS_IS_OK(status)) {
6113 DEBUG(10, ("create_file: info=%d\n", info));
6116 if (pinfo != NULL) {
6119 return NT_STATUS_OK;
6122 DEBUG(10, ("create_file: %s\n", nt_errstr(status)));
6125 close_file(req, fsp, ERROR_CLOSE);