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/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)) {
1476 * note: cleanup should have been done by
1477 * delay_for_batch_oplocks()
1482 DEBUG(10,("share_conflict: access_mask = 0x%x, share_access = 0x%x\n",
1483 (unsigned int)access_mask, (unsigned int)share_access));
1485 if ((entry->access_mask & (FILE_WRITE_DATA|
1489 DELETE_ACCESS)) == 0) {
1490 DEBUG(10,("share_conflict: No conflict due to "
1491 "entry->access_mask = 0x%x\n",
1492 (unsigned int)entry->access_mask ));
1496 if ((access_mask & (FILE_WRITE_DATA|
1500 DELETE_ACCESS)) == 0) {
1501 DEBUG(10,("share_conflict: No conflict due to "
1502 "access_mask = 0x%x\n",
1503 (unsigned int)access_mask ));
1507 #if 1 /* JRA TEST - Superdebug. */
1508 #define CHECK_MASK(num, am, right, sa, share) \
1509 DEBUG(10,("share_conflict: [%d] am (0x%x) & right (0x%x) = 0x%x\n", \
1510 (unsigned int)(num), (unsigned int)(am), \
1511 (unsigned int)(right), (unsigned int)(am)&(right) )); \
1512 DEBUG(10,("share_conflict: [%d] sa (0x%x) & share (0x%x) = 0x%x\n", \
1513 (unsigned int)(num), (unsigned int)(sa), \
1514 (unsigned int)(share), (unsigned int)(sa)&(share) )); \
1515 if (((am) & (right)) && !((sa) & (share))) { \
1516 DEBUG(10,("share_conflict: check %d conflict am = 0x%x, right = 0x%x, \
1517 sa = 0x%x, share = 0x%x\n", (num), (unsigned int)(am), (unsigned int)(right), (unsigned int)(sa), \
1518 (unsigned int)(share) )); \
1522 #define CHECK_MASK(num, am, right, sa, share) \
1523 if (((am) & (right)) && !((sa) & (share))) { \
1524 DEBUG(10,("share_conflict: check %d conflict am = 0x%x, right = 0x%x, \
1525 sa = 0x%x, share = 0x%x\n", (num), (unsigned int)(am), (unsigned int)(right), (unsigned int)(sa), \
1526 (unsigned int)(share) )); \
1531 CHECK_MASK(1, entry->access_mask, FILE_WRITE_DATA | FILE_APPEND_DATA,
1532 share_access, FILE_SHARE_WRITE);
1533 CHECK_MASK(2, access_mask, FILE_WRITE_DATA | FILE_APPEND_DATA,
1534 entry->share_access, FILE_SHARE_WRITE);
1536 CHECK_MASK(3, entry->access_mask, FILE_READ_DATA | FILE_EXECUTE,
1537 share_access, FILE_SHARE_READ);
1538 CHECK_MASK(4, access_mask, FILE_READ_DATA | FILE_EXECUTE,
1539 entry->share_access, FILE_SHARE_READ);
1541 CHECK_MASK(5, entry->access_mask, DELETE_ACCESS,
1542 share_access, FILE_SHARE_DELETE);
1543 CHECK_MASK(6, access_mask, DELETE_ACCESS,
1544 entry->share_access, FILE_SHARE_DELETE);
1546 DEBUG(10,("share_conflict: No conflict.\n"));
1550 #if defined(DEVELOPER)
1551 static void validate_my_share_entries(struct smbd_server_connection *sconn,
1552 const struct file_id id,
1554 struct share_mode_entry *share_entry)
1556 struct server_id self = messaging_server_id(sconn->msg_ctx);
1559 if (!serverid_equal(&self, &share_entry->pid)) {
1563 if (share_entry->op_mid == 0) {
1564 /* INTERNAL_OPEN_ONLY */
1568 if (!is_valid_share_mode_entry(share_entry)) {
1572 fsp = file_find_dif(sconn, id, share_entry->share_file_id);
1574 DBG_ERR("PANIC : %s\n",
1575 share_mode_str(talloc_tos(), num, &id,
1577 smb_panic("validate_my_share_entries: Cannot match a "
1578 "share entry with an open file\n");
1581 if (((uint16_t)fsp->oplock_type) != share_entry->op_type) {
1590 DBG_ERR("validate_my_share_entries: PANIC : %s\n",
1591 share_mode_str(talloc_tos(), num, &id,
1593 str = talloc_asprintf(talloc_tos(),
1594 "validate_my_share_entries: "
1595 "file %s, oplock_type = 0x%x, op_type = 0x%x\n",
1596 fsp->fsp_name->base_name,
1597 (unsigned int)fsp->oplock_type,
1598 (unsigned int)share_entry->op_type );
1604 bool is_stat_open(uint32_t access_mask)
1606 const uint32_t stat_open_bits =
1607 (SYNCHRONIZE_ACCESS|
1608 FILE_READ_ATTRIBUTES|
1609 FILE_WRITE_ATTRIBUTES);
1611 return (((access_mask & stat_open_bits) != 0) &&
1612 ((access_mask & ~stat_open_bits) == 0));
1615 static bool has_delete_on_close(struct share_mode_lock *lck,
1618 struct share_mode_data *d = lck->data;
1621 if (d->num_share_modes == 0) {
1624 if (!is_delete_on_close_set(lck, name_hash)) {
1627 for (i=0; i<d->num_share_modes; i++) {
1628 if (!share_mode_stale_pid(d, i)) {
1635 /****************************************************************************
1636 Deal with share modes
1637 Invariant: Share mode must be locked on entry and exit.
1638 Returns -1 on error, or number of share modes on success (may be zero).
1639 ****************************************************************************/
1641 static NTSTATUS open_mode_check(connection_struct *conn,
1642 struct share_mode_lock *lck,
1643 uint32_t access_mask,
1644 uint32_t share_access)
1648 if(lck->data->num_share_modes == 0) {
1649 return NT_STATUS_OK;
1652 if (is_stat_open(access_mask)) {
1653 /* Stat open that doesn't trigger oplock breaks or share mode
1654 * checks... ! JRA. */
1655 return NT_STATUS_OK;
1659 * Check if the share modes will give us access.
1662 #if defined(DEVELOPER)
1663 for(i = 0; i < lck->data->num_share_modes; i++) {
1664 validate_my_share_entries(conn->sconn, lck->data->id, i,
1665 &lck->data->share_modes[i]);
1669 /* Now we check the share modes, after any oplock breaks. */
1670 for(i = 0; i < lck->data->num_share_modes; i++) {
1672 if (!is_valid_share_mode_entry(&lck->data->share_modes[i])) {
1676 /* someone else has a share lock on it, check to see if we can
1678 if (share_conflict(&lck->data->share_modes[i],
1679 access_mask, share_access)) {
1681 if (share_mode_stale_pid(lck->data, i)) {
1685 return NT_STATUS_SHARING_VIOLATION;
1689 return NT_STATUS_OK;
1693 * Send a break message to the oplock holder and delay the open for
1697 NTSTATUS send_break_message(struct messaging_context *msg_ctx,
1698 const struct file_id *id,
1699 const struct share_mode_entry *exclusive,
1703 char msg[MSG_SMB_SHARE_MODE_ENTRY_SIZE];
1704 struct server_id_buf tmp;
1706 DEBUG(10, ("Sending break request to PID %s\n",
1707 server_id_str_buf(exclusive->pid, &tmp)));
1709 /* Create the message. */
1710 share_mode_entry_to_message(msg, id, exclusive);
1712 /* Overload entry->op_type */
1714 * This is a cut from uint32_t to uint16_t, but so far only the lower 3
1715 * bits (LEASE_WRITE/HANDLE/READ are used anyway.
1717 SSVAL(msg,OP_BREAK_MSG_OP_TYPE_OFFSET, break_to);
1719 status = messaging_send_buf(msg_ctx, exclusive->pid,
1720 MSG_SMB_BREAK_REQUEST,
1721 (uint8_t *)msg, sizeof(msg));
1722 if (!NT_STATUS_IS_OK(status)) {
1723 DEBUG(3, ("Could not send oplock break message: %s\n",
1724 nt_errstr(status)));
1731 * Do internal consistency checks on the share mode for a file.
1734 static bool validate_oplock_types(struct share_mode_lock *lck)
1736 struct share_mode_data *d = lck->data;
1738 bool ex_or_batch = false;
1739 bool level2 = false;
1740 bool no_oplock = false;
1741 uint32_t num_non_stat_opens = 0;
1744 for (i=0; i<d->num_share_modes; i++) {
1745 struct share_mode_entry *e = &d->share_modes[i];
1747 if (!is_valid_share_mode_entry(e)) {
1751 if (e->op_mid == 0) {
1752 /* INTERNAL_OPEN_ONLY */
1756 if (e->op_type == NO_OPLOCK && is_stat_open(e->access_mask)) {
1757 /* We ignore stat opens in the table - they
1758 always have NO_OPLOCK and never get or
1759 cause breaks. JRA. */
1763 num_non_stat_opens += 1;
1765 if (BATCH_OPLOCK_TYPE(e->op_type)) {
1766 /* batch - can only be one. */
1767 if (share_mode_stale_pid(d, i)) {
1768 DEBUG(10, ("Found stale batch oplock\n"));
1771 if (ex_or_batch || batch || level2 || no_oplock) {
1772 DEBUG(0, ("Bad batch oplock entry %u.",
1779 if (EXCLUSIVE_OPLOCK_TYPE(e->op_type)) {
1780 if (share_mode_stale_pid(d, i)) {
1781 DEBUG(10, ("Found stale duplicate oplock\n"));
1784 /* Exclusive or batch - can only be one. */
1785 if (ex_or_batch || level2 || no_oplock) {
1786 DEBUG(0, ("Bad exclusive or batch oplock "
1787 "entry %u.", (unsigned)i));
1793 if (LEVEL_II_OPLOCK_TYPE(e->op_type)) {
1794 if (batch || ex_or_batch) {
1795 if (share_mode_stale_pid(d, i)) {
1796 DEBUG(10, ("Found stale LevelII "
1800 DEBUG(0, ("Bad levelII oplock entry %u.",
1807 if (e->op_type == NO_OPLOCK) {
1808 if (batch || ex_or_batch) {
1809 if (share_mode_stale_pid(d, i)) {
1810 DEBUG(10, ("Found stale NO_OPLOCK "
1814 DEBUG(0, ("Bad no oplock entry %u.",
1822 remove_stale_share_mode_entries(d);
1824 if ((batch || ex_or_batch) && (num_non_stat_opens != 1)) {
1825 DEBUG(1, ("got batch (%d) or ex (%d) non-exclusively (%d)\n",
1826 (int)batch, (int)ex_or_batch,
1827 (int)d->num_share_modes));
1834 static bool delay_for_oplock(files_struct *fsp,
1836 const struct smb2_lease *lease,
1837 struct share_mode_lock *lck,
1838 bool have_sharing_violation,
1839 uint32_t create_disposition,
1840 bool first_open_attempt)
1842 struct share_mode_data *d = lck->data;
1845 bool will_overwrite;
1847 if ((oplock_request & INTERNAL_OPEN_ONLY) ||
1848 is_stat_open(fsp->access_mask)) {
1852 switch (create_disposition) {
1853 case FILE_SUPERSEDE:
1854 case FILE_OVERWRITE:
1855 case FILE_OVERWRITE_IF:
1856 will_overwrite = true;
1859 will_overwrite = false;
1863 for (i=0; i<d->num_share_modes; i++) {
1864 struct share_mode_entry *e = &d->share_modes[i];
1865 bool e_is_lease = (e->op_type == LEASE_OPLOCK);
1866 struct share_mode_lease *l = NULL;
1867 uint32_t e_lease_type = get_lease_type(d, e);
1869 uint32_t delay_mask = 0;
1870 bool lease_is_breaking = false;
1873 l = &d->leases[e->lease_idx];
1874 lease_is_breaking = l->breaking;
1877 if (have_sharing_violation) {
1878 delay_mask = SMB2_LEASE_HANDLE;
1880 delay_mask = SMB2_LEASE_WRITE;
1883 break_to = e_lease_type & ~delay_mask;
1885 if (will_overwrite) {
1887 * we'll decide about SMB2_LEASE_READ later.
1889 * Maybe the break will be deferred
1891 break_to &= ~SMB2_LEASE_HANDLE;
1894 DEBUG(10, ("entry %u: e_lease_type %u, will_overwrite: %u\n",
1895 (unsigned)i, (unsigned)e_lease_type,
1896 (unsigned)will_overwrite));
1898 if (e_is_lease && lease != NULL) {
1901 ign = smb2_lease_equal(fsp_client_guid(fsp),
1910 if ((e_lease_type & ~break_to) == 0) {
1911 if (lease_is_breaking) {
1917 if (share_mode_stale_pid(d, i)) {
1921 if (will_overwrite) {
1923 * If we break anyway break to NONE directly.
1924 * Otherwise vfs_set_filelen() will trigger the
1927 break_to &= ~(SMB2_LEASE_READ|SMB2_LEASE_WRITE);
1932 * Oplocks only support breaking to R or NONE.
1934 break_to &= ~(SMB2_LEASE_HANDLE|SMB2_LEASE_WRITE);
1937 DEBUG(10, ("breaking from %d to %d\n",
1938 (int)e_lease_type, (int)break_to));
1939 send_break_message(fsp->conn->sconn->msg_ctx, &fsp->file_id,
1941 if (e_lease_type & delay_mask) {
1944 if (lease_is_breaking && !first_open_attempt) {
1953 static bool file_has_brlocks(files_struct *fsp)
1955 struct byte_range_lock *br_lck;
1957 br_lck = brl_get_locks_readonly(fsp);
1961 return (brl_num_locks(br_lck) > 0);
1964 int find_share_mode_lease(struct share_mode_data *d,
1965 const struct GUID *client_guid,
1966 const struct smb2_lease_key *key)
1970 for (i=0; i<d->num_leases; i++) {
1971 struct share_mode_lease *l = &d->leases[i];
1973 if (smb2_lease_equal(client_guid,
1984 struct fsp_lease *find_fsp_lease(struct files_struct *new_fsp,
1985 const struct smb2_lease_key *key,
1986 uint32_t current_state,
1987 uint16_t lease_version,
1988 uint16_t lease_epoch)
1990 struct files_struct *fsp;
1993 * TODO: Measure how expensive this loop is with thousands of open
1997 for (fsp = file_find_di_first(new_fsp->conn->sconn, new_fsp->file_id);
1999 fsp = file_find_di_next(fsp)) {
2001 if (fsp == new_fsp) {
2004 if (fsp->oplock_type != LEASE_OPLOCK) {
2007 if (smb2_lease_key_equal(&fsp->lease->lease.lease_key, key)) {
2008 fsp->lease->ref_count += 1;
2013 /* Not found - must be leased in another smbd. */
2014 new_fsp->lease = talloc_zero(new_fsp->conn->sconn, struct fsp_lease);
2015 if (new_fsp->lease == NULL) {
2018 new_fsp->lease->ref_count = 1;
2019 new_fsp->lease->sconn = new_fsp->conn->sconn;
2020 new_fsp->lease->lease.lease_key = *key;
2021 new_fsp->lease->lease.lease_state = current_state;
2023 * We internally treat all leases as V2 and update
2024 * the epoch, but when sending breaks it matters if
2025 * the requesting lease was v1 or v2.
2027 new_fsp->lease->lease.lease_version = lease_version;
2028 new_fsp->lease->lease.lease_epoch = lease_epoch;
2029 return new_fsp->lease;
2032 static NTSTATUS grant_fsp_lease(struct files_struct *fsp,
2033 struct share_mode_lock *lck,
2034 const struct smb2_lease *lease,
2035 uint32_t *p_lease_idx,
2038 struct share_mode_data *d = lck->data;
2039 const struct GUID *client_guid = fsp_client_guid(fsp);
2040 struct share_mode_lease *tmp;
2044 idx = find_share_mode_lease(d, client_guid, &lease->lease_key);
2047 struct share_mode_lease *l = &d->leases[idx];
2049 uint32_t existing, requested;
2051 fsp->lease = find_fsp_lease(
2057 if (fsp->lease == NULL) {
2058 DEBUG(1, ("Did not find existing lease for file %s\n",
2060 return NT_STATUS_NO_MEMORY;
2066 * Upgrade only if the requested lease is a strict upgrade.
2068 existing = l->current_state;
2069 requested = lease->lease_state;
2072 * Tricky: This test makes sure that "requested" is a
2073 * strict bitwise superset of "existing".
2075 do_upgrade = ((existing & requested) == existing);
2078 * Upgrade only if there's a change.
2080 do_upgrade &= (granted != existing);
2083 * Upgrade only if other leases don't prevent what was asked
2086 do_upgrade &= (granted == requested);
2089 * only upgrade if we are not in breaking state
2091 do_upgrade &= !l->breaking;
2093 DEBUG(10, ("existing=%"PRIu32", requested=%"PRIu32", "
2094 "granted=%"PRIu32", do_upgrade=%d\n",
2095 existing, requested, granted, (int)do_upgrade));
2098 l->current_state = granted;
2103 NTSTATUS set_status;
2105 set_status = leases_db_set(
2110 l->breaking_to_requested,
2111 l->breaking_to_required,
2115 if (!NT_STATUS_IS_OK(set_status)) {
2116 DBG_DEBUG("leases_db_set failed: %s\n",
2117 nt_errstr(set_status));
2122 /* Ensure we're in sync with current lease state. */
2123 fsp_lease_update(lck, fsp_client_guid(fsp), fsp->lease);
2124 return NT_STATUS_OK;
2131 tmp = talloc_realloc(d, d->leases, struct share_mode_lease,
2137 return NT_STATUS_INSUFFICIENT_RESOURCES;
2141 fsp->lease = talloc_zero(fsp->conn->sconn, struct fsp_lease);
2142 if (fsp->lease == NULL) {
2143 return NT_STATUS_INSUFFICIENT_RESOURCES;
2145 fsp->lease->ref_count = 1;
2146 fsp->lease->sconn = fsp->conn->sconn;
2147 fsp->lease->lease.lease_version = lease->lease_version;
2148 fsp->lease->lease.lease_key = lease->lease_key;
2149 fsp->lease->lease.lease_state = granted;
2150 fsp->lease->lease.lease_epoch = lease->lease_epoch + 1;
2152 *p_lease_idx = d->num_leases;
2154 d->leases[d->num_leases] = (struct share_mode_lease) {
2155 .client_guid = *client_guid,
2156 .lease_key = fsp->lease->lease.lease_key,
2157 .current_state = fsp->lease->lease.lease_state,
2158 .lease_version = fsp->lease->lease.lease_version,
2159 .epoch = fsp->lease->lease.lease_epoch,
2162 status = leases_db_add(client_guid,
2165 fsp->lease->lease.lease_state,
2166 fsp->lease->lease.lease_version,
2167 fsp->lease->lease.lease_epoch,
2168 fsp->conn->connectpath,
2169 fsp->fsp_name->base_name,
2170 fsp->fsp_name->stream_name);
2171 if (!NT_STATUS_IS_OK(status)) {
2172 DEBUG(10, ("%s: leases_db_add failed: %s\n", __func__,
2173 nt_errstr(status)));
2174 TALLOC_FREE(fsp->lease);
2175 return NT_STATUS_INSUFFICIENT_RESOURCES;
2181 return NT_STATUS_OK;
2184 static bool is_same_lease(const files_struct *fsp,
2185 const struct share_mode_data *d,
2186 const struct share_mode_entry *e,
2187 const struct smb2_lease *lease)
2189 if (e->op_type != LEASE_OPLOCK) {
2192 if (lease == NULL) {
2196 return smb2_lease_equal(fsp_client_guid(fsp),
2198 &d->leases[e->lease_idx].client_guid,
2199 &d->leases[e->lease_idx].lease_key);
2202 static int map_lease_type_to_oplock(uint32_t lease_type)
2204 int result = NO_OPLOCK;
2206 switch (lease_type) {
2207 case SMB2_LEASE_READ|SMB2_LEASE_WRITE|SMB2_LEASE_HANDLE:
2208 result = BATCH_OPLOCK|EXCLUSIVE_OPLOCK;
2210 case SMB2_LEASE_READ|SMB2_LEASE_WRITE:
2211 result = EXCLUSIVE_OPLOCK;
2213 case SMB2_LEASE_READ|SMB2_LEASE_HANDLE:
2214 case SMB2_LEASE_READ:
2215 result = LEVEL_II_OPLOCK;
2222 static NTSTATUS grant_fsp_oplock_type(struct smb_request *req,
2223 struct files_struct *fsp,
2224 struct share_mode_lock *lck,
2226 struct smb2_lease *lease)
2228 struct share_mode_data *d = lck->data;
2229 bool got_handle_lease = false;
2230 bool got_oplock = false;
2233 uint32_t lease_idx = UINT32_MAX;
2237 if (oplock_request & INTERNAL_OPEN_ONLY) {
2238 /* No oplocks on internal open. */
2239 oplock_request = NO_OPLOCK;
2240 DEBUG(10,("grant_fsp_oplock_type: oplock type 0x%x on file %s\n",
2241 fsp->oplock_type, fsp_str_dbg(fsp)));
2244 if (oplock_request == LEASE_OPLOCK) {
2245 if (lease == NULL) {
2247 * The SMB2 layer should have checked this
2249 return NT_STATUS_INTERNAL_ERROR;
2252 granted = lease->lease_state;
2254 if (lp_kernel_oplocks(SNUM(fsp->conn))) {
2255 DEBUG(10, ("No lease granted because kernel oplocks are enabled\n"));
2256 granted = SMB2_LEASE_NONE;
2258 if ((granted & (SMB2_LEASE_READ|SMB2_LEASE_WRITE)) == 0) {
2259 DEBUG(10, ("No read or write lease requested\n"));
2260 granted = SMB2_LEASE_NONE;
2262 if (granted == SMB2_LEASE_WRITE) {
2263 DEBUG(10, ("pure write lease requested\n"));
2264 granted = SMB2_LEASE_NONE;
2266 if (granted == (SMB2_LEASE_WRITE|SMB2_LEASE_HANDLE)) {
2267 DEBUG(10, ("write and handle lease requested\n"));
2268 granted = SMB2_LEASE_NONE;
2271 granted = map_oplock_to_lease_type(
2272 oplock_request & ~SAMBA_PRIVATE_OPLOCK_MASK);
2275 if (lp_locking(fsp->conn->params) && file_has_brlocks(fsp)) {
2276 DEBUG(10,("grant_fsp_oplock_type: file %s has byte range locks\n",
2278 granted &= ~SMB2_LEASE_READ;
2281 for (i=0; i<d->num_share_modes; i++) {
2282 struct share_mode_entry *e = &d->share_modes[i];
2283 uint32_t e_lease_type;
2285 e_lease_type = get_lease_type(d, e);
2287 if ((granted & SMB2_LEASE_WRITE) &&
2288 !is_same_lease(fsp, d, e, lease) &&
2289 !share_mode_stale_pid(d, i)) {
2291 * Can grant only one writer
2293 granted &= ~SMB2_LEASE_WRITE;
2296 if ((e_lease_type & SMB2_LEASE_HANDLE) && !got_handle_lease &&
2297 !share_mode_stale_pid(d, i)) {
2298 got_handle_lease = true;
2301 if ((e->op_type != LEASE_OPLOCK) && !got_oplock &&
2302 !share_mode_stale_pid(d, i)) {
2307 if ((granted & SMB2_LEASE_READ) && !(granted & SMB2_LEASE_WRITE)) {
2309 (global_client_caps & CAP_LEVEL_II_OPLOCKS) &&
2310 lp_level2_oplocks(SNUM(fsp->conn));
2312 if (!allow_level2) {
2313 granted = SMB2_LEASE_NONE;
2317 if (oplock_request == LEASE_OPLOCK) {
2319 granted &= ~SMB2_LEASE_HANDLE;
2322 fsp->oplock_type = LEASE_OPLOCK;
2324 status = grant_fsp_lease(fsp, lck, lease, &lease_idx,
2326 if (!NT_STATUS_IS_OK(status)) {
2330 *lease = fsp->lease->lease;
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(lck, fsp, get_current_uid(fsp->conn),
2353 return NT_STATUS_NO_MEMORY;
2356 ok = update_num_read_oplocks(fsp, lck);
2358 del_share_mode(lck, fsp);
2359 return NT_STATUS_INTERNAL_ERROR;
2362 DEBUG(10,("grant_fsp_oplock_type: oplock type 0x%x on file %s\n",
2363 fsp->oplock_type, fsp_str_dbg(fsp)));
2365 return NT_STATUS_OK;
2368 static bool request_timed_out(struct timeval request_time,
2369 struct timeval timeout)
2371 struct timeval now, end_time;
2373 end_time = timeval_sum(&request_time, &timeout);
2374 return (timeval_compare(&end_time, &now) < 0);
2377 static struct deferred_open_record *deferred_open_record_create(
2378 bool delayed_for_oplocks,
2382 struct deferred_open_record *record = NULL;
2384 record = talloc(NULL, struct deferred_open_record);
2385 if (record == NULL) {
2389 *record = (struct deferred_open_record) {
2390 .delayed_for_oplocks = delayed_for_oplocks,
2391 .async_open = async_open,
2398 struct defer_open_state {
2399 struct smbXsrv_connection *xconn;
2403 static void defer_open_done(struct tevent_req *req);
2406 * Defer an open and watch a locking.tdb record
2408 * This defers an open that gets rescheduled once the locking.tdb record watch
2409 * is triggered by a change to the record.
2411 * It is used to defer opens that triggered an oplock break and for the SMB1
2412 * sharing violation delay.
2414 static void defer_open(struct share_mode_lock *lck,
2415 struct timeval request_time,
2416 struct timeval timeout,
2417 struct smb_request *req,
2418 bool delayed_for_oplocks,
2421 struct deferred_open_record *open_rec = NULL;
2422 struct timeval abs_timeout;
2423 struct defer_open_state *watch_state;
2424 struct tevent_req *watch_req;
2427 abs_timeout = timeval_sum(&request_time, &timeout);
2429 DBG_DEBUG("request time [%s] timeout [%s] mid [%" PRIu64 "] "
2430 "delayed_for_oplocks [%s] file_id [%s]\n",
2431 timeval_string(talloc_tos(), &request_time, false),
2432 timeval_string(talloc_tos(), &abs_timeout, false),
2434 delayed_for_oplocks ? "yes" : "no",
2435 file_id_string_tos(&id));
2437 open_rec = deferred_open_record_create(delayed_for_oplocks,
2440 if (open_rec == NULL) {
2442 exit_server("talloc failed");
2445 watch_state = talloc(open_rec, struct defer_open_state);
2446 if (watch_state == NULL) {
2447 exit_server("talloc failed");
2449 watch_state->xconn = req->xconn;
2450 watch_state->mid = req->mid;
2452 DBG_DEBUG("defering mid %" PRIu64 "\n", req->mid);
2454 watch_req = dbwrap_watched_watch_send(watch_state,
2457 (struct server_id){0});
2458 if (watch_req == NULL) {
2459 exit_server("Could not watch share mode record");
2461 tevent_req_set_callback(watch_req, defer_open_done, watch_state);
2463 ok = tevent_req_set_endtime(watch_req, req->sconn->ev_ctx, abs_timeout);
2465 exit_server("tevent_req_set_endtime failed");
2468 ok = push_deferred_open_message_smb(req, request_time, timeout,
2469 open_rec->id, open_rec);
2472 exit_server("push_deferred_open_message_smb failed");
2476 static void defer_open_done(struct tevent_req *req)
2478 struct defer_open_state *state = tevent_req_callback_data(
2479 req, struct defer_open_state);
2483 status = dbwrap_watched_watch_recv(req, NULL, NULL);
2485 if (!NT_STATUS_IS_OK(status)) {
2486 DEBUG(5, ("dbwrap_watched_watch_recv returned %s\n",
2487 nt_errstr(status)));
2489 * Even if it failed, retry anyway. TODO: We need a way to
2490 * tell a re-scheduled open about that error.
2494 DEBUG(10, ("scheduling mid %llu\n", (unsigned long long)state->mid));
2496 ret = schedule_deferred_open_message_smb(state->xconn, state->mid);
2502 * Actually attempt the kernel oplock polling open.
2505 static void kernel_oplock_poll_open_timer(struct tevent_context *ev,
2506 struct tevent_timer *te,
2507 struct timeval current_time,
2511 struct smb_request *req = (struct smb_request *)private_data;
2513 ok = schedule_deferred_open_message_smb(req->xconn, req->mid);
2515 exit_server("schedule_deferred_open_message_smb failed");
2517 DBG_DEBUG("kernel_oplock_poll_open_timer fired. Retying open !\n");
2521 * Reschedule an open for 1 second from now, if not timed out.
2523 static void setup_kernel_oplock_poll_open(struct timeval request_time,
2524 struct smb_request *req,
2529 struct deferred_open_record *open_rec = NULL;
2530 /* Maximum wait time. */
2531 struct timeval timeout = timeval_set(OPLOCK_BREAK_TIMEOUT*2, 0);
2533 if (request_timed_out(request_time, timeout)) {
2537 open_rec = deferred_open_record_create(false, false, id);
2538 if (open_rec == NULL) {
2539 exit_server("talloc failed");
2542 ok = push_deferred_open_message_smb(req,
2548 exit_server("push_deferred_open_message_smb failed");
2552 * As this timer event is owned by req, it will
2553 * disappear if req it talloc_freed.
2555 open_rec->te = tevent_add_timer(req->sconn->ev_ctx,
2557 timeval_current_ofs(1, 0),
2558 kernel_oplock_poll_open_timer,
2560 if (open_rec->te == NULL) {
2561 exit_server("tevent_add_timer failed");
2564 DBG_DEBUG("poll request time [%s] mid [%" PRIu64 "] file_id [%s]\n",
2565 timeval_string(talloc_tos(), &request_time, false),
2567 file_id_string_tos(&id));
2570 /****************************************************************************
2571 On overwrite open ensure that the attributes match.
2572 ****************************************************************************/
2574 static bool open_match_attributes(connection_struct *conn,
2575 uint32_t old_dos_attr,
2576 uint32_t new_dos_attr,
2577 mode_t new_unx_mode,
2578 mode_t *returned_unx_mode)
2580 uint32_t noarch_old_dos_attr, noarch_new_dos_attr;
2582 noarch_old_dos_attr = (old_dos_attr & ~FILE_ATTRIBUTE_ARCHIVE);
2583 noarch_new_dos_attr = (new_dos_attr & ~FILE_ATTRIBUTE_ARCHIVE);
2585 if((noarch_old_dos_attr == 0 && noarch_new_dos_attr != 0) ||
2586 (noarch_old_dos_attr != 0 && ((noarch_old_dos_attr & noarch_new_dos_attr) == noarch_old_dos_attr))) {
2587 *returned_unx_mode = new_unx_mode;
2589 *returned_unx_mode = (mode_t)0;
2592 DEBUG(10,("open_match_attributes: old_dos_attr = 0x%x, "
2593 "new_dos_attr = 0x%x "
2594 "returned_unx_mode = 0%o\n",
2595 (unsigned int)old_dos_attr,
2596 (unsigned int)new_dos_attr,
2597 (unsigned int)*returned_unx_mode ));
2599 /* If we're mapping SYSTEM and HIDDEN ensure they match. */
2600 if (lp_map_system(SNUM(conn)) || lp_store_dos_attributes(SNUM(conn))) {
2601 if ((old_dos_attr & FILE_ATTRIBUTE_SYSTEM) &&
2602 !(new_dos_attr & FILE_ATTRIBUTE_SYSTEM)) {
2606 if (lp_map_hidden(SNUM(conn)) || lp_store_dos_attributes(SNUM(conn))) {
2607 if ((old_dos_attr & FILE_ATTRIBUTE_HIDDEN) &&
2608 !(new_dos_attr & FILE_ATTRIBUTE_HIDDEN)) {
2615 /****************************************************************************
2616 Special FCB or DOS processing in the case of a sharing violation.
2617 Try and find a duplicated file handle.
2618 ****************************************************************************/
2620 static NTSTATUS fcb_or_dos_open(struct smb_request *req,
2621 connection_struct *conn,
2622 files_struct *fsp_to_dup_into,
2623 const struct smb_filename *smb_fname,
2627 uint32_t access_mask,
2628 uint32_t share_access,
2629 uint32_t create_options)
2633 DEBUG(5,("fcb_or_dos_open: attempting old open semantics for "
2634 "file %s.\n", smb_fname_str_dbg(smb_fname)));
2636 for(fsp = file_find_di_first(conn->sconn, id); fsp;
2637 fsp = file_find_di_next(fsp)) {
2639 DEBUG(10,("fcb_or_dos_open: checking file %s, fd = %d, "
2640 "vuid = %llu, file_pid = %u, private_options = 0x%x "
2641 "access_mask = 0x%x\n", fsp_str_dbg(fsp),
2642 fsp->fh->fd, (unsigned long long)fsp->vuid,
2643 (unsigned int)fsp->file_pid,
2644 (unsigned int)fsp->fh->private_options,
2645 (unsigned int)fsp->access_mask ));
2647 if (fsp != fsp_to_dup_into &&
2648 fsp->fh->fd != -1 &&
2649 fsp->vuid == vuid &&
2650 fsp->file_pid == file_pid &&
2651 (fsp->fh->private_options & (NTCREATEX_OPTIONS_PRIVATE_DENY_DOS |
2652 NTCREATEX_OPTIONS_PRIVATE_DENY_FCB)) &&
2653 (fsp->access_mask & FILE_WRITE_DATA) &&
2654 strequal(fsp->fsp_name->base_name, smb_fname->base_name) &&
2655 strequal(fsp->fsp_name->stream_name,
2656 smb_fname->stream_name)) {
2657 DEBUG(10,("fcb_or_dos_open: file match\n"));
2663 return NT_STATUS_NOT_FOUND;
2666 /* quite an insane set of semantics ... */
2667 if (is_executable(smb_fname->base_name) &&
2668 (fsp->fh->private_options & NTCREATEX_OPTIONS_PRIVATE_DENY_DOS)) {
2669 DEBUG(10,("fcb_or_dos_open: file fail due to is_executable.\n"));
2670 return NT_STATUS_INVALID_PARAMETER;
2673 /* We need to duplicate this fsp. */
2674 return dup_file_fsp(req, fsp, access_mask, share_access,
2675 create_options, fsp_to_dup_into);
2678 static void schedule_defer_open(struct share_mode_lock *lck,
2680 struct timeval request_time,
2681 struct smb_request *req)
2683 /* This is a relative time, added to the absolute
2684 request_time value to get the absolute timeout time.
2685 Note that if this is the second or greater time we enter
2686 this codepath for this particular request mid then
2687 request_time is left as the absolute time of the *first*
2688 time this request mid was processed. This is what allows
2689 the request to eventually time out. */
2691 struct timeval timeout;
2693 /* Normally the smbd we asked should respond within
2694 * OPLOCK_BREAK_TIMEOUT seconds regardless of whether
2695 * the client did, give twice the timeout as a safety
2696 * measure here in case the other smbd is stuck
2697 * somewhere else. */
2699 timeout = timeval_set(OPLOCK_BREAK_TIMEOUT*2, 0);
2701 if (request_timed_out(request_time, timeout)) {
2705 defer_open(lck, request_time, timeout, req, true, id);
2708 /****************************************************************************
2709 Reschedule an open call that went asynchronous.
2710 ****************************************************************************/
2712 static void schedule_async_open_timer(struct tevent_context *ev,
2713 struct tevent_timer *te,
2714 struct timeval current_time,
2717 exit_server("async open timeout");
2720 static void schedule_async_open(struct timeval request_time,
2721 struct smb_request *req)
2723 struct deferred_open_record *open_rec = NULL;
2724 struct timeval timeout = timeval_set(20, 0);
2727 if (request_timed_out(request_time, timeout)) {
2731 open_rec = deferred_open_record_create(false, true, (struct file_id){0});
2732 if (open_rec == NULL) {
2733 exit_server("deferred_open_record_create failed");
2736 ok = push_deferred_open_message_smb(req, request_time, timeout,
2737 (struct file_id){0}, open_rec);
2739 exit_server("push_deferred_open_message_smb failed");
2742 open_rec->te = tevent_add_timer(req->sconn->ev_ctx,
2744 timeval_current_ofs(20, 0),
2745 schedule_async_open_timer,
2747 if (open_rec->te == NULL) {
2748 exit_server("tevent_add_timer failed");
2752 /****************************************************************************
2753 Work out what access_mask to use from what the client sent us.
2754 ****************************************************************************/
2756 static NTSTATUS smbd_calculate_maximum_allowed_access(
2757 connection_struct *conn,
2758 const struct smb_filename *smb_fname,
2760 uint32_t *p_access_mask)
2762 struct security_descriptor *sd;
2763 uint32_t access_granted;
2766 if (!use_privs && (get_current_uid(conn) == (uid_t)0)) {
2767 *p_access_mask |= FILE_GENERIC_ALL;
2768 return NT_STATUS_OK;
2771 status = SMB_VFS_GET_NT_ACL(conn, smb_fname,
2777 if (NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
2779 * File did not exist
2781 *p_access_mask = FILE_GENERIC_ALL;
2782 return NT_STATUS_OK;
2784 if (!NT_STATUS_IS_OK(status)) {
2785 DEBUG(10,("Could not get acl on file %s: %s\n",
2786 smb_fname_str_dbg(smb_fname),
2787 nt_errstr(status)));
2788 return NT_STATUS_ACCESS_DENIED;
2792 * If we can access the path to this file, by
2793 * default we have FILE_READ_ATTRIBUTES from the
2794 * containing directory. See the section:
2795 * "Algorithm to Check Access to an Existing File"
2798 * se_file_access_check()
2799 * also takes care of owner WRITE_DAC and READ_CONTROL.
2801 status = se_file_access_check(sd,
2802 get_current_nttok(conn),
2804 (*p_access_mask & ~FILE_READ_ATTRIBUTES),
2809 if (!NT_STATUS_IS_OK(status)) {
2810 DEBUG(10, ("Access denied on file %s: "
2811 "when calculating maximum access\n",
2812 smb_fname_str_dbg(smb_fname)));
2813 return NT_STATUS_ACCESS_DENIED;
2815 *p_access_mask = (access_granted | FILE_READ_ATTRIBUTES);
2817 if (!(access_granted & DELETE_ACCESS)) {
2818 if (can_delete_file_in_directory(conn, smb_fname)) {
2819 *p_access_mask |= DELETE_ACCESS;
2823 return NT_STATUS_OK;
2826 NTSTATUS smbd_calculate_access_mask(connection_struct *conn,
2827 const struct smb_filename *smb_fname,
2829 uint32_t access_mask,
2830 uint32_t *access_mask_out)
2833 uint32_t orig_access_mask = access_mask;
2834 uint32_t rejected_share_access;
2836 if (access_mask & SEC_MASK_INVALID) {
2837 DBG_DEBUG("access_mask [%8x] contains invalid bits\n",
2839 return NT_STATUS_ACCESS_DENIED;
2843 * Convert GENERIC bits to specific bits.
2846 se_map_generic(&access_mask, &file_generic_mapping);
2848 /* Calculate MAXIMUM_ALLOWED_ACCESS if requested. */
2849 if (access_mask & MAXIMUM_ALLOWED_ACCESS) {
2851 status = smbd_calculate_maximum_allowed_access(
2852 conn, smb_fname, use_privs, &access_mask);
2854 if (!NT_STATUS_IS_OK(status)) {
2858 access_mask &= conn->share_access;
2861 rejected_share_access = access_mask & ~(conn->share_access);
2863 if (rejected_share_access) {
2864 DEBUG(10, ("smbd_calculate_access_mask: Access denied on "
2865 "file %s: rejected by share access mask[0x%08X] "
2866 "orig[0x%08X] mapped[0x%08X] reject[0x%08X]\n",
2867 smb_fname_str_dbg(smb_fname),
2869 orig_access_mask, access_mask,
2870 rejected_share_access));
2871 return NT_STATUS_ACCESS_DENIED;
2874 *access_mask_out = access_mask;
2875 return NT_STATUS_OK;
2878 /****************************************************************************
2879 Remove the deferred open entry under lock.
2880 ****************************************************************************/
2882 /****************************************************************************
2883 Return true if this is a state pointer to an asynchronous create.
2884 ****************************************************************************/
2886 bool is_deferred_open_async(const struct deferred_open_record *rec)
2888 return rec->async_open;
2891 static bool clear_ads(uint32_t create_disposition)
2895 switch (create_disposition) {
2896 case FILE_SUPERSEDE:
2897 case FILE_OVERWRITE_IF:
2898 case FILE_OVERWRITE:
2907 static int disposition_to_open_flags(uint32_t create_disposition)
2912 * Currently we're using FILE_SUPERSEDE as the same as
2913 * FILE_OVERWRITE_IF but they really are
2914 * different. FILE_SUPERSEDE deletes an existing file
2915 * (requiring delete access) then recreates it.
2918 switch (create_disposition) {
2919 case FILE_SUPERSEDE:
2920 case FILE_OVERWRITE_IF:
2922 * If file exists replace/overwrite. If file doesn't
2925 ret = O_CREAT|O_TRUNC;
2930 * If file exists open. If file doesn't exist error.
2935 case FILE_OVERWRITE:
2937 * If file exists overwrite. If file doesn't exist
2945 * If file exists error. If file doesn't exist create.
2947 ret = O_CREAT|O_EXCL;
2952 * If file exists open. If file doesn't exist create.
2960 static int calculate_open_access_flags(uint32_t access_mask,
2961 uint32_t private_flags)
2963 bool need_write, need_read;
2966 * Note that we ignore the append flag as append does not
2967 * mean the same thing under DOS and Unix.
2970 need_write = (access_mask & (FILE_WRITE_DATA | FILE_APPEND_DATA));
2975 /* DENY_DOS opens are always underlying read-write on the
2976 file handle, no matter what the requested access mask
2980 ((private_flags & NTCREATEX_OPTIONS_PRIVATE_DENY_DOS) ||
2981 access_mask & (FILE_READ_ATTRIBUTES|FILE_READ_DATA|
2982 FILE_READ_EA|FILE_EXECUTE));
2990 /****************************************************************************
2991 Open a file with a share mode. Passed in an already created files_struct *.
2992 ****************************************************************************/
2994 static NTSTATUS open_file_ntcreate(connection_struct *conn,
2995 struct smb_request *req,
2996 uint32_t access_mask, /* access bits (FILE_READ_DATA etc.) */
2997 uint32_t share_access, /* share constants (FILE_SHARE_READ etc) */
2998 uint32_t create_disposition, /* FILE_OPEN_IF etc. */
2999 uint32_t create_options, /* options such as delete on close. */
3000 uint32_t new_dos_attributes, /* attributes used for new file. */
3001 int oplock_request, /* internal Samba oplock codes. */
3002 struct smb2_lease *lease,
3003 /* Information (FILE_EXISTS etc.) */
3004 uint32_t private_flags, /* Samba specific flags. */
3008 struct smb_filename *smb_fname = fsp->fsp_name;
3011 bool file_existed = VALID_STAT(smb_fname->st);
3012 bool def_acl = False;
3013 bool posix_open = False;
3014 bool new_file_created = False;
3015 bool first_open_attempt = true;
3016 NTSTATUS fsp_open = NT_STATUS_ACCESS_DENIED;
3017 mode_t new_unx_mode = (mode_t)0;
3018 mode_t unx_mode = (mode_t)0;
3020 uint32_t existing_dos_attributes = 0;
3021 struct timeval request_time = timeval_zero();
3022 struct share_mode_lock *lck = NULL;
3023 uint32_t open_access_mask = access_mask;
3026 SMB_STRUCT_STAT saved_stat = smb_fname->st;
3027 struct timespec old_write_time;
3030 if (conn->printer) {
3032 * Printers are handled completely differently.
3033 * Most of the passed parameters are ignored.
3037 *pinfo = FILE_WAS_CREATED;
3040 DEBUG(10, ("open_file_ntcreate: printer open fname=%s\n",
3041 smb_fname_str_dbg(smb_fname)));
3044 DEBUG(0,("open_file_ntcreate: printer open without "
3045 "an SMB request!\n"));
3046 return NT_STATUS_INTERNAL_ERROR;
3049 return print_spool_open(fsp, smb_fname->base_name,
3053 if (!parent_dirname(talloc_tos(), smb_fname->base_name, &parent_dir,
3055 return NT_STATUS_NO_MEMORY;
3058 if (new_dos_attributes & FILE_FLAG_POSIX_SEMANTICS) {
3060 unx_mode = (mode_t)(new_dos_attributes & ~FILE_FLAG_POSIX_SEMANTICS);
3061 new_dos_attributes = 0;
3063 /* Windows allows a new file to be created and
3064 silently removes a FILE_ATTRIBUTE_DIRECTORY
3065 sent by the client. Do the same. */
3067 new_dos_attributes &= ~FILE_ATTRIBUTE_DIRECTORY;
3069 /* We add FILE_ATTRIBUTE_ARCHIVE to this as this mode is only used if the file is
3071 unx_mode = unix_mode(conn, new_dos_attributes | FILE_ATTRIBUTE_ARCHIVE,
3072 smb_fname, parent_dir);
3075 DEBUG(10, ("open_file_ntcreate: fname=%s, dos_attrs=0x%x "
3076 "access_mask=0x%x share_access=0x%x "
3077 "create_disposition = 0x%x create_options=0x%x "
3078 "unix mode=0%o oplock_request=%d private_flags = 0x%x\n",
3079 smb_fname_str_dbg(smb_fname), new_dos_attributes,
3080 access_mask, share_access, create_disposition,
3081 create_options, (unsigned int)unx_mode, oplock_request,
3082 (unsigned int)private_flags));
3085 /* Ensure req == NULL means INTERNAL_OPEN_ONLY */
3086 SMB_ASSERT(((oplock_request & INTERNAL_OPEN_ONLY) != 0));
3088 /* And req != NULL means no INTERNAL_OPEN_ONLY */
3089 SMB_ASSERT(((oplock_request & INTERNAL_OPEN_ONLY) == 0));
3093 * Only non-internal opens can be deferred at all
3097 struct deferred_open_record *open_rec;
3098 if (get_deferred_open_message_state(req,
3101 /* Remember the absolute time of the original
3102 request with this mid. We'll use it later to
3103 see if this has timed out. */
3105 /* If it was an async create retry, the file
3108 if (is_deferred_open_async(open_rec)) {
3109 SET_STAT_INVALID(smb_fname->st);
3110 file_existed = false;
3113 /* Ensure we don't reprocess this message. */
3114 remove_deferred_open_message_smb(req->xconn, req->mid);
3116 first_open_attempt = false;
3121 new_dos_attributes &= SAMBA_ATTRIBUTES_MASK;
3124 * Only use strored DOS attributes for checks
3125 * against requested attributes (below via
3126 * open_match_attributes()), cf bug #11992
3127 * for details. -slow
3131 status = SMB_VFS_GET_DOS_ATTRIBUTES(conn, smb_fname, &attr);
3132 if (NT_STATUS_IS_OK(status)) {
3133 existing_dos_attributes = attr;
3138 /* ignore any oplock requests if oplocks are disabled */
3139 if (!lp_oplocks(SNUM(conn)) ||
3140 IS_VETO_OPLOCK_PATH(conn, smb_fname->base_name)) {
3141 /* Mask off everything except the private Samba bits. */
3142 oplock_request &= SAMBA_PRIVATE_OPLOCK_MASK;
3145 /* this is for OS/2 long file names - say we don't support them */
3146 if (req != NULL && !req->posix_pathnames &&
3147 strstr(smb_fname->base_name,".+,;=[].")) {
3148 /* OS/2 Workplace shell fix may be main code stream in a later
3150 DEBUG(5,("open_file_ntcreate: OS/2 long filenames are not "
3152 if (use_nt_status()) {
3153 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3155 return NT_STATUS_DOS(ERRDOS, ERRcannotopen);
3158 switch( create_disposition ) {
3160 /* If file exists open. If file doesn't exist error. */
3161 if (!file_existed) {
3162 DEBUG(5,("open_file_ntcreate: FILE_OPEN "
3163 "requested for file %s and file "
3165 smb_fname_str_dbg(smb_fname)));
3167 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3171 case FILE_OVERWRITE:
3172 /* If file exists overwrite. If file doesn't exist
3174 if (!file_existed) {
3175 DEBUG(5,("open_file_ntcreate: FILE_OVERWRITE "
3176 "requested for file %s and file "
3178 smb_fname_str_dbg(smb_fname) ));
3180 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3185 /* If file exists error. If file doesn't exist
3188 DEBUG(5,("open_file_ntcreate: FILE_CREATE "
3189 "requested for file %s and file "
3190 "already exists.\n",
3191 smb_fname_str_dbg(smb_fname)));
3192 if (S_ISDIR(smb_fname->st.st_ex_mode)) {
3197 return map_nt_error_from_unix(errno);
3201 case FILE_SUPERSEDE:
3202 case FILE_OVERWRITE_IF:
3206 return NT_STATUS_INVALID_PARAMETER;
3209 flags2 = disposition_to_open_flags(create_disposition);
3211 /* We only care about matching attributes on file exists and
3214 if (!posix_open && file_existed &&
3215 ((create_disposition == FILE_OVERWRITE) ||
3216 (create_disposition == FILE_OVERWRITE_IF))) {
3217 if (!open_match_attributes(conn, existing_dos_attributes,
3219 unx_mode, &new_unx_mode)) {
3220 DEBUG(5,("open_file_ntcreate: attributes mismatch "
3221 "for file %s (%x %x) (0%o, 0%o)\n",
3222 smb_fname_str_dbg(smb_fname),
3223 existing_dos_attributes,
3225 (unsigned int)smb_fname->st.st_ex_mode,
3226 (unsigned int)unx_mode ));
3228 return NT_STATUS_ACCESS_DENIED;
3232 status = smbd_calculate_access_mask(conn, smb_fname,
3236 if (!NT_STATUS_IS_OK(status)) {
3237 DEBUG(10, ("open_file_ntcreate: smbd_calculate_access_mask "
3238 "on file %s returned %s\n",
3239 smb_fname_str_dbg(smb_fname), nt_errstr(status)));
3243 open_access_mask = access_mask;
3245 if (flags2 & O_TRUNC) {
3246 open_access_mask |= FILE_WRITE_DATA; /* This will cause oplock breaks. */
3249 DEBUG(10, ("open_file_ntcreate: fname=%s, after mapping "
3250 "access_mask=0x%x\n", smb_fname_str_dbg(smb_fname),
3254 * Note that we ignore the append flag as append does not
3255 * mean the same thing under DOS and Unix.
3258 flags = calculate_open_access_flags(access_mask, private_flags);
3261 * Currently we only look at FILE_WRITE_THROUGH for create options.
3265 if ((create_options & FILE_WRITE_THROUGH) && lp_strict_sync(SNUM(conn))) {
3270 if (posix_open && (access_mask & FILE_APPEND_DATA)) {
3274 if (!posix_open && !CAN_WRITE(conn)) {
3276 * We should really return a permission denied error if either
3277 * O_CREAT or O_TRUNC are set, but for compatibility with
3278 * older versions of Samba we just AND them out.
3280 flags2 &= ~(O_CREAT|O_TRUNC);
3283 if (lp_kernel_oplocks(SNUM(conn))) {
3285 * With kernel oplocks the open breaking an oplock
3286 * blocks until the oplock holder has given up the
3287 * oplock or closed the file. We prevent this by always
3288 * trying to open the file with O_NONBLOCK (see "man
3291 * If a process that doesn't use the smbd open files
3292 * database or communication methods holds a kernel
3293 * oplock we must periodically poll for available open
3296 flags2 |= O_NONBLOCK;
3300 * Ensure we can't write on a read-only share or file.
3303 if (flags != O_RDONLY && file_existed &&
3304 (!CAN_WRITE(conn) || IS_DOS_READONLY(existing_dos_attributes))) {
3305 DEBUG(5,("open_file_ntcreate: write access requested for "
3306 "file %s on read only %s\n",
3307 smb_fname_str_dbg(smb_fname),
3308 !CAN_WRITE(conn) ? "share" : "file" ));
3310 return NT_STATUS_ACCESS_DENIED;
3313 fsp->file_id = vfs_file_id_from_sbuf(conn, &smb_fname->st);
3314 fsp->share_access = share_access;
3315 fsp->fh->private_options = private_flags;
3316 fsp->access_mask = open_access_mask; /* We change this to the
3317 * requested access_mask after
3318 * the open is done. */
3320 fsp->posix_flags |= FSP_POSIX_FLAGS_ALL;
3323 if (timeval_is_zero(&request_time)) {
3324 request_time = fsp->open_time;
3327 if ((create_options & FILE_DELETE_ON_CLOSE) &&
3328 (flags2 & O_CREAT) &&
3330 /* Delete on close semantics for new files. */
3331 status = can_set_delete_on_close(fsp,
3332 new_dos_attributes);
3333 if (!NT_STATUS_IS_OK(status)) {
3340 * Ensure we pay attention to default ACLs on directories if required.
3343 if ((flags2 & O_CREAT) && lp_inherit_acls(SNUM(conn)) &&
3344 (def_acl = directory_has_default_acl(conn, parent_dir))) {
3345 unx_mode = (0777 & lp_create_mask(SNUM(conn)));
3348 DEBUG(4,("calling open_file with flags=0x%X flags2=0x%X mode=0%o, "
3349 "access_mask = 0x%x, open_access_mask = 0x%x\n",
3350 (unsigned int)flags, (unsigned int)flags2,
3351 (unsigned int)unx_mode, (unsigned int)access_mask,
3352 (unsigned int)open_access_mask));
3354 fsp_open = open_file(fsp, conn, req, parent_dir,
3355 flags|flags2, unx_mode, access_mask,
3356 open_access_mask, &new_file_created);
3358 if (NT_STATUS_EQUAL(fsp_open, NT_STATUS_NETWORK_BUSY)) {
3362 * This handles the kernel oplock case:
3364 * the file has an active kernel oplock and the open() returned
3365 * EWOULDBLOCK/EAGAIN which maps to NETWORK_BUSY.
3367 * "Samba locking.tdb oplocks" are handled below after acquiring
3368 * the sharemode lock with get_share_mode_lock().
3370 if (file_existed && S_ISFIFO(fsp->fsp_name->st.st_ex_mode)) {
3371 DEBUG(10, ("FIFO busy\n"));
3372 return NT_STATUS_NETWORK_BUSY;
3375 DEBUG(10, ("Internal open busy\n"));
3376 return NT_STATUS_NETWORK_BUSY;
3380 * From here on we assume this is an oplock break triggered
3383 lck = get_existing_share_mode_lock(talloc_tos(), fsp->file_id);
3386 * No oplock from Samba around. Set up a poll every 1
3387 * second to retry a non-blocking open until the time
3390 setup_kernel_oplock_poll_open(request_time,
3393 DBG_DEBUG("No Samba oplock around after EWOULDBLOCK. "
3394 "Retrying with poll\n");
3395 return NT_STATUS_SHARING_VIOLATION;
3398 if (!validate_oplock_types(lck)) {
3399 smb_panic("validate_oplock_types failed");
3402 delay = delay_for_oplock(fsp, 0, lease, lck, false,
3404 first_open_attempt);
3406 schedule_defer_open(lck, fsp->file_id, request_time,
3409 DEBUG(10, ("Sent oplock break request to kernel "
3410 "oplock holder\n"));
3411 return NT_STATUS_SHARING_VIOLATION;
3415 * No oplock from Samba around. Set up a poll every 1
3416 * second to retry a non-blocking open until the time
3419 setup_kernel_oplock_poll_open(request_time, req, fsp->file_id);
3422 DBG_DEBUG("No Samba oplock around after EWOULDBLOCK. "
3423 "Retrying with poll\n");
3424 return NT_STATUS_SHARING_VIOLATION;
3427 if (!NT_STATUS_IS_OK(fsp_open)) {
3428 if (NT_STATUS_EQUAL(fsp_open, NT_STATUS_RETRY)) {
3429 schedule_async_open(request_time, req);
3434 if (new_file_created) {
3436 * As we atomically create using O_CREAT|O_EXCL,
3437 * then if new_file_created is true, then
3438 * file_existed *MUST* have been false (even
3439 * if the file was previously detected as being
3442 file_existed = false;
3445 if (file_existed && !check_same_dev_ino(&saved_stat, &smb_fname->st)) {
3447 * The file did exist, but some other (local or NFS)
3448 * process either renamed/unlinked and re-created the
3449 * file with different dev/ino after we walked the path,
3450 * but before we did the open. We could retry the
3451 * open but it's a rare enough case it's easier to
3452 * just fail the open to prevent creating any problems
3453 * in the open file db having the wrong dev/ino key.
3456 DBG_WARNING("file %s - dev/ino mismatch. "
3457 "Old (dev=%ju, ino=%ju). "
3458 "New (dev=%ju, ino=%ju). Failing open "
3459 "with NT_STATUS_ACCESS_DENIED.\n",
3460 smb_fname_str_dbg(smb_fname),
3461 (uintmax_t)saved_stat.st_ex_dev,
3462 (uintmax_t)saved_stat.st_ex_ino,
3463 (uintmax_t)smb_fname->st.st_ex_dev,
3464 (uintmax_t)smb_fname->st.st_ex_ino);
3465 return NT_STATUS_ACCESS_DENIED;
3468 old_write_time = smb_fname->st.st_ex_mtime;
3471 * Deal with the race condition where two smbd's detect the
3472 * file doesn't exist and do the create at the same time. One
3473 * of them will win and set a share mode, the other (ie. this
3474 * one) should check if the requested share mode for this
3475 * create is allowed.
3479 * Now the file exists and fsp is successfully opened,
3480 * fsp->dev and fsp->inode are valid and should replace the
3481 * dev=0,inode=0 from a non existent file. Spotted by
3482 * Nadav Danieli <nadavd@exanet.com>. JRA.
3487 lck = get_share_mode_lock(talloc_tos(), id,
3489 smb_fname, &old_write_time);
3492 DEBUG(0, ("open_file_ntcreate: Could not get share "
3493 "mode lock for %s\n",
3494 smb_fname_str_dbg(smb_fname)));
3496 return NT_STATUS_SHARING_VIOLATION;
3499 /* Get the types we need to examine. */
3500 if (!validate_oplock_types(lck)) {
3501 smb_panic("validate_oplock_types failed");
3504 if (has_delete_on_close(lck, fsp->name_hash)) {
3507 return NT_STATUS_DELETE_PENDING;
3510 status = open_mode_check(conn, lck,
3511 access_mask, share_access);
3513 if (NT_STATUS_EQUAL(status, NT_STATUS_SHARING_VIOLATION) ||
3514 (lck->data->num_share_modes > 0)) {
3516 * This comes from ancient times out of open_mode_check. I
3517 * have no clue whether this is still necessary. I can't think
3518 * of a case where this would actually matter further down in
3519 * this function. I leave it here for further investigation
3522 file_existed = true;
3527 * Handle oplocks, deferring the request if delay_for_oplock()
3528 * triggered a break message and we have to wait for the break
3532 bool sharing_violation = NT_STATUS_EQUAL(
3533 status, NT_STATUS_SHARING_VIOLATION);
3535 delay = delay_for_oplock(fsp, oplock_request, lease, lck,
3538 first_open_attempt);
3540 schedule_defer_open(lck, fsp->file_id,
3544 return NT_STATUS_SHARING_VIOLATION;
3548 if (!NT_STATUS_IS_OK(status)) {
3549 uint32_t can_access_mask;
3550 bool can_access = True;
3552 SMB_ASSERT(NT_STATUS_EQUAL(status, NT_STATUS_SHARING_VIOLATION));
3554 /* Check if this can be done with the deny_dos and fcb
3557 (NTCREATEX_OPTIONS_PRIVATE_DENY_DOS|
3558 NTCREATEX_OPTIONS_PRIVATE_DENY_FCB)) {
3560 DEBUG(0, ("DOS open without an SMB "
3564 return NT_STATUS_INTERNAL_ERROR;
3567 /* Use the client requested access mask here,
3568 * not the one we open with. */
3569 status = fcb_or_dos_open(req,
3580 if (NT_STATUS_IS_OK(status)) {
3583 *pinfo = FILE_WAS_OPENED;
3585 return NT_STATUS_OK;
3590 * This next line is a subtlety we need for
3591 * MS-Access. If a file open will fail due to share
3592 * permissions and also for security (access) reasons,
3593 * we need to return the access failed error, not the
3594 * share error. We can't open the file due to kernel
3595 * oplock deadlock (it's possible we failed above on
3596 * the open_mode_check()) so use a userspace check.
3599 if (flags & O_RDWR) {
3600 can_access_mask = FILE_READ_DATA|FILE_WRITE_DATA;
3601 } else if (flags & O_WRONLY) {
3602 can_access_mask = FILE_WRITE_DATA;
3604 can_access_mask = FILE_READ_DATA;
3607 if (((can_access_mask & FILE_WRITE_DATA) &&
3608 !CAN_WRITE(conn)) ||
3609 !NT_STATUS_IS_OK(smbd_check_access_rights(conn,
3612 can_access_mask))) {
3617 * If we're returning a share violation, ensure we
3618 * cope with the braindead 1 second delay (SMB1 only).
3621 if (!(oplock_request & INTERNAL_OPEN_ONLY) &&
3622 !conn->sconn->using_smb2 &&
3623 lp_defer_sharing_violations()) {
3624 struct timeval timeout;
3627 /* this is a hack to speed up torture tests
3629 timeout_usecs = lp_parm_int(SNUM(conn),
3630 "smbd","sharedelay",
3631 SHARING_VIOLATION_USEC_WAIT);
3633 /* This is a relative time, added to the absolute
3634 request_time value to get the absolute timeout time.
3635 Note that if this is the second or greater time we enter
3636 this codepath for this particular request mid then
3637 request_time is left as the absolute time of the *first*
3638 time this request mid was processed. This is what allows
3639 the request to eventually time out. */
3641 timeout = timeval_set(0, timeout_usecs);
3643 if (!request_timed_out(request_time, timeout)) {
3644 defer_open(lck, request_time, timeout, req,
3653 * We have detected a sharing violation here
3654 * so return the correct error code
3656 status = NT_STATUS_SHARING_VIOLATION;
3658 status = NT_STATUS_ACCESS_DENIED;
3663 /* Should we atomically (to the client at least) truncate ? */
3664 if ((!new_file_created) &&
3665 (flags2 & O_TRUNC) &&
3666 (!S_ISFIFO(fsp->fsp_name->st.st_ex_mode))) {
3669 ret = vfs_set_filelen(fsp, 0);
3671 status = map_nt_error_from_unix(errno);
3679 * We have the share entry *locked*.....
3682 /* Delete streams if create_disposition requires it */
3683 if (!new_file_created && clear_ads(create_disposition) &&
3684 !is_ntfs_stream_smb_fname(smb_fname)) {
3685 status = delete_all_streams(conn, smb_fname);
3686 if (!NT_STATUS_IS_OK(status)) {
3693 /* note that we ignore failure for the following. It is
3694 basically a hack for NFS, and NFS will never set one of
3695 these only read them. Nobody but Samba can ever set a deny
3696 mode and we have already checked our more authoritative
3697 locking database for permission to set this deny mode. If
3698 the kernel refuses the operations then the kernel is wrong.
3699 note that GPFS supports it as well - jmcd */
3701 if (fsp->fh->fd != -1 && lp_kernel_share_modes(SNUM(conn))) {
3704 * Beware: streams implementing VFS modules may
3705 * implement streams in a way that fsp will have the
3706 * basefile open in the fsp fd, so lacking a distinct
3707 * fd for the stream kernel_flock will apply on the
3708 * basefile which is wrong. The actual check is
3709 * deffered to the VFS module implementing the
3710 * kernel_flock call.
3712 ret_flock = SMB_VFS_KERNEL_FLOCK(fsp, share_access, access_mask);
3713 if(ret_flock == -1 ){
3718 return NT_STATUS_SHARING_VIOLATION;
3721 fsp->kernel_share_modes_taken = true;
3725 * At this point onwards, we can guarantee that the share entry
3726 * is locked, whether we created the file or not, and that the
3727 * deny mode is compatible with all current opens.
3731 * According to Samba4, SEC_FILE_READ_ATTRIBUTE is always granted,
3732 * but we don't have to store this - just ignore it on access check.
3734 if (conn->sconn->using_smb2) {
3736 * SMB2 doesn't return it (according to Microsoft tests).
3737 * Test Case: TestSuite_ScenarioNo009GrantedAccessTestS0
3738 * File created with access = 0x7 (Read, Write, Delete)
3739 * Query Info on file returns 0x87 (Read, Write, Delete, Read Attributes)
3741 fsp->access_mask = access_mask;
3743 /* But SMB1 does. */
3744 fsp->access_mask = access_mask | FILE_READ_ATTRIBUTES;
3749 * stat opens on existing files don't get oplocks.
3750 * They can get leases.
3752 * Note that we check for stat open on the *open_access_mask*,
3753 * i.e. the access mask we actually used to do the open,
3754 * not the one the client asked for (which is in
3755 * fsp->access_mask). This is due to the fact that
3756 * FILE_OVERWRITE and FILE_OVERWRITE_IF add in O_TRUNC,
3757 * which adds FILE_WRITE_DATA to open_access_mask.
3759 if (is_stat_open(open_access_mask) && lease == NULL) {
3760 oplock_request = NO_OPLOCK;
3764 if (new_file_created) {
3765 info = FILE_WAS_CREATED;
3767 if (flags2 & O_TRUNC) {
3768 info = FILE_WAS_OVERWRITTEN;
3770 info = FILE_WAS_OPENED;
3779 * Setup the oplock info in both the shared memory and
3782 status = grant_fsp_oplock_type(req, fsp, lck, oplock_request, lease);
3783 if (!NT_STATUS_IS_OK(status)) {
3789 /* Handle strange delete on close create semantics. */
3790 if (create_options & FILE_DELETE_ON_CLOSE) {
3791 if (!new_file_created) {
3792 status = can_set_delete_on_close(fsp,
3793 existing_dos_attributes);
3795 if (!NT_STATUS_IS_OK(status)) {
3796 /* Remember to delete the mode we just added. */
3797 del_share_mode(lck, fsp);
3803 /* Note that here we set the *initial* delete on close flag,
3804 not the regular one. The magic gets handled in close. */
3805 fsp->initial_delete_on_close = True;
3808 if (info != FILE_WAS_OPENED) {
3809 /* Overwritten files should be initially set as archive */
3810 if ((info == FILE_WAS_OVERWRITTEN && lp_map_archive(SNUM(conn))) ||
3811 lp_store_dos_attributes(SNUM(conn))) {
3813 if (file_set_dosmode(conn, smb_fname,
3814 new_dos_attributes | FILE_ATTRIBUTE_ARCHIVE,
3815 parent_dir, true) == 0) {
3816 unx_mode = smb_fname->st.st_ex_mode;
3822 /* Determine sparse flag. */
3824 /* POSIX opens are sparse by default. */
3825 fsp->is_sparse = true;
3827 fsp->is_sparse = (file_existed &&
3828 (existing_dos_attributes & FILE_ATTRIBUTE_SPARSE));
3832 * Take care of inherited ACLs on created files - if default ACL not
3836 if (!posix_open && new_file_created && !def_acl) {
3837 if (unx_mode != smb_fname->st.st_ex_mode) {
3838 int ret = SMB_VFS_FCHMOD(fsp, unx_mode);
3840 DBG_INFO("failed to reset "
3841 "attributes of file %s to 0%o\n",
3842 smb_fname_str_dbg(smb_fname),
3843 (unsigned int)unx_mode);
3847 } else if (new_unx_mode) {
3849 * We only get here in the case of:
3851 * a). Not a POSIX open.
3852 * b). File already existed.
3853 * c). File was overwritten.
3854 * d). Requested DOS attributes didn't match
3855 * the DOS attributes on the existing file.
3857 * In that case new_unx_mode has been set
3858 * equal to the calculated mode (including
3859 * possible inheritance of the mode from the
3860 * containing directory).
3862 * Note this mode was calculated with the
3863 * DOS attribute FILE_ATTRIBUTE_ARCHIVE added,
3864 * so the mode change here is suitable for
3865 * an overwritten file.
3868 if (new_unx_mode != smb_fname->st.st_ex_mode) {
3869 int ret = SMB_VFS_FCHMOD(fsp, new_unx_mode);
3871 DBG_INFO("failed to reset "
3872 "attributes of file %s to 0%o\n",
3873 smb_fname_str_dbg(smb_fname),
3874 (unsigned int)new_unx_mode);
3881 * Deal with other opens having a modified write time.
3883 struct timespec write_time = get_share_mode_write_time(lck);
3885 if (!null_timespec(write_time)) {
3886 update_stat_ex_mtime(&fsp->fsp_name->st, write_time);
3892 return NT_STATUS_OK;
3895 static NTSTATUS mkdir_internal(connection_struct *conn,
3896 struct smb_filename *smb_dname,
3897 uint32_t file_attributes)
3900 char *parent_dir = NULL;
3902 bool posix_open = false;
3903 bool need_re_stat = false;
3904 uint32_t access_mask = SEC_DIR_ADD_SUBDIR;
3906 if (!CAN_WRITE(conn) || (access_mask & ~(conn->share_access))) {
3907 DEBUG(5,("mkdir_internal: failing share access "
3908 "%s\n", lp_servicename(talloc_tos(), SNUM(conn))));
3909 return NT_STATUS_ACCESS_DENIED;
3912 if (!parent_dirname(talloc_tos(), smb_dname->base_name, &parent_dir,
3914 return NT_STATUS_NO_MEMORY;
3917 if (file_attributes & FILE_FLAG_POSIX_SEMANTICS) {
3919 mode = (mode_t)(file_attributes & ~FILE_FLAG_POSIX_SEMANTICS);
3921 mode = unix_mode(conn, FILE_ATTRIBUTE_DIRECTORY, smb_dname, parent_dir);
3924 status = check_parent_access(conn,
3927 if(!NT_STATUS_IS_OK(status)) {
3928 DEBUG(5,("mkdir_internal: check_parent_access "
3929 "on directory %s for path %s returned %s\n",
3931 smb_dname->base_name,
3932 nt_errstr(status) ));
3936 if (SMB_VFS_MKDIR(conn, smb_dname, mode) != 0) {
3937 return map_nt_error_from_unix(errno);
3940 /* Ensure we're checking for a symlink here.... */
3941 /* We don't want to get caught by a symlink racer. */
3943 if (SMB_VFS_LSTAT(conn, smb_dname) == -1) {
3944 DEBUG(2, ("Could not stat directory '%s' just created: %s\n",
3945 smb_fname_str_dbg(smb_dname), strerror(errno)));
3946 return map_nt_error_from_unix(errno);
3949 if (!S_ISDIR(smb_dname->st.st_ex_mode)) {
3950 DEBUG(0, ("Directory '%s' just created is not a directory !\n",
3951 smb_fname_str_dbg(smb_dname)));
3952 return NT_STATUS_NOT_A_DIRECTORY;
3955 if (lp_store_dos_attributes(SNUM(conn))) {
3957 file_set_dosmode(conn, smb_dname,
3958 file_attributes | FILE_ATTRIBUTE_DIRECTORY,
3963 if (lp_inherit_permissions(SNUM(conn))) {
3964 inherit_access_posix_acl(conn, parent_dir,
3966 need_re_stat = true;
3971 * Check if high bits should have been set,
3972 * then (if bits are missing): add them.
3973 * Consider bits automagically set by UNIX, i.e. SGID bit from parent
3976 if ((mode & ~(S_IRWXU|S_IRWXG|S_IRWXO)) &&
3977 (mode & ~smb_dname->st.st_ex_mode)) {
3978 SMB_VFS_CHMOD(conn, smb_dname,
3979 (smb_dname->st.st_ex_mode |
3980 (mode & ~smb_dname->st.st_ex_mode)));
3981 need_re_stat = true;
3985 /* Change the owner if required. */
3986 if (lp_inherit_owner(SNUM(conn)) != INHERIT_OWNER_NO) {
3987 change_dir_owner_to_parent(conn, parent_dir,
3990 need_re_stat = true;
3994 if (SMB_VFS_LSTAT(conn, smb_dname) == -1) {
3995 DEBUG(2, ("Could not stat directory '%s' just created: %s\n",
3996 smb_fname_str_dbg(smb_dname), strerror(errno)));
3997 return map_nt_error_from_unix(errno);
4001 notify_fname(conn, NOTIFY_ACTION_ADDED, FILE_NOTIFY_CHANGE_DIR_NAME,
4002 smb_dname->base_name);
4004 return NT_STATUS_OK;
4007 /****************************************************************************
4008 Open a directory from an NT SMB call.
4009 ****************************************************************************/
4011 static NTSTATUS open_directory(connection_struct *conn,
4012 struct smb_request *req,
4013 struct smb_filename *smb_dname,
4014 uint32_t access_mask,
4015 uint32_t share_access,
4016 uint32_t create_disposition,
4017 uint32_t create_options,
4018 uint32_t file_attributes,
4020 files_struct **result)
4022 files_struct *fsp = NULL;
4023 bool dir_existed = VALID_STAT(smb_dname->st) ? True : False;
4024 struct share_mode_lock *lck = NULL;
4026 struct timespec mtimespec;
4030 if (is_ntfs_stream_smb_fname(smb_dname)) {
4031 DEBUG(2, ("open_directory: %s is a stream name!\n",
4032 smb_fname_str_dbg(smb_dname)));
4033 return NT_STATUS_NOT_A_DIRECTORY;
4036 if (!(file_attributes & FILE_FLAG_POSIX_SEMANTICS)) {
4037 /* Ensure we have a directory attribute. */
4038 file_attributes |= FILE_ATTRIBUTE_DIRECTORY;
4041 DEBUG(5,("open_directory: opening directory %s, access_mask = 0x%x, "
4042 "share_access = 0x%x create_options = 0x%x, "
4043 "create_disposition = 0x%x, file_attributes = 0x%x\n",
4044 smb_fname_str_dbg(smb_dname),
4045 (unsigned int)access_mask,
4046 (unsigned int)share_access,
4047 (unsigned int)create_options,
4048 (unsigned int)create_disposition,
4049 (unsigned int)file_attributes));
4051 status = smbd_calculate_access_mask(conn, smb_dname, false,
4052 access_mask, &access_mask);
4053 if (!NT_STATUS_IS_OK(status)) {
4054 DEBUG(10, ("open_directory: smbd_calculate_access_mask "
4055 "on file %s returned %s\n",
4056 smb_fname_str_dbg(smb_dname),
4057 nt_errstr(status)));
4061 if ((access_mask & SEC_FLAG_SYSTEM_SECURITY) &&
4062 !security_token_has_privilege(get_current_nttok(conn),
4063 SEC_PRIV_SECURITY)) {
4064 DEBUG(10, ("open_directory: open on %s "
4065 "failed - SEC_FLAG_SYSTEM_SECURITY denied.\n",
4066 smb_fname_str_dbg(smb_dname)));
4067 return NT_STATUS_PRIVILEGE_NOT_HELD;
4070 switch( create_disposition ) {
4074 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
4077 info = FILE_WAS_OPENED;
4082 /* If directory exists error. If directory doesn't
4086 status = NT_STATUS_OBJECT_NAME_COLLISION;
4087 DEBUG(2, ("open_directory: unable to create "
4088 "%s. Error was %s\n",
4089 smb_fname_str_dbg(smb_dname),
4090 nt_errstr(status)));
4094 status = mkdir_internal(conn, smb_dname,
4097 if (!NT_STATUS_IS_OK(status)) {
4098 DEBUG(2, ("open_directory: unable to create "
4099 "%s. Error was %s\n",
4100 smb_fname_str_dbg(smb_dname),
4101 nt_errstr(status)));
4105 info = FILE_WAS_CREATED;
4110 * If directory exists open. If directory doesn't
4115 status = NT_STATUS_OK;
4116 info = FILE_WAS_OPENED;
4118 status = mkdir_internal(conn, smb_dname,
4121 if (NT_STATUS_IS_OK(status)) {
4122 info = FILE_WAS_CREATED;
4124 /* Cope with create race. */
4125 if (!NT_STATUS_EQUAL(status,
4126 NT_STATUS_OBJECT_NAME_COLLISION)) {
4127 DEBUG(2, ("open_directory: unable to create "
4128 "%s. Error was %s\n",
4129 smb_fname_str_dbg(smb_dname),
4130 nt_errstr(status)));
4135 * If mkdir_internal() returned
4136 * NT_STATUS_OBJECT_NAME_COLLISION
4137 * we still must lstat the path.
4140 if (SMB_VFS_LSTAT(conn, smb_dname)
4142 DEBUG(2, ("Could not stat "
4143 "directory '%s' just "
4148 return map_nt_error_from_unix(
4152 info = FILE_WAS_OPENED;
4158 case FILE_SUPERSEDE:
4159 case FILE_OVERWRITE:
4160 case FILE_OVERWRITE_IF:
4162 DEBUG(5,("open_directory: invalid create_disposition "
4163 "0x%x for directory %s\n",
4164 (unsigned int)create_disposition,
4165 smb_fname_str_dbg(smb_dname)));
4166 return NT_STATUS_INVALID_PARAMETER;
4169 if(!S_ISDIR(smb_dname->st.st_ex_mode)) {
4170 DEBUG(5,("open_directory: %s is not a directory !\n",
4171 smb_fname_str_dbg(smb_dname)));
4172 return NT_STATUS_NOT_A_DIRECTORY;
4175 if (info == FILE_WAS_OPENED) {
4176 status = smbd_check_access_rights(conn,
4180 if (!NT_STATUS_IS_OK(status)) {
4181 DEBUG(10, ("open_directory: smbd_check_access_rights on "
4182 "file %s failed with %s\n",
4183 smb_fname_str_dbg(smb_dname),
4184 nt_errstr(status)));
4189 status = file_new(req, conn, &fsp);
4190 if(!NT_STATUS_IS_OK(status)) {
4195 * Setup the files_struct for it.
4198 fsp->file_id = vfs_file_id_from_sbuf(conn, &smb_dname->st);
4199 fsp->vuid = req ? req->vuid : UID_FIELD_INVALID;
4200 fsp->file_pid = req ? req->smbpid : 0;
4201 fsp->can_lock = False;
4202 fsp->can_read = False;
4203 fsp->can_write = False;
4205 fsp->share_access = share_access;
4206 fsp->fh->private_options = 0;
4208 * According to Samba4, SEC_FILE_READ_ATTRIBUTE is always granted,
4210 fsp->access_mask = access_mask | FILE_READ_ATTRIBUTES;
4211 fsp->print_file = NULL;
4212 fsp->modified = False;
4213 fsp->oplock_type = NO_OPLOCK;
4214 fsp->sent_oplock_break = NO_BREAK_SENT;
4215 fsp->is_directory = True;
4216 if (file_attributes & FILE_FLAG_POSIX_SEMANTICS) {
4217 fsp->posix_flags |= FSP_POSIX_FLAGS_ALL;
4219 status = fsp_set_smb_fname(fsp, smb_dname);
4220 if (!NT_STATUS_IS_OK(status)) {
4221 file_free(req, fsp);
4225 /* Don't store old timestamps for directory
4226 handles in the internal database. We don't
4227 update them in there if new objects
4228 are creaded in the directory. Currently
4229 we only update timestamps on file writes.
4232 ZERO_STRUCT(mtimespec);
4234 if (access_mask & (FILE_LIST_DIRECTORY|
4236 FILE_ADD_SUBDIRECTORY|
4239 FILE_DELETE_CHILD)) {
4241 status = fd_open(conn, fsp, O_RDONLY|O_DIRECTORY, 0);
4243 /* POSIX allows us to open a directory with O_RDONLY. */
4244 status = fd_open(conn, fsp, O_RDONLY, 0);
4246 if (!NT_STATUS_IS_OK(status)) {
4247 DEBUG(5, ("open_directory: Could not open fd for "
4249 smb_fname_str_dbg(smb_dname),
4250 nt_errstr(status)));
4251 file_free(req, fsp);
4256 DEBUG(10, ("Not opening Directory %s\n",
4257 smb_fname_str_dbg(smb_dname)));
4260 status = vfs_stat_fsp(fsp);
4261 if (!NT_STATUS_IS_OK(status)) {
4263 file_free(req, fsp);
4267 if(!S_ISDIR(fsp->fsp_name->st.st_ex_mode)) {
4268 DEBUG(5,("open_directory: %s is not a directory !\n",
4269 smb_fname_str_dbg(smb_dname)));
4271 file_free(req, fsp);
4272 return NT_STATUS_NOT_A_DIRECTORY;
4275 /* Ensure there was no race condition. We need to check
4276 * dev/inode but not permissions, as these can change
4278 if (!check_same_dev_ino(&smb_dname->st, &fsp->fsp_name->st)) {
4279 DEBUG(5,("open_directory: stat struct differs for "
4281 smb_fname_str_dbg(smb_dname)));
4283 file_free(req, fsp);
4284 return NT_STATUS_ACCESS_DENIED;
4287 lck = get_share_mode_lock(talloc_tos(), fsp->file_id,
4288 conn->connectpath, smb_dname,
4292 DEBUG(0, ("open_directory: Could not get share mode lock for "
4293 "%s\n", smb_fname_str_dbg(smb_dname)));
4295 file_free(req, fsp);
4296 return NT_STATUS_SHARING_VIOLATION;
4299 if (has_delete_on_close(lck, fsp->name_hash)) {
4302 file_free(req, fsp);
4303 return NT_STATUS_DELETE_PENDING;
4306 status = open_mode_check(conn, lck,
4307 access_mask, share_access);
4309 if (!NT_STATUS_IS_OK(status)) {
4312 file_free(req, fsp);
4316 ok = set_share_mode(lck, fsp, get_current_uid(conn),
4317 req ? req->mid : 0, NO_OPLOCK,
4322 file_free(req, fsp);
4323 return NT_STATUS_NO_MEMORY;
4326 /* For directories the delete on close bit at open time seems
4327 always to be honored on close... See test 19 in Samba4 BASE-DELETE. */
4328 if (create_options & FILE_DELETE_ON_CLOSE) {
4329 status = can_set_delete_on_close(fsp, 0);
4330 if (!NT_STATUS_IS_OK(status) && !NT_STATUS_EQUAL(status, NT_STATUS_DIRECTORY_NOT_EMPTY)) {
4331 del_share_mode(lck, fsp);
4334 file_free(req, fsp);
4338 if (NT_STATUS_IS_OK(status)) {
4339 /* Note that here we set the *initial* delete on close flag,
4340 not the regular one. The magic gets handled in close. */
4341 fsp->initial_delete_on_close = True;
4347 * Deal with other opens having a modified write time. Is this
4348 * possible for directories?
4350 struct timespec write_time = get_share_mode_write_time(lck);
4352 if (!null_timespec(write_time)) {
4353 update_stat_ex_mtime(&fsp->fsp_name->st, write_time);
4364 return NT_STATUS_OK;
4367 NTSTATUS create_directory(connection_struct *conn, struct smb_request *req,
4368 struct smb_filename *smb_dname)
4373 status = SMB_VFS_CREATE_FILE(
4376 0, /* root_dir_fid */
4377 smb_dname, /* fname */
4378 FILE_READ_ATTRIBUTES, /* access_mask */
4379 FILE_SHARE_NONE, /* share_access */
4380 FILE_CREATE, /* create_disposition*/
4381 FILE_DIRECTORY_FILE, /* create_options */
4382 FILE_ATTRIBUTE_DIRECTORY, /* file_attributes */
4383 0, /* oplock_request */
4385 0, /* allocation_size */
4386 0, /* private_flags */
4391 NULL, NULL); /* create context */
4393 if (NT_STATUS_IS_OK(status)) {
4394 close_file(req, fsp, NORMAL_CLOSE);
4400 /****************************************************************************
4401 Receive notification that one of our open files has been renamed by another
4403 ****************************************************************************/
4405 void msg_file_was_renamed(struct messaging_context *msg,
4408 struct server_id server_id,
4412 char *frm = (char *)data->data;
4414 const char *sharepath;
4415 const char *base_name;
4416 const char *stream_name;
4417 struct smb_filename *smb_fname = NULL;
4418 size_t sp_len, bn_len;
4420 struct smbd_server_connection *sconn =
4421 talloc_get_type_abort(private_data,
4422 struct smbd_server_connection);
4424 if (data->data == NULL
4425 || data->length < MSG_FILE_RENAMED_MIN_SIZE + 2) {
4426 DEBUG(0, ("msg_file_was_renamed: Got invalid msg len %d\n",
4427 (int)data->length));
4431 /* Unpack the message. */
4432 pull_file_id_24(frm, &id);
4433 sharepath = &frm[24];
4434 sp_len = strlen(sharepath);
4435 base_name = sharepath + sp_len + 1;
4436 bn_len = strlen(base_name);
4437 stream_name = sharepath + sp_len + 1 + bn_len + 1;
4439 /* stream_name must always be NULL if there is no stream. */
4440 if (stream_name[0] == '\0') {
4444 smb_fname = synthetic_smb_fname(talloc_tos(),
4449 if (smb_fname == NULL) {
4453 DEBUG(10,("msg_file_was_renamed: Got rename message for sharepath %s, new name %s, "
4455 sharepath, smb_fname_str_dbg(smb_fname),
4456 file_id_string_tos(&id)));
4458 for(fsp = file_find_di_first(sconn, id); fsp;
4459 fsp = file_find_di_next(fsp)) {
4460 if (memcmp(fsp->conn->connectpath, sharepath, sp_len) == 0) {
4462 DEBUG(10,("msg_file_was_renamed: renaming file %s from %s -> %s\n",
4463 fsp_fnum_dbg(fsp), fsp_str_dbg(fsp),
4464 smb_fname_str_dbg(smb_fname)));
4465 status = fsp_set_smb_fname(fsp, smb_fname);
4466 if (!NT_STATUS_IS_OK(status)) {
4471 /* Now we have the complete path we can work out if this is
4472 actually within this share and adjust newname accordingly. */
4473 DEBUG(10,("msg_file_was_renamed: share mismatch (sharepath %s "
4474 "not sharepath %s) "
4475 "%s from %s -> %s\n",
4476 fsp->conn->connectpath,
4480 smb_fname_str_dbg(smb_fname)));
4484 TALLOC_FREE(smb_fname);
4489 * If a main file is opened for delete, all streams need to be checked for
4490 * !FILE_SHARE_DELETE. Do this by opening with DELETE_ACCESS.
4491 * If that works, delete them all by setting the delete on close and close.
4494 static NTSTATUS open_streams_for_delete(connection_struct *conn,
4495 const struct smb_filename *smb_fname)
4497 struct stream_struct *stream_info = NULL;
4498 files_struct **streams = NULL;
4500 unsigned int num_streams = 0;
4501 TALLOC_CTX *frame = talloc_stackframe();
4504 status = vfs_streaminfo(conn, NULL, smb_fname, talloc_tos(),
4505 &num_streams, &stream_info);
4507 if (NT_STATUS_EQUAL(status, NT_STATUS_NOT_IMPLEMENTED)
4508 || NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
4509 DEBUG(10, ("no streams around\n"));
4511 return NT_STATUS_OK;
4514 if (!NT_STATUS_IS_OK(status)) {
4515 DEBUG(10, ("vfs_streaminfo failed: %s\n",
4516 nt_errstr(status)));
4520 DEBUG(10, ("open_streams_for_delete found %d streams\n",
4523 if (num_streams == 0) {
4525 return NT_STATUS_OK;
4528 streams = talloc_array(talloc_tos(), files_struct *, num_streams);
4529 if (streams == NULL) {
4530 DEBUG(0, ("talloc failed\n"));
4531 status = NT_STATUS_NO_MEMORY;
4535 for (i=0; i<num_streams; i++) {
4536 struct smb_filename *smb_fname_cp;
4538 if (strequal(stream_info[i].name, "::$DATA")) {
4543 smb_fname_cp = synthetic_smb_fname(talloc_tos(),
4544 smb_fname->base_name,
4545 stream_info[i].name,
4548 ~SMB_FILENAME_POSIX_PATH));
4549 if (smb_fname_cp == NULL) {
4550 status = NT_STATUS_NO_MEMORY;
4554 if (SMB_VFS_STAT(conn, smb_fname_cp) == -1) {
4555 DEBUG(10, ("Unable to stat stream: %s\n",
4556 smb_fname_str_dbg(smb_fname_cp)));
4559 status = SMB_VFS_CREATE_FILE(
4562 0, /* root_dir_fid */
4563 smb_fname_cp, /* fname */
4564 DELETE_ACCESS, /* access_mask */
4565 (FILE_SHARE_READ | /* share_access */
4566 FILE_SHARE_WRITE | FILE_SHARE_DELETE),
4567 FILE_OPEN, /* create_disposition*/
4568 0, /* create_options */
4569 FILE_ATTRIBUTE_NORMAL, /* file_attributes */
4570 0, /* oplock_request */
4572 0, /* allocation_size */
4573 NTCREATEX_OPTIONS_PRIVATE_STREAM_DELETE, /* private_flags */
4576 &streams[i], /* result */
4578 NULL, NULL); /* create context */
4580 if (!NT_STATUS_IS_OK(status)) {
4581 DEBUG(10, ("Could not open stream %s: %s\n",
4582 smb_fname_str_dbg(smb_fname_cp),
4583 nt_errstr(status)));
4585 TALLOC_FREE(smb_fname_cp);
4588 TALLOC_FREE(smb_fname_cp);
4592 * don't touch the variable "status" beyond this point :-)
4595 for (i -= 1 ; i >= 0; i--) {
4596 if (streams[i] == NULL) {
4600 DEBUG(10, ("Closing stream # %d, %s\n", i,
4601 fsp_str_dbg(streams[i])));
4602 close_file(NULL, streams[i], NORMAL_CLOSE);
4610 /*********************************************************************
4611 Create a default ACL by inheriting from the parent. If no inheritance
4612 from the parent available, don't set anything. This will leave the actual
4613 permissions the new file or directory already got from the filesystem
4614 as the NT ACL when read.
4615 *********************************************************************/
4617 static NTSTATUS inherit_new_acl(files_struct *fsp)
4619 TALLOC_CTX *frame = talloc_stackframe();
4620 char *parent_name = NULL;
4621 struct security_descriptor *parent_desc = NULL;
4622 NTSTATUS status = NT_STATUS_OK;
4623 struct security_descriptor *psd = NULL;
4624 const struct dom_sid *owner_sid = NULL;
4625 const struct dom_sid *group_sid = NULL;
4626 uint32_t security_info_sent = (SECINFO_OWNER | SECINFO_GROUP | SECINFO_DACL);
4627 struct security_token *token = fsp->conn->session_info->security_token;
4628 bool inherit_owner =
4629 (lp_inherit_owner(SNUM(fsp->conn)) == INHERIT_OWNER_WINDOWS_AND_UNIX);
4630 bool inheritable_components = false;
4631 bool try_builtin_administrators = false;
4632 const struct dom_sid *BA_U_sid = NULL;
4633 const struct dom_sid *BA_G_sid = NULL;
4634 bool try_system = false;
4635 const struct dom_sid *SY_U_sid = NULL;
4636 const struct dom_sid *SY_G_sid = NULL;
4638 struct smb_filename *parent_smb_fname = NULL;
4640 if (!parent_dirname(frame, fsp->fsp_name->base_name, &parent_name, NULL)) {
4642 return NT_STATUS_NO_MEMORY;
4644 parent_smb_fname = synthetic_smb_fname(talloc_tos(),
4648 fsp->fsp_name->flags);
4650 if (parent_smb_fname == NULL) {
4652 return NT_STATUS_NO_MEMORY;
4655 status = SMB_VFS_GET_NT_ACL(fsp->conn,
4657 (SECINFO_OWNER | SECINFO_GROUP | SECINFO_DACL),
4660 if (!NT_STATUS_IS_OK(status)) {
4665 inheritable_components = sd_has_inheritable_components(parent_desc,
4668 if (!inheritable_components && !inherit_owner) {
4670 /* Nothing to inherit and not setting owner. */
4671 return NT_STATUS_OK;
4674 /* Create an inherited descriptor from the parent. */
4676 if (DEBUGLEVEL >= 10) {
4677 DEBUG(10,("inherit_new_acl: parent acl for %s is:\n",
4678 fsp_str_dbg(fsp) ));
4679 NDR_PRINT_DEBUG(security_descriptor, parent_desc);
4682 /* Inherit from parent descriptor if "inherit owner" set. */
4683 if (inherit_owner) {
4684 owner_sid = parent_desc->owner_sid;
4685 group_sid = parent_desc->group_sid;
4688 if (owner_sid == NULL) {
4689 if (security_token_has_builtin_administrators(token)) {
4690 try_builtin_administrators = true;
4691 } else if (security_token_is_system(token)) {
4692 try_builtin_administrators = true;
4697 if (group_sid == NULL &&
4698 token->num_sids == PRIMARY_GROUP_SID_INDEX)
4700 if (security_token_is_system(token)) {
4701 try_builtin_administrators = true;
4706 if (try_builtin_administrators) {
4711 ok = sids_to_unixids(&global_sid_Builtin_Administrators, 1, &ids);
4715 BA_U_sid = &global_sid_Builtin_Administrators;
4716 BA_G_sid = &global_sid_Builtin_Administrators;
4719 BA_U_sid = &global_sid_Builtin_Administrators;
4722 BA_G_sid = &global_sid_Builtin_Administrators;
4735 ok = sids_to_unixids(&global_sid_System, 1, &ids);
4739 SY_U_sid = &global_sid_System;
4740 SY_G_sid = &global_sid_System;
4743 SY_U_sid = &global_sid_System;
4746 SY_G_sid = &global_sid_System;
4754 if (owner_sid == NULL) {
4755 owner_sid = BA_U_sid;
4758 if (owner_sid == NULL) {
4759 owner_sid = SY_U_sid;
4762 if (group_sid == NULL) {
4763 group_sid = SY_G_sid;
4766 if (try_system && group_sid == NULL) {
4767 group_sid = BA_G_sid;
4770 if (owner_sid == NULL) {
4771 owner_sid = &token->sids[PRIMARY_USER_SID_INDEX];
4773 if (group_sid == NULL) {
4774 if (token->num_sids == PRIMARY_GROUP_SID_INDEX) {
4775 group_sid = &token->sids[PRIMARY_USER_SID_INDEX];
4777 group_sid = &token->sids[PRIMARY_GROUP_SID_INDEX];
4781 status = se_create_child_secdesc(frame,
4788 if (!NT_STATUS_IS_OK(status)) {
4793 /* If inheritable_components == false,
4794 se_create_child_secdesc()
4795 creates a security descriptor with a NULL dacl
4796 entry, but with SEC_DESC_DACL_PRESENT. We need
4797 to remove that flag. */
4799 if (!inheritable_components) {
4800 security_info_sent &= ~SECINFO_DACL;
4801 psd->type &= ~SEC_DESC_DACL_PRESENT;
4804 if (DEBUGLEVEL >= 10) {
4805 DEBUG(10,("inherit_new_acl: child acl for %s is:\n",
4806 fsp_str_dbg(fsp) ));
4807 NDR_PRINT_DEBUG(security_descriptor, psd);
4810 if (inherit_owner) {
4811 /* We need to be root to force this. */
4814 status = SMB_VFS_FSET_NT_ACL(fsp,
4817 if (inherit_owner) {
4825 * If we already have a lease, it must match the new file id. [MS-SMB2]
4826 * 3.3.5.9.8 speaks about INVALID_PARAMETER if an already used lease key is
4827 * used for a different file name.
4830 struct lease_match_state {
4831 /* Input parameters. */
4832 TALLOC_CTX *mem_ctx;
4833 const char *servicepath;
4834 const struct smb_filename *fname;
4837 /* Return parameters. */
4838 uint32_t num_file_ids;
4839 struct file_id *ids;
4840 NTSTATUS match_status;
4843 /*************************************************************
4844 File doesn't exist but this lease key+guid is already in use.
4846 This is only allowable in the dynamic share case where the
4847 service path must be different.
4849 There is a small race condition here in the multi-connection
4850 case where a client sends two create calls on different connections,
4851 where the file doesn't exist and one smbd creates the leases_db
4852 entry first, but this will get fixed by the multichannel cleanup
4853 when all identical client_guids get handled by a single smbd.
4854 **************************************************************/
4856 static void lease_match_parser_new_file(
4858 const struct leases_db_file *files,
4859 struct lease_match_state *state)
4863 for (i = 0; i < num_files; i++) {
4864 const struct leases_db_file *f = &files[i];
4865 if (strequal(state->servicepath, f->servicepath)) {
4866 state->match_status = NT_STATUS_INVALID_PARAMETER;
4871 /* Dynamic share case. Break leases on all other files. */
4872 state->match_status = leases_db_copy_file_ids(state->mem_ctx,
4876 if (!NT_STATUS_IS_OK(state->match_status)) {
4880 state->num_file_ids = num_files;
4881 state->match_status = NT_STATUS_OPLOCK_NOT_GRANTED;
4885 static void lease_match_parser(
4887 const struct leases_db_file *files,
4890 struct lease_match_state *state =
4891 (struct lease_match_state *)private_data;
4894 if (!state->file_existed) {
4896 * Deal with name mismatch or
4897 * possible dynamic share case separately
4898 * to make code clearer.
4900 lease_match_parser_new_file(num_files,
4907 state->match_status = NT_STATUS_OK;
4909 for (i = 0; i < num_files; i++) {
4910 const struct leases_db_file *f = &files[i];
4912 /* Everything should be the same. */
4913 if (!file_id_equal(&state->id, &f->id)) {
4914 /* This should catch all dynamic share cases. */
4915 state->match_status = NT_STATUS_OPLOCK_NOT_GRANTED;
4918 if (!strequal(f->servicepath, state->servicepath)) {
4919 state->match_status = NT_STATUS_INVALID_PARAMETER;
4922 if (!strequal(f->base_name, state->fname->base_name)) {
4923 state->match_status = NT_STATUS_INVALID_PARAMETER;
4926 if (!strequal(f->stream_name, state->fname->stream_name)) {
4927 state->match_status = NT_STATUS_INVALID_PARAMETER;
4932 if (NT_STATUS_IS_OK(state->match_status)) {
4934 * Common case - just opening another handle on a
4935 * file on a non-dynamic share.
4940 if (NT_STATUS_EQUAL(state->match_status, NT_STATUS_INVALID_PARAMETER)) {
4941 /* Mismatched path. Error back to client. */
4946 * File id mismatch. Dynamic share case NT_STATUS_OPLOCK_NOT_GRANTED.
4947 * Don't allow leases.
4950 state->match_status = leases_db_copy_file_ids(state->mem_ctx,
4954 if (!NT_STATUS_IS_OK(state->match_status)) {
4958 state->num_file_ids = num_files;
4959 state->match_status = NT_STATUS_OPLOCK_NOT_GRANTED;
4963 static NTSTATUS lease_match(connection_struct *conn,
4964 struct smb_request *req,
4965 struct smb2_lease_key *lease_key,
4966 const char *servicepath,
4967 const struct smb_filename *fname,
4968 uint16_t *p_version,
4971 struct smbd_server_connection *sconn = req->sconn;
4972 TALLOC_CTX *tos = talloc_tos();
4973 struct lease_match_state state = {
4975 .servicepath = servicepath,
4977 .match_status = NT_STATUS_OK
4982 state.file_existed = VALID_STAT(fname->st);
4983 if (state.file_existed) {
4984 state.id = vfs_file_id_from_sbuf(conn, &fname->st);
4987 status = leases_db_parse(&sconn->client->connections->smb2.client.guid,
4988 lease_key, lease_match_parser, &state);
4989 if (!NT_STATUS_IS_OK(status)) {
4991 * Not found or error means okay: We can make the lease pass
4993 return NT_STATUS_OK;
4995 if (!NT_STATUS_EQUAL(state.match_status, NT_STATUS_OPLOCK_NOT_GRANTED)) {
4997 * Anything but NT_STATUS_OPLOCK_NOT_GRANTED, let the caller
5000 return state.match_status;
5003 /* We have to break all existing leases. */
5004 for (i = 0; i < state.num_file_ids; i++) {
5005 struct share_mode_lock *lck;
5006 struct share_mode_data *d;
5009 if (file_id_equal(&state.ids[i], &state.id)) {
5010 /* Don't need to break our own file. */
5014 lck = get_existing_share_mode_lock(talloc_tos(), state.ids[i]);
5016 /* Race condition - file already closed. */
5020 for (j=0; j<d->num_share_modes; j++) {
5021 struct share_mode_entry *e = &d->share_modes[j];
5022 uint32_t e_lease_type = get_lease_type(d, e);
5024 if (share_mode_stale_pid(d, j)) {
5028 if (e->op_type == LEASE_OPLOCK) {
5029 struct share_mode_lease *l = NULL;
5030 l = &lck->data->leases[e->lease_idx];
5031 if (!smb2_lease_key_equal(&l->lease_key,
5035 *p_epoch = l->epoch;
5036 *p_version = l->lease_version;
5039 if (e_lease_type == SMB2_LEASE_NONE) {
5043 send_break_message(conn->sconn->msg_ctx, &d->id, e,
5047 * Windows 7 and 8 lease clients
5048 * are broken in that they will not
5049 * respond to lease break requests
5050 * whilst waiting for an outstanding
5051 * open request on that lease handle
5052 * on the same TCP connection, due
5053 * to holding an internal inode lock.
5055 * This means we can't reschedule
5056 * ourselves here, but must return
5061 * Send the breaks and then return
5062 * SMB2_LEASE_NONE in the lease handle
5063 * to cause them to acknowledge the
5064 * lease break. Consultation with
5065 * Microsoft engineering confirmed
5066 * this approach is safe.
5073 * Ensure we don't grant anything more so we
5076 return NT_STATUS_OPLOCK_NOT_GRANTED;
5080 * Wrapper around open_file_ntcreate and open_directory
5083 static NTSTATUS create_file_unixpath(connection_struct *conn,
5084 struct smb_request *req,
5085 struct smb_filename *smb_fname,
5086 uint32_t access_mask,
5087 uint32_t share_access,
5088 uint32_t create_disposition,
5089 uint32_t create_options,
5090 uint32_t file_attributes,
5091 uint32_t oplock_request,
5092 struct smb2_lease *lease,
5093 uint64_t allocation_size,
5094 uint32_t private_flags,
5095 struct security_descriptor *sd,
5096 struct ea_list *ea_list,
5098 files_struct **result,
5101 int info = FILE_WAS_OPENED;
5102 files_struct *base_fsp = NULL;
5103 files_struct *fsp = NULL;
5106 DBG_DEBUG("create_file_unixpath: access_mask = 0x%x "
5107 "file_attributes = 0x%x, share_access = 0x%x, "
5108 "create_disposition = 0x%x create_options = 0x%x "
5109 "oplock_request = 0x%x private_flags = 0x%x "
5110 "ea_list = %p, sd = %p, "
5112 (unsigned int)access_mask,
5113 (unsigned int)file_attributes,
5114 (unsigned int)share_access,
5115 (unsigned int)create_disposition,
5116 (unsigned int)create_options,
5117 (unsigned int)oplock_request,
5118 (unsigned int)private_flags,
5119 ea_list, sd, smb_fname_str_dbg(smb_fname));
5121 if (create_options & FILE_OPEN_BY_FILE_ID) {
5122 status = NT_STATUS_NOT_SUPPORTED;
5126 if (create_options & NTCREATEX_OPTIONS_INVALID_PARAM_MASK) {
5127 status = NT_STATUS_INVALID_PARAMETER;
5132 oplock_request |= INTERNAL_OPEN_ONLY;
5135 if (lease != NULL) {
5136 uint16_t epoch = lease->lease_epoch;
5137 uint16_t version = lease->lease_version;
5140 DBG_WARNING("Got lease on internal open\n");
5141 status = NT_STATUS_INTERNAL_ERROR;
5145 status = lease_match(conn,
5152 if (NT_STATUS_EQUAL(status, NT_STATUS_OPLOCK_NOT_GRANTED)) {
5153 /* Dynamic share file. No leases and update epoch... */
5154 lease->lease_state = SMB2_LEASE_NONE;
5155 lease->lease_epoch = epoch;
5156 lease->lease_version = version;
5157 } else if (!NT_STATUS_IS_OK(status)) {
5162 if ((conn->fs_capabilities & FILE_NAMED_STREAMS)
5163 && (access_mask & DELETE_ACCESS)
5164 && !is_ntfs_stream_smb_fname(smb_fname)) {
5166 * We can't open a file with DELETE access if any of the
5167 * streams is open without FILE_SHARE_DELETE
5169 status = open_streams_for_delete(conn, smb_fname);
5171 if (!NT_STATUS_IS_OK(status)) {
5176 if ((access_mask & SEC_FLAG_SYSTEM_SECURITY) &&
5177 !security_token_has_privilege(get_current_nttok(conn),
5178 SEC_PRIV_SECURITY)) {
5179 DEBUG(10, ("create_file_unixpath: open on %s "
5180 "failed - SEC_FLAG_SYSTEM_SECURITY denied.\n",
5181 smb_fname_str_dbg(smb_fname)));
5182 status = NT_STATUS_PRIVILEGE_NOT_HELD;
5187 * Files or directories can't be opened DELETE_ON_CLOSE without
5189 * BUG: https://bugzilla.samba.org/show_bug.cgi?id=13358
5191 if (create_options & FILE_DELETE_ON_CLOSE) {
5192 if ((access_mask & DELETE_ACCESS) == 0) {
5193 status = NT_STATUS_INVALID_PARAMETER;
5198 if ((conn->fs_capabilities & FILE_NAMED_STREAMS)
5199 && is_ntfs_stream_smb_fname(smb_fname)
5200 && (!(private_flags & NTCREATEX_OPTIONS_PRIVATE_STREAM_DELETE))) {
5201 uint32_t base_create_disposition;
5202 struct smb_filename *smb_fname_base = NULL;
5203 uint32_t base_privflags;
5205 if (create_options & FILE_DIRECTORY_FILE) {
5206 status = NT_STATUS_NOT_A_DIRECTORY;
5210 switch (create_disposition) {
5212 base_create_disposition = FILE_OPEN;
5215 base_create_disposition = FILE_OPEN_IF;
5219 /* Create an smb_filename with stream_name == NULL. */
5220 smb_fname_base = synthetic_smb_fname(talloc_tos(),
5221 smb_fname->base_name,
5225 if (smb_fname_base == NULL) {
5226 status = NT_STATUS_NO_MEMORY;
5230 if (SMB_VFS_STAT(conn, smb_fname_base) == -1) {
5231 DEBUG(10, ("Unable to stat stream: %s\n",
5232 smb_fname_str_dbg(smb_fname_base)));
5235 * https://bugzilla.samba.org/show_bug.cgi?id=10229
5236 * We need to check if the requested access mask
5237 * could be used to open the underlying file (if
5238 * it existed), as we're passing in zero for the
5239 * access mask to the base filename.
5241 status = check_base_file_access(conn,
5245 if (!NT_STATUS_IS_OK(status)) {
5246 DEBUG(10, ("Permission check "
5247 "for base %s failed: "
5248 "%s\n", smb_fname->base_name,
5249 nt_errstr(status)));
5254 base_privflags = NTCREATEX_OPTIONS_PRIVATE_STREAM_BASEOPEN;
5256 /* Open the base file. */
5257 status = create_file_unixpath(conn, NULL, smb_fname_base, 0,
5260 | FILE_SHARE_DELETE,
5261 base_create_disposition,
5266 TALLOC_FREE(smb_fname_base);
5268 if (!NT_STATUS_IS_OK(status)) {
5269 DEBUG(10, ("create_file_unixpath for base %s failed: "
5270 "%s\n", smb_fname->base_name,
5271 nt_errstr(status)));
5274 /* we don't need the low level fd */
5279 * If it's a request for a directory open, deal with it separately.
5282 if (create_options & FILE_DIRECTORY_FILE) {
5284 if (create_options & FILE_NON_DIRECTORY_FILE) {
5285 status = NT_STATUS_INVALID_PARAMETER;
5289 /* Can't open a temp directory. IFS kit test. */
5290 if (!(file_attributes & FILE_FLAG_POSIX_SEMANTICS) &&
5291 (file_attributes & FILE_ATTRIBUTE_TEMPORARY)) {
5292 status = NT_STATUS_INVALID_PARAMETER;
5297 * We will get a create directory here if the Win32
5298 * app specified a security descriptor in the
5299 * CreateDirectory() call.
5303 status = open_directory(
5304 conn, req, smb_fname, access_mask, share_access,
5305 create_disposition, create_options, file_attributes,
5310 * Ordinary file case.
5313 status = file_new(req, conn, &fsp);
5314 if(!NT_STATUS_IS_OK(status)) {
5318 status = fsp_set_smb_fname(fsp, smb_fname);
5319 if (!NT_STATUS_IS_OK(status)) {
5325 * We're opening the stream element of a
5326 * base_fsp we already opened. Set up the
5329 fsp->base_fsp = base_fsp;
5332 if (allocation_size) {
5333 fsp->initial_allocation_size = smb_roundup(fsp->conn,
5337 status = open_file_ntcreate(conn,
5350 if(!NT_STATUS_IS_OK(status)) {
5351 file_free(req, fsp);
5355 if (NT_STATUS_EQUAL(status, NT_STATUS_FILE_IS_A_DIRECTORY)) {
5357 /* A stream open never opens a directory */
5360 status = NT_STATUS_FILE_IS_A_DIRECTORY;
5365 * Fail the open if it was explicitly a non-directory
5369 if (create_options & FILE_NON_DIRECTORY_FILE) {
5370 status = NT_STATUS_FILE_IS_A_DIRECTORY;
5375 status = open_directory(
5376 conn, req, smb_fname, access_mask,
5377 share_access, create_disposition,
5378 create_options, file_attributes,
5383 if (!NT_STATUS_IS_OK(status)) {
5387 fsp->base_fsp = base_fsp;
5389 if ((ea_list != NULL) &&
5390 ((info == FILE_WAS_CREATED) || (info == FILE_WAS_OVERWRITTEN))) {
5391 status = set_ea(conn, fsp, fsp->fsp_name, ea_list);
5392 if (!NT_STATUS_IS_OK(status)) {
5397 if (!fsp->is_directory && S_ISDIR(fsp->fsp_name->st.st_ex_mode)) {
5398 status = NT_STATUS_ACCESS_DENIED;
5402 /* Save the requested allocation size. */
5403 if ((info == FILE_WAS_CREATED) || (info == FILE_WAS_OVERWRITTEN)) {
5404 if ((allocation_size > fsp->fsp_name->st.st_ex_size)
5405 && !(fsp->is_directory))
5407 fsp->initial_allocation_size = smb_roundup(
5408 fsp->conn, allocation_size);
5409 if (vfs_allocate_file_space(
5410 fsp, fsp->initial_allocation_size) == -1) {
5411 status = NT_STATUS_DISK_FULL;
5415 fsp->initial_allocation_size = smb_roundup(
5416 fsp->conn, (uint64_t)fsp->fsp_name->st.st_ex_size);
5419 fsp->initial_allocation_size = 0;
5422 if ((info == FILE_WAS_CREATED) && lp_nt_acl_support(SNUM(conn)) &&
5423 fsp->base_fsp == NULL) {
5426 * According to the MS documentation, the only time the security
5427 * descriptor is applied to the opened file is iff we *created* the
5428 * file; an existing file stays the same.
5430 * Also, it seems (from observation) that you can open the file with
5431 * any access mask but you can still write the sd. We need to override
5432 * the granted access before we call set_sd
5433 * Patch for bug #2242 from Tom Lackemann <cessnatomny@yahoo.com>.
5436 uint32_t sec_info_sent;
5437 uint32_t saved_access_mask = fsp->access_mask;
5439 sec_info_sent = get_sec_info(sd);
5441 fsp->access_mask = FILE_GENERIC_ALL;
5443 if (sec_info_sent & (SECINFO_OWNER|
5447 status = set_sd(fsp, sd, sec_info_sent);
5450 fsp->access_mask = saved_access_mask;
5452 if (!NT_STATUS_IS_OK(status)) {
5455 } else if (lp_inherit_acls(SNUM(conn))) {
5456 /* Inherit from parent. Errors here are not fatal. */
5457 status = inherit_new_acl(fsp);
5458 if (!NT_STATUS_IS_OK(status)) {
5459 DEBUG(10,("inherit_new_acl: failed for %s with %s\n",
5461 nt_errstr(status) ));
5466 if ((conn->fs_capabilities & FILE_FILE_COMPRESSION)
5467 && (create_options & FILE_NO_COMPRESSION)
5468 && (info == FILE_WAS_CREATED)) {
5469 status = SMB_VFS_SET_COMPRESSION(conn, fsp, fsp,
5470 COMPRESSION_FORMAT_NONE);
5471 if (!NT_STATUS_IS_OK(status)) {
5472 DEBUG(1, ("failed to disable compression: %s\n",
5473 nt_errstr(status)));
5477 DEBUG(10, ("create_file_unixpath: info=%d\n", info));
5480 if (pinfo != NULL) {
5484 smb_fname->st = fsp->fsp_name->st;
5486 return NT_STATUS_OK;
5489 DEBUG(10, ("create_file_unixpath: %s\n", nt_errstr(status)));
5492 if (base_fsp && fsp->base_fsp == base_fsp) {
5494 * The close_file below will close
5499 close_file(req, fsp, ERROR_CLOSE);
5502 if (base_fsp != NULL) {
5503 close_file(req, base_fsp, ERROR_CLOSE);
5510 * Calculate the full path name given a relative fid.
5512 NTSTATUS get_relative_fid_filename(connection_struct *conn,
5513 struct smb_request *req,
5514 uint16_t root_dir_fid,
5515 const struct smb_filename *smb_fname,
5516 struct smb_filename **smb_fname_out)
5518 files_struct *dir_fsp;
5519 char *parent_fname = NULL;
5520 char *new_base_name = NULL;
5521 uint32_t ucf_flags = ucf_flags_from_smb_request(req);
5524 if (root_dir_fid == 0 || !smb_fname) {
5525 status = NT_STATUS_INTERNAL_ERROR;
5529 dir_fsp = file_fsp(req, root_dir_fid);
5531 if (dir_fsp == NULL) {
5532 status = NT_STATUS_INVALID_HANDLE;
5536 if (is_ntfs_stream_smb_fname(dir_fsp->fsp_name)) {
5537 status = NT_STATUS_INVALID_HANDLE;
5541 if (!dir_fsp->is_directory) {
5544 * Check to see if this is a mac fork of some kind.
5547 if ((conn->fs_capabilities & FILE_NAMED_STREAMS) &&
5548 is_ntfs_stream_smb_fname(smb_fname)) {
5549 status = NT_STATUS_OBJECT_PATH_NOT_FOUND;
5554 we need to handle the case when we get a
5555 relative open relative to a file and the
5556 pathname is blank - this is a reopen!
5557 (hint from demyn plantenberg)
5560 status = NT_STATUS_INVALID_HANDLE;
5564 if (ISDOT(dir_fsp->fsp_name->base_name)) {
5566 * We're at the toplevel dir, the final file name
5567 * must not contain ./, as this is filtered out
5568 * normally by srvstr_get_path and unix_convert
5569 * explicitly rejects paths containing ./.
5571 parent_fname = talloc_strdup(talloc_tos(), "");
5572 if (parent_fname == NULL) {
5573 status = NT_STATUS_NO_MEMORY;
5577 size_t dir_name_len = strlen(dir_fsp->fsp_name->base_name);
5580 * Copy in the base directory name.
5583 parent_fname = talloc_array(talloc_tos(), char,
5585 if (parent_fname == NULL) {
5586 status = NT_STATUS_NO_MEMORY;
5589 memcpy(parent_fname, dir_fsp->fsp_name->base_name,
5593 * Ensure it ends in a '/'.
5594 * We used TALLOC_SIZE +2 to add space for the '/'.
5598 && (parent_fname[dir_name_len-1] != '\\')
5599 && (parent_fname[dir_name_len-1] != '/')) {
5600 parent_fname[dir_name_len] = '/';
5601 parent_fname[dir_name_len+1] = '\0';
5605 new_base_name = talloc_asprintf(talloc_tos(), "%s%s", parent_fname,
5606 smb_fname->base_name);
5607 if (new_base_name == NULL) {
5608 status = NT_STATUS_NO_MEMORY;
5612 status = filename_convert(req,
5619 if (!NT_STATUS_IS_OK(status)) {
5624 TALLOC_FREE(parent_fname);
5625 TALLOC_FREE(new_base_name);
5629 NTSTATUS create_file_default(connection_struct *conn,
5630 struct smb_request *req,
5631 uint16_t root_dir_fid,
5632 struct smb_filename *smb_fname,
5633 uint32_t access_mask,
5634 uint32_t share_access,
5635 uint32_t create_disposition,
5636 uint32_t create_options,
5637 uint32_t file_attributes,
5638 uint32_t oplock_request,
5639 struct smb2_lease *lease,
5640 uint64_t allocation_size,
5641 uint32_t private_flags,
5642 struct security_descriptor *sd,
5643 struct ea_list *ea_list,
5644 files_struct **result,
5646 const struct smb2_create_blobs *in_context_blobs,
5647 struct smb2_create_blobs *out_context_blobs)
5649 int info = FILE_WAS_OPENED;
5650 files_struct *fsp = NULL;
5652 bool stream_name = false;
5654 DBG_DEBUG("create_file: access_mask = 0x%x "
5655 "file_attributes = 0x%x, share_access = 0x%x, "
5656 "create_disposition = 0x%x create_options = 0x%x "
5657 "oplock_request = 0x%x "
5658 "private_flags = 0x%x "
5659 "root_dir_fid = 0x%x, ea_list = %p, sd = %p, "
5661 (unsigned int)access_mask,
5662 (unsigned int)file_attributes,
5663 (unsigned int)share_access,
5664 (unsigned int)create_disposition,
5665 (unsigned int)create_options,
5666 (unsigned int)oplock_request,
5667 (unsigned int)private_flags,
5668 (unsigned int)root_dir_fid,
5669 ea_list, sd, smb_fname_str_dbg(smb_fname));
5672 * Calculate the filename from the root_dir_if if necessary.
5675 if (root_dir_fid != 0) {
5676 struct smb_filename *smb_fname_out = NULL;
5677 status = get_relative_fid_filename(conn, req, root_dir_fid,
5678 smb_fname, &smb_fname_out);
5679 if (!NT_STATUS_IS_OK(status)) {
5682 smb_fname = smb_fname_out;
5686 * Check to see if this is a mac fork of some kind.
5689 stream_name = is_ntfs_stream_smb_fname(smb_fname);
5691 enum FAKE_FILE_TYPE fake_file_type;
5693 fake_file_type = is_fake_file(smb_fname);
5695 if (fake_file_type != FAKE_FILE_TYPE_NONE) {
5698 * Here we go! support for changing the disk quotas
5701 * We need to fake up to open this MAGIC QUOTA file
5702 * and return a valid FID.
5704 * w2k close this file directly after openening xp
5705 * also tries a QUERY_FILE_INFO on the file and then
5708 status = open_fake_file(req, conn, req->vuid,
5709 fake_file_type, smb_fname,
5711 if (!NT_STATUS_IS_OK(status)) {
5715 ZERO_STRUCT(smb_fname->st);
5719 if (!(conn->fs_capabilities & FILE_NAMED_STREAMS)) {
5720 status = NT_STATUS_OBJECT_NAME_NOT_FOUND;
5725 if (is_ntfs_default_stream_smb_fname(smb_fname)) {
5727 smb_fname->stream_name = NULL;
5728 /* We have to handle this error here. */
5729 if (create_options & FILE_DIRECTORY_FILE) {
5730 status = NT_STATUS_NOT_A_DIRECTORY;
5733 if (req != NULL && req->posix_pathnames) {
5734 ret = SMB_VFS_LSTAT(conn, smb_fname);
5736 ret = SMB_VFS_STAT(conn, smb_fname);
5739 if (ret == 0 && VALID_STAT_OF_DIR(smb_fname->st)) {
5740 status = NT_STATUS_FILE_IS_A_DIRECTORY;
5745 status = create_file_unixpath(
5746 conn, req, smb_fname, access_mask, share_access,
5747 create_disposition, create_options, file_attributes,
5748 oplock_request, lease, allocation_size, private_flags,
5752 if (!NT_STATUS_IS_OK(status)) {
5757 DEBUG(10, ("create_file: info=%d\n", info));
5760 if (pinfo != NULL) {
5763 return NT_STATUS_OK;
5766 DEBUG(10, ("create_file: %s\n", nt_errstr(status)));
5769 close_file(req, fsp, ERROR_CLOSE);