2 Unix SMB/CIFS implementation.
3 file opening and share modes
4 Copyright (C) Andrew Tridgell 1992-1998
5 Copyright (C) Jeremy Allison 2001-2004
6 Copyright (C) Volker Lendecke 2005
7 Copyright (C) Ralph Boehme 2017
9 This program is free software; you can redistribute it and/or modify
10 it under the terms of the GNU General Public License as published by
11 the Free Software Foundation; either version 3 of the License, or
12 (at your option) any later version.
14 This program is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 GNU General Public License for more details.
19 You should have received a copy of the GNU General Public License
20 along with this program. If not, see <http://www.gnu.org/licenses/>.
24 #include "smb1_utils.h"
25 #include "system/filesys.h"
26 #include "lib/util/server_id.h"
28 #include "smbd/smbd.h"
29 #include "smbd/globals.h"
30 #include "fake_file.h"
31 #include "../libcli/security/security.h"
32 #include "../librpc/gen_ndr/ndr_security.h"
33 #include "../librpc/gen_ndr/ndr_open_files.h"
34 #include "../librpc/gen_ndr/idmap.h"
35 #include "../librpc/gen_ndr/ioctl.h"
36 #include "passdb/lookup_sid.h"
40 #include "source3/lib/dbwrap/dbwrap_watch.h"
41 #include "locking/leases_db.h"
42 #include "librpc/gen_ndr/ndr_leases_db.h"
44 extern const struct generic_mapping file_generic_mapping;
46 struct deferred_open_record {
47 bool delayed_for_oplocks;
52 * Timer for async opens, needed because they don't use a watch on
53 * a locking.tdb record. This is currently only used for real async
54 * opens and just terminates smbd if the async open times out.
56 struct tevent_timer *te;
59 /****************************************************************************
60 If the requester wanted DELETE_ACCESS and was rejected because
61 the file ACL didn't include DELETE_ACCESS, see if the parent ACL
63 ****************************************************************************/
65 static bool parent_override_delete(connection_struct *conn,
66 const struct smb_filename *smb_fname,
68 uint32_t rejected_mask)
70 if ((access_mask & DELETE_ACCESS) &&
71 (rejected_mask & DELETE_ACCESS) &&
72 can_delete_file_in_directory(conn, smb_fname)) {
78 /****************************************************************************
79 Check if we have open rights.
80 ****************************************************************************/
82 NTSTATUS smbd_check_access_rights(struct connection_struct *conn,
83 const struct smb_filename *smb_fname,
87 /* Check if we have rights to open. */
89 struct security_descriptor *sd = NULL;
90 uint32_t rejected_share_access;
91 uint32_t rejected_mask = access_mask;
92 uint32_t do_not_check_mask = 0;
94 rejected_share_access = access_mask & ~(conn->share_access);
96 if (rejected_share_access) {
97 DEBUG(10, ("smbd_check_access_rights: rejected share access 0x%x "
99 (unsigned int)access_mask,
100 smb_fname_str_dbg(smb_fname),
101 (unsigned int)rejected_share_access ));
102 return NT_STATUS_ACCESS_DENIED;
105 if (!use_privs && get_current_uid(conn) == (uid_t)0) {
106 /* I'm sorry sir, I didn't know you were root... */
107 DEBUG(10,("smbd_check_access_rights: root override "
108 "on %s. Granting 0x%x\n",
109 smb_fname_str_dbg(smb_fname),
110 (unsigned int)access_mask ));
114 if ((access_mask & DELETE_ACCESS) && !lp_acl_check_permissions(SNUM(conn))) {
115 DEBUG(10,("smbd_check_access_rights: not checking ACL "
116 "on DELETE_ACCESS on file %s. Granting 0x%x\n",
117 smb_fname_str_dbg(smb_fname),
118 (unsigned int)access_mask ));
122 if (access_mask == DELETE_ACCESS &&
123 VALID_STAT(smb_fname->st) &&
124 S_ISLNK(smb_fname->st.st_ex_mode)) {
125 /* We can always delete a symlink. */
126 DEBUG(10,("smbd_check_access_rights: not checking ACL "
127 "on DELETE_ACCESS on symlink %s.\n",
128 smb_fname_str_dbg(smb_fname) ));
132 status = SMB_VFS_GET_NT_ACL(conn, smb_fname,
135 SECINFO_DACL), talloc_tos(), &sd);
137 if (!NT_STATUS_IS_OK(status)) {
138 DEBUG(10, ("smbd_check_access_rights: Could not get acl "
140 smb_fname_str_dbg(smb_fname),
143 if (NT_STATUS_EQUAL(status, NT_STATUS_ACCESS_DENIED)) {
151 * If we can access the path to this file, by
152 * default we have FILE_READ_ATTRIBUTES from the
153 * containing directory. See the section:
154 * "Algorithm to Check Access to an Existing File"
157 * se_file_access_check() also takes care of
158 * owner WRITE_DAC and READ_CONTROL.
160 do_not_check_mask = FILE_READ_ATTRIBUTES;
163 * Samba 3.6 and earlier granted execute access even
164 * if the ACL did not contain execute rights.
165 * Samba 4.0 is more correct and checks it.
166 * The compatibilty mode allows one to skip this check
167 * to smoothen upgrades.
169 if (lp_acl_allow_execute_always(SNUM(conn))) {
170 do_not_check_mask |= FILE_EXECUTE;
173 status = se_file_access_check(sd,
174 get_current_nttok(conn),
176 (access_mask & ~do_not_check_mask),
179 DEBUG(10,("smbd_check_access_rights: file %s requesting "
180 "0x%x returning 0x%x (%s)\n",
181 smb_fname_str_dbg(smb_fname),
182 (unsigned int)access_mask,
183 (unsigned int)rejected_mask,
184 nt_errstr(status) ));
186 if (!NT_STATUS_IS_OK(status)) {
187 if (DEBUGLEVEL >= 10) {
188 DEBUG(10,("smbd_check_access_rights: acl for %s is:\n",
189 smb_fname_str_dbg(smb_fname) ));
190 NDR_PRINT_DEBUG(security_descriptor, sd);
196 if (NT_STATUS_IS_OK(status) ||
197 !NT_STATUS_EQUAL(status, NT_STATUS_ACCESS_DENIED)) {
201 /* Here we know status == NT_STATUS_ACCESS_DENIED. */
205 if ((access_mask & FILE_WRITE_ATTRIBUTES) &&
206 (rejected_mask & FILE_WRITE_ATTRIBUTES) &&
207 !lp_store_dos_attributes(SNUM(conn)) &&
208 (lp_map_readonly(SNUM(conn)) ||
209 lp_map_archive(SNUM(conn)) ||
210 lp_map_hidden(SNUM(conn)) ||
211 lp_map_system(SNUM(conn)))) {
212 rejected_mask &= ~FILE_WRITE_ATTRIBUTES;
214 DEBUG(10,("smbd_check_access_rights: "
216 "FILE_WRITE_ATTRIBUTES "
218 smb_fname_str_dbg(smb_fname)));
221 if (parent_override_delete(conn,
225 /* Were we trying to do an open
226 * for delete and didn't get DELETE
227 * access (only) ? Check if the
228 * directory allows DELETE_CHILD.
230 * http://blogs.msdn.com/oldnewthing/archive/2004/06/04/148426.aspx
233 rejected_mask &= ~DELETE_ACCESS;
235 DEBUG(10,("smbd_check_access_rights: "
239 smb_fname_str_dbg(smb_fname)));
242 if (rejected_mask != 0) {
243 return NT_STATUS_ACCESS_DENIED;
248 NTSTATUS check_parent_access(struct connection_struct *conn,
249 struct smb_filename *smb_fname,
250 uint32_t access_mask)
253 char *parent_dir = NULL;
254 struct security_descriptor *parent_sd = NULL;
255 uint32_t access_granted = 0;
256 struct smb_filename *parent_smb_fname = NULL;
257 struct share_mode_lock *lck = NULL;
258 struct file_id id = {0};
260 bool delete_on_close_set;
262 TALLOC_CTX *frame = talloc_stackframe();
264 if (!parent_dirname(frame,
265 smb_fname->base_name,
268 status = NT_STATUS_NO_MEMORY;
272 parent_smb_fname = synthetic_smb_fname(frame,
277 if (parent_smb_fname == NULL) {
278 status = NT_STATUS_NO_MEMORY;
282 if (get_current_uid(conn) == (uid_t)0) {
283 /* I'm sorry sir, I didn't know you were root... */
284 DEBUG(10,("check_parent_access: root override "
285 "on %s. Granting 0x%x\n",
286 smb_fname_str_dbg(smb_fname),
287 (unsigned int)access_mask ));
288 status = NT_STATUS_OK;
292 status = SMB_VFS_GET_NT_ACL(conn,
298 if (!NT_STATUS_IS_OK(status)) {
299 DEBUG(5,("check_parent_access: SMB_VFS_GET_NT_ACL failed for "
300 "%s with error %s\n",
307 * If we can access the path to this file, by
308 * default we have FILE_READ_ATTRIBUTES from the
309 * containing directory. See the section:
310 * "Algorithm to Check Access to an Existing File"
313 * se_file_access_check() also takes care of
314 * owner WRITE_DAC and READ_CONTROL.
316 status = se_file_access_check(parent_sd,
317 get_current_nttok(conn),
319 (access_mask & ~FILE_READ_ATTRIBUTES),
321 if(!NT_STATUS_IS_OK(status)) {
322 DEBUG(5,("check_parent_access: access check "
323 "on directory %s for "
324 "path %s for mask 0x%x returned (0x%x) %s\n",
326 smb_fname->base_name,
329 nt_errstr(status) ));
333 if (!(access_mask & (SEC_DIR_ADD_FILE | SEC_DIR_ADD_SUBDIR))) {
334 status = NT_STATUS_OK;
337 if (!lp_check_parent_directory_delete_on_close(SNUM(conn))) {
338 status = NT_STATUS_OK;
342 /* Check if the directory has delete-on-close set */
343 ret = SMB_VFS_STAT(conn, parent_smb_fname);
345 status = map_nt_error_from_unix(errno);
349 id = SMB_VFS_FILE_ID_CREATE(conn, &parent_smb_fname->st);
351 status = file_name_hash(conn, parent_smb_fname->base_name, &name_hash);
352 if (!NT_STATUS_IS_OK(status)) {
356 lck = get_existing_share_mode_lock(frame, id);
358 status = NT_STATUS_OK;
362 delete_on_close_set = is_delete_on_close_set(lck, name_hash);
363 if (delete_on_close_set) {
364 status = NT_STATUS_DELETE_PENDING;
368 status = NT_STATUS_OK;
375 /****************************************************************************
376 Ensure when opening a base file for a stream open that we have permissions
377 to do so given the access mask on the base file.
378 ****************************************************************************/
380 static NTSTATUS check_base_file_access(struct connection_struct *conn,
381 struct smb_filename *smb_fname,
382 uint32_t access_mask)
386 status = smbd_calculate_access_mask(conn, smb_fname,
390 if (!NT_STATUS_IS_OK(status)) {
391 DEBUG(10, ("smbd_calculate_access_mask "
392 "on file %s returned %s\n",
393 smb_fname_str_dbg(smb_fname),
398 if (access_mask & (FILE_WRITE_DATA|FILE_APPEND_DATA)) {
400 if (!CAN_WRITE(conn)) {
401 return NT_STATUS_ACCESS_DENIED;
403 dosattrs = dos_mode(conn, smb_fname);
404 if (IS_DOS_READONLY(dosattrs)) {
405 return NT_STATUS_ACCESS_DENIED;
409 return smbd_check_access_rights(conn,
415 /****************************************************************************
416 Handle differing symlink errno's
417 ****************************************************************************/
419 static int link_errno_convert(int err)
421 #if defined(ENOTSUP) && defined(OSF1)
422 /* handle special Tru64 errno */
423 if (err == ENOTSUP) {
428 /* fix broken NetBSD errno */
433 /* fix broken FreeBSD errno */
440 static int non_widelink_open(struct connection_struct *conn,
441 const struct smb_filename *conn_rootdir_fname,
443 struct smb_filename *smb_fname,
446 unsigned int link_depth);
448 /****************************************************************************
449 Follow a symlink in userspace.
450 ****************************************************************************/
452 static int process_symlink_open(struct connection_struct *conn,
453 const struct smb_filename *conn_rootdir_fname,
455 struct smb_filename *smb_fname,
458 unsigned int link_depth)
461 char *link_target = NULL;
462 struct smb_filename target_fname = {0};
464 struct smb_filename *oldwd_fname = NULL;
465 size_t rootdir_len = 0;
466 struct smb_filename *resolved_fname = NULL;
467 char *resolved_name = NULL;
468 bool matched = false;
472 * Ensure we don't get stuck in a symlink loop.
475 if (link_depth >= 20) {
480 /* Allocate space for the link target. */
481 link_target = talloc_array(talloc_tos(), char, PATH_MAX);
482 if (link_target == NULL) {
487 /* Read the link target. */
488 link_len = SMB_VFS_READLINK(conn,
492 if (link_len == -1) {
496 /* Ensure it's at least null terminated. */
497 link_target[link_len] = '\0';
498 target_fname = (struct smb_filename){ .base_name = link_target };
500 /* Convert to an absolute path. */
501 resolved_fname = SMB_VFS_REALPATH(conn, talloc_tos(), &target_fname);
502 if (resolved_fname == NULL) {
505 resolved_name = resolved_fname->base_name;
508 * We know conn_rootdir starts with '/' and
509 * does not end in '/'. FIXME ! Should we
512 rootdir_len = strlen(conn_rootdir_fname->base_name);
514 matched = (strncmp(conn_rootdir_fname->base_name,
523 * Turn into a path relative to the share root.
525 if (resolved_name[rootdir_len] == '\0') {
526 /* Link to the root of the share. */
527 TALLOC_FREE(smb_fname->base_name);
528 smb_fname->base_name = talloc_strdup(smb_fname, ".");
529 } else if (resolved_name[rootdir_len] == '/') {
530 TALLOC_FREE(smb_fname->base_name);
531 smb_fname->base_name = talloc_strdup(smb_fname,
532 &resolved_name[rootdir_len+1]);
538 if (smb_fname->base_name == NULL) {
543 oldwd_fname = vfs_GetWd(talloc_tos(), conn);
544 if (oldwd_fname == NULL) {
548 /* Ensure we operate from the root of the share. */
549 if (vfs_ChDir(conn, conn_rootdir_fname) == -1) {
553 /* And do it all again.. */
554 fd = non_widelink_open(conn,
567 TALLOC_FREE(resolved_fname);
568 TALLOC_FREE(link_target);
569 if (oldwd_fname != NULL) {
570 int ret = vfs_ChDir(conn, oldwd_fname);
572 smb_panic("unable to get back to old directory\n");
574 TALLOC_FREE(oldwd_fname);
576 if (saved_errno != 0) {
582 /****************************************************************************
584 ****************************************************************************/
586 static int non_widelink_open(struct connection_struct *conn,
587 const struct smb_filename *conn_rootdir_fname,
589 struct smb_filename *smb_fname,
592 unsigned int link_depth)
596 struct smb_filename *smb_fname_rel = NULL;
598 struct smb_filename *oldwd_fname = NULL;
599 char *parent_dir = NULL;
600 struct smb_filename parent_dir_fname = {0};
601 const char *final_component = NULL;
602 bool is_directory = false;
606 if (flags & O_DIRECTORY) {
612 parent_dir = talloc_strdup(talloc_tos(), smb_fname->base_name);
613 if (parent_dir == NULL) {
618 final_component = ".";
620 ok = parent_dirname(talloc_tos(),
621 smb_fname->base_name,
630 parent_dir_fname = (struct smb_filename) { .base_name = parent_dir };
632 oldwd_fname = vfs_GetWd(talloc_tos(), conn);
633 if (oldwd_fname == NULL) {
637 /* Pin parent directory in place. */
638 if (vfs_ChDir(conn, &parent_dir_fname) == -1) {
642 smb_fname_rel = synthetic_smb_fname(talloc_tos(),
644 smb_fname->stream_name,
647 if (smb_fname_rel == NULL) {
648 saved_errno = ENOMEM;
652 /* Ensure the relative path is below the share. */
653 status = check_reduced_name(conn, &parent_dir_fname, smb_fname_rel);
654 if (!NT_STATUS_IS_OK(status)) {
655 saved_errno = map_errno_from_nt_status(status);
662 struct smb_filename *tmp_name = fsp->fsp_name;
663 fsp->fsp_name = smb_fname_rel;
664 fd = SMB_VFS_OPEN(conn, smb_fname_rel, fsp, flags, mode);
665 fsp->fsp_name = tmp_name;
669 saved_errno = link_errno_convert(errno);
671 * Trying to open a symlink to a directory with O_NOFOLLOW and
672 * O_DIRECTORY can return either of ELOOP and ENOTDIR. So
673 * ENOTDIR really means: might be a symlink, but we're not sure.
674 * In this case, we just assume there's a symlink. If we were
675 * wrong, process_symlink_open() will return EINVAL. We check
676 * this below, and fall back to returning the initial
679 * BUG: https://bugzilla.samba.org/show_bug.cgi?id=12860
681 if (saved_errno == ELOOP || saved_errno == ENOTDIR) {
682 if (fsp->posix_flags & FSP_POSIX_FLAGS_OPEN) {
683 /* Never follow symlinks on posix open. */
686 if (!lp_follow_symlinks(SNUM(conn))) {
687 /* Explicitly no symlinks. */
691 * We may have a symlink. Follow in userspace
692 * to ensure it's under the share definition.
694 fd = process_symlink_open(conn,
702 if (saved_errno == ENOTDIR &&
705 * O_DIRECTORY on neither a directory,
706 * nor a symlink. Just return
707 * saved_errno from initial open()
712 link_errno_convert(errno);
719 TALLOC_FREE(parent_dir);
720 TALLOC_FREE(smb_fname_rel);
722 if (oldwd_fname != NULL) {
723 int ret = vfs_ChDir(conn, oldwd_fname);
725 smb_panic("unable to get back to old directory\n");
727 TALLOC_FREE(oldwd_fname);
729 if (saved_errno != 0) {
735 /****************************************************************************
736 fd support routines - attempt to do a dos_open.
737 ****************************************************************************/
739 NTSTATUS fd_open(struct connection_struct *conn,
744 struct smb_filename *smb_fname = fsp->fsp_name;
745 NTSTATUS status = NT_STATUS_OK;
748 * Never follow symlinks on a POSIX client. The
749 * client should be doing this.
752 if ((fsp->posix_flags & FSP_POSIX_FLAGS_OPEN) || !lp_follow_symlinks(SNUM(conn))) {
756 /* Ensure path is below share definition. */
757 if (!lp_widelinks(SNUM(conn))) {
758 struct smb_filename *conn_rootdir_fname = NULL;
759 const char *conn_rootdir = SMB_VFS_CONNECTPATH(conn,
763 if (conn_rootdir == NULL) {
764 return NT_STATUS_NO_MEMORY;
766 conn_rootdir_fname = synthetic_smb_fname(talloc_tos(),
771 if (conn_rootdir_fname == NULL) {
772 return NT_STATUS_NO_MEMORY;
776 * Only follow symlinks within a share
779 fsp->fh->fd = non_widelink_open(conn,
786 if (fsp->fh->fd == -1) {
789 TALLOC_FREE(conn_rootdir_fname);
790 if (saved_errno != 0) {
794 fsp->fh->fd = SMB_VFS_OPEN(conn, smb_fname, fsp, flags, mode);
797 if (fsp->fh->fd == -1) {
798 int posix_errno = link_errno_convert(errno);
799 status = map_nt_error_from_unix(posix_errno);
800 if (errno == EMFILE) {
801 static time_t last_warned = 0L;
803 if (time((time_t *) NULL) > last_warned) {
804 DEBUG(0,("Too many open files, unable "
805 "to open more! smbd's max "
807 lp_max_open_files()));
808 last_warned = time((time_t *) NULL);
814 DEBUG(10,("fd_open: name %s, flags = 0%o mode = 0%o, fd = %d. %s\n",
815 smb_fname_str_dbg(smb_fname), flags, (int)mode, fsp->fh->fd,
816 (fsp->fh->fd == -1) ? strerror(errno) : "" ));
821 /****************************************************************************
822 Close the file associated with a fsp.
823 ****************************************************************************/
825 NTSTATUS fd_close(files_struct *fsp)
832 if (fsp->fh->fd == -1) {
833 return NT_STATUS_OK; /* What we used to call a stat open. */
835 if (fsp->fh->ref_count > 1) {
836 return NT_STATUS_OK; /* Shared handle. Only close last reference. */
839 ret = SMB_VFS_CLOSE(fsp);
842 return map_nt_error_from_unix(errno);
847 /****************************************************************************
848 Change the ownership of a file to that of the parent directory.
849 Do this by fd if possible.
850 ****************************************************************************/
852 void change_file_owner_to_parent(connection_struct *conn,
853 const char *inherit_from_dir,
856 struct smb_filename *smb_fname_parent;
859 smb_fname_parent = synthetic_smb_fname(talloc_tos(),
864 if (smb_fname_parent == NULL) {
868 ret = SMB_VFS_STAT(conn, smb_fname_parent);
870 DEBUG(0,("change_file_owner_to_parent: failed to stat parent "
871 "directory %s. Error was %s\n",
872 smb_fname_str_dbg(smb_fname_parent),
874 TALLOC_FREE(smb_fname_parent);
878 if (smb_fname_parent->st.st_ex_uid == fsp->fsp_name->st.st_ex_uid) {
879 /* Already this uid - no need to change. */
880 DEBUG(10,("change_file_owner_to_parent: file %s "
881 "is already owned by uid %d\n",
883 (int)fsp->fsp_name->st.st_ex_uid ));
884 TALLOC_FREE(smb_fname_parent);
889 ret = SMB_VFS_FCHOWN(fsp, smb_fname_parent->st.st_ex_uid, (gid_t)-1);
892 DEBUG(0,("change_file_owner_to_parent: failed to fchown "
893 "file %s to parent directory uid %u. Error "
894 "was %s\n", fsp_str_dbg(fsp),
895 (unsigned int)smb_fname_parent->st.st_ex_uid,
898 DEBUG(10,("change_file_owner_to_parent: changed new file %s to "
899 "parent directory uid %u.\n", fsp_str_dbg(fsp),
900 (unsigned int)smb_fname_parent->st.st_ex_uid));
901 /* Ensure the uid entry is updated. */
902 fsp->fsp_name->st.st_ex_uid = smb_fname_parent->st.st_ex_uid;
905 TALLOC_FREE(smb_fname_parent);
908 static NTSTATUS change_dir_owner_to_parent(connection_struct *conn,
909 const char *inherit_from_dir,
910 struct smb_filename *smb_dname,
911 SMB_STRUCT_STAT *psbuf)
913 struct smb_filename *smb_fname_parent;
914 struct smb_filename *smb_fname_cwd = NULL;
915 struct smb_filename *saved_dir_fname = NULL;
916 TALLOC_CTX *ctx = talloc_tos();
917 NTSTATUS status = NT_STATUS_OK;
920 smb_fname_parent = synthetic_smb_fname(ctx,
925 if (smb_fname_parent == NULL) {
926 return NT_STATUS_NO_MEMORY;
929 ret = SMB_VFS_STAT(conn, smb_fname_parent);
931 status = map_nt_error_from_unix(errno);
932 DEBUG(0,("change_dir_owner_to_parent: failed to stat parent "
933 "directory %s. Error was %s\n",
934 smb_fname_str_dbg(smb_fname_parent),
939 /* We've already done an lstat into psbuf, and we know it's a
940 directory. If we can cd into the directory and the dev/ino
941 are the same then we can safely chown without races as
942 we're locking the directory in place by being in it. This
943 should work on any UNIX (thanks tridge :-). JRA.
946 saved_dir_fname = vfs_GetWd(ctx,conn);
947 if (!saved_dir_fname) {
948 status = map_nt_error_from_unix(errno);
949 DEBUG(0,("change_dir_owner_to_parent: failed to get "
950 "current working directory. Error was %s\n",
955 /* Chdir into the new path. */
956 if (vfs_ChDir(conn, smb_dname) == -1) {
957 status = map_nt_error_from_unix(errno);
958 DEBUG(0,("change_dir_owner_to_parent: failed to change "
959 "current working directory to %s. Error "
960 "was %s\n", smb_dname->base_name, strerror(errno) ));
964 smb_fname_cwd = synthetic_smb_fname(ctx, ".", NULL, NULL, 0);
965 if (smb_fname_cwd == NULL) {
966 status = NT_STATUS_NO_MEMORY;
970 ret = SMB_VFS_STAT(conn, smb_fname_cwd);
972 status = map_nt_error_from_unix(errno);
973 DEBUG(0,("change_dir_owner_to_parent: failed to stat "
974 "directory '.' (%s) Error was %s\n",
975 smb_dname->base_name, strerror(errno)));
979 /* Ensure we're pointing at the same place. */
980 if (smb_fname_cwd->st.st_ex_dev != psbuf->st_ex_dev ||
981 smb_fname_cwd->st.st_ex_ino != psbuf->st_ex_ino) {
982 DEBUG(0,("change_dir_owner_to_parent: "
983 "device/inode on directory %s changed. "
984 "Refusing to chown !\n",
985 smb_dname->base_name ));
986 status = NT_STATUS_ACCESS_DENIED;
990 if (smb_fname_parent->st.st_ex_uid == smb_fname_cwd->st.st_ex_uid) {
991 /* Already this uid - no need to change. */
992 DEBUG(10,("change_dir_owner_to_parent: directory %s "
993 "is already owned by uid %d\n",
994 smb_dname->base_name,
995 (int)smb_fname_cwd->st.st_ex_uid ));
996 status = NT_STATUS_OK;
1001 ret = SMB_VFS_LCHOWN(conn,
1003 smb_fname_parent->st.st_ex_uid,
1007 status = map_nt_error_from_unix(errno);
1008 DEBUG(10,("change_dir_owner_to_parent: failed to chown "
1009 "directory %s to parent directory uid %u. "
1011 smb_dname->base_name,
1012 (unsigned int)smb_fname_parent->st.st_ex_uid,
1015 DEBUG(10,("change_dir_owner_to_parent: changed ownership of new "
1016 "directory %s to parent directory uid %u.\n",
1017 smb_dname->base_name,
1018 (unsigned int)smb_fname_parent->st.st_ex_uid ));
1019 /* Ensure the uid entry is updated. */
1020 psbuf->st_ex_uid = smb_fname_parent->st.st_ex_uid;
1024 vfs_ChDir(conn, saved_dir_fname);
1026 TALLOC_FREE(saved_dir_fname);
1027 TALLOC_FREE(smb_fname_parent);
1028 TALLOC_FREE(smb_fname_cwd);
1032 /****************************************************************************
1033 Open a file - returning a guaranteed ATOMIC indication of if the
1034 file was created or not.
1035 ****************************************************************************/
1037 static NTSTATUS fd_open_atomic(struct connection_struct *conn,
1043 NTSTATUS status = NT_STATUS_UNSUCCESSFUL;
1044 NTSTATUS retry_status;
1045 bool file_existed = VALID_STAT(fsp->fsp_name->st);
1048 *file_created = false;
1050 if (!(flags & O_CREAT)) {
1052 * We're not creating the file, just pass through.
1054 return fd_open(conn, fsp, flags, mode);
1057 if (flags & O_EXCL) {
1059 * Fail if already exists, just pass through.
1061 status = fd_open(conn, fsp, flags, mode);
1064 * Here we've opened with O_CREAT|O_EXCL. If that went
1065 * NT_STATUS_OK, we *know* we created this file.
1067 *file_created = NT_STATUS_IS_OK(status);
1073 * Now it gets tricky. We have O_CREAT, but not O_EXCL.
1074 * To know absolutely if we created the file or not,
1075 * we can never call O_CREAT without O_EXCL. So if
1076 * we think the file existed, try without O_CREAT|O_EXCL.
1077 * If we think the file didn't exist, try with
1080 * The big problem here is dangling symlinks. Opening
1081 * without O_NOFOLLOW means both bad symlink
1082 * and missing path return -1, ENOENT from open(). As POSIX
1083 * is pathname based it's not possible to tell
1084 * the difference between these two cases in a
1085 * non-racy way, so change to try only two attempts before
1088 * We don't have this problem for the O_NOFOLLOW
1089 * case as it just returns NT_STATUS_OBJECT_PATH_NOT_FOUND
1090 * mapped from the ELOOP POSIX error.
1096 curr_flags &= ~(O_CREAT);
1097 retry_status = NT_STATUS_OBJECT_NAME_NOT_FOUND;
1099 curr_flags |= O_EXCL;
1100 retry_status = NT_STATUS_OBJECT_NAME_COLLISION;
1103 status = fd_open(conn, fsp, curr_flags, mode);
1104 if (NT_STATUS_IS_OK(status)) {
1105 if (!file_existed) {
1106 *file_created = true;
1108 return NT_STATUS_OK;
1110 if (!NT_STATUS_EQUAL(status, retry_status)) {
1117 * Keep file_existed up to date for clarity.
1119 if (NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
1120 file_existed = false;
1121 curr_flags |= O_EXCL;
1122 DBG_DEBUG("file %s did not exist. Retry.\n",
1123 smb_fname_str_dbg(fsp->fsp_name));
1125 file_existed = true;
1126 curr_flags &= ~(O_CREAT);
1127 DBG_DEBUG("file %s existed. Retry.\n",
1128 smb_fname_str_dbg(fsp->fsp_name));
1131 status = fd_open(conn, fsp, curr_flags, mode);
1133 if (NT_STATUS_IS_OK(status) && (!file_existed)) {
1134 *file_created = true;
1140 /****************************************************************************
1142 ****************************************************************************/
1144 static NTSTATUS open_file(files_struct *fsp,
1145 connection_struct *conn,
1146 struct smb_request *req,
1147 const char *parent_dir,
1150 uint32_t access_mask, /* client requested access mask. */
1151 uint32_t open_access_mask, /* what we're actually using in the open. */
1152 bool *p_file_created)
1154 struct smb_filename *smb_fname = fsp->fsp_name;
1155 NTSTATUS status = NT_STATUS_OK;
1156 int accmode = (flags & O_ACCMODE);
1157 int local_flags = flags;
1158 bool file_existed = VALID_STAT(fsp->fsp_name->st);
1163 /* Check permissions */
1166 * This code was changed after seeing a client open request
1167 * containing the open mode of (DENY_WRITE/read-only) with
1168 * the 'create if not exist' bit set. The previous code
1169 * would fail to open the file read only on a read-only share
1170 * as it was checking the flags parameter directly against O_RDONLY,
1171 * this was failing as the flags parameter was set to O_RDONLY|O_CREAT.
1175 if (!CAN_WRITE(conn)) {
1176 /* It's a read-only share - fail if we wanted to write. */
1177 if(accmode != O_RDONLY || (flags & O_TRUNC) || (flags & O_APPEND)) {
1178 DEBUG(3,("Permission denied opening %s\n",
1179 smb_fname_str_dbg(smb_fname)));
1180 return NT_STATUS_ACCESS_DENIED;
1182 if (flags & O_CREAT) {
1183 /* We don't want to write - but we must make sure that
1184 O_CREAT doesn't create the file if we have write
1185 access into the directory.
1187 flags &= ~(O_CREAT|O_EXCL);
1188 local_flags &= ~(O_CREAT|O_EXCL);
1193 * This little piece of insanity is inspired by the
1194 * fact that an NT client can open a file for O_RDONLY,
1195 * but set the create disposition to FILE_EXISTS_TRUNCATE.
1196 * If the client *can* write to the file, then it expects to
1197 * truncate the file, even though it is opening for readonly.
1198 * Quicken uses this stupid trick in backup file creation...
1199 * Thanks *greatly* to "David W. Chapman Jr." <dwcjr@inethouston.net>
1200 * for helping track this one down. It didn't bite us in 2.0.x
1201 * as we always opened files read-write in that release. JRA.
1204 if ((accmode == O_RDONLY) && ((flags & O_TRUNC) == O_TRUNC)) {
1205 DEBUG(10,("open_file: truncate requested on read-only open "
1206 "for file %s\n", smb_fname_str_dbg(smb_fname)));
1207 local_flags = (flags & ~O_ACCMODE)|O_RDWR;
1210 if ((open_access_mask & (FILE_READ_DATA|FILE_WRITE_DATA|
1211 FILE_APPEND_DATA|FILE_EXECUTE|
1212 WRITE_DAC_ACCESS|WRITE_OWNER_ACCESS|
1213 READ_CONTROL_ACCESS))||
1214 (!file_existed && (local_flags & O_CREAT)) ||
1215 ((local_flags & O_TRUNC) == O_TRUNC) ) {
1219 #if defined(O_NONBLOCK) && defined(S_ISFIFO)
1221 * We would block on opening a FIFO with no one else on the
1222 * other end. Do what we used to do and add O_NONBLOCK to the
1226 if (file_existed && S_ISFIFO(smb_fname->st.st_ex_mode)) {
1227 local_flags &= ~O_TRUNC; /* Can't truncate a FIFO. */
1228 local_flags |= O_NONBLOCK;
1232 /* Don't create files with Microsoft wildcard characters. */
1233 if (fsp->base_fsp) {
1235 * wildcard characters are allowed in stream names
1236 * only test the basefilename
1238 wild = fsp->base_fsp->fsp_name->base_name;
1240 wild = smb_fname->base_name;
1242 if ((local_flags & O_CREAT) && !file_existed &&
1243 !(fsp->posix_flags & FSP_POSIX_FLAGS_PATHNAMES) &&
1244 ms_has_wild(wild)) {
1245 return NT_STATUS_OBJECT_NAME_INVALID;
1248 /* Can we access this file ? */
1249 if (!fsp->base_fsp) {
1250 /* Only do this check on non-stream open. */
1252 status = smbd_check_access_rights(conn,
1257 if (!NT_STATUS_IS_OK(status)) {
1258 DEBUG(10, ("open_file: "
1259 "smbd_check_access_rights "
1260 "on file %s returned %s\n",
1261 smb_fname_str_dbg(smb_fname),
1262 nt_errstr(status)));
1265 if (!NT_STATUS_IS_OK(status) &&
1266 !NT_STATUS_EQUAL(status,
1267 NT_STATUS_OBJECT_NAME_NOT_FOUND))
1272 if (NT_STATUS_EQUAL(status,
1273 NT_STATUS_OBJECT_NAME_NOT_FOUND))
1275 DEBUG(10, ("open_file: "
1276 "file %s vanished since we "
1277 "checked for existence.\n",
1278 smb_fname_str_dbg(smb_fname)));
1279 file_existed = false;
1280 SET_STAT_INVALID(fsp->fsp_name->st);
1284 if (!file_existed) {
1285 if (!(local_flags & O_CREAT)) {
1286 /* File didn't exist and no O_CREAT. */
1287 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
1290 status = check_parent_access(conn,
1293 if (!NT_STATUS_IS_OK(status)) {
1294 DEBUG(10, ("open_file: "
1295 "check_parent_access on "
1296 "file %s returned %s\n",
1297 smb_fname_str_dbg(smb_fname),
1298 nt_errstr(status) ));
1305 * Actually do the open - if O_TRUNC is needed handle it
1306 * below under the share mode lock.
1308 status = fd_open_atomic(conn, fsp, local_flags & ~O_TRUNC,
1309 unx_mode, p_file_created);
1310 if (!NT_STATUS_IS_OK(status)) {
1311 DEBUG(3,("Error opening file %s (%s) (local_flags=%d) "
1312 "(flags=%d)\n", smb_fname_str_dbg(smb_fname),
1313 nt_errstr(status),local_flags,flags));
1317 if (local_flags & O_NONBLOCK) {
1319 * GPFS can return ETIMEDOUT for pread on
1320 * nonblocking file descriptors when files
1321 * migrated to tape need to be recalled. I
1322 * could imagine this happens elsewhere
1323 * too. With blocking file descriptors this
1326 ret = set_blocking(fsp->fh->fd, true);
1328 status = map_nt_error_from_unix(errno);
1329 DBG_WARNING("Could not set fd to blocking: "
1330 "%s\n", strerror(errno));
1336 ret = SMB_VFS_FSTAT(fsp, &smb_fname->st);
1338 /* If we have an fd, this stat should succeed. */
1339 DEBUG(0,("Error doing fstat on open file %s "
1341 smb_fname_str_dbg(smb_fname),
1343 status = map_nt_error_from_unix(errno);
1348 if (*p_file_created) {
1349 /* We created this file. */
1351 bool need_re_stat = false;
1352 /* Do all inheritance work after we've
1353 done a successful fstat call and filled
1354 in the stat struct in fsp->fsp_name. */
1356 /* Inherit the ACL if required */
1357 if (lp_inherit_permissions(SNUM(conn))) {
1358 inherit_access_posix_acl(conn, parent_dir,
1361 need_re_stat = true;
1364 /* Change the owner if required. */
1365 if (lp_inherit_owner(SNUM(conn)) != INHERIT_OWNER_NO) {
1366 change_file_owner_to_parent(conn, parent_dir,
1368 need_re_stat = true;
1372 ret = SMB_VFS_FSTAT(fsp, &smb_fname->st);
1373 /* If we have an fd, this stat should succeed. */
1375 DEBUG(0,("Error doing fstat on open file %s "
1377 smb_fname_str_dbg(smb_fname),
1382 notify_fname(conn, NOTIFY_ACTION_ADDED,
1383 FILE_NOTIFY_CHANGE_FILE_NAME,
1384 smb_fname->base_name);
1387 fsp->fh->fd = -1; /* What we used to call a stat open. */
1388 if (!file_existed) {
1389 /* File must exist for a stat open. */
1390 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
1393 status = smbd_check_access_rights(conn,
1398 if (NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND) &&
1399 (fsp->posix_flags & FSP_POSIX_FLAGS_OPEN) &&
1400 S_ISLNK(smb_fname->st.st_ex_mode)) {
1401 /* This is a POSIX stat open for delete
1402 * or rename on a symlink that points
1403 * nowhere. Allow. */
1404 DEBUG(10,("open_file: allowing POSIX "
1405 "open on bad symlink %s\n",
1406 smb_fname_str_dbg(smb_fname)));
1407 status = NT_STATUS_OK;
1410 if (!NT_STATUS_IS_OK(status)) {
1411 DEBUG(10,("open_file: "
1412 "smbd_check_access_rights on file "
1414 smb_fname_str_dbg(smb_fname),
1415 nt_errstr(status) ));
1421 * POSIX allows read-only opens of directories. We don't
1422 * want to do this (we use a different code path for this)
1423 * so catch a directory open and return an EISDIR. JRA.
1426 if(S_ISDIR(smb_fname->st.st_ex_mode)) {
1429 return NT_STATUS_FILE_IS_A_DIRECTORY;
1432 fsp->file_id = vfs_file_id_from_sbuf(conn, &smb_fname->st);
1433 fsp->vuid = req ? req->vuid : UID_FIELD_INVALID;
1434 fsp->file_pid = req ? req->smbpid : 0;
1435 fsp->can_lock = True;
1436 fsp->can_read = ((access_mask & FILE_READ_DATA) != 0);
1439 ((access_mask & (FILE_WRITE_DATA | FILE_APPEND_DATA)) != 0);
1440 fsp->print_file = NULL;
1441 fsp->modified = False;
1442 fsp->sent_oplock_break = NO_BREAK_SENT;
1443 fsp->is_directory = False;
1444 if (conn->aio_write_behind_list &&
1445 is_in_path(smb_fname->base_name, conn->aio_write_behind_list,
1446 conn->case_sensitive)) {
1447 fsp->aio_write_behind = True;
1450 fsp->wcp = NULL; /* Write cache pointer. */
1452 DEBUG(2,("%s opened file %s read=%s write=%s (numopen=%d)\n",
1453 conn->session_info->unix_info->unix_name,
1454 smb_fname_str_dbg(smb_fname),
1455 BOOLSTR(fsp->can_read), BOOLSTR(fsp->can_write),
1456 conn->num_files_open));
1459 return NT_STATUS_OK;
1462 /****************************************************************************
1463 Check if we can open a file with a share mode.
1464 Returns True if conflict, False if not.
1465 ****************************************************************************/
1467 static bool share_conflict(struct share_mode_entry *entry,
1468 uint32_t access_mask,
1469 uint32_t share_access)
1471 DEBUG(10,("share_conflict: entry->access_mask = 0x%x, "
1472 "entry->share_access = 0x%x, "
1473 "entry->private_options = 0x%x\n",
1474 (unsigned int)entry->access_mask,
1475 (unsigned int)entry->share_access,
1476 (unsigned int)entry->private_options));
1478 if (server_id_is_disconnected(&entry->pid)) {
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 (is_stat_open(access_mask)) {
1649 /* Stat open that doesn't trigger oplock breaks or share mode
1650 * checks... ! JRA. */
1651 return NT_STATUS_OK;
1655 * Check if the share modes will give us access.
1658 #if defined(DEVELOPER)
1659 for(i = 0; i < lck->data->num_share_modes; i++) {
1660 validate_my_share_entries(conn->sconn, lck->data->id, i,
1661 &lck->data->share_modes[i]);
1665 /* Now we check the share modes, after any oplock breaks. */
1666 for(i = 0; i < lck->data->num_share_modes; i++) {
1668 if (!is_valid_share_mode_entry(&lck->data->share_modes[i])) {
1672 /* someone else has a share lock on it, check to see if we can
1674 if (share_conflict(&lck->data->share_modes[i],
1675 access_mask, share_access)) {
1677 if (share_mode_stale_pid(lck->data, i)) {
1681 return NT_STATUS_SHARING_VIOLATION;
1685 return NT_STATUS_OK;
1689 * Send a break message to the oplock holder and delay the open for
1693 NTSTATUS send_break_message(struct messaging_context *msg_ctx,
1694 const struct file_id *id,
1695 const struct share_mode_entry *exclusive,
1698 struct oplock_break_message msg = {
1700 .share_file_id = exclusive->share_file_id,
1701 .break_to = break_to,
1703 enum ndr_err_code ndr_err;
1708 struct server_id_buf buf;
1709 DBG_DEBUG("Sending break message to %s\n",
1710 server_id_str_buf(exclusive->pid, &buf));
1711 NDR_PRINT_DEBUG(oplock_break_message, &msg);
1714 ndr_err = ndr_push_struct_blob(
1718 (ndr_push_flags_fn_t)ndr_push_oplock_break_message);
1719 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
1720 DBG_WARNING("ndr_push_oplock_break_message failed: %s\n",
1721 ndr_errstr(ndr_err));
1722 return ndr_map_error2ntstatus(ndr_err);
1725 status = messaging_send(
1726 msg_ctx, exclusive->pid, MSG_SMB_BREAK_REQUEST, &blob);
1727 TALLOC_FREE(blob.data);
1728 if (!NT_STATUS_IS_OK(status)) {
1729 DEBUG(3, ("Could not send oplock break message: %s\n",
1730 nt_errstr(status)));
1737 * Do internal consistency checks on the share mode for a file.
1740 static bool validate_oplock_types(struct share_mode_lock *lck)
1742 struct share_mode_data *d = lck->data;
1744 bool ex_or_batch = false;
1745 bool level2 = false;
1746 bool no_oplock = false;
1747 uint32_t num_non_stat_opens = 0;
1750 for (i=0; i<d->num_share_modes; i++) {
1751 struct share_mode_entry *e = &d->share_modes[i];
1753 if (!is_valid_share_mode_entry(e)) {
1757 if (e->op_mid == 0) {
1758 /* INTERNAL_OPEN_ONLY */
1762 if (e->op_type == NO_OPLOCK && is_stat_open(e->access_mask)) {
1763 /* We ignore stat opens in the table - they
1764 always have NO_OPLOCK and never get or
1765 cause breaks. JRA. */
1769 num_non_stat_opens += 1;
1771 if (BATCH_OPLOCK_TYPE(e->op_type)) {
1772 /* batch - can only be one. */
1773 if (share_mode_stale_pid(d, i)) {
1774 DEBUG(10, ("Found stale batch oplock\n"));
1777 if (ex_or_batch || batch || level2 || no_oplock) {
1778 DEBUG(0, ("Bad batch oplock entry %u.",
1785 if (EXCLUSIVE_OPLOCK_TYPE(e->op_type)) {
1786 if (share_mode_stale_pid(d, i)) {
1787 DEBUG(10, ("Found stale duplicate oplock\n"));
1790 /* Exclusive or batch - can only be one. */
1791 if (ex_or_batch || level2 || no_oplock) {
1792 DEBUG(0, ("Bad exclusive or batch oplock "
1793 "entry %u.", (unsigned)i));
1799 if (LEVEL_II_OPLOCK_TYPE(e->op_type)) {
1800 if (batch || ex_or_batch) {
1801 if (share_mode_stale_pid(d, i)) {
1802 DEBUG(10, ("Found stale LevelII "
1806 DEBUG(0, ("Bad levelII oplock entry %u.",
1813 if (e->op_type == NO_OPLOCK) {
1814 if (batch || ex_or_batch) {
1815 if (share_mode_stale_pid(d, i)) {
1816 DEBUG(10, ("Found stale NO_OPLOCK "
1820 DEBUG(0, ("Bad no oplock entry %u.",
1828 remove_stale_share_mode_entries(d);
1830 if ((batch || ex_or_batch) && (num_non_stat_opens != 1)) {
1831 DEBUG(1, ("got batch (%d) or ex (%d) non-exclusively (%d)\n",
1832 (int)batch, (int)ex_or_batch,
1833 (int)d->num_share_modes));
1840 static bool delay_for_oplock(files_struct *fsp,
1842 const struct smb2_lease *lease,
1843 struct share_mode_lock *lck,
1844 bool have_sharing_violation,
1845 uint32_t create_disposition,
1846 bool first_open_attempt)
1848 struct share_mode_data *d = lck->data;
1851 bool will_overwrite;
1852 const uint32_t delay_mask = have_sharing_violation ?
1853 SMB2_LEASE_HANDLE : SMB2_LEASE_WRITE;
1855 if ((oplock_request & INTERNAL_OPEN_ONLY) ||
1856 is_stat_open(fsp->access_mask)) {
1860 switch (create_disposition) {
1861 case FILE_SUPERSEDE:
1862 case FILE_OVERWRITE:
1863 case FILE_OVERWRITE_IF:
1864 will_overwrite = true;
1867 will_overwrite = false;
1871 for (i=0; i<d->num_share_modes; i++) {
1872 struct share_mode_entry *e = &d->share_modes[i];
1873 bool e_is_lease = (e->op_type == LEASE_OPLOCK);
1874 uint32_t e_lease_type = get_lease_type(d, e);
1876 bool lease_is_breaking = false;
1881 if (lease != NULL) {
1882 bool our_lease = smb2_lease_equal(
1883 fsp_client_guid(fsp),
1888 DBG_DEBUG("Ignoring our own lease\n");
1893 status = leases_db_get(
1897 NULL, /* current_state */
1899 NULL, /* breaking_to_requested */
1900 NULL, /* breaking_to_required */
1901 NULL, /* lease_version */
1903 SMB_ASSERT(NT_STATUS_IS_OK(status));
1906 break_to = e_lease_type & ~delay_mask;
1908 if (will_overwrite) {
1909 break_to &= ~(SMB2_LEASE_HANDLE|SMB2_LEASE_READ);
1912 DEBUG(10, ("entry %u: e_lease_type %u, will_overwrite: %u\n",
1913 (unsigned)i, (unsigned)e_lease_type,
1914 (unsigned)will_overwrite));
1916 if ((e_lease_type & ~break_to) == 0) {
1917 if (lease_is_breaking) {
1923 if (share_mode_stale_pid(d, i)) {
1927 if (will_overwrite) {
1929 * If we break anyway break to NONE directly.
1930 * Otherwise vfs_set_filelen() will trigger the
1933 break_to &= ~(SMB2_LEASE_READ|SMB2_LEASE_WRITE);
1938 * Oplocks only support breaking to R or NONE.
1940 break_to &= ~(SMB2_LEASE_HANDLE|SMB2_LEASE_WRITE);
1943 DEBUG(10, ("breaking from %d to %d\n",
1944 (int)e_lease_type, (int)break_to));
1945 send_break_message(fsp->conn->sconn->msg_ctx, &fsp->file_id,
1947 if (e_lease_type & delay_mask) {
1950 if (lease_is_breaking && !first_open_attempt) {
1958 static bool file_has_brlocks(files_struct *fsp)
1960 struct byte_range_lock *br_lck;
1962 br_lck = brl_get_locks_readonly(fsp);
1966 return (brl_num_locks(br_lck) > 0);
1969 struct fsp_lease *find_fsp_lease(struct files_struct *new_fsp,
1970 const struct smb2_lease_key *key,
1971 uint32_t current_state,
1972 uint16_t lease_version,
1973 uint16_t lease_epoch)
1975 struct files_struct *fsp;
1978 * TODO: Measure how expensive this loop is with thousands of open
1982 for (fsp = file_find_di_first(new_fsp->conn->sconn, new_fsp->file_id);
1984 fsp = file_find_di_next(fsp)) {
1986 if (fsp == new_fsp) {
1989 if (fsp->oplock_type != LEASE_OPLOCK) {
1992 if (smb2_lease_key_equal(&fsp->lease->lease.lease_key, key)) {
1993 fsp->lease->ref_count += 1;
1998 /* Not found - must be leased in another smbd. */
1999 new_fsp->lease = talloc_zero(new_fsp->conn->sconn, struct fsp_lease);
2000 if (new_fsp->lease == NULL) {
2003 new_fsp->lease->ref_count = 1;
2004 new_fsp->lease->sconn = new_fsp->conn->sconn;
2005 new_fsp->lease->lease.lease_key = *key;
2006 new_fsp->lease->lease.lease_state = current_state;
2008 * We internally treat all leases as V2 and update
2009 * the epoch, but when sending breaks it matters if
2010 * the requesting lease was v1 or v2.
2012 new_fsp->lease->lease.lease_version = lease_version;
2013 new_fsp->lease->lease.lease_epoch = lease_epoch;
2014 return new_fsp->lease;
2017 static NTSTATUS try_lease_upgrade(struct files_struct *fsp,
2018 struct share_mode_lock *lck,
2019 const struct GUID *client_guid,
2020 const struct smb2_lease *lease,
2024 uint32_t current_state, breaking_to_requested, breaking_to_required;
2026 uint16_t lease_version, epoch;
2027 uint32_t existing, requested;
2030 status = leases_db_get(
2036 &breaking_to_requested,
2037 &breaking_to_required,
2040 if (!NT_STATUS_IS_OK(status)) {
2044 fsp->lease = find_fsp_lease(
2050 if (fsp->lease == NULL) {
2051 DEBUG(1, ("Did not find existing lease for file %s\n",
2053 return NT_STATUS_NO_MEMORY;
2057 * Upgrade only if the requested lease is a strict upgrade.
2059 existing = current_state;
2060 requested = lease->lease_state;
2063 * Tricky: This test makes sure that "requested" is a
2064 * strict bitwise superset of "existing".
2066 do_upgrade = ((existing & requested) == existing);
2069 * Upgrade only if there's a change.
2071 do_upgrade &= (granted != existing);
2074 * Upgrade only if other leases don't prevent what was asked
2077 do_upgrade &= (granted == requested);
2080 * only upgrade if we are not in breaking state
2082 do_upgrade &= !breaking;
2084 DEBUG(10, ("existing=%"PRIu32", requested=%"PRIu32", "
2085 "granted=%"PRIu32", do_upgrade=%d\n",
2086 existing, requested, granted, (int)do_upgrade));
2089 NTSTATUS set_status;
2091 current_state = granted;
2094 set_status = leases_db_set(
2099 breaking_to_requested,
2100 breaking_to_required,
2104 if (!NT_STATUS_IS_OK(set_status)) {
2105 DBG_DEBUG("leases_db_set failed: %s\n",
2106 nt_errstr(set_status));
2111 fsp_lease_update(fsp);
2113 return NT_STATUS_OK;
2116 static NTSTATUS grant_new_fsp_lease(struct files_struct *fsp,
2117 struct share_mode_lock *lck,
2118 const struct GUID *client_guid,
2119 const struct smb2_lease *lease,
2122 struct share_mode_data *d = lck->data;
2125 fsp->lease = talloc_zero(fsp->conn->sconn, struct fsp_lease);
2126 if (fsp->lease == NULL) {
2127 return NT_STATUS_INSUFFICIENT_RESOURCES;
2129 fsp->lease->ref_count = 1;
2130 fsp->lease->sconn = fsp->conn->sconn;
2131 fsp->lease->lease.lease_version = lease->lease_version;
2132 fsp->lease->lease.lease_key = lease->lease_key;
2133 fsp->lease->lease.lease_state = granted;
2134 fsp->lease->lease.lease_epoch = lease->lease_epoch + 1;
2136 status = leases_db_add(client_guid,
2139 fsp->lease->lease.lease_state,
2140 fsp->lease->lease.lease_version,
2141 fsp->lease->lease.lease_epoch,
2142 fsp->conn->connectpath,
2143 fsp->fsp_name->base_name,
2144 fsp->fsp_name->stream_name);
2145 if (!NT_STATUS_IS_OK(status)) {
2146 DEBUG(10, ("%s: leases_db_add failed: %s\n", __func__,
2147 nt_errstr(status)));
2148 TALLOC_FREE(fsp->lease);
2149 return NT_STATUS_INSUFFICIENT_RESOURCES;
2154 return NT_STATUS_OK;
2157 static NTSTATUS grant_fsp_lease(struct files_struct *fsp,
2158 struct share_mode_lock *lck,
2159 const struct smb2_lease *lease,
2162 const struct GUID *client_guid = fsp_client_guid(fsp);
2165 status = try_lease_upgrade(fsp, lck, client_guid, lease, granted);
2167 if (NT_STATUS_EQUAL(status, NT_STATUS_NOT_FOUND)) {
2168 status = grant_new_fsp_lease(
2169 fsp, lck, client_guid, lease, granted);
2175 static bool is_same_lease(const files_struct *fsp,
2176 const struct share_mode_data *d,
2177 const struct share_mode_entry *e,
2178 const struct smb2_lease *lease)
2180 if (e->op_type != LEASE_OPLOCK) {
2183 if (lease == NULL) {
2187 return smb2_lease_equal(fsp_client_guid(fsp),
2193 static int map_lease_type_to_oplock(uint32_t lease_type)
2195 int result = NO_OPLOCK;
2197 switch (lease_type) {
2198 case SMB2_LEASE_READ|SMB2_LEASE_WRITE|SMB2_LEASE_HANDLE:
2199 result = BATCH_OPLOCK|EXCLUSIVE_OPLOCK;
2201 case SMB2_LEASE_READ|SMB2_LEASE_WRITE:
2202 result = EXCLUSIVE_OPLOCK;
2204 case SMB2_LEASE_READ|SMB2_LEASE_HANDLE:
2205 case SMB2_LEASE_READ:
2206 result = LEVEL_II_OPLOCK;
2213 static NTSTATUS grant_fsp_oplock_type(struct smb_request *req,
2214 struct files_struct *fsp,
2215 struct share_mode_lock *lck,
2217 struct smb2_lease *lease)
2219 struct share_mode_data *d = lck->data;
2220 bool got_handle_lease = false;
2221 bool got_oplock = false;
2224 const struct GUID *client_guid = NULL;
2225 const struct smb2_lease_key *lease_key = NULL;
2229 if (oplock_request & INTERNAL_OPEN_ONLY) {
2230 /* No oplocks on internal open. */
2231 oplock_request = NO_OPLOCK;
2232 DEBUG(10,("grant_fsp_oplock_type: oplock type 0x%x on file %s\n",
2233 fsp->oplock_type, fsp_str_dbg(fsp)));
2236 if (oplock_request == LEASE_OPLOCK) {
2237 if (lease == NULL) {
2239 * The SMB2 layer should have checked this
2241 return NT_STATUS_INTERNAL_ERROR;
2244 granted = lease->lease_state;
2246 if (lp_kernel_oplocks(SNUM(fsp->conn))) {
2247 DEBUG(10, ("No lease granted because kernel oplocks are enabled\n"));
2248 granted = SMB2_LEASE_NONE;
2250 if ((granted & (SMB2_LEASE_READ|SMB2_LEASE_WRITE)) == 0) {
2251 DEBUG(10, ("No read or write lease requested\n"));
2252 granted = SMB2_LEASE_NONE;
2254 if (granted == SMB2_LEASE_WRITE) {
2255 DEBUG(10, ("pure write lease requested\n"));
2256 granted = SMB2_LEASE_NONE;
2258 if (granted == (SMB2_LEASE_WRITE|SMB2_LEASE_HANDLE)) {
2259 DEBUG(10, ("write and handle lease requested\n"));
2260 granted = SMB2_LEASE_NONE;
2263 granted = map_oplock_to_lease_type(
2264 oplock_request & ~SAMBA_PRIVATE_OPLOCK_MASK);
2267 if (lp_locking(fsp->conn->params) && file_has_brlocks(fsp)) {
2268 DEBUG(10,("grant_fsp_oplock_type: file %s has byte range locks\n",
2270 granted &= ~SMB2_LEASE_READ;
2273 for (i=0; i<d->num_share_modes; i++) {
2274 struct share_mode_entry *e = &d->share_modes[i];
2275 uint32_t e_lease_type;
2277 e_lease_type = get_lease_type(d, e);
2279 if ((granted & SMB2_LEASE_WRITE) &&
2280 !is_same_lease(fsp, d, e, lease) &&
2281 !share_mode_stale_pid(d, i)) {
2283 * Can grant only one writer
2285 granted &= ~SMB2_LEASE_WRITE;
2288 if ((e_lease_type & SMB2_LEASE_HANDLE) && !got_handle_lease &&
2289 !share_mode_stale_pid(d, i)) {
2290 got_handle_lease = true;
2293 if ((e->op_type != LEASE_OPLOCK) && !got_oplock &&
2294 !share_mode_stale_pid(d, i)) {
2299 if ((granted & SMB2_LEASE_READ) && !(granted & SMB2_LEASE_WRITE)) {
2301 (global_client_caps & CAP_LEVEL_II_OPLOCKS) &&
2302 lp_level2_oplocks(SNUM(fsp->conn));
2304 if (!allow_level2) {
2305 granted = SMB2_LEASE_NONE;
2309 if (oplock_request == LEASE_OPLOCK) {
2311 granted &= ~SMB2_LEASE_HANDLE;
2314 fsp->oplock_type = LEASE_OPLOCK;
2316 status = grant_fsp_lease(fsp, lck, lease, granted);
2317 if (!NT_STATUS_IS_OK(status)) {
2321 *lease = fsp->lease->lease;
2323 lease_key = &fsp->lease->lease.lease_key;
2324 client_guid = fsp_client_guid(fsp);
2326 DEBUG(10, ("lease_state=%d\n", lease->lease_state));
2328 if (got_handle_lease) {
2329 granted = SMB2_LEASE_NONE;
2332 fsp->oplock_type = map_lease_type_to_oplock(granted);
2334 status = set_file_oplock(fsp);
2335 if (!NT_STATUS_IS_OK(status)) {
2337 * Could not get the kernel oplock
2339 fsp->oplock_type = NO_OPLOCK;
2343 ok = set_share_mode(
2346 get_current_uid(fsp->conn),
2352 return NT_STATUS_NO_MEMORY;
2355 if (granted & SMB2_LEASE_READ) {
2356 lck->data->flags |= SHARE_MODE_HAS_READ_LEASE;
2359 DEBUG(10,("grant_fsp_oplock_type: oplock type 0x%x on file %s\n",
2360 fsp->oplock_type, fsp_str_dbg(fsp)));
2362 return NT_STATUS_OK;
2365 static bool request_timed_out(struct timeval request_time,
2366 struct timeval timeout)
2368 struct timeval now, end_time;
2370 end_time = timeval_sum(&request_time, &timeout);
2371 return (timeval_compare(&end_time, &now) < 0);
2374 static struct deferred_open_record *deferred_open_record_create(
2375 bool delayed_for_oplocks,
2379 struct deferred_open_record *record = NULL;
2381 record = talloc(NULL, struct deferred_open_record);
2382 if (record == NULL) {
2386 *record = (struct deferred_open_record) {
2387 .delayed_for_oplocks = delayed_for_oplocks,
2388 .async_open = async_open,
2395 struct defer_open_state {
2396 struct smbXsrv_connection *xconn;
2400 static void defer_open_done(struct tevent_req *req);
2403 * Defer an open and watch a locking.tdb record
2405 * This defers an open that gets rescheduled once the locking.tdb record watch
2406 * is triggered by a change to the record.
2408 * It is used to defer opens that triggered an oplock break and for the SMB1
2409 * sharing violation delay.
2411 static void defer_open(struct share_mode_lock *lck,
2412 struct timeval request_time,
2413 struct timeval timeout,
2414 struct smb_request *req,
2415 bool delayed_for_oplocks,
2418 struct deferred_open_record *open_rec = NULL;
2419 struct timeval abs_timeout;
2420 struct defer_open_state *watch_state;
2421 struct tevent_req *watch_req;
2424 abs_timeout = timeval_sum(&request_time, &timeout);
2426 DBG_DEBUG("request time [%s] timeout [%s] mid [%" PRIu64 "] "
2427 "delayed_for_oplocks [%s] file_id [%s]\n",
2428 timeval_string(talloc_tos(), &request_time, false),
2429 timeval_string(talloc_tos(), &abs_timeout, false),
2431 delayed_for_oplocks ? "yes" : "no",
2432 file_id_string_tos(&id));
2434 open_rec = deferred_open_record_create(delayed_for_oplocks,
2437 if (open_rec == NULL) {
2439 exit_server("talloc failed");
2442 watch_state = talloc(open_rec, struct defer_open_state);
2443 if (watch_state == NULL) {
2444 exit_server("talloc failed");
2446 watch_state->xconn = req->xconn;
2447 watch_state->mid = req->mid;
2449 DBG_DEBUG("defering mid %" PRIu64 "\n", req->mid);
2451 watch_req = dbwrap_watched_watch_send(watch_state,
2454 (struct server_id){0});
2455 if (watch_req == NULL) {
2456 exit_server("Could not watch share mode record");
2458 tevent_req_set_callback(watch_req, defer_open_done, watch_state);
2460 ok = tevent_req_set_endtime(watch_req, req->sconn->ev_ctx, abs_timeout);
2462 exit_server("tevent_req_set_endtime failed");
2465 ok = push_deferred_open_message_smb(req, request_time, timeout,
2466 open_rec->id, open_rec);
2469 exit_server("push_deferred_open_message_smb failed");
2473 static void defer_open_done(struct tevent_req *req)
2475 struct defer_open_state *state = tevent_req_callback_data(
2476 req, struct defer_open_state);
2480 status = dbwrap_watched_watch_recv(req, NULL, NULL);
2482 if (!NT_STATUS_IS_OK(status)) {
2483 DEBUG(5, ("dbwrap_watched_watch_recv returned %s\n",
2484 nt_errstr(status)));
2486 * Even if it failed, retry anyway. TODO: We need a way to
2487 * tell a re-scheduled open about that error.
2491 DEBUG(10, ("scheduling mid %llu\n", (unsigned long long)state->mid));
2493 ret = schedule_deferred_open_message_smb(state->xconn, state->mid);
2499 * Actually attempt the kernel oplock polling open.
2502 static void kernel_oplock_poll_open_timer(struct tevent_context *ev,
2503 struct tevent_timer *te,
2504 struct timeval current_time,
2508 struct smb_request *req = (struct smb_request *)private_data;
2510 ok = schedule_deferred_open_message_smb(req->xconn, req->mid);
2512 exit_server("schedule_deferred_open_message_smb failed");
2514 DBG_DEBUG("kernel_oplock_poll_open_timer fired. Retying open !\n");
2518 * Reschedule an open for 1 second from now, if not timed out.
2520 static void setup_kernel_oplock_poll_open(struct timeval request_time,
2521 struct smb_request *req,
2526 struct deferred_open_record *open_rec = NULL;
2527 /* Maximum wait time. */
2528 struct timeval timeout = timeval_set(OPLOCK_BREAK_TIMEOUT*2, 0);
2530 if (request_timed_out(request_time, timeout)) {
2534 open_rec = deferred_open_record_create(false, false, id);
2535 if (open_rec == NULL) {
2536 exit_server("talloc failed");
2539 ok = push_deferred_open_message_smb(req,
2545 exit_server("push_deferred_open_message_smb failed");
2549 * As this timer event is owned by req, it will
2550 * disappear if req it talloc_freed.
2552 open_rec->te = tevent_add_timer(req->sconn->ev_ctx,
2554 timeval_current_ofs(1, 0),
2555 kernel_oplock_poll_open_timer,
2557 if (open_rec->te == NULL) {
2558 exit_server("tevent_add_timer failed");
2561 DBG_DEBUG("poll request time [%s] mid [%" PRIu64 "] file_id [%s]\n",
2562 timeval_string(talloc_tos(), &request_time, false),
2564 file_id_string_tos(&id));
2567 /****************************************************************************
2568 On overwrite open ensure that the attributes match.
2569 ****************************************************************************/
2571 static bool open_match_attributes(connection_struct *conn,
2572 uint32_t old_dos_attr,
2573 uint32_t new_dos_attr,
2574 mode_t new_unx_mode,
2575 mode_t *returned_unx_mode)
2577 uint32_t noarch_old_dos_attr, noarch_new_dos_attr;
2579 noarch_old_dos_attr = (old_dos_attr & ~FILE_ATTRIBUTE_ARCHIVE);
2580 noarch_new_dos_attr = (new_dos_attr & ~FILE_ATTRIBUTE_ARCHIVE);
2582 if((noarch_old_dos_attr == 0 && noarch_new_dos_attr != 0) ||
2583 (noarch_old_dos_attr != 0 && ((noarch_old_dos_attr & noarch_new_dos_attr) == noarch_old_dos_attr))) {
2584 *returned_unx_mode = new_unx_mode;
2586 *returned_unx_mode = (mode_t)0;
2589 DEBUG(10,("open_match_attributes: old_dos_attr = 0x%x, "
2590 "new_dos_attr = 0x%x "
2591 "returned_unx_mode = 0%o\n",
2592 (unsigned int)old_dos_attr,
2593 (unsigned int)new_dos_attr,
2594 (unsigned int)*returned_unx_mode ));
2596 /* If we're mapping SYSTEM and HIDDEN ensure they match. */
2597 if (lp_map_system(SNUM(conn)) || lp_store_dos_attributes(SNUM(conn))) {
2598 if ((old_dos_attr & FILE_ATTRIBUTE_SYSTEM) &&
2599 !(new_dos_attr & FILE_ATTRIBUTE_SYSTEM)) {
2603 if (lp_map_hidden(SNUM(conn)) || lp_store_dos_attributes(SNUM(conn))) {
2604 if ((old_dos_attr & FILE_ATTRIBUTE_HIDDEN) &&
2605 !(new_dos_attr & FILE_ATTRIBUTE_HIDDEN)) {
2612 static void schedule_defer_open(struct share_mode_lock *lck,
2614 struct timeval request_time,
2615 struct smb_request *req)
2617 /* This is a relative time, added to the absolute
2618 request_time value to get the absolute timeout time.
2619 Note that if this is the second or greater time we enter
2620 this codepath for this particular request mid then
2621 request_time is left as the absolute time of the *first*
2622 time this request mid was processed. This is what allows
2623 the request to eventually time out. */
2625 struct timeval timeout;
2627 /* Normally the smbd we asked should respond within
2628 * OPLOCK_BREAK_TIMEOUT seconds regardless of whether
2629 * the client did, give twice the timeout as a safety
2630 * measure here in case the other smbd is stuck
2631 * somewhere else. */
2633 timeout = timeval_set(OPLOCK_BREAK_TIMEOUT*2, 0);
2635 if (request_timed_out(request_time, timeout)) {
2639 defer_open(lck, request_time, timeout, req, true, id);
2642 /****************************************************************************
2643 Reschedule an open call that went asynchronous.
2644 ****************************************************************************/
2646 static void schedule_async_open_timer(struct tevent_context *ev,
2647 struct tevent_timer *te,
2648 struct timeval current_time,
2651 exit_server("async open timeout");
2654 static void schedule_async_open(struct timeval request_time,
2655 struct smb_request *req)
2657 struct deferred_open_record *open_rec = NULL;
2658 struct timeval timeout = timeval_set(20, 0);
2661 if (request_timed_out(request_time, timeout)) {
2665 open_rec = deferred_open_record_create(false, true, (struct file_id){0});
2666 if (open_rec == NULL) {
2667 exit_server("deferred_open_record_create failed");
2670 ok = push_deferred_open_message_smb(req, request_time, timeout,
2671 (struct file_id){0}, open_rec);
2673 exit_server("push_deferred_open_message_smb failed");
2676 open_rec->te = tevent_add_timer(req->sconn->ev_ctx,
2678 timeval_current_ofs(20, 0),
2679 schedule_async_open_timer,
2681 if (open_rec->te == NULL) {
2682 exit_server("tevent_add_timer failed");
2686 /****************************************************************************
2687 Work out what access_mask to use from what the client sent us.
2688 ****************************************************************************/
2690 static NTSTATUS smbd_calculate_maximum_allowed_access(
2691 connection_struct *conn,
2692 const struct smb_filename *smb_fname,
2694 uint32_t *p_access_mask)
2696 struct security_descriptor *sd;
2697 uint32_t access_granted;
2700 if (!use_privs && (get_current_uid(conn) == (uid_t)0)) {
2701 *p_access_mask |= FILE_GENERIC_ALL;
2702 return NT_STATUS_OK;
2705 status = SMB_VFS_GET_NT_ACL(conn, smb_fname,
2711 if (NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
2713 * File did not exist
2715 *p_access_mask = FILE_GENERIC_ALL;
2716 return NT_STATUS_OK;
2718 if (!NT_STATUS_IS_OK(status)) {
2719 DEBUG(10,("Could not get acl on file %s: %s\n",
2720 smb_fname_str_dbg(smb_fname),
2721 nt_errstr(status)));
2722 return NT_STATUS_ACCESS_DENIED;
2726 * If we can access the path to this file, by
2727 * default we have FILE_READ_ATTRIBUTES from the
2728 * containing directory. See the section:
2729 * "Algorithm to Check Access to an Existing File"
2732 * se_file_access_check()
2733 * also takes care of owner WRITE_DAC and READ_CONTROL.
2735 status = se_file_access_check(sd,
2736 get_current_nttok(conn),
2738 (*p_access_mask & ~FILE_READ_ATTRIBUTES),
2743 if (!NT_STATUS_IS_OK(status)) {
2744 DEBUG(10, ("Access denied on file %s: "
2745 "when calculating maximum access\n",
2746 smb_fname_str_dbg(smb_fname)));
2747 return NT_STATUS_ACCESS_DENIED;
2749 *p_access_mask = (access_granted | FILE_READ_ATTRIBUTES);
2751 if (!(access_granted & DELETE_ACCESS)) {
2752 if (can_delete_file_in_directory(conn, smb_fname)) {
2753 *p_access_mask |= DELETE_ACCESS;
2757 return NT_STATUS_OK;
2760 NTSTATUS smbd_calculate_access_mask(connection_struct *conn,
2761 const struct smb_filename *smb_fname,
2763 uint32_t access_mask,
2764 uint32_t *access_mask_out)
2767 uint32_t orig_access_mask = access_mask;
2768 uint32_t rejected_share_access;
2770 if (access_mask & SEC_MASK_INVALID) {
2771 DBG_DEBUG("access_mask [%8x] contains invalid bits\n",
2773 return NT_STATUS_ACCESS_DENIED;
2777 * Convert GENERIC bits to specific bits.
2780 se_map_generic(&access_mask, &file_generic_mapping);
2782 /* Calculate MAXIMUM_ALLOWED_ACCESS if requested. */
2783 if (access_mask & MAXIMUM_ALLOWED_ACCESS) {
2785 status = smbd_calculate_maximum_allowed_access(
2786 conn, smb_fname, use_privs, &access_mask);
2788 if (!NT_STATUS_IS_OK(status)) {
2792 access_mask &= conn->share_access;
2795 rejected_share_access = access_mask & ~(conn->share_access);
2797 if (rejected_share_access) {
2798 DEBUG(10, ("smbd_calculate_access_mask: Access denied on "
2799 "file %s: rejected by share access mask[0x%08X] "
2800 "orig[0x%08X] mapped[0x%08X] reject[0x%08X]\n",
2801 smb_fname_str_dbg(smb_fname),
2803 orig_access_mask, access_mask,
2804 rejected_share_access));
2805 return NT_STATUS_ACCESS_DENIED;
2808 *access_mask_out = access_mask;
2809 return NT_STATUS_OK;
2812 /****************************************************************************
2813 Remove the deferred open entry under lock.
2814 ****************************************************************************/
2816 /****************************************************************************
2817 Return true if this is a state pointer to an asynchronous create.
2818 ****************************************************************************/
2820 bool is_deferred_open_async(const struct deferred_open_record *rec)
2822 return rec->async_open;
2825 static bool clear_ads(uint32_t create_disposition)
2829 switch (create_disposition) {
2830 case FILE_SUPERSEDE:
2831 case FILE_OVERWRITE_IF:
2832 case FILE_OVERWRITE:
2841 static int disposition_to_open_flags(uint32_t create_disposition)
2846 * Currently we're using FILE_SUPERSEDE as the same as
2847 * FILE_OVERWRITE_IF but they really are
2848 * different. FILE_SUPERSEDE deletes an existing file
2849 * (requiring delete access) then recreates it.
2852 switch (create_disposition) {
2853 case FILE_SUPERSEDE:
2854 case FILE_OVERWRITE_IF:
2856 * If file exists replace/overwrite. If file doesn't
2859 ret = O_CREAT|O_TRUNC;
2864 * If file exists open. If file doesn't exist error.
2869 case FILE_OVERWRITE:
2871 * If file exists overwrite. If file doesn't exist
2879 * If file exists error. If file doesn't exist create.
2881 ret = O_CREAT|O_EXCL;
2886 * If file exists open. If file doesn't exist create.
2894 static int calculate_open_access_flags(uint32_t access_mask,
2895 uint32_t private_flags)
2897 bool need_write, need_read;
2900 * Note that we ignore the append flag as append does not
2901 * mean the same thing under DOS and Unix.
2904 need_write = (access_mask & (FILE_WRITE_DATA | FILE_APPEND_DATA));
2909 /* DENY_DOS opens are always underlying read-write on the
2910 file handle, no matter what the requested access mask
2914 ((private_flags & NTCREATEX_OPTIONS_PRIVATE_DENY_DOS) ||
2915 access_mask & (FILE_READ_ATTRIBUTES|FILE_READ_DATA|
2916 FILE_READ_EA|FILE_EXECUTE));
2924 /****************************************************************************
2925 Open a file with a share mode. Passed in an already created files_struct *.
2926 ****************************************************************************/
2928 static NTSTATUS open_file_ntcreate(connection_struct *conn,
2929 struct smb_request *req,
2930 uint32_t access_mask, /* access bits (FILE_READ_DATA etc.) */
2931 uint32_t share_access, /* share constants (FILE_SHARE_READ etc) */
2932 uint32_t create_disposition, /* FILE_OPEN_IF etc. */
2933 uint32_t create_options, /* options such as delete on close. */
2934 uint32_t new_dos_attributes, /* attributes used for new file. */
2935 int oplock_request, /* internal Samba oplock codes. */
2936 struct smb2_lease *lease,
2937 /* Information (FILE_EXISTS etc.) */
2938 uint32_t private_flags, /* Samba specific flags. */
2942 struct smb_filename *smb_fname = fsp->fsp_name;
2945 bool file_existed = VALID_STAT(smb_fname->st);
2946 bool def_acl = False;
2947 bool posix_open = False;
2948 bool new_file_created = False;
2949 bool first_open_attempt = true;
2950 NTSTATUS fsp_open = NT_STATUS_ACCESS_DENIED;
2951 mode_t new_unx_mode = (mode_t)0;
2952 mode_t unx_mode = (mode_t)0;
2954 uint32_t existing_dos_attributes = 0;
2955 struct timeval request_time = timeval_zero();
2956 struct share_mode_lock *lck = NULL;
2957 uint32_t open_access_mask = access_mask;
2960 SMB_STRUCT_STAT saved_stat = smb_fname->st;
2961 struct timespec old_write_time;
2964 if (conn->printer) {
2966 * Printers are handled completely differently.
2967 * Most of the passed parameters are ignored.
2971 *pinfo = FILE_WAS_CREATED;
2974 DEBUG(10, ("open_file_ntcreate: printer open fname=%s\n",
2975 smb_fname_str_dbg(smb_fname)));
2978 DEBUG(0,("open_file_ntcreate: printer open without "
2979 "an SMB request!\n"));
2980 return NT_STATUS_INTERNAL_ERROR;
2983 return print_spool_open(fsp, smb_fname->base_name,
2987 if (!parent_dirname(talloc_tos(), smb_fname->base_name, &parent_dir,
2989 return NT_STATUS_NO_MEMORY;
2992 if (new_dos_attributes & FILE_FLAG_POSIX_SEMANTICS) {
2994 unx_mode = (mode_t)(new_dos_attributes & ~FILE_FLAG_POSIX_SEMANTICS);
2995 new_dos_attributes = 0;
2997 /* Windows allows a new file to be created and
2998 silently removes a FILE_ATTRIBUTE_DIRECTORY
2999 sent by the client. Do the same. */
3001 new_dos_attributes &= ~FILE_ATTRIBUTE_DIRECTORY;
3003 /* We add FILE_ATTRIBUTE_ARCHIVE to this as this mode is only used if the file is
3005 unx_mode = unix_mode(conn, new_dos_attributes | FILE_ATTRIBUTE_ARCHIVE,
3006 smb_fname, parent_dir);
3009 DEBUG(10, ("open_file_ntcreate: fname=%s, dos_attrs=0x%x "
3010 "access_mask=0x%x share_access=0x%x "
3011 "create_disposition = 0x%x create_options=0x%x "
3012 "unix mode=0%o oplock_request=%d private_flags = 0x%x\n",
3013 smb_fname_str_dbg(smb_fname), new_dos_attributes,
3014 access_mask, share_access, create_disposition,
3015 create_options, (unsigned int)unx_mode, oplock_request,
3016 (unsigned int)private_flags));
3019 /* Ensure req == NULL means INTERNAL_OPEN_ONLY */
3020 SMB_ASSERT(((oplock_request & INTERNAL_OPEN_ONLY) != 0));
3022 /* And req != NULL means no INTERNAL_OPEN_ONLY */
3023 SMB_ASSERT(((oplock_request & INTERNAL_OPEN_ONLY) == 0));
3027 * Only non-internal opens can be deferred at all
3031 struct deferred_open_record *open_rec;
3032 if (get_deferred_open_message_state(req,
3035 /* Remember the absolute time of the original
3036 request with this mid. We'll use it later to
3037 see if this has timed out. */
3039 /* If it was an async create retry, the file
3042 if (is_deferred_open_async(open_rec)) {
3043 SET_STAT_INVALID(smb_fname->st);
3044 file_existed = false;
3047 /* Ensure we don't reprocess this message. */
3048 remove_deferred_open_message_smb(req->xconn, req->mid);
3050 first_open_attempt = false;
3055 new_dos_attributes &= SAMBA_ATTRIBUTES_MASK;
3058 * Only use stored DOS attributes for checks
3059 * against requested attributes (below via
3060 * open_match_attributes()), cf bug #11992
3061 * for details. -slow
3065 status = SMB_VFS_GET_DOS_ATTRIBUTES(conn, smb_fname, &attr);
3066 if (NT_STATUS_IS_OK(status)) {
3067 existing_dos_attributes = attr;
3072 /* ignore any oplock requests if oplocks are disabled */
3073 if (!lp_oplocks(SNUM(conn)) ||
3074 IS_VETO_OPLOCK_PATH(conn, smb_fname->base_name)) {
3075 /* Mask off everything except the private Samba bits. */
3076 oplock_request &= SAMBA_PRIVATE_OPLOCK_MASK;
3079 /* this is for OS/2 long file names - say we don't support them */
3080 if (req != NULL && !req->posix_pathnames &&
3081 strstr(smb_fname->base_name,".+,;=[].")) {
3082 /* OS/2 Workplace shell fix may be main code stream in a later
3084 DEBUG(5,("open_file_ntcreate: OS/2 long filenames are not "
3086 if (use_nt_status()) {
3087 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3089 return NT_STATUS_DOS(ERRDOS, ERRcannotopen);
3092 switch( create_disposition ) {
3094 /* If file exists open. If file doesn't exist error. */
3095 if (!file_existed) {
3096 DEBUG(5,("open_file_ntcreate: FILE_OPEN "
3097 "requested for file %s and file "
3099 smb_fname_str_dbg(smb_fname)));
3101 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3105 case FILE_OVERWRITE:
3106 /* If file exists overwrite. If file doesn't exist
3108 if (!file_existed) {
3109 DEBUG(5,("open_file_ntcreate: FILE_OVERWRITE "
3110 "requested for file %s and file "
3112 smb_fname_str_dbg(smb_fname) ));
3114 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3119 /* If file exists error. If file doesn't exist
3122 DEBUG(5,("open_file_ntcreate: FILE_CREATE "
3123 "requested for file %s and file "
3124 "already exists.\n",
3125 smb_fname_str_dbg(smb_fname)));
3126 if (S_ISDIR(smb_fname->st.st_ex_mode)) {
3131 return map_nt_error_from_unix(errno);
3135 case FILE_SUPERSEDE:
3136 case FILE_OVERWRITE_IF:
3140 return NT_STATUS_INVALID_PARAMETER;
3143 flags2 = disposition_to_open_flags(create_disposition);
3145 /* We only care about matching attributes on file exists and
3148 if (!posix_open && file_existed &&
3149 ((create_disposition == FILE_OVERWRITE) ||
3150 (create_disposition == FILE_OVERWRITE_IF))) {
3151 if (!open_match_attributes(conn, existing_dos_attributes,
3153 unx_mode, &new_unx_mode)) {
3154 DEBUG(5,("open_file_ntcreate: attributes mismatch "
3155 "for file %s (%x %x) (0%o, 0%o)\n",
3156 smb_fname_str_dbg(smb_fname),
3157 existing_dos_attributes,
3159 (unsigned int)smb_fname->st.st_ex_mode,
3160 (unsigned int)unx_mode ));
3162 return NT_STATUS_ACCESS_DENIED;
3166 status = smbd_calculate_access_mask(conn, smb_fname,
3170 if (!NT_STATUS_IS_OK(status)) {
3171 DEBUG(10, ("open_file_ntcreate: smbd_calculate_access_mask "
3172 "on file %s returned %s\n",
3173 smb_fname_str_dbg(smb_fname), nt_errstr(status)));
3177 open_access_mask = access_mask;
3179 if (flags2 & O_TRUNC) {
3180 open_access_mask |= FILE_WRITE_DATA; /* This will cause oplock breaks. */
3183 DEBUG(10, ("open_file_ntcreate: fname=%s, after mapping "
3184 "access_mask=0x%x\n", smb_fname_str_dbg(smb_fname),
3188 * Note that we ignore the append flag as append does not
3189 * mean the same thing under DOS and Unix.
3192 flags = calculate_open_access_flags(access_mask, private_flags);
3195 * Currently we only look at FILE_WRITE_THROUGH for create options.
3199 if ((create_options & FILE_WRITE_THROUGH) && lp_strict_sync(SNUM(conn))) {
3204 if (posix_open && (access_mask & FILE_APPEND_DATA)) {
3208 if (!posix_open && !CAN_WRITE(conn)) {
3210 * We should really return a permission denied error if either
3211 * O_CREAT or O_TRUNC are set, but for compatibility with
3212 * older versions of Samba we just AND them out.
3214 flags2 &= ~(O_CREAT|O_TRUNC);
3218 * With kernel oplocks the open breaking an oplock
3219 * blocks until the oplock holder has given up the
3220 * oplock or closed the file. We prevent this by always
3221 * trying to open the file with O_NONBLOCK (see "man
3224 * If a process that doesn't use the smbd open files
3225 * database or communication methods holds a kernel
3226 * oplock we must periodically poll for available open
3229 flags2 |= O_NONBLOCK;
3232 * Ensure we can't write on a read-only share or file.
3235 if (flags != O_RDONLY && file_existed &&
3236 (!CAN_WRITE(conn) || IS_DOS_READONLY(existing_dos_attributes))) {
3237 DEBUG(5,("open_file_ntcreate: write access requested for "
3238 "file %s on read only %s\n",
3239 smb_fname_str_dbg(smb_fname),
3240 !CAN_WRITE(conn) ? "share" : "file" ));
3242 return NT_STATUS_ACCESS_DENIED;
3245 fsp->file_id = vfs_file_id_from_sbuf(conn, &smb_fname->st);
3246 fsp->share_access = share_access;
3247 fsp->fh->private_options = private_flags;
3248 fsp->access_mask = open_access_mask; /* We change this to the
3249 * requested access_mask after
3250 * the open is done. */
3252 fsp->posix_flags |= FSP_POSIX_FLAGS_ALL;
3255 if (timeval_is_zero(&request_time)) {
3256 request_time = fsp->open_time;
3259 if ((create_options & FILE_DELETE_ON_CLOSE) &&
3260 (flags2 & O_CREAT) &&
3262 /* Delete on close semantics for new files. */
3263 status = can_set_delete_on_close(fsp,
3264 new_dos_attributes);
3265 if (!NT_STATUS_IS_OK(status)) {
3272 * Ensure we pay attention to default ACLs on directories if required.
3275 if ((flags2 & O_CREAT) && lp_inherit_acls(SNUM(conn)) &&
3276 (def_acl = directory_has_default_acl(conn, parent_dir))) {
3277 unx_mode = (0777 & lp_create_mask(SNUM(conn)));
3280 DEBUG(4,("calling open_file with flags=0x%X flags2=0x%X mode=0%o, "
3281 "access_mask = 0x%x, open_access_mask = 0x%x\n",
3282 (unsigned int)flags, (unsigned int)flags2,
3283 (unsigned int)unx_mode, (unsigned int)access_mask,
3284 (unsigned int)open_access_mask));
3286 fsp_open = open_file(fsp, conn, req, parent_dir,
3287 flags|flags2, unx_mode, access_mask,
3288 open_access_mask, &new_file_created);
3290 if (NT_STATUS_EQUAL(fsp_open, NT_STATUS_NETWORK_BUSY)) {
3294 * This handles the kernel oplock case:
3296 * the file has an active kernel oplock and the open() returned
3297 * EWOULDBLOCK/EAGAIN which maps to NETWORK_BUSY.
3299 * "Samba locking.tdb oplocks" are handled below after acquiring
3300 * the sharemode lock with get_share_mode_lock().
3302 if (file_existed && S_ISFIFO(fsp->fsp_name->st.st_ex_mode)) {
3303 DEBUG(10, ("FIFO busy\n"));
3304 return NT_STATUS_NETWORK_BUSY;
3307 DEBUG(10, ("Internal open busy\n"));
3308 return NT_STATUS_NETWORK_BUSY;
3312 * From here on we assume this is an oplock break triggered
3315 lck = get_existing_share_mode_lock(talloc_tos(), fsp->file_id);
3318 * No oplock from Samba around. Set up a poll every 1
3319 * second to retry a non-blocking open until the time
3322 setup_kernel_oplock_poll_open(request_time,
3325 DBG_DEBUG("No Samba oplock around after EWOULDBLOCK. "
3326 "Retrying with poll\n");
3327 return NT_STATUS_SHARING_VIOLATION;
3330 if (!validate_oplock_types(lck)) {
3331 smb_panic("validate_oplock_types failed");
3334 delay = delay_for_oplock(fsp, 0, lease, lck, false,
3336 first_open_attempt);
3338 schedule_defer_open(lck, fsp->file_id, request_time,
3341 DEBUG(10, ("Sent oplock break request to kernel "
3342 "oplock holder\n"));
3343 return NT_STATUS_SHARING_VIOLATION;
3347 * No oplock from Samba around. Set up a poll every 1
3348 * second to retry a non-blocking open until the time
3351 setup_kernel_oplock_poll_open(request_time, req, fsp->file_id);
3354 DBG_DEBUG("No Samba oplock around after EWOULDBLOCK. "
3355 "Retrying with poll\n");
3356 return NT_STATUS_SHARING_VIOLATION;
3359 if (!NT_STATUS_IS_OK(fsp_open)) {
3360 if (NT_STATUS_EQUAL(fsp_open, NT_STATUS_RETRY)) {
3361 schedule_async_open(request_time, req);
3366 if (new_file_created) {
3368 * As we atomically create using O_CREAT|O_EXCL,
3369 * then if new_file_created is true, then
3370 * file_existed *MUST* have been false (even
3371 * if the file was previously detected as being
3374 file_existed = false;
3377 if (file_existed && !check_same_dev_ino(&saved_stat, &smb_fname->st)) {
3379 * The file did exist, but some other (local or NFS)
3380 * process either renamed/unlinked and re-created the
3381 * file with different dev/ino after we walked the path,
3382 * but before we did the open. We could retry the
3383 * open but it's a rare enough case it's easier to
3384 * just fail the open to prevent creating any problems
3385 * in the open file db having the wrong dev/ino key.
3388 DBG_WARNING("file %s - dev/ino mismatch. "
3389 "Old (dev=%ju, ino=%ju). "
3390 "New (dev=%ju, ino=%ju). Failing open "
3391 "with NT_STATUS_ACCESS_DENIED.\n",
3392 smb_fname_str_dbg(smb_fname),
3393 (uintmax_t)saved_stat.st_ex_dev,
3394 (uintmax_t)saved_stat.st_ex_ino,
3395 (uintmax_t)smb_fname->st.st_ex_dev,
3396 (uintmax_t)smb_fname->st.st_ex_ino);
3397 return NT_STATUS_ACCESS_DENIED;
3400 old_write_time = smb_fname->st.st_ex_mtime;
3403 * Deal with the race condition where two smbd's detect the
3404 * file doesn't exist and do the create at the same time. One
3405 * of them will win and set a share mode, the other (ie. this
3406 * one) should check if the requested share mode for this
3407 * create is allowed.
3411 * Now the file exists and fsp is successfully opened,
3412 * fsp->dev and fsp->inode are valid and should replace the
3413 * dev=0,inode=0 from a non existent file. Spotted by
3414 * Nadav Danieli <nadavd@exanet.com>. JRA.
3419 lck = get_share_mode_lock(talloc_tos(), id,
3421 smb_fname, &old_write_time);
3424 DEBUG(0, ("open_file_ntcreate: Could not get share "
3425 "mode lock for %s\n",
3426 smb_fname_str_dbg(smb_fname)));
3428 return NT_STATUS_SHARING_VIOLATION;
3431 /* Get the types we need to examine. */
3432 if (!validate_oplock_types(lck)) {
3433 smb_panic("validate_oplock_types failed");
3436 if (has_delete_on_close(lck, fsp->name_hash)) {
3439 return NT_STATUS_DELETE_PENDING;
3442 status = open_mode_check(conn, lck,
3443 access_mask, share_access);
3445 if (NT_STATUS_EQUAL(status, NT_STATUS_SHARING_VIOLATION) ||
3446 (lck->data->num_share_modes > 0)) {
3448 * This comes from ancient times out of open_mode_check. I
3449 * have no clue whether this is still necessary. I can't think
3450 * of a case where this would actually matter further down in
3451 * this function. I leave it here for further investigation
3454 file_existed = true;
3459 * Handle oplocks, deferring the request if delay_for_oplock()
3460 * triggered a break message and we have to wait for the break
3464 bool sharing_violation = NT_STATUS_EQUAL(
3465 status, NT_STATUS_SHARING_VIOLATION);
3467 delay = delay_for_oplock(fsp, oplock_request, lease, lck,
3470 first_open_attempt);
3472 schedule_defer_open(lck, fsp->file_id,
3476 return NT_STATUS_SHARING_VIOLATION;
3480 if (!NT_STATUS_IS_OK(status)) {
3481 uint32_t can_access_mask;
3482 bool can_access = True;
3484 SMB_ASSERT(NT_STATUS_EQUAL(status, NT_STATUS_SHARING_VIOLATION));
3487 * This next line is a subtlety we need for
3488 * MS-Access. If a file open will fail due to share
3489 * permissions and also for security (access) reasons,
3490 * we need to return the access failed error, not the
3491 * share error. We can't open the file due to kernel
3492 * oplock deadlock (it's possible we failed above on
3493 * the open_mode_check()) so use a userspace check.
3496 if (flags & O_RDWR) {
3497 can_access_mask = FILE_READ_DATA|FILE_WRITE_DATA;
3498 } else if (flags & O_WRONLY) {
3499 can_access_mask = FILE_WRITE_DATA;
3501 can_access_mask = FILE_READ_DATA;
3504 if (((can_access_mask & FILE_WRITE_DATA) &&
3505 !CAN_WRITE(conn)) ||
3506 !NT_STATUS_IS_OK(smbd_check_access_rights(conn,
3509 can_access_mask))) {
3514 * If we're returning a share violation, ensure we
3515 * cope with the braindead 1 second delay (SMB1 only).
3518 if (!(oplock_request & INTERNAL_OPEN_ONLY) &&
3519 !conn->sconn->using_smb2 &&
3520 lp_defer_sharing_violations()) {
3521 struct timeval timeout;
3524 /* this is a hack to speed up torture tests
3526 timeout_usecs = lp_parm_int(SNUM(conn),
3527 "smbd","sharedelay",
3528 SHARING_VIOLATION_USEC_WAIT);
3530 /* This is a relative time, added to the absolute
3531 request_time value to get the absolute timeout time.
3532 Note that if this is the second or greater time we enter
3533 this codepath for this particular request mid then
3534 request_time is left as the absolute time of the *first*
3535 time this request mid was processed. This is what allows
3536 the request to eventually time out. */
3538 timeout = timeval_set(0, timeout_usecs);
3540 if (!request_timed_out(request_time, timeout)) {
3541 defer_open(lck, request_time, timeout, req,
3550 * We have detected a sharing violation here
3551 * so return the correct error code
3553 status = NT_STATUS_SHARING_VIOLATION;
3555 status = NT_STATUS_ACCESS_DENIED;
3560 /* Should we atomically (to the client at least) truncate ? */
3561 if ((!new_file_created) &&
3562 (flags2 & O_TRUNC) &&
3563 (!S_ISFIFO(fsp->fsp_name->st.st_ex_mode))) {
3566 ret = SMB_VFS_FTRUNCATE(fsp, 0);
3568 status = map_nt_error_from_unix(errno);
3573 notify_fname(fsp->conn, NOTIFY_ACTION_MODIFIED,
3574 FILE_NOTIFY_CHANGE_SIZE
3575 | FILE_NOTIFY_CHANGE_ATTRIBUTES,
3576 fsp->fsp_name->base_name);
3580 * We have the share entry *locked*.....
3583 /* Delete streams if create_disposition requires it */
3584 if (!new_file_created && clear_ads(create_disposition) &&
3585 !is_ntfs_stream_smb_fname(smb_fname)) {
3586 status = delete_all_streams(conn, smb_fname);
3587 if (!NT_STATUS_IS_OK(status)) {
3594 /* note that we ignore failure for the following. It is
3595 basically a hack for NFS, and NFS will never set one of
3596 these only read them. Nobody but Samba can ever set a deny
3597 mode and we have already checked our more authoritative
3598 locking database for permission to set this deny mode. If
3599 the kernel refuses the operations then the kernel is wrong.
3600 note that GPFS supports it as well - jmcd */
3602 if (fsp->fh->fd != -1 && lp_kernel_share_modes(SNUM(conn))) {
3605 * Beware: streams implementing VFS modules may
3606 * implement streams in a way that fsp will have the
3607 * basefile open in the fsp fd, so lacking a distinct
3608 * fd for the stream kernel_flock will apply on the
3609 * basefile which is wrong. The actual check is
3610 * deffered to the VFS module implementing the
3611 * kernel_flock call.
3613 ret_flock = SMB_VFS_KERNEL_FLOCK(fsp, share_access, access_mask);
3614 if(ret_flock == -1 ){
3619 return NT_STATUS_SHARING_VIOLATION;
3622 fsp->kernel_share_modes_taken = true;
3626 * At this point onwards, we can guarantee that the share entry
3627 * is locked, whether we created the file or not, and that the
3628 * deny mode is compatible with all current opens.
3632 * According to Samba4, SEC_FILE_READ_ATTRIBUTE is always granted,
3633 * but we don't have to store this - just ignore it on access check.
3635 if (conn->sconn->using_smb2) {
3637 * SMB2 doesn't return it (according to Microsoft tests).
3638 * Test Case: TestSuite_ScenarioNo009GrantedAccessTestS0
3639 * File created with access = 0x7 (Read, Write, Delete)
3640 * Query Info on file returns 0x87 (Read, Write, Delete, Read Attributes)
3642 fsp->access_mask = access_mask;
3644 /* But SMB1 does. */
3645 fsp->access_mask = access_mask | FILE_READ_ATTRIBUTES;
3650 * stat opens on existing files don't get oplocks.
3651 * They can get leases.
3653 * Note that we check for stat open on the *open_access_mask*,
3654 * i.e. the access mask we actually used to do the open,
3655 * not the one the client asked for (which is in
3656 * fsp->access_mask). This is due to the fact that
3657 * FILE_OVERWRITE and FILE_OVERWRITE_IF add in O_TRUNC,
3658 * which adds FILE_WRITE_DATA to open_access_mask.
3660 if (is_stat_open(open_access_mask) && lease == NULL) {
3661 oplock_request = NO_OPLOCK;
3665 if (new_file_created) {
3666 info = FILE_WAS_CREATED;
3668 if (flags2 & O_TRUNC) {
3669 info = FILE_WAS_OVERWRITTEN;
3671 info = FILE_WAS_OPENED;
3680 * Setup the oplock info in both the shared memory and
3683 status = grant_fsp_oplock_type(req, fsp, lck, oplock_request, lease);
3684 if (!NT_STATUS_IS_OK(status)) {
3690 /* Handle strange delete on close create semantics. */
3691 if (create_options & FILE_DELETE_ON_CLOSE) {
3692 if (!new_file_created) {
3693 status = can_set_delete_on_close(fsp,
3694 existing_dos_attributes);
3696 if (!NT_STATUS_IS_OK(status)) {
3697 /* Remember to delete the mode we just added. */
3698 del_share_mode(lck, fsp);
3704 /* Note that here we set the *initial* delete on close flag,
3705 not the regular one. The magic gets handled in close. */
3706 fsp->initial_delete_on_close = True;
3709 if (info == FILE_WAS_CREATED) {
3710 smb_fname->st.st_ex_iflags &= ~ST_EX_IFLAG_CALCULATED_ITIME;
3713 if (info != FILE_WAS_OPENED) {
3714 /* Overwritten files should be initially set as archive */
3715 if ((info == FILE_WAS_OVERWRITTEN && lp_map_archive(SNUM(conn))) ||
3716 lp_store_dos_attributes(SNUM(conn))) {
3718 if (file_set_dosmode(conn, smb_fname,
3719 new_dos_attributes | FILE_ATTRIBUTE_ARCHIVE,
3720 parent_dir, true) == 0) {
3721 unx_mode = smb_fname->st.st_ex_mode;
3727 /* Determine sparse flag. */
3729 /* POSIX opens are sparse by default. */
3730 fsp->is_sparse = true;
3732 fsp->is_sparse = (file_existed &&
3733 (existing_dos_attributes & FILE_ATTRIBUTE_SPARSE));
3737 * Take care of inherited ACLs on created files - if default ACL not
3741 if (!posix_open && new_file_created && !def_acl) {
3742 if (unx_mode != smb_fname->st.st_ex_mode) {
3743 int ret = SMB_VFS_FCHMOD(fsp, unx_mode);
3745 DBG_INFO("failed to reset "
3746 "attributes of file %s to 0%o\n",
3747 smb_fname_str_dbg(smb_fname),
3748 (unsigned int)unx_mode);
3752 } else if (new_unx_mode) {
3754 * We only get here in the case of:
3756 * a). Not a POSIX open.
3757 * b). File already existed.
3758 * c). File was overwritten.
3759 * d). Requested DOS attributes didn't match
3760 * the DOS attributes on the existing file.
3762 * In that case new_unx_mode has been set
3763 * equal to the calculated mode (including
3764 * possible inheritance of the mode from the
3765 * containing directory).
3767 * Note this mode was calculated with the
3768 * DOS attribute FILE_ATTRIBUTE_ARCHIVE added,
3769 * so the mode change here is suitable for
3770 * an overwritten file.
3773 if (new_unx_mode != smb_fname->st.st_ex_mode) {
3774 int ret = SMB_VFS_FCHMOD(fsp, new_unx_mode);
3776 DBG_INFO("failed to reset "
3777 "attributes of file %s to 0%o\n",
3778 smb_fname_str_dbg(smb_fname),
3779 (unsigned int)new_unx_mode);
3786 * Deal with other opens having a modified write time.
3788 struct timespec write_time = get_share_mode_write_time(lck);
3790 if (!null_timespec(write_time)) {
3791 update_stat_ex_mtime(&fsp->fsp_name->st, write_time);
3797 return NT_STATUS_OK;
3800 static NTSTATUS mkdir_internal(connection_struct *conn,
3801 struct smb_filename *smb_dname,
3802 uint32_t file_attributes)
3805 char *parent_dir = NULL;
3807 bool posix_open = false;
3808 bool need_re_stat = false;
3809 uint32_t access_mask = SEC_DIR_ADD_SUBDIR;
3811 if (!CAN_WRITE(conn) || (access_mask & ~(conn->share_access))) {
3812 DEBUG(5,("mkdir_internal: failing share access "
3813 "%s\n", lp_servicename(talloc_tos(), SNUM(conn))));
3814 return NT_STATUS_ACCESS_DENIED;
3817 if (!parent_dirname(talloc_tos(), smb_dname->base_name, &parent_dir,
3819 return NT_STATUS_NO_MEMORY;
3822 if (file_attributes & FILE_FLAG_POSIX_SEMANTICS) {
3824 mode = (mode_t)(file_attributes & ~FILE_FLAG_POSIX_SEMANTICS);
3826 mode = unix_mode(conn, FILE_ATTRIBUTE_DIRECTORY, smb_dname, parent_dir);
3829 status = check_parent_access(conn,
3832 if(!NT_STATUS_IS_OK(status)) {
3833 DEBUG(5,("mkdir_internal: check_parent_access "
3834 "on directory %s for path %s returned %s\n",
3836 smb_dname->base_name,
3837 nt_errstr(status) ));
3841 if (SMB_VFS_MKDIR(conn, smb_dname, mode) != 0) {
3842 return map_nt_error_from_unix(errno);
3845 /* Ensure we're checking for a symlink here.... */
3846 /* We don't want to get caught by a symlink racer. */
3848 if (SMB_VFS_LSTAT(conn, smb_dname) == -1) {
3849 DEBUG(2, ("Could not stat directory '%s' just created: %s\n",
3850 smb_fname_str_dbg(smb_dname), strerror(errno)));
3851 return map_nt_error_from_unix(errno);
3854 if (!S_ISDIR(smb_dname->st.st_ex_mode)) {
3855 DEBUG(0, ("Directory '%s' just created is not a directory !\n",
3856 smb_fname_str_dbg(smb_dname)));
3857 return NT_STATUS_NOT_A_DIRECTORY;
3860 smb_dname->st.st_ex_iflags &= ~ST_EX_IFLAG_CALCULATED_ITIME;
3862 if (lp_store_dos_attributes(SNUM(conn))) {
3864 file_set_dosmode(conn, smb_dname,
3865 file_attributes | FILE_ATTRIBUTE_DIRECTORY,
3870 if (lp_inherit_permissions(SNUM(conn))) {
3871 inherit_access_posix_acl(conn, parent_dir,
3873 need_re_stat = true;
3878 * Check if high bits should have been set,
3879 * then (if bits are missing): add them.
3880 * Consider bits automagically set by UNIX, i.e. SGID bit from parent
3883 if ((mode & ~(S_IRWXU|S_IRWXG|S_IRWXO)) &&
3884 (mode & ~smb_dname->st.st_ex_mode)) {
3885 SMB_VFS_CHMOD(conn, smb_dname,
3886 (smb_dname->st.st_ex_mode |
3887 (mode & ~smb_dname->st.st_ex_mode)));
3888 need_re_stat = true;
3892 /* Change the owner if required. */
3893 if (lp_inherit_owner(SNUM(conn)) != INHERIT_OWNER_NO) {
3894 change_dir_owner_to_parent(conn, parent_dir,
3897 need_re_stat = true;
3901 if (SMB_VFS_LSTAT(conn, smb_dname) == -1) {
3902 DEBUG(2, ("Could not stat directory '%s' just created: %s\n",
3903 smb_fname_str_dbg(smb_dname), strerror(errno)));
3904 return map_nt_error_from_unix(errno);
3908 notify_fname(conn, NOTIFY_ACTION_ADDED, FILE_NOTIFY_CHANGE_DIR_NAME,
3909 smb_dname->base_name);
3911 return NT_STATUS_OK;
3914 /****************************************************************************
3915 Open a directory from an NT SMB call.
3916 ****************************************************************************/
3918 static NTSTATUS open_directory(connection_struct *conn,
3919 struct smb_request *req,
3920 struct smb_filename *smb_dname,
3921 uint32_t access_mask,
3922 uint32_t share_access,
3923 uint32_t create_disposition,
3924 uint32_t create_options,
3925 uint32_t file_attributes,
3927 files_struct **result)
3929 files_struct *fsp = NULL;
3930 bool dir_existed = VALID_STAT(smb_dname->st) ? True : False;
3931 struct share_mode_lock *lck = NULL;
3933 struct timespec mtimespec;
3937 if (is_ntfs_stream_smb_fname(smb_dname)) {
3938 DEBUG(2, ("open_directory: %s is a stream name!\n",
3939 smb_fname_str_dbg(smb_dname)));
3940 return NT_STATUS_NOT_A_DIRECTORY;
3943 if (!(file_attributes & FILE_FLAG_POSIX_SEMANTICS)) {
3944 /* Ensure we have a directory attribute. */
3945 file_attributes |= FILE_ATTRIBUTE_DIRECTORY;
3948 DEBUG(5,("open_directory: opening directory %s, access_mask = 0x%x, "
3949 "share_access = 0x%x create_options = 0x%x, "
3950 "create_disposition = 0x%x, file_attributes = 0x%x\n",
3951 smb_fname_str_dbg(smb_dname),
3952 (unsigned int)access_mask,
3953 (unsigned int)share_access,
3954 (unsigned int)create_options,
3955 (unsigned int)create_disposition,
3956 (unsigned int)file_attributes));
3958 status = smbd_calculate_access_mask(conn, smb_dname, false,
3959 access_mask, &access_mask);
3960 if (!NT_STATUS_IS_OK(status)) {
3961 DEBUG(10, ("open_directory: smbd_calculate_access_mask "
3962 "on file %s returned %s\n",
3963 smb_fname_str_dbg(smb_dname),
3964 nt_errstr(status)));
3968 if ((access_mask & SEC_FLAG_SYSTEM_SECURITY) &&
3969 !security_token_has_privilege(get_current_nttok(conn),
3970 SEC_PRIV_SECURITY)) {
3971 DEBUG(10, ("open_directory: open on %s "
3972 "failed - SEC_FLAG_SYSTEM_SECURITY denied.\n",
3973 smb_fname_str_dbg(smb_dname)));
3974 return NT_STATUS_PRIVILEGE_NOT_HELD;
3977 switch( create_disposition ) {
3981 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3984 info = FILE_WAS_OPENED;
3989 /* If directory exists error. If directory doesn't
3993 status = NT_STATUS_OBJECT_NAME_COLLISION;
3994 DEBUG(2, ("open_directory: unable to create "
3995 "%s. Error was %s\n",
3996 smb_fname_str_dbg(smb_dname),
3997 nt_errstr(status)));
4001 status = mkdir_internal(conn, smb_dname,
4004 if (!NT_STATUS_IS_OK(status)) {
4005 DEBUG(2, ("open_directory: unable to create "
4006 "%s. Error was %s\n",
4007 smb_fname_str_dbg(smb_dname),
4008 nt_errstr(status)));
4012 info = FILE_WAS_CREATED;
4017 * If directory exists open. If directory doesn't
4022 status = NT_STATUS_OK;
4023 info = FILE_WAS_OPENED;
4025 status = mkdir_internal(conn, smb_dname,
4028 if (NT_STATUS_IS_OK(status)) {
4029 info = FILE_WAS_CREATED;
4031 /* Cope with create race. */
4032 if (!NT_STATUS_EQUAL(status,
4033 NT_STATUS_OBJECT_NAME_COLLISION)) {
4034 DEBUG(2, ("open_directory: unable to create "
4035 "%s. Error was %s\n",
4036 smb_fname_str_dbg(smb_dname),
4037 nt_errstr(status)));
4042 * If mkdir_internal() returned
4043 * NT_STATUS_OBJECT_NAME_COLLISION
4044 * we still must lstat the path.
4047 if (SMB_VFS_LSTAT(conn, smb_dname)
4049 DEBUG(2, ("Could not stat "
4050 "directory '%s' just "
4055 return map_nt_error_from_unix(
4059 info = FILE_WAS_OPENED;
4065 case FILE_SUPERSEDE:
4066 case FILE_OVERWRITE:
4067 case FILE_OVERWRITE_IF:
4069 DEBUG(5,("open_directory: invalid create_disposition "
4070 "0x%x for directory %s\n",
4071 (unsigned int)create_disposition,
4072 smb_fname_str_dbg(smb_dname)));
4073 return NT_STATUS_INVALID_PARAMETER;
4076 if(!S_ISDIR(smb_dname->st.st_ex_mode)) {
4077 DEBUG(5,("open_directory: %s is not a directory !\n",
4078 smb_fname_str_dbg(smb_dname)));
4079 return NT_STATUS_NOT_A_DIRECTORY;
4082 if (info == FILE_WAS_OPENED) {
4083 status = smbd_check_access_rights(conn,
4087 if (!NT_STATUS_IS_OK(status)) {
4088 DEBUG(10, ("open_directory: smbd_check_access_rights on "
4089 "file %s failed with %s\n",
4090 smb_fname_str_dbg(smb_dname),
4091 nt_errstr(status)));
4096 status = file_new(req, conn, &fsp);
4097 if(!NT_STATUS_IS_OK(status)) {
4102 * Setup the files_struct for it.
4105 fsp->file_id = vfs_file_id_from_sbuf(conn, &smb_dname->st);
4106 fsp->vuid = req ? req->vuid : UID_FIELD_INVALID;
4107 fsp->file_pid = req ? req->smbpid : 0;
4108 fsp->can_lock = False;
4109 fsp->can_read = False;
4110 fsp->can_write = False;
4112 fsp->share_access = share_access;
4113 fsp->fh->private_options = 0;
4115 * According to Samba4, SEC_FILE_READ_ATTRIBUTE is always granted,
4117 fsp->access_mask = access_mask | FILE_READ_ATTRIBUTES;
4118 fsp->print_file = NULL;
4119 fsp->modified = False;
4120 fsp->oplock_type = NO_OPLOCK;
4121 fsp->sent_oplock_break = NO_BREAK_SENT;
4122 fsp->is_directory = True;
4123 if (file_attributes & FILE_FLAG_POSIX_SEMANTICS) {
4124 fsp->posix_flags |= FSP_POSIX_FLAGS_ALL;
4126 status = fsp_set_smb_fname(fsp, smb_dname);
4127 if (!NT_STATUS_IS_OK(status)) {
4128 file_free(req, fsp);
4132 /* Don't store old timestamps for directory
4133 handles in the internal database. We don't
4134 update them in there if new objects
4135 are creaded in the directory. Currently
4136 we only update timestamps on file writes.
4139 ZERO_STRUCT(mtimespec);
4142 status = fd_open(conn, fsp, O_RDONLY|O_DIRECTORY, 0);
4144 /* POSIX allows us to open a directory with O_RDONLY. */
4145 status = fd_open(conn, fsp, O_RDONLY, 0);
4147 if (!NT_STATUS_IS_OK(status)) {
4148 DBG_INFO("Could not open fd for "
4150 smb_fname_str_dbg(smb_dname),
4152 file_free(req, fsp);
4156 status = vfs_stat_fsp(fsp);
4157 if (!NT_STATUS_IS_OK(status)) {
4159 file_free(req, fsp);
4163 if(!S_ISDIR(fsp->fsp_name->st.st_ex_mode)) {
4164 DEBUG(5,("open_directory: %s is not a directory !\n",
4165 smb_fname_str_dbg(smb_dname)));
4167 file_free(req, fsp);
4168 return NT_STATUS_NOT_A_DIRECTORY;
4171 /* Ensure there was no race condition. We need to check
4172 * dev/inode but not permissions, as these can change
4174 if (!check_same_dev_ino(&smb_dname->st, &fsp->fsp_name->st)) {
4175 DEBUG(5,("open_directory: stat struct differs for "
4177 smb_fname_str_dbg(smb_dname)));
4179 file_free(req, fsp);
4180 return NT_STATUS_ACCESS_DENIED;
4183 lck = get_share_mode_lock(talloc_tos(), fsp->file_id,
4184 conn->connectpath, smb_dname,
4188 DEBUG(0, ("open_directory: Could not get share mode lock for "
4189 "%s\n", smb_fname_str_dbg(smb_dname)));
4191 file_free(req, fsp);
4192 return NT_STATUS_SHARING_VIOLATION;
4195 if (has_delete_on_close(lck, fsp->name_hash)) {
4198 file_free(req, fsp);
4199 return NT_STATUS_DELETE_PENDING;
4202 status = open_mode_check(conn, lck,
4203 access_mask, share_access);
4205 if (!NT_STATUS_IS_OK(status)) {
4208 file_free(req, fsp);
4212 ok = set_share_mode(
4215 get_current_uid(conn),
4223 file_free(req, fsp);
4224 return NT_STATUS_NO_MEMORY;
4227 /* For directories the delete on close bit at open time seems
4228 always to be honored on close... See test 19 in Samba4 BASE-DELETE. */
4229 if (create_options & FILE_DELETE_ON_CLOSE) {
4230 status = can_set_delete_on_close(fsp, 0);
4231 if (!NT_STATUS_IS_OK(status) && !NT_STATUS_EQUAL(status, NT_STATUS_DIRECTORY_NOT_EMPTY)) {
4232 del_share_mode(lck, fsp);
4235 file_free(req, fsp);
4239 if (NT_STATUS_IS_OK(status)) {
4240 /* Note that here we set the *initial* delete on close flag,
4241 not the regular one. The magic gets handled in close. */
4242 fsp->initial_delete_on_close = True;
4248 * Deal with other opens having a modified write time. Is this
4249 * possible for directories?
4251 struct timespec write_time = get_share_mode_write_time(lck);
4253 if (!null_timespec(write_time)) {
4254 update_stat_ex_mtime(&fsp->fsp_name->st, write_time);
4265 return NT_STATUS_OK;
4268 NTSTATUS create_directory(connection_struct *conn, struct smb_request *req,
4269 struct smb_filename *smb_dname)
4274 status = SMB_VFS_CREATE_FILE(
4277 0, /* root_dir_fid */
4278 smb_dname, /* fname */
4279 FILE_READ_ATTRIBUTES, /* access_mask */
4280 FILE_SHARE_NONE, /* share_access */
4281 FILE_CREATE, /* create_disposition*/
4282 FILE_DIRECTORY_FILE, /* create_options */
4283 FILE_ATTRIBUTE_DIRECTORY, /* file_attributes */
4284 0, /* oplock_request */
4286 0, /* allocation_size */
4287 0, /* private_flags */
4292 NULL, NULL); /* create context */
4294 if (NT_STATUS_IS_OK(status)) {
4295 close_file(req, fsp, NORMAL_CLOSE);
4301 /****************************************************************************
4302 Receive notification that one of our open files has been renamed by another
4304 ****************************************************************************/
4306 void msg_file_was_renamed(struct messaging_context *msg_ctx,
4309 struct server_id src,
4312 struct file_rename_message *msg = NULL;
4313 enum ndr_err_code ndr_err;
4315 struct smb_filename *smb_fname = NULL;
4316 struct smbd_server_connection *sconn =
4317 talloc_get_type_abort(private_data,
4318 struct smbd_server_connection);
4320 msg = talloc(talloc_tos(), struct file_rename_message);
4322 DBG_WARNING("talloc failed\n");
4326 ndr_err = ndr_pull_struct_blob_all(
4330 (ndr_pull_flags_fn_t)ndr_pull_file_rename_message);
4331 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
4332 DBG_DEBUG("ndr_pull_oplock_break_message failed: %s\n",
4333 ndr_errstr(ndr_err));
4336 if (DEBUGLEVEL >= 10) {
4337 struct server_id_buf buf;
4338 DBG_DEBUG("Got rename message from %s\n",
4339 server_id_str_buf(src, &buf));
4340 NDR_PRINT_DEBUG(file_rename_message, msg);
4343 /* stream_name must always be NULL if there is no stream. */
4344 if ((msg->stream_name != NULL) && (msg->stream_name[0] == '\0')) {
4345 msg->stream_name = NULL;
4348 smb_fname = synthetic_smb_fname(
4349 msg, msg->base_name, msg->stream_name, NULL, 0);
4350 if (smb_fname == NULL) {
4351 DBG_DEBUG("synthetic_smb_fname failed\n");
4355 fsp = file_find_dif(sconn, msg->id, msg->share_file_id);
4357 DBG_DEBUG("fsp not found\n");
4361 if (strcmp(fsp->conn->connectpath, msg->servicepath) == 0) {
4363 DBG_DEBUG("renaming file %s from %s -> %s\n",
4366 smb_fname_str_dbg(smb_fname));
4367 status = fsp_set_smb_fname(fsp, smb_fname);
4368 if (!NT_STATUS_IS_OK(status)) {
4369 DBG_DEBUG("fsp_set_smb_fname failed: %s\n",
4375 * Now we have the complete path we can work out if
4376 * this is actually within this share and adjust
4377 * newname accordingly.
4379 DBG_DEBUG("share mismatch (sharepath %s not sharepath %s) "
4380 "%s from %s -> %s\n",
4381 fsp->conn->connectpath,
4385 smb_fname_str_dbg(smb_fname));
4392 * If a main file is opened for delete, all streams need to be checked for
4393 * !FILE_SHARE_DELETE. Do this by opening with DELETE_ACCESS.
4394 * If that works, delete them all by setting the delete on close and close.
4397 static NTSTATUS open_streams_for_delete(connection_struct *conn,
4398 const struct smb_filename *smb_fname)
4400 struct stream_struct *stream_info = NULL;
4401 files_struct **streams = NULL;
4403 unsigned int num_streams = 0;
4404 TALLOC_CTX *frame = talloc_stackframe();
4407 status = vfs_streaminfo(conn, NULL, smb_fname, talloc_tos(),
4408 &num_streams, &stream_info);
4410 if (NT_STATUS_EQUAL(status, NT_STATUS_NOT_IMPLEMENTED)
4411 || NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
4412 DEBUG(10, ("no streams around\n"));
4414 return NT_STATUS_OK;
4417 if (!NT_STATUS_IS_OK(status)) {
4418 DEBUG(10, ("vfs_streaminfo failed: %s\n",
4419 nt_errstr(status)));
4423 DEBUG(10, ("open_streams_for_delete found %d streams\n",
4426 if (num_streams == 0) {
4428 return NT_STATUS_OK;
4431 streams = talloc_array(talloc_tos(), files_struct *, num_streams);
4432 if (streams == NULL) {
4433 DEBUG(0, ("talloc failed\n"));
4434 status = NT_STATUS_NO_MEMORY;
4438 for (i=0; i<num_streams; i++) {
4439 struct smb_filename *smb_fname_cp;
4441 if (strequal(stream_info[i].name, "::$DATA")) {
4446 smb_fname_cp = synthetic_smb_fname(talloc_tos(),
4447 smb_fname->base_name,
4448 stream_info[i].name,
4451 ~SMB_FILENAME_POSIX_PATH));
4452 if (smb_fname_cp == NULL) {
4453 status = NT_STATUS_NO_MEMORY;
4457 if (SMB_VFS_STAT(conn, smb_fname_cp) == -1) {
4458 DEBUG(10, ("Unable to stat stream: %s\n",
4459 smb_fname_str_dbg(smb_fname_cp)));
4462 status = SMB_VFS_CREATE_FILE(
4465 0, /* root_dir_fid */
4466 smb_fname_cp, /* fname */
4467 DELETE_ACCESS, /* access_mask */
4468 (FILE_SHARE_READ | /* share_access */
4469 FILE_SHARE_WRITE | FILE_SHARE_DELETE),
4470 FILE_OPEN, /* create_disposition*/
4471 0, /* create_options */
4472 FILE_ATTRIBUTE_NORMAL, /* file_attributes */
4473 0, /* oplock_request */
4475 0, /* allocation_size */
4476 NTCREATEX_OPTIONS_PRIVATE_STREAM_DELETE, /* private_flags */
4479 &streams[i], /* result */
4481 NULL, NULL); /* create context */
4483 if (!NT_STATUS_IS_OK(status)) {
4484 DEBUG(10, ("Could not open stream %s: %s\n",
4485 smb_fname_str_dbg(smb_fname_cp),
4486 nt_errstr(status)));
4488 TALLOC_FREE(smb_fname_cp);
4491 TALLOC_FREE(smb_fname_cp);
4495 * don't touch the variable "status" beyond this point :-)
4498 for (i -= 1 ; i >= 0; i--) {
4499 if (streams[i] == NULL) {
4503 DEBUG(10, ("Closing stream # %d, %s\n", i,
4504 fsp_str_dbg(streams[i])));
4505 close_file(NULL, streams[i], NORMAL_CLOSE);
4513 /*********************************************************************
4514 Create a default ACL by inheriting from the parent. If no inheritance
4515 from the parent available, don't set anything. This will leave the actual
4516 permissions the new file or directory already got from the filesystem
4517 as the NT ACL when read.
4518 *********************************************************************/
4520 static NTSTATUS inherit_new_acl(files_struct *fsp)
4522 TALLOC_CTX *frame = talloc_stackframe();
4523 char *parent_name = NULL;
4524 struct security_descriptor *parent_desc = NULL;
4525 NTSTATUS status = NT_STATUS_OK;
4526 struct security_descriptor *psd = NULL;
4527 const struct dom_sid *owner_sid = NULL;
4528 const struct dom_sid *group_sid = NULL;
4529 uint32_t security_info_sent = (SECINFO_OWNER | SECINFO_GROUP | SECINFO_DACL);
4530 struct security_token *token = fsp->conn->session_info->security_token;
4531 bool inherit_owner =
4532 (lp_inherit_owner(SNUM(fsp->conn)) == INHERIT_OWNER_WINDOWS_AND_UNIX);
4533 bool inheritable_components = false;
4534 bool try_builtin_administrators = false;
4535 const struct dom_sid *BA_U_sid = NULL;
4536 const struct dom_sid *BA_G_sid = NULL;
4537 bool try_system = false;
4538 const struct dom_sid *SY_U_sid = NULL;
4539 const struct dom_sid *SY_G_sid = NULL;
4541 struct smb_filename *parent_smb_fname = NULL;
4543 if (!parent_dirname(frame, fsp->fsp_name->base_name, &parent_name, NULL)) {
4545 return NT_STATUS_NO_MEMORY;
4547 parent_smb_fname = synthetic_smb_fname(talloc_tos(),
4551 fsp->fsp_name->flags);
4553 if (parent_smb_fname == NULL) {
4555 return NT_STATUS_NO_MEMORY;
4558 status = SMB_VFS_GET_NT_ACL(fsp->conn,
4560 (SECINFO_OWNER | SECINFO_GROUP | SECINFO_DACL),
4563 if (!NT_STATUS_IS_OK(status)) {
4568 inheritable_components = sd_has_inheritable_components(parent_desc,
4571 if (!inheritable_components && !inherit_owner) {
4573 /* Nothing to inherit and not setting owner. */
4574 return NT_STATUS_OK;
4577 /* Create an inherited descriptor from the parent. */
4579 if (DEBUGLEVEL >= 10) {
4580 DEBUG(10,("inherit_new_acl: parent acl for %s is:\n",
4581 fsp_str_dbg(fsp) ));
4582 NDR_PRINT_DEBUG(security_descriptor, parent_desc);
4585 /* Inherit from parent descriptor if "inherit owner" set. */
4586 if (inherit_owner) {
4587 owner_sid = parent_desc->owner_sid;
4588 group_sid = parent_desc->group_sid;
4591 if (owner_sid == NULL) {
4592 if (security_token_has_builtin_administrators(token)) {
4593 try_builtin_administrators = true;
4594 } else if (security_token_is_system(token)) {
4595 try_builtin_administrators = true;
4600 if (group_sid == NULL &&
4601 token->num_sids == PRIMARY_GROUP_SID_INDEX)
4603 if (security_token_is_system(token)) {
4604 try_builtin_administrators = true;
4609 if (try_builtin_administrators) {
4614 ok = sids_to_unixids(&global_sid_Builtin_Administrators, 1, &ids);
4618 BA_U_sid = &global_sid_Builtin_Administrators;
4619 BA_G_sid = &global_sid_Builtin_Administrators;
4622 BA_U_sid = &global_sid_Builtin_Administrators;
4625 BA_G_sid = &global_sid_Builtin_Administrators;
4638 ok = sids_to_unixids(&global_sid_System, 1, &ids);
4642 SY_U_sid = &global_sid_System;
4643 SY_G_sid = &global_sid_System;
4646 SY_U_sid = &global_sid_System;
4649 SY_G_sid = &global_sid_System;
4657 if (owner_sid == NULL) {
4658 owner_sid = BA_U_sid;
4661 if (owner_sid == NULL) {
4662 owner_sid = SY_U_sid;
4665 if (group_sid == NULL) {
4666 group_sid = SY_G_sid;
4669 if (try_system && group_sid == NULL) {
4670 group_sid = BA_G_sid;
4673 if (owner_sid == NULL) {
4674 owner_sid = &token->sids[PRIMARY_USER_SID_INDEX];
4676 if (group_sid == NULL) {
4677 if (token->num_sids == PRIMARY_GROUP_SID_INDEX) {
4678 group_sid = &token->sids[PRIMARY_USER_SID_INDEX];
4680 group_sid = &token->sids[PRIMARY_GROUP_SID_INDEX];
4684 status = se_create_child_secdesc(frame,
4691 if (!NT_STATUS_IS_OK(status)) {
4696 /* If inheritable_components == false,
4697 se_create_child_secdesc()
4698 creates a security descriptor with a NULL dacl
4699 entry, but with SEC_DESC_DACL_PRESENT. We need
4700 to remove that flag. */
4702 if (!inheritable_components) {
4703 security_info_sent &= ~SECINFO_DACL;
4704 psd->type &= ~SEC_DESC_DACL_PRESENT;
4707 if (DEBUGLEVEL >= 10) {
4708 DEBUG(10,("inherit_new_acl: child acl for %s is:\n",
4709 fsp_str_dbg(fsp) ));
4710 NDR_PRINT_DEBUG(security_descriptor, psd);
4713 if (inherit_owner) {
4714 /* We need to be root to force this. */
4717 status = SMB_VFS_FSET_NT_ACL(fsp,
4720 if (inherit_owner) {
4728 * If we already have a lease, it must match the new file id. [MS-SMB2]
4729 * 3.3.5.9.8 speaks about INVALID_PARAMETER if an already used lease key is
4730 * used for a different file name.
4733 struct lease_match_state {
4734 /* Input parameters. */
4735 TALLOC_CTX *mem_ctx;
4736 const char *servicepath;
4737 const struct smb_filename *fname;
4740 /* Return parameters. */
4741 uint32_t num_file_ids;
4742 struct file_id *ids;
4743 NTSTATUS match_status;
4746 /*************************************************************
4747 File doesn't exist but this lease key+guid is already in use.
4749 This is only allowable in the dynamic share case where the
4750 service path must be different.
4752 There is a small race condition here in the multi-connection
4753 case where a client sends two create calls on different connections,
4754 where the file doesn't exist and one smbd creates the leases_db
4755 entry first, but this will get fixed by the multichannel cleanup
4756 when all identical client_guids get handled by a single smbd.
4757 **************************************************************/
4759 static void lease_match_parser_new_file(
4761 const struct leases_db_file *files,
4762 struct lease_match_state *state)
4766 for (i = 0; i < num_files; i++) {
4767 const struct leases_db_file *f = &files[i];
4768 if (strequal(state->servicepath, f->servicepath)) {
4769 state->match_status = NT_STATUS_INVALID_PARAMETER;
4774 /* Dynamic share case. Break leases on all other files. */
4775 state->match_status = leases_db_copy_file_ids(state->mem_ctx,
4779 if (!NT_STATUS_IS_OK(state->match_status)) {
4783 state->num_file_ids = num_files;
4784 state->match_status = NT_STATUS_OPLOCK_NOT_GRANTED;
4788 static void lease_match_parser(
4790 const struct leases_db_file *files,
4793 struct lease_match_state *state =
4794 (struct lease_match_state *)private_data;
4797 if (!state->file_existed) {
4799 * Deal with name mismatch or
4800 * possible dynamic share case separately
4801 * to make code clearer.
4803 lease_match_parser_new_file(num_files,
4810 state->match_status = NT_STATUS_OK;
4812 for (i = 0; i < num_files; i++) {
4813 const struct leases_db_file *f = &files[i];
4815 /* Everything should be the same. */
4816 if (!file_id_equal(&state->id, &f->id)) {
4817 /* This should catch all dynamic share cases. */
4818 state->match_status = NT_STATUS_OPLOCK_NOT_GRANTED;
4821 if (!strequal(f->servicepath, state->servicepath)) {
4822 state->match_status = NT_STATUS_INVALID_PARAMETER;
4825 if (!strequal(f->base_name, state->fname->base_name)) {
4826 state->match_status = NT_STATUS_INVALID_PARAMETER;
4829 if (!strequal(f->stream_name, state->fname->stream_name)) {
4830 state->match_status = NT_STATUS_INVALID_PARAMETER;
4835 if (NT_STATUS_IS_OK(state->match_status)) {
4837 * Common case - just opening another handle on a
4838 * file on a non-dynamic share.
4843 if (NT_STATUS_EQUAL(state->match_status, NT_STATUS_INVALID_PARAMETER)) {
4844 /* Mismatched path. Error back to client. */
4849 * File id mismatch. Dynamic share case NT_STATUS_OPLOCK_NOT_GRANTED.
4850 * Don't allow leases.
4853 state->match_status = leases_db_copy_file_ids(state->mem_ctx,
4857 if (!NT_STATUS_IS_OK(state->match_status)) {
4861 state->num_file_ids = num_files;
4862 state->match_status = NT_STATUS_OPLOCK_NOT_GRANTED;
4866 static NTSTATUS lease_match(connection_struct *conn,
4867 struct smb_request *req,
4868 struct smb2_lease_key *lease_key,
4869 const char *servicepath,
4870 const struct smb_filename *fname,
4871 uint16_t *p_version,
4874 struct smbd_server_connection *sconn = req->sconn;
4875 TALLOC_CTX *tos = talloc_tos();
4876 struct lease_match_state state = {
4878 .servicepath = servicepath,
4880 .match_status = NT_STATUS_OK
4885 state.file_existed = VALID_STAT(fname->st);
4886 if (state.file_existed) {
4887 state.id = vfs_file_id_from_sbuf(conn, &fname->st);
4890 status = leases_db_parse(&sconn->client->connections->smb2.client.guid,
4891 lease_key, lease_match_parser, &state);
4892 if (!NT_STATUS_IS_OK(status)) {
4894 * Not found or error means okay: We can make the lease pass
4896 return NT_STATUS_OK;
4898 if (!NT_STATUS_EQUAL(state.match_status, NT_STATUS_OPLOCK_NOT_GRANTED)) {
4900 * Anything but NT_STATUS_OPLOCK_NOT_GRANTED, let the caller
4903 return state.match_status;
4906 /* We have to break all existing leases. */
4907 for (i = 0; i < state.num_file_ids; i++) {
4908 struct share_mode_lock *lck;
4909 struct share_mode_data *d;
4910 struct share_mode_entry *lease_entry = NULL;
4913 if (file_id_equal(&state.ids[i], &state.id)) {
4914 /* Don't need to break our own file. */
4918 lck = get_existing_share_mode_lock(talloc_tos(), state.ids[i]);
4920 /* Race condition - file already closed. */
4924 for (j=0; j<d->num_share_modes; j++) {
4925 struct share_mode_entry *e = &d->share_modes[j];
4926 uint32_t e_lease_type = get_lease_type(d, e);
4928 if (share_mode_stale_pid(d, j)) {
4932 if (e->op_type == LEASE_OPLOCK) {
4933 if (!smb2_lease_key_equal(&e->lease_key,
4940 if (e_lease_type == SMB2_LEASE_NONE) {
4944 send_break_message(conn->sconn->msg_ctx, &d->id, e,
4948 * Windows 7 and 8 lease clients
4949 * are broken in that they will not
4950 * respond to lease break requests
4951 * whilst waiting for an outstanding
4952 * open request on that lease handle
4953 * on the same TCP connection, due
4954 * to holding an internal inode lock.
4956 * This means we can't reschedule
4957 * ourselves here, but must return
4962 * Send the breaks and then return
4963 * SMB2_LEASE_NONE in the lease handle
4964 * to cause them to acknowledge the
4965 * lease break. Consultation with
4966 * Microsoft engineering confirmed
4967 * this approach is safe.
4972 if (lease_entry != NULL) {
4973 status = leases_db_get(
4974 &lease_entry->client_guid,
4975 &lease_entry->lease_key,
4977 NULL, /* current_state */
4978 NULL, /* breaking */
4979 NULL, /* breaking_to_requested */
4980 NULL, /* breaking_to_required */
4981 p_version, /* lease_version */
4982 p_epoch); /* epoch */
4983 if (!NT_STATUS_IS_OK(status)) {
4984 DBG_WARNING("Could not find version/epoch: "
4993 * Ensure we don't grant anything more so we
4996 return NT_STATUS_OPLOCK_NOT_GRANTED;
5000 * Wrapper around open_file_ntcreate and open_directory
5003 static NTSTATUS create_file_unixpath(connection_struct *conn,
5004 struct smb_request *req,
5005 struct smb_filename *smb_fname,
5006 uint32_t access_mask,
5007 uint32_t share_access,
5008 uint32_t create_disposition,
5009 uint32_t create_options,
5010 uint32_t file_attributes,
5011 uint32_t oplock_request,
5012 struct smb2_lease *lease,
5013 uint64_t allocation_size,
5014 uint32_t private_flags,
5015 struct security_descriptor *sd,
5016 struct ea_list *ea_list,
5018 files_struct **result,
5021 int info = FILE_WAS_OPENED;
5022 files_struct *base_fsp = NULL;
5023 files_struct *fsp = NULL;
5026 DBG_DEBUG("create_file_unixpath: access_mask = 0x%x "
5027 "file_attributes = 0x%x, share_access = 0x%x, "
5028 "create_disposition = 0x%x create_options = 0x%x "
5029 "oplock_request = 0x%x private_flags = 0x%x "
5030 "ea_list = %p, sd = %p, "
5032 (unsigned int)access_mask,
5033 (unsigned int)file_attributes,
5034 (unsigned int)share_access,
5035 (unsigned int)create_disposition,
5036 (unsigned int)create_options,
5037 (unsigned int)oplock_request,
5038 (unsigned int)private_flags,
5039 ea_list, sd, smb_fname_str_dbg(smb_fname));
5041 if (create_options & FILE_OPEN_BY_FILE_ID) {
5042 status = NT_STATUS_NOT_SUPPORTED;
5046 if (create_options & NTCREATEX_OPTIONS_INVALID_PARAM_MASK) {
5047 status = NT_STATUS_INVALID_PARAMETER;
5052 oplock_request |= INTERNAL_OPEN_ONLY;
5055 if (lease != NULL) {
5056 uint16_t epoch = lease->lease_epoch;
5057 uint16_t version = lease->lease_version;
5060 DBG_WARNING("Got lease on internal open\n");
5061 status = NT_STATUS_INTERNAL_ERROR;
5065 status = lease_match(conn,
5072 if (NT_STATUS_EQUAL(status, NT_STATUS_OPLOCK_NOT_GRANTED)) {
5073 /* Dynamic share file. No leases and update epoch... */
5074 lease->lease_state = SMB2_LEASE_NONE;
5075 lease->lease_epoch = epoch;
5076 lease->lease_version = version;
5077 } else if (!NT_STATUS_IS_OK(status)) {
5082 if ((conn->fs_capabilities & FILE_NAMED_STREAMS)
5083 && (access_mask & DELETE_ACCESS)
5084 && !is_ntfs_stream_smb_fname(smb_fname)) {
5086 * We can't open a file with DELETE access if any of the
5087 * streams is open without FILE_SHARE_DELETE
5089 status = open_streams_for_delete(conn, smb_fname);
5091 if (!NT_STATUS_IS_OK(status)) {
5096 if ((access_mask & SEC_FLAG_SYSTEM_SECURITY) &&
5097 !security_token_has_privilege(get_current_nttok(conn),
5098 SEC_PRIV_SECURITY)) {
5099 DEBUG(10, ("create_file_unixpath: open on %s "
5100 "failed - SEC_FLAG_SYSTEM_SECURITY denied.\n",
5101 smb_fname_str_dbg(smb_fname)));
5102 status = NT_STATUS_PRIVILEGE_NOT_HELD;
5107 * Files or directories can't be opened DELETE_ON_CLOSE without
5109 * BUG: https://bugzilla.samba.org/show_bug.cgi?id=13358
5111 if (create_options & FILE_DELETE_ON_CLOSE) {
5112 if ((access_mask & DELETE_ACCESS) == 0) {
5113 status = NT_STATUS_INVALID_PARAMETER;
5118 if ((conn->fs_capabilities & FILE_NAMED_STREAMS)
5119 && is_ntfs_stream_smb_fname(smb_fname)
5120 && (!(private_flags & NTCREATEX_OPTIONS_PRIVATE_STREAM_DELETE))) {
5121 uint32_t base_create_disposition;
5122 struct smb_filename *smb_fname_base = NULL;
5123 uint32_t base_privflags;
5125 if (create_options & FILE_DIRECTORY_FILE) {
5126 status = NT_STATUS_NOT_A_DIRECTORY;
5130 switch (create_disposition) {
5132 base_create_disposition = FILE_OPEN;
5135 base_create_disposition = FILE_OPEN_IF;
5139 /* Create an smb_filename with stream_name == NULL. */
5140 smb_fname_base = synthetic_smb_fname(talloc_tos(),
5141 smb_fname->base_name,
5145 if (smb_fname_base == NULL) {
5146 status = NT_STATUS_NO_MEMORY;
5150 if (SMB_VFS_STAT(conn, smb_fname_base) == -1) {
5151 DEBUG(10, ("Unable to stat stream: %s\n",
5152 smb_fname_str_dbg(smb_fname_base)));
5155 * https://bugzilla.samba.org/show_bug.cgi?id=10229
5156 * We need to check if the requested access mask
5157 * could be used to open the underlying file (if
5158 * it existed), as we're passing in zero for the
5159 * access mask to the base filename.
5161 status = check_base_file_access(conn,
5165 if (!NT_STATUS_IS_OK(status)) {
5166 DEBUG(10, ("Permission check "
5167 "for base %s failed: "
5168 "%s\n", smb_fname->base_name,
5169 nt_errstr(status)));
5174 base_privflags = NTCREATEX_OPTIONS_PRIVATE_STREAM_BASEOPEN;
5176 /* Open the base file. */
5177 status = create_file_unixpath(conn, NULL, smb_fname_base, 0,
5180 | FILE_SHARE_DELETE,
5181 base_create_disposition,
5186 TALLOC_FREE(smb_fname_base);
5188 if (!NT_STATUS_IS_OK(status)) {
5189 DEBUG(10, ("create_file_unixpath for base %s failed: "
5190 "%s\n", smb_fname->base_name,
5191 nt_errstr(status)));
5194 /* we don't need the low level fd */
5199 * If it's a request for a directory open, deal with it separately.
5202 if (create_options & FILE_DIRECTORY_FILE) {
5204 if (create_options & FILE_NON_DIRECTORY_FILE) {
5205 status = NT_STATUS_INVALID_PARAMETER;
5209 /* Can't open a temp directory. IFS kit test. */
5210 if (!(file_attributes & FILE_FLAG_POSIX_SEMANTICS) &&
5211 (file_attributes & FILE_ATTRIBUTE_TEMPORARY)) {
5212 status = NT_STATUS_INVALID_PARAMETER;
5217 * We will get a create directory here if the Win32
5218 * app specified a security descriptor in the
5219 * CreateDirectory() call.
5223 status = open_directory(
5224 conn, req, smb_fname, access_mask, share_access,
5225 create_disposition, create_options, file_attributes,
5230 * Ordinary file case.
5233 status = file_new(req, conn, &fsp);
5234 if(!NT_STATUS_IS_OK(status)) {
5238 status = fsp_set_smb_fname(fsp, smb_fname);
5239 if (!NT_STATUS_IS_OK(status)) {
5245 * We're opening the stream element of a
5246 * base_fsp we already opened. Set up the
5249 fsp->base_fsp = base_fsp;
5252 if (allocation_size) {
5253 fsp->initial_allocation_size = smb_roundup(fsp->conn,
5257 status = open_file_ntcreate(conn,
5270 if(!NT_STATUS_IS_OK(status)) {
5271 file_free(req, fsp);
5275 if (NT_STATUS_EQUAL(status, NT_STATUS_FILE_IS_A_DIRECTORY)) {
5277 /* A stream open never opens a directory */
5280 status = NT_STATUS_FILE_IS_A_DIRECTORY;
5285 * Fail the open if it was explicitly a non-directory
5289 if (create_options & FILE_NON_DIRECTORY_FILE) {
5290 status = NT_STATUS_FILE_IS_A_DIRECTORY;
5295 status = open_directory(
5296 conn, req, smb_fname, access_mask,
5297 share_access, create_disposition,
5298 create_options, file_attributes,
5303 if (!NT_STATUS_IS_OK(status)) {
5307 fsp->base_fsp = base_fsp;
5309 if ((ea_list != NULL) &&
5310 ((info == FILE_WAS_CREATED) || (info == FILE_WAS_OVERWRITTEN))) {
5311 status = set_ea(conn, fsp, fsp->fsp_name, ea_list);
5312 if (!NT_STATUS_IS_OK(status)) {
5317 if (!fsp->is_directory && S_ISDIR(fsp->fsp_name->st.st_ex_mode)) {
5318 status = NT_STATUS_ACCESS_DENIED;
5322 /* Save the requested allocation size. */
5323 if ((info == FILE_WAS_CREATED) || (info == FILE_WAS_OVERWRITTEN)) {
5324 if ((allocation_size > fsp->fsp_name->st.st_ex_size)
5325 && !(fsp->is_directory))
5327 fsp->initial_allocation_size = smb_roundup(
5328 fsp->conn, allocation_size);
5329 if (vfs_allocate_file_space(
5330 fsp, fsp->initial_allocation_size) == -1) {
5331 status = NT_STATUS_DISK_FULL;
5335 fsp->initial_allocation_size = smb_roundup(
5336 fsp->conn, (uint64_t)fsp->fsp_name->st.st_ex_size);
5339 fsp->initial_allocation_size = 0;
5342 if ((info == FILE_WAS_CREATED) && lp_nt_acl_support(SNUM(conn)) &&
5343 fsp->base_fsp == NULL) {
5346 * According to the MS documentation, the only time the security
5347 * descriptor is applied to the opened file is iff we *created* the
5348 * file; an existing file stays the same.
5350 * Also, it seems (from observation) that you can open the file with
5351 * any access mask but you can still write the sd. We need to override
5352 * the granted access before we call set_sd
5353 * Patch for bug #2242 from Tom Lackemann <cessnatomny@yahoo.com>.
5356 uint32_t sec_info_sent;
5357 uint32_t saved_access_mask = fsp->access_mask;
5359 sec_info_sent = get_sec_info(sd);
5361 fsp->access_mask = FILE_GENERIC_ALL;
5363 if (sec_info_sent & (SECINFO_OWNER|
5367 status = set_sd(fsp, sd, sec_info_sent);
5370 fsp->access_mask = saved_access_mask;
5372 if (!NT_STATUS_IS_OK(status)) {
5375 } else if (lp_inherit_acls(SNUM(conn))) {
5376 /* Inherit from parent. Errors here are not fatal. */
5377 status = inherit_new_acl(fsp);
5378 if (!NT_STATUS_IS_OK(status)) {
5379 DEBUG(10,("inherit_new_acl: failed for %s with %s\n",
5381 nt_errstr(status) ));
5386 if ((conn->fs_capabilities & FILE_FILE_COMPRESSION)
5387 && (create_options & FILE_NO_COMPRESSION)
5388 && (info == FILE_WAS_CREATED)) {
5389 status = SMB_VFS_SET_COMPRESSION(conn, fsp, fsp,
5390 COMPRESSION_FORMAT_NONE);
5391 if (!NT_STATUS_IS_OK(status)) {
5392 DEBUG(1, ("failed to disable compression: %s\n",
5393 nt_errstr(status)));
5397 DEBUG(10, ("create_file_unixpath: info=%d\n", info));
5400 if (pinfo != NULL) {
5404 smb_fname->st = fsp->fsp_name->st;
5406 return NT_STATUS_OK;
5409 DEBUG(10, ("create_file_unixpath: %s\n", nt_errstr(status)));
5412 if (base_fsp && fsp->base_fsp == base_fsp) {
5414 * The close_file below will close
5419 close_file(req, fsp, ERROR_CLOSE);
5422 if (base_fsp != NULL) {
5423 close_file(req, base_fsp, ERROR_CLOSE);
5430 * Calculate the full path name given a relative fid.
5432 static NTSTATUS get_relative_fid_filename(
5433 connection_struct *conn,
5434 struct smb_request *req,
5435 uint16_t root_dir_fid,
5436 const struct smb_filename *smb_fname,
5437 struct smb_filename **smb_fname_out)
5439 files_struct *dir_fsp;
5440 char *parent_fname = NULL;
5441 char *new_base_name = NULL;
5442 uint32_t ucf_flags = ucf_flags_from_smb_request(req);
5445 if (root_dir_fid == 0 || !smb_fname) {
5446 status = NT_STATUS_INTERNAL_ERROR;
5450 dir_fsp = file_fsp(req, root_dir_fid);
5452 if (dir_fsp == NULL) {
5453 status = NT_STATUS_INVALID_HANDLE;
5457 if (is_ntfs_stream_smb_fname(dir_fsp->fsp_name)) {
5458 status = NT_STATUS_INVALID_HANDLE;
5462 if (!dir_fsp->is_directory) {
5465 * Check to see if this is a mac fork of some kind.
5468 if ((conn->fs_capabilities & FILE_NAMED_STREAMS) &&
5469 is_ntfs_stream_smb_fname(smb_fname)) {
5470 status = NT_STATUS_OBJECT_PATH_NOT_FOUND;
5475 we need to handle the case when we get a
5476 relative open relative to a file and the
5477 pathname is blank - this is a reopen!
5478 (hint from demyn plantenberg)
5481 status = NT_STATUS_INVALID_HANDLE;
5485 if (ISDOT(dir_fsp->fsp_name->base_name)) {
5487 * We're at the toplevel dir, the final file name
5488 * must not contain ./, as this is filtered out
5489 * normally by srvstr_get_path and unix_convert
5490 * explicitly rejects paths containing ./.
5492 parent_fname = talloc_strdup(talloc_tos(), "");
5493 if (parent_fname == NULL) {
5494 status = NT_STATUS_NO_MEMORY;
5498 size_t dir_name_len = strlen(dir_fsp->fsp_name->base_name);
5501 * Copy in the base directory name.
5504 parent_fname = talloc_array(talloc_tos(), char,
5506 if (parent_fname == NULL) {
5507 status = NT_STATUS_NO_MEMORY;
5510 memcpy(parent_fname, dir_fsp->fsp_name->base_name,
5514 * Ensure it ends in a '/'.
5515 * We used TALLOC_SIZE +2 to add space for the '/'.
5519 && (parent_fname[dir_name_len-1] != '\\')
5520 && (parent_fname[dir_name_len-1] != '/')) {
5521 parent_fname[dir_name_len] = '/';
5522 parent_fname[dir_name_len+1] = '\0';
5526 new_base_name = talloc_asprintf(talloc_tos(), "%s%s", parent_fname,
5527 smb_fname->base_name);
5528 if (new_base_name == NULL) {
5529 status = NT_STATUS_NO_MEMORY;
5533 status = filename_convert(req,
5540 if (!NT_STATUS_IS_OK(status)) {
5545 TALLOC_FREE(parent_fname);
5546 TALLOC_FREE(new_base_name);
5550 NTSTATUS create_file_default(connection_struct *conn,
5551 struct smb_request *req,
5552 uint16_t root_dir_fid,
5553 struct smb_filename *smb_fname,
5554 uint32_t access_mask,
5555 uint32_t share_access,
5556 uint32_t create_disposition,
5557 uint32_t create_options,
5558 uint32_t file_attributes,
5559 uint32_t oplock_request,
5560 struct smb2_lease *lease,
5561 uint64_t allocation_size,
5562 uint32_t private_flags,
5563 struct security_descriptor *sd,
5564 struct ea_list *ea_list,
5565 files_struct **result,
5567 const struct smb2_create_blobs *in_context_blobs,
5568 struct smb2_create_blobs *out_context_blobs)
5570 int info = FILE_WAS_OPENED;
5571 files_struct *fsp = NULL;
5573 bool stream_name = false;
5575 DBG_DEBUG("create_file: access_mask = 0x%x "
5576 "file_attributes = 0x%x, share_access = 0x%x, "
5577 "create_disposition = 0x%x create_options = 0x%x "
5578 "oplock_request = 0x%x "
5579 "private_flags = 0x%x "
5580 "root_dir_fid = 0x%x, ea_list = %p, sd = %p, "
5582 (unsigned int)access_mask,
5583 (unsigned int)file_attributes,
5584 (unsigned int)share_access,
5585 (unsigned int)create_disposition,
5586 (unsigned int)create_options,
5587 (unsigned int)oplock_request,
5588 (unsigned int)private_flags,
5589 (unsigned int)root_dir_fid,
5590 ea_list, sd, smb_fname_str_dbg(smb_fname));
5593 * Calculate the filename from the root_dir_if if necessary.
5596 if (root_dir_fid != 0) {
5597 struct smb_filename *smb_fname_out = NULL;
5598 status = get_relative_fid_filename(conn, req, root_dir_fid,
5599 smb_fname, &smb_fname_out);
5600 if (!NT_STATUS_IS_OK(status)) {
5603 smb_fname = smb_fname_out;
5607 * Check to see if this is a mac fork of some kind.
5610 stream_name = is_ntfs_stream_smb_fname(smb_fname);
5612 enum FAKE_FILE_TYPE fake_file_type;
5614 fake_file_type = is_fake_file(smb_fname);
5616 if (fake_file_type != FAKE_FILE_TYPE_NONE) {
5619 * Here we go! support for changing the disk quotas
5622 * We need to fake up to open this MAGIC QUOTA file
5623 * and return a valid FID.
5625 * w2k close this file directly after openening xp
5626 * also tries a QUERY_FILE_INFO on the file and then
5629 status = open_fake_file(req, conn, req->vuid,
5630 fake_file_type, smb_fname,
5632 if (!NT_STATUS_IS_OK(status)) {
5636 ZERO_STRUCT(smb_fname->st);
5640 if (!(conn->fs_capabilities & FILE_NAMED_STREAMS)) {
5641 status = NT_STATUS_OBJECT_NAME_NOT_FOUND;
5646 if (is_ntfs_default_stream_smb_fname(smb_fname)) {
5648 smb_fname->stream_name = NULL;
5649 /* We have to handle this error here. */
5650 if (create_options & FILE_DIRECTORY_FILE) {
5651 status = NT_STATUS_NOT_A_DIRECTORY;
5654 if (req != NULL && req->posix_pathnames) {
5655 ret = SMB_VFS_LSTAT(conn, smb_fname);
5657 ret = SMB_VFS_STAT(conn, smb_fname);
5660 if (ret == 0 && VALID_STAT_OF_DIR(smb_fname->st)) {
5661 status = NT_STATUS_FILE_IS_A_DIRECTORY;
5666 status = create_file_unixpath(
5667 conn, req, smb_fname, access_mask, share_access,
5668 create_disposition, create_options, file_attributes,
5669 oplock_request, lease, allocation_size, private_flags,
5673 if (!NT_STATUS_IS_OK(status)) {
5678 DEBUG(10, ("create_file: info=%d\n", info));
5681 if (pinfo != NULL) {
5684 return NT_STATUS_OK;
5687 DEBUG(10, ("create_file: %s\n", nt_errstr(status)));
5690 close_file(req, fsp, ERROR_CLOSE);