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 "system/filesys.h"
25 #include "lib/util/server_id.h"
27 #include "smbd/smbd.h"
28 #include "smbd/globals.h"
29 #include "fake_file.h"
30 #include "../libcli/security/security.h"
31 #include "../librpc/gen_ndr/ndr_security.h"
32 #include "../librpc/gen_ndr/ndr_open_files.h"
33 #include "../librpc/gen_ndr/idmap.h"
34 #include "../librpc/gen_ndr/ioctl.h"
35 #include "passdb/lookup_sid.h"
39 #include "source3/lib/dbwrap/dbwrap_watch.h"
40 #include "locking/leases_db.h"
41 #include "librpc/gen_ndr/ndr_leases_db.h"
43 extern const struct generic_mapping file_generic_mapping;
45 struct deferred_open_record {
46 bool delayed_for_oplocks;
51 * Timer for async opens, needed because they don't use a watch on
52 * a locking.tdb record. This is currently only used for real async
53 * opens and just terminates smbd if the async open times out.
55 struct tevent_timer *te;
58 /****************************************************************************
59 If the requester wanted DELETE_ACCESS and was rejected because
60 the file ACL didn't include DELETE_ACCESS, see if the parent ACL
62 ****************************************************************************/
64 static bool parent_override_delete(connection_struct *conn,
65 const struct smb_filename *smb_fname,
67 uint32_t rejected_mask)
69 if ((access_mask & DELETE_ACCESS) &&
70 (rejected_mask & DELETE_ACCESS) &&
71 can_delete_file_in_directory(conn, smb_fname)) {
77 /****************************************************************************
78 Check if we have open rights.
79 ****************************************************************************/
81 NTSTATUS smbd_check_access_rights(struct connection_struct *conn,
82 const struct smb_filename *smb_fname,
86 /* Check if we have rights to open. */
88 struct security_descriptor *sd = NULL;
89 uint32_t rejected_share_access;
90 uint32_t rejected_mask = access_mask;
91 uint32_t do_not_check_mask = 0;
93 rejected_share_access = access_mask & ~(conn->share_access);
95 if (rejected_share_access) {
96 DEBUG(10, ("smbd_check_access_rights: rejected share access 0x%x "
98 (unsigned int)access_mask,
99 smb_fname_str_dbg(smb_fname),
100 (unsigned int)rejected_share_access ));
101 return NT_STATUS_ACCESS_DENIED;
104 if (!use_privs && get_current_uid(conn) == (uid_t)0) {
105 /* I'm sorry sir, I didn't know you were root... */
106 DEBUG(10,("smbd_check_access_rights: root override "
107 "on %s. Granting 0x%x\n",
108 smb_fname_str_dbg(smb_fname),
109 (unsigned int)access_mask ));
113 if ((access_mask & DELETE_ACCESS) && !lp_acl_check_permissions(SNUM(conn))) {
114 DEBUG(10,("smbd_check_access_rights: not checking ACL "
115 "on DELETE_ACCESS on file %s. Granting 0x%x\n",
116 smb_fname_str_dbg(smb_fname),
117 (unsigned int)access_mask ));
121 if (access_mask == DELETE_ACCESS &&
122 VALID_STAT(smb_fname->st) &&
123 S_ISLNK(smb_fname->st.st_ex_mode)) {
124 /* We can always delete a symlink. */
125 DEBUG(10,("smbd_check_access_rights: not checking ACL "
126 "on DELETE_ACCESS on symlink %s.\n",
127 smb_fname_str_dbg(smb_fname) ));
131 status = SMB_VFS_GET_NT_ACL(conn, smb_fname,
134 SECINFO_DACL), talloc_tos(), &sd);
136 if (!NT_STATUS_IS_OK(status)) {
137 DEBUG(10, ("smbd_check_access_rights: Could not get acl "
139 smb_fname_str_dbg(smb_fname),
142 if (NT_STATUS_EQUAL(status, NT_STATUS_ACCESS_DENIED)) {
150 * If we can access the path to this file, by
151 * default we have FILE_READ_ATTRIBUTES from the
152 * containing directory. See the section:
153 * "Algorithm to Check Access to an Existing File"
156 * se_file_access_check() also takes care of
157 * owner WRITE_DAC and READ_CONTROL.
159 do_not_check_mask = FILE_READ_ATTRIBUTES;
162 * Samba 3.6 and earlier granted execute access even
163 * if the ACL did not contain execute rights.
164 * Samba 4.0 is more correct and checks it.
165 * The compatibilty mode allows one to skip this check
166 * to smoothen upgrades.
168 if (lp_acl_allow_execute_always(SNUM(conn))) {
169 do_not_check_mask |= FILE_EXECUTE;
172 status = se_file_access_check(sd,
173 get_current_nttok(conn),
175 (access_mask & ~do_not_check_mask),
178 DEBUG(10,("smbd_check_access_rights: file %s requesting "
179 "0x%x returning 0x%x (%s)\n",
180 smb_fname_str_dbg(smb_fname),
181 (unsigned int)access_mask,
182 (unsigned int)rejected_mask,
183 nt_errstr(status) ));
185 if (!NT_STATUS_IS_OK(status)) {
186 if (DEBUGLEVEL >= 10) {
187 DEBUG(10,("smbd_check_access_rights: acl for %s is:\n",
188 smb_fname_str_dbg(smb_fname) ));
189 NDR_PRINT_DEBUG(security_descriptor, sd);
195 if (NT_STATUS_IS_OK(status) ||
196 !NT_STATUS_EQUAL(status, NT_STATUS_ACCESS_DENIED)) {
200 /* Here we know status == NT_STATUS_ACCESS_DENIED. */
204 if ((access_mask & FILE_WRITE_ATTRIBUTES) &&
205 (rejected_mask & FILE_WRITE_ATTRIBUTES) &&
206 !lp_store_dos_attributes(SNUM(conn)) &&
207 (lp_map_readonly(SNUM(conn)) ||
208 lp_map_archive(SNUM(conn)) ||
209 lp_map_hidden(SNUM(conn)) ||
210 lp_map_system(SNUM(conn)))) {
211 rejected_mask &= ~FILE_WRITE_ATTRIBUTES;
213 DEBUG(10,("smbd_check_access_rights: "
215 "FILE_WRITE_ATTRIBUTES "
217 smb_fname_str_dbg(smb_fname)));
220 if (parent_override_delete(conn,
224 /* Were we trying to do an open
225 * for delete and didn't get DELETE
226 * access (only) ? Check if the
227 * directory allows DELETE_CHILD.
229 * http://blogs.msdn.com/oldnewthing/archive/2004/06/04/148426.aspx
232 rejected_mask &= ~DELETE_ACCESS;
234 DEBUG(10,("smbd_check_access_rights: "
238 smb_fname_str_dbg(smb_fname)));
241 if (rejected_mask != 0) {
242 return NT_STATUS_ACCESS_DENIED;
247 NTSTATUS check_parent_access(struct connection_struct *conn,
248 struct smb_filename *smb_fname,
249 uint32_t access_mask)
252 char *parent_dir = NULL;
253 struct security_descriptor *parent_sd = NULL;
254 uint32_t access_granted = 0;
255 struct smb_filename *parent_smb_fname = NULL;
256 struct share_mode_lock *lck = NULL;
257 struct file_id id = {0};
259 bool delete_on_close_set;
261 TALLOC_CTX *frame = talloc_stackframe();
263 if (!parent_dirname(frame,
264 smb_fname->base_name,
267 status = NT_STATUS_NO_MEMORY;
271 parent_smb_fname = synthetic_smb_fname(frame,
276 if (parent_smb_fname == NULL) {
277 status = NT_STATUS_NO_MEMORY;
281 if (get_current_uid(conn) == (uid_t)0) {
282 /* I'm sorry sir, I didn't know you were root... */
283 DEBUG(10,("check_parent_access: root override "
284 "on %s. Granting 0x%x\n",
285 smb_fname_str_dbg(smb_fname),
286 (unsigned int)access_mask ));
287 status = NT_STATUS_OK;
291 status = SMB_VFS_GET_NT_ACL(conn,
297 if (!NT_STATUS_IS_OK(status)) {
298 DEBUG(5,("check_parent_access: SMB_VFS_GET_NT_ACL failed for "
299 "%s with error %s\n",
306 * If we can access the path to this file, by
307 * default we have FILE_READ_ATTRIBUTES from the
308 * containing directory. See the section:
309 * "Algorithm to Check Access to an Existing File"
312 * se_file_access_check() also takes care of
313 * owner WRITE_DAC and READ_CONTROL.
315 status = se_file_access_check(parent_sd,
316 get_current_nttok(conn),
318 (access_mask & ~FILE_READ_ATTRIBUTES),
320 if(!NT_STATUS_IS_OK(status)) {
321 DEBUG(5,("check_parent_access: access check "
322 "on directory %s for "
323 "path %s for mask 0x%x returned (0x%x) %s\n",
325 smb_fname->base_name,
328 nt_errstr(status) ));
332 if (!(access_mask & (SEC_DIR_ADD_FILE | SEC_DIR_ADD_SUBDIR))) {
333 status = NT_STATUS_OK;
336 if (!lp_check_parent_directory_delete_on_close(SNUM(conn))) {
337 status = NT_STATUS_OK;
341 /* Check if the directory has delete-on-close set */
342 ret = SMB_VFS_STAT(conn, parent_smb_fname);
344 status = map_nt_error_from_unix(errno);
348 id = SMB_VFS_FILE_ID_CREATE(conn, &parent_smb_fname->st);
350 status = file_name_hash(conn, parent_smb_fname->base_name, &name_hash);
351 if (!NT_STATUS_IS_OK(status)) {
355 lck = get_existing_share_mode_lock(frame, id);
357 status = NT_STATUS_OK;
361 delete_on_close_set = is_delete_on_close_set(lck, name_hash);
362 if (delete_on_close_set) {
363 status = NT_STATUS_DELETE_PENDING;
367 status = NT_STATUS_OK;
374 /****************************************************************************
375 Ensure when opening a base file for a stream open that we have permissions
376 to do so given the access mask on the base file.
377 ****************************************************************************/
379 static NTSTATUS check_base_file_access(struct connection_struct *conn,
380 struct smb_filename *smb_fname,
381 uint32_t access_mask)
385 status = smbd_calculate_access_mask(conn, smb_fname,
389 if (!NT_STATUS_IS_OK(status)) {
390 DEBUG(10, ("smbd_calculate_access_mask "
391 "on file %s returned %s\n",
392 smb_fname_str_dbg(smb_fname),
397 if (access_mask & (FILE_WRITE_DATA|FILE_APPEND_DATA)) {
399 if (!CAN_WRITE(conn)) {
400 return NT_STATUS_ACCESS_DENIED;
402 dosattrs = dos_mode(conn, smb_fname);
403 if (IS_DOS_READONLY(dosattrs)) {
404 return NT_STATUS_ACCESS_DENIED;
408 return smbd_check_access_rights(conn,
414 /****************************************************************************
415 Handle differing symlink errno's
416 ****************************************************************************/
418 static int link_errno_convert(int err)
420 #if defined(ENOTSUP) && defined(OSF1)
421 /* handle special Tru64 errno */
422 if (err == ENOTSUP) {
427 /* fix broken NetBSD errno */
432 /* fix broken FreeBSD errno */
439 static int non_widelink_open(struct connection_struct *conn,
440 const struct smb_filename *conn_rootdir_fname,
442 struct smb_filename *smb_fname,
445 unsigned int link_depth);
447 /****************************************************************************
448 Follow a symlink in userspace.
449 ****************************************************************************/
451 static int process_symlink_open(struct connection_struct *conn,
452 const struct smb_filename *conn_rootdir_fname,
454 struct smb_filename *smb_fname,
457 unsigned int link_depth)
460 char *link_target = NULL;
461 struct smb_filename target_fname = {0};
463 struct smb_filename *oldwd_fname = NULL;
464 size_t rootdir_len = 0;
465 struct smb_filename *resolved_fname = NULL;
466 char *resolved_name = NULL;
467 bool matched = false;
471 * Ensure we don't get stuck in a symlink loop.
474 if (link_depth >= 20) {
479 /* Allocate space for the link target. */
480 link_target = talloc_array(talloc_tos(), char, PATH_MAX);
481 if (link_target == NULL) {
486 /* Read the link target. */
487 link_len = SMB_VFS_READLINK(conn,
491 if (link_len == -1) {
495 /* Ensure it's at least null terminated. */
496 link_target[link_len] = '\0';
497 target_fname = (struct smb_filename){ .base_name = link_target };
499 /* Convert to an absolute path. */
500 resolved_fname = SMB_VFS_REALPATH(conn, talloc_tos(), &target_fname);
501 if (resolved_fname == NULL) {
504 resolved_name = resolved_fname->base_name;
507 * We know conn_rootdir starts with '/' and
508 * does not end in '/'. FIXME ! Should we
511 rootdir_len = strlen(conn_rootdir_fname->base_name);
513 matched = (strncmp(conn_rootdir_fname->base_name,
522 * Turn into a path relative to the share root.
524 if (resolved_name[rootdir_len] == '\0') {
525 /* Link to the root of the share. */
526 TALLOC_FREE(smb_fname->base_name);
527 smb_fname->base_name = talloc_strdup(smb_fname, ".");
528 } else if (resolved_name[rootdir_len] == '/') {
529 TALLOC_FREE(smb_fname->base_name);
530 smb_fname->base_name = talloc_strdup(smb_fname,
531 &resolved_name[rootdir_len+1]);
537 if (smb_fname->base_name == NULL) {
542 oldwd_fname = vfs_GetWd(talloc_tos(), conn);
543 if (oldwd_fname == NULL) {
547 /* Ensure we operate from the root of the share. */
548 if (vfs_ChDir(conn, conn_rootdir_fname) == -1) {
552 /* And do it all again.. */
553 fd = non_widelink_open(conn,
566 TALLOC_FREE(resolved_fname);
567 TALLOC_FREE(link_target);
568 if (oldwd_fname != NULL) {
569 int ret = vfs_ChDir(conn, oldwd_fname);
571 smb_panic("unable to get back to old directory\n");
573 TALLOC_FREE(oldwd_fname);
575 if (saved_errno != 0) {
581 /****************************************************************************
583 ****************************************************************************/
585 static int non_widelink_open(struct connection_struct *conn,
586 const struct smb_filename *conn_rootdir_fname,
588 struct smb_filename *smb_fname,
591 unsigned int link_depth)
595 struct smb_filename *smb_fname_rel = NULL;
597 struct smb_filename *oldwd_fname = NULL;
598 char *parent_dir = NULL;
599 struct smb_filename parent_dir_fname = {0};
600 const char *final_component = NULL;
601 bool is_directory = false;
605 if (flags & O_DIRECTORY) {
611 parent_dir = talloc_strdup(talloc_tos(), smb_fname->base_name);
612 if (parent_dir == NULL) {
617 final_component = ".";
619 ok = parent_dirname(talloc_tos(),
620 smb_fname->base_name,
629 parent_dir_fname = (struct smb_filename) { .base_name = parent_dir };
631 oldwd_fname = vfs_GetWd(talloc_tos(), conn);
632 if (oldwd_fname == NULL) {
636 /* Pin parent directory in place. */
637 if (vfs_ChDir(conn, &parent_dir_fname) == -1) {
641 smb_fname_rel = synthetic_smb_fname(talloc_tos(),
643 smb_fname->stream_name,
646 if (smb_fname_rel == NULL) {
647 saved_errno = ENOMEM;
651 /* Ensure the relative path is below the share. */
652 status = check_reduced_name(conn, &parent_dir_fname, smb_fname_rel);
653 if (!NT_STATUS_IS_OK(status)) {
654 saved_errno = map_errno_from_nt_status(status);
661 struct smb_filename *tmp_name = fsp->fsp_name;
662 fsp->fsp_name = smb_fname_rel;
663 fd = SMB_VFS_OPEN(conn, smb_fname_rel, fsp, flags, mode);
664 fsp->fsp_name = tmp_name;
668 saved_errno = link_errno_convert(errno);
670 * Trying to open a symlink to a directory with O_NOFOLLOW and
671 * O_DIRECTORY can return either of ELOOP and ENOTDIR. So
672 * ENOTDIR really means: might be a symlink, but we're not sure.
673 * In this case, we just assume there's a symlink. If we were
674 * wrong, process_symlink_open() will return EINVAL. We check
675 * this below, and fall back to returning the initial
678 * BUG: https://bugzilla.samba.org/show_bug.cgi?id=12860
680 if (saved_errno == ELOOP || saved_errno == ENOTDIR) {
681 if (fsp->posix_flags & FSP_POSIX_FLAGS_OPEN) {
682 /* Never follow symlinks on posix open. */
685 if (!lp_follow_symlinks(SNUM(conn))) {
686 /* Explicitly no symlinks. */
690 * We may have a symlink. Follow in userspace
691 * to ensure it's under the share definition.
693 fd = process_symlink_open(conn,
701 if (saved_errno == ENOTDIR &&
704 * O_DIRECTORY on neither a directory,
705 * nor a symlink. Just return
706 * saved_errno from initial open()
711 link_errno_convert(errno);
718 TALLOC_FREE(parent_dir);
719 TALLOC_FREE(smb_fname_rel);
721 if (oldwd_fname != NULL) {
722 int ret = vfs_ChDir(conn, oldwd_fname);
724 smb_panic("unable to get back to old directory\n");
726 TALLOC_FREE(oldwd_fname);
728 if (saved_errno != 0) {
734 /****************************************************************************
735 fd support routines - attempt to do a dos_open.
736 ****************************************************************************/
738 NTSTATUS fd_open(struct connection_struct *conn,
743 struct smb_filename *smb_fname = fsp->fsp_name;
744 NTSTATUS status = NT_STATUS_OK;
747 * Never follow symlinks on a POSIX client. The
748 * client should be doing this.
751 if ((fsp->posix_flags & FSP_POSIX_FLAGS_OPEN) || !lp_follow_symlinks(SNUM(conn))) {
755 /* Ensure path is below share definition. */
756 if (!lp_widelinks(SNUM(conn))) {
757 struct smb_filename *conn_rootdir_fname = NULL;
758 const char *conn_rootdir = SMB_VFS_CONNECTPATH(conn,
762 if (conn_rootdir == NULL) {
763 return NT_STATUS_NO_MEMORY;
765 conn_rootdir_fname = synthetic_smb_fname(talloc_tos(),
770 if (conn_rootdir_fname == NULL) {
771 return NT_STATUS_NO_MEMORY;
775 * Only follow symlinks within a share
778 fsp->fh->fd = non_widelink_open(conn,
785 if (fsp->fh->fd == -1) {
788 TALLOC_FREE(conn_rootdir_fname);
789 if (saved_errno != 0) {
793 fsp->fh->fd = SMB_VFS_OPEN(conn, smb_fname, fsp, flags, mode);
796 if (fsp->fh->fd == -1) {
797 int posix_errno = link_errno_convert(errno);
798 status = map_nt_error_from_unix(posix_errno);
799 if (errno == EMFILE) {
800 static time_t last_warned = 0L;
802 if (time((time_t *) NULL) > last_warned) {
803 DEBUG(0,("Too many open files, unable "
804 "to open more! smbd's max "
806 lp_max_open_files()));
807 last_warned = time((time_t *) NULL);
813 DEBUG(10,("fd_open: name %s, flags = 0%o mode = 0%o, fd = %d. %s\n",
814 smb_fname_str_dbg(smb_fname), flags, (int)mode, fsp->fh->fd,
815 (fsp->fh->fd == -1) ? strerror(errno) : "" ));
820 /****************************************************************************
821 Close the file associated with a fsp.
822 ****************************************************************************/
824 NTSTATUS fd_close(files_struct *fsp)
831 if (fsp->fh->fd == -1) {
832 return NT_STATUS_OK; /* What we used to call a stat open. */
834 if (fsp->fh->ref_count > 1) {
835 return NT_STATUS_OK; /* Shared handle. Only close last reference. */
838 ret = SMB_VFS_CLOSE(fsp);
841 return map_nt_error_from_unix(errno);
846 /****************************************************************************
847 Change the ownership of a file to that of the parent directory.
848 Do this by fd if possible.
849 ****************************************************************************/
851 void change_file_owner_to_parent(connection_struct *conn,
852 const char *inherit_from_dir,
855 struct smb_filename *smb_fname_parent;
858 smb_fname_parent = synthetic_smb_fname(talloc_tos(),
863 if (smb_fname_parent == NULL) {
867 ret = SMB_VFS_STAT(conn, smb_fname_parent);
869 DEBUG(0,("change_file_owner_to_parent: failed to stat parent "
870 "directory %s. Error was %s\n",
871 smb_fname_str_dbg(smb_fname_parent),
873 TALLOC_FREE(smb_fname_parent);
877 if (smb_fname_parent->st.st_ex_uid == fsp->fsp_name->st.st_ex_uid) {
878 /* Already this uid - no need to change. */
879 DEBUG(10,("change_file_owner_to_parent: file %s "
880 "is already owned by uid %d\n",
882 (int)fsp->fsp_name->st.st_ex_uid ));
883 TALLOC_FREE(smb_fname_parent);
888 ret = SMB_VFS_FCHOWN(fsp, smb_fname_parent->st.st_ex_uid, (gid_t)-1);
891 DEBUG(0,("change_file_owner_to_parent: failed to fchown "
892 "file %s to parent directory uid %u. Error "
893 "was %s\n", fsp_str_dbg(fsp),
894 (unsigned int)smb_fname_parent->st.st_ex_uid,
897 DEBUG(10,("change_file_owner_to_parent: changed new file %s to "
898 "parent directory uid %u.\n", fsp_str_dbg(fsp),
899 (unsigned int)smb_fname_parent->st.st_ex_uid));
900 /* Ensure the uid entry is updated. */
901 fsp->fsp_name->st.st_ex_uid = smb_fname_parent->st.st_ex_uid;
904 TALLOC_FREE(smb_fname_parent);
907 static NTSTATUS change_dir_owner_to_parent(connection_struct *conn,
908 const char *inherit_from_dir,
909 struct smb_filename *smb_dname,
910 SMB_STRUCT_STAT *psbuf)
912 struct smb_filename *smb_fname_parent;
913 struct smb_filename *smb_fname_cwd = NULL;
914 struct smb_filename *saved_dir_fname = NULL;
915 TALLOC_CTX *ctx = talloc_tos();
916 NTSTATUS status = NT_STATUS_OK;
919 smb_fname_parent = synthetic_smb_fname(ctx,
924 if (smb_fname_parent == NULL) {
925 return NT_STATUS_NO_MEMORY;
928 ret = SMB_VFS_STAT(conn, smb_fname_parent);
930 status = map_nt_error_from_unix(errno);
931 DEBUG(0,("change_dir_owner_to_parent: failed to stat parent "
932 "directory %s. Error was %s\n",
933 smb_fname_str_dbg(smb_fname_parent),
938 /* We've already done an lstat into psbuf, and we know it's a
939 directory. If we can cd into the directory and the dev/ino
940 are the same then we can safely chown without races as
941 we're locking the directory in place by being in it. This
942 should work on any UNIX (thanks tridge :-). JRA.
945 saved_dir_fname = vfs_GetWd(ctx,conn);
946 if (!saved_dir_fname) {
947 status = map_nt_error_from_unix(errno);
948 DEBUG(0,("change_dir_owner_to_parent: failed to get "
949 "current working directory. Error was %s\n",
954 /* Chdir into the new path. */
955 if (vfs_ChDir(conn, smb_dname) == -1) {
956 status = map_nt_error_from_unix(errno);
957 DEBUG(0,("change_dir_owner_to_parent: failed to change "
958 "current working directory to %s. Error "
959 "was %s\n", smb_dname->base_name, strerror(errno) ));
963 smb_fname_cwd = synthetic_smb_fname(ctx, ".", NULL, NULL, 0);
964 if (smb_fname_cwd == NULL) {
965 status = NT_STATUS_NO_MEMORY;
969 ret = SMB_VFS_STAT(conn, smb_fname_cwd);
971 status = map_nt_error_from_unix(errno);
972 DEBUG(0,("change_dir_owner_to_parent: failed to stat "
973 "directory '.' (%s) Error was %s\n",
974 smb_dname->base_name, strerror(errno)));
978 /* Ensure we're pointing at the same place. */
979 if (smb_fname_cwd->st.st_ex_dev != psbuf->st_ex_dev ||
980 smb_fname_cwd->st.st_ex_ino != psbuf->st_ex_ino) {
981 DEBUG(0,("change_dir_owner_to_parent: "
982 "device/inode on directory %s changed. "
983 "Refusing to chown !\n",
984 smb_dname->base_name ));
985 status = NT_STATUS_ACCESS_DENIED;
989 if (smb_fname_parent->st.st_ex_uid == smb_fname_cwd->st.st_ex_uid) {
990 /* Already this uid - no need to change. */
991 DEBUG(10,("change_dir_owner_to_parent: directory %s "
992 "is already owned by uid %d\n",
993 smb_dname->base_name,
994 (int)smb_fname_cwd->st.st_ex_uid ));
995 status = NT_STATUS_OK;
1000 ret = SMB_VFS_LCHOWN(conn,
1002 smb_fname_parent->st.st_ex_uid,
1006 status = map_nt_error_from_unix(errno);
1007 DEBUG(10,("change_dir_owner_to_parent: failed to chown "
1008 "directory %s to parent directory uid %u. "
1010 smb_dname->base_name,
1011 (unsigned int)smb_fname_parent->st.st_ex_uid,
1014 DEBUG(10,("change_dir_owner_to_parent: changed ownership of new "
1015 "directory %s to parent directory uid %u.\n",
1016 smb_dname->base_name,
1017 (unsigned int)smb_fname_parent->st.st_ex_uid ));
1018 /* Ensure the uid entry is updated. */
1019 psbuf->st_ex_uid = smb_fname_parent->st.st_ex_uid;
1023 vfs_ChDir(conn, saved_dir_fname);
1025 TALLOC_FREE(saved_dir_fname);
1026 TALLOC_FREE(smb_fname_parent);
1027 TALLOC_FREE(smb_fname_cwd);
1031 /****************************************************************************
1032 Open a file - returning a guaranteed ATOMIC indication of if the
1033 file was created or not.
1034 ****************************************************************************/
1036 static NTSTATUS fd_open_atomic(struct connection_struct *conn,
1042 NTSTATUS status = NT_STATUS_UNSUCCESSFUL;
1043 NTSTATUS retry_status;
1044 bool file_existed = VALID_STAT(fsp->fsp_name->st);
1047 *file_created = false;
1049 if (!(flags & O_CREAT)) {
1051 * We're not creating the file, just pass through.
1053 return fd_open(conn, fsp, flags, mode);
1056 if (flags & O_EXCL) {
1058 * Fail if already exists, just pass through.
1060 status = fd_open(conn, fsp, flags, mode);
1063 * Here we've opened with O_CREAT|O_EXCL. If that went
1064 * NT_STATUS_OK, we *know* we created this file.
1066 *file_created = NT_STATUS_IS_OK(status);
1072 * Now it gets tricky. We have O_CREAT, but not O_EXCL.
1073 * To know absolutely if we created the file or not,
1074 * we can never call O_CREAT without O_EXCL. So if
1075 * we think the file existed, try without O_CREAT|O_EXCL.
1076 * If we think the file didn't exist, try with
1079 * The big problem here is dangling symlinks. Opening
1080 * without O_NOFOLLOW means both bad symlink
1081 * and missing path return -1, ENOENT from open(). As POSIX
1082 * is pathname based it's not possible to tell
1083 * the difference between these two cases in a
1084 * non-racy way, so change to try only two attempts before
1087 * We don't have this problem for the O_NOFOLLOW
1088 * case as it just returns NT_STATUS_OBJECT_PATH_NOT_FOUND
1089 * mapped from the ELOOP POSIX error.
1095 curr_flags &= ~(O_CREAT);
1096 retry_status = NT_STATUS_OBJECT_NAME_NOT_FOUND;
1098 curr_flags |= O_EXCL;
1099 retry_status = NT_STATUS_OBJECT_NAME_COLLISION;
1102 status = fd_open(conn, fsp, curr_flags, mode);
1103 if (NT_STATUS_IS_OK(status)) {
1104 if (!file_existed) {
1105 *file_created = true;
1107 return NT_STATUS_OK;
1109 if (!NT_STATUS_EQUAL(status, retry_status)) {
1116 * Keep file_existed up to date for clarity.
1118 if (NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
1119 file_existed = false;
1120 curr_flags |= O_EXCL;
1121 DBG_DEBUG("file %s did not exist. Retry.\n",
1122 smb_fname_str_dbg(fsp->fsp_name));
1124 file_existed = true;
1125 curr_flags &= ~(O_CREAT);
1126 DBG_DEBUG("file %s existed. Retry.\n",
1127 smb_fname_str_dbg(fsp->fsp_name));
1130 status = fd_open(conn, fsp, curr_flags, mode);
1132 if (NT_STATUS_IS_OK(status) && (!file_existed)) {
1133 *file_created = true;
1139 /****************************************************************************
1141 ****************************************************************************/
1143 static NTSTATUS open_file(files_struct *fsp,
1144 connection_struct *conn,
1145 struct smb_request *req,
1146 const char *parent_dir,
1149 uint32_t access_mask, /* client requested access mask. */
1150 uint32_t open_access_mask, /* what we're actually using in the open. */
1151 bool *p_file_created)
1153 struct smb_filename *smb_fname = fsp->fsp_name;
1154 NTSTATUS status = NT_STATUS_OK;
1155 int accmode = (flags & O_ACCMODE);
1156 int local_flags = flags;
1157 bool file_existed = VALID_STAT(fsp->fsp_name->st);
1162 /* Check permissions */
1165 * This code was changed after seeing a client open request
1166 * containing the open mode of (DENY_WRITE/read-only) with
1167 * the 'create if not exist' bit set. The previous code
1168 * would fail to open the file read only on a read-only share
1169 * as it was checking the flags parameter directly against O_RDONLY,
1170 * this was failing as the flags parameter was set to O_RDONLY|O_CREAT.
1174 if (!CAN_WRITE(conn)) {
1175 /* It's a read-only share - fail if we wanted to write. */
1176 if(accmode != O_RDONLY || (flags & O_TRUNC) || (flags & O_APPEND)) {
1177 DEBUG(3,("Permission denied opening %s\n",
1178 smb_fname_str_dbg(smb_fname)));
1179 return NT_STATUS_ACCESS_DENIED;
1181 if (flags & O_CREAT) {
1182 /* We don't want to write - but we must make sure that
1183 O_CREAT doesn't create the file if we have write
1184 access into the directory.
1186 flags &= ~(O_CREAT|O_EXCL);
1187 local_flags &= ~(O_CREAT|O_EXCL);
1192 * This little piece of insanity is inspired by the
1193 * fact that an NT client can open a file for O_RDONLY,
1194 * but set the create disposition to FILE_EXISTS_TRUNCATE.
1195 * If the client *can* write to the file, then it expects to
1196 * truncate the file, even though it is opening for readonly.
1197 * Quicken uses this stupid trick in backup file creation...
1198 * Thanks *greatly* to "David W. Chapman Jr." <dwcjr@inethouston.net>
1199 * for helping track this one down. It didn't bite us in 2.0.x
1200 * as we always opened files read-write in that release. JRA.
1203 if ((accmode == O_RDONLY) && ((flags & O_TRUNC) == O_TRUNC)) {
1204 DEBUG(10,("open_file: truncate requested on read-only open "
1205 "for file %s\n", smb_fname_str_dbg(smb_fname)));
1206 local_flags = (flags & ~O_ACCMODE)|O_RDWR;
1209 if ((open_access_mask & (FILE_READ_DATA|FILE_WRITE_DATA|FILE_APPEND_DATA|FILE_EXECUTE)) ||
1210 (!file_existed && (local_flags & O_CREAT)) ||
1211 ((local_flags & O_TRUNC) == O_TRUNC) ) {
1215 #if defined(O_NONBLOCK) && defined(S_ISFIFO)
1217 * We would block on opening a FIFO with no one else on the
1218 * other end. Do what we used to do and add O_NONBLOCK to the
1222 if (file_existed && S_ISFIFO(smb_fname->st.st_ex_mode)) {
1223 local_flags &= ~O_TRUNC; /* Can't truncate a FIFO. */
1224 local_flags |= O_NONBLOCK;
1228 /* Don't create files with Microsoft wildcard characters. */
1229 if (fsp->base_fsp) {
1231 * wildcard characters are allowed in stream names
1232 * only test the basefilename
1234 wild = fsp->base_fsp->fsp_name->base_name;
1236 wild = smb_fname->base_name;
1238 if ((local_flags & O_CREAT) && !file_existed &&
1239 !(fsp->posix_flags & FSP_POSIX_FLAGS_PATHNAMES) &&
1240 ms_has_wild(wild)) {
1241 return NT_STATUS_OBJECT_NAME_INVALID;
1244 /* Can we access this file ? */
1245 if (!fsp->base_fsp) {
1246 /* Only do this check on non-stream open. */
1248 status = smbd_check_access_rights(conn,
1253 if (!NT_STATUS_IS_OK(status)) {
1254 DEBUG(10, ("open_file: "
1255 "smbd_check_access_rights "
1256 "on file %s returned %s\n",
1257 smb_fname_str_dbg(smb_fname),
1258 nt_errstr(status)));
1261 if (!NT_STATUS_IS_OK(status) &&
1262 !NT_STATUS_EQUAL(status,
1263 NT_STATUS_OBJECT_NAME_NOT_FOUND))
1268 if (NT_STATUS_EQUAL(status,
1269 NT_STATUS_OBJECT_NAME_NOT_FOUND))
1271 DEBUG(10, ("open_file: "
1272 "file %s vanished since we "
1273 "checked for existence.\n",
1274 smb_fname_str_dbg(smb_fname)));
1275 file_existed = false;
1276 SET_STAT_INVALID(fsp->fsp_name->st);
1280 if (!file_existed) {
1281 if (!(local_flags & O_CREAT)) {
1282 /* File didn't exist and no O_CREAT. */
1283 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
1286 status = check_parent_access(conn,
1289 if (!NT_STATUS_IS_OK(status)) {
1290 DEBUG(10, ("open_file: "
1291 "check_parent_access on "
1292 "file %s returned %s\n",
1293 smb_fname_str_dbg(smb_fname),
1294 nt_errstr(status) ));
1301 * Actually do the open - if O_TRUNC is needed handle it
1302 * below under the share mode lock.
1304 status = fd_open_atomic(conn, fsp, local_flags & ~O_TRUNC,
1305 unx_mode, p_file_created);
1306 if (!NT_STATUS_IS_OK(status)) {
1307 DEBUG(3,("Error opening file %s (%s) (local_flags=%d) "
1308 "(flags=%d)\n", smb_fname_str_dbg(smb_fname),
1309 nt_errstr(status),local_flags,flags));
1313 if (local_flags & O_NONBLOCK) {
1315 * GPFS can return ETIMEDOUT for pread on
1316 * nonblocking file descriptors when files
1317 * migrated to tape need to be recalled. I
1318 * could imagine this happens elsehwere
1319 * too. With blocking file descriptors this
1322 ret = set_blocking(fsp->fh->fd, true);
1324 status = map_nt_error_from_unix(errno);
1325 DBG_WARNING("Could not set fd to blocking: "
1326 "%s\n", strerror(errno));
1332 ret = SMB_VFS_FSTAT(fsp, &smb_fname->st);
1334 /* If we have an fd, this stat should succeed. */
1335 DEBUG(0,("Error doing fstat on open file %s "
1337 smb_fname_str_dbg(smb_fname),
1339 status = map_nt_error_from_unix(errno);
1344 if (*p_file_created) {
1345 /* We created this file. */
1347 bool need_re_stat = false;
1348 /* Do all inheritance work after we've
1349 done a successful fstat call and filled
1350 in the stat struct in fsp->fsp_name. */
1352 /* Inherit the ACL if required */
1353 if (lp_inherit_permissions(SNUM(conn))) {
1354 inherit_access_posix_acl(conn, parent_dir,
1357 need_re_stat = true;
1360 /* Change the owner if required. */
1361 if (lp_inherit_owner(SNUM(conn)) != INHERIT_OWNER_NO) {
1362 change_file_owner_to_parent(conn, parent_dir,
1364 need_re_stat = true;
1368 ret = SMB_VFS_FSTAT(fsp, &smb_fname->st);
1369 /* If we have an fd, this stat should succeed. */
1371 DEBUG(0,("Error doing fstat on open file %s "
1373 smb_fname_str_dbg(smb_fname),
1378 notify_fname(conn, NOTIFY_ACTION_ADDED,
1379 FILE_NOTIFY_CHANGE_FILE_NAME,
1380 smb_fname->base_name);
1383 fsp->fh->fd = -1; /* What we used to call a stat open. */
1384 if (!file_existed) {
1385 /* File must exist for a stat open. */
1386 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
1389 status = smbd_check_access_rights(conn,
1394 if (NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND) &&
1395 (fsp->posix_flags & FSP_POSIX_FLAGS_OPEN) &&
1396 S_ISLNK(smb_fname->st.st_ex_mode)) {
1397 /* This is a POSIX stat open for delete
1398 * or rename on a symlink that points
1399 * nowhere. Allow. */
1400 DEBUG(10,("open_file: allowing POSIX "
1401 "open on bad symlink %s\n",
1402 smb_fname_str_dbg(smb_fname)));
1403 status = NT_STATUS_OK;
1406 if (!NT_STATUS_IS_OK(status)) {
1407 DEBUG(10,("open_file: "
1408 "smbd_check_access_rights on file "
1410 smb_fname_str_dbg(smb_fname),
1411 nt_errstr(status) ));
1417 * POSIX allows read-only opens of directories. We don't
1418 * want to do this (we use a different code path for this)
1419 * so catch a directory open and return an EISDIR. JRA.
1422 if(S_ISDIR(smb_fname->st.st_ex_mode)) {
1425 return NT_STATUS_FILE_IS_A_DIRECTORY;
1428 fsp->file_id = vfs_file_id_from_sbuf(conn, &smb_fname->st);
1429 fsp->vuid = req ? req->vuid : UID_FIELD_INVALID;
1430 fsp->file_pid = req ? req->smbpid : 0;
1431 fsp->can_lock = True;
1432 fsp->can_read = ((access_mask & FILE_READ_DATA) != 0);
1435 ((access_mask & (FILE_WRITE_DATA | FILE_APPEND_DATA)) != 0);
1436 fsp->print_file = NULL;
1437 fsp->modified = False;
1438 fsp->sent_oplock_break = NO_BREAK_SENT;
1439 fsp->is_directory = False;
1440 if (conn->aio_write_behind_list &&
1441 is_in_path(smb_fname->base_name, conn->aio_write_behind_list,
1442 conn->case_sensitive)) {
1443 fsp->aio_write_behind = True;
1446 fsp->wcp = NULL; /* Write cache pointer. */
1448 DEBUG(2,("%s opened file %s read=%s write=%s (numopen=%d)\n",
1449 conn->session_info->unix_info->unix_name,
1450 smb_fname_str_dbg(smb_fname),
1451 BOOLSTR(fsp->can_read), BOOLSTR(fsp->can_write),
1452 conn->num_files_open));
1455 return NT_STATUS_OK;
1458 /****************************************************************************
1459 Check if we can open a file with a share mode.
1460 Returns True if conflict, False if not.
1461 ****************************************************************************/
1463 static bool share_conflict(struct share_mode_entry *entry,
1464 uint32_t access_mask,
1465 uint32_t share_access)
1467 DEBUG(10,("share_conflict: entry->access_mask = 0x%x, "
1468 "entry->share_access = 0x%x, "
1469 "entry->private_options = 0x%x\n",
1470 (unsigned int)entry->access_mask,
1471 (unsigned int)entry->share_access,
1472 (unsigned int)entry->private_options));
1474 if (server_id_is_disconnected(&entry->pid)) {
1478 DEBUG(10,("share_conflict: access_mask = 0x%x, share_access = 0x%x\n",
1479 (unsigned int)access_mask, (unsigned int)share_access));
1481 if ((entry->access_mask & (FILE_WRITE_DATA|
1485 DELETE_ACCESS)) == 0) {
1486 DEBUG(10,("share_conflict: No conflict due to "
1487 "entry->access_mask = 0x%x\n",
1488 (unsigned int)entry->access_mask ));
1492 if ((access_mask & (FILE_WRITE_DATA|
1496 DELETE_ACCESS)) == 0) {
1497 DEBUG(10,("share_conflict: No conflict due to "
1498 "access_mask = 0x%x\n",
1499 (unsigned int)access_mask ));
1503 #if 1 /* JRA TEST - Superdebug. */
1504 #define CHECK_MASK(num, am, right, sa, share) \
1505 DEBUG(10,("share_conflict: [%d] am (0x%x) & right (0x%x) = 0x%x\n", \
1506 (unsigned int)(num), (unsigned int)(am), \
1507 (unsigned int)(right), (unsigned int)(am)&(right) )); \
1508 DEBUG(10,("share_conflict: [%d] sa (0x%x) & share (0x%x) = 0x%x\n", \
1509 (unsigned int)(num), (unsigned int)(sa), \
1510 (unsigned int)(share), (unsigned int)(sa)&(share) )); \
1511 if (((am) & (right)) && !((sa) & (share))) { \
1512 DEBUG(10,("share_conflict: check %d conflict am = 0x%x, right = 0x%x, \
1513 sa = 0x%x, share = 0x%x\n", (num), (unsigned int)(am), (unsigned int)(right), (unsigned int)(sa), \
1514 (unsigned int)(share) )); \
1518 #define CHECK_MASK(num, am, right, sa, share) \
1519 if (((am) & (right)) && !((sa) & (share))) { \
1520 DEBUG(10,("share_conflict: check %d conflict am = 0x%x, right = 0x%x, \
1521 sa = 0x%x, share = 0x%x\n", (num), (unsigned int)(am), (unsigned int)(right), (unsigned int)(sa), \
1522 (unsigned int)(share) )); \
1527 CHECK_MASK(1, entry->access_mask, FILE_WRITE_DATA | FILE_APPEND_DATA,
1528 share_access, FILE_SHARE_WRITE);
1529 CHECK_MASK(2, access_mask, FILE_WRITE_DATA | FILE_APPEND_DATA,
1530 entry->share_access, FILE_SHARE_WRITE);
1532 CHECK_MASK(3, entry->access_mask, FILE_READ_DATA | FILE_EXECUTE,
1533 share_access, FILE_SHARE_READ);
1534 CHECK_MASK(4, access_mask, FILE_READ_DATA | FILE_EXECUTE,
1535 entry->share_access, FILE_SHARE_READ);
1537 CHECK_MASK(5, entry->access_mask, DELETE_ACCESS,
1538 share_access, FILE_SHARE_DELETE);
1539 CHECK_MASK(6, access_mask, DELETE_ACCESS,
1540 entry->share_access, FILE_SHARE_DELETE);
1542 DEBUG(10,("share_conflict: No conflict.\n"));
1546 #if defined(DEVELOPER)
1547 static void validate_my_share_entries(struct smbd_server_connection *sconn,
1548 const struct file_id id,
1550 struct share_mode_entry *share_entry)
1552 struct server_id self = messaging_server_id(sconn->msg_ctx);
1555 if (!serverid_equal(&self, &share_entry->pid)) {
1559 if (share_entry->op_mid == 0) {
1560 /* INTERNAL_OPEN_ONLY */
1564 if (!is_valid_share_mode_entry(share_entry)) {
1568 fsp = file_find_dif(sconn, id, share_entry->share_file_id);
1570 DBG_ERR("PANIC : %s\n",
1571 share_mode_str(talloc_tos(), num, &id,
1573 smb_panic("validate_my_share_entries: Cannot match a "
1574 "share entry with an open file\n");
1577 if (((uint16_t)fsp->oplock_type) != share_entry->op_type) {
1586 DBG_ERR("validate_my_share_entries: PANIC : %s\n",
1587 share_mode_str(talloc_tos(), num, &id,
1589 str = talloc_asprintf(talloc_tos(),
1590 "validate_my_share_entries: "
1591 "file %s, oplock_type = 0x%x, op_type = 0x%x\n",
1592 fsp->fsp_name->base_name,
1593 (unsigned int)fsp->oplock_type,
1594 (unsigned int)share_entry->op_type );
1600 bool is_stat_open(uint32_t access_mask)
1602 const uint32_t stat_open_bits =
1603 (SYNCHRONIZE_ACCESS|
1604 FILE_READ_ATTRIBUTES|
1605 FILE_WRITE_ATTRIBUTES);
1607 return (((access_mask & stat_open_bits) != 0) &&
1608 ((access_mask & ~stat_open_bits) == 0));
1611 static bool has_delete_on_close(struct share_mode_lock *lck,
1614 struct share_mode_data *d = lck->data;
1617 if (d->num_share_modes == 0) {
1620 if (!is_delete_on_close_set(lck, name_hash)) {
1623 for (i=0; i<d->num_share_modes; i++) {
1624 if (!share_mode_stale_pid(d, i)) {
1631 /****************************************************************************
1632 Deal with share modes
1633 Invariant: Share mode must be locked on entry and exit.
1634 Returns -1 on error, or number of share modes on success (may be zero).
1635 ****************************************************************************/
1637 static NTSTATUS open_mode_check(connection_struct *conn,
1638 struct share_mode_lock *lck,
1639 uint32_t access_mask,
1640 uint32_t share_access)
1644 if(lck->data->num_share_modes == 0) {
1645 return NT_STATUS_OK;
1648 if (is_stat_open(access_mask)) {
1649 /* Stat open that doesn't trigger oplock breaks or share mode
1650 * checks... ! JRA. */
1651 return NT_STATUS_OK;
1655 * Check if the share modes will give us access.
1658 #if defined(DEVELOPER)
1659 for(i = 0; i < lck->data->num_share_modes; i++) {
1660 validate_my_share_entries(conn->sconn, lck->data->id, i,
1661 &lck->data->share_modes[i]);
1665 /* Now we check the share modes, after any oplock breaks. */
1666 for(i = 0; i < lck->data->num_share_modes; i++) {
1668 if (!is_valid_share_mode_entry(&lck->data->share_modes[i])) {
1672 /* someone else has a share lock on it, check to see if we can
1674 if (share_conflict(&lck->data->share_modes[i],
1675 access_mask, share_access)) {
1677 if (share_mode_stale_pid(lck->data, i)) {
1681 return NT_STATUS_SHARING_VIOLATION;
1685 return NT_STATUS_OK;
1689 * Send a break message to the oplock holder and delay the open for
1693 NTSTATUS send_break_message(struct messaging_context *msg_ctx,
1694 const struct file_id *id,
1695 const struct share_mode_entry *exclusive,
1698 struct oplock_break_message msg = {
1700 .share_file_id = exclusive->share_file_id,
1701 .break_to = break_to,
1703 enum ndr_err_code ndr_err;
1708 struct server_id_buf buf;
1709 DBG_DEBUG("Sending break message to %s\n",
1710 server_id_str_buf(exclusive->pid, &buf));
1711 NDR_PRINT_DEBUG(oplock_break_message, &msg);
1714 ndr_err = ndr_push_struct_blob(
1718 (ndr_push_flags_fn_t)ndr_push_oplock_break_message);
1719 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
1720 DBG_WARNING("ndr_push_oplock_break_message failed: %s\n",
1721 ndr_errstr(ndr_err));
1722 return ndr_map_error2ntstatus(ndr_err);
1725 status = messaging_send(
1726 msg_ctx, exclusive->pid, MSG_SMB_BREAK_REQUEST, &blob);
1727 TALLOC_FREE(blob.data);
1728 if (!NT_STATUS_IS_OK(status)) {
1729 DEBUG(3, ("Could not send oplock break message: %s\n",
1730 nt_errstr(status)));
1737 * Do internal consistency checks on the share mode for a file.
1740 static bool validate_oplock_types(struct share_mode_lock *lck)
1742 struct share_mode_data *d = lck->data;
1744 bool ex_or_batch = false;
1745 bool level2 = false;
1746 bool no_oplock = false;
1747 uint32_t num_non_stat_opens = 0;
1750 for (i=0; i<d->num_share_modes; i++) {
1751 struct share_mode_entry *e = &d->share_modes[i];
1753 if (!is_valid_share_mode_entry(e)) {
1757 if (e->op_mid == 0) {
1758 /* INTERNAL_OPEN_ONLY */
1762 if (e->op_type == NO_OPLOCK && is_stat_open(e->access_mask)) {
1763 /* We ignore stat opens in the table - they
1764 always have NO_OPLOCK and never get or
1765 cause breaks. JRA. */
1769 num_non_stat_opens += 1;
1771 if (BATCH_OPLOCK_TYPE(e->op_type)) {
1772 /* batch - can only be one. */
1773 if (share_mode_stale_pid(d, i)) {
1774 DEBUG(10, ("Found stale batch oplock\n"));
1777 if (ex_or_batch || batch || level2 || no_oplock) {
1778 DEBUG(0, ("Bad batch oplock entry %u.",
1785 if (EXCLUSIVE_OPLOCK_TYPE(e->op_type)) {
1786 if (share_mode_stale_pid(d, i)) {
1787 DEBUG(10, ("Found stale duplicate oplock\n"));
1790 /* Exclusive or batch - can only be one. */
1791 if (ex_or_batch || level2 || no_oplock) {
1792 DEBUG(0, ("Bad exclusive or batch oplock "
1793 "entry %u.", (unsigned)i));
1799 if (LEVEL_II_OPLOCK_TYPE(e->op_type)) {
1800 if (batch || ex_or_batch) {
1801 if (share_mode_stale_pid(d, i)) {
1802 DEBUG(10, ("Found stale LevelII "
1806 DEBUG(0, ("Bad levelII oplock entry %u.",
1813 if (e->op_type == NO_OPLOCK) {
1814 if (batch || ex_or_batch) {
1815 if (share_mode_stale_pid(d, i)) {
1816 DEBUG(10, ("Found stale NO_OPLOCK "
1820 DEBUG(0, ("Bad no oplock entry %u.",
1828 remove_stale_share_mode_entries(d);
1830 if ((batch || ex_or_batch) && (num_non_stat_opens != 1)) {
1831 DEBUG(1, ("got batch (%d) or ex (%d) non-exclusively (%d)\n",
1832 (int)batch, (int)ex_or_batch,
1833 (int)d->num_share_modes));
1840 static bool delay_for_oplock(files_struct *fsp,
1842 const struct smb2_lease *lease,
1843 struct share_mode_lock *lck,
1844 bool have_sharing_violation,
1845 uint32_t create_disposition,
1846 bool first_open_attempt)
1848 struct share_mode_data *d = lck->data;
1851 bool will_overwrite;
1853 if ((oplock_request & INTERNAL_OPEN_ONLY) ||
1854 is_stat_open(fsp->access_mask)) {
1858 switch (create_disposition) {
1859 case FILE_SUPERSEDE:
1860 case FILE_OVERWRITE:
1861 case FILE_OVERWRITE_IF:
1862 will_overwrite = true;
1865 will_overwrite = false;
1869 for (i=0; i<d->num_share_modes; i++) {
1870 struct share_mode_entry *e = &d->share_modes[i];
1871 bool e_is_lease = (e->op_type == LEASE_OPLOCK);
1872 uint32_t e_lease_type = get_lease_type(d, e);
1874 uint32_t delay_mask = 0;
1875 bool lease_is_breaking = false;
1880 if (lease != NULL) {
1881 bool our_lease = smb2_lease_equal(
1882 fsp_client_guid(fsp),
1887 DBG_DEBUG("Ignoring our own lease\n");
1892 status = leases_db_get(
1896 NULL, /* current_state */
1898 NULL, /* breaking_to_requested */
1899 NULL, /* breaking_to_required */
1900 NULL, /* lease_version */
1902 SMB_ASSERT(NT_STATUS_IS_OK(status));
1905 if (have_sharing_violation) {
1906 delay_mask = SMB2_LEASE_HANDLE;
1908 delay_mask = SMB2_LEASE_WRITE;
1911 break_to = e_lease_type & ~delay_mask;
1913 if (will_overwrite) {
1914 break_to &= ~(SMB2_LEASE_HANDLE|SMB2_LEASE_READ);
1917 DEBUG(10, ("entry %u: e_lease_type %u, will_overwrite: %u\n",
1918 (unsigned)i, (unsigned)e_lease_type,
1919 (unsigned)will_overwrite));
1921 if ((e_lease_type & ~break_to) == 0) {
1922 if (lease_is_breaking) {
1928 if (share_mode_stale_pid(d, i)) {
1932 if (will_overwrite) {
1934 * If we break anyway break to NONE directly.
1935 * Otherwise vfs_set_filelen() will trigger the
1938 break_to &= ~(SMB2_LEASE_READ|SMB2_LEASE_WRITE);
1943 * Oplocks only support breaking to R or NONE.
1945 break_to &= ~(SMB2_LEASE_HANDLE|SMB2_LEASE_WRITE);
1948 DEBUG(10, ("breaking from %d to %d\n",
1949 (int)e_lease_type, (int)break_to));
1950 send_break_message(fsp->conn->sconn->msg_ctx, &fsp->file_id,
1952 if (e_lease_type & delay_mask) {
1955 if (lease_is_breaking && !first_open_attempt) {
1963 static bool file_has_brlocks(files_struct *fsp)
1965 struct byte_range_lock *br_lck;
1967 br_lck = brl_get_locks_readonly(fsp);
1971 return (brl_num_locks(br_lck) > 0);
1974 struct fsp_lease *find_fsp_lease(struct files_struct *new_fsp,
1975 const struct smb2_lease_key *key,
1976 uint32_t current_state,
1977 uint16_t lease_version,
1978 uint16_t lease_epoch)
1980 struct files_struct *fsp;
1983 * TODO: Measure how expensive this loop is with thousands of open
1987 for (fsp = file_find_di_first(new_fsp->conn->sconn, new_fsp->file_id);
1989 fsp = file_find_di_next(fsp)) {
1991 if (fsp == new_fsp) {
1994 if (fsp->oplock_type != LEASE_OPLOCK) {
1997 if (smb2_lease_key_equal(&fsp->lease->lease.lease_key, key)) {
1998 fsp->lease->ref_count += 1;
2003 /* Not found - must be leased in another smbd. */
2004 new_fsp->lease = talloc_zero(new_fsp->conn->sconn, struct fsp_lease);
2005 if (new_fsp->lease == NULL) {
2008 new_fsp->lease->ref_count = 1;
2009 new_fsp->lease->sconn = new_fsp->conn->sconn;
2010 new_fsp->lease->lease.lease_key = *key;
2011 new_fsp->lease->lease.lease_state = current_state;
2013 * We internally treat all leases as V2 and update
2014 * the epoch, but when sending breaks it matters if
2015 * the requesting lease was v1 or v2.
2017 new_fsp->lease->lease.lease_version = lease_version;
2018 new_fsp->lease->lease.lease_epoch = lease_epoch;
2019 return new_fsp->lease;
2022 static NTSTATUS try_lease_upgrade(struct files_struct *fsp,
2023 struct share_mode_lock *lck,
2024 const struct GUID *client_guid,
2025 const struct smb2_lease *lease,
2029 uint32_t current_state, breaking_to_requested, breaking_to_required;
2031 uint16_t lease_version, epoch;
2032 uint32_t existing, requested;
2035 status = leases_db_get(
2041 &breaking_to_requested,
2042 &breaking_to_required,
2045 if (!NT_STATUS_IS_OK(status)) {
2049 fsp->lease = find_fsp_lease(
2055 if (fsp->lease == NULL) {
2056 DEBUG(1, ("Did not find existing lease for file %s\n",
2058 return NT_STATUS_NO_MEMORY;
2062 * Upgrade only if the requested lease is a strict upgrade.
2064 existing = current_state;
2065 requested = lease->lease_state;
2068 * Tricky: This test makes sure that "requested" is a
2069 * strict bitwise superset of "existing".
2071 do_upgrade = ((existing & requested) == existing);
2074 * Upgrade only if there's a change.
2076 do_upgrade &= (granted != existing);
2079 * Upgrade only if other leases don't prevent what was asked
2082 do_upgrade &= (granted == requested);
2085 * only upgrade if we are not in breaking state
2087 do_upgrade &= !breaking;
2089 DEBUG(10, ("existing=%"PRIu32", requested=%"PRIu32", "
2090 "granted=%"PRIu32", do_upgrade=%d\n",
2091 existing, requested, granted, (int)do_upgrade));
2094 NTSTATUS set_status;
2096 current_state = granted;
2099 set_status = leases_db_set(
2104 breaking_to_requested,
2105 breaking_to_required,
2109 if (!NT_STATUS_IS_OK(set_status)) {
2110 DBG_DEBUG("leases_db_set failed: %s\n",
2111 nt_errstr(set_status));
2116 fsp_lease_update(lck, fsp_client_guid(fsp), fsp->lease);
2118 return NT_STATUS_OK;
2121 static NTSTATUS grant_new_fsp_lease(struct files_struct *fsp,
2122 struct share_mode_lock *lck,
2123 const struct GUID *client_guid,
2124 const struct smb2_lease *lease,
2127 struct share_mode_data *d = lck->data;
2130 fsp->lease = talloc_zero(fsp->conn->sconn, struct fsp_lease);
2131 if (fsp->lease == NULL) {
2132 return NT_STATUS_INSUFFICIENT_RESOURCES;
2134 fsp->lease->ref_count = 1;
2135 fsp->lease->sconn = fsp->conn->sconn;
2136 fsp->lease->lease.lease_version = lease->lease_version;
2137 fsp->lease->lease.lease_key = lease->lease_key;
2138 fsp->lease->lease.lease_state = granted;
2139 fsp->lease->lease.lease_epoch = lease->lease_epoch + 1;
2141 status = leases_db_add(client_guid,
2144 fsp->lease->lease.lease_state,
2145 fsp->lease->lease.lease_version,
2146 fsp->lease->lease.lease_epoch,
2147 fsp->conn->connectpath,
2148 fsp->fsp_name->base_name,
2149 fsp->fsp_name->stream_name);
2150 if (!NT_STATUS_IS_OK(status)) {
2151 DEBUG(10, ("%s: leases_db_add failed: %s\n", __func__,
2152 nt_errstr(status)));
2153 TALLOC_FREE(fsp->lease);
2154 return NT_STATUS_INSUFFICIENT_RESOURCES;
2159 return NT_STATUS_OK;
2162 static NTSTATUS grant_fsp_lease(struct files_struct *fsp,
2163 struct share_mode_lock *lck,
2164 const struct smb2_lease *lease,
2167 const struct GUID *client_guid = fsp_client_guid(fsp);
2170 status = try_lease_upgrade(fsp, lck, client_guid, lease, granted);
2172 if (NT_STATUS_EQUAL(status, NT_STATUS_NOT_FOUND)) {
2173 status = grant_new_fsp_lease(
2174 fsp, lck, client_guid, lease, granted);
2180 static bool is_same_lease(const files_struct *fsp,
2181 const struct share_mode_data *d,
2182 const struct share_mode_entry *e,
2183 const struct smb2_lease *lease)
2185 if (e->op_type != LEASE_OPLOCK) {
2188 if (lease == NULL) {
2192 return smb2_lease_equal(fsp_client_guid(fsp),
2198 static int map_lease_type_to_oplock(uint32_t lease_type)
2200 int result = NO_OPLOCK;
2202 switch (lease_type) {
2203 case SMB2_LEASE_READ|SMB2_LEASE_WRITE|SMB2_LEASE_HANDLE:
2204 result = BATCH_OPLOCK|EXCLUSIVE_OPLOCK;
2206 case SMB2_LEASE_READ|SMB2_LEASE_WRITE:
2207 result = EXCLUSIVE_OPLOCK;
2209 case SMB2_LEASE_READ|SMB2_LEASE_HANDLE:
2210 case SMB2_LEASE_READ:
2211 result = LEVEL_II_OPLOCK;
2218 static NTSTATUS grant_fsp_oplock_type(struct smb_request *req,
2219 struct files_struct *fsp,
2220 struct share_mode_lock *lck,
2222 struct smb2_lease *lease)
2224 struct share_mode_data *d = lck->data;
2225 bool got_handle_lease = false;
2226 bool got_oplock = false;
2229 const struct GUID *client_guid = NULL;
2230 const struct smb2_lease_key *lease_key = NULL;
2234 if (oplock_request & INTERNAL_OPEN_ONLY) {
2235 /* No oplocks on internal open. */
2236 oplock_request = NO_OPLOCK;
2237 DEBUG(10,("grant_fsp_oplock_type: oplock type 0x%x on file %s\n",
2238 fsp->oplock_type, fsp_str_dbg(fsp)));
2241 if (oplock_request == LEASE_OPLOCK) {
2242 if (lease == NULL) {
2244 * The SMB2 layer should have checked this
2246 return NT_STATUS_INTERNAL_ERROR;
2249 granted = lease->lease_state;
2251 if (lp_kernel_oplocks(SNUM(fsp->conn))) {
2252 DEBUG(10, ("No lease granted because kernel oplocks are enabled\n"));
2253 granted = SMB2_LEASE_NONE;
2255 if ((granted & (SMB2_LEASE_READ|SMB2_LEASE_WRITE)) == 0) {
2256 DEBUG(10, ("No read or write lease requested\n"));
2257 granted = SMB2_LEASE_NONE;
2259 if (granted == SMB2_LEASE_WRITE) {
2260 DEBUG(10, ("pure write lease requested\n"));
2261 granted = SMB2_LEASE_NONE;
2263 if (granted == (SMB2_LEASE_WRITE|SMB2_LEASE_HANDLE)) {
2264 DEBUG(10, ("write and handle lease requested\n"));
2265 granted = SMB2_LEASE_NONE;
2268 granted = map_oplock_to_lease_type(
2269 oplock_request & ~SAMBA_PRIVATE_OPLOCK_MASK);
2272 if (lp_locking(fsp->conn->params) && file_has_brlocks(fsp)) {
2273 DEBUG(10,("grant_fsp_oplock_type: file %s has byte range locks\n",
2275 granted &= ~SMB2_LEASE_READ;
2278 for (i=0; i<d->num_share_modes; i++) {
2279 struct share_mode_entry *e = &d->share_modes[i];
2280 uint32_t e_lease_type;
2282 e_lease_type = get_lease_type(d, e);
2284 if ((granted & SMB2_LEASE_WRITE) &&
2285 !is_same_lease(fsp, d, e, lease) &&
2286 !share_mode_stale_pid(d, i)) {
2288 * Can grant only one writer
2290 granted &= ~SMB2_LEASE_WRITE;
2293 if ((e_lease_type & SMB2_LEASE_HANDLE) && !got_handle_lease &&
2294 !share_mode_stale_pid(d, i)) {
2295 got_handle_lease = true;
2298 if ((e->op_type != LEASE_OPLOCK) && !got_oplock &&
2299 !share_mode_stale_pid(d, i)) {
2304 if ((granted & SMB2_LEASE_READ) && !(granted & SMB2_LEASE_WRITE)) {
2306 (global_client_caps & CAP_LEVEL_II_OPLOCKS) &&
2307 lp_level2_oplocks(SNUM(fsp->conn));
2309 if (!allow_level2) {
2310 granted = SMB2_LEASE_NONE;
2314 if (oplock_request == LEASE_OPLOCK) {
2316 granted &= ~SMB2_LEASE_HANDLE;
2319 fsp->oplock_type = LEASE_OPLOCK;
2321 status = grant_fsp_lease(fsp, lck, lease, granted);
2322 if (!NT_STATUS_IS_OK(status)) {
2326 *lease = fsp->lease->lease;
2328 lease_key = &fsp->lease->lease.lease_key;
2329 client_guid = fsp_client_guid(fsp);
2331 DEBUG(10, ("lease_state=%d\n", lease->lease_state));
2333 if (got_handle_lease) {
2334 granted = SMB2_LEASE_NONE;
2337 fsp->oplock_type = map_lease_type_to_oplock(granted);
2339 status = set_file_oplock(fsp);
2340 if (!NT_STATUS_IS_OK(status)) {
2342 * Could not get the kernel oplock
2344 fsp->oplock_type = NO_OPLOCK;
2348 ok = set_share_mode(
2351 get_current_uid(fsp->conn),
2357 return NT_STATUS_NO_MEMORY;
2360 ok = update_num_read_oplocks(fsp, lck);
2362 del_share_mode(lck, fsp);
2363 return NT_STATUS_INTERNAL_ERROR;
2366 DEBUG(10,("grant_fsp_oplock_type: oplock type 0x%x on file %s\n",
2367 fsp->oplock_type, fsp_str_dbg(fsp)));
2369 return NT_STATUS_OK;
2372 static bool request_timed_out(struct timeval request_time,
2373 struct timeval timeout)
2375 struct timeval now, end_time;
2377 end_time = timeval_sum(&request_time, &timeout);
2378 return (timeval_compare(&end_time, &now) < 0);
2381 static struct deferred_open_record *deferred_open_record_create(
2382 bool delayed_for_oplocks,
2386 struct deferred_open_record *record = NULL;
2388 record = talloc(NULL, struct deferred_open_record);
2389 if (record == NULL) {
2393 *record = (struct deferred_open_record) {
2394 .delayed_for_oplocks = delayed_for_oplocks,
2395 .async_open = async_open,
2402 struct defer_open_state {
2403 struct smbXsrv_connection *xconn;
2407 static void defer_open_done(struct tevent_req *req);
2410 * Defer an open and watch a locking.tdb record
2412 * This defers an open that gets rescheduled once the locking.tdb record watch
2413 * is triggered by a change to the record.
2415 * It is used to defer opens that triggered an oplock break and for the SMB1
2416 * sharing violation delay.
2418 static void defer_open(struct share_mode_lock *lck,
2419 struct timeval request_time,
2420 struct timeval timeout,
2421 struct smb_request *req,
2422 bool delayed_for_oplocks,
2425 struct deferred_open_record *open_rec = NULL;
2426 struct timeval abs_timeout;
2427 struct defer_open_state *watch_state;
2428 struct tevent_req *watch_req;
2431 abs_timeout = timeval_sum(&request_time, &timeout);
2433 DBG_DEBUG("request time [%s] timeout [%s] mid [%" PRIu64 "] "
2434 "delayed_for_oplocks [%s] file_id [%s]\n",
2435 timeval_string(talloc_tos(), &request_time, false),
2436 timeval_string(talloc_tos(), &abs_timeout, false),
2438 delayed_for_oplocks ? "yes" : "no",
2439 file_id_string_tos(&id));
2441 open_rec = deferred_open_record_create(delayed_for_oplocks,
2444 if (open_rec == NULL) {
2446 exit_server("talloc failed");
2449 watch_state = talloc(open_rec, struct defer_open_state);
2450 if (watch_state == NULL) {
2451 exit_server("talloc failed");
2453 watch_state->xconn = req->xconn;
2454 watch_state->mid = req->mid;
2456 DBG_DEBUG("defering mid %" PRIu64 "\n", req->mid);
2458 watch_req = dbwrap_watched_watch_send(watch_state,
2461 (struct server_id){0});
2462 if (watch_req == NULL) {
2463 exit_server("Could not watch share mode record");
2465 tevent_req_set_callback(watch_req, defer_open_done, watch_state);
2467 ok = tevent_req_set_endtime(watch_req, req->sconn->ev_ctx, abs_timeout);
2469 exit_server("tevent_req_set_endtime failed");
2472 ok = push_deferred_open_message_smb(req, request_time, timeout,
2473 open_rec->id, open_rec);
2476 exit_server("push_deferred_open_message_smb failed");
2480 static void defer_open_done(struct tevent_req *req)
2482 struct defer_open_state *state = tevent_req_callback_data(
2483 req, struct defer_open_state);
2487 status = dbwrap_watched_watch_recv(req, NULL, NULL);
2489 if (!NT_STATUS_IS_OK(status)) {
2490 DEBUG(5, ("dbwrap_watched_watch_recv returned %s\n",
2491 nt_errstr(status)));
2493 * Even if it failed, retry anyway. TODO: We need a way to
2494 * tell a re-scheduled open about that error.
2498 DEBUG(10, ("scheduling mid %llu\n", (unsigned long long)state->mid));
2500 ret = schedule_deferred_open_message_smb(state->xconn, state->mid);
2506 * Actually attempt the kernel oplock polling open.
2509 static void kernel_oplock_poll_open_timer(struct tevent_context *ev,
2510 struct tevent_timer *te,
2511 struct timeval current_time,
2515 struct smb_request *req = (struct smb_request *)private_data;
2517 ok = schedule_deferred_open_message_smb(req->xconn, req->mid);
2519 exit_server("schedule_deferred_open_message_smb failed");
2521 DBG_DEBUG("kernel_oplock_poll_open_timer fired. Retying open !\n");
2525 * Reschedule an open for 1 second from now, if not timed out.
2527 static void setup_kernel_oplock_poll_open(struct timeval request_time,
2528 struct smb_request *req,
2533 struct deferred_open_record *open_rec = NULL;
2534 /* Maximum wait time. */
2535 struct timeval timeout = timeval_set(OPLOCK_BREAK_TIMEOUT*2, 0);
2537 if (request_timed_out(request_time, timeout)) {
2541 open_rec = deferred_open_record_create(false, false, id);
2542 if (open_rec == NULL) {
2543 exit_server("talloc failed");
2546 ok = push_deferred_open_message_smb(req,
2552 exit_server("push_deferred_open_message_smb failed");
2556 * As this timer event is owned by req, it will
2557 * disappear if req it talloc_freed.
2559 open_rec->te = tevent_add_timer(req->sconn->ev_ctx,
2561 timeval_current_ofs(1, 0),
2562 kernel_oplock_poll_open_timer,
2564 if (open_rec->te == NULL) {
2565 exit_server("tevent_add_timer failed");
2568 DBG_DEBUG("poll request time [%s] mid [%" PRIu64 "] file_id [%s]\n",
2569 timeval_string(talloc_tos(), &request_time, false),
2571 file_id_string_tos(&id));
2574 /****************************************************************************
2575 On overwrite open ensure that the attributes match.
2576 ****************************************************************************/
2578 static bool open_match_attributes(connection_struct *conn,
2579 uint32_t old_dos_attr,
2580 uint32_t new_dos_attr,
2581 mode_t new_unx_mode,
2582 mode_t *returned_unx_mode)
2584 uint32_t noarch_old_dos_attr, noarch_new_dos_attr;
2586 noarch_old_dos_attr = (old_dos_attr & ~FILE_ATTRIBUTE_ARCHIVE);
2587 noarch_new_dos_attr = (new_dos_attr & ~FILE_ATTRIBUTE_ARCHIVE);
2589 if((noarch_old_dos_attr == 0 && noarch_new_dos_attr != 0) ||
2590 (noarch_old_dos_attr != 0 && ((noarch_old_dos_attr & noarch_new_dos_attr) == noarch_old_dos_attr))) {
2591 *returned_unx_mode = new_unx_mode;
2593 *returned_unx_mode = (mode_t)0;
2596 DEBUG(10,("open_match_attributes: old_dos_attr = 0x%x, "
2597 "new_dos_attr = 0x%x "
2598 "returned_unx_mode = 0%o\n",
2599 (unsigned int)old_dos_attr,
2600 (unsigned int)new_dos_attr,
2601 (unsigned int)*returned_unx_mode ));
2603 /* If we're mapping SYSTEM and HIDDEN ensure they match. */
2604 if (lp_map_system(SNUM(conn)) || lp_store_dos_attributes(SNUM(conn))) {
2605 if ((old_dos_attr & FILE_ATTRIBUTE_SYSTEM) &&
2606 !(new_dos_attr & FILE_ATTRIBUTE_SYSTEM)) {
2610 if (lp_map_hidden(SNUM(conn)) || lp_store_dos_attributes(SNUM(conn))) {
2611 if ((old_dos_attr & FILE_ATTRIBUTE_HIDDEN) &&
2612 !(new_dos_attr & FILE_ATTRIBUTE_HIDDEN)) {
2619 /****************************************************************************
2620 Special FCB or DOS processing in the case of a sharing violation.
2621 Try and find a duplicated file handle.
2622 ****************************************************************************/
2624 static NTSTATUS fcb_or_dos_open(struct smb_request *req,
2625 connection_struct *conn,
2626 files_struct *fsp_to_dup_into,
2627 const struct smb_filename *smb_fname,
2631 uint32_t access_mask,
2632 uint32_t share_access,
2633 uint32_t create_options)
2637 DEBUG(5,("fcb_or_dos_open: attempting old open semantics for "
2638 "file %s.\n", smb_fname_str_dbg(smb_fname)));
2640 for(fsp = file_find_di_first(conn->sconn, id); fsp;
2641 fsp = file_find_di_next(fsp)) {
2643 DEBUG(10,("fcb_or_dos_open: checking file %s, fd = %d, "
2644 "vuid = %llu, file_pid = %u, private_options = 0x%x "
2645 "access_mask = 0x%x\n", fsp_str_dbg(fsp),
2646 fsp->fh->fd, (unsigned long long)fsp->vuid,
2647 (unsigned int)fsp->file_pid,
2648 (unsigned int)fsp->fh->private_options,
2649 (unsigned int)fsp->access_mask ));
2651 if (fsp != fsp_to_dup_into &&
2652 fsp->fh->fd != -1 &&
2653 fsp->vuid == vuid &&
2654 fsp->file_pid == file_pid &&
2655 (fsp->fh->private_options & (NTCREATEX_OPTIONS_PRIVATE_DENY_DOS |
2656 NTCREATEX_OPTIONS_PRIVATE_DENY_FCB)) &&
2657 (fsp->access_mask & FILE_WRITE_DATA) &&
2658 strequal(fsp->fsp_name->base_name, smb_fname->base_name) &&
2659 strequal(fsp->fsp_name->stream_name,
2660 smb_fname->stream_name)) {
2661 DEBUG(10,("fcb_or_dos_open: file match\n"));
2667 return NT_STATUS_NOT_FOUND;
2670 /* quite an insane set of semantics ... */
2671 if (is_executable(smb_fname->base_name) &&
2672 (fsp->fh->private_options & NTCREATEX_OPTIONS_PRIVATE_DENY_DOS)) {
2673 DEBUG(10,("fcb_or_dos_open: file fail due to is_executable.\n"));
2674 return NT_STATUS_INVALID_PARAMETER;
2677 /* We need to duplicate this fsp. */
2678 return dup_file_fsp(req, fsp, access_mask, share_access,
2679 create_options, fsp_to_dup_into);
2682 static void schedule_defer_open(struct share_mode_lock *lck,
2684 struct timeval request_time,
2685 struct smb_request *req)
2687 /* This is a relative time, added to the absolute
2688 request_time value to get the absolute timeout time.
2689 Note that if this is the second or greater time we enter
2690 this codepath for this particular request mid then
2691 request_time is left as the absolute time of the *first*
2692 time this request mid was processed. This is what allows
2693 the request to eventually time out. */
2695 struct timeval timeout;
2697 /* Normally the smbd we asked should respond within
2698 * OPLOCK_BREAK_TIMEOUT seconds regardless of whether
2699 * the client did, give twice the timeout as a safety
2700 * measure here in case the other smbd is stuck
2701 * somewhere else. */
2703 timeout = timeval_set(OPLOCK_BREAK_TIMEOUT*2, 0);
2705 if (request_timed_out(request_time, timeout)) {
2709 defer_open(lck, request_time, timeout, req, true, id);
2712 /****************************************************************************
2713 Reschedule an open call that went asynchronous.
2714 ****************************************************************************/
2716 static void schedule_async_open_timer(struct tevent_context *ev,
2717 struct tevent_timer *te,
2718 struct timeval current_time,
2721 exit_server("async open timeout");
2724 static void schedule_async_open(struct timeval request_time,
2725 struct smb_request *req)
2727 struct deferred_open_record *open_rec = NULL;
2728 struct timeval timeout = timeval_set(20, 0);
2731 if (request_timed_out(request_time, timeout)) {
2735 open_rec = deferred_open_record_create(false, true, (struct file_id){0});
2736 if (open_rec == NULL) {
2737 exit_server("deferred_open_record_create failed");
2740 ok = push_deferred_open_message_smb(req, request_time, timeout,
2741 (struct file_id){0}, open_rec);
2743 exit_server("push_deferred_open_message_smb failed");
2746 open_rec->te = tevent_add_timer(req->sconn->ev_ctx,
2748 timeval_current_ofs(20, 0),
2749 schedule_async_open_timer,
2751 if (open_rec->te == NULL) {
2752 exit_server("tevent_add_timer failed");
2756 /****************************************************************************
2757 Work out what access_mask to use from what the client sent us.
2758 ****************************************************************************/
2760 static NTSTATUS smbd_calculate_maximum_allowed_access(
2761 connection_struct *conn,
2762 const struct smb_filename *smb_fname,
2764 uint32_t *p_access_mask)
2766 struct security_descriptor *sd;
2767 uint32_t access_granted;
2770 if (!use_privs && (get_current_uid(conn) == (uid_t)0)) {
2771 *p_access_mask |= FILE_GENERIC_ALL;
2772 return NT_STATUS_OK;
2775 status = SMB_VFS_GET_NT_ACL(conn, smb_fname,
2781 if (NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
2783 * File did not exist
2785 *p_access_mask = FILE_GENERIC_ALL;
2786 return NT_STATUS_OK;
2788 if (!NT_STATUS_IS_OK(status)) {
2789 DEBUG(10,("Could not get acl on file %s: %s\n",
2790 smb_fname_str_dbg(smb_fname),
2791 nt_errstr(status)));
2792 return NT_STATUS_ACCESS_DENIED;
2796 * If we can access the path to this file, by
2797 * default we have FILE_READ_ATTRIBUTES from the
2798 * containing directory. See the section:
2799 * "Algorithm to Check Access to an Existing File"
2802 * se_file_access_check()
2803 * also takes care of owner WRITE_DAC and READ_CONTROL.
2805 status = se_file_access_check(sd,
2806 get_current_nttok(conn),
2808 (*p_access_mask & ~FILE_READ_ATTRIBUTES),
2813 if (!NT_STATUS_IS_OK(status)) {
2814 DEBUG(10, ("Access denied on file %s: "
2815 "when calculating maximum access\n",
2816 smb_fname_str_dbg(smb_fname)));
2817 return NT_STATUS_ACCESS_DENIED;
2819 *p_access_mask = (access_granted | FILE_READ_ATTRIBUTES);
2821 if (!(access_granted & DELETE_ACCESS)) {
2822 if (can_delete_file_in_directory(conn, smb_fname)) {
2823 *p_access_mask |= DELETE_ACCESS;
2827 return NT_STATUS_OK;
2830 NTSTATUS smbd_calculate_access_mask(connection_struct *conn,
2831 const struct smb_filename *smb_fname,
2833 uint32_t access_mask,
2834 uint32_t *access_mask_out)
2837 uint32_t orig_access_mask = access_mask;
2838 uint32_t rejected_share_access;
2840 if (access_mask & SEC_MASK_INVALID) {
2841 DBG_DEBUG("access_mask [%8x] contains invalid bits\n",
2843 return NT_STATUS_ACCESS_DENIED;
2847 * Convert GENERIC bits to specific bits.
2850 se_map_generic(&access_mask, &file_generic_mapping);
2852 /* Calculate MAXIMUM_ALLOWED_ACCESS if requested. */
2853 if (access_mask & MAXIMUM_ALLOWED_ACCESS) {
2855 status = smbd_calculate_maximum_allowed_access(
2856 conn, smb_fname, use_privs, &access_mask);
2858 if (!NT_STATUS_IS_OK(status)) {
2862 access_mask &= conn->share_access;
2865 rejected_share_access = access_mask & ~(conn->share_access);
2867 if (rejected_share_access) {
2868 DEBUG(10, ("smbd_calculate_access_mask: Access denied on "
2869 "file %s: rejected by share access mask[0x%08X] "
2870 "orig[0x%08X] mapped[0x%08X] reject[0x%08X]\n",
2871 smb_fname_str_dbg(smb_fname),
2873 orig_access_mask, access_mask,
2874 rejected_share_access));
2875 return NT_STATUS_ACCESS_DENIED;
2878 *access_mask_out = access_mask;
2879 return NT_STATUS_OK;
2882 /****************************************************************************
2883 Remove the deferred open entry under lock.
2884 ****************************************************************************/
2886 /****************************************************************************
2887 Return true if this is a state pointer to an asynchronous create.
2888 ****************************************************************************/
2890 bool is_deferred_open_async(const struct deferred_open_record *rec)
2892 return rec->async_open;
2895 static bool clear_ads(uint32_t create_disposition)
2899 switch (create_disposition) {
2900 case FILE_SUPERSEDE:
2901 case FILE_OVERWRITE_IF:
2902 case FILE_OVERWRITE:
2911 static int disposition_to_open_flags(uint32_t create_disposition)
2916 * Currently we're using FILE_SUPERSEDE as the same as
2917 * FILE_OVERWRITE_IF but they really are
2918 * different. FILE_SUPERSEDE deletes an existing file
2919 * (requiring delete access) then recreates it.
2922 switch (create_disposition) {
2923 case FILE_SUPERSEDE:
2924 case FILE_OVERWRITE_IF:
2926 * If file exists replace/overwrite. If file doesn't
2929 ret = O_CREAT|O_TRUNC;
2934 * If file exists open. If file doesn't exist error.
2939 case FILE_OVERWRITE:
2941 * If file exists overwrite. If file doesn't exist
2949 * If file exists error. If file doesn't exist create.
2951 ret = O_CREAT|O_EXCL;
2956 * If file exists open. If file doesn't exist create.
2964 static int calculate_open_access_flags(uint32_t access_mask,
2965 uint32_t private_flags)
2967 bool need_write, need_read;
2970 * Note that we ignore the append flag as append does not
2971 * mean the same thing under DOS and Unix.
2974 need_write = (access_mask & (FILE_WRITE_DATA | FILE_APPEND_DATA));
2979 /* DENY_DOS opens are always underlying read-write on the
2980 file handle, no matter what the requested access mask
2984 ((private_flags & NTCREATEX_OPTIONS_PRIVATE_DENY_DOS) ||
2985 access_mask & (FILE_READ_ATTRIBUTES|FILE_READ_DATA|
2986 FILE_READ_EA|FILE_EXECUTE));
2994 /****************************************************************************
2995 Open a file with a share mode. Passed in an already created files_struct *.
2996 ****************************************************************************/
2998 static NTSTATUS open_file_ntcreate(connection_struct *conn,
2999 struct smb_request *req,
3000 uint32_t access_mask, /* access bits (FILE_READ_DATA etc.) */
3001 uint32_t share_access, /* share constants (FILE_SHARE_READ etc) */
3002 uint32_t create_disposition, /* FILE_OPEN_IF etc. */
3003 uint32_t create_options, /* options such as delete on close. */
3004 uint32_t new_dos_attributes, /* attributes used for new file. */
3005 int oplock_request, /* internal Samba oplock codes. */
3006 struct smb2_lease *lease,
3007 /* Information (FILE_EXISTS etc.) */
3008 uint32_t private_flags, /* Samba specific flags. */
3012 struct smb_filename *smb_fname = fsp->fsp_name;
3015 bool file_existed = VALID_STAT(smb_fname->st);
3016 bool def_acl = False;
3017 bool posix_open = False;
3018 bool new_file_created = False;
3019 bool first_open_attempt = true;
3020 NTSTATUS fsp_open = NT_STATUS_ACCESS_DENIED;
3021 mode_t new_unx_mode = (mode_t)0;
3022 mode_t unx_mode = (mode_t)0;
3024 uint32_t existing_dos_attributes = 0;
3025 struct timeval request_time = timeval_zero();
3026 struct share_mode_lock *lck = NULL;
3027 uint32_t open_access_mask = access_mask;
3030 SMB_STRUCT_STAT saved_stat = smb_fname->st;
3031 struct timespec old_write_time;
3034 if (conn->printer) {
3036 * Printers are handled completely differently.
3037 * Most of the passed parameters are ignored.
3041 *pinfo = FILE_WAS_CREATED;
3044 DEBUG(10, ("open_file_ntcreate: printer open fname=%s\n",
3045 smb_fname_str_dbg(smb_fname)));
3048 DEBUG(0,("open_file_ntcreate: printer open without "
3049 "an SMB request!\n"));
3050 return NT_STATUS_INTERNAL_ERROR;
3053 return print_spool_open(fsp, smb_fname->base_name,
3057 if (!parent_dirname(talloc_tos(), smb_fname->base_name, &parent_dir,
3059 return NT_STATUS_NO_MEMORY;
3062 if (new_dos_attributes & FILE_FLAG_POSIX_SEMANTICS) {
3064 unx_mode = (mode_t)(new_dos_attributes & ~FILE_FLAG_POSIX_SEMANTICS);
3065 new_dos_attributes = 0;
3067 /* Windows allows a new file to be created and
3068 silently removes a FILE_ATTRIBUTE_DIRECTORY
3069 sent by the client. Do the same. */
3071 new_dos_attributes &= ~FILE_ATTRIBUTE_DIRECTORY;
3073 /* We add FILE_ATTRIBUTE_ARCHIVE to this as this mode is only used if the file is
3075 unx_mode = unix_mode(conn, new_dos_attributes | FILE_ATTRIBUTE_ARCHIVE,
3076 smb_fname, parent_dir);
3079 DEBUG(10, ("open_file_ntcreate: fname=%s, dos_attrs=0x%x "
3080 "access_mask=0x%x share_access=0x%x "
3081 "create_disposition = 0x%x create_options=0x%x "
3082 "unix mode=0%o oplock_request=%d private_flags = 0x%x\n",
3083 smb_fname_str_dbg(smb_fname), new_dos_attributes,
3084 access_mask, share_access, create_disposition,
3085 create_options, (unsigned int)unx_mode, oplock_request,
3086 (unsigned int)private_flags));
3089 /* Ensure req == NULL means INTERNAL_OPEN_ONLY */
3090 SMB_ASSERT(((oplock_request & INTERNAL_OPEN_ONLY) != 0));
3092 /* And req != NULL means no INTERNAL_OPEN_ONLY */
3093 SMB_ASSERT(((oplock_request & INTERNAL_OPEN_ONLY) == 0));
3097 * Only non-internal opens can be deferred at all
3101 struct deferred_open_record *open_rec;
3102 if (get_deferred_open_message_state(req,
3105 /* Remember the absolute time of the original
3106 request with this mid. We'll use it later to
3107 see if this has timed out. */
3109 /* If it was an async create retry, the file
3112 if (is_deferred_open_async(open_rec)) {
3113 SET_STAT_INVALID(smb_fname->st);
3114 file_existed = false;
3117 /* Ensure we don't reprocess this message. */
3118 remove_deferred_open_message_smb(req->xconn, req->mid);
3120 first_open_attempt = false;
3125 new_dos_attributes &= SAMBA_ATTRIBUTES_MASK;
3128 * Only use strored DOS attributes for checks
3129 * against requested attributes (below via
3130 * open_match_attributes()), cf bug #11992
3131 * for details. -slow
3135 status = SMB_VFS_GET_DOS_ATTRIBUTES(conn, smb_fname, &attr);
3136 if (NT_STATUS_IS_OK(status)) {
3137 existing_dos_attributes = attr;
3142 /* ignore any oplock requests if oplocks are disabled */
3143 if (!lp_oplocks(SNUM(conn)) ||
3144 IS_VETO_OPLOCK_PATH(conn, smb_fname->base_name)) {
3145 /* Mask off everything except the private Samba bits. */
3146 oplock_request &= SAMBA_PRIVATE_OPLOCK_MASK;
3149 /* this is for OS/2 long file names - say we don't support them */
3150 if (req != NULL && !req->posix_pathnames &&
3151 strstr(smb_fname->base_name,".+,;=[].")) {
3152 /* OS/2 Workplace shell fix may be main code stream in a later
3154 DEBUG(5,("open_file_ntcreate: OS/2 long filenames are not "
3156 if (use_nt_status()) {
3157 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3159 return NT_STATUS_DOS(ERRDOS, ERRcannotopen);
3162 switch( create_disposition ) {
3164 /* If file exists open. If file doesn't exist error. */
3165 if (!file_existed) {
3166 DEBUG(5,("open_file_ntcreate: FILE_OPEN "
3167 "requested for file %s and file "
3169 smb_fname_str_dbg(smb_fname)));
3171 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3175 case FILE_OVERWRITE:
3176 /* If file exists overwrite. If file doesn't exist
3178 if (!file_existed) {
3179 DEBUG(5,("open_file_ntcreate: FILE_OVERWRITE "
3180 "requested for file %s and file "
3182 smb_fname_str_dbg(smb_fname) ));
3184 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3189 /* If file exists error. If file doesn't exist
3192 DEBUG(5,("open_file_ntcreate: FILE_CREATE "
3193 "requested for file %s and file "
3194 "already exists.\n",
3195 smb_fname_str_dbg(smb_fname)));
3196 if (S_ISDIR(smb_fname->st.st_ex_mode)) {
3201 return map_nt_error_from_unix(errno);
3205 case FILE_SUPERSEDE:
3206 case FILE_OVERWRITE_IF:
3210 return NT_STATUS_INVALID_PARAMETER;
3213 flags2 = disposition_to_open_flags(create_disposition);
3215 /* We only care about matching attributes on file exists and
3218 if (!posix_open && file_existed &&
3219 ((create_disposition == FILE_OVERWRITE) ||
3220 (create_disposition == FILE_OVERWRITE_IF))) {
3221 if (!open_match_attributes(conn, existing_dos_attributes,
3223 unx_mode, &new_unx_mode)) {
3224 DEBUG(5,("open_file_ntcreate: attributes mismatch "
3225 "for file %s (%x %x) (0%o, 0%o)\n",
3226 smb_fname_str_dbg(smb_fname),
3227 existing_dos_attributes,
3229 (unsigned int)smb_fname->st.st_ex_mode,
3230 (unsigned int)unx_mode ));
3232 return NT_STATUS_ACCESS_DENIED;
3236 status = smbd_calculate_access_mask(conn, smb_fname,
3240 if (!NT_STATUS_IS_OK(status)) {
3241 DEBUG(10, ("open_file_ntcreate: smbd_calculate_access_mask "
3242 "on file %s returned %s\n",
3243 smb_fname_str_dbg(smb_fname), nt_errstr(status)));
3247 open_access_mask = access_mask;
3249 if (flags2 & O_TRUNC) {
3250 open_access_mask |= FILE_WRITE_DATA; /* This will cause oplock breaks. */
3253 DEBUG(10, ("open_file_ntcreate: fname=%s, after mapping "
3254 "access_mask=0x%x\n", smb_fname_str_dbg(smb_fname),
3258 * Note that we ignore the append flag as append does not
3259 * mean the same thing under DOS and Unix.
3262 flags = calculate_open_access_flags(access_mask, private_flags);
3265 * Currently we only look at FILE_WRITE_THROUGH for create options.
3269 if ((create_options & FILE_WRITE_THROUGH) && lp_strict_sync(SNUM(conn))) {
3274 if (posix_open && (access_mask & FILE_APPEND_DATA)) {
3278 if (!posix_open && !CAN_WRITE(conn)) {
3280 * We should really return a permission denied error if either
3281 * O_CREAT or O_TRUNC are set, but for compatibility with
3282 * older versions of Samba we just AND them out.
3284 flags2 &= ~(O_CREAT|O_TRUNC);
3287 if (lp_kernel_oplocks(SNUM(conn))) {
3289 * With kernel oplocks the open breaking an oplock
3290 * blocks until the oplock holder has given up the
3291 * oplock or closed the file. We prevent this by always
3292 * trying to open the file with O_NONBLOCK (see "man
3295 * If a process that doesn't use the smbd open files
3296 * database or communication methods holds a kernel
3297 * oplock we must periodically poll for available open
3300 flags2 |= O_NONBLOCK;
3304 * Ensure we can't write on a read-only share or file.
3307 if (flags != O_RDONLY && file_existed &&
3308 (!CAN_WRITE(conn) || IS_DOS_READONLY(existing_dos_attributes))) {
3309 DEBUG(5,("open_file_ntcreate: write access requested for "
3310 "file %s on read only %s\n",
3311 smb_fname_str_dbg(smb_fname),
3312 !CAN_WRITE(conn) ? "share" : "file" ));
3314 return NT_STATUS_ACCESS_DENIED;
3317 fsp->file_id = vfs_file_id_from_sbuf(conn, &smb_fname->st);
3318 fsp->share_access = share_access;
3319 fsp->fh->private_options = private_flags;
3320 fsp->access_mask = open_access_mask; /* We change this to the
3321 * requested access_mask after
3322 * the open is done. */
3324 fsp->posix_flags |= FSP_POSIX_FLAGS_ALL;
3327 if (timeval_is_zero(&request_time)) {
3328 request_time = fsp->open_time;
3331 if ((create_options & FILE_DELETE_ON_CLOSE) &&
3332 (flags2 & O_CREAT) &&
3334 /* Delete on close semantics for new files. */
3335 status = can_set_delete_on_close(fsp,
3336 new_dos_attributes);
3337 if (!NT_STATUS_IS_OK(status)) {
3344 * Ensure we pay attention to default ACLs on directories if required.
3347 if ((flags2 & O_CREAT) && lp_inherit_acls(SNUM(conn)) &&
3348 (def_acl = directory_has_default_acl(conn, parent_dir))) {
3349 unx_mode = (0777 & lp_create_mask(SNUM(conn)));
3352 DEBUG(4,("calling open_file with flags=0x%X flags2=0x%X mode=0%o, "
3353 "access_mask = 0x%x, open_access_mask = 0x%x\n",
3354 (unsigned int)flags, (unsigned int)flags2,
3355 (unsigned int)unx_mode, (unsigned int)access_mask,
3356 (unsigned int)open_access_mask));
3358 fsp_open = open_file(fsp, conn, req, parent_dir,
3359 flags|flags2, unx_mode, access_mask,
3360 open_access_mask, &new_file_created);
3362 if (NT_STATUS_EQUAL(fsp_open, NT_STATUS_NETWORK_BUSY)) {
3366 * This handles the kernel oplock case:
3368 * the file has an active kernel oplock and the open() returned
3369 * EWOULDBLOCK/EAGAIN which maps to NETWORK_BUSY.
3371 * "Samba locking.tdb oplocks" are handled below after acquiring
3372 * the sharemode lock with get_share_mode_lock().
3374 if (file_existed && S_ISFIFO(fsp->fsp_name->st.st_ex_mode)) {
3375 DEBUG(10, ("FIFO busy\n"));
3376 return NT_STATUS_NETWORK_BUSY;
3379 DEBUG(10, ("Internal open busy\n"));
3380 return NT_STATUS_NETWORK_BUSY;
3384 * From here on we assume this is an oplock break triggered
3387 lck = get_existing_share_mode_lock(talloc_tos(), fsp->file_id);
3390 * No oplock from Samba around. Set up a poll every 1
3391 * second to retry a non-blocking open until the time
3394 setup_kernel_oplock_poll_open(request_time,
3397 DBG_DEBUG("No Samba oplock around after EWOULDBLOCK. "
3398 "Retrying with poll\n");
3399 return NT_STATUS_SHARING_VIOLATION;
3402 if (!validate_oplock_types(lck)) {
3403 smb_panic("validate_oplock_types failed");
3406 delay = delay_for_oplock(fsp, 0, lease, lck, false,
3408 first_open_attempt);
3410 schedule_defer_open(lck, fsp->file_id, request_time,
3413 DEBUG(10, ("Sent oplock break request to kernel "
3414 "oplock holder\n"));
3415 return NT_STATUS_SHARING_VIOLATION;
3419 * No oplock from Samba around. Set up a poll every 1
3420 * second to retry a non-blocking open until the time
3423 setup_kernel_oplock_poll_open(request_time, req, fsp->file_id);
3426 DBG_DEBUG("No Samba oplock around after EWOULDBLOCK. "
3427 "Retrying with poll\n");
3428 return NT_STATUS_SHARING_VIOLATION;
3431 if (!NT_STATUS_IS_OK(fsp_open)) {
3432 if (NT_STATUS_EQUAL(fsp_open, NT_STATUS_RETRY)) {
3433 schedule_async_open(request_time, req);
3438 if (new_file_created) {
3440 * As we atomically create using O_CREAT|O_EXCL,
3441 * then if new_file_created is true, then
3442 * file_existed *MUST* have been false (even
3443 * if the file was previously detected as being
3446 file_existed = false;
3449 if (file_existed && !check_same_dev_ino(&saved_stat, &smb_fname->st)) {
3451 * The file did exist, but some other (local or NFS)
3452 * process either renamed/unlinked and re-created the
3453 * file with different dev/ino after we walked the path,
3454 * but before we did the open. We could retry the
3455 * open but it's a rare enough case it's easier to
3456 * just fail the open to prevent creating any problems
3457 * in the open file db having the wrong dev/ino key.
3460 DBG_WARNING("file %s - dev/ino mismatch. "
3461 "Old (dev=%ju, ino=%ju). "
3462 "New (dev=%ju, ino=%ju). Failing open "
3463 "with NT_STATUS_ACCESS_DENIED.\n",
3464 smb_fname_str_dbg(smb_fname),
3465 (uintmax_t)saved_stat.st_ex_dev,
3466 (uintmax_t)saved_stat.st_ex_ino,
3467 (uintmax_t)smb_fname->st.st_ex_dev,
3468 (uintmax_t)smb_fname->st.st_ex_ino);
3469 return NT_STATUS_ACCESS_DENIED;
3472 old_write_time = smb_fname->st.st_ex_mtime;
3475 * Deal with the race condition where two smbd's detect the
3476 * file doesn't exist and do the create at the same time. One
3477 * of them will win and set a share mode, the other (ie. this
3478 * one) should check if the requested share mode for this
3479 * create is allowed.
3483 * Now the file exists and fsp is successfully opened,
3484 * fsp->dev and fsp->inode are valid and should replace the
3485 * dev=0,inode=0 from a non existent file. Spotted by
3486 * Nadav Danieli <nadavd@exanet.com>. JRA.
3491 lck = get_share_mode_lock(talloc_tos(), id,
3493 smb_fname, &old_write_time);
3496 DEBUG(0, ("open_file_ntcreate: Could not get share "
3497 "mode lock for %s\n",
3498 smb_fname_str_dbg(smb_fname)));
3500 return NT_STATUS_SHARING_VIOLATION;
3503 /* Get the types we need to examine. */
3504 if (!validate_oplock_types(lck)) {
3505 smb_panic("validate_oplock_types failed");
3508 if (has_delete_on_close(lck, fsp->name_hash)) {
3511 return NT_STATUS_DELETE_PENDING;
3514 status = open_mode_check(conn, lck,
3515 access_mask, share_access);
3517 if (NT_STATUS_EQUAL(status, NT_STATUS_SHARING_VIOLATION) ||
3518 (lck->data->num_share_modes > 0)) {
3520 * This comes from ancient times out of open_mode_check. I
3521 * have no clue whether this is still necessary. I can't think
3522 * of a case where this would actually matter further down in
3523 * this function. I leave it here for further investigation
3526 file_existed = true;
3531 * Handle oplocks, deferring the request if delay_for_oplock()
3532 * triggered a break message and we have to wait for the break
3536 bool sharing_violation = NT_STATUS_EQUAL(
3537 status, NT_STATUS_SHARING_VIOLATION);
3539 delay = delay_for_oplock(fsp, oplock_request, lease, lck,
3542 first_open_attempt);
3544 schedule_defer_open(lck, fsp->file_id,
3548 return NT_STATUS_SHARING_VIOLATION;
3552 if (!NT_STATUS_IS_OK(status)) {
3553 uint32_t can_access_mask;
3554 bool can_access = True;
3556 SMB_ASSERT(NT_STATUS_EQUAL(status, NT_STATUS_SHARING_VIOLATION));
3558 /* Check if this can be done with the deny_dos and fcb
3561 (NTCREATEX_OPTIONS_PRIVATE_DENY_DOS|
3562 NTCREATEX_OPTIONS_PRIVATE_DENY_FCB)) {
3564 DEBUG(0, ("DOS open without an SMB "
3568 return NT_STATUS_INTERNAL_ERROR;
3571 /* Use the client requested access mask here,
3572 * not the one we open with. */
3573 status = fcb_or_dos_open(req,
3584 if (NT_STATUS_IS_OK(status)) {
3587 *pinfo = FILE_WAS_OPENED;
3589 return NT_STATUS_OK;
3594 * This next line is a subtlety we need for
3595 * MS-Access. If a file open will fail due to share
3596 * permissions and also for security (access) reasons,
3597 * we need to return the access failed error, not the
3598 * share error. We can't open the file due to kernel
3599 * oplock deadlock (it's possible we failed above on
3600 * the open_mode_check()) so use a userspace check.
3603 if (flags & O_RDWR) {
3604 can_access_mask = FILE_READ_DATA|FILE_WRITE_DATA;
3605 } else if (flags & O_WRONLY) {
3606 can_access_mask = FILE_WRITE_DATA;
3608 can_access_mask = FILE_READ_DATA;
3611 if (((can_access_mask & FILE_WRITE_DATA) &&
3612 !CAN_WRITE(conn)) ||
3613 !NT_STATUS_IS_OK(smbd_check_access_rights(conn,
3616 can_access_mask))) {
3621 * If we're returning a share violation, ensure we
3622 * cope with the braindead 1 second delay (SMB1 only).
3625 if (!(oplock_request & INTERNAL_OPEN_ONLY) &&
3626 !conn->sconn->using_smb2 &&
3627 lp_defer_sharing_violations()) {
3628 struct timeval timeout;
3631 /* this is a hack to speed up torture tests
3633 timeout_usecs = lp_parm_int(SNUM(conn),
3634 "smbd","sharedelay",
3635 SHARING_VIOLATION_USEC_WAIT);
3637 /* This is a relative time, added to the absolute
3638 request_time value to get the absolute timeout time.
3639 Note that if this is the second or greater time we enter
3640 this codepath for this particular request mid then
3641 request_time is left as the absolute time of the *first*
3642 time this request mid was processed. This is what allows
3643 the request to eventually time out. */
3645 timeout = timeval_set(0, timeout_usecs);
3647 if (!request_timed_out(request_time, timeout)) {
3648 defer_open(lck, request_time, timeout, req,
3657 * We have detected a sharing violation here
3658 * so return the correct error code
3660 status = NT_STATUS_SHARING_VIOLATION;
3662 status = NT_STATUS_ACCESS_DENIED;
3667 /* Should we atomically (to the client at least) truncate ? */
3668 if ((!new_file_created) &&
3669 (flags2 & O_TRUNC) &&
3670 (!S_ISFIFO(fsp->fsp_name->st.st_ex_mode))) {
3673 ret = SMB_VFS_FTRUNCATE(fsp, 0);
3675 status = map_nt_error_from_unix(errno);
3680 notify_fname(fsp->conn, NOTIFY_ACTION_MODIFIED,
3681 FILE_NOTIFY_CHANGE_SIZE
3682 | FILE_NOTIFY_CHANGE_ATTRIBUTES,
3683 fsp->fsp_name->base_name);
3687 * We have the share entry *locked*.....
3690 /* Delete streams if create_disposition requires it */
3691 if (!new_file_created && clear_ads(create_disposition) &&
3692 !is_ntfs_stream_smb_fname(smb_fname)) {
3693 status = delete_all_streams(conn, smb_fname);
3694 if (!NT_STATUS_IS_OK(status)) {
3701 /* note that we ignore failure for the following. It is
3702 basically a hack for NFS, and NFS will never set one of
3703 these only read them. Nobody but Samba can ever set a deny
3704 mode and we have already checked our more authoritative
3705 locking database for permission to set this deny mode. If
3706 the kernel refuses the operations then the kernel is wrong.
3707 note that GPFS supports it as well - jmcd */
3709 if (fsp->fh->fd != -1 && lp_kernel_share_modes(SNUM(conn))) {
3712 * Beware: streams implementing VFS modules may
3713 * implement streams in a way that fsp will have the
3714 * basefile open in the fsp fd, so lacking a distinct
3715 * fd for the stream kernel_flock will apply on the
3716 * basefile which is wrong. The actual check is
3717 * deffered to the VFS module implementing the
3718 * kernel_flock call.
3720 ret_flock = SMB_VFS_KERNEL_FLOCK(fsp, share_access, access_mask);
3721 if(ret_flock == -1 ){
3726 return NT_STATUS_SHARING_VIOLATION;
3729 fsp->kernel_share_modes_taken = true;
3733 * At this point onwards, we can guarantee that the share entry
3734 * is locked, whether we created the file or not, and that the
3735 * deny mode is compatible with all current opens.
3739 * According to Samba4, SEC_FILE_READ_ATTRIBUTE is always granted,
3740 * but we don't have to store this - just ignore it on access check.
3742 if (conn->sconn->using_smb2) {
3744 * SMB2 doesn't return it (according to Microsoft tests).
3745 * Test Case: TestSuite_ScenarioNo009GrantedAccessTestS0
3746 * File created with access = 0x7 (Read, Write, Delete)
3747 * Query Info on file returns 0x87 (Read, Write, Delete, Read Attributes)
3749 fsp->access_mask = access_mask;
3751 /* But SMB1 does. */
3752 fsp->access_mask = access_mask | FILE_READ_ATTRIBUTES;
3757 * stat opens on existing files don't get oplocks.
3758 * They can get leases.
3760 * Note that we check for stat open on the *open_access_mask*,
3761 * i.e. the access mask we actually used to do the open,
3762 * not the one the client asked for (which is in
3763 * fsp->access_mask). This is due to the fact that
3764 * FILE_OVERWRITE and FILE_OVERWRITE_IF add in O_TRUNC,
3765 * which adds FILE_WRITE_DATA to open_access_mask.
3767 if (is_stat_open(open_access_mask) && lease == NULL) {
3768 oplock_request = NO_OPLOCK;
3772 if (new_file_created) {
3773 info = FILE_WAS_CREATED;
3775 if (flags2 & O_TRUNC) {
3776 info = FILE_WAS_OVERWRITTEN;
3778 info = FILE_WAS_OPENED;
3787 * Setup the oplock info in both the shared memory and
3790 status = grant_fsp_oplock_type(req, fsp, lck, oplock_request, lease);
3791 if (!NT_STATUS_IS_OK(status)) {
3797 /* Handle strange delete on close create semantics. */
3798 if (create_options & FILE_DELETE_ON_CLOSE) {
3799 if (!new_file_created) {
3800 status = can_set_delete_on_close(fsp,
3801 existing_dos_attributes);
3803 if (!NT_STATUS_IS_OK(status)) {
3804 /* Remember to delete the mode we just added. */
3805 del_share_mode(lck, fsp);
3811 /* Note that here we set the *initial* delete on close flag,
3812 not the regular one. The magic gets handled in close. */
3813 fsp->initial_delete_on_close = True;
3816 if (info != FILE_WAS_OPENED) {
3817 /* Overwritten files should be initially set as archive */
3818 if ((info == FILE_WAS_OVERWRITTEN && lp_map_archive(SNUM(conn))) ||
3819 lp_store_dos_attributes(SNUM(conn))) {
3821 if (file_set_dosmode(conn, smb_fname,
3822 new_dos_attributes | FILE_ATTRIBUTE_ARCHIVE,
3823 parent_dir, true) == 0) {
3824 unx_mode = smb_fname->st.st_ex_mode;
3830 /* Determine sparse flag. */
3832 /* POSIX opens are sparse by default. */
3833 fsp->is_sparse = true;
3835 fsp->is_sparse = (file_existed &&
3836 (existing_dos_attributes & FILE_ATTRIBUTE_SPARSE));
3840 * Take care of inherited ACLs on created files - if default ACL not
3844 if (!posix_open && new_file_created && !def_acl) {
3845 if (unx_mode != smb_fname->st.st_ex_mode) {
3846 int ret = SMB_VFS_FCHMOD(fsp, unx_mode);
3848 DBG_INFO("failed to reset "
3849 "attributes of file %s to 0%o\n",
3850 smb_fname_str_dbg(smb_fname),
3851 (unsigned int)unx_mode);
3855 } else if (new_unx_mode) {
3857 * We only get here in the case of:
3859 * a). Not a POSIX open.
3860 * b). File already existed.
3861 * c). File was overwritten.
3862 * d). Requested DOS attributes didn't match
3863 * the DOS attributes on the existing file.
3865 * In that case new_unx_mode has been set
3866 * equal to the calculated mode (including
3867 * possible inheritance of the mode from the
3868 * containing directory).
3870 * Note this mode was calculated with the
3871 * DOS attribute FILE_ATTRIBUTE_ARCHIVE added,
3872 * so the mode change here is suitable for
3873 * an overwritten file.
3876 if (new_unx_mode != smb_fname->st.st_ex_mode) {
3877 int ret = SMB_VFS_FCHMOD(fsp, new_unx_mode);
3879 DBG_INFO("failed to reset "
3880 "attributes of file %s to 0%o\n",
3881 smb_fname_str_dbg(smb_fname),
3882 (unsigned int)new_unx_mode);
3889 * Deal with other opens having a modified write time.
3891 struct timespec write_time = get_share_mode_write_time(lck);
3893 if (!null_timespec(write_time)) {
3894 update_stat_ex_mtime(&fsp->fsp_name->st, write_time);
3900 return NT_STATUS_OK;
3903 static NTSTATUS mkdir_internal(connection_struct *conn,
3904 struct smb_filename *smb_dname,
3905 uint32_t file_attributes)
3908 char *parent_dir = NULL;
3910 bool posix_open = false;
3911 bool need_re_stat = false;
3912 uint32_t access_mask = SEC_DIR_ADD_SUBDIR;
3914 if (!CAN_WRITE(conn) || (access_mask & ~(conn->share_access))) {
3915 DEBUG(5,("mkdir_internal: failing share access "
3916 "%s\n", lp_servicename(talloc_tos(), SNUM(conn))));
3917 return NT_STATUS_ACCESS_DENIED;
3920 if (!parent_dirname(talloc_tos(), smb_dname->base_name, &parent_dir,
3922 return NT_STATUS_NO_MEMORY;
3925 if (file_attributes & FILE_FLAG_POSIX_SEMANTICS) {
3927 mode = (mode_t)(file_attributes & ~FILE_FLAG_POSIX_SEMANTICS);
3929 mode = unix_mode(conn, FILE_ATTRIBUTE_DIRECTORY, smb_dname, parent_dir);
3932 status = check_parent_access(conn,
3935 if(!NT_STATUS_IS_OK(status)) {
3936 DEBUG(5,("mkdir_internal: check_parent_access "
3937 "on directory %s for path %s returned %s\n",
3939 smb_dname->base_name,
3940 nt_errstr(status) ));
3944 if (SMB_VFS_MKDIR(conn, smb_dname, mode) != 0) {
3945 return map_nt_error_from_unix(errno);
3948 /* Ensure we're checking for a symlink here.... */
3949 /* We don't want to get caught by a symlink racer. */
3951 if (SMB_VFS_LSTAT(conn, smb_dname) == -1) {
3952 DEBUG(2, ("Could not stat directory '%s' just created: %s\n",
3953 smb_fname_str_dbg(smb_dname), strerror(errno)));
3954 return map_nt_error_from_unix(errno);
3957 if (!S_ISDIR(smb_dname->st.st_ex_mode)) {
3958 DEBUG(0, ("Directory '%s' just created is not a directory !\n",
3959 smb_fname_str_dbg(smb_dname)));
3960 return NT_STATUS_NOT_A_DIRECTORY;
3963 if (lp_store_dos_attributes(SNUM(conn))) {
3965 file_set_dosmode(conn, smb_dname,
3966 file_attributes | FILE_ATTRIBUTE_DIRECTORY,
3971 if (lp_inherit_permissions(SNUM(conn))) {
3972 inherit_access_posix_acl(conn, parent_dir,
3974 need_re_stat = true;
3979 * Check if high bits should have been set,
3980 * then (if bits are missing): add them.
3981 * Consider bits automagically set by UNIX, i.e. SGID bit from parent
3984 if ((mode & ~(S_IRWXU|S_IRWXG|S_IRWXO)) &&
3985 (mode & ~smb_dname->st.st_ex_mode)) {
3986 SMB_VFS_CHMOD(conn, smb_dname,
3987 (smb_dname->st.st_ex_mode |
3988 (mode & ~smb_dname->st.st_ex_mode)));
3989 need_re_stat = true;
3993 /* Change the owner if required. */
3994 if (lp_inherit_owner(SNUM(conn)) != INHERIT_OWNER_NO) {
3995 change_dir_owner_to_parent(conn, parent_dir,
3998 need_re_stat = true;
4002 if (SMB_VFS_LSTAT(conn, smb_dname) == -1) {
4003 DEBUG(2, ("Could not stat directory '%s' just created: %s\n",
4004 smb_fname_str_dbg(smb_dname), strerror(errno)));
4005 return map_nt_error_from_unix(errno);
4009 notify_fname(conn, NOTIFY_ACTION_ADDED, FILE_NOTIFY_CHANGE_DIR_NAME,
4010 smb_dname->base_name);
4012 return NT_STATUS_OK;
4015 /****************************************************************************
4016 Open a directory from an NT SMB call.
4017 ****************************************************************************/
4019 static NTSTATUS open_directory(connection_struct *conn,
4020 struct smb_request *req,
4021 struct smb_filename *smb_dname,
4022 uint32_t access_mask,
4023 uint32_t share_access,
4024 uint32_t create_disposition,
4025 uint32_t create_options,
4026 uint32_t file_attributes,
4028 files_struct **result)
4030 files_struct *fsp = NULL;
4031 bool dir_existed = VALID_STAT(smb_dname->st) ? True : False;
4032 struct share_mode_lock *lck = NULL;
4034 struct timespec mtimespec;
4038 if (is_ntfs_stream_smb_fname(smb_dname)) {
4039 DEBUG(2, ("open_directory: %s is a stream name!\n",
4040 smb_fname_str_dbg(smb_dname)));
4041 return NT_STATUS_NOT_A_DIRECTORY;
4044 if (!(file_attributes & FILE_FLAG_POSIX_SEMANTICS)) {
4045 /* Ensure we have a directory attribute. */
4046 file_attributes |= FILE_ATTRIBUTE_DIRECTORY;
4049 DEBUG(5,("open_directory: opening directory %s, access_mask = 0x%x, "
4050 "share_access = 0x%x create_options = 0x%x, "
4051 "create_disposition = 0x%x, file_attributes = 0x%x\n",
4052 smb_fname_str_dbg(smb_dname),
4053 (unsigned int)access_mask,
4054 (unsigned int)share_access,
4055 (unsigned int)create_options,
4056 (unsigned int)create_disposition,
4057 (unsigned int)file_attributes));
4059 status = smbd_calculate_access_mask(conn, smb_dname, false,
4060 access_mask, &access_mask);
4061 if (!NT_STATUS_IS_OK(status)) {
4062 DEBUG(10, ("open_directory: smbd_calculate_access_mask "
4063 "on file %s returned %s\n",
4064 smb_fname_str_dbg(smb_dname),
4065 nt_errstr(status)));
4069 if ((access_mask & SEC_FLAG_SYSTEM_SECURITY) &&
4070 !security_token_has_privilege(get_current_nttok(conn),
4071 SEC_PRIV_SECURITY)) {
4072 DEBUG(10, ("open_directory: open on %s "
4073 "failed - SEC_FLAG_SYSTEM_SECURITY denied.\n",
4074 smb_fname_str_dbg(smb_dname)));
4075 return NT_STATUS_PRIVILEGE_NOT_HELD;
4078 switch( create_disposition ) {
4082 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
4085 info = FILE_WAS_OPENED;
4090 /* If directory exists error. If directory doesn't
4094 status = NT_STATUS_OBJECT_NAME_COLLISION;
4095 DEBUG(2, ("open_directory: unable to create "
4096 "%s. Error was %s\n",
4097 smb_fname_str_dbg(smb_dname),
4098 nt_errstr(status)));
4102 status = mkdir_internal(conn, smb_dname,
4105 if (!NT_STATUS_IS_OK(status)) {
4106 DEBUG(2, ("open_directory: unable to create "
4107 "%s. Error was %s\n",
4108 smb_fname_str_dbg(smb_dname),
4109 nt_errstr(status)));
4113 info = FILE_WAS_CREATED;
4118 * If directory exists open. If directory doesn't
4123 status = NT_STATUS_OK;
4124 info = FILE_WAS_OPENED;
4126 status = mkdir_internal(conn, smb_dname,
4129 if (NT_STATUS_IS_OK(status)) {
4130 info = FILE_WAS_CREATED;
4132 /* Cope with create race. */
4133 if (!NT_STATUS_EQUAL(status,
4134 NT_STATUS_OBJECT_NAME_COLLISION)) {
4135 DEBUG(2, ("open_directory: unable to create "
4136 "%s. Error was %s\n",
4137 smb_fname_str_dbg(smb_dname),
4138 nt_errstr(status)));
4143 * If mkdir_internal() returned
4144 * NT_STATUS_OBJECT_NAME_COLLISION
4145 * we still must lstat the path.
4148 if (SMB_VFS_LSTAT(conn, smb_dname)
4150 DEBUG(2, ("Could not stat "
4151 "directory '%s' just "
4156 return map_nt_error_from_unix(
4160 info = FILE_WAS_OPENED;
4166 case FILE_SUPERSEDE:
4167 case FILE_OVERWRITE:
4168 case FILE_OVERWRITE_IF:
4170 DEBUG(5,("open_directory: invalid create_disposition "
4171 "0x%x for directory %s\n",
4172 (unsigned int)create_disposition,
4173 smb_fname_str_dbg(smb_dname)));
4174 return NT_STATUS_INVALID_PARAMETER;
4177 if(!S_ISDIR(smb_dname->st.st_ex_mode)) {
4178 DEBUG(5,("open_directory: %s is not a directory !\n",
4179 smb_fname_str_dbg(smb_dname)));
4180 return NT_STATUS_NOT_A_DIRECTORY;
4183 if (info == FILE_WAS_OPENED) {
4184 status = smbd_check_access_rights(conn,
4188 if (!NT_STATUS_IS_OK(status)) {
4189 DEBUG(10, ("open_directory: smbd_check_access_rights on "
4190 "file %s failed with %s\n",
4191 smb_fname_str_dbg(smb_dname),
4192 nt_errstr(status)));
4197 status = file_new(req, conn, &fsp);
4198 if(!NT_STATUS_IS_OK(status)) {
4203 * Setup the files_struct for it.
4206 fsp->file_id = vfs_file_id_from_sbuf(conn, &smb_dname->st);
4207 fsp->vuid = req ? req->vuid : UID_FIELD_INVALID;
4208 fsp->file_pid = req ? req->smbpid : 0;
4209 fsp->can_lock = False;
4210 fsp->can_read = False;
4211 fsp->can_write = False;
4213 fsp->share_access = share_access;
4214 fsp->fh->private_options = 0;
4216 * According to Samba4, SEC_FILE_READ_ATTRIBUTE is always granted,
4218 fsp->access_mask = access_mask | FILE_READ_ATTRIBUTES;
4219 fsp->print_file = NULL;
4220 fsp->modified = False;
4221 fsp->oplock_type = NO_OPLOCK;
4222 fsp->sent_oplock_break = NO_BREAK_SENT;
4223 fsp->is_directory = True;
4224 if (file_attributes & FILE_FLAG_POSIX_SEMANTICS) {
4225 fsp->posix_flags |= FSP_POSIX_FLAGS_ALL;
4227 status = fsp_set_smb_fname(fsp, smb_dname);
4228 if (!NT_STATUS_IS_OK(status)) {
4229 file_free(req, fsp);
4233 /* Don't store old timestamps for directory
4234 handles in the internal database. We don't
4235 update them in there if new objects
4236 are creaded in the directory. Currently
4237 we only update timestamps on file writes.
4240 ZERO_STRUCT(mtimespec);
4242 if (access_mask & (FILE_LIST_DIRECTORY|
4244 FILE_ADD_SUBDIRECTORY|
4247 FILE_DELETE_CHILD)) {
4249 status = fd_open(conn, fsp, O_RDONLY|O_DIRECTORY, 0);
4251 /* POSIX allows us to open a directory with O_RDONLY. */
4252 status = fd_open(conn, fsp, O_RDONLY, 0);
4254 if (!NT_STATUS_IS_OK(status)) {
4255 DEBUG(5, ("open_directory: Could not open fd for "
4257 smb_fname_str_dbg(smb_dname),
4258 nt_errstr(status)));
4259 file_free(req, fsp);
4264 DEBUG(10, ("Not opening Directory %s\n",
4265 smb_fname_str_dbg(smb_dname)));
4268 status = vfs_stat_fsp(fsp);
4269 if (!NT_STATUS_IS_OK(status)) {
4271 file_free(req, fsp);
4275 if(!S_ISDIR(fsp->fsp_name->st.st_ex_mode)) {
4276 DEBUG(5,("open_directory: %s is not a directory !\n",
4277 smb_fname_str_dbg(smb_dname)));
4279 file_free(req, fsp);
4280 return NT_STATUS_NOT_A_DIRECTORY;
4283 /* Ensure there was no race condition. We need to check
4284 * dev/inode but not permissions, as these can change
4286 if (!check_same_dev_ino(&smb_dname->st, &fsp->fsp_name->st)) {
4287 DEBUG(5,("open_directory: stat struct differs for "
4289 smb_fname_str_dbg(smb_dname)));
4291 file_free(req, fsp);
4292 return NT_STATUS_ACCESS_DENIED;
4295 lck = get_share_mode_lock(talloc_tos(), fsp->file_id,
4296 conn->connectpath, smb_dname,
4300 DEBUG(0, ("open_directory: Could not get share mode lock for "
4301 "%s\n", smb_fname_str_dbg(smb_dname)));
4303 file_free(req, fsp);
4304 return NT_STATUS_SHARING_VIOLATION;
4307 if (has_delete_on_close(lck, fsp->name_hash)) {
4310 file_free(req, fsp);
4311 return NT_STATUS_DELETE_PENDING;
4314 status = open_mode_check(conn, lck,
4315 access_mask, share_access);
4317 if (!NT_STATUS_IS_OK(status)) {
4320 file_free(req, fsp);
4324 ok = set_share_mode(
4327 get_current_uid(conn),
4335 file_free(req, fsp);
4336 return NT_STATUS_NO_MEMORY;
4339 /* For directories the delete on close bit at open time seems
4340 always to be honored on close... See test 19 in Samba4 BASE-DELETE. */
4341 if (create_options & FILE_DELETE_ON_CLOSE) {
4342 status = can_set_delete_on_close(fsp, 0);
4343 if (!NT_STATUS_IS_OK(status) && !NT_STATUS_EQUAL(status, NT_STATUS_DIRECTORY_NOT_EMPTY)) {
4344 del_share_mode(lck, fsp);
4347 file_free(req, fsp);
4351 if (NT_STATUS_IS_OK(status)) {
4352 /* Note that here we set the *initial* delete on close flag,
4353 not the regular one. The magic gets handled in close. */
4354 fsp->initial_delete_on_close = True;
4360 * Deal with other opens having a modified write time. Is this
4361 * possible for directories?
4363 struct timespec write_time = get_share_mode_write_time(lck);
4365 if (!null_timespec(write_time)) {
4366 update_stat_ex_mtime(&fsp->fsp_name->st, write_time);
4377 return NT_STATUS_OK;
4380 NTSTATUS create_directory(connection_struct *conn, struct smb_request *req,
4381 struct smb_filename *smb_dname)
4386 status = SMB_VFS_CREATE_FILE(
4389 0, /* root_dir_fid */
4390 smb_dname, /* fname */
4391 FILE_READ_ATTRIBUTES, /* access_mask */
4392 FILE_SHARE_NONE, /* share_access */
4393 FILE_CREATE, /* create_disposition*/
4394 FILE_DIRECTORY_FILE, /* create_options */
4395 FILE_ATTRIBUTE_DIRECTORY, /* file_attributes */
4396 0, /* oplock_request */
4398 0, /* allocation_size */
4399 0, /* private_flags */
4404 NULL, NULL); /* create context */
4406 if (NT_STATUS_IS_OK(status)) {
4407 close_file(req, fsp, NORMAL_CLOSE);
4413 /****************************************************************************
4414 Receive notification that one of our open files has been renamed by another
4416 ****************************************************************************/
4418 void msg_file_was_renamed(struct messaging_context *msg_ctx,
4421 struct server_id src,
4424 struct file_rename_message *msg = NULL;
4425 enum ndr_err_code ndr_err;
4427 struct smb_filename *smb_fname = NULL;
4428 struct smbd_server_connection *sconn =
4429 talloc_get_type_abort(private_data,
4430 struct smbd_server_connection);
4432 msg = talloc(talloc_tos(), struct file_rename_message);
4434 DBG_WARNING("talloc failed\n");
4438 ndr_err = ndr_pull_struct_blob_all(
4442 (ndr_pull_flags_fn_t)ndr_pull_file_rename_message);
4443 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
4444 DBG_DEBUG("ndr_pull_oplock_break_message failed: %s\n",
4445 ndr_errstr(ndr_err));
4448 if (DEBUGLEVEL >= 10) {
4449 struct server_id_buf buf;
4450 DBG_DEBUG("Got rename message from %s\n",
4451 server_id_str_buf(src, &buf));
4452 NDR_PRINT_DEBUG(file_rename_message, msg);
4455 /* stream_name must always be NULL if there is no stream. */
4456 if ((msg->stream_name != NULL) && (msg->stream_name[0] == '\0')) {
4457 msg->stream_name = NULL;
4460 smb_fname = synthetic_smb_fname(
4461 msg, msg->base_name, msg->stream_name, NULL, 0);
4462 if (smb_fname == NULL) {
4463 DBG_DEBUG("synthetic_smb_fname failed\n");
4467 fsp = file_find_dif(sconn, msg->id, msg->share_file_id);
4469 DBG_DEBUG("fsp not found\n");
4473 if (strcmp(fsp->conn->connectpath, msg->servicepath) == 0) {
4475 DBG_DEBUG("renaming file %s from %s -> %s\n",
4478 smb_fname_str_dbg(smb_fname));
4479 status = fsp_set_smb_fname(fsp, smb_fname);
4480 if (!NT_STATUS_IS_OK(status)) {
4481 DBG_DEBUG("fsp_set_smb_fname failed: %s\n",
4487 * Now we have the complete path we can work out if
4488 * this is actually within this share and adjust
4489 * newname accordingly.
4491 DBG_DEBUG("share mismatch (sharepath %s not sharepath %s) "
4492 "%s from %s -> %s\n",
4493 fsp->conn->connectpath,
4497 smb_fname_str_dbg(smb_fname));
4504 * If a main file is opened for delete, all streams need to be checked for
4505 * !FILE_SHARE_DELETE. Do this by opening with DELETE_ACCESS.
4506 * If that works, delete them all by setting the delete on close and close.
4509 static NTSTATUS open_streams_for_delete(connection_struct *conn,
4510 const struct smb_filename *smb_fname)
4512 struct stream_struct *stream_info = NULL;
4513 files_struct **streams = NULL;
4515 unsigned int num_streams = 0;
4516 TALLOC_CTX *frame = talloc_stackframe();
4519 status = vfs_streaminfo(conn, NULL, smb_fname, talloc_tos(),
4520 &num_streams, &stream_info);
4522 if (NT_STATUS_EQUAL(status, NT_STATUS_NOT_IMPLEMENTED)
4523 || NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
4524 DEBUG(10, ("no streams around\n"));
4526 return NT_STATUS_OK;
4529 if (!NT_STATUS_IS_OK(status)) {
4530 DEBUG(10, ("vfs_streaminfo failed: %s\n",
4531 nt_errstr(status)));
4535 DEBUG(10, ("open_streams_for_delete found %d streams\n",
4538 if (num_streams == 0) {
4540 return NT_STATUS_OK;
4543 streams = talloc_array(talloc_tos(), files_struct *, num_streams);
4544 if (streams == NULL) {
4545 DEBUG(0, ("talloc failed\n"));
4546 status = NT_STATUS_NO_MEMORY;
4550 for (i=0; i<num_streams; i++) {
4551 struct smb_filename *smb_fname_cp;
4553 if (strequal(stream_info[i].name, "::$DATA")) {
4558 smb_fname_cp = synthetic_smb_fname(talloc_tos(),
4559 smb_fname->base_name,
4560 stream_info[i].name,
4563 ~SMB_FILENAME_POSIX_PATH));
4564 if (smb_fname_cp == NULL) {
4565 status = NT_STATUS_NO_MEMORY;
4569 if (SMB_VFS_STAT(conn, smb_fname_cp) == -1) {
4570 DEBUG(10, ("Unable to stat stream: %s\n",
4571 smb_fname_str_dbg(smb_fname_cp)));
4574 status = SMB_VFS_CREATE_FILE(
4577 0, /* root_dir_fid */
4578 smb_fname_cp, /* fname */
4579 DELETE_ACCESS, /* access_mask */
4580 (FILE_SHARE_READ | /* share_access */
4581 FILE_SHARE_WRITE | FILE_SHARE_DELETE),
4582 FILE_OPEN, /* create_disposition*/
4583 0, /* create_options */
4584 FILE_ATTRIBUTE_NORMAL, /* file_attributes */
4585 0, /* oplock_request */
4587 0, /* allocation_size */
4588 NTCREATEX_OPTIONS_PRIVATE_STREAM_DELETE, /* private_flags */
4591 &streams[i], /* result */
4593 NULL, NULL); /* create context */
4595 if (!NT_STATUS_IS_OK(status)) {
4596 DEBUG(10, ("Could not open stream %s: %s\n",
4597 smb_fname_str_dbg(smb_fname_cp),
4598 nt_errstr(status)));
4600 TALLOC_FREE(smb_fname_cp);
4603 TALLOC_FREE(smb_fname_cp);
4607 * don't touch the variable "status" beyond this point :-)
4610 for (i -= 1 ; i >= 0; i--) {
4611 if (streams[i] == NULL) {
4615 DEBUG(10, ("Closing stream # %d, %s\n", i,
4616 fsp_str_dbg(streams[i])));
4617 close_file(NULL, streams[i], NORMAL_CLOSE);
4625 /*********************************************************************
4626 Create a default ACL by inheriting from the parent. If no inheritance
4627 from the parent available, don't set anything. This will leave the actual
4628 permissions the new file or directory already got from the filesystem
4629 as the NT ACL when read.
4630 *********************************************************************/
4632 static NTSTATUS inherit_new_acl(files_struct *fsp)
4634 TALLOC_CTX *frame = talloc_stackframe();
4635 char *parent_name = NULL;
4636 struct security_descriptor *parent_desc = NULL;
4637 NTSTATUS status = NT_STATUS_OK;
4638 struct security_descriptor *psd = NULL;
4639 const struct dom_sid *owner_sid = NULL;
4640 const struct dom_sid *group_sid = NULL;
4641 uint32_t security_info_sent = (SECINFO_OWNER | SECINFO_GROUP | SECINFO_DACL);
4642 struct security_token *token = fsp->conn->session_info->security_token;
4643 bool inherit_owner =
4644 (lp_inherit_owner(SNUM(fsp->conn)) == INHERIT_OWNER_WINDOWS_AND_UNIX);
4645 bool inheritable_components = false;
4646 bool try_builtin_administrators = false;
4647 const struct dom_sid *BA_U_sid = NULL;
4648 const struct dom_sid *BA_G_sid = NULL;
4649 bool try_system = false;
4650 const struct dom_sid *SY_U_sid = NULL;
4651 const struct dom_sid *SY_G_sid = NULL;
4653 struct smb_filename *parent_smb_fname = NULL;
4655 if (!parent_dirname(frame, fsp->fsp_name->base_name, &parent_name, NULL)) {
4657 return NT_STATUS_NO_MEMORY;
4659 parent_smb_fname = synthetic_smb_fname(talloc_tos(),
4663 fsp->fsp_name->flags);
4665 if (parent_smb_fname == NULL) {
4667 return NT_STATUS_NO_MEMORY;
4670 status = SMB_VFS_GET_NT_ACL(fsp->conn,
4672 (SECINFO_OWNER | SECINFO_GROUP | SECINFO_DACL),
4675 if (!NT_STATUS_IS_OK(status)) {
4680 inheritable_components = sd_has_inheritable_components(parent_desc,
4683 if (!inheritable_components && !inherit_owner) {
4685 /* Nothing to inherit and not setting owner. */
4686 return NT_STATUS_OK;
4689 /* Create an inherited descriptor from the parent. */
4691 if (DEBUGLEVEL >= 10) {
4692 DEBUG(10,("inherit_new_acl: parent acl for %s is:\n",
4693 fsp_str_dbg(fsp) ));
4694 NDR_PRINT_DEBUG(security_descriptor, parent_desc);
4697 /* Inherit from parent descriptor if "inherit owner" set. */
4698 if (inherit_owner) {
4699 owner_sid = parent_desc->owner_sid;
4700 group_sid = parent_desc->group_sid;
4703 if (owner_sid == NULL) {
4704 if (security_token_has_builtin_administrators(token)) {
4705 try_builtin_administrators = true;
4706 } else if (security_token_is_system(token)) {
4707 try_builtin_administrators = true;
4712 if (group_sid == NULL &&
4713 token->num_sids == PRIMARY_GROUP_SID_INDEX)
4715 if (security_token_is_system(token)) {
4716 try_builtin_administrators = true;
4721 if (try_builtin_administrators) {
4726 ok = sids_to_unixids(&global_sid_Builtin_Administrators, 1, &ids);
4730 BA_U_sid = &global_sid_Builtin_Administrators;
4731 BA_G_sid = &global_sid_Builtin_Administrators;
4734 BA_U_sid = &global_sid_Builtin_Administrators;
4737 BA_G_sid = &global_sid_Builtin_Administrators;
4750 ok = sids_to_unixids(&global_sid_System, 1, &ids);
4754 SY_U_sid = &global_sid_System;
4755 SY_G_sid = &global_sid_System;
4758 SY_U_sid = &global_sid_System;
4761 SY_G_sid = &global_sid_System;
4769 if (owner_sid == NULL) {
4770 owner_sid = BA_U_sid;
4773 if (owner_sid == NULL) {
4774 owner_sid = SY_U_sid;
4777 if (group_sid == NULL) {
4778 group_sid = SY_G_sid;
4781 if (try_system && group_sid == NULL) {
4782 group_sid = BA_G_sid;
4785 if (owner_sid == NULL) {
4786 owner_sid = &token->sids[PRIMARY_USER_SID_INDEX];
4788 if (group_sid == NULL) {
4789 if (token->num_sids == PRIMARY_GROUP_SID_INDEX) {
4790 group_sid = &token->sids[PRIMARY_USER_SID_INDEX];
4792 group_sid = &token->sids[PRIMARY_GROUP_SID_INDEX];
4796 status = se_create_child_secdesc(frame,
4803 if (!NT_STATUS_IS_OK(status)) {
4808 /* If inheritable_components == false,
4809 se_create_child_secdesc()
4810 creates a security descriptor with a NULL dacl
4811 entry, but with SEC_DESC_DACL_PRESENT. We need
4812 to remove that flag. */
4814 if (!inheritable_components) {
4815 security_info_sent &= ~SECINFO_DACL;
4816 psd->type &= ~SEC_DESC_DACL_PRESENT;
4819 if (DEBUGLEVEL >= 10) {
4820 DEBUG(10,("inherit_new_acl: child acl for %s is:\n",
4821 fsp_str_dbg(fsp) ));
4822 NDR_PRINT_DEBUG(security_descriptor, psd);
4825 if (inherit_owner) {
4826 /* We need to be root to force this. */
4829 status = SMB_VFS_FSET_NT_ACL(fsp,
4832 if (inherit_owner) {
4840 * If we already have a lease, it must match the new file id. [MS-SMB2]
4841 * 3.3.5.9.8 speaks about INVALID_PARAMETER if an already used lease key is
4842 * used for a different file name.
4845 struct lease_match_state {
4846 /* Input parameters. */
4847 TALLOC_CTX *mem_ctx;
4848 const char *servicepath;
4849 const struct smb_filename *fname;
4852 /* Return parameters. */
4853 uint32_t num_file_ids;
4854 struct file_id *ids;
4855 NTSTATUS match_status;
4858 /*************************************************************
4859 File doesn't exist but this lease key+guid is already in use.
4861 This is only allowable in the dynamic share case where the
4862 service path must be different.
4864 There is a small race condition here in the multi-connection
4865 case where a client sends two create calls on different connections,
4866 where the file doesn't exist and one smbd creates the leases_db
4867 entry first, but this will get fixed by the multichannel cleanup
4868 when all identical client_guids get handled by a single smbd.
4869 **************************************************************/
4871 static void lease_match_parser_new_file(
4873 const struct leases_db_file *files,
4874 struct lease_match_state *state)
4878 for (i = 0; i < num_files; i++) {
4879 const struct leases_db_file *f = &files[i];
4880 if (strequal(state->servicepath, f->servicepath)) {
4881 state->match_status = NT_STATUS_INVALID_PARAMETER;
4886 /* Dynamic share case. Break leases on all other files. */
4887 state->match_status = leases_db_copy_file_ids(state->mem_ctx,
4891 if (!NT_STATUS_IS_OK(state->match_status)) {
4895 state->num_file_ids = num_files;
4896 state->match_status = NT_STATUS_OPLOCK_NOT_GRANTED;
4900 static void lease_match_parser(
4902 const struct leases_db_file *files,
4905 struct lease_match_state *state =
4906 (struct lease_match_state *)private_data;
4909 if (!state->file_existed) {
4911 * Deal with name mismatch or
4912 * possible dynamic share case separately
4913 * to make code clearer.
4915 lease_match_parser_new_file(num_files,
4922 state->match_status = NT_STATUS_OK;
4924 for (i = 0; i < num_files; i++) {
4925 const struct leases_db_file *f = &files[i];
4927 /* Everything should be the same. */
4928 if (!file_id_equal(&state->id, &f->id)) {
4929 /* This should catch all dynamic share cases. */
4930 state->match_status = NT_STATUS_OPLOCK_NOT_GRANTED;
4933 if (!strequal(f->servicepath, state->servicepath)) {
4934 state->match_status = NT_STATUS_INVALID_PARAMETER;
4937 if (!strequal(f->base_name, state->fname->base_name)) {
4938 state->match_status = NT_STATUS_INVALID_PARAMETER;
4941 if (!strequal(f->stream_name, state->fname->stream_name)) {
4942 state->match_status = NT_STATUS_INVALID_PARAMETER;
4947 if (NT_STATUS_IS_OK(state->match_status)) {
4949 * Common case - just opening another handle on a
4950 * file on a non-dynamic share.
4955 if (NT_STATUS_EQUAL(state->match_status, NT_STATUS_INVALID_PARAMETER)) {
4956 /* Mismatched path. Error back to client. */
4961 * File id mismatch. Dynamic share case NT_STATUS_OPLOCK_NOT_GRANTED.
4962 * Don't allow leases.
4965 state->match_status = leases_db_copy_file_ids(state->mem_ctx,
4969 if (!NT_STATUS_IS_OK(state->match_status)) {
4973 state->num_file_ids = num_files;
4974 state->match_status = NT_STATUS_OPLOCK_NOT_GRANTED;
4978 static NTSTATUS lease_match(connection_struct *conn,
4979 struct smb_request *req,
4980 struct smb2_lease_key *lease_key,
4981 const char *servicepath,
4982 const struct smb_filename *fname,
4983 uint16_t *p_version,
4986 struct smbd_server_connection *sconn = req->sconn;
4987 TALLOC_CTX *tos = talloc_tos();
4988 struct lease_match_state state = {
4990 .servicepath = servicepath,
4992 .match_status = NT_STATUS_OK
4997 state.file_existed = VALID_STAT(fname->st);
4998 if (state.file_existed) {
4999 state.id = vfs_file_id_from_sbuf(conn, &fname->st);
5002 status = leases_db_parse(&sconn->client->connections->smb2.client.guid,
5003 lease_key, lease_match_parser, &state);
5004 if (!NT_STATUS_IS_OK(status)) {
5006 * Not found or error means okay: We can make the lease pass
5008 return NT_STATUS_OK;
5010 if (!NT_STATUS_EQUAL(state.match_status, NT_STATUS_OPLOCK_NOT_GRANTED)) {
5012 * Anything but NT_STATUS_OPLOCK_NOT_GRANTED, let the caller
5015 return state.match_status;
5018 /* We have to break all existing leases. */
5019 for (i = 0; i < state.num_file_ids; i++) {
5020 struct share_mode_lock *lck;
5021 struct share_mode_data *d;
5022 struct share_mode_entry *lease_entry = NULL;
5025 if (file_id_equal(&state.ids[i], &state.id)) {
5026 /* Don't need to break our own file. */
5030 lck = get_existing_share_mode_lock(talloc_tos(), state.ids[i]);
5032 /* Race condition - file already closed. */
5036 for (j=0; j<d->num_share_modes; j++) {
5037 struct share_mode_entry *e = &d->share_modes[j];
5038 uint32_t e_lease_type = get_lease_type(d, e);
5040 if (share_mode_stale_pid(d, j)) {
5044 if (e->op_type == LEASE_OPLOCK) {
5045 if (!smb2_lease_key_equal(&e->lease_key,
5052 if (e_lease_type == SMB2_LEASE_NONE) {
5056 send_break_message(conn->sconn->msg_ctx, &d->id, e,
5060 * Windows 7 and 8 lease clients
5061 * are broken in that they will not
5062 * respond to lease break requests
5063 * whilst waiting for an outstanding
5064 * open request on that lease handle
5065 * on the same TCP connection, due
5066 * to holding an internal inode lock.
5068 * This means we can't reschedule
5069 * ourselves here, but must return
5074 * Send the breaks and then return
5075 * SMB2_LEASE_NONE in the lease handle
5076 * to cause them to acknowledge the
5077 * lease break. Consultation with
5078 * Microsoft engineering confirmed
5079 * this approach is safe.
5084 if (lease_entry != NULL) {
5085 status = leases_db_get(
5086 &lease_entry->client_guid,
5087 &lease_entry->lease_key,
5089 NULL, /* current_state */
5090 NULL, /* breaking */
5091 NULL, /* breaking_to_requested */
5092 NULL, /* breaking_to_required */
5093 p_version, /* lease_version */
5094 p_epoch); /* epoch */
5095 if (!NT_STATUS_IS_OK(status)) {
5096 DBG_WARNING("Could not find version/epoch: "
5105 * Ensure we don't grant anything more so we
5108 return NT_STATUS_OPLOCK_NOT_GRANTED;
5112 * Wrapper around open_file_ntcreate and open_directory
5115 static NTSTATUS create_file_unixpath(connection_struct *conn,
5116 struct smb_request *req,
5117 struct smb_filename *smb_fname,
5118 uint32_t access_mask,
5119 uint32_t share_access,
5120 uint32_t create_disposition,
5121 uint32_t create_options,
5122 uint32_t file_attributes,
5123 uint32_t oplock_request,
5124 struct smb2_lease *lease,
5125 uint64_t allocation_size,
5126 uint32_t private_flags,
5127 struct security_descriptor *sd,
5128 struct ea_list *ea_list,
5130 files_struct **result,
5133 int info = FILE_WAS_OPENED;
5134 files_struct *base_fsp = NULL;
5135 files_struct *fsp = NULL;
5138 DBG_DEBUG("create_file_unixpath: access_mask = 0x%x "
5139 "file_attributes = 0x%x, share_access = 0x%x, "
5140 "create_disposition = 0x%x create_options = 0x%x "
5141 "oplock_request = 0x%x private_flags = 0x%x "
5142 "ea_list = %p, sd = %p, "
5144 (unsigned int)access_mask,
5145 (unsigned int)file_attributes,
5146 (unsigned int)share_access,
5147 (unsigned int)create_disposition,
5148 (unsigned int)create_options,
5149 (unsigned int)oplock_request,
5150 (unsigned int)private_flags,
5151 ea_list, sd, smb_fname_str_dbg(smb_fname));
5153 if (create_options & FILE_OPEN_BY_FILE_ID) {
5154 status = NT_STATUS_NOT_SUPPORTED;
5158 if (create_options & NTCREATEX_OPTIONS_INVALID_PARAM_MASK) {
5159 status = NT_STATUS_INVALID_PARAMETER;
5164 oplock_request |= INTERNAL_OPEN_ONLY;
5167 if (lease != NULL) {
5168 uint16_t epoch = lease->lease_epoch;
5169 uint16_t version = lease->lease_version;
5172 DBG_WARNING("Got lease on internal open\n");
5173 status = NT_STATUS_INTERNAL_ERROR;
5177 status = lease_match(conn,
5184 if (NT_STATUS_EQUAL(status, NT_STATUS_OPLOCK_NOT_GRANTED)) {
5185 /* Dynamic share file. No leases and update epoch... */
5186 lease->lease_state = SMB2_LEASE_NONE;
5187 lease->lease_epoch = epoch;
5188 lease->lease_version = version;
5189 } else if (!NT_STATUS_IS_OK(status)) {
5194 if ((conn->fs_capabilities & FILE_NAMED_STREAMS)
5195 && (access_mask & DELETE_ACCESS)
5196 && !is_ntfs_stream_smb_fname(smb_fname)) {
5198 * We can't open a file with DELETE access if any of the
5199 * streams is open without FILE_SHARE_DELETE
5201 status = open_streams_for_delete(conn, smb_fname);
5203 if (!NT_STATUS_IS_OK(status)) {
5208 if ((access_mask & SEC_FLAG_SYSTEM_SECURITY) &&
5209 !security_token_has_privilege(get_current_nttok(conn),
5210 SEC_PRIV_SECURITY)) {
5211 DEBUG(10, ("create_file_unixpath: open on %s "
5212 "failed - SEC_FLAG_SYSTEM_SECURITY denied.\n",
5213 smb_fname_str_dbg(smb_fname)));
5214 status = NT_STATUS_PRIVILEGE_NOT_HELD;
5219 * Files or directories can't be opened DELETE_ON_CLOSE without
5221 * BUG: https://bugzilla.samba.org/show_bug.cgi?id=13358
5223 if (create_options & FILE_DELETE_ON_CLOSE) {
5224 if ((access_mask & DELETE_ACCESS) == 0) {
5225 status = NT_STATUS_INVALID_PARAMETER;
5230 if ((conn->fs_capabilities & FILE_NAMED_STREAMS)
5231 && is_ntfs_stream_smb_fname(smb_fname)
5232 && (!(private_flags & NTCREATEX_OPTIONS_PRIVATE_STREAM_DELETE))) {
5233 uint32_t base_create_disposition;
5234 struct smb_filename *smb_fname_base = NULL;
5235 uint32_t base_privflags;
5237 if (create_options & FILE_DIRECTORY_FILE) {
5238 status = NT_STATUS_NOT_A_DIRECTORY;
5242 switch (create_disposition) {
5244 base_create_disposition = FILE_OPEN;
5247 base_create_disposition = FILE_OPEN_IF;
5251 /* Create an smb_filename with stream_name == NULL. */
5252 smb_fname_base = synthetic_smb_fname(talloc_tos(),
5253 smb_fname->base_name,
5257 if (smb_fname_base == NULL) {
5258 status = NT_STATUS_NO_MEMORY;
5262 if (SMB_VFS_STAT(conn, smb_fname_base) == -1) {
5263 DEBUG(10, ("Unable to stat stream: %s\n",
5264 smb_fname_str_dbg(smb_fname_base)));
5267 * https://bugzilla.samba.org/show_bug.cgi?id=10229
5268 * We need to check if the requested access mask
5269 * could be used to open the underlying file (if
5270 * it existed), as we're passing in zero for the
5271 * access mask to the base filename.
5273 status = check_base_file_access(conn,
5277 if (!NT_STATUS_IS_OK(status)) {
5278 DEBUG(10, ("Permission check "
5279 "for base %s failed: "
5280 "%s\n", smb_fname->base_name,
5281 nt_errstr(status)));
5286 base_privflags = NTCREATEX_OPTIONS_PRIVATE_STREAM_BASEOPEN;
5288 /* Open the base file. */
5289 status = create_file_unixpath(conn, NULL, smb_fname_base, 0,
5292 | FILE_SHARE_DELETE,
5293 base_create_disposition,
5298 TALLOC_FREE(smb_fname_base);
5300 if (!NT_STATUS_IS_OK(status)) {
5301 DEBUG(10, ("create_file_unixpath for base %s failed: "
5302 "%s\n", smb_fname->base_name,
5303 nt_errstr(status)));
5306 /* we don't need the low level fd */
5311 * If it's a request for a directory open, deal with it separately.
5314 if (create_options & FILE_DIRECTORY_FILE) {
5316 if (create_options & FILE_NON_DIRECTORY_FILE) {
5317 status = NT_STATUS_INVALID_PARAMETER;
5321 /* Can't open a temp directory. IFS kit test. */
5322 if (!(file_attributes & FILE_FLAG_POSIX_SEMANTICS) &&
5323 (file_attributes & FILE_ATTRIBUTE_TEMPORARY)) {
5324 status = NT_STATUS_INVALID_PARAMETER;
5329 * We will get a create directory here if the Win32
5330 * app specified a security descriptor in the
5331 * CreateDirectory() call.
5335 status = open_directory(
5336 conn, req, smb_fname, access_mask, share_access,
5337 create_disposition, create_options, file_attributes,
5342 * Ordinary file case.
5345 status = file_new(req, conn, &fsp);
5346 if(!NT_STATUS_IS_OK(status)) {
5350 status = fsp_set_smb_fname(fsp, smb_fname);
5351 if (!NT_STATUS_IS_OK(status)) {
5357 * We're opening the stream element of a
5358 * base_fsp we already opened. Set up the
5361 fsp->base_fsp = base_fsp;
5364 if (allocation_size) {
5365 fsp->initial_allocation_size = smb_roundup(fsp->conn,
5369 status = open_file_ntcreate(conn,
5382 if(!NT_STATUS_IS_OK(status)) {
5383 file_free(req, fsp);
5387 if (NT_STATUS_EQUAL(status, NT_STATUS_FILE_IS_A_DIRECTORY)) {
5389 /* A stream open never opens a directory */
5392 status = NT_STATUS_FILE_IS_A_DIRECTORY;
5397 * Fail the open if it was explicitly a non-directory
5401 if (create_options & FILE_NON_DIRECTORY_FILE) {
5402 status = NT_STATUS_FILE_IS_A_DIRECTORY;
5407 status = open_directory(
5408 conn, req, smb_fname, access_mask,
5409 share_access, create_disposition,
5410 create_options, file_attributes,
5415 if (!NT_STATUS_IS_OK(status)) {
5419 fsp->base_fsp = base_fsp;
5421 if ((ea_list != NULL) &&
5422 ((info == FILE_WAS_CREATED) || (info == FILE_WAS_OVERWRITTEN))) {
5423 status = set_ea(conn, fsp, fsp->fsp_name, ea_list);
5424 if (!NT_STATUS_IS_OK(status)) {
5429 if (!fsp->is_directory && S_ISDIR(fsp->fsp_name->st.st_ex_mode)) {
5430 status = NT_STATUS_ACCESS_DENIED;
5434 /* Save the requested allocation size. */
5435 if ((info == FILE_WAS_CREATED) || (info == FILE_WAS_OVERWRITTEN)) {
5436 if ((allocation_size > fsp->fsp_name->st.st_ex_size)
5437 && !(fsp->is_directory))
5439 fsp->initial_allocation_size = smb_roundup(
5440 fsp->conn, allocation_size);
5441 if (vfs_allocate_file_space(
5442 fsp, fsp->initial_allocation_size) == -1) {
5443 status = NT_STATUS_DISK_FULL;
5447 fsp->initial_allocation_size = smb_roundup(
5448 fsp->conn, (uint64_t)fsp->fsp_name->st.st_ex_size);
5451 fsp->initial_allocation_size = 0;
5454 if ((info == FILE_WAS_CREATED) && lp_nt_acl_support(SNUM(conn)) &&
5455 fsp->base_fsp == NULL) {
5458 * According to the MS documentation, the only time the security
5459 * descriptor is applied to the opened file is iff we *created* the
5460 * file; an existing file stays the same.
5462 * Also, it seems (from observation) that you can open the file with
5463 * any access mask but you can still write the sd. We need to override
5464 * the granted access before we call set_sd
5465 * Patch for bug #2242 from Tom Lackemann <cessnatomny@yahoo.com>.
5468 uint32_t sec_info_sent;
5469 uint32_t saved_access_mask = fsp->access_mask;
5471 sec_info_sent = get_sec_info(sd);
5473 fsp->access_mask = FILE_GENERIC_ALL;
5475 if (sec_info_sent & (SECINFO_OWNER|
5479 status = set_sd(fsp, sd, sec_info_sent);
5482 fsp->access_mask = saved_access_mask;
5484 if (!NT_STATUS_IS_OK(status)) {
5487 } else if (lp_inherit_acls(SNUM(conn))) {
5488 /* Inherit from parent. Errors here are not fatal. */
5489 status = inherit_new_acl(fsp);
5490 if (!NT_STATUS_IS_OK(status)) {
5491 DEBUG(10,("inherit_new_acl: failed for %s with %s\n",
5493 nt_errstr(status) ));
5498 if ((conn->fs_capabilities & FILE_FILE_COMPRESSION)
5499 && (create_options & FILE_NO_COMPRESSION)
5500 && (info == FILE_WAS_CREATED)) {
5501 status = SMB_VFS_SET_COMPRESSION(conn, fsp, fsp,
5502 COMPRESSION_FORMAT_NONE);
5503 if (!NT_STATUS_IS_OK(status)) {
5504 DEBUG(1, ("failed to disable compression: %s\n",
5505 nt_errstr(status)));
5509 DEBUG(10, ("create_file_unixpath: info=%d\n", info));
5512 if (pinfo != NULL) {
5516 smb_fname->st = fsp->fsp_name->st;
5518 return NT_STATUS_OK;
5521 DEBUG(10, ("create_file_unixpath: %s\n", nt_errstr(status)));
5524 if (base_fsp && fsp->base_fsp == base_fsp) {
5526 * The close_file below will close
5531 close_file(req, fsp, ERROR_CLOSE);
5534 if (base_fsp != NULL) {
5535 close_file(req, base_fsp, ERROR_CLOSE);
5542 * Calculate the full path name given a relative fid.
5544 NTSTATUS get_relative_fid_filename(connection_struct *conn,
5545 struct smb_request *req,
5546 uint16_t root_dir_fid,
5547 const struct smb_filename *smb_fname,
5548 struct smb_filename **smb_fname_out)
5550 files_struct *dir_fsp;
5551 char *parent_fname = NULL;
5552 char *new_base_name = NULL;
5553 uint32_t ucf_flags = ucf_flags_from_smb_request(req);
5556 if (root_dir_fid == 0 || !smb_fname) {
5557 status = NT_STATUS_INTERNAL_ERROR;
5561 dir_fsp = file_fsp(req, root_dir_fid);
5563 if (dir_fsp == NULL) {
5564 status = NT_STATUS_INVALID_HANDLE;
5568 if (is_ntfs_stream_smb_fname(dir_fsp->fsp_name)) {
5569 status = NT_STATUS_INVALID_HANDLE;
5573 if (!dir_fsp->is_directory) {
5576 * Check to see if this is a mac fork of some kind.
5579 if ((conn->fs_capabilities & FILE_NAMED_STREAMS) &&
5580 is_ntfs_stream_smb_fname(smb_fname)) {
5581 status = NT_STATUS_OBJECT_PATH_NOT_FOUND;
5586 we need to handle the case when we get a
5587 relative open relative to a file and the
5588 pathname is blank - this is a reopen!
5589 (hint from demyn plantenberg)
5592 status = NT_STATUS_INVALID_HANDLE;
5596 if (ISDOT(dir_fsp->fsp_name->base_name)) {
5598 * We're at the toplevel dir, the final file name
5599 * must not contain ./, as this is filtered out
5600 * normally by srvstr_get_path and unix_convert
5601 * explicitly rejects paths containing ./.
5603 parent_fname = talloc_strdup(talloc_tos(), "");
5604 if (parent_fname == NULL) {
5605 status = NT_STATUS_NO_MEMORY;
5609 size_t dir_name_len = strlen(dir_fsp->fsp_name->base_name);
5612 * Copy in the base directory name.
5615 parent_fname = talloc_array(talloc_tos(), char,
5617 if (parent_fname == NULL) {
5618 status = NT_STATUS_NO_MEMORY;
5621 memcpy(parent_fname, dir_fsp->fsp_name->base_name,
5625 * Ensure it ends in a '/'.
5626 * We used TALLOC_SIZE +2 to add space for the '/'.
5630 && (parent_fname[dir_name_len-1] != '\\')
5631 && (parent_fname[dir_name_len-1] != '/')) {
5632 parent_fname[dir_name_len] = '/';
5633 parent_fname[dir_name_len+1] = '\0';
5637 new_base_name = talloc_asprintf(talloc_tos(), "%s%s", parent_fname,
5638 smb_fname->base_name);
5639 if (new_base_name == NULL) {
5640 status = NT_STATUS_NO_MEMORY;
5644 status = filename_convert(req,
5651 if (!NT_STATUS_IS_OK(status)) {
5656 TALLOC_FREE(parent_fname);
5657 TALLOC_FREE(new_base_name);
5661 NTSTATUS create_file_default(connection_struct *conn,
5662 struct smb_request *req,
5663 uint16_t root_dir_fid,
5664 struct smb_filename *smb_fname,
5665 uint32_t access_mask,
5666 uint32_t share_access,
5667 uint32_t create_disposition,
5668 uint32_t create_options,
5669 uint32_t file_attributes,
5670 uint32_t oplock_request,
5671 struct smb2_lease *lease,
5672 uint64_t allocation_size,
5673 uint32_t private_flags,
5674 struct security_descriptor *sd,
5675 struct ea_list *ea_list,
5676 files_struct **result,
5678 const struct smb2_create_blobs *in_context_blobs,
5679 struct smb2_create_blobs *out_context_blobs)
5681 int info = FILE_WAS_OPENED;
5682 files_struct *fsp = NULL;
5684 bool stream_name = false;
5686 DBG_DEBUG("create_file: access_mask = 0x%x "
5687 "file_attributes = 0x%x, share_access = 0x%x, "
5688 "create_disposition = 0x%x create_options = 0x%x "
5689 "oplock_request = 0x%x "
5690 "private_flags = 0x%x "
5691 "root_dir_fid = 0x%x, ea_list = %p, sd = %p, "
5693 (unsigned int)access_mask,
5694 (unsigned int)file_attributes,
5695 (unsigned int)share_access,
5696 (unsigned int)create_disposition,
5697 (unsigned int)create_options,
5698 (unsigned int)oplock_request,
5699 (unsigned int)private_flags,
5700 (unsigned int)root_dir_fid,
5701 ea_list, sd, smb_fname_str_dbg(smb_fname));
5704 * Calculate the filename from the root_dir_if if necessary.
5707 if (root_dir_fid != 0) {
5708 struct smb_filename *smb_fname_out = NULL;
5709 status = get_relative_fid_filename(conn, req, root_dir_fid,
5710 smb_fname, &smb_fname_out);
5711 if (!NT_STATUS_IS_OK(status)) {
5714 smb_fname = smb_fname_out;
5718 * Check to see if this is a mac fork of some kind.
5721 stream_name = is_ntfs_stream_smb_fname(smb_fname);
5723 enum FAKE_FILE_TYPE fake_file_type;
5725 fake_file_type = is_fake_file(smb_fname);
5727 if (fake_file_type != FAKE_FILE_TYPE_NONE) {
5730 * Here we go! support for changing the disk quotas
5733 * We need to fake up to open this MAGIC QUOTA file
5734 * and return a valid FID.
5736 * w2k close this file directly after openening xp
5737 * also tries a QUERY_FILE_INFO on the file and then
5740 status = open_fake_file(req, conn, req->vuid,
5741 fake_file_type, smb_fname,
5743 if (!NT_STATUS_IS_OK(status)) {
5747 ZERO_STRUCT(smb_fname->st);
5751 if (!(conn->fs_capabilities & FILE_NAMED_STREAMS)) {
5752 status = NT_STATUS_OBJECT_NAME_NOT_FOUND;
5757 if (is_ntfs_default_stream_smb_fname(smb_fname)) {
5759 smb_fname->stream_name = NULL;
5760 /* We have to handle this error here. */
5761 if (create_options & FILE_DIRECTORY_FILE) {
5762 status = NT_STATUS_NOT_A_DIRECTORY;
5765 if (req != NULL && req->posix_pathnames) {
5766 ret = SMB_VFS_LSTAT(conn, smb_fname);
5768 ret = SMB_VFS_STAT(conn, smb_fname);
5771 if (ret == 0 && VALID_STAT_OF_DIR(smb_fname->st)) {
5772 status = NT_STATUS_FILE_IS_A_DIRECTORY;
5777 status = create_file_unixpath(
5778 conn, req, smb_fname, access_mask, share_access,
5779 create_disposition, create_options, file_attributes,
5780 oplock_request, lease, allocation_size, private_flags,
5784 if (!NT_STATUS_IS_OK(status)) {
5789 DEBUG(10, ("create_file: info=%d\n", info));
5792 if (pinfo != NULL) {
5795 return NT_STATUS_OK;
5798 DEBUG(10, ("create_file: %s\n", nt_errstr(status)));
5801 close_file(req, fsp, ERROR_CLOSE);