2 Unix SMB/CIFS implementation.
3 file opening and share modes
4 Copyright (C) Andrew Tridgell 1992-1998
5 Copyright (C) Jeremy Allison 2001-2004
6 Copyright (C) Volker Lendecke 2005
7 Copyright (C) Ralph Boehme 2017
9 This program is free software; you can redistribute it and/or modify
10 it under the terms of the GNU General Public License as published by
11 the Free Software Foundation; either version 3 of the License, or
12 (at your option) any later version.
14 This program is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 GNU General Public License for more details.
19 You should have received a copy of the GNU General Public License
20 along with this program. If not, see <http://www.gnu.org/licenses/>.
24 #include "system/filesys.h"
25 #include "lib/util/server_id.h"
27 #include "smbd/smbd.h"
28 #include "smbd/globals.h"
29 #include "fake_file.h"
30 #include "../libcli/security/security.h"
31 #include "../librpc/gen_ndr/ndr_security.h"
32 #include "../librpc/gen_ndr/open_files.h"
33 #include "../librpc/gen_ndr/idmap.h"
34 #include "../librpc/gen_ndr/ioctl.h"
35 #include "passdb/lookup_sid.h"
39 #include "source3/lib/dbwrap/dbwrap_watch.h"
40 #include "locking/leases_db.h"
41 #include "librpc/gen_ndr/ndr_leases_db.h"
43 extern const struct generic_mapping file_generic_mapping;
45 struct deferred_open_record {
46 bool delayed_for_oplocks;
51 * Timer for async opens, needed because they don't use a watch on
52 * a locking.tdb record. This is currently only used for real async
53 * opens and just terminates smbd if the async open times out.
55 struct tevent_timer *te;
58 /****************************************************************************
59 If the requester wanted DELETE_ACCESS and was rejected because
60 the file ACL didn't include DELETE_ACCESS, see if the parent ACL
62 ****************************************************************************/
64 static bool parent_override_delete(connection_struct *conn,
65 const struct smb_filename *smb_fname,
67 uint32_t rejected_mask)
69 if ((access_mask & DELETE_ACCESS) &&
70 (rejected_mask & DELETE_ACCESS) &&
71 can_delete_file_in_directory(conn, smb_fname)) {
77 /****************************************************************************
78 Check if we have open rights.
79 ****************************************************************************/
81 NTSTATUS smbd_check_access_rights(struct connection_struct *conn,
82 const struct smb_filename *smb_fname,
86 /* Check if we have rights to open. */
88 struct security_descriptor *sd = NULL;
89 uint32_t rejected_share_access;
90 uint32_t rejected_mask = access_mask;
91 uint32_t do_not_check_mask = 0;
93 rejected_share_access = access_mask & ~(conn->share_access);
95 if (rejected_share_access) {
96 DEBUG(10, ("smbd_check_access_rights: rejected share access 0x%x "
98 (unsigned int)access_mask,
99 smb_fname_str_dbg(smb_fname),
100 (unsigned int)rejected_share_access ));
101 return NT_STATUS_ACCESS_DENIED;
104 if (!use_privs && get_current_uid(conn) == (uid_t)0) {
105 /* I'm sorry sir, I didn't know you were root... */
106 DEBUG(10,("smbd_check_access_rights: root override "
107 "on %s. Granting 0x%x\n",
108 smb_fname_str_dbg(smb_fname),
109 (unsigned int)access_mask ));
113 if ((access_mask & DELETE_ACCESS) && !lp_acl_check_permissions(SNUM(conn))) {
114 DEBUG(10,("smbd_check_access_rights: not checking ACL "
115 "on DELETE_ACCESS on file %s. Granting 0x%x\n",
116 smb_fname_str_dbg(smb_fname),
117 (unsigned int)access_mask ));
121 if (access_mask == DELETE_ACCESS &&
122 VALID_STAT(smb_fname->st) &&
123 S_ISLNK(smb_fname->st.st_ex_mode)) {
124 /* We can always delete a symlink. */
125 DEBUG(10,("smbd_check_access_rights: not checking ACL "
126 "on DELETE_ACCESS on symlink %s.\n",
127 smb_fname_str_dbg(smb_fname) ));
131 status = SMB_VFS_GET_NT_ACL(conn, smb_fname,
134 SECINFO_DACL), talloc_tos(), &sd);
136 if (!NT_STATUS_IS_OK(status)) {
137 DEBUG(10, ("smbd_check_access_rights: Could not get acl "
139 smb_fname_str_dbg(smb_fname),
142 if (NT_STATUS_EQUAL(status, NT_STATUS_ACCESS_DENIED)) {
150 * If we can access the path to this file, by
151 * default we have FILE_READ_ATTRIBUTES from the
152 * containing directory. See the section:
153 * "Algorithm to Check Access to an Existing File"
156 * se_file_access_check() also takes care of
157 * owner WRITE_DAC and READ_CONTROL.
159 do_not_check_mask = FILE_READ_ATTRIBUTES;
162 * Samba 3.6 and earlier granted execute access even
163 * if the ACL did not contain execute rights.
164 * Samba 4.0 is more correct and checks it.
165 * The compatibilty mode allows one to skip this check
166 * to smoothen upgrades.
168 if (lp_acl_allow_execute_always(SNUM(conn))) {
169 do_not_check_mask |= FILE_EXECUTE;
172 status = se_file_access_check(sd,
173 get_current_nttok(conn),
175 (access_mask & ~do_not_check_mask),
178 DEBUG(10,("smbd_check_access_rights: file %s requesting "
179 "0x%x returning 0x%x (%s)\n",
180 smb_fname_str_dbg(smb_fname),
181 (unsigned int)access_mask,
182 (unsigned int)rejected_mask,
183 nt_errstr(status) ));
185 if (!NT_STATUS_IS_OK(status)) {
186 if (DEBUGLEVEL >= 10) {
187 DEBUG(10,("smbd_check_access_rights: acl for %s is:\n",
188 smb_fname_str_dbg(smb_fname) ));
189 NDR_PRINT_DEBUG(security_descriptor, sd);
195 if (NT_STATUS_IS_OK(status) ||
196 !NT_STATUS_EQUAL(status, NT_STATUS_ACCESS_DENIED)) {
200 /* Here we know status == NT_STATUS_ACCESS_DENIED. */
204 if ((access_mask & FILE_WRITE_ATTRIBUTES) &&
205 (rejected_mask & FILE_WRITE_ATTRIBUTES) &&
206 !lp_store_dos_attributes(SNUM(conn)) &&
207 (lp_map_readonly(SNUM(conn)) ||
208 lp_map_archive(SNUM(conn)) ||
209 lp_map_hidden(SNUM(conn)) ||
210 lp_map_system(SNUM(conn)))) {
211 rejected_mask &= ~FILE_WRITE_ATTRIBUTES;
213 DEBUG(10,("smbd_check_access_rights: "
215 "FILE_WRITE_ATTRIBUTES "
217 smb_fname_str_dbg(smb_fname)));
220 if (parent_override_delete(conn,
224 /* Were we trying to do an open
225 * for delete and didn't get DELETE
226 * access (only) ? Check if the
227 * directory allows DELETE_CHILD.
229 * http://blogs.msdn.com/oldnewthing/archive/2004/06/04/148426.aspx
232 rejected_mask &= ~DELETE_ACCESS;
234 DEBUG(10,("smbd_check_access_rights: "
238 smb_fname_str_dbg(smb_fname)));
241 if (rejected_mask != 0) {
242 return NT_STATUS_ACCESS_DENIED;
247 NTSTATUS check_parent_access(struct connection_struct *conn,
248 struct smb_filename *smb_fname,
249 uint32_t access_mask)
252 char *parent_dir = NULL;
253 struct security_descriptor *parent_sd = NULL;
254 uint32_t access_granted = 0;
255 struct smb_filename *parent_smb_fname = NULL;
257 if (!parent_dirname(talloc_tos(),
258 smb_fname->base_name,
261 return NT_STATUS_NO_MEMORY;
264 parent_smb_fname = synthetic_smb_fname(talloc_tos(),
269 if (parent_smb_fname == NULL) {
270 return NT_STATUS_NO_MEMORY;
273 if (get_current_uid(conn) == (uid_t)0) {
274 /* I'm sorry sir, I didn't know you were root... */
275 DEBUG(10,("check_parent_access: root override "
276 "on %s. Granting 0x%x\n",
277 smb_fname_str_dbg(smb_fname),
278 (unsigned int)access_mask ));
282 status = SMB_VFS_GET_NT_ACL(conn,
288 if (!NT_STATUS_IS_OK(status)) {
289 DEBUG(5,("check_parent_access: SMB_VFS_GET_NT_ACL failed for "
290 "%s with error %s\n",
297 * If we can access the path to this file, by
298 * default we have FILE_READ_ATTRIBUTES from the
299 * containing directory. See the section:
300 * "Algorithm to Check Access to an Existing File"
303 * se_file_access_check() also takes care of
304 * owner WRITE_DAC and READ_CONTROL.
306 status = se_file_access_check(parent_sd,
307 get_current_nttok(conn),
309 (access_mask & ~FILE_READ_ATTRIBUTES),
311 if(!NT_STATUS_IS_OK(status)) {
312 DEBUG(5,("check_parent_access: access check "
313 "on directory %s for "
314 "path %s for mask 0x%x returned (0x%x) %s\n",
316 smb_fname->base_name,
319 nt_errstr(status) ));
326 /****************************************************************************
327 Ensure when opening a base file for a stream open that we have permissions
328 to do so given the access mask on the base file.
329 ****************************************************************************/
331 static NTSTATUS check_base_file_access(struct connection_struct *conn,
332 struct smb_filename *smb_fname,
333 uint32_t access_mask)
337 status = smbd_calculate_access_mask(conn, smb_fname,
341 if (!NT_STATUS_IS_OK(status)) {
342 DEBUG(10, ("smbd_calculate_access_mask "
343 "on file %s returned %s\n",
344 smb_fname_str_dbg(smb_fname),
349 if (access_mask & (FILE_WRITE_DATA|FILE_APPEND_DATA)) {
351 if (!CAN_WRITE(conn)) {
352 return NT_STATUS_ACCESS_DENIED;
354 dosattrs = dos_mode(conn, smb_fname);
355 if (IS_DOS_READONLY(dosattrs)) {
356 return NT_STATUS_ACCESS_DENIED;
360 return smbd_check_access_rights(conn,
366 /****************************************************************************
367 Handle differing symlink errno's
368 ****************************************************************************/
370 static int link_errno_convert(int err)
372 #if defined(ENOTSUP) && defined(OSF1)
373 /* handle special Tru64 errno */
374 if (err == ENOTSUP) {
379 /* fix broken NetBSD errno */
384 /* fix broken FreeBSD errno */
391 static int non_widelink_open(struct connection_struct *conn,
392 const struct smb_filename *conn_rootdir_fname,
394 struct smb_filename *smb_fname,
397 unsigned int link_depth);
399 /****************************************************************************
400 Follow a symlink in userspace.
401 ****************************************************************************/
403 static int process_symlink_open(struct connection_struct *conn,
404 const struct smb_filename *conn_rootdir_fname,
406 struct smb_filename *smb_fname,
409 unsigned int link_depth)
412 char *link_target = NULL;
415 struct smb_filename oldwd_fname = {0};
416 size_t rootdir_len = 0;
417 char *resolved_name = NULL;
418 bool matched = false;
422 * Ensure we don't get stuck in a symlink loop.
425 if (link_depth >= 20) {
430 /* Allocate space for the link target. */
431 link_target = talloc_array(talloc_tos(), char, PATH_MAX);
432 if (link_target == NULL) {
437 /* Read the link target. */
438 link_len = SMB_VFS_READLINK(conn,
442 if (link_len == -1) {
446 /* Ensure it's at least null terminated. */
447 link_target[link_len] = '\0';
449 /* Convert to an absolute path. */
450 resolved_name = SMB_VFS_REALPATH(conn, link_target);
451 if (resolved_name == NULL) {
456 * We know conn_rootdir starts with '/' and
457 * does not end in '/'. FIXME ! Should we
460 rootdir_len = strlen(conn_rootdir_fname->base_name);
462 matched = (strncmp(conn_rootdir_fname->base_name,
471 * Turn into a path relative to the share root.
473 if (resolved_name[rootdir_len] == '\0') {
474 /* Link to the root of the share. */
475 smb_fname->base_name = talloc_strdup(talloc_tos(), ".");
476 if (smb_fname->base_name == NULL) {
480 } else if (resolved_name[rootdir_len] == '/') {
481 smb_fname->base_name = &resolved_name[rootdir_len+1];
487 oldwd = vfs_GetWd(talloc_tos(), conn);
492 oldwd_fname = (struct smb_filename) { .base_name = oldwd };
494 /* Ensure we operate from the root of the share. */
495 if (vfs_ChDir(conn, conn_rootdir_fname) == -1) {
499 /* And do it all again.. */
500 fd = non_widelink_open(conn,
513 SAFE_FREE(resolved_name);
514 TALLOC_FREE(link_target);
516 int ret = vfs_ChDir(conn, &oldwd_fname);
518 smb_panic("unable to get back to old directory\n");
522 if (saved_errno != 0) {
528 /****************************************************************************
530 ****************************************************************************/
532 static int non_widelink_open(struct connection_struct *conn,
533 const struct smb_filename *conn_rootdir_fname,
535 struct smb_filename *smb_fname,
538 unsigned int link_depth)
542 struct smb_filename *smb_fname_rel = NULL;
545 struct smb_filename oldwd_fname = {0};
546 char *parent_dir = NULL;
547 struct smb_filename parent_dir_fname = {0};
548 const char *final_component = NULL;
550 if (!parent_dirname(talloc_tos(),
551 smb_fname->base_name,
557 parent_dir_fname = (struct smb_filename) { .base_name = parent_dir };
559 oldwd = vfs_GetWd(talloc_tos(), conn);
564 oldwd_fname = (struct smb_filename) { .base_name = oldwd };
566 /* Pin parent directory in place. */
567 if (vfs_ChDir(conn, &parent_dir_fname) == -1) {
571 /* Ensure the relative path is below the share. */
572 status = check_reduced_name(conn, parent_dir, final_component);
573 if (!NT_STATUS_IS_OK(status)) {
574 saved_errno = map_errno_from_nt_status(status);
578 smb_fname_rel = synthetic_smb_fname(talloc_tos(),
580 smb_fname->stream_name,
587 struct smb_filename *tmp_name = fsp->fsp_name;
588 fsp->fsp_name = smb_fname_rel;
589 fd = SMB_VFS_OPEN(conn, smb_fname_rel, fsp, flags, mode);
590 fsp->fsp_name = tmp_name;
594 saved_errno = link_errno_convert(errno);
596 * Trying to open a symlink to a directory with O_NOFOLLOW and
597 * O_DIRECTORY can return either of ELOOP and ENOTDIR. So
598 * ENOTDIR really means: might be a symlink, but we're not sure.
599 * In this case, we just assume there's a symlink. If we were
600 * wrong, process_symlink_open() will return EINVAL. We check
601 * this below, and fall back to returning the initial
604 * BUG: https://bugzilla.samba.org/show_bug.cgi?id=12860
606 if (saved_errno == ELOOP || saved_errno == ENOTDIR) {
607 if (fsp->posix_flags & FSP_POSIX_FLAGS_OPEN) {
608 /* Never follow symlinks on posix open. */
611 if (!lp_follow_symlinks(SNUM(conn))) {
612 /* Explicitly no symlinks. */
616 * We may have a symlink. Follow in userspace
617 * to ensure it's under the share definition.
619 fd = process_symlink_open(conn,
627 if (saved_errno == ENOTDIR &&
630 * O_DIRECTORY on neither a directory,
631 * nor a symlink. Just return
632 * saved_errno from initial open()
637 link_errno_convert(errno);
644 TALLOC_FREE(parent_dir);
645 TALLOC_FREE(smb_fname_rel);
648 int ret = vfs_ChDir(conn, &oldwd_fname);
650 smb_panic("unable to get back to old directory\n");
654 if (saved_errno != 0) {
660 /****************************************************************************
661 fd support routines - attempt to do a dos_open.
662 ****************************************************************************/
664 NTSTATUS fd_open(struct connection_struct *conn,
669 struct smb_filename *smb_fname = fsp->fsp_name;
670 NTSTATUS status = NT_STATUS_OK;
673 * Never follow symlinks on a POSIX client. The
674 * client should be doing this.
677 if ((fsp->posix_flags & FSP_POSIX_FLAGS_OPEN) || !lp_follow_symlinks(SNUM(conn))) {
681 /* Ensure path is below share definition. */
682 if (!lp_widelinks(SNUM(conn))) {
683 struct smb_filename *conn_rootdir_fname = NULL;
684 const char *conn_rootdir = SMB_VFS_CONNECTPATH(conn,
685 smb_fname->base_name);
688 if (conn_rootdir == NULL) {
689 return NT_STATUS_NO_MEMORY;
691 conn_rootdir_fname = synthetic_smb_fname(talloc_tos(),
696 if (conn_rootdir_fname == NULL) {
697 return NT_STATUS_NO_MEMORY;
701 * Only follow symlinks within a share
704 fsp->fh->fd = non_widelink_open(conn,
711 if (fsp->fh->fd == -1) {
714 TALLOC_FREE(conn_rootdir_fname);
715 if (saved_errno != 0) {
719 fsp->fh->fd = SMB_VFS_OPEN(conn, smb_fname, fsp, flags, mode);
722 if (fsp->fh->fd == -1) {
723 int posix_errno = link_errno_convert(errno);
724 status = map_nt_error_from_unix(posix_errno);
725 if (errno == EMFILE) {
726 static time_t last_warned = 0L;
728 if (time((time_t *) NULL) > last_warned) {
729 DEBUG(0,("Too many open files, unable "
730 "to open more! smbd's max "
732 lp_max_open_files()));
733 last_warned = time((time_t *) NULL);
739 DEBUG(10,("fd_open: name %s, flags = 0%o mode = 0%o, fd = %d. %s\n",
740 smb_fname_str_dbg(smb_fname), flags, (int)mode, fsp->fh->fd,
741 (fsp->fh->fd == -1) ? strerror(errno) : "" ));
746 /****************************************************************************
747 Close the file associated with a fsp.
748 ****************************************************************************/
750 NTSTATUS fd_close(files_struct *fsp)
757 if (fsp->fh->fd == -1) {
758 return NT_STATUS_OK; /* What we used to call a stat open. */
760 if (fsp->fh->ref_count > 1) {
761 return NT_STATUS_OK; /* Shared handle. Only close last reference. */
764 ret = SMB_VFS_CLOSE(fsp);
767 return map_nt_error_from_unix(errno);
772 /****************************************************************************
773 Change the ownership of a file to that of the parent directory.
774 Do this by fd if possible.
775 ****************************************************************************/
777 void change_file_owner_to_parent(connection_struct *conn,
778 const char *inherit_from_dir,
781 struct smb_filename *smb_fname_parent;
784 smb_fname_parent = synthetic_smb_fname(talloc_tos(),
789 if (smb_fname_parent == NULL) {
793 ret = SMB_VFS_STAT(conn, smb_fname_parent);
795 DEBUG(0,("change_file_owner_to_parent: failed to stat parent "
796 "directory %s. Error was %s\n",
797 smb_fname_str_dbg(smb_fname_parent),
799 TALLOC_FREE(smb_fname_parent);
803 if (smb_fname_parent->st.st_ex_uid == fsp->fsp_name->st.st_ex_uid) {
804 /* Already this uid - no need to change. */
805 DEBUG(10,("change_file_owner_to_parent: file %s "
806 "is already owned by uid %d\n",
808 (int)fsp->fsp_name->st.st_ex_uid ));
809 TALLOC_FREE(smb_fname_parent);
814 ret = SMB_VFS_FCHOWN(fsp, smb_fname_parent->st.st_ex_uid, (gid_t)-1);
817 DEBUG(0,("change_file_owner_to_parent: failed to fchown "
818 "file %s to parent directory uid %u. Error "
819 "was %s\n", fsp_str_dbg(fsp),
820 (unsigned int)smb_fname_parent->st.st_ex_uid,
823 DEBUG(10,("change_file_owner_to_parent: changed new file %s to "
824 "parent directory uid %u.\n", fsp_str_dbg(fsp),
825 (unsigned int)smb_fname_parent->st.st_ex_uid));
826 /* Ensure the uid entry is updated. */
827 fsp->fsp_name->st.st_ex_uid = smb_fname_parent->st.st_ex_uid;
830 TALLOC_FREE(smb_fname_parent);
833 static NTSTATUS change_dir_owner_to_parent(connection_struct *conn,
834 const char *inherit_from_dir,
835 struct smb_filename *smb_dname,
836 SMB_STRUCT_STAT *psbuf)
838 struct smb_filename *smb_fname_parent;
839 struct smb_filename *smb_fname_cwd = NULL;
840 char *saved_dir = NULL;
841 struct smb_filename smb_fname_saved_dir = {0};
842 TALLOC_CTX *ctx = talloc_tos();
843 NTSTATUS status = NT_STATUS_OK;
846 smb_fname_parent = synthetic_smb_fname(ctx,
851 if (smb_fname_parent == NULL) {
852 return NT_STATUS_NO_MEMORY;
855 ret = SMB_VFS_STAT(conn, smb_fname_parent);
857 status = map_nt_error_from_unix(errno);
858 DEBUG(0,("change_dir_owner_to_parent: failed to stat parent "
859 "directory %s. Error was %s\n",
860 smb_fname_str_dbg(smb_fname_parent),
865 /* We've already done an lstat into psbuf, and we know it's a
866 directory. If we can cd into the directory and the dev/ino
867 are the same then we can safely chown without races as
868 we're locking the directory in place by being in it. This
869 should work on any UNIX (thanks tridge :-). JRA.
872 saved_dir = vfs_GetWd(ctx,conn);
874 status = map_nt_error_from_unix(errno);
875 DEBUG(0,("change_dir_owner_to_parent: failed to get "
876 "current working directory. Error was %s\n",
881 smb_fname_saved_dir = (struct smb_filename) { .base_name = saved_dir };
883 /* Chdir into the new path. */
884 if (vfs_ChDir(conn, smb_dname) == -1) {
885 status = map_nt_error_from_unix(errno);
886 DEBUG(0,("change_dir_owner_to_parent: failed to change "
887 "current working directory to %s. Error "
888 "was %s\n", smb_dname->base_name, strerror(errno) ));
892 smb_fname_cwd = synthetic_smb_fname(ctx, ".", NULL, NULL, 0);
893 if (smb_fname_cwd == NULL) {
894 status = NT_STATUS_NO_MEMORY;
898 ret = SMB_VFS_STAT(conn, smb_fname_cwd);
900 status = map_nt_error_from_unix(errno);
901 DEBUG(0,("change_dir_owner_to_parent: failed to stat "
902 "directory '.' (%s) Error was %s\n",
903 smb_dname->base_name, strerror(errno)));
907 /* Ensure we're pointing at the same place. */
908 if (smb_fname_cwd->st.st_ex_dev != psbuf->st_ex_dev ||
909 smb_fname_cwd->st.st_ex_ino != psbuf->st_ex_ino) {
910 DEBUG(0,("change_dir_owner_to_parent: "
911 "device/inode on directory %s changed. "
912 "Refusing to chown !\n",
913 smb_dname->base_name ));
914 status = NT_STATUS_ACCESS_DENIED;
918 if (smb_fname_parent->st.st_ex_uid == smb_fname_cwd->st.st_ex_uid) {
919 /* Already this uid - no need to change. */
920 DEBUG(10,("change_dir_owner_to_parent: directory %s "
921 "is already owned by uid %d\n",
922 smb_dname->base_name,
923 (int)smb_fname_cwd->st.st_ex_uid ));
924 status = NT_STATUS_OK;
929 ret = SMB_VFS_LCHOWN(conn,
931 smb_fname_parent->st.st_ex_uid,
935 status = map_nt_error_from_unix(errno);
936 DEBUG(10,("change_dir_owner_to_parent: failed to chown "
937 "directory %s to parent directory uid %u. "
939 smb_dname->base_name,
940 (unsigned int)smb_fname_parent->st.st_ex_uid,
943 DEBUG(10,("change_dir_owner_to_parent: changed ownership of new "
944 "directory %s to parent directory uid %u.\n",
945 smb_dname->base_name,
946 (unsigned int)smb_fname_parent->st.st_ex_uid ));
947 /* Ensure the uid entry is updated. */
948 psbuf->st_ex_uid = smb_fname_parent->st.st_ex_uid;
952 vfs_ChDir(conn, &smb_fname_saved_dir);
954 TALLOC_FREE(saved_dir);
955 TALLOC_FREE(smb_fname_parent);
956 TALLOC_FREE(smb_fname_cwd);
960 /****************************************************************************
961 Open a file - returning a guaranteed ATOMIC indication of if the
962 file was created or not.
963 ****************************************************************************/
965 static NTSTATUS fd_open_atomic(struct connection_struct *conn,
971 NTSTATUS status = NT_STATUS_UNSUCCESSFUL;
972 NTSTATUS retry_status;
973 bool file_existed = VALID_STAT(fsp->fsp_name->st);
976 *file_created = false;
978 if (!(flags & O_CREAT)) {
980 * We're not creating the file, just pass through.
982 return fd_open(conn, fsp, flags, mode);
985 if (flags & O_EXCL) {
987 * Fail if already exists, just pass through.
989 status = fd_open(conn, fsp, flags, mode);
992 * Here we've opened with O_CREAT|O_EXCL. If that went
993 * NT_STATUS_OK, we *know* we created this file.
995 *file_created = NT_STATUS_IS_OK(status);
1001 * Now it gets tricky. We have O_CREAT, but not O_EXCL.
1002 * To know absolutely if we created the file or not,
1003 * we can never call O_CREAT without O_EXCL. So if
1004 * we think the file existed, try without O_CREAT|O_EXCL.
1005 * If we think the file didn't exist, try with
1008 * The big problem here is dangling symlinks. Opening
1009 * without O_NOFOLLOW means both bad symlink
1010 * and missing path return -1, ENOENT from open(). As POSIX
1011 * is pathname based it's not possible to tell
1012 * the difference between these two cases in a
1013 * non-racy way, so change to try only two attempts before
1016 * We don't have this problem for the O_NOFOLLOW
1017 * case as it just returns NT_STATUS_OBJECT_PATH_NOT_FOUND
1018 * mapped from the ELOOP POSIX error.
1024 curr_flags &= ~(O_CREAT);
1025 retry_status = NT_STATUS_OBJECT_NAME_NOT_FOUND;
1027 curr_flags |= O_EXCL;
1028 retry_status = NT_STATUS_OBJECT_NAME_COLLISION;
1031 status = fd_open(conn, fsp, curr_flags, mode);
1032 if (NT_STATUS_IS_OK(status)) {
1033 if (!file_existed) {
1034 *file_created = true;
1036 return NT_STATUS_OK;
1038 if (!NT_STATUS_EQUAL(status, retry_status)) {
1045 * Keep file_existed up to date for clarity.
1047 if (NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
1048 file_existed = false;
1049 curr_flags |= O_EXCL;
1050 DBG_DEBUG("file %s did not exist. Retry.\n",
1051 smb_fname_str_dbg(fsp->fsp_name));
1053 file_existed = true;
1054 curr_flags &= ~(O_CREAT);
1055 DBG_DEBUG("file %s existed. Retry.\n",
1056 smb_fname_str_dbg(fsp->fsp_name));
1059 status = fd_open(conn, fsp, curr_flags, mode);
1061 if (NT_STATUS_IS_OK(status) && (!file_existed)) {
1062 *file_created = true;
1068 /****************************************************************************
1070 ****************************************************************************/
1072 static NTSTATUS open_file(files_struct *fsp,
1073 connection_struct *conn,
1074 struct smb_request *req,
1075 const char *parent_dir,
1078 uint32_t access_mask, /* client requested access mask. */
1079 uint32_t open_access_mask, /* what we're actually using in the open. */
1080 bool *p_file_created)
1082 struct smb_filename *smb_fname = fsp->fsp_name;
1083 NTSTATUS status = NT_STATUS_OK;
1084 int accmode = (flags & O_ACCMODE);
1085 int local_flags = flags;
1086 bool file_existed = VALID_STAT(fsp->fsp_name->st);
1091 /* Check permissions */
1094 * This code was changed after seeing a client open request
1095 * containing the open mode of (DENY_WRITE/read-only) with
1096 * the 'create if not exist' bit set. The previous code
1097 * would fail to open the file read only on a read-only share
1098 * as it was checking the flags parameter directly against O_RDONLY,
1099 * this was failing as the flags parameter was set to O_RDONLY|O_CREAT.
1103 if (!CAN_WRITE(conn)) {
1104 /* It's a read-only share - fail if we wanted to write. */
1105 if(accmode != O_RDONLY || (flags & O_TRUNC) || (flags & O_APPEND)) {
1106 DEBUG(3,("Permission denied opening %s\n",
1107 smb_fname_str_dbg(smb_fname)));
1108 return NT_STATUS_ACCESS_DENIED;
1110 if (flags & O_CREAT) {
1111 /* We don't want to write - but we must make sure that
1112 O_CREAT doesn't create the file if we have write
1113 access into the directory.
1115 flags &= ~(O_CREAT|O_EXCL);
1116 local_flags &= ~(O_CREAT|O_EXCL);
1121 * This little piece of insanity is inspired by the
1122 * fact that an NT client can open a file for O_RDONLY,
1123 * but set the create disposition to FILE_EXISTS_TRUNCATE.
1124 * If the client *can* write to the file, then it expects to
1125 * truncate the file, even though it is opening for readonly.
1126 * Quicken uses this stupid trick in backup file creation...
1127 * Thanks *greatly* to "David W. Chapman Jr." <dwcjr@inethouston.net>
1128 * for helping track this one down. It didn't bite us in 2.0.x
1129 * as we always opened files read-write in that release. JRA.
1132 if ((accmode == O_RDONLY) && ((flags & O_TRUNC) == O_TRUNC)) {
1133 DEBUG(10,("open_file: truncate requested on read-only open "
1134 "for file %s\n", smb_fname_str_dbg(smb_fname)));
1135 local_flags = (flags & ~O_ACCMODE)|O_RDWR;
1138 if ((open_access_mask & (FILE_READ_DATA|FILE_WRITE_DATA|FILE_APPEND_DATA|FILE_EXECUTE)) ||
1139 (!file_existed && (local_flags & O_CREAT)) ||
1140 ((local_flags & O_TRUNC) == O_TRUNC) ) {
1144 #if defined(O_NONBLOCK) && defined(S_ISFIFO)
1146 * We would block on opening a FIFO with no one else on the
1147 * other end. Do what we used to do and add O_NONBLOCK to the
1151 if (file_existed && S_ISFIFO(smb_fname->st.st_ex_mode)) {
1152 local_flags &= ~O_TRUNC; /* Can't truncate a FIFO. */
1153 local_flags |= O_NONBLOCK;
1157 /* Don't create files with Microsoft wildcard characters. */
1158 if (fsp->base_fsp) {
1160 * wildcard characters are allowed in stream names
1161 * only test the basefilename
1163 wild = fsp->base_fsp->fsp_name->base_name;
1165 wild = smb_fname->base_name;
1167 if ((local_flags & O_CREAT) && !file_existed &&
1168 !(fsp->posix_flags & FSP_POSIX_FLAGS_PATHNAMES) &&
1169 ms_has_wild(wild)) {
1170 return NT_STATUS_OBJECT_NAME_INVALID;
1173 /* Can we access this file ? */
1174 if (!fsp->base_fsp) {
1175 /* Only do this check on non-stream open. */
1177 status = smbd_check_access_rights(conn,
1182 if (!NT_STATUS_IS_OK(status)) {
1183 DEBUG(10, ("open_file: "
1184 "smbd_check_access_rights "
1185 "on file %s returned %s\n",
1186 smb_fname_str_dbg(smb_fname),
1187 nt_errstr(status)));
1190 if (!NT_STATUS_IS_OK(status) &&
1191 !NT_STATUS_EQUAL(status,
1192 NT_STATUS_OBJECT_NAME_NOT_FOUND))
1197 if (NT_STATUS_EQUAL(status,
1198 NT_STATUS_OBJECT_NAME_NOT_FOUND))
1200 DEBUG(10, ("open_file: "
1201 "file %s vanished since we "
1202 "checked for existence.\n",
1203 smb_fname_str_dbg(smb_fname)));
1204 file_existed = false;
1205 SET_STAT_INVALID(fsp->fsp_name->st);
1209 if (!file_existed) {
1210 if (!(local_flags & O_CREAT)) {
1211 /* File didn't exist and no O_CREAT. */
1212 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
1215 status = check_parent_access(conn,
1218 if (!NT_STATUS_IS_OK(status)) {
1219 DEBUG(10, ("open_file: "
1220 "check_parent_access on "
1221 "file %s returned %s\n",
1222 smb_fname_str_dbg(smb_fname),
1223 nt_errstr(status) ));
1230 * Actually do the open - if O_TRUNC is needed handle it
1231 * below under the share mode lock.
1233 status = fd_open_atomic(conn, fsp, local_flags & ~O_TRUNC,
1234 unx_mode, p_file_created);
1235 if (!NT_STATUS_IS_OK(status)) {
1236 DEBUG(3,("Error opening file %s (%s) (local_flags=%d) "
1237 "(flags=%d)\n", smb_fname_str_dbg(smb_fname),
1238 nt_errstr(status),local_flags,flags));
1242 if (local_flags & O_NONBLOCK) {
1244 * GPFS can return ETIMEDOUT for pread on
1245 * nonblocking file descriptors when files
1246 * migrated to tape need to be recalled. I
1247 * could imagine this happens elsehwere
1248 * too. With blocking file descriptors this
1251 ret = set_blocking(fsp->fh->fd, true);
1253 status = map_nt_error_from_unix(errno);
1254 DBG_WARNING("Could not set fd to blocking: "
1255 "%s\n", strerror(errno));
1261 ret = SMB_VFS_FSTAT(fsp, &smb_fname->st);
1263 /* If we have an fd, this stat should succeed. */
1264 DEBUG(0,("Error doing fstat on open file %s "
1266 smb_fname_str_dbg(smb_fname),
1268 status = map_nt_error_from_unix(errno);
1273 if (*p_file_created) {
1274 /* We created this file. */
1276 bool need_re_stat = false;
1277 /* Do all inheritance work after we've
1278 done a successful fstat call and filled
1279 in the stat struct in fsp->fsp_name. */
1281 /* Inherit the ACL if required */
1282 if (lp_inherit_permissions(SNUM(conn))) {
1283 inherit_access_posix_acl(conn, parent_dir,
1286 need_re_stat = true;
1289 /* Change the owner if required. */
1290 if (lp_inherit_owner(SNUM(conn)) != INHERIT_OWNER_NO) {
1291 change_file_owner_to_parent(conn, parent_dir,
1293 need_re_stat = true;
1297 ret = SMB_VFS_FSTAT(fsp, &smb_fname->st);
1298 /* If we have an fd, this stat should succeed. */
1300 DEBUG(0,("Error doing fstat on open file %s "
1302 smb_fname_str_dbg(smb_fname),
1307 notify_fname(conn, NOTIFY_ACTION_ADDED,
1308 FILE_NOTIFY_CHANGE_FILE_NAME,
1309 smb_fname->base_name);
1312 fsp->fh->fd = -1; /* What we used to call a stat open. */
1313 if (!file_existed) {
1314 /* File must exist for a stat open. */
1315 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
1318 status = smbd_check_access_rights(conn,
1323 if (NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND) &&
1324 (fsp->posix_flags & FSP_POSIX_FLAGS_OPEN) &&
1325 S_ISLNK(smb_fname->st.st_ex_mode)) {
1326 /* This is a POSIX stat open for delete
1327 * or rename on a symlink that points
1328 * nowhere. Allow. */
1329 DEBUG(10,("open_file: allowing POSIX "
1330 "open on bad symlink %s\n",
1331 smb_fname_str_dbg(smb_fname)));
1332 status = NT_STATUS_OK;
1335 if (!NT_STATUS_IS_OK(status)) {
1336 DEBUG(10,("open_file: "
1337 "smbd_check_access_rights on file "
1339 smb_fname_str_dbg(smb_fname),
1340 nt_errstr(status) ));
1346 * POSIX allows read-only opens of directories. We don't
1347 * want to do this (we use a different code path for this)
1348 * so catch a directory open and return an EISDIR. JRA.
1351 if(S_ISDIR(smb_fname->st.st_ex_mode)) {
1354 return NT_STATUS_FILE_IS_A_DIRECTORY;
1357 fsp->file_id = vfs_file_id_from_sbuf(conn, &smb_fname->st);
1358 fsp->vuid = req ? req->vuid : UID_FIELD_INVALID;
1359 fsp->file_pid = req ? req->smbpid : 0;
1360 fsp->can_lock = True;
1361 fsp->can_read = ((access_mask & FILE_READ_DATA) != 0);
1364 ((access_mask & (FILE_WRITE_DATA | FILE_APPEND_DATA)) != 0);
1365 fsp->print_file = NULL;
1366 fsp->modified = False;
1367 fsp->sent_oplock_break = NO_BREAK_SENT;
1368 fsp->is_directory = False;
1369 if (conn->aio_write_behind_list &&
1370 is_in_path(smb_fname->base_name, conn->aio_write_behind_list,
1371 conn->case_sensitive)) {
1372 fsp->aio_write_behind = True;
1375 fsp->wcp = NULL; /* Write cache pointer. */
1377 DEBUG(2,("%s opened file %s read=%s write=%s (numopen=%d)\n",
1378 conn->session_info->unix_info->unix_name,
1379 smb_fname_str_dbg(smb_fname),
1380 BOOLSTR(fsp->can_read), BOOLSTR(fsp->can_write),
1381 conn->num_files_open));
1384 return NT_STATUS_OK;
1387 /****************************************************************************
1388 Check if we can open a file with a share mode.
1389 Returns True if conflict, False if not.
1390 ****************************************************************************/
1392 static bool share_conflict(struct share_mode_entry *entry,
1393 uint32_t access_mask,
1394 uint32_t share_access)
1396 DEBUG(10,("share_conflict: entry->access_mask = 0x%x, "
1397 "entry->share_access = 0x%x, "
1398 "entry->private_options = 0x%x\n",
1399 (unsigned int)entry->access_mask,
1400 (unsigned int)entry->share_access,
1401 (unsigned int)entry->private_options));
1403 if (server_id_is_disconnected(&entry->pid)) {
1405 * note: cleanup should have been done by
1406 * delay_for_batch_oplocks()
1411 DEBUG(10,("share_conflict: access_mask = 0x%x, share_access = 0x%x\n",
1412 (unsigned int)access_mask, (unsigned int)share_access));
1414 if ((entry->access_mask & (FILE_WRITE_DATA|
1418 DELETE_ACCESS)) == 0) {
1419 DEBUG(10,("share_conflict: No conflict due to "
1420 "entry->access_mask = 0x%x\n",
1421 (unsigned int)entry->access_mask ));
1425 if ((access_mask & (FILE_WRITE_DATA|
1429 DELETE_ACCESS)) == 0) {
1430 DEBUG(10,("share_conflict: No conflict due to "
1431 "access_mask = 0x%x\n",
1432 (unsigned int)access_mask ));
1436 #if 1 /* JRA TEST - Superdebug. */
1437 #define CHECK_MASK(num, am, right, sa, share) \
1438 DEBUG(10,("share_conflict: [%d] am (0x%x) & right (0x%x) = 0x%x\n", \
1439 (unsigned int)(num), (unsigned int)(am), \
1440 (unsigned int)(right), (unsigned int)(am)&(right) )); \
1441 DEBUG(10,("share_conflict: [%d] sa (0x%x) & share (0x%x) = 0x%x\n", \
1442 (unsigned int)(num), (unsigned int)(sa), \
1443 (unsigned int)(share), (unsigned int)(sa)&(share) )); \
1444 if (((am) & (right)) && !((sa) & (share))) { \
1445 DEBUG(10,("share_conflict: check %d conflict am = 0x%x, right = 0x%x, \
1446 sa = 0x%x, share = 0x%x\n", (num), (unsigned int)(am), (unsigned int)(right), (unsigned int)(sa), \
1447 (unsigned int)(share) )); \
1451 #define CHECK_MASK(num, am, right, sa, share) \
1452 if (((am) & (right)) && !((sa) & (share))) { \
1453 DEBUG(10,("share_conflict: check %d conflict am = 0x%x, right = 0x%x, \
1454 sa = 0x%x, share = 0x%x\n", (num), (unsigned int)(am), (unsigned int)(right), (unsigned int)(sa), \
1455 (unsigned int)(share) )); \
1460 CHECK_MASK(1, entry->access_mask, FILE_WRITE_DATA | FILE_APPEND_DATA,
1461 share_access, FILE_SHARE_WRITE);
1462 CHECK_MASK(2, access_mask, FILE_WRITE_DATA | FILE_APPEND_DATA,
1463 entry->share_access, FILE_SHARE_WRITE);
1465 CHECK_MASK(3, entry->access_mask, FILE_READ_DATA | FILE_EXECUTE,
1466 share_access, FILE_SHARE_READ);
1467 CHECK_MASK(4, access_mask, FILE_READ_DATA | FILE_EXECUTE,
1468 entry->share_access, FILE_SHARE_READ);
1470 CHECK_MASK(5, entry->access_mask, DELETE_ACCESS,
1471 share_access, FILE_SHARE_DELETE);
1472 CHECK_MASK(6, access_mask, DELETE_ACCESS,
1473 entry->share_access, FILE_SHARE_DELETE);
1475 DEBUG(10,("share_conflict: No conflict.\n"));
1479 #if defined(DEVELOPER)
1480 static void validate_my_share_entries(struct smbd_server_connection *sconn,
1482 struct share_mode_entry *share_entry)
1484 struct server_id self = messaging_server_id(sconn->msg_ctx);
1487 if (!serverid_equal(&self, &share_entry->pid)) {
1491 if (share_entry->op_mid == 0) {
1492 /* INTERNAL_OPEN_ONLY */
1496 if (!is_valid_share_mode_entry(share_entry)) {
1500 fsp = file_find_dif(sconn, share_entry->id,
1501 share_entry->share_file_id);
1503 DEBUG(0,("validate_my_share_entries: PANIC : %s\n",
1504 share_mode_str(talloc_tos(), num, share_entry) ));
1505 smb_panic("validate_my_share_entries: Cannot match a "
1506 "share entry with an open file\n");
1509 if (((uint16_t)fsp->oplock_type) != share_entry->op_type) {
1518 DEBUG(0,("validate_my_share_entries: PANIC : %s\n",
1519 share_mode_str(talloc_tos(), num, share_entry) ));
1520 str = talloc_asprintf(talloc_tos(),
1521 "validate_my_share_entries: "
1522 "file %s, oplock_type = 0x%x, op_type = 0x%x\n",
1523 fsp->fsp_name->base_name,
1524 (unsigned int)fsp->oplock_type,
1525 (unsigned int)share_entry->op_type );
1531 bool is_stat_open(uint32_t access_mask)
1533 const uint32_t stat_open_bits =
1534 (SYNCHRONIZE_ACCESS|
1535 FILE_READ_ATTRIBUTES|
1536 FILE_WRITE_ATTRIBUTES);
1538 return (((access_mask & stat_open_bits) != 0) &&
1539 ((access_mask & ~stat_open_bits) == 0));
1542 static bool has_delete_on_close(struct share_mode_lock *lck,
1545 struct share_mode_data *d = lck->data;
1548 if (d->num_share_modes == 0) {
1551 if (!is_delete_on_close_set(lck, name_hash)) {
1554 for (i=0; i<d->num_share_modes; i++) {
1555 if (!share_mode_stale_pid(d, i)) {
1562 /****************************************************************************
1563 Deal with share modes
1564 Invariant: Share mode must be locked on entry and exit.
1565 Returns -1 on error, or number of share modes on success (may be zero).
1566 ****************************************************************************/
1568 static NTSTATUS open_mode_check(connection_struct *conn,
1569 struct share_mode_lock *lck,
1570 uint32_t access_mask,
1571 uint32_t share_access)
1575 if(lck->data->num_share_modes == 0) {
1576 return NT_STATUS_OK;
1579 if (is_stat_open(access_mask)) {
1580 /* Stat open that doesn't trigger oplock breaks or share mode
1581 * checks... ! JRA. */
1582 return NT_STATUS_OK;
1586 * Check if the share modes will give us access.
1589 #if defined(DEVELOPER)
1590 for(i = 0; i < lck->data->num_share_modes; i++) {
1591 validate_my_share_entries(conn->sconn, i,
1592 &lck->data->share_modes[i]);
1596 /* Now we check the share modes, after any oplock breaks. */
1597 for(i = 0; i < lck->data->num_share_modes; i++) {
1599 if (!is_valid_share_mode_entry(&lck->data->share_modes[i])) {
1603 /* someone else has a share lock on it, check to see if we can
1605 if (share_conflict(&lck->data->share_modes[i],
1606 access_mask, share_access)) {
1608 if (share_mode_stale_pid(lck->data, i)) {
1612 return NT_STATUS_SHARING_VIOLATION;
1616 return NT_STATUS_OK;
1620 * Send a break message to the oplock holder and delay the open for
1624 NTSTATUS send_break_message(struct messaging_context *msg_ctx,
1625 const struct share_mode_entry *exclusive,
1629 char msg[MSG_SMB_SHARE_MODE_ENTRY_SIZE];
1630 struct server_id_buf tmp;
1632 DEBUG(10, ("Sending break request to PID %s\n",
1633 server_id_str_buf(exclusive->pid, &tmp)));
1635 /* Create the message. */
1636 share_mode_entry_to_message(msg, exclusive);
1638 /* Overload entry->op_type */
1640 * This is a cut from uint32_t to uint16_t, but so far only the lower 3
1641 * bits (LEASE_WRITE/HANDLE/READ are used anyway.
1643 SSVAL(msg,OP_BREAK_MSG_OP_TYPE_OFFSET, break_to);
1645 status = messaging_send_buf(msg_ctx, exclusive->pid,
1646 MSG_SMB_BREAK_REQUEST,
1647 (uint8_t *)msg, sizeof(msg));
1648 if (!NT_STATUS_IS_OK(status)) {
1649 DEBUG(3, ("Could not send oplock break message: %s\n",
1650 nt_errstr(status)));
1657 * Do internal consistency checks on the share mode for a file.
1660 static bool validate_oplock_types(struct share_mode_lock *lck)
1662 struct share_mode_data *d = lck->data;
1664 bool ex_or_batch = false;
1665 bool level2 = false;
1666 bool no_oplock = false;
1667 uint32_t num_non_stat_opens = 0;
1670 for (i=0; i<d->num_share_modes; i++) {
1671 struct share_mode_entry *e = &d->share_modes[i];
1673 if (!is_valid_share_mode_entry(e)) {
1677 if (e->op_mid == 0) {
1678 /* INTERNAL_OPEN_ONLY */
1682 if (e->op_type == NO_OPLOCK && is_stat_open(e->access_mask)) {
1683 /* We ignore stat opens in the table - they
1684 always have NO_OPLOCK and never get or
1685 cause breaks. JRA. */
1689 num_non_stat_opens += 1;
1691 if (BATCH_OPLOCK_TYPE(e->op_type)) {
1692 /* batch - can only be one. */
1693 if (share_mode_stale_pid(d, i)) {
1694 DEBUG(10, ("Found stale batch oplock\n"));
1697 if (ex_or_batch || batch || level2 || no_oplock) {
1698 DEBUG(0, ("Bad batch oplock entry %u.",
1705 if (EXCLUSIVE_OPLOCK_TYPE(e->op_type)) {
1706 if (share_mode_stale_pid(d, i)) {
1707 DEBUG(10, ("Found stale duplicate oplock\n"));
1710 /* Exclusive or batch - can only be one. */
1711 if (ex_or_batch || level2 || no_oplock) {
1712 DEBUG(0, ("Bad exclusive or batch oplock "
1713 "entry %u.", (unsigned)i));
1719 if (LEVEL_II_OPLOCK_TYPE(e->op_type)) {
1720 if (batch || ex_or_batch) {
1721 if (share_mode_stale_pid(d, i)) {
1722 DEBUG(10, ("Found stale LevelII "
1726 DEBUG(0, ("Bad levelII oplock entry %u.",
1733 if (e->op_type == NO_OPLOCK) {
1734 if (batch || ex_or_batch) {
1735 if (share_mode_stale_pid(d, i)) {
1736 DEBUG(10, ("Found stale NO_OPLOCK "
1740 DEBUG(0, ("Bad no oplock entry %u.",
1748 remove_stale_share_mode_entries(d);
1750 if ((batch || ex_or_batch) && (num_non_stat_opens != 1)) {
1751 DEBUG(1, ("got batch (%d) or ex (%d) non-exclusively (%d)\n",
1752 (int)batch, (int)ex_or_batch,
1753 (int)d->num_share_modes));
1760 static bool delay_for_oplock(files_struct *fsp,
1762 const struct smb2_lease *lease,
1763 struct share_mode_lock *lck,
1764 bool have_sharing_violation,
1765 uint32_t create_disposition,
1766 bool first_open_attempt)
1768 struct share_mode_data *d = lck->data;
1771 bool will_overwrite;
1773 if ((oplock_request & INTERNAL_OPEN_ONLY) ||
1774 is_stat_open(fsp->access_mask)) {
1778 switch (create_disposition) {
1779 case FILE_SUPERSEDE:
1780 case FILE_OVERWRITE:
1781 case FILE_OVERWRITE_IF:
1782 will_overwrite = true;
1785 will_overwrite = false;
1789 for (i=0; i<d->num_share_modes; i++) {
1790 struct share_mode_entry *e = &d->share_modes[i];
1791 struct share_mode_lease *l = NULL;
1792 uint32_t e_lease_type = get_lease_type(d, e);
1794 uint32_t delay_mask = 0;
1796 if (e->op_type == LEASE_OPLOCK) {
1797 l = &d->leases[e->lease_idx];
1800 if (have_sharing_violation) {
1801 delay_mask = SMB2_LEASE_HANDLE;
1803 delay_mask = SMB2_LEASE_WRITE;
1806 break_to = e_lease_type & ~delay_mask;
1808 if (will_overwrite) {
1810 * we'll decide about SMB2_LEASE_READ later.
1812 * Maybe the break will be deferred
1814 break_to &= ~SMB2_LEASE_HANDLE;
1817 DEBUG(10, ("entry %u: e_lease_type %u, will_overwrite: %u\n",
1818 (unsigned)i, (unsigned)e_lease_type,
1819 (unsigned)will_overwrite));
1821 if (lease != NULL && l != NULL) {
1824 ign = smb2_lease_equal(fsp_client_guid(fsp),
1833 if ((e_lease_type & ~break_to) == 0) {
1834 if (l != NULL && l->breaking) {
1840 if (share_mode_stale_pid(d, i)) {
1844 if (will_overwrite) {
1846 * If we break anyway break to NONE directly.
1847 * Otherwise vfs_set_filelen() will trigger the
1850 break_to &= ~(SMB2_LEASE_READ|SMB2_LEASE_WRITE);
1853 if (e->op_type != LEASE_OPLOCK) {
1855 * Oplocks only support breaking to R or NONE.
1857 break_to &= ~(SMB2_LEASE_HANDLE|SMB2_LEASE_WRITE);
1860 DEBUG(10, ("breaking from %d to %d\n",
1861 (int)e_lease_type, (int)break_to));
1862 send_break_message(fsp->conn->sconn->msg_ctx, e,
1864 if (e_lease_type & delay_mask) {
1867 if (l != NULL && l->breaking && !first_open_attempt) {
1877 * Return lease or oplock state from a share mode
1879 static uint32_t get_lease_type_from_share_mode(const struct share_mode_data *d)
1881 uint32_t e_lease_type = 0;
1884 for (i=0; i < d->num_share_modes; i++) {
1885 struct share_mode_entry *e = &d->share_modes[i];
1887 e_lease_type |= get_lease_type(d, e);
1890 return e_lease_type;
1893 static bool file_has_brlocks(files_struct *fsp)
1895 struct byte_range_lock *br_lck;
1897 br_lck = brl_get_locks_readonly(fsp);
1901 return (brl_num_locks(br_lck) > 0);
1904 int find_share_mode_lease(struct share_mode_data *d,
1905 const struct GUID *client_guid,
1906 const struct smb2_lease_key *key)
1910 for (i=0; i<d->num_leases; i++) {
1911 struct share_mode_lease *l = &d->leases[i];
1913 if (smb2_lease_equal(client_guid,
1924 struct fsp_lease *find_fsp_lease(struct files_struct *new_fsp,
1925 const struct smb2_lease_key *key,
1926 const struct share_mode_lease *l)
1928 struct files_struct *fsp;
1931 * TODO: Measure how expensive this loop is with thousands of open
1935 for (fsp = file_find_di_first(new_fsp->conn->sconn, new_fsp->file_id);
1937 fsp = file_find_di_next(fsp)) {
1939 if (fsp == new_fsp) {
1942 if (fsp->oplock_type != LEASE_OPLOCK) {
1945 if (smb2_lease_key_equal(&fsp->lease->lease.lease_key, key)) {
1946 fsp->lease->ref_count += 1;
1951 /* Not found - must be leased in another smbd. */
1952 new_fsp->lease = talloc_zero(new_fsp->conn->sconn, struct fsp_lease);
1953 if (new_fsp->lease == NULL) {
1956 new_fsp->lease->ref_count = 1;
1957 new_fsp->lease->sconn = new_fsp->conn->sconn;
1958 new_fsp->lease->lease.lease_key = *key;
1959 new_fsp->lease->lease.lease_state = l->current_state;
1961 * We internally treat all leases as V2 and update
1962 * the epoch, but when sending breaks it matters if
1963 * the requesting lease was v1 or v2.
1965 new_fsp->lease->lease.lease_version = l->lease_version;
1966 new_fsp->lease->lease.lease_epoch = l->epoch;
1967 return new_fsp->lease;
1970 static NTSTATUS grant_fsp_lease(struct files_struct *fsp,
1971 struct share_mode_lock *lck,
1972 const struct smb2_lease *lease,
1973 uint32_t *p_lease_idx,
1976 struct share_mode_data *d = lck->data;
1977 const struct GUID *client_guid = fsp_client_guid(fsp);
1978 struct share_mode_lease *tmp;
1982 idx = find_share_mode_lease(d, client_guid, &lease->lease_key);
1985 struct share_mode_lease *l = &d->leases[idx];
1987 uint32_t existing, requested;
1989 fsp->lease = find_fsp_lease(fsp, &lease->lease_key, l);
1990 if (fsp->lease == NULL) {
1991 DEBUG(1, ("Did not find existing lease for file %s\n",
1993 return NT_STATUS_NO_MEMORY;
1999 * Upgrade only if the requested lease is a strict upgrade.
2001 existing = l->current_state;
2002 requested = lease->lease_state;
2005 * Tricky: This test makes sure that "requested" is a
2006 * strict bitwise superset of "existing".
2008 do_upgrade = ((existing & requested) == existing);
2011 * Upgrade only if there's a change.
2013 do_upgrade &= (granted != existing);
2016 * Upgrade only if other leases don't prevent what was asked
2019 do_upgrade &= (granted == requested);
2022 * only upgrade if we are not in breaking state
2024 do_upgrade &= !l->breaking;
2026 DEBUG(10, ("existing=%"PRIu32", requested=%"PRIu32", "
2027 "granted=%"PRIu32", do_upgrade=%d\n",
2028 existing, requested, granted, (int)do_upgrade));
2031 l->current_state = granted;
2035 /* Ensure we're in sync with current lease state. */
2036 fsp_lease_update(lck, fsp_client_guid(fsp), fsp->lease);
2037 return NT_STATUS_OK;
2044 tmp = talloc_realloc(d, d->leases, struct share_mode_lease,
2050 return NT_STATUS_INSUFFICIENT_RESOURCES;
2054 fsp->lease = talloc_zero(fsp->conn->sconn, struct fsp_lease);
2055 if (fsp->lease == NULL) {
2056 return NT_STATUS_INSUFFICIENT_RESOURCES;
2058 fsp->lease->ref_count = 1;
2059 fsp->lease->sconn = fsp->conn->sconn;
2060 fsp->lease->lease.lease_version = lease->lease_version;
2061 fsp->lease->lease.lease_key = lease->lease_key;
2062 fsp->lease->lease.lease_state = granted;
2063 fsp->lease->lease.lease_epoch = lease->lease_epoch + 1;
2065 *p_lease_idx = d->num_leases;
2067 d->leases[d->num_leases] = (struct share_mode_lease) {
2068 .client_guid = *client_guid,
2069 .lease_key = fsp->lease->lease.lease_key,
2070 .current_state = fsp->lease->lease.lease_state,
2071 .lease_version = fsp->lease->lease.lease_version,
2072 .epoch = fsp->lease->lease.lease_epoch,
2075 status = leases_db_add(client_guid,
2078 fsp->conn->connectpath,
2079 fsp->fsp_name->base_name,
2080 fsp->fsp_name->stream_name);
2081 if (!NT_STATUS_IS_OK(status)) {
2082 DEBUG(10, ("%s: leases_db_add failed: %s\n", __func__,
2083 nt_errstr(status)));
2084 TALLOC_FREE(fsp->lease);
2085 return NT_STATUS_INSUFFICIENT_RESOURCES;
2091 return NT_STATUS_OK;
2094 static bool is_same_lease(const files_struct *fsp,
2095 const struct share_mode_data *d,
2096 const struct share_mode_entry *e,
2097 const struct smb2_lease *lease)
2099 if (e->op_type != LEASE_OPLOCK) {
2102 if (lease == NULL) {
2106 return smb2_lease_equal(fsp_client_guid(fsp),
2108 &d->leases[e->lease_idx].client_guid,
2109 &d->leases[e->lease_idx].lease_key);
2112 static NTSTATUS grant_fsp_oplock_type(struct smb_request *req,
2113 struct files_struct *fsp,
2114 struct share_mode_lock *lck,
2116 struct smb2_lease *lease)
2118 struct share_mode_data *d = lck->data;
2119 bool got_handle_lease = false;
2120 bool got_oplock = false;
2123 uint32_t lease_idx = UINT32_MAX;
2127 if (oplock_request & INTERNAL_OPEN_ONLY) {
2128 /* No oplocks on internal open. */
2129 oplock_request = NO_OPLOCK;
2130 DEBUG(10,("grant_fsp_oplock_type: oplock type 0x%x on file %s\n",
2131 fsp->oplock_type, fsp_str_dbg(fsp)));
2134 if (oplock_request == LEASE_OPLOCK) {
2135 if (lease == NULL) {
2137 * The SMB2 layer should have checked this
2139 return NT_STATUS_INTERNAL_ERROR;
2142 granted = lease->lease_state;
2144 if (lp_kernel_oplocks(SNUM(fsp->conn))) {
2145 DEBUG(10, ("No lease granted because kernel oplocks are enabled\n"));
2146 granted = SMB2_LEASE_NONE;
2148 if ((granted & (SMB2_LEASE_READ|SMB2_LEASE_WRITE)) == 0) {
2149 DEBUG(10, ("No read or write lease requested\n"));
2150 granted = SMB2_LEASE_NONE;
2152 if (granted == SMB2_LEASE_WRITE) {
2153 DEBUG(10, ("pure write lease requested\n"));
2154 granted = SMB2_LEASE_NONE;
2156 if (granted == (SMB2_LEASE_WRITE|SMB2_LEASE_HANDLE)) {
2157 DEBUG(10, ("write and handle lease requested\n"));
2158 granted = SMB2_LEASE_NONE;
2161 granted = map_oplock_to_lease_type(
2162 oplock_request & ~SAMBA_PRIVATE_OPLOCK_MASK);
2165 if (lp_locking(fsp->conn->params) && file_has_brlocks(fsp)) {
2166 DEBUG(10,("grant_fsp_oplock_type: file %s has byte range locks\n",
2168 granted &= ~SMB2_LEASE_READ;
2171 for (i=0; i<d->num_share_modes; i++) {
2172 struct share_mode_entry *e = &d->share_modes[i];
2173 uint32_t e_lease_type;
2175 e_lease_type = get_lease_type(d, e);
2177 if ((granted & SMB2_LEASE_WRITE) &&
2178 !is_same_lease(fsp, d, e, lease) &&
2179 !share_mode_stale_pid(d, i)) {
2181 * Can grant only one writer
2183 granted &= ~SMB2_LEASE_WRITE;
2186 if ((e_lease_type & SMB2_LEASE_HANDLE) && !got_handle_lease &&
2187 !share_mode_stale_pid(d, i)) {
2188 got_handle_lease = true;
2191 if ((e->op_type != LEASE_OPLOCK) && !got_oplock &&
2192 !share_mode_stale_pid(d, i)) {
2197 if ((granted & SMB2_LEASE_READ) && !(granted & SMB2_LEASE_WRITE)) {
2199 (global_client_caps & CAP_LEVEL_II_OPLOCKS) &&
2200 lp_level2_oplocks(SNUM(fsp->conn));
2202 if (!allow_level2) {
2203 granted = SMB2_LEASE_NONE;
2207 if (oplock_request == LEASE_OPLOCK) {
2209 granted &= ~SMB2_LEASE_HANDLE;
2212 fsp->oplock_type = LEASE_OPLOCK;
2214 status = grant_fsp_lease(fsp, lck, lease, &lease_idx,
2216 if (!NT_STATUS_IS_OK(status)) {
2220 *lease = fsp->lease->lease;
2221 DEBUG(10, ("lease_state=%d\n", lease->lease_state));
2223 if (got_handle_lease) {
2224 granted = SMB2_LEASE_NONE;
2228 case SMB2_LEASE_READ|SMB2_LEASE_WRITE|SMB2_LEASE_HANDLE:
2229 fsp->oplock_type = BATCH_OPLOCK|EXCLUSIVE_OPLOCK;
2231 case SMB2_LEASE_READ|SMB2_LEASE_WRITE:
2232 fsp->oplock_type = EXCLUSIVE_OPLOCK;
2234 case SMB2_LEASE_READ|SMB2_LEASE_HANDLE:
2235 case SMB2_LEASE_READ:
2236 fsp->oplock_type = LEVEL_II_OPLOCK;
2239 fsp->oplock_type = NO_OPLOCK;
2243 status = set_file_oplock(fsp);
2244 if (!NT_STATUS_IS_OK(status)) {
2246 * Could not get the kernel oplock
2248 fsp->oplock_type = NO_OPLOCK;
2252 ok = set_share_mode(lck, fsp, get_current_uid(fsp->conn),
2257 return NT_STATUS_NO_MEMORY;
2260 ok = update_num_read_oplocks(fsp, lck);
2262 del_share_mode(lck, fsp);
2263 return NT_STATUS_INTERNAL_ERROR;
2266 DEBUG(10,("grant_fsp_oplock_type: oplock type 0x%x on file %s\n",
2267 fsp->oplock_type, fsp_str_dbg(fsp)));
2269 return NT_STATUS_OK;
2272 static bool request_timed_out(struct timeval request_time,
2273 struct timeval timeout)
2275 struct timeval now, end_time;
2277 end_time = timeval_sum(&request_time, &timeout);
2278 return (timeval_compare(&end_time, &now) < 0);
2281 static struct deferred_open_record *deferred_open_record_create(
2282 bool delayed_for_oplocks,
2286 struct deferred_open_record *record = NULL;
2288 record = talloc(NULL, struct deferred_open_record);
2289 if (record == NULL) {
2293 *record = (struct deferred_open_record) {
2294 .delayed_for_oplocks = delayed_for_oplocks,
2295 .async_open = async_open,
2302 struct defer_open_state {
2303 struct smbXsrv_connection *xconn;
2305 struct file_id file_id;
2306 struct timeval request_time;
2307 struct timeval timeout;
2309 uint32_t lease_type;
2312 static void defer_open_done(struct tevent_req *req);
2315 * Defer an open and watch a locking.tdb record
2317 * This defers an open that gets rescheduled once the locking.tdb record watch
2318 * is triggered by a change to the record.
2320 * It is used to defer opens that triggered an oplock break and for the SMB1
2321 * sharing violation delay.
2323 static void defer_open(struct share_mode_lock *lck,
2324 struct timeval request_time,
2325 struct timeval timeout,
2326 struct smb_request *req,
2327 bool delayed_for_oplocks,
2331 struct deferred_open_record *open_rec = NULL;
2332 struct timeval abs_timeout;
2333 struct defer_open_state *watch_state;
2334 struct tevent_req *watch_req;
2337 abs_timeout = timeval_sum(&request_time, &timeout);
2339 DBG_DEBUG("request time [%s] timeout [%s] mid [%" PRIu64 "] "
2340 "delayed_for_oplocks [%s] kernel_oplock [%s] file_id [%s]\n",
2341 timeval_string(talloc_tos(), &request_time, false),
2342 timeval_string(talloc_tos(), &abs_timeout, false),
2344 delayed_for_oplocks ? "yes" : "no",
2345 kernel_oplock ? "yes" : "no",
2346 file_id_string_tos(&id));
2348 open_rec = deferred_open_record_create(delayed_for_oplocks,
2351 if (open_rec == NULL) {
2353 exit_server("talloc failed");
2356 watch_state = talloc(open_rec, struct defer_open_state);
2357 if (watch_state == NULL) {
2358 exit_server("talloc failed");
2360 watch_state->xconn = req->xconn;
2361 watch_state->mid = req->mid;
2362 watch_state->file_id = lck->data->id;
2363 watch_state->request_time = request_time;
2364 watch_state->timeout = timeout;
2365 watch_state->kernel_oplock = kernel_oplock;
2366 watch_state->lease_type = get_lease_type_from_share_mode(lck->data);
2368 DBG_DEBUG("defering mid %" PRIu64 "\n", req->mid);
2370 watch_req = dbwrap_watched_watch_send(watch_state,
2373 (struct server_id){0});
2374 if (watch_req == NULL) {
2375 exit_server("Could not watch share mode record");
2377 tevent_req_set_callback(watch_req, defer_open_done, watch_state);
2379 ok = tevent_req_set_endtime(watch_req, req->sconn->ev_ctx, abs_timeout);
2381 exit_server("tevent_req_set_endtime failed");
2384 ok = push_deferred_open_message_smb(req, request_time, timeout,
2385 open_rec->id, open_rec);
2388 exit_server("push_deferred_open_message_smb failed");
2392 static void defer_open_done(struct tevent_req *req)
2394 struct defer_open_state *state = tevent_req_callback_data(
2395 req, struct defer_open_state);
2396 struct tevent_req *watch_req = NULL;
2397 struct share_mode_lock *lck = NULL;
2398 bool schedule_req = true;
2399 struct timeval timeout;
2403 status = dbwrap_watched_watch_recv(req, talloc_tos(), NULL, NULL,
2406 if (!NT_STATUS_IS_OK(status)) {
2407 DEBUG(5, ("dbwrap_watched_watch_recv returned %s\n",
2408 nt_errstr(status)));
2410 * Even if it failed, retry anyway. TODO: We need a way to
2411 * tell a re-scheduled open about that error.
2413 if (NT_STATUS_EQUAL(status, NT_STATUS_IO_TIMEOUT) &&
2414 state->kernel_oplock)
2417 * If we reschedule but the kernel oplock is still hold
2418 * we would block in the second open as that will be a
2419 * blocking open attempt.
2421 exit_server("Kernel oplock holder didn't "
2422 "respond to break message");
2426 if (state->kernel_oplock) {
2427 lck = get_existing_share_mode_lock(talloc_tos(), state->file_id);
2429 uint32_t lease_type;
2431 lease_type = get_lease_type_from_share_mode(lck->data);
2433 if ((lease_type != 0) &&
2434 (lease_type == state->lease_type))
2436 DBG_DEBUG("Unchanged lease: %" PRIu32 "\n",
2438 schedule_req = false;
2444 DBG_DEBUG("scheduling mid %" PRIu64 "\n", state->mid);
2446 ok = schedule_deferred_open_message_smb(state->xconn,
2449 exit_server("schedule_deferred_open_message_smb failed");
2456 DBG_DEBUG("Keep waiting for oplock release for [%s/%s%s] "
2457 "mid: %" PRIu64 "\n",
2458 lck->data->servicepath,
2459 lck->data->base_name,
2460 lck->data->stream_name ? lck->data->stream_name : "",
2463 watch_req = dbwrap_watched_watch_send(state,
2464 state->xconn->ev_ctx,
2466 (struct server_id){0});
2467 if (watch_req == NULL) {
2468 exit_server("Could not watch share mode record");
2470 tevent_req_set_callback(watch_req, defer_open_done, state);
2472 timeout = timeval_sum(&state->request_time, &state->timeout);
2473 ok = tevent_req_set_endtime(watch_req, state->xconn->ev_ctx, timeout);
2475 exit_server("tevent_req_set_endtime failed");
2482 * Reschedule an open for immediate execution
2484 static void retry_open(struct timeval request_time,
2485 struct smb_request *req,
2488 struct deferred_open_record *open_rec = NULL;
2491 DBG_DEBUG("request time [%s] mid [%" PRIu64 "] file_id [%s]\n",
2492 timeval_string(talloc_tos(), &request_time, false),
2494 file_id_string_tos(&id));
2496 open_rec = deferred_open_record_create(false, false, id);
2497 if (open_rec == NULL) {
2498 exit_server("talloc failed");
2501 ok = push_deferred_open_message_smb(req,
2507 exit_server("push_deferred_open_message_smb failed");
2510 ok = schedule_deferred_open_message_smb(req->xconn, req->mid);
2512 exit_server("schedule_deferred_open_message_smb failed");
2516 /****************************************************************************
2517 On overwrite open ensure that the attributes match.
2518 ****************************************************************************/
2520 static bool open_match_attributes(connection_struct *conn,
2521 uint32_t old_dos_attr,
2522 uint32_t new_dos_attr,
2523 mode_t existing_unx_mode,
2524 mode_t new_unx_mode,
2525 mode_t *returned_unx_mode)
2527 uint32_t noarch_old_dos_attr, noarch_new_dos_attr;
2529 noarch_old_dos_attr = (old_dos_attr & ~FILE_ATTRIBUTE_ARCHIVE);
2530 noarch_new_dos_attr = (new_dos_attr & ~FILE_ATTRIBUTE_ARCHIVE);
2532 if((noarch_old_dos_attr == 0 && noarch_new_dos_attr != 0) ||
2533 (noarch_old_dos_attr != 0 && ((noarch_old_dos_attr & noarch_new_dos_attr) == noarch_old_dos_attr))) {
2534 *returned_unx_mode = new_unx_mode;
2536 *returned_unx_mode = (mode_t)0;
2539 DEBUG(10,("open_match_attributes: old_dos_attr = 0x%x, "
2540 "existing_unx_mode = 0%o, new_dos_attr = 0x%x "
2541 "returned_unx_mode = 0%o\n",
2542 (unsigned int)old_dos_attr,
2543 (unsigned int)existing_unx_mode,
2544 (unsigned int)new_dos_attr,
2545 (unsigned int)*returned_unx_mode ));
2547 /* If we're mapping SYSTEM and HIDDEN ensure they match. */
2548 if (lp_map_system(SNUM(conn)) || lp_store_dos_attributes(SNUM(conn))) {
2549 if ((old_dos_attr & FILE_ATTRIBUTE_SYSTEM) &&
2550 !(new_dos_attr & FILE_ATTRIBUTE_SYSTEM)) {
2554 if (lp_map_hidden(SNUM(conn)) || lp_store_dos_attributes(SNUM(conn))) {
2555 if ((old_dos_attr & FILE_ATTRIBUTE_HIDDEN) &&
2556 !(new_dos_attr & FILE_ATTRIBUTE_HIDDEN)) {
2563 /****************************************************************************
2564 Special FCB or DOS processing in the case of a sharing violation.
2565 Try and find a duplicated file handle.
2566 ****************************************************************************/
2568 static NTSTATUS fcb_or_dos_open(struct smb_request *req,
2569 connection_struct *conn,
2570 files_struct *fsp_to_dup_into,
2571 const struct smb_filename *smb_fname,
2575 uint32_t access_mask,
2576 uint32_t share_access,
2577 uint32_t create_options)
2581 DEBUG(5,("fcb_or_dos_open: attempting old open semantics for "
2582 "file %s.\n", smb_fname_str_dbg(smb_fname)));
2584 for(fsp = file_find_di_first(conn->sconn, id); fsp;
2585 fsp = file_find_di_next(fsp)) {
2587 DEBUG(10,("fcb_or_dos_open: checking file %s, fd = %d, "
2588 "vuid = %llu, file_pid = %u, private_options = 0x%x "
2589 "access_mask = 0x%x\n", fsp_str_dbg(fsp),
2590 fsp->fh->fd, (unsigned long long)fsp->vuid,
2591 (unsigned int)fsp->file_pid,
2592 (unsigned int)fsp->fh->private_options,
2593 (unsigned int)fsp->access_mask ));
2595 if (fsp != fsp_to_dup_into &&
2596 fsp->fh->fd != -1 &&
2597 fsp->vuid == vuid &&
2598 fsp->file_pid == file_pid &&
2599 (fsp->fh->private_options & (NTCREATEX_OPTIONS_PRIVATE_DENY_DOS |
2600 NTCREATEX_OPTIONS_PRIVATE_DENY_FCB)) &&
2601 (fsp->access_mask & FILE_WRITE_DATA) &&
2602 strequal(fsp->fsp_name->base_name, smb_fname->base_name) &&
2603 strequal(fsp->fsp_name->stream_name,
2604 smb_fname->stream_name)) {
2605 DEBUG(10,("fcb_or_dos_open: file match\n"));
2611 return NT_STATUS_NOT_FOUND;
2614 /* quite an insane set of semantics ... */
2615 if (is_executable(smb_fname->base_name) &&
2616 (fsp->fh->private_options & NTCREATEX_OPTIONS_PRIVATE_DENY_DOS)) {
2617 DEBUG(10,("fcb_or_dos_open: file fail due to is_executable.\n"));
2618 return NT_STATUS_INVALID_PARAMETER;
2621 /* We need to duplicate this fsp. */
2622 return dup_file_fsp(req, fsp, access_mask, share_access,
2623 create_options, fsp_to_dup_into);
2626 static void schedule_defer_open(struct share_mode_lock *lck,
2628 struct timeval request_time,
2629 struct smb_request *req,
2632 /* This is a relative time, added to the absolute
2633 request_time value to get the absolute timeout time.
2634 Note that if this is the second or greater time we enter
2635 this codepath for this particular request mid then
2636 request_time is left as the absolute time of the *first*
2637 time this request mid was processed. This is what allows
2638 the request to eventually time out. */
2640 struct timeval timeout;
2642 /* Normally the smbd we asked should respond within
2643 * OPLOCK_BREAK_TIMEOUT seconds regardless of whether
2644 * the client did, give twice the timeout as a safety
2645 * measure here in case the other smbd is stuck
2646 * somewhere else. */
2648 timeout = timeval_set(OPLOCK_BREAK_TIMEOUT*2, 0);
2650 if (request_timed_out(request_time, timeout)) {
2654 defer_open(lck, request_time, timeout, req, true, kernel_oplock, id);
2657 /****************************************************************************
2658 Reschedule an open call that went asynchronous.
2659 ****************************************************************************/
2661 static void schedule_async_open_timer(struct tevent_context *ev,
2662 struct tevent_timer *te,
2663 struct timeval current_time,
2666 exit_server("async open timeout");
2669 static void schedule_async_open(struct timeval request_time,
2670 struct smb_request *req)
2672 struct deferred_open_record *open_rec = NULL;
2673 struct timeval timeout = timeval_set(20, 0);
2676 if (request_timed_out(request_time, timeout)) {
2680 open_rec = deferred_open_record_create(false, true, (struct file_id){0});
2681 if (open_rec == NULL) {
2682 exit_server("deferred_open_record_create failed");
2685 ok = push_deferred_open_message_smb(req, request_time, timeout,
2686 (struct file_id){0}, open_rec);
2688 exit_server("push_deferred_open_message_smb failed");
2691 open_rec->te = tevent_add_timer(req->sconn->ev_ctx,
2693 timeval_current_ofs(20, 0),
2694 schedule_async_open_timer,
2696 if (open_rec->te == NULL) {
2697 exit_server("tevent_add_timer failed");
2701 /****************************************************************************
2702 Work out what access_mask to use from what the client sent us.
2703 ****************************************************************************/
2705 static NTSTATUS smbd_calculate_maximum_allowed_access(
2706 connection_struct *conn,
2707 const struct smb_filename *smb_fname,
2709 uint32_t *p_access_mask)
2711 struct security_descriptor *sd;
2712 uint32_t access_granted;
2715 if (!use_privs && (get_current_uid(conn) == (uid_t)0)) {
2716 *p_access_mask |= FILE_GENERIC_ALL;
2717 return NT_STATUS_OK;
2720 status = SMB_VFS_GET_NT_ACL(conn, smb_fname,
2726 if (NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
2728 * File did not exist
2730 *p_access_mask = FILE_GENERIC_ALL;
2731 return NT_STATUS_OK;
2733 if (!NT_STATUS_IS_OK(status)) {
2734 DEBUG(10,("Could not get acl on file %s: %s\n",
2735 smb_fname_str_dbg(smb_fname),
2736 nt_errstr(status)));
2737 return NT_STATUS_ACCESS_DENIED;
2741 * If we can access the path to this file, by
2742 * default we have FILE_READ_ATTRIBUTES from the
2743 * containing directory. See the section:
2744 * "Algorithm to Check Access to an Existing File"
2747 * se_file_access_check()
2748 * also takes care of owner WRITE_DAC and READ_CONTROL.
2750 status = se_file_access_check(sd,
2751 get_current_nttok(conn),
2753 (*p_access_mask & ~FILE_READ_ATTRIBUTES),
2758 if (!NT_STATUS_IS_OK(status)) {
2759 DEBUG(10, ("Access denied on file %s: "
2760 "when calculating maximum access\n",
2761 smb_fname_str_dbg(smb_fname)));
2762 return NT_STATUS_ACCESS_DENIED;
2764 *p_access_mask = (access_granted | FILE_READ_ATTRIBUTES);
2766 if (!(access_granted & DELETE_ACCESS)) {
2767 if (can_delete_file_in_directory(conn, smb_fname)) {
2768 *p_access_mask |= DELETE_ACCESS;
2772 return NT_STATUS_OK;
2775 NTSTATUS smbd_calculate_access_mask(connection_struct *conn,
2776 const struct smb_filename *smb_fname,
2778 uint32_t access_mask,
2779 uint32_t *access_mask_out)
2782 uint32_t orig_access_mask = access_mask;
2783 uint32_t rejected_share_access;
2785 if (access_mask & SEC_MASK_INVALID) {
2786 DBG_DEBUG("access_mask [%8x] contains invalid bits\n",
2788 return NT_STATUS_ACCESS_DENIED;
2792 * Convert GENERIC bits to specific bits.
2795 se_map_generic(&access_mask, &file_generic_mapping);
2797 /* Calculate MAXIMUM_ALLOWED_ACCESS if requested. */
2798 if (access_mask & MAXIMUM_ALLOWED_ACCESS) {
2800 status = smbd_calculate_maximum_allowed_access(
2801 conn, smb_fname, use_privs, &access_mask);
2803 if (!NT_STATUS_IS_OK(status)) {
2807 access_mask &= conn->share_access;
2810 rejected_share_access = access_mask & ~(conn->share_access);
2812 if (rejected_share_access) {
2813 DEBUG(10, ("smbd_calculate_access_mask: Access denied on "
2814 "file %s: rejected by share access mask[0x%08X] "
2815 "orig[0x%08X] mapped[0x%08X] reject[0x%08X]\n",
2816 smb_fname_str_dbg(smb_fname),
2818 orig_access_mask, access_mask,
2819 rejected_share_access));
2820 return NT_STATUS_ACCESS_DENIED;
2823 *access_mask_out = access_mask;
2824 return NT_STATUS_OK;
2827 /****************************************************************************
2828 Remove the deferred open entry under lock.
2829 ****************************************************************************/
2831 /****************************************************************************
2832 Return true if this is a state pointer to an asynchronous create.
2833 ****************************************************************************/
2835 bool is_deferred_open_async(const struct deferred_open_record *rec)
2837 return rec->async_open;
2840 static bool clear_ads(uint32_t create_disposition)
2844 switch (create_disposition) {
2845 case FILE_SUPERSEDE:
2846 case FILE_OVERWRITE_IF:
2847 case FILE_OVERWRITE:
2856 static int disposition_to_open_flags(uint32_t create_disposition)
2861 * Currently we're using FILE_SUPERSEDE as the same as
2862 * FILE_OVERWRITE_IF but they really are
2863 * different. FILE_SUPERSEDE deletes an existing file
2864 * (requiring delete access) then recreates it.
2867 switch (create_disposition) {
2868 case FILE_SUPERSEDE:
2869 case FILE_OVERWRITE_IF:
2871 * If file exists replace/overwrite. If file doesn't
2874 ret = O_CREAT|O_TRUNC;
2879 * If file exists open. If file doesn't exist error.
2884 case FILE_OVERWRITE:
2886 * If file exists overwrite. If file doesn't exist
2894 * If file exists error. If file doesn't exist create.
2896 ret = O_CREAT|O_EXCL;
2901 * If file exists open. If file doesn't exist create.
2909 static int calculate_open_access_flags(uint32_t access_mask,
2910 uint32_t private_flags)
2912 bool need_write, need_read;
2915 * Note that we ignore the append flag as append does not
2916 * mean the same thing under DOS and Unix.
2919 need_write = (access_mask & (FILE_WRITE_DATA | FILE_APPEND_DATA));
2924 /* DENY_DOS opens are always underlying read-write on the
2925 file handle, no matter what the requested access mask
2929 ((private_flags & NTCREATEX_OPTIONS_PRIVATE_DENY_DOS) ||
2930 access_mask & (FILE_READ_ATTRIBUTES|FILE_READ_DATA|
2931 FILE_READ_EA|FILE_EXECUTE));
2939 /****************************************************************************
2940 Open a file with a share mode. Passed in an already created files_struct *.
2941 ****************************************************************************/
2943 static NTSTATUS open_file_ntcreate(connection_struct *conn,
2944 struct smb_request *req,
2945 uint32_t access_mask, /* access bits (FILE_READ_DATA etc.) */
2946 uint32_t share_access, /* share constants (FILE_SHARE_READ etc) */
2947 uint32_t create_disposition, /* FILE_OPEN_IF etc. */
2948 uint32_t create_options, /* options such as delete on close. */
2949 uint32_t new_dos_attributes, /* attributes used for new file. */
2950 int oplock_request, /* internal Samba oplock codes. */
2951 struct smb2_lease *lease,
2952 /* Information (FILE_EXISTS etc.) */
2953 uint32_t private_flags, /* Samba specific flags. */
2957 struct smb_filename *smb_fname = fsp->fsp_name;
2960 bool file_existed = VALID_STAT(smb_fname->st);
2961 bool def_acl = False;
2962 bool posix_open = False;
2963 bool new_file_created = False;
2964 bool first_open_attempt = true;
2965 NTSTATUS fsp_open = NT_STATUS_ACCESS_DENIED;
2966 mode_t new_unx_mode = (mode_t)0;
2967 mode_t unx_mode = (mode_t)0;
2969 uint32_t existing_dos_attributes = 0;
2970 struct timeval request_time = timeval_zero();
2971 struct share_mode_lock *lck = NULL;
2972 uint32_t open_access_mask = access_mask;
2975 SMB_STRUCT_STAT saved_stat = smb_fname->st;
2976 struct timespec old_write_time;
2979 if (conn->printer) {
2981 * Printers are handled completely differently.
2982 * Most of the passed parameters are ignored.
2986 *pinfo = FILE_WAS_CREATED;
2989 DEBUG(10, ("open_file_ntcreate: printer open fname=%s\n",
2990 smb_fname_str_dbg(smb_fname)));
2993 DEBUG(0,("open_file_ntcreate: printer open without "
2994 "an SMB request!\n"));
2995 return NT_STATUS_INTERNAL_ERROR;
2998 return print_spool_open(fsp, smb_fname->base_name,
3002 if (!parent_dirname(talloc_tos(), smb_fname->base_name, &parent_dir,
3004 return NT_STATUS_NO_MEMORY;
3007 if (new_dos_attributes & FILE_FLAG_POSIX_SEMANTICS) {
3009 unx_mode = (mode_t)(new_dos_attributes & ~FILE_FLAG_POSIX_SEMANTICS);
3010 new_dos_attributes = 0;
3012 /* Windows allows a new file to be created and
3013 silently removes a FILE_ATTRIBUTE_DIRECTORY
3014 sent by the client. Do the same. */
3016 new_dos_attributes &= ~FILE_ATTRIBUTE_DIRECTORY;
3018 /* We add FILE_ATTRIBUTE_ARCHIVE to this as this mode is only used if the file is
3020 unx_mode = unix_mode(conn, new_dos_attributes | FILE_ATTRIBUTE_ARCHIVE,
3021 smb_fname, parent_dir);
3024 DEBUG(10, ("open_file_ntcreate: fname=%s, dos_attrs=0x%x "
3025 "access_mask=0x%x share_access=0x%x "
3026 "create_disposition = 0x%x create_options=0x%x "
3027 "unix mode=0%o oplock_request=%d private_flags = 0x%x\n",
3028 smb_fname_str_dbg(smb_fname), new_dos_attributes,
3029 access_mask, share_access, create_disposition,
3030 create_options, (unsigned int)unx_mode, oplock_request,
3031 (unsigned int)private_flags));
3034 /* Ensure req == NULL means INTERNAL_OPEN_ONLY */
3035 SMB_ASSERT(((oplock_request & INTERNAL_OPEN_ONLY) != 0));
3037 /* And req != NULL means no INTERNAL_OPEN_ONLY */
3038 SMB_ASSERT(((oplock_request & INTERNAL_OPEN_ONLY) == 0));
3042 * Only non-internal opens can be deferred at all
3046 struct deferred_open_record *open_rec;
3047 if (get_deferred_open_message_state(req,
3050 /* Remember the absolute time of the original
3051 request with this mid. We'll use it later to
3052 see if this has timed out. */
3054 /* If it was an async create retry, the file
3057 if (is_deferred_open_async(open_rec)) {
3058 SET_STAT_INVALID(smb_fname->st);
3059 file_existed = false;
3062 /* Ensure we don't reprocess this message. */
3063 remove_deferred_open_message_smb(req->xconn, req->mid);
3065 first_open_attempt = false;
3070 new_dos_attributes &= SAMBA_ATTRIBUTES_MASK;
3073 * Only use strored DOS attributes for checks
3074 * against requested attributes (below via
3075 * open_match_attributes()), cf bug #11992
3076 * for details. -slow
3080 status = SMB_VFS_GET_DOS_ATTRIBUTES(conn, smb_fname, &attr);
3081 if (NT_STATUS_IS_OK(status)) {
3082 existing_dos_attributes = attr;
3087 /* ignore any oplock requests if oplocks are disabled */
3088 if (!lp_oplocks(SNUM(conn)) ||
3089 IS_VETO_OPLOCK_PATH(conn, smb_fname->base_name)) {
3090 /* Mask off everything except the private Samba bits. */
3091 oplock_request &= SAMBA_PRIVATE_OPLOCK_MASK;
3094 /* this is for OS/2 long file names - say we don't support them */
3095 if (req != NULL && !req->posix_pathnames &&
3096 strstr(smb_fname->base_name,".+,;=[].")) {
3097 /* OS/2 Workplace shell fix may be main code stream in a later
3099 DEBUG(5,("open_file_ntcreate: OS/2 long filenames are not "
3101 if (use_nt_status()) {
3102 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3104 return NT_STATUS_DOS(ERRDOS, ERRcannotopen);
3107 switch( create_disposition ) {
3109 /* If file exists open. If file doesn't exist error. */
3110 if (!file_existed) {
3111 DEBUG(5,("open_file_ntcreate: FILE_OPEN "
3112 "requested for file %s and file "
3114 smb_fname_str_dbg(smb_fname)));
3116 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3120 case FILE_OVERWRITE:
3121 /* If file exists overwrite. If file doesn't exist
3123 if (!file_existed) {
3124 DEBUG(5,("open_file_ntcreate: FILE_OVERWRITE "
3125 "requested for file %s and file "
3127 smb_fname_str_dbg(smb_fname) ));
3129 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3134 /* If file exists error. If file doesn't exist
3137 DEBUG(5,("open_file_ntcreate: FILE_CREATE "
3138 "requested for file %s and file "
3139 "already exists.\n",
3140 smb_fname_str_dbg(smb_fname)));
3141 if (S_ISDIR(smb_fname->st.st_ex_mode)) {
3146 return map_nt_error_from_unix(errno);
3150 case FILE_SUPERSEDE:
3151 case FILE_OVERWRITE_IF:
3155 return NT_STATUS_INVALID_PARAMETER;
3158 flags2 = disposition_to_open_flags(create_disposition);
3160 /* We only care about matching attributes on file exists and
3163 if (!posix_open && file_existed &&
3164 ((create_disposition == FILE_OVERWRITE) ||
3165 (create_disposition == FILE_OVERWRITE_IF))) {
3166 if (!open_match_attributes(conn, existing_dos_attributes,
3168 smb_fname->st.st_ex_mode,
3169 unx_mode, &new_unx_mode)) {
3170 DEBUG(5,("open_file_ntcreate: attributes missmatch "
3171 "for file %s (%x %x) (0%o, 0%o)\n",
3172 smb_fname_str_dbg(smb_fname),
3173 existing_dos_attributes,
3175 (unsigned int)smb_fname->st.st_ex_mode,
3176 (unsigned int)unx_mode ));
3178 return NT_STATUS_ACCESS_DENIED;
3182 status = smbd_calculate_access_mask(conn, smb_fname,
3186 if (!NT_STATUS_IS_OK(status)) {
3187 DEBUG(10, ("open_file_ntcreate: smbd_calculate_access_mask "
3188 "on file %s returned %s\n",
3189 smb_fname_str_dbg(smb_fname), nt_errstr(status)));
3193 open_access_mask = access_mask;
3195 if (flags2 & O_TRUNC) {
3196 open_access_mask |= FILE_WRITE_DATA; /* This will cause oplock breaks. */
3199 DEBUG(10, ("open_file_ntcreate: fname=%s, after mapping "
3200 "access_mask=0x%x\n", smb_fname_str_dbg(smb_fname),
3204 * Note that we ignore the append flag as append does not
3205 * mean the same thing under DOS and Unix.
3208 flags = calculate_open_access_flags(access_mask, private_flags);
3211 * Currently we only look at FILE_WRITE_THROUGH for create options.
3215 if ((create_options & FILE_WRITE_THROUGH) && lp_strict_sync(SNUM(conn))) {
3220 if (posix_open && (access_mask & FILE_APPEND_DATA)) {
3224 if (!posix_open && !CAN_WRITE(conn)) {
3226 * We should really return a permission denied error if either
3227 * O_CREAT or O_TRUNC are set, but for compatibility with
3228 * older versions of Samba we just AND them out.
3230 flags2 &= ~(O_CREAT|O_TRUNC);
3233 if (first_open_attempt && lp_kernel_oplocks(SNUM(conn))) {
3235 * With kernel oplocks the open breaking an oplock
3236 * blocks until the oplock holder has given up the
3237 * oplock or closed the file. We prevent this by first
3238 * trying to open the file with O_NONBLOCK (see "man
3239 * fcntl" on Linux). For the second try, triggered by
3240 * an oplock break response, we do not need this
3243 * This is true under the assumption that only Samba
3244 * requests kernel oplocks. Once someone else like
3245 * NFSv4 starts to use that API, we will have to
3246 * modify this by communicating with the NFSv4 server.
3248 flags2 |= O_NONBLOCK;
3252 * Ensure we can't write on a read-only share or file.
3255 if (flags != O_RDONLY && file_existed &&
3256 (!CAN_WRITE(conn) || IS_DOS_READONLY(existing_dos_attributes))) {
3257 DEBUG(5,("open_file_ntcreate: write access requested for "
3258 "file %s on read only %s\n",
3259 smb_fname_str_dbg(smb_fname),
3260 !CAN_WRITE(conn) ? "share" : "file" ));
3262 return NT_STATUS_ACCESS_DENIED;
3265 fsp->file_id = vfs_file_id_from_sbuf(conn, &smb_fname->st);
3266 fsp->share_access = share_access;
3267 fsp->fh->private_options = private_flags;
3268 fsp->access_mask = open_access_mask; /* We change this to the
3269 * requested access_mask after
3270 * the open is done. */
3272 fsp->posix_flags |= FSP_POSIX_FLAGS_ALL;
3275 if (timeval_is_zero(&request_time)) {
3276 request_time = fsp->open_time;
3280 * Ensure we pay attention to default ACLs on directories if required.
3283 if ((flags2 & O_CREAT) && lp_inherit_acls(SNUM(conn)) &&
3284 (def_acl = directory_has_default_acl(conn, parent_dir))) {
3285 unx_mode = (0777 & lp_create_mask(SNUM(conn)));
3288 DEBUG(4,("calling open_file with flags=0x%X flags2=0x%X mode=0%o, "
3289 "access_mask = 0x%x, open_access_mask = 0x%x\n",
3290 (unsigned int)flags, (unsigned int)flags2,
3291 (unsigned int)unx_mode, (unsigned int)access_mask,
3292 (unsigned int)open_access_mask));
3294 fsp_open = open_file(fsp, conn, req, parent_dir,
3295 flags|flags2, unx_mode, access_mask,
3296 open_access_mask, &new_file_created);
3298 if (NT_STATUS_EQUAL(fsp_open, NT_STATUS_NETWORK_BUSY)) {
3302 * This handles the kernel oplock case:
3304 * the file has an active kernel oplock and the open() returned
3305 * EWOULDBLOCK/EAGAIN which maps to NETWORK_BUSY.
3307 * "Samba locking.tdb oplocks" are handled below after acquiring
3308 * the sharemode lock with get_share_mode_lock().
3310 if (file_existed && S_ISFIFO(fsp->fsp_name->st.st_ex_mode)) {
3311 DEBUG(10, ("FIFO busy\n"));
3312 return NT_STATUS_NETWORK_BUSY;
3315 DEBUG(10, ("Internal open busy\n"));
3316 return NT_STATUS_NETWORK_BUSY;
3320 * From here on we assume this is an oplock break triggered
3323 lck = get_existing_share_mode_lock(talloc_tos(), fsp->file_id);
3325 retry_open(request_time, req, fsp->file_id);
3326 DEBUG(10, ("No share mode lock found after "
3327 "EWOULDBLOCK, retrying sync\n"));
3328 return NT_STATUS_SHARING_VIOLATION;
3331 if (!validate_oplock_types(lck)) {
3332 smb_panic("validate_oplock_types failed");
3335 delay = delay_for_oplock(fsp, 0, lease, lck, false,
3337 first_open_attempt);
3339 schedule_defer_open(lck, fsp->file_id, request_time,
3342 DEBUG(10, ("Sent oplock break request to kernel "
3343 "oplock holder\n"));
3344 return NT_STATUS_SHARING_VIOLATION;
3348 * No oplock from Samba around. Immediately retry with
3351 retry_open(request_time, req, fsp->file_id);
3354 DEBUG(10, ("No Samba oplock around after EWOULDBLOCK. "
3355 "Retrying sync\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 DEBUG(1,("open_file_ntcreate: file %s - dev/ino mismatch. "
3389 "Old (dev=0x%llu, ino =0x%llu). "
3390 "New (dev=0x%llu, ino=0x%llu). Failing open "
3391 " with NT_STATUS_ACCESS_DENIED.\n",
3392 smb_fname_str_dbg(smb_fname),
3393 (unsigned long long)saved_stat.st_ex_dev,
3394 (unsigned long long)saved_stat.st_ex_ino,
3395 (unsigned long long)smb_fname->st.st_ex_dev,
3396 (unsigned long long)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,
3473 request_time, req, false);
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));
3486 /* Check if this can be done with the deny_dos and fcb
3489 (NTCREATEX_OPTIONS_PRIVATE_DENY_DOS|
3490 NTCREATEX_OPTIONS_PRIVATE_DENY_FCB)) {
3492 DEBUG(0, ("DOS open without an SMB "
3496 return NT_STATUS_INTERNAL_ERROR;
3499 /* Use the client requested access mask here,
3500 * not the one we open with. */
3501 status = fcb_or_dos_open(req,
3512 if (NT_STATUS_IS_OK(status)) {
3515 *pinfo = FILE_WAS_OPENED;
3517 return NT_STATUS_OK;
3522 * This next line is a subtlety we need for
3523 * MS-Access. If a file open will fail due to share
3524 * permissions and also for security (access) reasons,
3525 * we need to return the access failed error, not the
3526 * share error. We can't open the file due to kernel
3527 * oplock deadlock (it's possible we failed above on
3528 * the open_mode_check()) so use a userspace check.
3531 if (flags & O_RDWR) {
3532 can_access_mask = FILE_READ_DATA|FILE_WRITE_DATA;
3533 } else if (flags & O_WRONLY) {
3534 can_access_mask = FILE_WRITE_DATA;
3536 can_access_mask = FILE_READ_DATA;
3539 if (((can_access_mask & FILE_WRITE_DATA) &&
3540 !CAN_WRITE(conn)) ||
3541 !NT_STATUS_IS_OK(smbd_check_access_rights(conn,
3544 can_access_mask))) {
3549 * If we're returning a share violation, ensure we
3550 * cope with the braindead 1 second delay (SMB1 only).
3553 if (!(oplock_request & INTERNAL_OPEN_ONLY) &&
3554 !conn->sconn->using_smb2 &&
3555 lp_defer_sharing_violations()) {
3556 struct timeval timeout;
3559 /* this is a hack to speed up torture tests
3561 timeout_usecs = lp_parm_int(SNUM(conn),
3562 "smbd","sharedelay",
3563 SHARING_VIOLATION_USEC_WAIT);
3565 /* This is a relative time, added to the absolute
3566 request_time value to get the absolute timeout time.
3567 Note that if this is the second or greater time we enter
3568 this codepath for this particular request mid then
3569 request_time is left as the absolute time of the *first*
3570 time this request mid was processed. This is what allows
3571 the request to eventually time out. */
3573 timeout = timeval_set(0, timeout_usecs);
3575 if (!request_timed_out(request_time, timeout)) {
3576 defer_open(lck, request_time, timeout, req,
3585 * We have detected a sharing violation here
3586 * so return the correct error code
3588 status = NT_STATUS_SHARING_VIOLATION;
3590 status = NT_STATUS_ACCESS_DENIED;
3595 /* Should we atomically (to the client at least) truncate ? */
3596 if ((!new_file_created) &&
3597 (flags2 & O_TRUNC) &&
3598 (!S_ISFIFO(fsp->fsp_name->st.st_ex_mode))) {
3601 ret = vfs_set_filelen(fsp, 0);
3603 status = map_nt_error_from_unix(errno);
3611 * We have the share entry *locked*.....
3614 /* Delete streams if create_disposition requires it */
3615 if (!new_file_created && clear_ads(create_disposition) &&
3616 !is_ntfs_stream_smb_fname(smb_fname)) {
3617 status = delete_all_streams(conn, smb_fname);
3618 if (!NT_STATUS_IS_OK(status)) {
3625 /* note that we ignore failure for the following. It is
3626 basically a hack for NFS, and NFS will never set one of
3627 these only read them. Nobody but Samba can ever set a deny
3628 mode and we have already checked our more authoritative
3629 locking database for permission to set this deny mode. If
3630 the kernel refuses the operations then the kernel is wrong.
3631 note that GPFS supports it as well - jmcd */
3633 if (fsp->fh->fd != -1 && lp_kernel_share_modes(SNUM(conn))) {
3636 * Beware: streams implementing VFS modules may
3637 * implement streams in a way that fsp will have the
3638 * basefile open in the fsp fd, so lacking a distinct
3639 * fd for the stream kernel_flock will apply on the
3640 * basefile which is wrong. The actual check is
3641 * deffered to the VFS module implementing the
3642 * kernel_flock call.
3644 ret_flock = SMB_VFS_KERNEL_FLOCK(fsp, share_access, access_mask);
3645 if(ret_flock == -1 ){
3650 return NT_STATUS_SHARING_VIOLATION;
3653 fsp->kernel_share_modes_taken = true;
3657 * At this point onwards, we can guarantee that the share entry
3658 * is locked, whether we created the file or not, and that the
3659 * deny mode is compatible with all current opens.
3663 * According to Samba4, SEC_FILE_READ_ATTRIBUTE is always granted,
3664 * but we don't have to store this - just ignore it on access check.
3666 if (conn->sconn->using_smb2) {
3668 * SMB2 doesn't return it (according to Microsoft tests).
3669 * Test Case: TestSuite_ScenarioNo009GrantedAccessTestS0
3670 * File created with access = 0x7 (Read, Write, Delete)
3671 * Query Info on file returns 0x87 (Read, Write, Delete, Read Attributes)
3673 fsp->access_mask = access_mask;
3675 /* But SMB1 does. */
3676 fsp->access_mask = access_mask | FILE_READ_ATTRIBUTES;
3681 * stat opens on existing files don't get oplocks.
3682 * They can get leases.
3684 * Note that we check for stat open on the *open_access_mask*,
3685 * i.e. the access mask we actually used to do the open,
3686 * not the one the client asked for (which is in
3687 * fsp->access_mask). This is due to the fact that
3688 * FILE_OVERWRITE and FILE_OVERWRITE_IF add in O_TRUNC,
3689 * which adds FILE_WRITE_DATA to open_access_mask.
3691 if (is_stat_open(open_access_mask) && lease == NULL) {
3692 oplock_request = NO_OPLOCK;
3696 if (new_file_created) {
3697 info = FILE_WAS_CREATED;
3699 if (flags2 & O_TRUNC) {
3700 info = FILE_WAS_OVERWRITTEN;
3702 info = FILE_WAS_OPENED;
3711 * Setup the oplock info in both the shared memory and
3714 status = grant_fsp_oplock_type(req, fsp, lck, oplock_request, lease);
3715 if (!NT_STATUS_IS_OK(status)) {
3721 /* Handle strange delete on close create semantics. */
3722 if (create_options & FILE_DELETE_ON_CLOSE) {
3724 status = can_set_delete_on_close(fsp, new_dos_attributes);
3726 if (!NT_STATUS_IS_OK(status)) {
3727 /* Remember to delete the mode we just added. */
3728 del_share_mode(lck, fsp);
3733 /* Note that here we set the *inital* delete on close flag,
3734 not the regular one. The magic gets handled in close. */
3735 fsp->initial_delete_on_close = True;
3738 if (info != FILE_WAS_OPENED) {
3739 /* Overwritten files should be initially set as archive */
3740 if ((info == FILE_WAS_OVERWRITTEN && lp_map_archive(SNUM(conn))) ||
3741 lp_store_dos_attributes(SNUM(conn))) {
3743 if (file_set_dosmode(conn, smb_fname,
3744 new_dos_attributes | FILE_ATTRIBUTE_ARCHIVE,
3745 parent_dir, true) == 0) {
3746 unx_mode = smb_fname->st.st_ex_mode;
3752 /* Determine sparse flag. */
3754 /* POSIX opens are sparse by default. */
3755 fsp->is_sparse = true;
3757 fsp->is_sparse = (file_existed &&
3758 (existing_dos_attributes & FILE_ATTRIBUTE_SPARSE));
3762 * Take care of inherited ACLs on created files - if default ACL not
3766 if (!posix_open && new_file_created && !def_acl) {
3768 int saved_errno = errno; /* We might get ENOSYS in the next
3771 if (SMB_VFS_FCHMOD_ACL(fsp, unx_mode) == -1 &&
3773 errno = saved_errno; /* Ignore ENOSYS */
3776 } else if (new_unx_mode) {
3780 /* Attributes need changing. File already existed. */
3783 int saved_errno = errno; /* We might get ENOSYS in the
3785 ret = SMB_VFS_FCHMOD_ACL(fsp, new_unx_mode);
3787 if (ret == -1 && errno == ENOSYS) {
3788 errno = saved_errno; /* Ignore ENOSYS */
3790 DEBUG(5, ("open_file_ntcreate: reset "
3791 "attributes of file %s to 0%o\n",
3792 smb_fname_str_dbg(smb_fname),
3793 (unsigned int)new_unx_mode));
3794 ret = 0; /* Don't do the fchmod below. */
3799 (SMB_VFS_FCHMOD(fsp, new_unx_mode) == -1))
3800 DEBUG(5, ("open_file_ntcreate: failed to reset "
3801 "attributes of file %s to 0%o\n",
3802 smb_fname_str_dbg(smb_fname),
3803 (unsigned int)new_unx_mode));
3808 * Deal with other opens having a modified write time.
3810 struct timespec write_time = get_share_mode_write_time(lck);
3812 if (!null_timespec(write_time)) {
3813 update_stat_ex_mtime(&fsp->fsp_name->st, write_time);
3819 return NT_STATUS_OK;
3822 static NTSTATUS mkdir_internal(connection_struct *conn,
3823 struct smb_filename *smb_dname,
3824 uint32_t file_attributes)
3827 char *parent_dir = NULL;
3829 bool posix_open = false;
3830 bool need_re_stat = false;
3831 uint32_t access_mask = SEC_DIR_ADD_SUBDIR;
3833 if (!CAN_WRITE(conn) || (access_mask & ~(conn->share_access))) {
3834 DEBUG(5,("mkdir_internal: failing share access "
3835 "%s\n", lp_servicename(talloc_tos(), SNUM(conn))));
3836 return NT_STATUS_ACCESS_DENIED;
3839 if (!parent_dirname(talloc_tos(), smb_dname->base_name, &parent_dir,
3841 return NT_STATUS_NO_MEMORY;
3844 if (file_attributes & FILE_FLAG_POSIX_SEMANTICS) {
3846 mode = (mode_t)(file_attributes & ~FILE_FLAG_POSIX_SEMANTICS);
3848 mode = unix_mode(conn, FILE_ATTRIBUTE_DIRECTORY, smb_dname, parent_dir);
3851 status = check_parent_access(conn,
3854 if(!NT_STATUS_IS_OK(status)) {
3855 DEBUG(5,("mkdir_internal: check_parent_access "
3856 "on directory %s for path %s returned %s\n",
3858 smb_dname->base_name,
3859 nt_errstr(status) ));
3863 if (SMB_VFS_MKDIR(conn, smb_dname, mode) != 0) {
3864 return map_nt_error_from_unix(errno);
3867 /* Ensure we're checking for a symlink here.... */
3868 /* We don't want to get caught by a symlink racer. */
3870 if (SMB_VFS_LSTAT(conn, smb_dname) == -1) {
3871 DEBUG(2, ("Could not stat directory '%s' just created: %s\n",
3872 smb_fname_str_dbg(smb_dname), strerror(errno)));
3873 return map_nt_error_from_unix(errno);
3876 if (!S_ISDIR(smb_dname->st.st_ex_mode)) {
3877 DEBUG(0, ("Directory '%s' just created is not a directory !\n",
3878 smb_fname_str_dbg(smb_dname)));
3879 return NT_STATUS_NOT_A_DIRECTORY;
3882 if (lp_store_dos_attributes(SNUM(conn))) {
3884 file_set_dosmode(conn, smb_dname,
3885 file_attributes | FILE_ATTRIBUTE_DIRECTORY,
3890 if (lp_inherit_permissions(SNUM(conn))) {
3891 inherit_access_posix_acl(conn, parent_dir,
3893 need_re_stat = true;
3898 * Check if high bits should have been set,
3899 * then (if bits are missing): add them.
3900 * Consider bits automagically set by UNIX, i.e. SGID bit from parent
3903 if ((mode & ~(S_IRWXU|S_IRWXG|S_IRWXO)) &&
3904 (mode & ~smb_dname->st.st_ex_mode)) {
3905 SMB_VFS_CHMOD(conn, smb_dname,
3906 (smb_dname->st.st_ex_mode |
3907 (mode & ~smb_dname->st.st_ex_mode)));
3908 need_re_stat = true;
3912 /* Change the owner if required. */
3913 if (lp_inherit_owner(SNUM(conn)) != INHERIT_OWNER_NO) {
3914 change_dir_owner_to_parent(conn, parent_dir,
3917 need_re_stat = true;
3921 if (SMB_VFS_LSTAT(conn, smb_dname) == -1) {
3922 DEBUG(2, ("Could not stat directory '%s' just created: %s\n",
3923 smb_fname_str_dbg(smb_dname), strerror(errno)));
3924 return map_nt_error_from_unix(errno);
3928 notify_fname(conn, NOTIFY_ACTION_ADDED, FILE_NOTIFY_CHANGE_DIR_NAME,
3929 smb_dname->base_name);
3931 return NT_STATUS_OK;
3934 /****************************************************************************
3935 Open a directory from an NT SMB call.
3936 ****************************************************************************/
3938 static NTSTATUS open_directory(connection_struct *conn,
3939 struct smb_request *req,
3940 struct smb_filename *smb_dname,
3941 uint32_t access_mask,
3942 uint32_t share_access,
3943 uint32_t create_disposition,
3944 uint32_t create_options,
3945 uint32_t file_attributes,
3947 files_struct **result)
3949 files_struct *fsp = NULL;
3950 bool dir_existed = VALID_STAT(smb_dname->st) ? True : False;
3951 struct share_mode_lock *lck = NULL;
3953 struct timespec mtimespec;
3957 if (is_ntfs_stream_smb_fname(smb_dname)) {
3958 DEBUG(2, ("open_directory: %s is a stream name!\n",
3959 smb_fname_str_dbg(smb_dname)));
3960 return NT_STATUS_NOT_A_DIRECTORY;
3963 if (!(file_attributes & FILE_FLAG_POSIX_SEMANTICS)) {
3964 /* Ensure we have a directory attribute. */
3965 file_attributes |= FILE_ATTRIBUTE_DIRECTORY;
3968 DEBUG(5,("open_directory: opening directory %s, access_mask = 0x%x, "
3969 "share_access = 0x%x create_options = 0x%x, "
3970 "create_disposition = 0x%x, file_attributes = 0x%x\n",
3971 smb_fname_str_dbg(smb_dname),
3972 (unsigned int)access_mask,
3973 (unsigned int)share_access,
3974 (unsigned int)create_options,
3975 (unsigned int)create_disposition,
3976 (unsigned int)file_attributes));
3978 status = smbd_calculate_access_mask(conn, smb_dname, false,
3979 access_mask, &access_mask);
3980 if (!NT_STATUS_IS_OK(status)) {
3981 DEBUG(10, ("open_directory: smbd_calculate_access_mask "
3982 "on file %s returned %s\n",
3983 smb_fname_str_dbg(smb_dname),
3984 nt_errstr(status)));
3988 if ((access_mask & SEC_FLAG_SYSTEM_SECURITY) &&
3989 !security_token_has_privilege(get_current_nttok(conn),
3990 SEC_PRIV_SECURITY)) {
3991 DEBUG(10, ("open_directory: open on %s "
3992 "failed - SEC_FLAG_SYSTEM_SECURITY denied.\n",
3993 smb_fname_str_dbg(smb_dname)));
3994 return NT_STATUS_PRIVILEGE_NOT_HELD;
3997 switch( create_disposition ) {
4001 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
4004 info = FILE_WAS_OPENED;
4009 /* If directory exists error. If directory doesn't
4013 status = NT_STATUS_OBJECT_NAME_COLLISION;
4014 DEBUG(2, ("open_directory: unable to create "
4015 "%s. Error was %s\n",
4016 smb_fname_str_dbg(smb_dname),
4017 nt_errstr(status)));
4021 status = mkdir_internal(conn, smb_dname,
4024 if (!NT_STATUS_IS_OK(status)) {
4025 DEBUG(2, ("open_directory: unable to create "
4026 "%s. Error was %s\n",
4027 smb_fname_str_dbg(smb_dname),
4028 nt_errstr(status)));
4032 info = FILE_WAS_CREATED;
4037 * If directory exists open. If directory doesn't
4042 status = NT_STATUS_OK;
4043 info = FILE_WAS_OPENED;
4045 status = mkdir_internal(conn, smb_dname,
4048 if (NT_STATUS_IS_OK(status)) {
4049 info = FILE_WAS_CREATED;
4051 /* Cope with create race. */
4052 if (!NT_STATUS_EQUAL(status,
4053 NT_STATUS_OBJECT_NAME_COLLISION)) {
4054 DEBUG(2, ("open_directory: unable to create "
4055 "%s. Error was %s\n",
4056 smb_fname_str_dbg(smb_dname),
4057 nt_errstr(status)));
4062 * If mkdir_internal() returned
4063 * NT_STATUS_OBJECT_NAME_COLLISION
4064 * we still must lstat the path.
4067 if (SMB_VFS_LSTAT(conn, smb_dname)
4069 DEBUG(2, ("Could not stat "
4070 "directory '%s' just "
4075 return map_nt_error_from_unix(
4079 info = FILE_WAS_OPENED;
4085 case FILE_SUPERSEDE:
4086 case FILE_OVERWRITE:
4087 case FILE_OVERWRITE_IF:
4089 DEBUG(5,("open_directory: invalid create_disposition "
4090 "0x%x for directory %s\n",
4091 (unsigned int)create_disposition,
4092 smb_fname_str_dbg(smb_dname)));
4093 return NT_STATUS_INVALID_PARAMETER;
4096 if(!S_ISDIR(smb_dname->st.st_ex_mode)) {
4097 DEBUG(5,("open_directory: %s is not a directory !\n",
4098 smb_fname_str_dbg(smb_dname)));
4099 return NT_STATUS_NOT_A_DIRECTORY;
4102 if (info == FILE_WAS_OPENED) {
4103 status = smbd_check_access_rights(conn,
4107 if (!NT_STATUS_IS_OK(status)) {
4108 DEBUG(10, ("open_directory: smbd_check_access_rights on "
4109 "file %s failed with %s\n",
4110 smb_fname_str_dbg(smb_dname),
4111 nt_errstr(status)));
4116 status = file_new(req, conn, &fsp);
4117 if(!NT_STATUS_IS_OK(status)) {
4122 * Setup the files_struct for it.
4125 fsp->file_id = vfs_file_id_from_sbuf(conn, &smb_dname->st);
4126 fsp->vuid = req ? req->vuid : UID_FIELD_INVALID;
4127 fsp->file_pid = req ? req->smbpid : 0;
4128 fsp->can_lock = False;
4129 fsp->can_read = False;
4130 fsp->can_write = False;
4132 fsp->share_access = share_access;
4133 fsp->fh->private_options = 0;
4135 * According to Samba4, SEC_FILE_READ_ATTRIBUTE is always granted,
4137 fsp->access_mask = access_mask | FILE_READ_ATTRIBUTES;
4138 fsp->print_file = NULL;
4139 fsp->modified = False;
4140 fsp->oplock_type = NO_OPLOCK;
4141 fsp->sent_oplock_break = NO_BREAK_SENT;
4142 fsp->is_directory = True;
4143 if (file_attributes & FILE_FLAG_POSIX_SEMANTICS) {
4144 fsp->posix_flags |= FSP_POSIX_FLAGS_ALL;
4146 status = fsp_set_smb_fname(fsp, smb_dname);
4147 if (!NT_STATUS_IS_OK(status)) {
4148 file_free(req, fsp);
4152 /* Don't store old timestamps for directory
4153 handles in the internal database. We don't
4154 update them in there if new objects
4155 are creaded in the directory. Currently
4156 we only update timestamps on file writes.
4159 ZERO_STRUCT(mtimespec);
4161 if (access_mask & (FILE_LIST_DIRECTORY|
4163 FILE_ADD_SUBDIRECTORY|
4166 FILE_DELETE_CHILD)) {
4168 status = fd_open(conn, fsp, O_RDONLY|O_DIRECTORY, 0);
4170 /* POSIX allows us to open a directory with O_RDONLY. */
4171 status = fd_open(conn, fsp, O_RDONLY, 0);
4173 if (!NT_STATUS_IS_OK(status)) {
4174 DEBUG(5, ("open_directory: Could not open fd for "
4176 smb_fname_str_dbg(smb_dname),
4177 nt_errstr(status)));
4178 file_free(req, fsp);
4183 DEBUG(10, ("Not opening Directory %s\n",
4184 smb_fname_str_dbg(smb_dname)));
4187 status = vfs_stat_fsp(fsp);
4188 if (!NT_STATUS_IS_OK(status)) {
4190 file_free(req, fsp);
4194 if(!S_ISDIR(fsp->fsp_name->st.st_ex_mode)) {
4195 DEBUG(5,("open_directory: %s is not a directory !\n",
4196 smb_fname_str_dbg(smb_dname)));
4198 file_free(req, fsp);
4199 return NT_STATUS_NOT_A_DIRECTORY;
4202 /* Ensure there was no race condition. We need to check
4203 * dev/inode but not permissions, as these can change
4205 if (!check_same_dev_ino(&smb_dname->st, &fsp->fsp_name->st)) {
4206 DEBUG(5,("open_directory: stat struct differs for "
4208 smb_fname_str_dbg(smb_dname)));
4210 file_free(req, fsp);
4211 return NT_STATUS_ACCESS_DENIED;
4214 lck = get_share_mode_lock(talloc_tos(), fsp->file_id,
4215 conn->connectpath, smb_dname,
4219 DEBUG(0, ("open_directory: Could not get share mode lock for "
4220 "%s\n", smb_fname_str_dbg(smb_dname)));
4222 file_free(req, fsp);
4223 return NT_STATUS_SHARING_VIOLATION;
4226 if (has_delete_on_close(lck, fsp->name_hash)) {
4229 file_free(req, fsp);
4230 return NT_STATUS_DELETE_PENDING;
4233 status = open_mode_check(conn, lck,
4234 access_mask, share_access);
4236 if (!NT_STATUS_IS_OK(status)) {
4239 file_free(req, fsp);
4243 ok = set_share_mode(lck, fsp, get_current_uid(conn),
4244 req ? req->mid : 0, NO_OPLOCK,
4249 file_free(req, fsp);
4250 return NT_STATUS_NO_MEMORY;
4253 /* For directories the delete on close bit at open time seems
4254 always to be honored on close... See test 19 in Samba4 BASE-DELETE. */
4255 if (create_options & FILE_DELETE_ON_CLOSE) {
4256 status = can_set_delete_on_close(fsp, 0);
4257 if (!NT_STATUS_IS_OK(status) && !NT_STATUS_EQUAL(status, NT_STATUS_DIRECTORY_NOT_EMPTY)) {
4258 del_share_mode(lck, fsp);
4261 file_free(req, fsp);
4265 if (NT_STATUS_IS_OK(status)) {
4266 /* Note that here we set the *inital* delete on close flag,
4267 not the regular one. The magic gets handled in close. */
4268 fsp->initial_delete_on_close = True;
4274 * Deal with other opens having a modified write time. Is this
4275 * possible for directories?
4277 struct timespec write_time = get_share_mode_write_time(lck);
4279 if (!null_timespec(write_time)) {
4280 update_stat_ex_mtime(&fsp->fsp_name->st, write_time);
4291 return NT_STATUS_OK;
4294 NTSTATUS create_directory(connection_struct *conn, struct smb_request *req,
4295 struct smb_filename *smb_dname)
4300 status = SMB_VFS_CREATE_FILE(
4303 0, /* root_dir_fid */
4304 smb_dname, /* fname */
4305 FILE_READ_ATTRIBUTES, /* access_mask */
4306 FILE_SHARE_NONE, /* share_access */
4307 FILE_CREATE, /* create_disposition*/
4308 FILE_DIRECTORY_FILE, /* create_options */
4309 FILE_ATTRIBUTE_DIRECTORY, /* file_attributes */
4310 0, /* oplock_request */
4312 0, /* allocation_size */
4313 0, /* private_flags */
4318 NULL, NULL); /* create context */
4320 if (NT_STATUS_IS_OK(status)) {
4321 close_file(req, fsp, NORMAL_CLOSE);
4327 /****************************************************************************
4328 Receive notification that one of our open files has been renamed by another
4330 ****************************************************************************/
4332 void msg_file_was_renamed(struct messaging_context *msg,
4335 struct server_id server_id,
4339 char *frm = (char *)data->data;
4341 const char *sharepath;
4342 const char *base_name;
4343 const char *stream_name;
4344 struct smb_filename *smb_fname = NULL;
4345 size_t sp_len, bn_len;
4347 struct smbd_server_connection *sconn =
4348 talloc_get_type_abort(private_data,
4349 struct smbd_server_connection);
4351 if (data->data == NULL
4352 || data->length < MSG_FILE_RENAMED_MIN_SIZE + 2) {
4353 DEBUG(0, ("msg_file_was_renamed: Got invalid msg len %d\n",
4354 (int)data->length));
4358 /* Unpack the message. */
4359 pull_file_id_24(frm, &id);
4360 sharepath = &frm[24];
4361 sp_len = strlen(sharepath);
4362 base_name = sharepath + sp_len + 1;
4363 bn_len = strlen(base_name);
4364 stream_name = sharepath + sp_len + 1 + bn_len + 1;
4366 /* stream_name must always be NULL if there is no stream. */
4367 if (stream_name[0] == '\0') {
4371 smb_fname = synthetic_smb_fname(talloc_tos(),
4376 if (smb_fname == NULL) {
4380 DEBUG(10,("msg_file_was_renamed: Got rename message for sharepath %s, new name %s, "
4382 sharepath, smb_fname_str_dbg(smb_fname),
4383 file_id_string_tos(&id)));
4385 for(fsp = file_find_di_first(sconn, id); fsp;
4386 fsp = file_find_di_next(fsp)) {
4387 if (memcmp(fsp->conn->connectpath, sharepath, sp_len) == 0) {
4389 DEBUG(10,("msg_file_was_renamed: renaming file %s from %s -> %s\n",
4390 fsp_fnum_dbg(fsp), fsp_str_dbg(fsp),
4391 smb_fname_str_dbg(smb_fname)));
4392 status = fsp_set_smb_fname(fsp, smb_fname);
4393 if (!NT_STATUS_IS_OK(status)) {
4398 /* Now we have the complete path we can work out if this is
4399 actually within this share and adjust newname accordingly. */
4400 DEBUG(10,("msg_file_was_renamed: share mismatch (sharepath %s "
4401 "not sharepath %s) "
4402 "%s from %s -> %s\n",
4403 fsp->conn->connectpath,
4407 smb_fname_str_dbg(smb_fname)));
4411 TALLOC_FREE(smb_fname);
4416 * If a main file is opened for delete, all streams need to be checked for
4417 * !FILE_SHARE_DELETE. Do this by opening with DELETE_ACCESS.
4418 * If that works, delete them all by setting the delete on close and close.
4421 static NTSTATUS open_streams_for_delete(connection_struct *conn,
4422 const struct smb_filename *smb_fname)
4424 struct stream_struct *stream_info = NULL;
4425 files_struct **streams = NULL;
4427 unsigned int num_streams = 0;
4428 TALLOC_CTX *frame = talloc_stackframe();
4431 status = vfs_streaminfo(conn, NULL, smb_fname, talloc_tos(),
4432 &num_streams, &stream_info);
4434 if (NT_STATUS_EQUAL(status, NT_STATUS_NOT_IMPLEMENTED)
4435 || NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
4436 DEBUG(10, ("no streams around\n"));
4438 return NT_STATUS_OK;
4441 if (!NT_STATUS_IS_OK(status)) {
4442 DEBUG(10, ("vfs_streaminfo failed: %s\n",
4443 nt_errstr(status)));
4447 DEBUG(10, ("open_streams_for_delete found %d streams\n",
4450 if (num_streams == 0) {
4452 return NT_STATUS_OK;
4455 streams = talloc_array(talloc_tos(), files_struct *, num_streams);
4456 if (streams == NULL) {
4457 DEBUG(0, ("talloc failed\n"));
4458 status = NT_STATUS_NO_MEMORY;
4462 for (i=0; i<num_streams; i++) {
4463 struct smb_filename *smb_fname_cp;
4465 if (strequal(stream_info[i].name, "::$DATA")) {
4470 smb_fname_cp = synthetic_smb_fname(talloc_tos(),
4471 smb_fname->base_name,
4472 stream_info[i].name,
4475 ~SMB_FILENAME_POSIX_PATH));
4476 if (smb_fname_cp == NULL) {
4477 status = NT_STATUS_NO_MEMORY;
4481 if (SMB_VFS_STAT(conn, smb_fname_cp) == -1) {
4482 DEBUG(10, ("Unable to stat stream: %s\n",
4483 smb_fname_str_dbg(smb_fname_cp)));
4486 status = SMB_VFS_CREATE_FILE(
4489 0, /* root_dir_fid */
4490 smb_fname_cp, /* fname */
4491 DELETE_ACCESS, /* access_mask */
4492 (FILE_SHARE_READ | /* share_access */
4493 FILE_SHARE_WRITE | FILE_SHARE_DELETE),
4494 FILE_OPEN, /* create_disposition*/
4495 0, /* create_options */
4496 FILE_ATTRIBUTE_NORMAL, /* file_attributes */
4497 0, /* oplock_request */
4499 0, /* allocation_size */
4500 NTCREATEX_OPTIONS_PRIVATE_STREAM_DELETE, /* private_flags */
4503 &streams[i], /* result */
4505 NULL, NULL); /* create context */
4507 if (!NT_STATUS_IS_OK(status)) {
4508 DEBUG(10, ("Could not open stream %s: %s\n",
4509 smb_fname_str_dbg(smb_fname_cp),
4510 nt_errstr(status)));
4512 TALLOC_FREE(smb_fname_cp);
4515 TALLOC_FREE(smb_fname_cp);
4519 * don't touch the variable "status" beyond this point :-)
4522 for (i -= 1 ; i >= 0; i--) {
4523 if (streams[i] == NULL) {
4527 DEBUG(10, ("Closing stream # %d, %s\n", i,
4528 fsp_str_dbg(streams[i])));
4529 close_file(NULL, streams[i], NORMAL_CLOSE);
4537 /*********************************************************************
4538 Create a default ACL by inheriting from the parent. If no inheritance
4539 from the parent available, don't set anything. This will leave the actual
4540 permissions the new file or directory already got from the filesystem
4541 as the NT ACL when read.
4542 *********************************************************************/
4544 static NTSTATUS inherit_new_acl(files_struct *fsp)
4546 TALLOC_CTX *frame = talloc_stackframe();
4547 char *parent_name = NULL;
4548 struct security_descriptor *parent_desc = NULL;
4549 NTSTATUS status = NT_STATUS_OK;
4550 struct security_descriptor *psd = NULL;
4551 const struct dom_sid *owner_sid = NULL;
4552 const struct dom_sid *group_sid = NULL;
4553 uint32_t security_info_sent = (SECINFO_OWNER | SECINFO_GROUP | SECINFO_DACL);
4554 struct security_token *token = fsp->conn->session_info->security_token;
4555 bool inherit_owner =
4556 (lp_inherit_owner(SNUM(fsp->conn)) == INHERIT_OWNER_WINDOWS_AND_UNIX);
4557 bool inheritable_components = false;
4558 bool try_builtin_administrators = false;
4559 const struct dom_sid *BA_U_sid = NULL;
4560 const struct dom_sid *BA_G_sid = NULL;
4561 bool try_system = false;
4562 const struct dom_sid *SY_U_sid = NULL;
4563 const struct dom_sid *SY_G_sid = NULL;
4565 struct smb_filename *parent_smb_fname = NULL;
4567 if (!parent_dirname(frame, fsp->fsp_name->base_name, &parent_name, NULL)) {
4569 return NT_STATUS_NO_MEMORY;
4571 parent_smb_fname = synthetic_smb_fname(talloc_tos(),
4575 fsp->fsp_name->flags);
4577 if (parent_smb_fname == NULL) {
4579 return NT_STATUS_NO_MEMORY;
4582 status = SMB_VFS_GET_NT_ACL(fsp->conn,
4584 (SECINFO_OWNER | SECINFO_GROUP | SECINFO_DACL),
4587 if (!NT_STATUS_IS_OK(status)) {
4592 inheritable_components = sd_has_inheritable_components(parent_desc,
4595 if (!inheritable_components && !inherit_owner) {
4597 /* Nothing to inherit and not setting owner. */
4598 return NT_STATUS_OK;
4601 /* Create an inherited descriptor from the parent. */
4603 if (DEBUGLEVEL >= 10) {
4604 DEBUG(10,("inherit_new_acl: parent acl for %s is:\n",
4605 fsp_str_dbg(fsp) ));
4606 NDR_PRINT_DEBUG(security_descriptor, parent_desc);
4609 /* Inherit from parent descriptor if "inherit owner" set. */
4610 if (inherit_owner) {
4611 owner_sid = parent_desc->owner_sid;
4612 group_sid = parent_desc->group_sid;
4615 if (owner_sid == NULL) {
4616 if (security_token_has_builtin_administrators(token)) {
4617 try_builtin_administrators = true;
4618 } else if (security_token_is_system(token)) {
4619 try_builtin_administrators = true;
4624 if (group_sid == NULL &&
4625 token->num_sids == PRIMARY_GROUP_SID_INDEX)
4627 if (security_token_is_system(token)) {
4628 try_builtin_administrators = true;
4633 if (try_builtin_administrators) {
4638 ok = sids_to_unixids(&global_sid_Builtin_Administrators, 1, &ids);
4642 BA_U_sid = &global_sid_Builtin_Administrators;
4643 BA_G_sid = &global_sid_Builtin_Administrators;
4646 BA_U_sid = &global_sid_Builtin_Administrators;
4649 BA_G_sid = &global_sid_Builtin_Administrators;
4662 ok = sids_to_unixids(&global_sid_System, 1, &ids);
4666 SY_U_sid = &global_sid_System;
4667 SY_G_sid = &global_sid_System;
4670 SY_U_sid = &global_sid_System;
4673 SY_G_sid = &global_sid_System;
4681 if (owner_sid == NULL) {
4682 owner_sid = BA_U_sid;
4685 if (owner_sid == NULL) {
4686 owner_sid = SY_U_sid;
4689 if (group_sid == NULL) {
4690 group_sid = SY_G_sid;
4693 if (try_system && group_sid == NULL) {
4694 group_sid = BA_G_sid;
4697 if (owner_sid == NULL) {
4698 owner_sid = &token->sids[PRIMARY_USER_SID_INDEX];
4700 if (group_sid == NULL) {
4701 if (token->num_sids == PRIMARY_GROUP_SID_INDEX) {
4702 group_sid = &token->sids[PRIMARY_USER_SID_INDEX];
4704 group_sid = &token->sids[PRIMARY_GROUP_SID_INDEX];
4708 status = se_create_child_secdesc(frame,
4715 if (!NT_STATUS_IS_OK(status)) {
4720 /* If inheritable_components == false,
4721 se_create_child_secdesc()
4722 creates a security desriptor with a NULL dacl
4723 entry, but with SEC_DESC_DACL_PRESENT. We need
4724 to remove that flag. */
4726 if (!inheritable_components) {
4727 security_info_sent &= ~SECINFO_DACL;
4728 psd->type &= ~SEC_DESC_DACL_PRESENT;
4731 if (DEBUGLEVEL >= 10) {
4732 DEBUG(10,("inherit_new_acl: child acl for %s is:\n",
4733 fsp_str_dbg(fsp) ));
4734 NDR_PRINT_DEBUG(security_descriptor, psd);
4737 if (inherit_owner) {
4738 /* We need to be root to force this. */
4741 status = SMB_VFS_FSET_NT_ACL(fsp,
4744 if (inherit_owner) {
4752 * If we already have a lease, it must match the new file id. [MS-SMB2]
4753 * 3.3.5.9.8 speaks about INVALID_PARAMETER if an already used lease key is
4754 * used for a different file name.
4757 struct lease_match_state {
4758 /* Input parameters. */
4759 TALLOC_CTX *mem_ctx;
4760 const char *servicepath;
4761 const struct smb_filename *fname;
4764 /* Return parameters. */
4765 uint32_t num_file_ids;
4766 struct file_id *ids;
4767 NTSTATUS match_status;
4770 /*************************************************************
4771 File doesn't exist but this lease key+guid is already in use.
4773 This is only allowable in the dynamic share case where the
4774 service path must be different.
4776 There is a small race condition here in the multi-connection
4777 case where a client sends two create calls on different connections,
4778 where the file doesn't exist and one smbd creates the leases_db
4779 entry first, but this will get fixed by the multichannel cleanup
4780 when all identical client_guids get handled by a single smbd.
4781 **************************************************************/
4783 static void lease_match_parser_new_file(
4785 const struct leases_db_file *files,
4786 struct lease_match_state *state)
4790 for (i = 0; i < num_files; i++) {
4791 const struct leases_db_file *f = &files[i];
4792 if (strequal(state->servicepath, f->servicepath)) {
4793 state->match_status = NT_STATUS_INVALID_PARAMETER;
4798 /* Dynamic share case. Break leases on all other files. */
4799 state->match_status = leases_db_copy_file_ids(state->mem_ctx,
4803 if (!NT_STATUS_IS_OK(state->match_status)) {
4807 state->num_file_ids = num_files;
4808 state->match_status = NT_STATUS_OPLOCK_NOT_GRANTED;
4812 static void lease_match_parser(
4814 const struct leases_db_file *files,
4817 struct lease_match_state *state =
4818 (struct lease_match_state *)private_data;
4821 if (!state->file_existed) {
4823 * Deal with name mismatch or
4824 * possible dynamic share case separately
4825 * to make code clearer.
4827 lease_match_parser_new_file(num_files,
4834 state->match_status = NT_STATUS_OK;
4836 for (i = 0; i < num_files; i++) {
4837 const struct leases_db_file *f = &files[i];
4839 /* Everything should be the same. */
4840 if (!file_id_equal(&state->id, &f->id)) {
4841 /* This should catch all dynamic share cases. */
4842 state->match_status = NT_STATUS_OPLOCK_NOT_GRANTED;
4845 if (!strequal(f->servicepath, state->servicepath)) {
4846 state->match_status = NT_STATUS_INVALID_PARAMETER;
4849 if (!strequal(f->base_name, state->fname->base_name)) {
4850 state->match_status = NT_STATUS_INVALID_PARAMETER;
4853 if (!strequal(f->stream_name, state->fname->stream_name)) {
4854 state->match_status = NT_STATUS_INVALID_PARAMETER;
4859 if (NT_STATUS_IS_OK(state->match_status)) {
4861 * Common case - just opening another handle on a
4862 * file on a non-dynamic share.
4867 if (NT_STATUS_EQUAL(state->match_status, NT_STATUS_INVALID_PARAMETER)) {
4868 /* Mismatched path. Error back to client. */
4873 * File id mismatch. Dynamic share case NT_STATUS_OPLOCK_NOT_GRANTED.
4874 * Don't allow leases.
4877 state->match_status = leases_db_copy_file_ids(state->mem_ctx,
4881 if (!NT_STATUS_IS_OK(state->match_status)) {
4885 state->num_file_ids = num_files;
4886 state->match_status = NT_STATUS_OPLOCK_NOT_GRANTED;
4890 static NTSTATUS lease_match(connection_struct *conn,
4891 struct smb_request *req,
4892 struct smb2_lease_key *lease_key,
4893 const char *servicepath,
4894 const struct smb_filename *fname,
4895 uint16_t *p_version,
4898 struct smbd_server_connection *sconn = req->sconn;
4899 TALLOC_CTX *tos = talloc_tos();
4900 struct lease_match_state state = {
4902 .servicepath = servicepath,
4904 .match_status = NT_STATUS_OK
4909 state.file_existed = VALID_STAT(fname->st);
4910 if (state.file_existed) {
4911 state.id = vfs_file_id_from_sbuf(conn, &fname->st);
4913 memset(&state.id, '\0', sizeof(state.id));
4916 status = leases_db_parse(&sconn->client->connections->smb2.client.guid,
4917 lease_key, lease_match_parser, &state);
4918 if (!NT_STATUS_IS_OK(status)) {
4920 * Not found or error means okay: We can make the lease pass
4922 return NT_STATUS_OK;
4924 if (!NT_STATUS_EQUAL(state.match_status, NT_STATUS_OPLOCK_NOT_GRANTED)) {
4926 * Anything but NT_STATUS_OPLOCK_NOT_GRANTED, let the caller
4929 return state.match_status;
4932 /* We have to break all existing leases. */
4933 for (i = 0; i < state.num_file_ids; i++) {
4934 struct share_mode_lock *lck;
4935 struct share_mode_data *d;
4938 if (file_id_equal(&state.ids[i], &state.id)) {
4939 /* Don't need to break our own file. */
4943 lck = get_existing_share_mode_lock(talloc_tos(), state.ids[i]);
4945 /* Race condition - file already closed. */
4949 for (j=0; j<d->num_share_modes; j++) {
4950 struct share_mode_entry *e = &d->share_modes[j];
4951 uint32_t e_lease_type = get_lease_type(d, e);
4952 struct share_mode_lease *l = NULL;
4954 if (share_mode_stale_pid(d, j)) {
4958 if (e->op_type == LEASE_OPLOCK) {
4959 l = &lck->data->leases[e->lease_idx];
4960 if (!smb2_lease_key_equal(&l->lease_key,
4964 *p_epoch = l->epoch;
4965 *p_version = l->lease_version;
4968 if (e_lease_type == SMB2_LEASE_NONE) {
4972 send_break_message(conn->sconn->msg_ctx, e,
4976 * Windows 7 and 8 lease clients
4977 * are broken in that they will not
4978 * respond to lease break requests
4979 * whilst waiting for an outstanding
4980 * open request on that lease handle
4981 * on the same TCP connection, due
4982 * to holding an internal inode lock.
4984 * This means we can't reschedule
4985 * ourselves here, but must return
4990 * Send the breaks and then return
4991 * SMB2_LEASE_NONE in the lease handle
4992 * to cause them to acknowledge the
4993 * lease break. Consulatation with
4994 * Microsoft engineering confirmed
4995 * this approach is safe.
5002 * Ensure we don't grant anything more so we
5005 return NT_STATUS_OPLOCK_NOT_GRANTED;
5009 * Wrapper around open_file_ntcreate and open_directory
5012 static NTSTATUS create_file_unixpath(connection_struct *conn,
5013 struct smb_request *req,
5014 struct smb_filename *smb_fname,
5015 uint32_t access_mask,
5016 uint32_t share_access,
5017 uint32_t create_disposition,
5018 uint32_t create_options,
5019 uint32_t file_attributes,
5020 uint32_t oplock_request,
5021 struct smb2_lease *lease,
5022 uint64_t allocation_size,
5023 uint32_t private_flags,
5024 struct security_descriptor *sd,
5025 struct ea_list *ea_list,
5027 files_struct **result,
5030 int info = FILE_WAS_OPENED;
5031 files_struct *base_fsp = NULL;
5032 files_struct *fsp = NULL;
5035 DEBUG(10,("create_file_unixpath: access_mask = 0x%x "
5036 "file_attributes = 0x%x, share_access = 0x%x, "
5037 "create_disposition = 0x%x create_options = 0x%x "
5038 "oplock_request = 0x%x private_flags = 0x%x "
5039 "ea_list = 0x%p, sd = 0x%p, "
5041 (unsigned int)access_mask,
5042 (unsigned int)file_attributes,
5043 (unsigned int)share_access,
5044 (unsigned int)create_disposition,
5045 (unsigned int)create_options,
5046 (unsigned int)oplock_request,
5047 (unsigned int)private_flags,
5048 ea_list, sd, smb_fname_str_dbg(smb_fname)));
5050 if (create_options & FILE_OPEN_BY_FILE_ID) {
5051 status = NT_STATUS_NOT_SUPPORTED;
5055 if (create_options & NTCREATEX_OPTIONS_INVALID_PARAM_MASK) {
5056 status = NT_STATUS_INVALID_PARAMETER;
5061 oplock_request |= INTERNAL_OPEN_ONLY;
5064 if (lease != NULL) {
5065 uint16_t epoch = lease->lease_epoch;
5066 uint16_t version = lease->lease_version;
5067 status = lease_match(conn,
5074 if (NT_STATUS_EQUAL(status, NT_STATUS_OPLOCK_NOT_GRANTED)) {
5075 /* Dynamic share file. No leases and update epoch... */
5076 lease->lease_state = SMB2_LEASE_NONE;
5077 lease->lease_epoch = epoch;
5078 lease->lease_version = version;
5079 } else if (!NT_STATUS_IS_OK(status)) {
5084 if ((conn->fs_capabilities & FILE_NAMED_STREAMS)
5085 && (access_mask & DELETE_ACCESS)
5086 && !is_ntfs_stream_smb_fname(smb_fname)) {
5088 * We can't open a file with DELETE access if any of the
5089 * streams is open without FILE_SHARE_DELETE
5091 status = open_streams_for_delete(conn, smb_fname);
5093 if (!NT_STATUS_IS_OK(status)) {
5098 if ((access_mask & SEC_FLAG_SYSTEM_SECURITY) &&
5099 !security_token_has_privilege(get_current_nttok(conn),
5100 SEC_PRIV_SECURITY)) {
5101 DEBUG(10, ("create_file_unixpath: open on %s "
5102 "failed - SEC_FLAG_SYSTEM_SECURITY denied.\n",
5103 smb_fname_str_dbg(smb_fname)));
5104 status = NT_STATUS_PRIVILEGE_NOT_HELD;
5108 if ((conn->fs_capabilities & FILE_NAMED_STREAMS)
5109 && is_ntfs_stream_smb_fname(smb_fname)
5110 && (!(private_flags & NTCREATEX_OPTIONS_PRIVATE_STREAM_DELETE))) {
5111 uint32_t base_create_disposition;
5112 struct smb_filename *smb_fname_base = NULL;
5114 if (create_options & FILE_DIRECTORY_FILE) {
5115 status = NT_STATUS_NOT_A_DIRECTORY;
5119 switch (create_disposition) {
5121 base_create_disposition = FILE_OPEN;
5124 base_create_disposition = FILE_OPEN_IF;
5128 /* Create an smb_filename with stream_name == NULL. */
5129 smb_fname_base = synthetic_smb_fname(talloc_tos(),
5130 smb_fname->base_name,
5134 if (smb_fname_base == NULL) {
5135 status = NT_STATUS_NO_MEMORY;
5139 if (SMB_VFS_STAT(conn, smb_fname_base) == -1) {
5140 DEBUG(10, ("Unable to stat stream: %s\n",
5141 smb_fname_str_dbg(smb_fname_base)));
5144 * https://bugzilla.samba.org/show_bug.cgi?id=10229
5145 * We need to check if the requested access mask
5146 * could be used to open the underlying file (if
5147 * it existed), as we're passing in zero for the
5148 * access mask to the base filename.
5150 status = check_base_file_access(conn,
5154 if (!NT_STATUS_IS_OK(status)) {
5155 DEBUG(10, ("Permission check "
5156 "for base %s failed: "
5157 "%s\n", smb_fname->base_name,
5158 nt_errstr(status)));
5163 /* Open the base file. */
5164 status = create_file_unixpath(conn, NULL, smb_fname_base, 0,
5167 | FILE_SHARE_DELETE,
5168 base_create_disposition,
5169 0, 0, 0, NULL, 0, 0, NULL, NULL,
5171 TALLOC_FREE(smb_fname_base);
5173 if (!NT_STATUS_IS_OK(status)) {
5174 DEBUG(10, ("create_file_unixpath for base %s failed: "
5175 "%s\n", smb_fname->base_name,
5176 nt_errstr(status)));
5179 /* we don't need the low level fd */
5184 * If it's a request for a directory open, deal with it separately.
5187 if (create_options & FILE_DIRECTORY_FILE) {
5189 if (create_options & FILE_NON_DIRECTORY_FILE) {
5190 status = NT_STATUS_INVALID_PARAMETER;
5194 /* Can't open a temp directory. IFS kit test. */
5195 if (!(file_attributes & FILE_FLAG_POSIX_SEMANTICS) &&
5196 (file_attributes & FILE_ATTRIBUTE_TEMPORARY)) {
5197 status = NT_STATUS_INVALID_PARAMETER;
5202 * We will get a create directory here if the Win32
5203 * app specified a security descriptor in the
5204 * CreateDirectory() call.
5208 status = open_directory(
5209 conn, req, smb_fname, access_mask, share_access,
5210 create_disposition, create_options, file_attributes,
5215 * Ordinary file case.
5218 status = file_new(req, conn, &fsp);
5219 if(!NT_STATUS_IS_OK(status)) {
5223 status = fsp_set_smb_fname(fsp, smb_fname);
5224 if (!NT_STATUS_IS_OK(status)) {
5230 * We're opening the stream element of a
5231 * base_fsp we already opened. Set up the
5234 fsp->base_fsp = base_fsp;
5237 if (allocation_size) {
5238 fsp->initial_allocation_size = smb_roundup(fsp->conn,
5242 status = open_file_ntcreate(conn,
5255 if(!NT_STATUS_IS_OK(status)) {
5256 file_free(req, fsp);
5260 if (NT_STATUS_EQUAL(status, NT_STATUS_FILE_IS_A_DIRECTORY)) {
5262 /* A stream open never opens a directory */
5265 status = NT_STATUS_FILE_IS_A_DIRECTORY;
5270 * Fail the open if it was explicitly a non-directory
5274 if (create_options & FILE_NON_DIRECTORY_FILE) {
5275 status = NT_STATUS_FILE_IS_A_DIRECTORY;
5280 status = open_directory(
5281 conn, req, smb_fname, access_mask,
5282 share_access, create_disposition,
5283 create_options, file_attributes,
5288 if (!NT_STATUS_IS_OK(status)) {
5292 fsp->base_fsp = base_fsp;
5294 if ((ea_list != NULL) &&
5295 ((info == FILE_WAS_CREATED) || (info == FILE_WAS_OVERWRITTEN))) {
5296 status = set_ea(conn, fsp, fsp->fsp_name, ea_list);
5297 if (!NT_STATUS_IS_OK(status)) {
5302 if (!fsp->is_directory && S_ISDIR(fsp->fsp_name->st.st_ex_mode)) {
5303 status = NT_STATUS_ACCESS_DENIED;
5307 /* Save the requested allocation size. */
5308 if ((info == FILE_WAS_CREATED) || (info == FILE_WAS_OVERWRITTEN)) {
5309 if ((allocation_size > fsp->fsp_name->st.st_ex_size)
5310 && !(fsp->is_directory))
5312 fsp->initial_allocation_size = smb_roundup(
5313 fsp->conn, allocation_size);
5314 if (vfs_allocate_file_space(
5315 fsp, fsp->initial_allocation_size) == -1) {
5316 status = NT_STATUS_DISK_FULL;
5320 fsp->initial_allocation_size = smb_roundup(
5321 fsp->conn, (uint64_t)fsp->fsp_name->st.st_ex_size);
5324 fsp->initial_allocation_size = 0;
5327 if ((info == FILE_WAS_CREATED) && lp_nt_acl_support(SNUM(conn)) &&
5328 fsp->base_fsp == NULL) {
5331 * According to the MS documentation, the only time the security
5332 * descriptor is applied to the opened file is iff we *created* the
5333 * file; an existing file stays the same.
5335 * Also, it seems (from observation) that you can open the file with
5336 * any access mask but you can still write the sd. We need to override
5337 * the granted access before we call set_sd
5338 * Patch for bug #2242 from Tom Lackemann <cessnatomny@yahoo.com>.
5341 uint32_t sec_info_sent;
5342 uint32_t saved_access_mask = fsp->access_mask;
5344 sec_info_sent = get_sec_info(sd);
5346 fsp->access_mask = FILE_GENERIC_ALL;
5348 if (sec_info_sent & (SECINFO_OWNER|
5352 status = set_sd(fsp, sd, sec_info_sent);
5355 fsp->access_mask = saved_access_mask;
5357 if (!NT_STATUS_IS_OK(status)) {
5360 } else if (lp_inherit_acls(SNUM(conn))) {
5361 /* Inherit from parent. Errors here are not fatal. */
5362 status = inherit_new_acl(fsp);
5363 if (!NT_STATUS_IS_OK(status)) {
5364 DEBUG(10,("inherit_new_acl: failed for %s with %s\n",
5366 nt_errstr(status) ));
5371 if ((conn->fs_capabilities & FILE_FILE_COMPRESSION)
5372 && (create_options & FILE_NO_COMPRESSION)
5373 && (info == FILE_WAS_CREATED)) {
5374 status = SMB_VFS_SET_COMPRESSION(conn, fsp, fsp,
5375 COMPRESSION_FORMAT_NONE);
5376 if (!NT_STATUS_IS_OK(status)) {
5377 DEBUG(1, ("failed to disable compression: %s\n",
5378 nt_errstr(status)));
5382 DEBUG(10, ("create_file_unixpath: info=%d\n", info));
5385 if (pinfo != NULL) {
5389 smb_fname->st = fsp->fsp_name->st;
5391 return NT_STATUS_OK;
5394 DEBUG(10, ("create_file_unixpath: %s\n", nt_errstr(status)));
5397 if (base_fsp && fsp->base_fsp == base_fsp) {
5399 * The close_file below will close
5404 close_file(req, fsp, ERROR_CLOSE);
5407 if (base_fsp != NULL) {
5408 close_file(req, base_fsp, ERROR_CLOSE);
5415 * Calculate the full path name given a relative fid.
5417 NTSTATUS get_relative_fid_filename(connection_struct *conn,
5418 struct smb_request *req,
5419 uint16_t root_dir_fid,
5420 const struct smb_filename *smb_fname,
5421 struct smb_filename **smb_fname_out)
5423 files_struct *dir_fsp;
5424 char *parent_fname = NULL;
5425 char *new_base_name = NULL;
5426 uint32_t ucf_flags = ucf_flags_from_smb_request(req);
5429 if (root_dir_fid == 0 || !smb_fname) {
5430 status = NT_STATUS_INTERNAL_ERROR;
5434 dir_fsp = file_fsp(req, root_dir_fid);
5436 if (dir_fsp == NULL) {
5437 status = NT_STATUS_INVALID_HANDLE;
5441 if (is_ntfs_stream_smb_fname(dir_fsp->fsp_name)) {
5442 status = NT_STATUS_INVALID_HANDLE;
5446 if (!dir_fsp->is_directory) {
5449 * Check to see if this is a mac fork of some kind.
5452 if ((conn->fs_capabilities & FILE_NAMED_STREAMS) &&
5453 is_ntfs_stream_smb_fname(smb_fname)) {
5454 status = NT_STATUS_OBJECT_PATH_NOT_FOUND;
5459 we need to handle the case when we get a
5460 relative open relative to a file and the
5461 pathname is blank - this is a reopen!
5462 (hint from demyn plantenberg)
5465 status = NT_STATUS_INVALID_HANDLE;
5469 if (ISDOT(dir_fsp->fsp_name->base_name)) {
5471 * We're at the toplevel dir, the final file name
5472 * must not contain ./, as this is filtered out
5473 * normally by srvstr_get_path and unix_convert
5474 * explicitly rejects paths containing ./.
5476 parent_fname = talloc_strdup(talloc_tos(), "");
5477 if (parent_fname == NULL) {
5478 status = NT_STATUS_NO_MEMORY;
5482 size_t dir_name_len = strlen(dir_fsp->fsp_name->base_name);
5485 * Copy in the base directory name.
5488 parent_fname = talloc_array(talloc_tos(), char,
5490 if (parent_fname == NULL) {
5491 status = NT_STATUS_NO_MEMORY;
5494 memcpy(parent_fname, dir_fsp->fsp_name->base_name,
5498 * Ensure it ends in a '/'.
5499 * We used TALLOC_SIZE +2 to add space for the '/'.
5503 && (parent_fname[dir_name_len-1] != '\\')
5504 && (parent_fname[dir_name_len-1] != '/')) {
5505 parent_fname[dir_name_len] = '/';
5506 parent_fname[dir_name_len+1] = '\0';
5510 new_base_name = talloc_asprintf(talloc_tos(), "%s%s", parent_fname,
5511 smb_fname->base_name);
5512 if (new_base_name == NULL) {
5513 status = NT_STATUS_NO_MEMORY;
5517 status = filename_convert(req,
5523 if (!NT_STATUS_IS_OK(status)) {
5528 TALLOC_FREE(parent_fname);
5529 TALLOC_FREE(new_base_name);
5533 NTSTATUS create_file_default(connection_struct *conn,
5534 struct smb_request *req,
5535 uint16_t root_dir_fid,
5536 struct smb_filename *smb_fname,
5537 uint32_t access_mask,
5538 uint32_t share_access,
5539 uint32_t create_disposition,
5540 uint32_t create_options,
5541 uint32_t file_attributes,
5542 uint32_t oplock_request,
5543 struct smb2_lease *lease,
5544 uint64_t allocation_size,
5545 uint32_t private_flags,
5546 struct security_descriptor *sd,
5547 struct ea_list *ea_list,
5548 files_struct **result,
5550 const struct smb2_create_blobs *in_context_blobs,
5551 struct smb2_create_blobs *out_context_blobs)
5553 int info = FILE_WAS_OPENED;
5554 files_struct *fsp = NULL;
5556 bool stream_name = false;
5558 DEBUG(10,("create_file: access_mask = 0x%x "
5559 "file_attributes = 0x%x, share_access = 0x%x, "
5560 "create_disposition = 0x%x create_options = 0x%x "
5561 "oplock_request = 0x%x "
5562 "private_flags = 0x%x "
5563 "root_dir_fid = 0x%x, ea_list = 0x%p, sd = 0x%p, "
5565 (unsigned int)access_mask,
5566 (unsigned int)file_attributes,
5567 (unsigned int)share_access,
5568 (unsigned int)create_disposition,
5569 (unsigned int)create_options,
5570 (unsigned int)oplock_request,
5571 (unsigned int)private_flags,
5572 (unsigned int)root_dir_fid,
5573 ea_list, sd, smb_fname_str_dbg(smb_fname)));
5576 * Calculate the filename from the root_dir_if if necessary.
5579 if (root_dir_fid != 0) {
5580 struct smb_filename *smb_fname_out = NULL;
5581 status = get_relative_fid_filename(conn, req, root_dir_fid,
5582 smb_fname, &smb_fname_out);
5583 if (!NT_STATUS_IS_OK(status)) {
5586 smb_fname = smb_fname_out;
5590 * Check to see if this is a mac fork of some kind.
5593 stream_name = is_ntfs_stream_smb_fname(smb_fname);
5595 enum FAKE_FILE_TYPE fake_file_type;
5597 fake_file_type = is_fake_file(smb_fname);
5599 if (fake_file_type != FAKE_FILE_TYPE_NONE) {
5602 * Here we go! support for changing the disk quotas
5605 * We need to fake up to open this MAGIC QUOTA file
5606 * and return a valid FID.
5608 * w2k close this file directly after openening xp
5609 * also tries a QUERY_FILE_INFO on the file and then
5612 status = open_fake_file(req, conn, req->vuid,
5613 fake_file_type, smb_fname,
5615 if (!NT_STATUS_IS_OK(status)) {
5619 ZERO_STRUCT(smb_fname->st);
5623 if (!(conn->fs_capabilities & FILE_NAMED_STREAMS)) {
5624 status = NT_STATUS_OBJECT_NAME_NOT_FOUND;
5629 if (is_ntfs_default_stream_smb_fname(smb_fname)) {
5631 smb_fname->stream_name = NULL;
5632 /* We have to handle this error here. */
5633 if (create_options & FILE_DIRECTORY_FILE) {
5634 status = NT_STATUS_NOT_A_DIRECTORY;
5637 if (req != NULL && req->posix_pathnames) {
5638 ret = SMB_VFS_LSTAT(conn, smb_fname);
5640 ret = SMB_VFS_STAT(conn, smb_fname);
5643 if (ret == 0 && VALID_STAT_OF_DIR(smb_fname->st)) {
5644 status = NT_STATUS_FILE_IS_A_DIRECTORY;
5649 status = create_file_unixpath(
5650 conn, req, smb_fname, access_mask, share_access,
5651 create_disposition, create_options, file_attributes,
5652 oplock_request, lease, allocation_size, private_flags,
5656 if (!NT_STATUS_IS_OK(status)) {
5661 DEBUG(10, ("create_file: info=%d\n", info));
5664 if (pinfo != NULL) {
5667 return NT_STATUS_OK;
5670 DEBUG(10, ("create_file: %s\n", nt_errstr(status)));
5673 close_file(req, fsp, ERROR_CLOSE);