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;
414 struct smb_filename *oldwd_fname = NULL;
415 size_t rootdir_len = 0;
416 char *resolved_name = NULL;
417 bool matched = false;
421 * Ensure we don't get stuck in a symlink loop.
424 if (link_depth >= 20) {
429 /* Allocate space for the link target. */
430 link_target = talloc_array(talloc_tos(), char, PATH_MAX);
431 if (link_target == NULL) {
436 /* Read the link target. */
437 link_len = SMB_VFS_READLINK(conn,
441 if (link_len == -1) {
445 /* Ensure it's at least null terminated. */
446 link_target[link_len] = '\0';
448 /* Convert to an absolute path. */
449 resolved_name = SMB_VFS_REALPATH(conn, link_target);
450 if (resolved_name == NULL) {
455 * We know conn_rootdir starts with '/' and
456 * does not end in '/'. FIXME ! Should we
459 rootdir_len = strlen(conn_rootdir_fname->base_name);
461 matched = (strncmp(conn_rootdir_fname->base_name,
470 * Turn into a path relative to the share root.
472 if (resolved_name[rootdir_len] == '\0') {
473 /* Link to the root of the share. */
474 smb_fname->base_name = talloc_strdup(talloc_tos(), ".");
475 if (smb_fname->base_name == NULL) {
479 } else if (resolved_name[rootdir_len] == '/') {
480 smb_fname->base_name = &resolved_name[rootdir_len+1];
486 oldwd_fname = vfs_GetWd(talloc_tos(), conn);
487 if (oldwd_fname == NULL) {
491 /* Ensure we operate from the root of the share. */
492 if (vfs_ChDir(conn, conn_rootdir_fname) == -1) {
496 /* And do it all again.. */
497 fd = non_widelink_open(conn,
510 SAFE_FREE(resolved_name);
511 TALLOC_FREE(link_target);
512 if (oldwd_fname != NULL) {
513 int ret = vfs_ChDir(conn, oldwd_fname);
515 smb_panic("unable to get back to old directory\n");
517 TALLOC_FREE(oldwd_fname);
519 if (saved_errno != 0) {
525 /****************************************************************************
527 ****************************************************************************/
529 static int non_widelink_open(struct connection_struct *conn,
530 const struct smb_filename *conn_rootdir_fname,
532 struct smb_filename *smb_fname,
535 unsigned int link_depth)
539 struct smb_filename *smb_fname_rel = NULL;
541 struct smb_filename *oldwd_fname = NULL;
542 char *parent_dir = NULL;
543 struct smb_filename parent_dir_fname = {0};
544 const char *final_component = NULL;
546 if (!parent_dirname(talloc_tos(),
547 smb_fname->base_name,
553 parent_dir_fname = (struct smb_filename) { .base_name = parent_dir };
555 oldwd_fname = vfs_GetWd(talloc_tos(), conn);
556 if (oldwd_fname == NULL) {
560 /* Pin parent directory in place. */
561 if (vfs_ChDir(conn, &parent_dir_fname) == -1) {
565 /* Ensure the relative path is below the share. */
566 status = check_reduced_name(conn, parent_dir, final_component);
567 if (!NT_STATUS_IS_OK(status)) {
568 saved_errno = map_errno_from_nt_status(status);
572 smb_fname_rel = synthetic_smb_fname(talloc_tos(),
574 smb_fname->stream_name,
581 struct smb_filename *tmp_name = fsp->fsp_name;
582 fsp->fsp_name = smb_fname_rel;
583 fd = SMB_VFS_OPEN(conn, smb_fname_rel, fsp, flags, mode);
584 fsp->fsp_name = tmp_name;
588 saved_errno = link_errno_convert(errno);
590 * Trying to open a symlink to a directory with O_NOFOLLOW and
591 * O_DIRECTORY can return either of ELOOP and ENOTDIR. So
592 * ENOTDIR really means: might be a symlink, but we're not sure.
593 * In this case, we just assume there's a symlink. If we were
594 * wrong, process_symlink_open() will return EINVAL. We check
595 * this below, and fall back to returning the initial
598 * BUG: https://bugzilla.samba.org/show_bug.cgi?id=12860
600 if (saved_errno == ELOOP || saved_errno == ENOTDIR) {
601 if (fsp->posix_flags & FSP_POSIX_FLAGS_OPEN) {
602 /* Never follow symlinks on posix open. */
605 if (!lp_follow_symlinks(SNUM(conn))) {
606 /* Explicitly no symlinks. */
610 * We may have a symlink. Follow in userspace
611 * to ensure it's under the share definition.
613 fd = process_symlink_open(conn,
621 if (saved_errno == ENOTDIR &&
624 * O_DIRECTORY on neither a directory,
625 * nor a symlink. Just return
626 * saved_errno from initial open()
631 link_errno_convert(errno);
638 TALLOC_FREE(parent_dir);
639 TALLOC_FREE(smb_fname_rel);
641 if (oldwd_fname != NULL) {
642 int ret = vfs_ChDir(conn, oldwd_fname);
644 smb_panic("unable to get back to old directory\n");
646 TALLOC_FREE(oldwd_fname);
648 if (saved_errno != 0) {
654 /****************************************************************************
655 fd support routines - attempt to do a dos_open.
656 ****************************************************************************/
658 NTSTATUS fd_open(struct connection_struct *conn,
663 struct smb_filename *smb_fname = fsp->fsp_name;
664 NTSTATUS status = NT_STATUS_OK;
667 * Never follow symlinks on a POSIX client. The
668 * client should be doing this.
671 if ((fsp->posix_flags & FSP_POSIX_FLAGS_OPEN) || !lp_follow_symlinks(SNUM(conn))) {
675 /* Ensure path is below share definition. */
676 if (!lp_widelinks(SNUM(conn))) {
677 struct smb_filename *conn_rootdir_fname = NULL;
678 const char *conn_rootdir = SMB_VFS_CONNECTPATH(conn,
679 smb_fname->base_name);
682 if (conn_rootdir == NULL) {
683 return NT_STATUS_NO_MEMORY;
685 conn_rootdir_fname = synthetic_smb_fname(talloc_tos(),
690 if (conn_rootdir_fname == NULL) {
691 return NT_STATUS_NO_MEMORY;
695 * Only follow symlinks within a share
698 fsp->fh->fd = non_widelink_open(conn,
705 if (fsp->fh->fd == -1) {
708 TALLOC_FREE(conn_rootdir_fname);
709 if (saved_errno != 0) {
713 fsp->fh->fd = SMB_VFS_OPEN(conn, smb_fname, fsp, flags, mode);
716 if (fsp->fh->fd == -1) {
717 int posix_errno = link_errno_convert(errno);
718 status = map_nt_error_from_unix(posix_errno);
719 if (errno == EMFILE) {
720 static time_t last_warned = 0L;
722 if (time((time_t *) NULL) > last_warned) {
723 DEBUG(0,("Too many open files, unable "
724 "to open more! smbd's max "
726 lp_max_open_files()));
727 last_warned = time((time_t *) NULL);
733 DEBUG(10,("fd_open: name %s, flags = 0%o mode = 0%o, fd = %d. %s\n",
734 smb_fname_str_dbg(smb_fname), flags, (int)mode, fsp->fh->fd,
735 (fsp->fh->fd == -1) ? strerror(errno) : "" ));
740 /****************************************************************************
741 Close the file associated with a fsp.
742 ****************************************************************************/
744 NTSTATUS fd_close(files_struct *fsp)
751 if (fsp->fh->fd == -1) {
752 return NT_STATUS_OK; /* What we used to call a stat open. */
754 if (fsp->fh->ref_count > 1) {
755 return NT_STATUS_OK; /* Shared handle. Only close last reference. */
758 ret = SMB_VFS_CLOSE(fsp);
761 return map_nt_error_from_unix(errno);
766 /****************************************************************************
767 Change the ownership of a file to that of the parent directory.
768 Do this by fd if possible.
769 ****************************************************************************/
771 void change_file_owner_to_parent(connection_struct *conn,
772 const char *inherit_from_dir,
775 struct smb_filename *smb_fname_parent;
778 smb_fname_parent = synthetic_smb_fname(talloc_tos(),
783 if (smb_fname_parent == NULL) {
787 ret = SMB_VFS_STAT(conn, smb_fname_parent);
789 DEBUG(0,("change_file_owner_to_parent: failed to stat parent "
790 "directory %s. Error was %s\n",
791 smb_fname_str_dbg(smb_fname_parent),
793 TALLOC_FREE(smb_fname_parent);
797 if (smb_fname_parent->st.st_ex_uid == fsp->fsp_name->st.st_ex_uid) {
798 /* Already this uid - no need to change. */
799 DEBUG(10,("change_file_owner_to_parent: file %s "
800 "is already owned by uid %d\n",
802 (int)fsp->fsp_name->st.st_ex_uid ));
803 TALLOC_FREE(smb_fname_parent);
808 ret = SMB_VFS_FCHOWN(fsp, smb_fname_parent->st.st_ex_uid, (gid_t)-1);
811 DEBUG(0,("change_file_owner_to_parent: failed to fchown "
812 "file %s to parent directory uid %u. Error "
813 "was %s\n", fsp_str_dbg(fsp),
814 (unsigned int)smb_fname_parent->st.st_ex_uid,
817 DEBUG(10,("change_file_owner_to_parent: changed new file %s to "
818 "parent directory uid %u.\n", fsp_str_dbg(fsp),
819 (unsigned int)smb_fname_parent->st.st_ex_uid));
820 /* Ensure the uid entry is updated. */
821 fsp->fsp_name->st.st_ex_uid = smb_fname_parent->st.st_ex_uid;
824 TALLOC_FREE(smb_fname_parent);
827 static NTSTATUS change_dir_owner_to_parent(connection_struct *conn,
828 const char *inherit_from_dir,
829 struct smb_filename *smb_dname,
830 SMB_STRUCT_STAT *psbuf)
832 struct smb_filename *smb_fname_parent;
833 struct smb_filename *smb_fname_cwd = NULL;
834 struct smb_filename *saved_dir_fname = NULL;
835 TALLOC_CTX *ctx = talloc_tos();
836 NTSTATUS status = NT_STATUS_OK;
839 smb_fname_parent = synthetic_smb_fname(ctx,
844 if (smb_fname_parent == NULL) {
845 return NT_STATUS_NO_MEMORY;
848 ret = SMB_VFS_STAT(conn, smb_fname_parent);
850 status = map_nt_error_from_unix(errno);
851 DEBUG(0,("change_dir_owner_to_parent: failed to stat parent "
852 "directory %s. Error was %s\n",
853 smb_fname_str_dbg(smb_fname_parent),
858 /* We've already done an lstat into psbuf, and we know it's a
859 directory. If we can cd into the directory and the dev/ino
860 are the same then we can safely chown without races as
861 we're locking the directory in place by being in it. This
862 should work on any UNIX (thanks tridge :-). JRA.
865 saved_dir_fname = vfs_GetWd(ctx,conn);
866 if (!saved_dir_fname) {
867 status = map_nt_error_from_unix(errno);
868 DEBUG(0,("change_dir_owner_to_parent: failed to get "
869 "current working directory. Error was %s\n",
874 /* Chdir into the new path. */
875 if (vfs_ChDir(conn, smb_dname) == -1) {
876 status = map_nt_error_from_unix(errno);
877 DEBUG(0,("change_dir_owner_to_parent: failed to change "
878 "current working directory to %s. Error "
879 "was %s\n", smb_dname->base_name, strerror(errno) ));
883 smb_fname_cwd = synthetic_smb_fname(ctx, ".", NULL, NULL, 0);
884 if (smb_fname_cwd == NULL) {
885 status = NT_STATUS_NO_MEMORY;
889 ret = SMB_VFS_STAT(conn, smb_fname_cwd);
891 status = map_nt_error_from_unix(errno);
892 DEBUG(0,("change_dir_owner_to_parent: failed to stat "
893 "directory '.' (%s) Error was %s\n",
894 smb_dname->base_name, strerror(errno)));
898 /* Ensure we're pointing at the same place. */
899 if (smb_fname_cwd->st.st_ex_dev != psbuf->st_ex_dev ||
900 smb_fname_cwd->st.st_ex_ino != psbuf->st_ex_ino) {
901 DEBUG(0,("change_dir_owner_to_parent: "
902 "device/inode on directory %s changed. "
903 "Refusing to chown !\n",
904 smb_dname->base_name ));
905 status = NT_STATUS_ACCESS_DENIED;
909 if (smb_fname_parent->st.st_ex_uid == smb_fname_cwd->st.st_ex_uid) {
910 /* Already this uid - no need to change. */
911 DEBUG(10,("change_dir_owner_to_parent: directory %s "
912 "is already owned by uid %d\n",
913 smb_dname->base_name,
914 (int)smb_fname_cwd->st.st_ex_uid ));
915 status = NT_STATUS_OK;
920 ret = SMB_VFS_LCHOWN(conn,
922 smb_fname_parent->st.st_ex_uid,
926 status = map_nt_error_from_unix(errno);
927 DEBUG(10,("change_dir_owner_to_parent: failed to chown "
928 "directory %s to parent directory uid %u. "
930 smb_dname->base_name,
931 (unsigned int)smb_fname_parent->st.st_ex_uid,
934 DEBUG(10,("change_dir_owner_to_parent: changed ownership of new "
935 "directory %s to parent directory uid %u.\n",
936 smb_dname->base_name,
937 (unsigned int)smb_fname_parent->st.st_ex_uid ));
938 /* Ensure the uid entry is updated. */
939 psbuf->st_ex_uid = smb_fname_parent->st.st_ex_uid;
943 vfs_ChDir(conn, saved_dir_fname);
945 TALLOC_FREE(saved_dir_fname);
946 TALLOC_FREE(smb_fname_parent);
947 TALLOC_FREE(smb_fname_cwd);
951 /****************************************************************************
952 Open a file - returning a guaranteed ATOMIC indication of if the
953 file was created or not.
954 ****************************************************************************/
956 static NTSTATUS fd_open_atomic(struct connection_struct *conn,
962 NTSTATUS status = NT_STATUS_UNSUCCESSFUL;
963 NTSTATUS retry_status;
964 bool file_existed = VALID_STAT(fsp->fsp_name->st);
967 *file_created = false;
969 if (!(flags & O_CREAT)) {
971 * We're not creating the file, just pass through.
973 return fd_open(conn, fsp, flags, mode);
976 if (flags & O_EXCL) {
978 * Fail if already exists, just pass through.
980 status = fd_open(conn, fsp, flags, mode);
983 * Here we've opened with O_CREAT|O_EXCL. If that went
984 * NT_STATUS_OK, we *know* we created this file.
986 *file_created = NT_STATUS_IS_OK(status);
992 * Now it gets tricky. We have O_CREAT, but not O_EXCL.
993 * To know absolutely if we created the file or not,
994 * we can never call O_CREAT without O_EXCL. So if
995 * we think the file existed, try without O_CREAT|O_EXCL.
996 * If we think the file didn't exist, try with
999 * The big problem here is dangling symlinks. Opening
1000 * without O_NOFOLLOW means both bad symlink
1001 * and missing path return -1, ENOENT from open(). As POSIX
1002 * is pathname based it's not possible to tell
1003 * the difference between these two cases in a
1004 * non-racy way, so change to try only two attempts before
1007 * We don't have this problem for the O_NOFOLLOW
1008 * case as it just returns NT_STATUS_OBJECT_PATH_NOT_FOUND
1009 * mapped from the ELOOP POSIX error.
1015 curr_flags &= ~(O_CREAT);
1016 retry_status = NT_STATUS_OBJECT_NAME_NOT_FOUND;
1018 curr_flags |= O_EXCL;
1019 retry_status = NT_STATUS_OBJECT_NAME_COLLISION;
1022 status = fd_open(conn, fsp, curr_flags, mode);
1023 if (NT_STATUS_IS_OK(status)) {
1024 if (!file_existed) {
1025 *file_created = true;
1027 return NT_STATUS_OK;
1029 if (!NT_STATUS_EQUAL(status, retry_status)) {
1036 * Keep file_existed up to date for clarity.
1038 if (NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
1039 file_existed = false;
1040 curr_flags |= O_EXCL;
1041 DBG_DEBUG("file %s did not exist. Retry.\n",
1042 smb_fname_str_dbg(fsp->fsp_name));
1044 file_existed = true;
1045 curr_flags &= ~(O_CREAT);
1046 DBG_DEBUG("file %s existed. Retry.\n",
1047 smb_fname_str_dbg(fsp->fsp_name));
1050 status = fd_open(conn, fsp, curr_flags, mode);
1052 if (NT_STATUS_IS_OK(status) && (!file_existed)) {
1053 *file_created = true;
1059 /****************************************************************************
1061 ****************************************************************************/
1063 static NTSTATUS open_file(files_struct *fsp,
1064 connection_struct *conn,
1065 struct smb_request *req,
1066 const char *parent_dir,
1069 uint32_t access_mask, /* client requested access mask. */
1070 uint32_t open_access_mask, /* what we're actually using in the open. */
1071 bool *p_file_created)
1073 struct smb_filename *smb_fname = fsp->fsp_name;
1074 NTSTATUS status = NT_STATUS_OK;
1075 int accmode = (flags & O_ACCMODE);
1076 int local_flags = flags;
1077 bool file_existed = VALID_STAT(fsp->fsp_name->st);
1082 /* Check permissions */
1085 * This code was changed after seeing a client open request
1086 * containing the open mode of (DENY_WRITE/read-only) with
1087 * the 'create if not exist' bit set. The previous code
1088 * would fail to open the file read only on a read-only share
1089 * as it was checking the flags parameter directly against O_RDONLY,
1090 * this was failing as the flags parameter was set to O_RDONLY|O_CREAT.
1094 if (!CAN_WRITE(conn)) {
1095 /* It's a read-only share - fail if we wanted to write. */
1096 if(accmode != O_RDONLY || (flags & O_TRUNC) || (flags & O_APPEND)) {
1097 DEBUG(3,("Permission denied opening %s\n",
1098 smb_fname_str_dbg(smb_fname)));
1099 return NT_STATUS_ACCESS_DENIED;
1101 if (flags & O_CREAT) {
1102 /* We don't want to write - but we must make sure that
1103 O_CREAT doesn't create the file if we have write
1104 access into the directory.
1106 flags &= ~(O_CREAT|O_EXCL);
1107 local_flags &= ~(O_CREAT|O_EXCL);
1112 * This little piece of insanity is inspired by the
1113 * fact that an NT client can open a file for O_RDONLY,
1114 * but set the create disposition to FILE_EXISTS_TRUNCATE.
1115 * If the client *can* write to the file, then it expects to
1116 * truncate the file, even though it is opening for readonly.
1117 * Quicken uses this stupid trick in backup file creation...
1118 * Thanks *greatly* to "David W. Chapman Jr." <dwcjr@inethouston.net>
1119 * for helping track this one down. It didn't bite us in 2.0.x
1120 * as we always opened files read-write in that release. JRA.
1123 if ((accmode == O_RDONLY) && ((flags & O_TRUNC) == O_TRUNC)) {
1124 DEBUG(10,("open_file: truncate requested on read-only open "
1125 "for file %s\n", smb_fname_str_dbg(smb_fname)));
1126 local_flags = (flags & ~O_ACCMODE)|O_RDWR;
1129 if ((open_access_mask & (FILE_READ_DATA|FILE_WRITE_DATA|FILE_APPEND_DATA|FILE_EXECUTE)) ||
1130 (!file_existed && (local_flags & O_CREAT)) ||
1131 ((local_flags & O_TRUNC) == O_TRUNC) ) {
1135 #if defined(O_NONBLOCK) && defined(S_ISFIFO)
1137 * We would block on opening a FIFO with no one else on the
1138 * other end. Do what we used to do and add O_NONBLOCK to the
1142 if (file_existed && S_ISFIFO(smb_fname->st.st_ex_mode)) {
1143 local_flags &= ~O_TRUNC; /* Can't truncate a FIFO. */
1144 local_flags |= O_NONBLOCK;
1148 /* Don't create files with Microsoft wildcard characters. */
1149 if (fsp->base_fsp) {
1151 * wildcard characters are allowed in stream names
1152 * only test the basefilename
1154 wild = fsp->base_fsp->fsp_name->base_name;
1156 wild = smb_fname->base_name;
1158 if ((local_flags & O_CREAT) && !file_existed &&
1159 !(fsp->posix_flags & FSP_POSIX_FLAGS_PATHNAMES) &&
1160 ms_has_wild(wild)) {
1161 return NT_STATUS_OBJECT_NAME_INVALID;
1164 /* Can we access this file ? */
1165 if (!fsp->base_fsp) {
1166 /* Only do this check on non-stream open. */
1168 status = smbd_check_access_rights(conn,
1173 if (!NT_STATUS_IS_OK(status)) {
1174 DEBUG(10, ("open_file: "
1175 "smbd_check_access_rights "
1176 "on file %s returned %s\n",
1177 smb_fname_str_dbg(smb_fname),
1178 nt_errstr(status)));
1181 if (!NT_STATUS_IS_OK(status) &&
1182 !NT_STATUS_EQUAL(status,
1183 NT_STATUS_OBJECT_NAME_NOT_FOUND))
1188 if (NT_STATUS_EQUAL(status,
1189 NT_STATUS_OBJECT_NAME_NOT_FOUND))
1191 DEBUG(10, ("open_file: "
1192 "file %s vanished since we "
1193 "checked for existence.\n",
1194 smb_fname_str_dbg(smb_fname)));
1195 file_existed = false;
1196 SET_STAT_INVALID(fsp->fsp_name->st);
1200 if (!file_existed) {
1201 if (!(local_flags & O_CREAT)) {
1202 /* File didn't exist and no O_CREAT. */
1203 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
1206 status = check_parent_access(conn,
1209 if (!NT_STATUS_IS_OK(status)) {
1210 DEBUG(10, ("open_file: "
1211 "check_parent_access on "
1212 "file %s returned %s\n",
1213 smb_fname_str_dbg(smb_fname),
1214 nt_errstr(status) ));
1221 * Actually do the open - if O_TRUNC is needed handle it
1222 * below under the share mode lock.
1224 status = fd_open_atomic(conn, fsp, local_flags & ~O_TRUNC,
1225 unx_mode, p_file_created);
1226 if (!NT_STATUS_IS_OK(status)) {
1227 DEBUG(3,("Error opening file %s (%s) (local_flags=%d) "
1228 "(flags=%d)\n", smb_fname_str_dbg(smb_fname),
1229 nt_errstr(status),local_flags,flags));
1233 if (local_flags & O_NONBLOCK) {
1235 * GPFS can return ETIMEDOUT for pread on
1236 * nonblocking file descriptors when files
1237 * migrated to tape need to be recalled. I
1238 * could imagine this happens elsehwere
1239 * too. With blocking file descriptors this
1242 ret = set_blocking(fsp->fh->fd, true);
1244 status = map_nt_error_from_unix(errno);
1245 DBG_WARNING("Could not set fd to blocking: "
1246 "%s\n", strerror(errno));
1252 ret = SMB_VFS_FSTAT(fsp, &smb_fname->st);
1254 /* If we have an fd, this stat should succeed. */
1255 DEBUG(0,("Error doing fstat on open file %s "
1257 smb_fname_str_dbg(smb_fname),
1259 status = map_nt_error_from_unix(errno);
1264 if (*p_file_created) {
1265 /* We created this file. */
1267 bool need_re_stat = false;
1268 /* Do all inheritance work after we've
1269 done a successful fstat call and filled
1270 in the stat struct in fsp->fsp_name. */
1272 /* Inherit the ACL if required */
1273 if (lp_inherit_permissions(SNUM(conn))) {
1274 inherit_access_posix_acl(conn, parent_dir,
1277 need_re_stat = true;
1280 /* Change the owner if required. */
1281 if (lp_inherit_owner(SNUM(conn)) != INHERIT_OWNER_NO) {
1282 change_file_owner_to_parent(conn, parent_dir,
1284 need_re_stat = true;
1288 ret = SMB_VFS_FSTAT(fsp, &smb_fname->st);
1289 /* If we have an fd, this stat should succeed. */
1291 DEBUG(0,("Error doing fstat on open file %s "
1293 smb_fname_str_dbg(smb_fname),
1298 notify_fname(conn, NOTIFY_ACTION_ADDED,
1299 FILE_NOTIFY_CHANGE_FILE_NAME,
1300 smb_fname->base_name);
1303 fsp->fh->fd = -1; /* What we used to call a stat open. */
1304 if (!file_existed) {
1305 /* File must exist for a stat open. */
1306 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
1309 status = smbd_check_access_rights(conn,
1314 if (NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND) &&
1315 (fsp->posix_flags & FSP_POSIX_FLAGS_OPEN) &&
1316 S_ISLNK(smb_fname->st.st_ex_mode)) {
1317 /* This is a POSIX stat open for delete
1318 * or rename on a symlink that points
1319 * nowhere. Allow. */
1320 DEBUG(10,("open_file: allowing POSIX "
1321 "open on bad symlink %s\n",
1322 smb_fname_str_dbg(smb_fname)));
1323 status = NT_STATUS_OK;
1326 if (!NT_STATUS_IS_OK(status)) {
1327 DEBUG(10,("open_file: "
1328 "smbd_check_access_rights on file "
1330 smb_fname_str_dbg(smb_fname),
1331 nt_errstr(status) ));
1337 * POSIX allows read-only opens of directories. We don't
1338 * want to do this (we use a different code path for this)
1339 * so catch a directory open and return an EISDIR. JRA.
1342 if(S_ISDIR(smb_fname->st.st_ex_mode)) {
1345 return NT_STATUS_FILE_IS_A_DIRECTORY;
1348 fsp->file_id = vfs_file_id_from_sbuf(conn, &smb_fname->st);
1349 fsp->vuid = req ? req->vuid : UID_FIELD_INVALID;
1350 fsp->file_pid = req ? req->smbpid : 0;
1351 fsp->can_lock = True;
1352 fsp->can_read = ((access_mask & FILE_READ_DATA) != 0);
1355 ((access_mask & (FILE_WRITE_DATA | FILE_APPEND_DATA)) != 0);
1356 fsp->print_file = NULL;
1357 fsp->modified = False;
1358 fsp->sent_oplock_break = NO_BREAK_SENT;
1359 fsp->is_directory = False;
1360 if (conn->aio_write_behind_list &&
1361 is_in_path(smb_fname->base_name, conn->aio_write_behind_list,
1362 conn->case_sensitive)) {
1363 fsp->aio_write_behind = True;
1366 fsp->wcp = NULL; /* Write cache pointer. */
1368 DEBUG(2,("%s opened file %s read=%s write=%s (numopen=%d)\n",
1369 conn->session_info->unix_info->unix_name,
1370 smb_fname_str_dbg(smb_fname),
1371 BOOLSTR(fsp->can_read), BOOLSTR(fsp->can_write),
1372 conn->num_files_open));
1375 return NT_STATUS_OK;
1378 /****************************************************************************
1379 Check if we can open a file with a share mode.
1380 Returns True if conflict, False if not.
1381 ****************************************************************************/
1383 static bool share_conflict(struct share_mode_entry *entry,
1384 uint32_t access_mask,
1385 uint32_t share_access)
1387 DEBUG(10,("share_conflict: entry->access_mask = 0x%x, "
1388 "entry->share_access = 0x%x, "
1389 "entry->private_options = 0x%x\n",
1390 (unsigned int)entry->access_mask,
1391 (unsigned int)entry->share_access,
1392 (unsigned int)entry->private_options));
1394 if (server_id_is_disconnected(&entry->pid)) {
1396 * note: cleanup should have been done by
1397 * delay_for_batch_oplocks()
1402 DEBUG(10,("share_conflict: access_mask = 0x%x, share_access = 0x%x\n",
1403 (unsigned int)access_mask, (unsigned int)share_access));
1405 if ((entry->access_mask & (FILE_WRITE_DATA|
1409 DELETE_ACCESS)) == 0) {
1410 DEBUG(10,("share_conflict: No conflict due to "
1411 "entry->access_mask = 0x%x\n",
1412 (unsigned int)entry->access_mask ));
1416 if ((access_mask & (FILE_WRITE_DATA|
1420 DELETE_ACCESS)) == 0) {
1421 DEBUG(10,("share_conflict: No conflict due to "
1422 "access_mask = 0x%x\n",
1423 (unsigned int)access_mask ));
1427 #if 1 /* JRA TEST - Superdebug. */
1428 #define CHECK_MASK(num, am, right, sa, share) \
1429 DEBUG(10,("share_conflict: [%d] am (0x%x) & right (0x%x) = 0x%x\n", \
1430 (unsigned int)(num), (unsigned int)(am), \
1431 (unsigned int)(right), (unsigned int)(am)&(right) )); \
1432 DEBUG(10,("share_conflict: [%d] sa (0x%x) & share (0x%x) = 0x%x\n", \
1433 (unsigned int)(num), (unsigned int)(sa), \
1434 (unsigned int)(share), (unsigned int)(sa)&(share) )); \
1435 if (((am) & (right)) && !((sa) & (share))) { \
1436 DEBUG(10,("share_conflict: check %d conflict am = 0x%x, right = 0x%x, \
1437 sa = 0x%x, share = 0x%x\n", (num), (unsigned int)(am), (unsigned int)(right), (unsigned int)(sa), \
1438 (unsigned int)(share) )); \
1442 #define CHECK_MASK(num, am, right, sa, share) \
1443 if (((am) & (right)) && !((sa) & (share))) { \
1444 DEBUG(10,("share_conflict: check %d conflict am = 0x%x, right = 0x%x, \
1445 sa = 0x%x, share = 0x%x\n", (num), (unsigned int)(am), (unsigned int)(right), (unsigned int)(sa), \
1446 (unsigned int)(share) )); \
1451 CHECK_MASK(1, entry->access_mask, FILE_WRITE_DATA | FILE_APPEND_DATA,
1452 share_access, FILE_SHARE_WRITE);
1453 CHECK_MASK(2, access_mask, FILE_WRITE_DATA | FILE_APPEND_DATA,
1454 entry->share_access, FILE_SHARE_WRITE);
1456 CHECK_MASK(3, entry->access_mask, FILE_READ_DATA | FILE_EXECUTE,
1457 share_access, FILE_SHARE_READ);
1458 CHECK_MASK(4, access_mask, FILE_READ_DATA | FILE_EXECUTE,
1459 entry->share_access, FILE_SHARE_READ);
1461 CHECK_MASK(5, entry->access_mask, DELETE_ACCESS,
1462 share_access, FILE_SHARE_DELETE);
1463 CHECK_MASK(6, access_mask, DELETE_ACCESS,
1464 entry->share_access, FILE_SHARE_DELETE);
1466 DEBUG(10,("share_conflict: No conflict.\n"));
1470 #if defined(DEVELOPER)
1471 static void validate_my_share_entries(struct smbd_server_connection *sconn,
1473 struct share_mode_entry *share_entry)
1475 struct server_id self = messaging_server_id(sconn->msg_ctx);
1478 if (!serverid_equal(&self, &share_entry->pid)) {
1482 if (share_entry->op_mid == 0) {
1483 /* INTERNAL_OPEN_ONLY */
1487 if (!is_valid_share_mode_entry(share_entry)) {
1491 fsp = file_find_dif(sconn, share_entry->id,
1492 share_entry->share_file_id);
1494 DEBUG(0,("validate_my_share_entries: PANIC : %s\n",
1495 share_mode_str(talloc_tos(), num, share_entry) ));
1496 smb_panic("validate_my_share_entries: Cannot match a "
1497 "share entry with an open file\n");
1500 if (((uint16_t)fsp->oplock_type) != share_entry->op_type) {
1509 DEBUG(0,("validate_my_share_entries: PANIC : %s\n",
1510 share_mode_str(talloc_tos(), num, share_entry) ));
1511 str = talloc_asprintf(talloc_tos(),
1512 "validate_my_share_entries: "
1513 "file %s, oplock_type = 0x%x, op_type = 0x%x\n",
1514 fsp->fsp_name->base_name,
1515 (unsigned int)fsp->oplock_type,
1516 (unsigned int)share_entry->op_type );
1522 bool is_stat_open(uint32_t access_mask)
1524 const uint32_t stat_open_bits =
1525 (SYNCHRONIZE_ACCESS|
1526 FILE_READ_ATTRIBUTES|
1527 FILE_WRITE_ATTRIBUTES);
1529 return (((access_mask & stat_open_bits) != 0) &&
1530 ((access_mask & ~stat_open_bits) == 0));
1533 static bool has_delete_on_close(struct share_mode_lock *lck,
1536 struct share_mode_data *d = lck->data;
1539 if (d->num_share_modes == 0) {
1542 if (!is_delete_on_close_set(lck, name_hash)) {
1545 for (i=0; i<d->num_share_modes; i++) {
1546 if (!share_mode_stale_pid(d, i)) {
1553 /****************************************************************************
1554 Deal with share modes
1555 Invariant: Share mode must be locked on entry and exit.
1556 Returns -1 on error, or number of share modes on success (may be zero).
1557 ****************************************************************************/
1559 static NTSTATUS open_mode_check(connection_struct *conn,
1560 struct share_mode_lock *lck,
1561 uint32_t access_mask,
1562 uint32_t share_access)
1566 if(lck->data->num_share_modes == 0) {
1567 return NT_STATUS_OK;
1570 if (is_stat_open(access_mask)) {
1571 /* Stat open that doesn't trigger oplock breaks or share mode
1572 * checks... ! JRA. */
1573 return NT_STATUS_OK;
1577 * Check if the share modes will give us access.
1580 #if defined(DEVELOPER)
1581 for(i = 0; i < lck->data->num_share_modes; i++) {
1582 validate_my_share_entries(conn->sconn, i,
1583 &lck->data->share_modes[i]);
1587 /* Now we check the share modes, after any oplock breaks. */
1588 for(i = 0; i < lck->data->num_share_modes; i++) {
1590 if (!is_valid_share_mode_entry(&lck->data->share_modes[i])) {
1594 /* someone else has a share lock on it, check to see if we can
1596 if (share_conflict(&lck->data->share_modes[i],
1597 access_mask, share_access)) {
1599 if (share_mode_stale_pid(lck->data, i)) {
1603 return NT_STATUS_SHARING_VIOLATION;
1607 return NT_STATUS_OK;
1611 * Send a break message to the oplock holder and delay the open for
1615 NTSTATUS send_break_message(struct messaging_context *msg_ctx,
1616 const struct share_mode_entry *exclusive,
1620 char msg[MSG_SMB_SHARE_MODE_ENTRY_SIZE];
1621 struct server_id_buf tmp;
1623 DEBUG(10, ("Sending break request to PID %s\n",
1624 server_id_str_buf(exclusive->pid, &tmp)));
1626 /* Create the message. */
1627 share_mode_entry_to_message(msg, exclusive);
1629 /* Overload entry->op_type */
1631 * This is a cut from uint32_t to uint16_t, but so far only the lower 3
1632 * bits (LEASE_WRITE/HANDLE/READ are used anyway.
1634 SSVAL(msg,OP_BREAK_MSG_OP_TYPE_OFFSET, break_to);
1636 status = messaging_send_buf(msg_ctx, exclusive->pid,
1637 MSG_SMB_BREAK_REQUEST,
1638 (uint8_t *)msg, sizeof(msg));
1639 if (!NT_STATUS_IS_OK(status)) {
1640 DEBUG(3, ("Could not send oplock break message: %s\n",
1641 nt_errstr(status)));
1648 * Do internal consistency checks on the share mode for a file.
1651 static bool validate_oplock_types(struct share_mode_lock *lck)
1653 struct share_mode_data *d = lck->data;
1655 bool ex_or_batch = false;
1656 bool level2 = false;
1657 bool no_oplock = false;
1658 uint32_t num_non_stat_opens = 0;
1661 for (i=0; i<d->num_share_modes; i++) {
1662 struct share_mode_entry *e = &d->share_modes[i];
1664 if (!is_valid_share_mode_entry(e)) {
1668 if (e->op_mid == 0) {
1669 /* INTERNAL_OPEN_ONLY */
1673 if (e->op_type == NO_OPLOCK && is_stat_open(e->access_mask)) {
1674 /* We ignore stat opens in the table - they
1675 always have NO_OPLOCK and never get or
1676 cause breaks. JRA. */
1680 num_non_stat_opens += 1;
1682 if (BATCH_OPLOCK_TYPE(e->op_type)) {
1683 /* batch - can only be one. */
1684 if (share_mode_stale_pid(d, i)) {
1685 DEBUG(10, ("Found stale batch oplock\n"));
1688 if (ex_or_batch || batch || level2 || no_oplock) {
1689 DEBUG(0, ("Bad batch oplock entry %u.",
1696 if (EXCLUSIVE_OPLOCK_TYPE(e->op_type)) {
1697 if (share_mode_stale_pid(d, i)) {
1698 DEBUG(10, ("Found stale duplicate oplock\n"));
1701 /* Exclusive or batch - can only be one. */
1702 if (ex_or_batch || level2 || no_oplock) {
1703 DEBUG(0, ("Bad exclusive or batch oplock "
1704 "entry %u.", (unsigned)i));
1710 if (LEVEL_II_OPLOCK_TYPE(e->op_type)) {
1711 if (batch || ex_or_batch) {
1712 if (share_mode_stale_pid(d, i)) {
1713 DEBUG(10, ("Found stale LevelII "
1717 DEBUG(0, ("Bad levelII oplock entry %u.",
1724 if (e->op_type == NO_OPLOCK) {
1725 if (batch || ex_or_batch) {
1726 if (share_mode_stale_pid(d, i)) {
1727 DEBUG(10, ("Found stale NO_OPLOCK "
1731 DEBUG(0, ("Bad no oplock entry %u.",
1739 remove_stale_share_mode_entries(d);
1741 if ((batch || ex_or_batch) && (num_non_stat_opens != 1)) {
1742 DEBUG(1, ("got batch (%d) or ex (%d) non-exclusively (%d)\n",
1743 (int)batch, (int)ex_or_batch,
1744 (int)d->num_share_modes));
1751 static bool delay_for_oplock(files_struct *fsp,
1753 const struct smb2_lease *lease,
1754 struct share_mode_lock *lck,
1755 bool have_sharing_violation,
1756 uint32_t create_disposition,
1757 bool first_open_attempt)
1759 struct share_mode_data *d = lck->data;
1762 bool will_overwrite;
1764 if ((oplock_request & INTERNAL_OPEN_ONLY) ||
1765 is_stat_open(fsp->access_mask)) {
1769 switch (create_disposition) {
1770 case FILE_SUPERSEDE:
1771 case FILE_OVERWRITE:
1772 case FILE_OVERWRITE_IF:
1773 will_overwrite = true;
1776 will_overwrite = false;
1780 for (i=0; i<d->num_share_modes; i++) {
1781 struct share_mode_entry *e = &d->share_modes[i];
1782 struct share_mode_lease *l = NULL;
1783 uint32_t e_lease_type = get_lease_type(d, e);
1785 uint32_t delay_mask = 0;
1787 if (e->op_type == LEASE_OPLOCK) {
1788 l = &d->leases[e->lease_idx];
1791 if (have_sharing_violation) {
1792 delay_mask = SMB2_LEASE_HANDLE;
1794 delay_mask = SMB2_LEASE_WRITE;
1797 break_to = e_lease_type & ~delay_mask;
1799 if (will_overwrite) {
1801 * we'll decide about SMB2_LEASE_READ later.
1803 * Maybe the break will be deferred
1805 break_to &= ~SMB2_LEASE_HANDLE;
1808 DEBUG(10, ("entry %u: e_lease_type %u, will_overwrite: %u\n",
1809 (unsigned)i, (unsigned)e_lease_type,
1810 (unsigned)will_overwrite));
1812 if (lease != NULL && l != NULL) {
1815 ign = smb2_lease_equal(fsp_client_guid(fsp),
1824 if ((e_lease_type & ~break_to) == 0) {
1825 if (l != NULL && l->breaking) {
1831 if (share_mode_stale_pid(d, i)) {
1835 if (will_overwrite) {
1837 * If we break anyway break to NONE directly.
1838 * Otherwise vfs_set_filelen() will trigger the
1841 break_to &= ~(SMB2_LEASE_READ|SMB2_LEASE_WRITE);
1844 if (e->op_type != LEASE_OPLOCK) {
1846 * Oplocks only support breaking to R or NONE.
1848 break_to &= ~(SMB2_LEASE_HANDLE|SMB2_LEASE_WRITE);
1851 DEBUG(10, ("breaking from %d to %d\n",
1852 (int)e_lease_type, (int)break_to));
1853 send_break_message(fsp->conn->sconn->msg_ctx, e,
1855 if (e_lease_type & delay_mask) {
1858 if (l != NULL && l->breaking && !first_open_attempt) {
1868 * Return lease or oplock state from a share mode
1870 static uint32_t get_lease_type_from_share_mode(const struct share_mode_data *d)
1872 uint32_t e_lease_type = 0;
1875 for (i=0; i < d->num_share_modes; i++) {
1876 struct share_mode_entry *e = &d->share_modes[i];
1878 e_lease_type |= get_lease_type(d, e);
1881 return e_lease_type;
1884 static bool file_has_brlocks(files_struct *fsp)
1886 struct byte_range_lock *br_lck;
1888 br_lck = brl_get_locks_readonly(fsp);
1892 return (brl_num_locks(br_lck) > 0);
1895 int find_share_mode_lease(struct share_mode_data *d,
1896 const struct GUID *client_guid,
1897 const struct smb2_lease_key *key)
1901 for (i=0; i<d->num_leases; i++) {
1902 struct share_mode_lease *l = &d->leases[i];
1904 if (smb2_lease_equal(client_guid,
1915 struct fsp_lease *find_fsp_lease(struct files_struct *new_fsp,
1916 const struct smb2_lease_key *key,
1917 const struct share_mode_lease *l)
1919 struct files_struct *fsp;
1922 * TODO: Measure how expensive this loop is with thousands of open
1926 for (fsp = file_find_di_first(new_fsp->conn->sconn, new_fsp->file_id);
1928 fsp = file_find_di_next(fsp)) {
1930 if (fsp == new_fsp) {
1933 if (fsp->oplock_type != LEASE_OPLOCK) {
1936 if (smb2_lease_key_equal(&fsp->lease->lease.lease_key, key)) {
1937 fsp->lease->ref_count += 1;
1942 /* Not found - must be leased in another smbd. */
1943 new_fsp->lease = talloc_zero(new_fsp->conn->sconn, struct fsp_lease);
1944 if (new_fsp->lease == NULL) {
1947 new_fsp->lease->ref_count = 1;
1948 new_fsp->lease->sconn = new_fsp->conn->sconn;
1949 new_fsp->lease->lease.lease_key = *key;
1950 new_fsp->lease->lease.lease_state = l->current_state;
1952 * We internally treat all leases as V2 and update
1953 * the epoch, but when sending breaks it matters if
1954 * the requesting lease was v1 or v2.
1956 new_fsp->lease->lease.lease_version = l->lease_version;
1957 new_fsp->lease->lease.lease_epoch = l->epoch;
1958 return new_fsp->lease;
1961 static NTSTATUS grant_fsp_lease(struct files_struct *fsp,
1962 struct share_mode_lock *lck,
1963 const struct smb2_lease *lease,
1964 uint32_t *p_lease_idx,
1967 struct share_mode_data *d = lck->data;
1968 const struct GUID *client_guid = fsp_client_guid(fsp);
1969 struct share_mode_lease *tmp;
1973 idx = find_share_mode_lease(d, client_guid, &lease->lease_key);
1976 struct share_mode_lease *l = &d->leases[idx];
1978 uint32_t existing, requested;
1980 fsp->lease = find_fsp_lease(fsp, &lease->lease_key, l);
1981 if (fsp->lease == NULL) {
1982 DEBUG(1, ("Did not find existing lease for file %s\n",
1984 return NT_STATUS_NO_MEMORY;
1990 * Upgrade only if the requested lease is a strict upgrade.
1992 existing = l->current_state;
1993 requested = lease->lease_state;
1996 * Tricky: This test makes sure that "requested" is a
1997 * strict bitwise superset of "existing".
1999 do_upgrade = ((existing & requested) == existing);
2002 * Upgrade only if there's a change.
2004 do_upgrade &= (granted != existing);
2007 * Upgrade only if other leases don't prevent what was asked
2010 do_upgrade &= (granted == requested);
2013 * only upgrade if we are not in breaking state
2015 do_upgrade &= !l->breaking;
2017 DEBUG(10, ("existing=%"PRIu32", requested=%"PRIu32", "
2018 "granted=%"PRIu32", do_upgrade=%d\n",
2019 existing, requested, granted, (int)do_upgrade));
2022 l->current_state = granted;
2026 /* Ensure we're in sync with current lease state. */
2027 fsp_lease_update(lck, fsp_client_guid(fsp), fsp->lease);
2028 return NT_STATUS_OK;
2035 tmp = talloc_realloc(d, d->leases, struct share_mode_lease,
2041 return NT_STATUS_INSUFFICIENT_RESOURCES;
2045 fsp->lease = talloc_zero(fsp->conn->sconn, struct fsp_lease);
2046 if (fsp->lease == NULL) {
2047 return NT_STATUS_INSUFFICIENT_RESOURCES;
2049 fsp->lease->ref_count = 1;
2050 fsp->lease->sconn = fsp->conn->sconn;
2051 fsp->lease->lease.lease_version = lease->lease_version;
2052 fsp->lease->lease.lease_key = lease->lease_key;
2053 fsp->lease->lease.lease_state = granted;
2054 fsp->lease->lease.lease_epoch = lease->lease_epoch + 1;
2056 *p_lease_idx = d->num_leases;
2058 d->leases[d->num_leases] = (struct share_mode_lease) {
2059 .client_guid = *client_guid,
2060 .lease_key = fsp->lease->lease.lease_key,
2061 .current_state = fsp->lease->lease.lease_state,
2062 .lease_version = fsp->lease->lease.lease_version,
2063 .epoch = fsp->lease->lease.lease_epoch,
2066 status = leases_db_add(client_guid,
2069 fsp->conn->connectpath,
2070 fsp->fsp_name->base_name,
2071 fsp->fsp_name->stream_name);
2072 if (!NT_STATUS_IS_OK(status)) {
2073 DEBUG(10, ("%s: leases_db_add failed: %s\n", __func__,
2074 nt_errstr(status)));
2075 TALLOC_FREE(fsp->lease);
2076 return NT_STATUS_INSUFFICIENT_RESOURCES;
2082 return NT_STATUS_OK;
2085 static bool is_same_lease(const files_struct *fsp,
2086 const struct share_mode_data *d,
2087 const struct share_mode_entry *e,
2088 const struct smb2_lease *lease)
2090 if (e->op_type != LEASE_OPLOCK) {
2093 if (lease == NULL) {
2097 return smb2_lease_equal(fsp_client_guid(fsp),
2099 &d->leases[e->lease_idx].client_guid,
2100 &d->leases[e->lease_idx].lease_key);
2103 static NTSTATUS grant_fsp_oplock_type(struct smb_request *req,
2104 struct files_struct *fsp,
2105 struct share_mode_lock *lck,
2107 struct smb2_lease *lease)
2109 struct share_mode_data *d = lck->data;
2110 bool got_handle_lease = false;
2111 bool got_oplock = false;
2114 uint32_t lease_idx = UINT32_MAX;
2118 if (oplock_request & INTERNAL_OPEN_ONLY) {
2119 /* No oplocks on internal open. */
2120 oplock_request = NO_OPLOCK;
2121 DEBUG(10,("grant_fsp_oplock_type: oplock type 0x%x on file %s\n",
2122 fsp->oplock_type, fsp_str_dbg(fsp)));
2125 if (oplock_request == LEASE_OPLOCK) {
2126 if (lease == NULL) {
2128 * The SMB2 layer should have checked this
2130 return NT_STATUS_INTERNAL_ERROR;
2133 granted = lease->lease_state;
2135 if (lp_kernel_oplocks(SNUM(fsp->conn))) {
2136 DEBUG(10, ("No lease granted because kernel oplocks are enabled\n"));
2137 granted = SMB2_LEASE_NONE;
2139 if ((granted & (SMB2_LEASE_READ|SMB2_LEASE_WRITE)) == 0) {
2140 DEBUG(10, ("No read or write lease requested\n"));
2141 granted = SMB2_LEASE_NONE;
2143 if (granted == SMB2_LEASE_WRITE) {
2144 DEBUG(10, ("pure write lease requested\n"));
2145 granted = SMB2_LEASE_NONE;
2147 if (granted == (SMB2_LEASE_WRITE|SMB2_LEASE_HANDLE)) {
2148 DEBUG(10, ("write and handle lease requested\n"));
2149 granted = SMB2_LEASE_NONE;
2152 granted = map_oplock_to_lease_type(
2153 oplock_request & ~SAMBA_PRIVATE_OPLOCK_MASK);
2156 if (lp_locking(fsp->conn->params) && file_has_brlocks(fsp)) {
2157 DEBUG(10,("grant_fsp_oplock_type: file %s has byte range locks\n",
2159 granted &= ~SMB2_LEASE_READ;
2162 for (i=0; i<d->num_share_modes; i++) {
2163 struct share_mode_entry *e = &d->share_modes[i];
2164 uint32_t e_lease_type;
2166 e_lease_type = get_lease_type(d, e);
2168 if ((granted & SMB2_LEASE_WRITE) &&
2169 !is_same_lease(fsp, d, e, lease) &&
2170 !share_mode_stale_pid(d, i)) {
2172 * Can grant only one writer
2174 granted &= ~SMB2_LEASE_WRITE;
2177 if ((e_lease_type & SMB2_LEASE_HANDLE) && !got_handle_lease &&
2178 !share_mode_stale_pid(d, i)) {
2179 got_handle_lease = true;
2182 if ((e->op_type != LEASE_OPLOCK) && !got_oplock &&
2183 !share_mode_stale_pid(d, i)) {
2188 if ((granted & SMB2_LEASE_READ) && !(granted & SMB2_LEASE_WRITE)) {
2190 (global_client_caps & CAP_LEVEL_II_OPLOCKS) &&
2191 lp_level2_oplocks(SNUM(fsp->conn));
2193 if (!allow_level2) {
2194 granted = SMB2_LEASE_NONE;
2198 if (oplock_request == LEASE_OPLOCK) {
2200 granted &= ~SMB2_LEASE_HANDLE;
2203 fsp->oplock_type = LEASE_OPLOCK;
2205 status = grant_fsp_lease(fsp, lck, lease, &lease_idx,
2207 if (!NT_STATUS_IS_OK(status)) {
2211 *lease = fsp->lease->lease;
2212 DEBUG(10, ("lease_state=%d\n", lease->lease_state));
2214 if (got_handle_lease) {
2215 granted = SMB2_LEASE_NONE;
2219 case SMB2_LEASE_READ|SMB2_LEASE_WRITE|SMB2_LEASE_HANDLE:
2220 fsp->oplock_type = BATCH_OPLOCK|EXCLUSIVE_OPLOCK;
2222 case SMB2_LEASE_READ|SMB2_LEASE_WRITE:
2223 fsp->oplock_type = EXCLUSIVE_OPLOCK;
2225 case SMB2_LEASE_READ|SMB2_LEASE_HANDLE:
2226 case SMB2_LEASE_READ:
2227 fsp->oplock_type = LEVEL_II_OPLOCK;
2230 fsp->oplock_type = NO_OPLOCK;
2234 status = set_file_oplock(fsp);
2235 if (!NT_STATUS_IS_OK(status)) {
2237 * Could not get the kernel oplock
2239 fsp->oplock_type = NO_OPLOCK;
2243 ok = set_share_mode(lck, fsp, get_current_uid(fsp->conn),
2248 return NT_STATUS_NO_MEMORY;
2251 ok = update_num_read_oplocks(fsp, lck);
2253 del_share_mode(lck, fsp);
2254 return NT_STATUS_INTERNAL_ERROR;
2257 DEBUG(10,("grant_fsp_oplock_type: oplock type 0x%x on file %s\n",
2258 fsp->oplock_type, fsp_str_dbg(fsp)));
2260 return NT_STATUS_OK;
2263 static bool request_timed_out(struct timeval request_time,
2264 struct timeval timeout)
2266 struct timeval now, end_time;
2268 end_time = timeval_sum(&request_time, &timeout);
2269 return (timeval_compare(&end_time, &now) < 0);
2272 static struct deferred_open_record *deferred_open_record_create(
2273 bool delayed_for_oplocks,
2277 struct deferred_open_record *record = NULL;
2279 record = talloc(NULL, struct deferred_open_record);
2280 if (record == NULL) {
2284 *record = (struct deferred_open_record) {
2285 .delayed_for_oplocks = delayed_for_oplocks,
2286 .async_open = async_open,
2293 struct defer_open_state {
2294 struct smbXsrv_connection *xconn;
2296 struct file_id file_id;
2297 struct timeval request_time;
2298 struct timeval timeout;
2300 uint32_t lease_type;
2303 static void defer_open_done(struct tevent_req *req);
2306 * Defer an open and watch a locking.tdb record
2308 * This defers an open that gets rescheduled once the locking.tdb record watch
2309 * is triggered by a change to the record.
2311 * It is used to defer opens that triggered an oplock break and for the SMB1
2312 * sharing violation delay.
2314 static void defer_open(struct share_mode_lock *lck,
2315 struct timeval request_time,
2316 struct timeval timeout,
2317 struct smb_request *req,
2318 bool delayed_for_oplocks,
2322 struct deferred_open_record *open_rec = NULL;
2323 struct timeval abs_timeout;
2324 struct defer_open_state *watch_state;
2325 struct tevent_req *watch_req;
2328 abs_timeout = timeval_sum(&request_time, &timeout);
2330 DBG_DEBUG("request time [%s] timeout [%s] mid [%" PRIu64 "] "
2331 "delayed_for_oplocks [%s] kernel_oplock [%s] file_id [%s]\n",
2332 timeval_string(talloc_tos(), &request_time, false),
2333 timeval_string(talloc_tos(), &abs_timeout, false),
2335 delayed_for_oplocks ? "yes" : "no",
2336 kernel_oplock ? "yes" : "no",
2337 file_id_string_tos(&id));
2339 open_rec = deferred_open_record_create(delayed_for_oplocks,
2342 if (open_rec == NULL) {
2344 exit_server("talloc failed");
2347 watch_state = talloc(open_rec, struct defer_open_state);
2348 if (watch_state == NULL) {
2349 exit_server("talloc failed");
2351 watch_state->xconn = req->xconn;
2352 watch_state->mid = req->mid;
2353 watch_state->file_id = lck->data->id;
2354 watch_state->request_time = request_time;
2355 watch_state->timeout = timeout;
2356 watch_state->kernel_oplock = kernel_oplock;
2357 watch_state->lease_type = get_lease_type_from_share_mode(lck->data);
2359 DBG_DEBUG("defering mid %" PRIu64 "\n", req->mid);
2361 watch_req = dbwrap_watched_watch_send(watch_state,
2364 (struct server_id){0});
2365 if (watch_req == NULL) {
2366 exit_server("Could not watch share mode record");
2368 tevent_req_set_callback(watch_req, defer_open_done, watch_state);
2370 ok = tevent_req_set_endtime(watch_req, req->sconn->ev_ctx, abs_timeout);
2372 exit_server("tevent_req_set_endtime failed");
2375 ok = push_deferred_open_message_smb(req, request_time, timeout,
2376 open_rec->id, open_rec);
2379 exit_server("push_deferred_open_message_smb failed");
2383 static void defer_open_done(struct tevent_req *req)
2385 struct defer_open_state *state = tevent_req_callback_data(
2386 req, struct defer_open_state);
2387 struct tevent_req *watch_req = NULL;
2388 struct share_mode_lock *lck = NULL;
2389 bool schedule_req = true;
2390 struct timeval timeout;
2394 status = dbwrap_watched_watch_recv(req, talloc_tos(), NULL, NULL,
2397 if (!NT_STATUS_IS_OK(status)) {
2398 DEBUG(5, ("dbwrap_watched_watch_recv returned %s\n",
2399 nt_errstr(status)));
2401 * Even if it failed, retry anyway. TODO: We need a way to
2402 * tell a re-scheduled open about that error.
2404 if (NT_STATUS_EQUAL(status, NT_STATUS_IO_TIMEOUT) &&
2405 state->kernel_oplock)
2408 * If we reschedule but the kernel oplock is still hold
2409 * we would block in the second open as that will be a
2410 * blocking open attempt.
2412 exit_server("Kernel oplock holder didn't "
2413 "respond to break message");
2417 if (state->kernel_oplock) {
2418 lck = get_existing_share_mode_lock(talloc_tos(), state->file_id);
2420 uint32_t lease_type;
2422 lease_type = get_lease_type_from_share_mode(lck->data);
2424 if ((lease_type != 0) &&
2425 (lease_type == state->lease_type))
2427 DBG_DEBUG("Unchanged lease: %" PRIu32 "\n",
2429 schedule_req = false;
2435 DBG_DEBUG("scheduling mid %" PRIu64 "\n", state->mid);
2437 ok = schedule_deferred_open_message_smb(state->xconn,
2440 exit_server("schedule_deferred_open_message_smb failed");
2447 DBG_DEBUG("Keep waiting for oplock release for [%s/%s%s] "
2448 "mid: %" PRIu64 "\n",
2449 lck->data->servicepath,
2450 lck->data->base_name,
2451 lck->data->stream_name ? lck->data->stream_name : "",
2454 watch_req = dbwrap_watched_watch_send(state,
2455 state->xconn->ev_ctx,
2457 (struct server_id){0});
2458 if (watch_req == NULL) {
2459 exit_server("Could not watch share mode record");
2461 tevent_req_set_callback(watch_req, defer_open_done, state);
2463 timeout = timeval_sum(&state->request_time, &state->timeout);
2464 ok = tevent_req_set_endtime(watch_req, state->xconn->ev_ctx, timeout);
2466 exit_server("tevent_req_set_endtime failed");
2473 * Reschedule an open for immediate execution
2475 static void retry_open(struct timeval request_time,
2476 struct smb_request *req,
2479 struct deferred_open_record *open_rec = NULL;
2482 DBG_DEBUG("request time [%s] mid [%" PRIu64 "] file_id [%s]\n",
2483 timeval_string(talloc_tos(), &request_time, false),
2485 file_id_string_tos(&id));
2487 open_rec = deferred_open_record_create(false, false, id);
2488 if (open_rec == NULL) {
2489 exit_server("talloc failed");
2492 ok = push_deferred_open_message_smb(req,
2498 exit_server("push_deferred_open_message_smb failed");
2501 ok = schedule_deferred_open_message_smb(req->xconn, req->mid);
2503 exit_server("schedule_deferred_open_message_smb failed");
2507 /****************************************************************************
2508 On overwrite open ensure that the attributes match.
2509 ****************************************************************************/
2511 static bool open_match_attributes(connection_struct *conn,
2512 uint32_t old_dos_attr,
2513 uint32_t new_dos_attr,
2514 mode_t existing_unx_mode,
2515 mode_t new_unx_mode,
2516 mode_t *returned_unx_mode)
2518 uint32_t noarch_old_dos_attr, noarch_new_dos_attr;
2520 noarch_old_dos_attr = (old_dos_attr & ~FILE_ATTRIBUTE_ARCHIVE);
2521 noarch_new_dos_attr = (new_dos_attr & ~FILE_ATTRIBUTE_ARCHIVE);
2523 if((noarch_old_dos_attr == 0 && noarch_new_dos_attr != 0) ||
2524 (noarch_old_dos_attr != 0 && ((noarch_old_dos_attr & noarch_new_dos_attr) == noarch_old_dos_attr))) {
2525 *returned_unx_mode = new_unx_mode;
2527 *returned_unx_mode = (mode_t)0;
2530 DEBUG(10,("open_match_attributes: old_dos_attr = 0x%x, "
2531 "existing_unx_mode = 0%o, new_dos_attr = 0x%x "
2532 "returned_unx_mode = 0%o\n",
2533 (unsigned int)old_dos_attr,
2534 (unsigned int)existing_unx_mode,
2535 (unsigned int)new_dos_attr,
2536 (unsigned int)*returned_unx_mode ));
2538 /* If we're mapping SYSTEM and HIDDEN ensure they match. */
2539 if (lp_map_system(SNUM(conn)) || lp_store_dos_attributes(SNUM(conn))) {
2540 if ((old_dos_attr & FILE_ATTRIBUTE_SYSTEM) &&
2541 !(new_dos_attr & FILE_ATTRIBUTE_SYSTEM)) {
2545 if (lp_map_hidden(SNUM(conn)) || lp_store_dos_attributes(SNUM(conn))) {
2546 if ((old_dos_attr & FILE_ATTRIBUTE_HIDDEN) &&
2547 !(new_dos_attr & FILE_ATTRIBUTE_HIDDEN)) {
2554 /****************************************************************************
2555 Special FCB or DOS processing in the case of a sharing violation.
2556 Try and find a duplicated file handle.
2557 ****************************************************************************/
2559 static NTSTATUS fcb_or_dos_open(struct smb_request *req,
2560 connection_struct *conn,
2561 files_struct *fsp_to_dup_into,
2562 const struct smb_filename *smb_fname,
2566 uint32_t access_mask,
2567 uint32_t share_access,
2568 uint32_t create_options)
2572 DEBUG(5,("fcb_or_dos_open: attempting old open semantics for "
2573 "file %s.\n", smb_fname_str_dbg(smb_fname)));
2575 for(fsp = file_find_di_first(conn->sconn, id); fsp;
2576 fsp = file_find_di_next(fsp)) {
2578 DEBUG(10,("fcb_or_dos_open: checking file %s, fd = %d, "
2579 "vuid = %llu, file_pid = %u, private_options = 0x%x "
2580 "access_mask = 0x%x\n", fsp_str_dbg(fsp),
2581 fsp->fh->fd, (unsigned long long)fsp->vuid,
2582 (unsigned int)fsp->file_pid,
2583 (unsigned int)fsp->fh->private_options,
2584 (unsigned int)fsp->access_mask ));
2586 if (fsp != fsp_to_dup_into &&
2587 fsp->fh->fd != -1 &&
2588 fsp->vuid == vuid &&
2589 fsp->file_pid == file_pid &&
2590 (fsp->fh->private_options & (NTCREATEX_OPTIONS_PRIVATE_DENY_DOS |
2591 NTCREATEX_OPTIONS_PRIVATE_DENY_FCB)) &&
2592 (fsp->access_mask & FILE_WRITE_DATA) &&
2593 strequal(fsp->fsp_name->base_name, smb_fname->base_name) &&
2594 strequal(fsp->fsp_name->stream_name,
2595 smb_fname->stream_name)) {
2596 DEBUG(10,("fcb_or_dos_open: file match\n"));
2602 return NT_STATUS_NOT_FOUND;
2605 /* quite an insane set of semantics ... */
2606 if (is_executable(smb_fname->base_name) &&
2607 (fsp->fh->private_options & NTCREATEX_OPTIONS_PRIVATE_DENY_DOS)) {
2608 DEBUG(10,("fcb_or_dos_open: file fail due to is_executable.\n"));
2609 return NT_STATUS_INVALID_PARAMETER;
2612 /* We need to duplicate this fsp. */
2613 return dup_file_fsp(req, fsp, access_mask, share_access,
2614 create_options, fsp_to_dup_into);
2617 static void schedule_defer_open(struct share_mode_lock *lck,
2619 struct timeval request_time,
2620 struct smb_request *req,
2623 /* This is a relative time, added to the absolute
2624 request_time value to get the absolute timeout time.
2625 Note that if this is the second or greater time we enter
2626 this codepath for this particular request mid then
2627 request_time is left as the absolute time of the *first*
2628 time this request mid was processed. This is what allows
2629 the request to eventually time out. */
2631 struct timeval timeout;
2633 /* Normally the smbd we asked should respond within
2634 * OPLOCK_BREAK_TIMEOUT seconds regardless of whether
2635 * the client did, give twice the timeout as a safety
2636 * measure here in case the other smbd is stuck
2637 * somewhere else. */
2639 timeout = timeval_set(OPLOCK_BREAK_TIMEOUT*2, 0);
2641 if (request_timed_out(request_time, timeout)) {
2645 defer_open(lck, request_time, timeout, req, true, kernel_oplock, id);
2648 /****************************************************************************
2649 Reschedule an open call that went asynchronous.
2650 ****************************************************************************/
2652 static void schedule_async_open_timer(struct tevent_context *ev,
2653 struct tevent_timer *te,
2654 struct timeval current_time,
2657 exit_server("async open timeout");
2660 static void schedule_async_open(struct timeval request_time,
2661 struct smb_request *req)
2663 struct deferred_open_record *open_rec = NULL;
2664 struct timeval timeout = timeval_set(20, 0);
2667 if (request_timed_out(request_time, timeout)) {
2671 open_rec = deferred_open_record_create(false, true, (struct file_id){0});
2672 if (open_rec == NULL) {
2673 exit_server("deferred_open_record_create failed");
2676 ok = push_deferred_open_message_smb(req, request_time, timeout,
2677 (struct file_id){0}, open_rec);
2679 exit_server("push_deferred_open_message_smb failed");
2682 open_rec->te = tevent_add_timer(req->sconn->ev_ctx,
2684 timeval_current_ofs(20, 0),
2685 schedule_async_open_timer,
2687 if (open_rec->te == NULL) {
2688 exit_server("tevent_add_timer failed");
2692 /****************************************************************************
2693 Work out what access_mask to use from what the client sent us.
2694 ****************************************************************************/
2696 static NTSTATUS smbd_calculate_maximum_allowed_access(
2697 connection_struct *conn,
2698 const struct smb_filename *smb_fname,
2700 uint32_t *p_access_mask)
2702 struct security_descriptor *sd;
2703 uint32_t access_granted;
2706 if (!use_privs && (get_current_uid(conn) == (uid_t)0)) {
2707 *p_access_mask |= FILE_GENERIC_ALL;
2708 return NT_STATUS_OK;
2711 status = SMB_VFS_GET_NT_ACL(conn, smb_fname,
2717 if (NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
2719 * File did not exist
2721 *p_access_mask = FILE_GENERIC_ALL;
2722 return NT_STATUS_OK;
2724 if (!NT_STATUS_IS_OK(status)) {
2725 DEBUG(10,("Could not get acl on file %s: %s\n",
2726 smb_fname_str_dbg(smb_fname),
2727 nt_errstr(status)));
2728 return NT_STATUS_ACCESS_DENIED;
2732 * If we can access the path to this file, by
2733 * default we have FILE_READ_ATTRIBUTES from the
2734 * containing directory. See the section:
2735 * "Algorithm to Check Access to an Existing File"
2738 * se_file_access_check()
2739 * also takes care of owner WRITE_DAC and READ_CONTROL.
2741 status = se_file_access_check(sd,
2742 get_current_nttok(conn),
2744 (*p_access_mask & ~FILE_READ_ATTRIBUTES),
2749 if (!NT_STATUS_IS_OK(status)) {
2750 DEBUG(10, ("Access denied on file %s: "
2751 "when calculating maximum access\n",
2752 smb_fname_str_dbg(smb_fname)));
2753 return NT_STATUS_ACCESS_DENIED;
2755 *p_access_mask = (access_granted | FILE_READ_ATTRIBUTES);
2757 if (!(access_granted & DELETE_ACCESS)) {
2758 if (can_delete_file_in_directory(conn, smb_fname)) {
2759 *p_access_mask |= DELETE_ACCESS;
2763 return NT_STATUS_OK;
2766 NTSTATUS smbd_calculate_access_mask(connection_struct *conn,
2767 const struct smb_filename *smb_fname,
2769 uint32_t access_mask,
2770 uint32_t *access_mask_out)
2773 uint32_t orig_access_mask = access_mask;
2774 uint32_t rejected_share_access;
2776 if (access_mask & SEC_MASK_INVALID) {
2777 DBG_DEBUG("access_mask [%8x] contains invalid bits\n",
2779 return NT_STATUS_ACCESS_DENIED;
2783 * Convert GENERIC bits to specific bits.
2786 se_map_generic(&access_mask, &file_generic_mapping);
2788 /* Calculate MAXIMUM_ALLOWED_ACCESS if requested. */
2789 if (access_mask & MAXIMUM_ALLOWED_ACCESS) {
2791 status = smbd_calculate_maximum_allowed_access(
2792 conn, smb_fname, use_privs, &access_mask);
2794 if (!NT_STATUS_IS_OK(status)) {
2798 access_mask &= conn->share_access;
2801 rejected_share_access = access_mask & ~(conn->share_access);
2803 if (rejected_share_access) {
2804 DEBUG(10, ("smbd_calculate_access_mask: Access denied on "
2805 "file %s: rejected by share access mask[0x%08X] "
2806 "orig[0x%08X] mapped[0x%08X] reject[0x%08X]\n",
2807 smb_fname_str_dbg(smb_fname),
2809 orig_access_mask, access_mask,
2810 rejected_share_access));
2811 return NT_STATUS_ACCESS_DENIED;
2814 *access_mask_out = access_mask;
2815 return NT_STATUS_OK;
2818 /****************************************************************************
2819 Remove the deferred open entry under lock.
2820 ****************************************************************************/
2822 /****************************************************************************
2823 Return true if this is a state pointer to an asynchronous create.
2824 ****************************************************************************/
2826 bool is_deferred_open_async(const struct deferred_open_record *rec)
2828 return rec->async_open;
2831 static bool clear_ads(uint32_t create_disposition)
2835 switch (create_disposition) {
2836 case FILE_SUPERSEDE:
2837 case FILE_OVERWRITE_IF:
2838 case FILE_OVERWRITE:
2847 static int disposition_to_open_flags(uint32_t create_disposition)
2852 * Currently we're using FILE_SUPERSEDE as the same as
2853 * FILE_OVERWRITE_IF but they really are
2854 * different. FILE_SUPERSEDE deletes an existing file
2855 * (requiring delete access) then recreates it.
2858 switch (create_disposition) {
2859 case FILE_SUPERSEDE:
2860 case FILE_OVERWRITE_IF:
2862 * If file exists replace/overwrite. If file doesn't
2865 ret = O_CREAT|O_TRUNC;
2870 * If file exists open. If file doesn't exist error.
2875 case FILE_OVERWRITE:
2877 * If file exists overwrite. If file doesn't exist
2885 * If file exists error. If file doesn't exist create.
2887 ret = O_CREAT|O_EXCL;
2892 * If file exists open. If file doesn't exist create.
2900 static int calculate_open_access_flags(uint32_t access_mask,
2901 uint32_t private_flags)
2903 bool need_write, need_read;
2906 * Note that we ignore the append flag as append does not
2907 * mean the same thing under DOS and Unix.
2910 need_write = (access_mask & (FILE_WRITE_DATA | FILE_APPEND_DATA));
2915 /* DENY_DOS opens are always underlying read-write on the
2916 file handle, no matter what the requested access mask
2920 ((private_flags & NTCREATEX_OPTIONS_PRIVATE_DENY_DOS) ||
2921 access_mask & (FILE_READ_ATTRIBUTES|FILE_READ_DATA|
2922 FILE_READ_EA|FILE_EXECUTE));
2930 /****************************************************************************
2931 Open a file with a share mode. Passed in an already created files_struct *.
2932 ****************************************************************************/
2934 static NTSTATUS open_file_ntcreate(connection_struct *conn,
2935 struct smb_request *req,
2936 uint32_t access_mask, /* access bits (FILE_READ_DATA etc.) */
2937 uint32_t share_access, /* share constants (FILE_SHARE_READ etc) */
2938 uint32_t create_disposition, /* FILE_OPEN_IF etc. */
2939 uint32_t create_options, /* options such as delete on close. */
2940 uint32_t new_dos_attributes, /* attributes used for new file. */
2941 int oplock_request, /* internal Samba oplock codes. */
2942 struct smb2_lease *lease,
2943 /* Information (FILE_EXISTS etc.) */
2944 uint32_t private_flags, /* Samba specific flags. */
2948 struct smb_filename *smb_fname = fsp->fsp_name;
2951 bool file_existed = VALID_STAT(smb_fname->st);
2952 bool def_acl = False;
2953 bool posix_open = False;
2954 bool new_file_created = False;
2955 bool first_open_attempt = true;
2956 NTSTATUS fsp_open = NT_STATUS_ACCESS_DENIED;
2957 mode_t new_unx_mode = (mode_t)0;
2958 mode_t unx_mode = (mode_t)0;
2960 uint32_t existing_dos_attributes = 0;
2961 struct timeval request_time = timeval_zero();
2962 struct share_mode_lock *lck = NULL;
2963 uint32_t open_access_mask = access_mask;
2966 SMB_STRUCT_STAT saved_stat = smb_fname->st;
2967 struct timespec old_write_time;
2970 if (conn->printer) {
2972 * Printers are handled completely differently.
2973 * Most of the passed parameters are ignored.
2977 *pinfo = FILE_WAS_CREATED;
2980 DEBUG(10, ("open_file_ntcreate: printer open fname=%s\n",
2981 smb_fname_str_dbg(smb_fname)));
2984 DEBUG(0,("open_file_ntcreate: printer open without "
2985 "an SMB request!\n"));
2986 return NT_STATUS_INTERNAL_ERROR;
2989 return print_spool_open(fsp, smb_fname->base_name,
2993 if (!parent_dirname(talloc_tos(), smb_fname->base_name, &parent_dir,
2995 return NT_STATUS_NO_MEMORY;
2998 if (new_dos_attributes & FILE_FLAG_POSIX_SEMANTICS) {
3000 unx_mode = (mode_t)(new_dos_attributes & ~FILE_FLAG_POSIX_SEMANTICS);
3001 new_dos_attributes = 0;
3003 /* Windows allows a new file to be created and
3004 silently removes a FILE_ATTRIBUTE_DIRECTORY
3005 sent by the client. Do the same. */
3007 new_dos_attributes &= ~FILE_ATTRIBUTE_DIRECTORY;
3009 /* We add FILE_ATTRIBUTE_ARCHIVE to this as this mode is only used if the file is
3011 unx_mode = unix_mode(conn, new_dos_attributes | FILE_ATTRIBUTE_ARCHIVE,
3012 smb_fname, parent_dir);
3015 DEBUG(10, ("open_file_ntcreate: fname=%s, dos_attrs=0x%x "
3016 "access_mask=0x%x share_access=0x%x "
3017 "create_disposition = 0x%x create_options=0x%x "
3018 "unix mode=0%o oplock_request=%d private_flags = 0x%x\n",
3019 smb_fname_str_dbg(smb_fname), new_dos_attributes,
3020 access_mask, share_access, create_disposition,
3021 create_options, (unsigned int)unx_mode, oplock_request,
3022 (unsigned int)private_flags));
3025 /* Ensure req == NULL means INTERNAL_OPEN_ONLY */
3026 SMB_ASSERT(((oplock_request & INTERNAL_OPEN_ONLY) != 0));
3028 /* And req != NULL means no INTERNAL_OPEN_ONLY */
3029 SMB_ASSERT(((oplock_request & INTERNAL_OPEN_ONLY) == 0));
3033 * Only non-internal opens can be deferred at all
3037 struct deferred_open_record *open_rec;
3038 if (get_deferred_open_message_state(req,
3041 /* Remember the absolute time of the original
3042 request with this mid. We'll use it later to
3043 see if this has timed out. */
3045 /* If it was an async create retry, the file
3048 if (is_deferred_open_async(open_rec)) {
3049 SET_STAT_INVALID(smb_fname->st);
3050 file_existed = false;
3053 /* Ensure we don't reprocess this message. */
3054 remove_deferred_open_message_smb(req->xconn, req->mid);
3056 first_open_attempt = false;
3061 new_dos_attributes &= SAMBA_ATTRIBUTES_MASK;
3064 * Only use strored DOS attributes for checks
3065 * against requested attributes (below via
3066 * open_match_attributes()), cf bug #11992
3067 * for details. -slow
3071 status = SMB_VFS_GET_DOS_ATTRIBUTES(conn, smb_fname, &attr);
3072 if (NT_STATUS_IS_OK(status)) {
3073 existing_dos_attributes = attr;
3078 /* ignore any oplock requests if oplocks are disabled */
3079 if (!lp_oplocks(SNUM(conn)) ||
3080 IS_VETO_OPLOCK_PATH(conn, smb_fname->base_name)) {
3081 /* Mask off everything except the private Samba bits. */
3082 oplock_request &= SAMBA_PRIVATE_OPLOCK_MASK;
3085 /* this is for OS/2 long file names - say we don't support them */
3086 if (req != NULL && !req->posix_pathnames &&
3087 strstr(smb_fname->base_name,".+,;=[].")) {
3088 /* OS/2 Workplace shell fix may be main code stream in a later
3090 DEBUG(5,("open_file_ntcreate: OS/2 long filenames are not "
3092 if (use_nt_status()) {
3093 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3095 return NT_STATUS_DOS(ERRDOS, ERRcannotopen);
3098 switch( create_disposition ) {
3100 /* If file exists open. If file doesn't exist error. */
3101 if (!file_existed) {
3102 DEBUG(5,("open_file_ntcreate: FILE_OPEN "
3103 "requested for file %s and file "
3105 smb_fname_str_dbg(smb_fname)));
3107 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3111 case FILE_OVERWRITE:
3112 /* If file exists overwrite. If file doesn't exist
3114 if (!file_existed) {
3115 DEBUG(5,("open_file_ntcreate: FILE_OVERWRITE "
3116 "requested for file %s and file "
3118 smb_fname_str_dbg(smb_fname) ));
3120 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3125 /* If file exists error. If file doesn't exist
3128 DEBUG(5,("open_file_ntcreate: FILE_CREATE "
3129 "requested for file %s and file "
3130 "already exists.\n",
3131 smb_fname_str_dbg(smb_fname)));
3132 if (S_ISDIR(smb_fname->st.st_ex_mode)) {
3137 return map_nt_error_from_unix(errno);
3141 case FILE_SUPERSEDE:
3142 case FILE_OVERWRITE_IF:
3146 return NT_STATUS_INVALID_PARAMETER;
3149 flags2 = disposition_to_open_flags(create_disposition);
3151 /* We only care about matching attributes on file exists and
3154 if (!posix_open && file_existed &&
3155 ((create_disposition == FILE_OVERWRITE) ||
3156 (create_disposition == FILE_OVERWRITE_IF))) {
3157 if (!open_match_attributes(conn, existing_dos_attributes,
3159 smb_fname->st.st_ex_mode,
3160 unx_mode, &new_unx_mode)) {
3161 DEBUG(5,("open_file_ntcreate: attributes missmatch "
3162 "for file %s (%x %x) (0%o, 0%o)\n",
3163 smb_fname_str_dbg(smb_fname),
3164 existing_dos_attributes,
3166 (unsigned int)smb_fname->st.st_ex_mode,
3167 (unsigned int)unx_mode ));
3169 return NT_STATUS_ACCESS_DENIED;
3173 status = smbd_calculate_access_mask(conn, smb_fname,
3177 if (!NT_STATUS_IS_OK(status)) {
3178 DEBUG(10, ("open_file_ntcreate: smbd_calculate_access_mask "
3179 "on file %s returned %s\n",
3180 smb_fname_str_dbg(smb_fname), nt_errstr(status)));
3184 open_access_mask = access_mask;
3186 if (flags2 & O_TRUNC) {
3187 open_access_mask |= FILE_WRITE_DATA; /* This will cause oplock breaks. */
3190 DEBUG(10, ("open_file_ntcreate: fname=%s, after mapping "
3191 "access_mask=0x%x\n", smb_fname_str_dbg(smb_fname),
3195 * Note that we ignore the append flag as append does not
3196 * mean the same thing under DOS and Unix.
3199 flags = calculate_open_access_flags(access_mask, private_flags);
3202 * Currently we only look at FILE_WRITE_THROUGH for create options.
3206 if ((create_options & FILE_WRITE_THROUGH) && lp_strict_sync(SNUM(conn))) {
3211 if (posix_open && (access_mask & FILE_APPEND_DATA)) {
3215 if (!posix_open && !CAN_WRITE(conn)) {
3217 * We should really return a permission denied error if either
3218 * O_CREAT or O_TRUNC are set, but for compatibility with
3219 * older versions of Samba we just AND them out.
3221 flags2 &= ~(O_CREAT|O_TRUNC);
3224 if (first_open_attempt && lp_kernel_oplocks(SNUM(conn))) {
3226 * With kernel oplocks the open breaking an oplock
3227 * blocks until the oplock holder has given up the
3228 * oplock or closed the file. We prevent this by first
3229 * trying to open the file with O_NONBLOCK (see "man
3230 * fcntl" on Linux). For the second try, triggered by
3231 * an oplock break response, we do not need this
3234 * This is true under the assumption that only Samba
3235 * requests kernel oplocks. Once someone else like
3236 * NFSv4 starts to use that API, we will have to
3237 * modify this by communicating with the NFSv4 server.
3239 flags2 |= O_NONBLOCK;
3243 * Ensure we can't write on a read-only share or file.
3246 if (flags != O_RDONLY && file_existed &&
3247 (!CAN_WRITE(conn) || IS_DOS_READONLY(existing_dos_attributes))) {
3248 DEBUG(5,("open_file_ntcreate: write access requested for "
3249 "file %s on read only %s\n",
3250 smb_fname_str_dbg(smb_fname),
3251 !CAN_WRITE(conn) ? "share" : "file" ));
3253 return NT_STATUS_ACCESS_DENIED;
3256 fsp->file_id = vfs_file_id_from_sbuf(conn, &smb_fname->st);
3257 fsp->share_access = share_access;
3258 fsp->fh->private_options = private_flags;
3259 fsp->access_mask = open_access_mask; /* We change this to the
3260 * requested access_mask after
3261 * the open is done. */
3263 fsp->posix_flags |= FSP_POSIX_FLAGS_ALL;
3266 if (timeval_is_zero(&request_time)) {
3267 request_time = fsp->open_time;
3271 * Ensure we pay attention to default ACLs on directories if required.
3274 if ((flags2 & O_CREAT) && lp_inherit_acls(SNUM(conn)) &&
3275 (def_acl = directory_has_default_acl(conn, parent_dir))) {
3276 unx_mode = (0777 & lp_create_mask(SNUM(conn)));
3279 DEBUG(4,("calling open_file with flags=0x%X flags2=0x%X mode=0%o, "
3280 "access_mask = 0x%x, open_access_mask = 0x%x\n",
3281 (unsigned int)flags, (unsigned int)flags2,
3282 (unsigned int)unx_mode, (unsigned int)access_mask,
3283 (unsigned int)open_access_mask));
3285 fsp_open = open_file(fsp, conn, req, parent_dir,
3286 flags|flags2, unx_mode, access_mask,
3287 open_access_mask, &new_file_created);
3289 if (NT_STATUS_EQUAL(fsp_open, NT_STATUS_NETWORK_BUSY)) {
3293 * This handles the kernel oplock case:
3295 * the file has an active kernel oplock and the open() returned
3296 * EWOULDBLOCK/EAGAIN which maps to NETWORK_BUSY.
3298 * "Samba locking.tdb oplocks" are handled below after acquiring
3299 * the sharemode lock with get_share_mode_lock().
3301 if (file_existed && S_ISFIFO(fsp->fsp_name->st.st_ex_mode)) {
3302 DEBUG(10, ("FIFO busy\n"));
3303 return NT_STATUS_NETWORK_BUSY;
3306 DEBUG(10, ("Internal open busy\n"));
3307 return NT_STATUS_NETWORK_BUSY;
3311 * From here on we assume this is an oplock break triggered
3314 lck = get_existing_share_mode_lock(talloc_tos(), fsp->file_id);
3316 retry_open(request_time, req, fsp->file_id);
3317 DEBUG(10, ("No share mode lock found after "
3318 "EWOULDBLOCK, retrying sync\n"));
3319 return NT_STATUS_SHARING_VIOLATION;
3322 if (!validate_oplock_types(lck)) {
3323 smb_panic("validate_oplock_types failed");
3326 delay = delay_for_oplock(fsp, 0, lease, lck, false,
3328 first_open_attempt);
3330 schedule_defer_open(lck, fsp->file_id, request_time,
3333 DEBUG(10, ("Sent oplock break request to kernel "
3334 "oplock holder\n"));
3335 return NT_STATUS_SHARING_VIOLATION;
3339 * No oplock from Samba around. Immediately retry with
3342 retry_open(request_time, req, fsp->file_id);
3345 DEBUG(10, ("No Samba oplock around after EWOULDBLOCK. "
3346 "Retrying sync\n"));
3347 return NT_STATUS_SHARING_VIOLATION;
3350 if (!NT_STATUS_IS_OK(fsp_open)) {
3351 if (NT_STATUS_EQUAL(fsp_open, NT_STATUS_RETRY)) {
3352 schedule_async_open(request_time, req);
3357 if (new_file_created) {
3359 * As we atomically create using O_CREAT|O_EXCL,
3360 * then if new_file_created is true, then
3361 * file_existed *MUST* have been false (even
3362 * if the file was previously detected as being
3365 file_existed = false;
3368 if (file_existed && !check_same_dev_ino(&saved_stat, &smb_fname->st)) {
3370 * The file did exist, but some other (local or NFS)
3371 * process either renamed/unlinked and re-created the
3372 * file with different dev/ino after we walked the path,
3373 * but before we did the open. We could retry the
3374 * open but it's a rare enough case it's easier to
3375 * just fail the open to prevent creating any problems
3376 * in the open file db having the wrong dev/ino key.
3379 DEBUG(1,("open_file_ntcreate: file %s - dev/ino mismatch. "
3380 "Old (dev=0x%llu, ino =0x%llu). "
3381 "New (dev=0x%llu, ino=0x%llu). Failing open "
3382 " with NT_STATUS_ACCESS_DENIED.\n",
3383 smb_fname_str_dbg(smb_fname),
3384 (unsigned long long)saved_stat.st_ex_dev,
3385 (unsigned long long)saved_stat.st_ex_ino,
3386 (unsigned long long)smb_fname->st.st_ex_dev,
3387 (unsigned long long)smb_fname->st.st_ex_ino));
3388 return NT_STATUS_ACCESS_DENIED;
3391 old_write_time = smb_fname->st.st_ex_mtime;
3394 * Deal with the race condition where two smbd's detect the
3395 * file doesn't exist and do the create at the same time. One
3396 * of them will win and set a share mode, the other (ie. this
3397 * one) should check if the requested share mode for this
3398 * create is allowed.
3402 * Now the file exists and fsp is successfully opened,
3403 * fsp->dev and fsp->inode are valid and should replace the
3404 * dev=0,inode=0 from a non existent file. Spotted by
3405 * Nadav Danieli <nadavd@exanet.com>. JRA.
3410 lck = get_share_mode_lock(talloc_tos(), id,
3412 smb_fname, &old_write_time);
3415 DEBUG(0, ("open_file_ntcreate: Could not get share "
3416 "mode lock for %s\n",
3417 smb_fname_str_dbg(smb_fname)));
3419 return NT_STATUS_SHARING_VIOLATION;
3422 /* Get the types we need to examine. */
3423 if (!validate_oplock_types(lck)) {
3424 smb_panic("validate_oplock_types failed");
3427 if (has_delete_on_close(lck, fsp->name_hash)) {
3430 return NT_STATUS_DELETE_PENDING;
3433 status = open_mode_check(conn, lck,
3434 access_mask, share_access);
3436 if (NT_STATUS_EQUAL(status, NT_STATUS_SHARING_VIOLATION) ||
3437 (lck->data->num_share_modes > 0)) {
3439 * This comes from ancient times out of open_mode_check. I
3440 * have no clue whether this is still necessary. I can't think
3441 * of a case where this would actually matter further down in
3442 * this function. I leave it here for further investigation
3445 file_existed = true;
3450 * Handle oplocks, deferring the request if delay_for_oplock()
3451 * triggered a break message and we have to wait for the break
3455 bool sharing_violation = NT_STATUS_EQUAL(
3456 status, NT_STATUS_SHARING_VIOLATION);
3458 delay = delay_for_oplock(fsp, oplock_request, lease, lck,
3461 first_open_attempt);
3463 schedule_defer_open(lck, fsp->file_id,
3464 request_time, req, false);
3467 return NT_STATUS_SHARING_VIOLATION;
3471 if (!NT_STATUS_IS_OK(status)) {
3472 uint32_t can_access_mask;
3473 bool can_access = True;
3475 SMB_ASSERT(NT_STATUS_EQUAL(status, NT_STATUS_SHARING_VIOLATION));
3477 /* Check if this can be done with the deny_dos and fcb
3480 (NTCREATEX_OPTIONS_PRIVATE_DENY_DOS|
3481 NTCREATEX_OPTIONS_PRIVATE_DENY_FCB)) {
3483 DEBUG(0, ("DOS open without an SMB "
3487 return NT_STATUS_INTERNAL_ERROR;
3490 /* Use the client requested access mask here,
3491 * not the one we open with. */
3492 status = fcb_or_dos_open(req,
3503 if (NT_STATUS_IS_OK(status)) {
3506 *pinfo = FILE_WAS_OPENED;
3508 return NT_STATUS_OK;
3513 * This next line is a subtlety we need for
3514 * MS-Access. If a file open will fail due to share
3515 * permissions and also for security (access) reasons,
3516 * we need to return the access failed error, not the
3517 * share error. We can't open the file due to kernel
3518 * oplock deadlock (it's possible we failed above on
3519 * the open_mode_check()) so use a userspace check.
3522 if (flags & O_RDWR) {
3523 can_access_mask = FILE_READ_DATA|FILE_WRITE_DATA;
3524 } else if (flags & O_WRONLY) {
3525 can_access_mask = FILE_WRITE_DATA;
3527 can_access_mask = FILE_READ_DATA;
3530 if (((can_access_mask & FILE_WRITE_DATA) &&
3531 !CAN_WRITE(conn)) ||
3532 !NT_STATUS_IS_OK(smbd_check_access_rights(conn,
3535 can_access_mask))) {
3540 * If we're returning a share violation, ensure we
3541 * cope with the braindead 1 second delay (SMB1 only).
3544 if (!(oplock_request & INTERNAL_OPEN_ONLY) &&
3545 !conn->sconn->using_smb2 &&
3546 lp_defer_sharing_violations()) {
3547 struct timeval timeout;
3550 /* this is a hack to speed up torture tests
3552 timeout_usecs = lp_parm_int(SNUM(conn),
3553 "smbd","sharedelay",
3554 SHARING_VIOLATION_USEC_WAIT);
3556 /* This is a relative time, added to the absolute
3557 request_time value to get the absolute timeout time.
3558 Note that if this is the second or greater time we enter
3559 this codepath for this particular request mid then
3560 request_time is left as the absolute time of the *first*
3561 time this request mid was processed. This is what allows
3562 the request to eventually time out. */
3564 timeout = timeval_set(0, timeout_usecs);
3566 if (!request_timed_out(request_time, timeout)) {
3567 defer_open(lck, request_time, timeout, req,
3576 * We have detected a sharing violation here
3577 * so return the correct error code
3579 status = NT_STATUS_SHARING_VIOLATION;
3581 status = NT_STATUS_ACCESS_DENIED;
3586 /* Should we atomically (to the client at least) truncate ? */
3587 if ((!new_file_created) &&
3588 (flags2 & O_TRUNC) &&
3589 (!S_ISFIFO(fsp->fsp_name->st.st_ex_mode))) {
3592 ret = vfs_set_filelen(fsp, 0);
3594 status = map_nt_error_from_unix(errno);
3602 * We have the share entry *locked*.....
3605 /* Delete streams if create_disposition requires it */
3606 if (!new_file_created && clear_ads(create_disposition) &&
3607 !is_ntfs_stream_smb_fname(smb_fname)) {
3608 status = delete_all_streams(conn, smb_fname);
3609 if (!NT_STATUS_IS_OK(status)) {
3616 /* note that we ignore failure for the following. It is
3617 basically a hack for NFS, and NFS will never set one of
3618 these only read them. Nobody but Samba can ever set a deny
3619 mode and we have already checked our more authoritative
3620 locking database for permission to set this deny mode. If
3621 the kernel refuses the operations then the kernel is wrong.
3622 note that GPFS supports it as well - jmcd */
3624 if (fsp->fh->fd != -1 && lp_kernel_share_modes(SNUM(conn))) {
3627 * Beware: streams implementing VFS modules may
3628 * implement streams in a way that fsp will have the
3629 * basefile open in the fsp fd, so lacking a distinct
3630 * fd for the stream kernel_flock will apply on the
3631 * basefile which is wrong. The actual check is
3632 * deffered to the VFS module implementing the
3633 * kernel_flock call.
3635 ret_flock = SMB_VFS_KERNEL_FLOCK(fsp, share_access, access_mask);
3636 if(ret_flock == -1 ){
3641 return NT_STATUS_SHARING_VIOLATION;
3644 fsp->kernel_share_modes_taken = true;
3648 * At this point onwards, we can guarantee that the share entry
3649 * is locked, whether we created the file or not, and that the
3650 * deny mode is compatible with all current opens.
3654 * According to Samba4, SEC_FILE_READ_ATTRIBUTE is always granted,
3655 * but we don't have to store this - just ignore it on access check.
3657 if (conn->sconn->using_smb2) {
3659 * SMB2 doesn't return it (according to Microsoft tests).
3660 * Test Case: TestSuite_ScenarioNo009GrantedAccessTestS0
3661 * File created with access = 0x7 (Read, Write, Delete)
3662 * Query Info on file returns 0x87 (Read, Write, Delete, Read Attributes)
3664 fsp->access_mask = access_mask;
3666 /* But SMB1 does. */
3667 fsp->access_mask = access_mask | FILE_READ_ATTRIBUTES;
3672 * stat opens on existing files don't get oplocks.
3673 * They can get leases.
3675 * Note that we check for stat open on the *open_access_mask*,
3676 * i.e. the access mask we actually used to do the open,
3677 * not the one the client asked for (which is in
3678 * fsp->access_mask). This is due to the fact that
3679 * FILE_OVERWRITE and FILE_OVERWRITE_IF add in O_TRUNC,
3680 * which adds FILE_WRITE_DATA to open_access_mask.
3682 if (is_stat_open(open_access_mask) && lease == NULL) {
3683 oplock_request = NO_OPLOCK;
3687 if (new_file_created) {
3688 info = FILE_WAS_CREATED;
3690 if (flags2 & O_TRUNC) {
3691 info = FILE_WAS_OVERWRITTEN;
3693 info = FILE_WAS_OPENED;
3702 * Setup the oplock info in both the shared memory and
3705 status = grant_fsp_oplock_type(req, fsp, lck, oplock_request, lease);
3706 if (!NT_STATUS_IS_OK(status)) {
3712 /* Handle strange delete on close create semantics. */
3713 if (create_options & FILE_DELETE_ON_CLOSE) {
3715 status = can_set_delete_on_close(fsp, new_dos_attributes);
3717 if (!NT_STATUS_IS_OK(status)) {
3718 /* Remember to delete the mode we just added. */
3719 del_share_mode(lck, fsp);
3724 /* Note that here we set the *inital* delete on close flag,
3725 not the regular one. The magic gets handled in close. */
3726 fsp->initial_delete_on_close = True;
3729 if (info != FILE_WAS_OPENED) {
3730 /* Overwritten files should be initially set as archive */
3731 if ((info == FILE_WAS_OVERWRITTEN && lp_map_archive(SNUM(conn))) ||
3732 lp_store_dos_attributes(SNUM(conn))) {
3734 if (file_set_dosmode(conn, smb_fname,
3735 new_dos_attributes | FILE_ATTRIBUTE_ARCHIVE,
3736 parent_dir, true) == 0) {
3737 unx_mode = smb_fname->st.st_ex_mode;
3743 /* Determine sparse flag. */
3745 /* POSIX opens are sparse by default. */
3746 fsp->is_sparse = true;
3748 fsp->is_sparse = (file_existed &&
3749 (existing_dos_attributes & FILE_ATTRIBUTE_SPARSE));
3753 * Take care of inherited ACLs on created files - if default ACL not
3757 if (!posix_open && new_file_created && !def_acl) {
3759 int saved_errno = errno; /* We might get ENOSYS in the next
3762 if (SMB_VFS_FCHMOD_ACL(fsp, unx_mode) == -1 &&
3764 errno = saved_errno; /* Ignore ENOSYS */
3767 } else if (new_unx_mode) {
3771 /* Attributes need changing. File already existed. */
3774 int saved_errno = errno; /* We might get ENOSYS in the
3776 ret = SMB_VFS_FCHMOD_ACL(fsp, new_unx_mode);
3778 if (ret == -1 && errno == ENOSYS) {
3779 errno = saved_errno; /* Ignore ENOSYS */
3781 DEBUG(5, ("open_file_ntcreate: reset "
3782 "attributes of file %s to 0%o\n",
3783 smb_fname_str_dbg(smb_fname),
3784 (unsigned int)new_unx_mode));
3785 ret = 0; /* Don't do the fchmod below. */
3790 (SMB_VFS_FCHMOD(fsp, new_unx_mode) == -1))
3791 DEBUG(5, ("open_file_ntcreate: failed to reset "
3792 "attributes of file %s to 0%o\n",
3793 smb_fname_str_dbg(smb_fname),
3794 (unsigned int)new_unx_mode));
3799 * Deal with other opens having a modified write time.
3801 struct timespec write_time = get_share_mode_write_time(lck);
3803 if (!null_timespec(write_time)) {
3804 update_stat_ex_mtime(&fsp->fsp_name->st, write_time);
3810 return NT_STATUS_OK;
3813 static NTSTATUS mkdir_internal(connection_struct *conn,
3814 struct smb_filename *smb_dname,
3815 uint32_t file_attributes)
3818 char *parent_dir = NULL;
3820 bool posix_open = false;
3821 bool need_re_stat = false;
3822 uint32_t access_mask = SEC_DIR_ADD_SUBDIR;
3824 if (!CAN_WRITE(conn) || (access_mask & ~(conn->share_access))) {
3825 DEBUG(5,("mkdir_internal: failing share access "
3826 "%s\n", lp_servicename(talloc_tos(), SNUM(conn))));
3827 return NT_STATUS_ACCESS_DENIED;
3830 if (!parent_dirname(talloc_tos(), smb_dname->base_name, &parent_dir,
3832 return NT_STATUS_NO_MEMORY;
3835 if (file_attributes & FILE_FLAG_POSIX_SEMANTICS) {
3837 mode = (mode_t)(file_attributes & ~FILE_FLAG_POSIX_SEMANTICS);
3839 mode = unix_mode(conn, FILE_ATTRIBUTE_DIRECTORY, smb_dname, parent_dir);
3842 status = check_parent_access(conn,
3845 if(!NT_STATUS_IS_OK(status)) {
3846 DEBUG(5,("mkdir_internal: check_parent_access "
3847 "on directory %s for path %s returned %s\n",
3849 smb_dname->base_name,
3850 nt_errstr(status) ));
3854 if (SMB_VFS_MKDIR(conn, smb_dname, mode) != 0) {
3855 return map_nt_error_from_unix(errno);
3858 /* Ensure we're checking for a symlink here.... */
3859 /* We don't want to get caught by a symlink racer. */
3861 if (SMB_VFS_LSTAT(conn, smb_dname) == -1) {
3862 DEBUG(2, ("Could not stat directory '%s' just created: %s\n",
3863 smb_fname_str_dbg(smb_dname), strerror(errno)));
3864 return map_nt_error_from_unix(errno);
3867 if (!S_ISDIR(smb_dname->st.st_ex_mode)) {
3868 DEBUG(0, ("Directory '%s' just created is not a directory !\n",
3869 smb_fname_str_dbg(smb_dname)));
3870 return NT_STATUS_NOT_A_DIRECTORY;
3873 if (lp_store_dos_attributes(SNUM(conn))) {
3875 file_set_dosmode(conn, smb_dname,
3876 file_attributes | FILE_ATTRIBUTE_DIRECTORY,
3881 if (lp_inherit_permissions(SNUM(conn))) {
3882 inherit_access_posix_acl(conn, parent_dir,
3884 need_re_stat = true;
3889 * Check if high bits should have been set,
3890 * then (if bits are missing): add them.
3891 * Consider bits automagically set by UNIX, i.e. SGID bit from parent
3894 if ((mode & ~(S_IRWXU|S_IRWXG|S_IRWXO)) &&
3895 (mode & ~smb_dname->st.st_ex_mode)) {
3896 SMB_VFS_CHMOD(conn, smb_dname,
3897 (smb_dname->st.st_ex_mode |
3898 (mode & ~smb_dname->st.st_ex_mode)));
3899 need_re_stat = true;
3903 /* Change the owner if required. */
3904 if (lp_inherit_owner(SNUM(conn)) != INHERIT_OWNER_NO) {
3905 change_dir_owner_to_parent(conn, parent_dir,
3908 need_re_stat = true;
3912 if (SMB_VFS_LSTAT(conn, smb_dname) == -1) {
3913 DEBUG(2, ("Could not stat directory '%s' just created: %s\n",
3914 smb_fname_str_dbg(smb_dname), strerror(errno)));
3915 return map_nt_error_from_unix(errno);
3919 notify_fname(conn, NOTIFY_ACTION_ADDED, FILE_NOTIFY_CHANGE_DIR_NAME,
3920 smb_dname->base_name);
3922 return NT_STATUS_OK;
3925 /****************************************************************************
3926 Open a directory from an NT SMB call.
3927 ****************************************************************************/
3929 static NTSTATUS open_directory(connection_struct *conn,
3930 struct smb_request *req,
3931 struct smb_filename *smb_dname,
3932 uint32_t access_mask,
3933 uint32_t share_access,
3934 uint32_t create_disposition,
3935 uint32_t create_options,
3936 uint32_t file_attributes,
3938 files_struct **result)
3940 files_struct *fsp = NULL;
3941 bool dir_existed = VALID_STAT(smb_dname->st) ? True : False;
3942 struct share_mode_lock *lck = NULL;
3944 struct timespec mtimespec;
3948 if (is_ntfs_stream_smb_fname(smb_dname)) {
3949 DEBUG(2, ("open_directory: %s is a stream name!\n",
3950 smb_fname_str_dbg(smb_dname)));
3951 return NT_STATUS_NOT_A_DIRECTORY;
3954 if (!(file_attributes & FILE_FLAG_POSIX_SEMANTICS)) {
3955 /* Ensure we have a directory attribute. */
3956 file_attributes |= FILE_ATTRIBUTE_DIRECTORY;
3959 DEBUG(5,("open_directory: opening directory %s, access_mask = 0x%x, "
3960 "share_access = 0x%x create_options = 0x%x, "
3961 "create_disposition = 0x%x, file_attributes = 0x%x\n",
3962 smb_fname_str_dbg(smb_dname),
3963 (unsigned int)access_mask,
3964 (unsigned int)share_access,
3965 (unsigned int)create_options,
3966 (unsigned int)create_disposition,
3967 (unsigned int)file_attributes));
3969 status = smbd_calculate_access_mask(conn, smb_dname, false,
3970 access_mask, &access_mask);
3971 if (!NT_STATUS_IS_OK(status)) {
3972 DEBUG(10, ("open_directory: smbd_calculate_access_mask "
3973 "on file %s returned %s\n",
3974 smb_fname_str_dbg(smb_dname),
3975 nt_errstr(status)));
3979 if ((access_mask & SEC_FLAG_SYSTEM_SECURITY) &&
3980 !security_token_has_privilege(get_current_nttok(conn),
3981 SEC_PRIV_SECURITY)) {
3982 DEBUG(10, ("open_directory: open on %s "
3983 "failed - SEC_FLAG_SYSTEM_SECURITY denied.\n",
3984 smb_fname_str_dbg(smb_dname)));
3985 return NT_STATUS_PRIVILEGE_NOT_HELD;
3988 switch( create_disposition ) {
3992 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3995 info = FILE_WAS_OPENED;
4000 /* If directory exists error. If directory doesn't
4004 status = NT_STATUS_OBJECT_NAME_COLLISION;
4005 DEBUG(2, ("open_directory: unable to create "
4006 "%s. Error was %s\n",
4007 smb_fname_str_dbg(smb_dname),
4008 nt_errstr(status)));
4012 status = mkdir_internal(conn, smb_dname,
4015 if (!NT_STATUS_IS_OK(status)) {
4016 DEBUG(2, ("open_directory: unable to create "
4017 "%s. Error was %s\n",
4018 smb_fname_str_dbg(smb_dname),
4019 nt_errstr(status)));
4023 info = FILE_WAS_CREATED;
4028 * If directory exists open. If directory doesn't
4033 status = NT_STATUS_OK;
4034 info = FILE_WAS_OPENED;
4036 status = mkdir_internal(conn, smb_dname,
4039 if (NT_STATUS_IS_OK(status)) {
4040 info = FILE_WAS_CREATED;
4042 /* Cope with create race. */
4043 if (!NT_STATUS_EQUAL(status,
4044 NT_STATUS_OBJECT_NAME_COLLISION)) {
4045 DEBUG(2, ("open_directory: unable to create "
4046 "%s. Error was %s\n",
4047 smb_fname_str_dbg(smb_dname),
4048 nt_errstr(status)));
4053 * If mkdir_internal() returned
4054 * NT_STATUS_OBJECT_NAME_COLLISION
4055 * we still must lstat the path.
4058 if (SMB_VFS_LSTAT(conn, smb_dname)
4060 DEBUG(2, ("Could not stat "
4061 "directory '%s' just "
4066 return map_nt_error_from_unix(
4070 info = FILE_WAS_OPENED;
4076 case FILE_SUPERSEDE:
4077 case FILE_OVERWRITE:
4078 case FILE_OVERWRITE_IF:
4080 DEBUG(5,("open_directory: invalid create_disposition "
4081 "0x%x for directory %s\n",
4082 (unsigned int)create_disposition,
4083 smb_fname_str_dbg(smb_dname)));
4084 return NT_STATUS_INVALID_PARAMETER;
4087 if(!S_ISDIR(smb_dname->st.st_ex_mode)) {
4088 DEBUG(5,("open_directory: %s is not a directory !\n",
4089 smb_fname_str_dbg(smb_dname)));
4090 return NT_STATUS_NOT_A_DIRECTORY;
4093 if (info == FILE_WAS_OPENED) {
4094 status = smbd_check_access_rights(conn,
4098 if (!NT_STATUS_IS_OK(status)) {
4099 DEBUG(10, ("open_directory: smbd_check_access_rights on "
4100 "file %s failed with %s\n",
4101 smb_fname_str_dbg(smb_dname),
4102 nt_errstr(status)));
4107 status = file_new(req, conn, &fsp);
4108 if(!NT_STATUS_IS_OK(status)) {
4113 * Setup the files_struct for it.
4116 fsp->file_id = vfs_file_id_from_sbuf(conn, &smb_dname->st);
4117 fsp->vuid = req ? req->vuid : UID_FIELD_INVALID;
4118 fsp->file_pid = req ? req->smbpid : 0;
4119 fsp->can_lock = False;
4120 fsp->can_read = False;
4121 fsp->can_write = False;
4123 fsp->share_access = share_access;
4124 fsp->fh->private_options = 0;
4126 * According to Samba4, SEC_FILE_READ_ATTRIBUTE is always granted,
4128 fsp->access_mask = access_mask | FILE_READ_ATTRIBUTES;
4129 fsp->print_file = NULL;
4130 fsp->modified = False;
4131 fsp->oplock_type = NO_OPLOCK;
4132 fsp->sent_oplock_break = NO_BREAK_SENT;
4133 fsp->is_directory = True;
4134 if (file_attributes & FILE_FLAG_POSIX_SEMANTICS) {
4135 fsp->posix_flags |= FSP_POSIX_FLAGS_ALL;
4137 status = fsp_set_smb_fname(fsp, smb_dname);
4138 if (!NT_STATUS_IS_OK(status)) {
4139 file_free(req, fsp);
4143 /* Don't store old timestamps for directory
4144 handles in the internal database. We don't
4145 update them in there if new objects
4146 are creaded in the directory. Currently
4147 we only update timestamps on file writes.
4150 ZERO_STRUCT(mtimespec);
4152 if (access_mask & (FILE_LIST_DIRECTORY|
4154 FILE_ADD_SUBDIRECTORY|
4157 FILE_DELETE_CHILD)) {
4159 status = fd_open(conn, fsp, O_RDONLY|O_DIRECTORY, 0);
4161 /* POSIX allows us to open a directory with O_RDONLY. */
4162 status = fd_open(conn, fsp, O_RDONLY, 0);
4164 if (!NT_STATUS_IS_OK(status)) {
4165 DEBUG(5, ("open_directory: Could not open fd for "
4167 smb_fname_str_dbg(smb_dname),
4168 nt_errstr(status)));
4169 file_free(req, fsp);
4174 DEBUG(10, ("Not opening Directory %s\n",
4175 smb_fname_str_dbg(smb_dname)));
4178 status = vfs_stat_fsp(fsp);
4179 if (!NT_STATUS_IS_OK(status)) {
4181 file_free(req, fsp);
4185 if(!S_ISDIR(fsp->fsp_name->st.st_ex_mode)) {
4186 DEBUG(5,("open_directory: %s is not a directory !\n",
4187 smb_fname_str_dbg(smb_dname)));
4189 file_free(req, fsp);
4190 return NT_STATUS_NOT_A_DIRECTORY;
4193 /* Ensure there was no race condition. We need to check
4194 * dev/inode but not permissions, as these can change
4196 if (!check_same_dev_ino(&smb_dname->st, &fsp->fsp_name->st)) {
4197 DEBUG(5,("open_directory: stat struct differs for "
4199 smb_fname_str_dbg(smb_dname)));
4201 file_free(req, fsp);
4202 return NT_STATUS_ACCESS_DENIED;
4205 lck = get_share_mode_lock(talloc_tos(), fsp->file_id,
4206 conn->connectpath, smb_dname,
4210 DEBUG(0, ("open_directory: Could not get share mode lock for "
4211 "%s\n", smb_fname_str_dbg(smb_dname)));
4213 file_free(req, fsp);
4214 return NT_STATUS_SHARING_VIOLATION;
4217 if (has_delete_on_close(lck, fsp->name_hash)) {
4220 file_free(req, fsp);
4221 return NT_STATUS_DELETE_PENDING;
4224 status = open_mode_check(conn, lck,
4225 access_mask, share_access);
4227 if (!NT_STATUS_IS_OK(status)) {
4230 file_free(req, fsp);
4234 ok = set_share_mode(lck, fsp, get_current_uid(conn),
4235 req ? req->mid : 0, NO_OPLOCK,
4240 file_free(req, fsp);
4241 return NT_STATUS_NO_MEMORY;
4244 /* For directories the delete on close bit at open time seems
4245 always to be honored on close... See test 19 in Samba4 BASE-DELETE. */
4246 if (create_options & FILE_DELETE_ON_CLOSE) {
4247 status = can_set_delete_on_close(fsp, 0);
4248 if (!NT_STATUS_IS_OK(status) && !NT_STATUS_EQUAL(status, NT_STATUS_DIRECTORY_NOT_EMPTY)) {
4249 del_share_mode(lck, fsp);
4252 file_free(req, fsp);
4256 if (NT_STATUS_IS_OK(status)) {
4257 /* Note that here we set the *inital* delete on close flag,
4258 not the regular one. The magic gets handled in close. */
4259 fsp->initial_delete_on_close = True;
4265 * Deal with other opens having a modified write time. Is this
4266 * possible for directories?
4268 struct timespec write_time = get_share_mode_write_time(lck);
4270 if (!null_timespec(write_time)) {
4271 update_stat_ex_mtime(&fsp->fsp_name->st, write_time);
4282 return NT_STATUS_OK;
4285 NTSTATUS create_directory(connection_struct *conn, struct smb_request *req,
4286 struct smb_filename *smb_dname)
4291 status = SMB_VFS_CREATE_FILE(
4294 0, /* root_dir_fid */
4295 smb_dname, /* fname */
4296 FILE_READ_ATTRIBUTES, /* access_mask */
4297 FILE_SHARE_NONE, /* share_access */
4298 FILE_CREATE, /* create_disposition*/
4299 FILE_DIRECTORY_FILE, /* create_options */
4300 FILE_ATTRIBUTE_DIRECTORY, /* file_attributes */
4301 0, /* oplock_request */
4303 0, /* allocation_size */
4304 0, /* private_flags */
4309 NULL, NULL); /* create context */
4311 if (NT_STATUS_IS_OK(status)) {
4312 close_file(req, fsp, NORMAL_CLOSE);
4318 /****************************************************************************
4319 Receive notification that one of our open files has been renamed by another
4321 ****************************************************************************/
4323 void msg_file_was_renamed(struct messaging_context *msg,
4326 struct server_id server_id,
4330 char *frm = (char *)data->data;
4332 const char *sharepath;
4333 const char *base_name;
4334 const char *stream_name;
4335 struct smb_filename *smb_fname = NULL;
4336 size_t sp_len, bn_len;
4338 struct smbd_server_connection *sconn =
4339 talloc_get_type_abort(private_data,
4340 struct smbd_server_connection);
4342 if (data->data == NULL
4343 || data->length < MSG_FILE_RENAMED_MIN_SIZE + 2) {
4344 DEBUG(0, ("msg_file_was_renamed: Got invalid msg len %d\n",
4345 (int)data->length));
4349 /* Unpack the message. */
4350 pull_file_id_24(frm, &id);
4351 sharepath = &frm[24];
4352 sp_len = strlen(sharepath);
4353 base_name = sharepath + sp_len + 1;
4354 bn_len = strlen(base_name);
4355 stream_name = sharepath + sp_len + 1 + bn_len + 1;
4357 /* stream_name must always be NULL if there is no stream. */
4358 if (stream_name[0] == '\0') {
4362 smb_fname = synthetic_smb_fname(talloc_tos(),
4367 if (smb_fname == NULL) {
4371 DEBUG(10,("msg_file_was_renamed: Got rename message for sharepath %s, new name %s, "
4373 sharepath, smb_fname_str_dbg(smb_fname),
4374 file_id_string_tos(&id)));
4376 for(fsp = file_find_di_first(sconn, id); fsp;
4377 fsp = file_find_di_next(fsp)) {
4378 if (memcmp(fsp->conn->connectpath, sharepath, sp_len) == 0) {
4380 DEBUG(10,("msg_file_was_renamed: renaming file %s from %s -> %s\n",
4381 fsp_fnum_dbg(fsp), fsp_str_dbg(fsp),
4382 smb_fname_str_dbg(smb_fname)));
4383 status = fsp_set_smb_fname(fsp, smb_fname);
4384 if (!NT_STATUS_IS_OK(status)) {
4389 /* Now we have the complete path we can work out if this is
4390 actually within this share and adjust newname accordingly. */
4391 DEBUG(10,("msg_file_was_renamed: share mismatch (sharepath %s "
4392 "not sharepath %s) "
4393 "%s from %s -> %s\n",
4394 fsp->conn->connectpath,
4398 smb_fname_str_dbg(smb_fname)));
4402 TALLOC_FREE(smb_fname);
4407 * If a main file is opened for delete, all streams need to be checked for
4408 * !FILE_SHARE_DELETE. Do this by opening with DELETE_ACCESS.
4409 * If that works, delete them all by setting the delete on close and close.
4412 static NTSTATUS open_streams_for_delete(connection_struct *conn,
4413 const struct smb_filename *smb_fname)
4415 struct stream_struct *stream_info = NULL;
4416 files_struct **streams = NULL;
4418 unsigned int num_streams = 0;
4419 TALLOC_CTX *frame = talloc_stackframe();
4422 status = vfs_streaminfo(conn, NULL, smb_fname, talloc_tos(),
4423 &num_streams, &stream_info);
4425 if (NT_STATUS_EQUAL(status, NT_STATUS_NOT_IMPLEMENTED)
4426 || NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
4427 DEBUG(10, ("no streams around\n"));
4429 return NT_STATUS_OK;
4432 if (!NT_STATUS_IS_OK(status)) {
4433 DEBUG(10, ("vfs_streaminfo failed: %s\n",
4434 nt_errstr(status)));
4438 DEBUG(10, ("open_streams_for_delete found %d streams\n",
4441 if (num_streams == 0) {
4443 return NT_STATUS_OK;
4446 streams = talloc_array(talloc_tos(), files_struct *, num_streams);
4447 if (streams == NULL) {
4448 DEBUG(0, ("talloc failed\n"));
4449 status = NT_STATUS_NO_MEMORY;
4453 for (i=0; i<num_streams; i++) {
4454 struct smb_filename *smb_fname_cp;
4456 if (strequal(stream_info[i].name, "::$DATA")) {
4461 smb_fname_cp = synthetic_smb_fname(talloc_tos(),
4462 smb_fname->base_name,
4463 stream_info[i].name,
4466 ~SMB_FILENAME_POSIX_PATH));
4467 if (smb_fname_cp == NULL) {
4468 status = NT_STATUS_NO_MEMORY;
4472 if (SMB_VFS_STAT(conn, smb_fname_cp) == -1) {
4473 DEBUG(10, ("Unable to stat stream: %s\n",
4474 smb_fname_str_dbg(smb_fname_cp)));
4477 status = SMB_VFS_CREATE_FILE(
4480 0, /* root_dir_fid */
4481 smb_fname_cp, /* fname */
4482 DELETE_ACCESS, /* access_mask */
4483 (FILE_SHARE_READ | /* share_access */
4484 FILE_SHARE_WRITE | FILE_SHARE_DELETE),
4485 FILE_OPEN, /* create_disposition*/
4486 0, /* create_options */
4487 FILE_ATTRIBUTE_NORMAL, /* file_attributes */
4488 0, /* oplock_request */
4490 0, /* allocation_size */
4491 NTCREATEX_OPTIONS_PRIVATE_STREAM_DELETE, /* private_flags */
4494 &streams[i], /* result */
4496 NULL, NULL); /* create context */
4498 if (!NT_STATUS_IS_OK(status)) {
4499 DEBUG(10, ("Could not open stream %s: %s\n",
4500 smb_fname_str_dbg(smb_fname_cp),
4501 nt_errstr(status)));
4503 TALLOC_FREE(smb_fname_cp);
4506 TALLOC_FREE(smb_fname_cp);
4510 * don't touch the variable "status" beyond this point :-)
4513 for (i -= 1 ; i >= 0; i--) {
4514 if (streams[i] == NULL) {
4518 DEBUG(10, ("Closing stream # %d, %s\n", i,
4519 fsp_str_dbg(streams[i])));
4520 close_file(NULL, streams[i], NORMAL_CLOSE);
4528 /*********************************************************************
4529 Create a default ACL by inheriting from the parent. If no inheritance
4530 from the parent available, don't set anything. This will leave the actual
4531 permissions the new file or directory already got from the filesystem
4532 as the NT ACL when read.
4533 *********************************************************************/
4535 static NTSTATUS inherit_new_acl(files_struct *fsp)
4537 TALLOC_CTX *frame = talloc_stackframe();
4538 char *parent_name = NULL;
4539 struct security_descriptor *parent_desc = NULL;
4540 NTSTATUS status = NT_STATUS_OK;
4541 struct security_descriptor *psd = NULL;
4542 const struct dom_sid *owner_sid = NULL;
4543 const struct dom_sid *group_sid = NULL;
4544 uint32_t security_info_sent = (SECINFO_OWNER | SECINFO_GROUP | SECINFO_DACL);
4545 struct security_token *token = fsp->conn->session_info->security_token;
4546 bool inherit_owner =
4547 (lp_inherit_owner(SNUM(fsp->conn)) == INHERIT_OWNER_WINDOWS_AND_UNIX);
4548 bool inheritable_components = false;
4549 bool try_builtin_administrators = false;
4550 const struct dom_sid *BA_U_sid = NULL;
4551 const struct dom_sid *BA_G_sid = NULL;
4552 bool try_system = false;
4553 const struct dom_sid *SY_U_sid = NULL;
4554 const struct dom_sid *SY_G_sid = NULL;
4556 struct smb_filename *parent_smb_fname = NULL;
4558 if (!parent_dirname(frame, fsp->fsp_name->base_name, &parent_name, NULL)) {
4560 return NT_STATUS_NO_MEMORY;
4562 parent_smb_fname = synthetic_smb_fname(talloc_tos(),
4566 fsp->fsp_name->flags);
4568 if (parent_smb_fname == NULL) {
4570 return NT_STATUS_NO_MEMORY;
4573 status = SMB_VFS_GET_NT_ACL(fsp->conn,
4575 (SECINFO_OWNER | SECINFO_GROUP | SECINFO_DACL),
4578 if (!NT_STATUS_IS_OK(status)) {
4583 inheritable_components = sd_has_inheritable_components(parent_desc,
4586 if (!inheritable_components && !inherit_owner) {
4588 /* Nothing to inherit and not setting owner. */
4589 return NT_STATUS_OK;
4592 /* Create an inherited descriptor from the parent. */
4594 if (DEBUGLEVEL >= 10) {
4595 DEBUG(10,("inherit_new_acl: parent acl for %s is:\n",
4596 fsp_str_dbg(fsp) ));
4597 NDR_PRINT_DEBUG(security_descriptor, parent_desc);
4600 /* Inherit from parent descriptor if "inherit owner" set. */
4601 if (inherit_owner) {
4602 owner_sid = parent_desc->owner_sid;
4603 group_sid = parent_desc->group_sid;
4606 if (owner_sid == NULL) {
4607 if (security_token_has_builtin_administrators(token)) {
4608 try_builtin_administrators = true;
4609 } else if (security_token_is_system(token)) {
4610 try_builtin_administrators = true;
4615 if (group_sid == NULL &&
4616 token->num_sids == PRIMARY_GROUP_SID_INDEX)
4618 if (security_token_is_system(token)) {
4619 try_builtin_administrators = true;
4624 if (try_builtin_administrators) {
4629 ok = sids_to_unixids(&global_sid_Builtin_Administrators, 1, &ids);
4633 BA_U_sid = &global_sid_Builtin_Administrators;
4634 BA_G_sid = &global_sid_Builtin_Administrators;
4637 BA_U_sid = &global_sid_Builtin_Administrators;
4640 BA_G_sid = &global_sid_Builtin_Administrators;
4653 ok = sids_to_unixids(&global_sid_System, 1, &ids);
4657 SY_U_sid = &global_sid_System;
4658 SY_G_sid = &global_sid_System;
4661 SY_U_sid = &global_sid_System;
4664 SY_G_sid = &global_sid_System;
4672 if (owner_sid == NULL) {
4673 owner_sid = BA_U_sid;
4676 if (owner_sid == NULL) {
4677 owner_sid = SY_U_sid;
4680 if (group_sid == NULL) {
4681 group_sid = SY_G_sid;
4684 if (try_system && group_sid == NULL) {
4685 group_sid = BA_G_sid;
4688 if (owner_sid == NULL) {
4689 owner_sid = &token->sids[PRIMARY_USER_SID_INDEX];
4691 if (group_sid == NULL) {
4692 if (token->num_sids == PRIMARY_GROUP_SID_INDEX) {
4693 group_sid = &token->sids[PRIMARY_USER_SID_INDEX];
4695 group_sid = &token->sids[PRIMARY_GROUP_SID_INDEX];
4699 status = se_create_child_secdesc(frame,
4706 if (!NT_STATUS_IS_OK(status)) {
4711 /* If inheritable_components == false,
4712 se_create_child_secdesc()
4713 creates a security desriptor with a NULL dacl
4714 entry, but with SEC_DESC_DACL_PRESENT. We need
4715 to remove that flag. */
4717 if (!inheritable_components) {
4718 security_info_sent &= ~SECINFO_DACL;
4719 psd->type &= ~SEC_DESC_DACL_PRESENT;
4722 if (DEBUGLEVEL >= 10) {
4723 DEBUG(10,("inherit_new_acl: child acl for %s is:\n",
4724 fsp_str_dbg(fsp) ));
4725 NDR_PRINT_DEBUG(security_descriptor, psd);
4728 if (inherit_owner) {
4729 /* We need to be root to force this. */
4732 status = SMB_VFS_FSET_NT_ACL(fsp,
4735 if (inherit_owner) {
4743 * If we already have a lease, it must match the new file id. [MS-SMB2]
4744 * 3.3.5.9.8 speaks about INVALID_PARAMETER if an already used lease key is
4745 * used for a different file name.
4748 struct lease_match_state {
4749 /* Input parameters. */
4750 TALLOC_CTX *mem_ctx;
4751 const char *servicepath;
4752 const struct smb_filename *fname;
4755 /* Return parameters. */
4756 uint32_t num_file_ids;
4757 struct file_id *ids;
4758 NTSTATUS match_status;
4761 /*************************************************************
4762 File doesn't exist but this lease key+guid is already in use.
4764 This is only allowable in the dynamic share case where the
4765 service path must be different.
4767 There is a small race condition here in the multi-connection
4768 case where a client sends two create calls on different connections,
4769 where the file doesn't exist and one smbd creates the leases_db
4770 entry first, but this will get fixed by the multichannel cleanup
4771 when all identical client_guids get handled by a single smbd.
4772 **************************************************************/
4774 static void lease_match_parser_new_file(
4776 const struct leases_db_file *files,
4777 struct lease_match_state *state)
4781 for (i = 0; i < num_files; i++) {
4782 const struct leases_db_file *f = &files[i];
4783 if (strequal(state->servicepath, f->servicepath)) {
4784 state->match_status = NT_STATUS_INVALID_PARAMETER;
4789 /* Dynamic share case. Break leases on all other files. */
4790 state->match_status = leases_db_copy_file_ids(state->mem_ctx,
4794 if (!NT_STATUS_IS_OK(state->match_status)) {
4798 state->num_file_ids = num_files;
4799 state->match_status = NT_STATUS_OPLOCK_NOT_GRANTED;
4803 static void lease_match_parser(
4805 const struct leases_db_file *files,
4808 struct lease_match_state *state =
4809 (struct lease_match_state *)private_data;
4812 if (!state->file_existed) {
4814 * Deal with name mismatch or
4815 * possible dynamic share case separately
4816 * to make code clearer.
4818 lease_match_parser_new_file(num_files,
4825 state->match_status = NT_STATUS_OK;
4827 for (i = 0; i < num_files; i++) {
4828 const struct leases_db_file *f = &files[i];
4830 /* Everything should be the same. */
4831 if (!file_id_equal(&state->id, &f->id)) {
4832 /* This should catch all dynamic share cases. */
4833 state->match_status = NT_STATUS_OPLOCK_NOT_GRANTED;
4836 if (!strequal(f->servicepath, state->servicepath)) {
4837 state->match_status = NT_STATUS_INVALID_PARAMETER;
4840 if (!strequal(f->base_name, state->fname->base_name)) {
4841 state->match_status = NT_STATUS_INVALID_PARAMETER;
4844 if (!strequal(f->stream_name, state->fname->stream_name)) {
4845 state->match_status = NT_STATUS_INVALID_PARAMETER;
4850 if (NT_STATUS_IS_OK(state->match_status)) {
4852 * Common case - just opening another handle on a
4853 * file on a non-dynamic share.
4858 if (NT_STATUS_EQUAL(state->match_status, NT_STATUS_INVALID_PARAMETER)) {
4859 /* Mismatched path. Error back to client. */
4864 * File id mismatch. Dynamic share case NT_STATUS_OPLOCK_NOT_GRANTED.
4865 * Don't allow leases.
4868 state->match_status = leases_db_copy_file_ids(state->mem_ctx,
4872 if (!NT_STATUS_IS_OK(state->match_status)) {
4876 state->num_file_ids = num_files;
4877 state->match_status = NT_STATUS_OPLOCK_NOT_GRANTED;
4881 static NTSTATUS lease_match(connection_struct *conn,
4882 struct smb_request *req,
4883 struct smb2_lease_key *lease_key,
4884 const char *servicepath,
4885 const struct smb_filename *fname,
4886 uint16_t *p_version,
4889 struct smbd_server_connection *sconn = req->sconn;
4890 TALLOC_CTX *tos = talloc_tos();
4891 struct lease_match_state state = {
4893 .servicepath = servicepath,
4895 .match_status = NT_STATUS_OK
4900 state.file_existed = VALID_STAT(fname->st);
4901 if (state.file_existed) {
4902 state.id = vfs_file_id_from_sbuf(conn, &fname->st);
4904 memset(&state.id, '\0', sizeof(state.id));
4907 status = leases_db_parse(&sconn->client->connections->smb2.client.guid,
4908 lease_key, lease_match_parser, &state);
4909 if (!NT_STATUS_IS_OK(status)) {
4911 * Not found or error means okay: We can make the lease pass
4913 return NT_STATUS_OK;
4915 if (!NT_STATUS_EQUAL(state.match_status, NT_STATUS_OPLOCK_NOT_GRANTED)) {
4917 * Anything but NT_STATUS_OPLOCK_NOT_GRANTED, let the caller
4920 return state.match_status;
4923 /* We have to break all existing leases. */
4924 for (i = 0; i < state.num_file_ids; i++) {
4925 struct share_mode_lock *lck;
4926 struct share_mode_data *d;
4929 if (file_id_equal(&state.ids[i], &state.id)) {
4930 /* Don't need to break our own file. */
4934 lck = get_existing_share_mode_lock(talloc_tos(), state.ids[i]);
4936 /* Race condition - file already closed. */
4940 for (j=0; j<d->num_share_modes; j++) {
4941 struct share_mode_entry *e = &d->share_modes[j];
4942 uint32_t e_lease_type = get_lease_type(d, e);
4943 struct share_mode_lease *l = NULL;
4945 if (share_mode_stale_pid(d, j)) {
4949 if (e->op_type == LEASE_OPLOCK) {
4950 l = &lck->data->leases[e->lease_idx];
4951 if (!smb2_lease_key_equal(&l->lease_key,
4955 *p_epoch = l->epoch;
4956 *p_version = l->lease_version;
4959 if (e_lease_type == SMB2_LEASE_NONE) {
4963 send_break_message(conn->sconn->msg_ctx, e,
4967 * Windows 7 and 8 lease clients
4968 * are broken in that they will not
4969 * respond to lease break requests
4970 * whilst waiting for an outstanding
4971 * open request on that lease handle
4972 * on the same TCP connection, due
4973 * to holding an internal inode lock.
4975 * This means we can't reschedule
4976 * ourselves here, but must return
4981 * Send the breaks and then return
4982 * SMB2_LEASE_NONE in the lease handle
4983 * to cause them to acknowledge the
4984 * lease break. Consulatation with
4985 * Microsoft engineering confirmed
4986 * this approach is safe.
4993 * Ensure we don't grant anything more so we
4996 return NT_STATUS_OPLOCK_NOT_GRANTED;
5000 * Wrapper around open_file_ntcreate and open_directory
5003 static NTSTATUS create_file_unixpath(connection_struct *conn,
5004 struct smb_request *req,
5005 struct smb_filename *smb_fname,
5006 uint32_t access_mask,
5007 uint32_t share_access,
5008 uint32_t create_disposition,
5009 uint32_t create_options,
5010 uint32_t file_attributes,
5011 uint32_t oplock_request,
5012 struct smb2_lease *lease,
5013 uint64_t allocation_size,
5014 uint32_t private_flags,
5015 struct security_descriptor *sd,
5016 struct ea_list *ea_list,
5018 files_struct **result,
5021 int info = FILE_WAS_OPENED;
5022 files_struct *base_fsp = NULL;
5023 files_struct *fsp = NULL;
5026 DEBUG(10,("create_file_unixpath: access_mask = 0x%x "
5027 "file_attributes = 0x%x, share_access = 0x%x, "
5028 "create_disposition = 0x%x create_options = 0x%x "
5029 "oplock_request = 0x%x private_flags = 0x%x "
5030 "ea_list = 0x%p, sd = 0x%p, "
5032 (unsigned int)access_mask,
5033 (unsigned int)file_attributes,
5034 (unsigned int)share_access,
5035 (unsigned int)create_disposition,
5036 (unsigned int)create_options,
5037 (unsigned int)oplock_request,
5038 (unsigned int)private_flags,
5039 ea_list, sd, smb_fname_str_dbg(smb_fname)));
5041 if (create_options & FILE_OPEN_BY_FILE_ID) {
5042 status = NT_STATUS_NOT_SUPPORTED;
5046 if (create_options & NTCREATEX_OPTIONS_INVALID_PARAM_MASK) {
5047 status = NT_STATUS_INVALID_PARAMETER;
5052 oplock_request |= INTERNAL_OPEN_ONLY;
5055 if (lease != NULL) {
5056 uint16_t epoch = lease->lease_epoch;
5057 uint16_t version = lease->lease_version;
5058 status = lease_match(conn,
5065 if (NT_STATUS_EQUAL(status, NT_STATUS_OPLOCK_NOT_GRANTED)) {
5066 /* Dynamic share file. No leases and update epoch... */
5067 lease->lease_state = SMB2_LEASE_NONE;
5068 lease->lease_epoch = epoch;
5069 lease->lease_version = version;
5070 } else if (!NT_STATUS_IS_OK(status)) {
5075 if ((conn->fs_capabilities & FILE_NAMED_STREAMS)
5076 && (access_mask & DELETE_ACCESS)
5077 && !is_ntfs_stream_smb_fname(smb_fname)) {
5079 * We can't open a file with DELETE access if any of the
5080 * streams is open without FILE_SHARE_DELETE
5082 status = open_streams_for_delete(conn, smb_fname);
5084 if (!NT_STATUS_IS_OK(status)) {
5089 if ((access_mask & SEC_FLAG_SYSTEM_SECURITY) &&
5090 !security_token_has_privilege(get_current_nttok(conn),
5091 SEC_PRIV_SECURITY)) {
5092 DEBUG(10, ("create_file_unixpath: open on %s "
5093 "failed - SEC_FLAG_SYSTEM_SECURITY denied.\n",
5094 smb_fname_str_dbg(smb_fname)));
5095 status = NT_STATUS_PRIVILEGE_NOT_HELD;
5099 if ((conn->fs_capabilities & FILE_NAMED_STREAMS)
5100 && is_ntfs_stream_smb_fname(smb_fname)
5101 && (!(private_flags & NTCREATEX_OPTIONS_PRIVATE_STREAM_DELETE))) {
5102 uint32_t base_create_disposition;
5103 struct smb_filename *smb_fname_base = NULL;
5105 if (create_options & FILE_DIRECTORY_FILE) {
5106 status = NT_STATUS_NOT_A_DIRECTORY;
5110 switch (create_disposition) {
5112 base_create_disposition = FILE_OPEN;
5115 base_create_disposition = FILE_OPEN_IF;
5119 /* Create an smb_filename with stream_name == NULL. */
5120 smb_fname_base = synthetic_smb_fname(talloc_tos(),
5121 smb_fname->base_name,
5125 if (smb_fname_base == NULL) {
5126 status = NT_STATUS_NO_MEMORY;
5130 if (SMB_VFS_STAT(conn, smb_fname_base) == -1) {
5131 DEBUG(10, ("Unable to stat stream: %s\n",
5132 smb_fname_str_dbg(smb_fname_base)));
5135 * https://bugzilla.samba.org/show_bug.cgi?id=10229
5136 * We need to check if the requested access mask
5137 * could be used to open the underlying file (if
5138 * it existed), as we're passing in zero for the
5139 * access mask to the base filename.
5141 status = check_base_file_access(conn,
5145 if (!NT_STATUS_IS_OK(status)) {
5146 DEBUG(10, ("Permission check "
5147 "for base %s failed: "
5148 "%s\n", smb_fname->base_name,
5149 nt_errstr(status)));
5154 /* Open the base file. */
5155 status = create_file_unixpath(conn, NULL, smb_fname_base, 0,
5158 | FILE_SHARE_DELETE,
5159 base_create_disposition,
5160 0, 0, 0, NULL, 0, 0, NULL, NULL,
5162 TALLOC_FREE(smb_fname_base);
5164 if (!NT_STATUS_IS_OK(status)) {
5165 DEBUG(10, ("create_file_unixpath for base %s failed: "
5166 "%s\n", smb_fname->base_name,
5167 nt_errstr(status)));
5170 /* we don't need the low level fd */
5175 * If it's a request for a directory open, deal with it separately.
5178 if (create_options & FILE_DIRECTORY_FILE) {
5180 if (create_options & FILE_NON_DIRECTORY_FILE) {
5181 status = NT_STATUS_INVALID_PARAMETER;
5185 /* Can't open a temp directory. IFS kit test. */
5186 if (!(file_attributes & FILE_FLAG_POSIX_SEMANTICS) &&
5187 (file_attributes & FILE_ATTRIBUTE_TEMPORARY)) {
5188 status = NT_STATUS_INVALID_PARAMETER;
5193 * We will get a create directory here if the Win32
5194 * app specified a security descriptor in the
5195 * CreateDirectory() call.
5199 status = open_directory(
5200 conn, req, smb_fname, access_mask, share_access,
5201 create_disposition, create_options, file_attributes,
5206 * Ordinary file case.
5209 status = file_new(req, conn, &fsp);
5210 if(!NT_STATUS_IS_OK(status)) {
5214 status = fsp_set_smb_fname(fsp, smb_fname);
5215 if (!NT_STATUS_IS_OK(status)) {
5221 * We're opening the stream element of a
5222 * base_fsp we already opened. Set up the
5225 fsp->base_fsp = base_fsp;
5228 if (allocation_size) {
5229 fsp->initial_allocation_size = smb_roundup(fsp->conn,
5233 status = open_file_ntcreate(conn,
5246 if(!NT_STATUS_IS_OK(status)) {
5247 file_free(req, fsp);
5251 if (NT_STATUS_EQUAL(status, NT_STATUS_FILE_IS_A_DIRECTORY)) {
5253 /* A stream open never opens a directory */
5256 status = NT_STATUS_FILE_IS_A_DIRECTORY;
5261 * Fail the open if it was explicitly a non-directory
5265 if (create_options & FILE_NON_DIRECTORY_FILE) {
5266 status = NT_STATUS_FILE_IS_A_DIRECTORY;
5271 status = open_directory(
5272 conn, req, smb_fname, access_mask,
5273 share_access, create_disposition,
5274 create_options, file_attributes,
5279 if (!NT_STATUS_IS_OK(status)) {
5283 fsp->base_fsp = base_fsp;
5285 if ((ea_list != NULL) &&
5286 ((info == FILE_WAS_CREATED) || (info == FILE_WAS_OVERWRITTEN))) {
5287 status = set_ea(conn, fsp, fsp->fsp_name, ea_list);
5288 if (!NT_STATUS_IS_OK(status)) {
5293 if (!fsp->is_directory && S_ISDIR(fsp->fsp_name->st.st_ex_mode)) {
5294 status = NT_STATUS_ACCESS_DENIED;
5298 /* Save the requested allocation size. */
5299 if ((info == FILE_WAS_CREATED) || (info == FILE_WAS_OVERWRITTEN)) {
5300 if ((allocation_size > fsp->fsp_name->st.st_ex_size)
5301 && !(fsp->is_directory))
5303 fsp->initial_allocation_size = smb_roundup(
5304 fsp->conn, allocation_size);
5305 if (vfs_allocate_file_space(
5306 fsp, fsp->initial_allocation_size) == -1) {
5307 status = NT_STATUS_DISK_FULL;
5311 fsp->initial_allocation_size = smb_roundup(
5312 fsp->conn, (uint64_t)fsp->fsp_name->st.st_ex_size);
5315 fsp->initial_allocation_size = 0;
5318 if ((info == FILE_WAS_CREATED) && lp_nt_acl_support(SNUM(conn)) &&
5319 fsp->base_fsp == NULL) {
5322 * According to the MS documentation, the only time the security
5323 * descriptor is applied to the opened file is iff we *created* the
5324 * file; an existing file stays the same.
5326 * Also, it seems (from observation) that you can open the file with
5327 * any access mask but you can still write the sd. We need to override
5328 * the granted access before we call set_sd
5329 * Patch for bug #2242 from Tom Lackemann <cessnatomny@yahoo.com>.
5332 uint32_t sec_info_sent;
5333 uint32_t saved_access_mask = fsp->access_mask;
5335 sec_info_sent = get_sec_info(sd);
5337 fsp->access_mask = FILE_GENERIC_ALL;
5339 if (sec_info_sent & (SECINFO_OWNER|
5343 status = set_sd(fsp, sd, sec_info_sent);
5346 fsp->access_mask = saved_access_mask;
5348 if (!NT_STATUS_IS_OK(status)) {
5351 } else if (lp_inherit_acls(SNUM(conn))) {
5352 /* Inherit from parent. Errors here are not fatal. */
5353 status = inherit_new_acl(fsp);
5354 if (!NT_STATUS_IS_OK(status)) {
5355 DEBUG(10,("inherit_new_acl: failed for %s with %s\n",
5357 nt_errstr(status) ));
5362 if ((conn->fs_capabilities & FILE_FILE_COMPRESSION)
5363 && (create_options & FILE_NO_COMPRESSION)
5364 && (info == FILE_WAS_CREATED)) {
5365 status = SMB_VFS_SET_COMPRESSION(conn, fsp, fsp,
5366 COMPRESSION_FORMAT_NONE);
5367 if (!NT_STATUS_IS_OK(status)) {
5368 DEBUG(1, ("failed to disable compression: %s\n",
5369 nt_errstr(status)));
5373 DEBUG(10, ("create_file_unixpath: info=%d\n", info));
5376 if (pinfo != NULL) {
5380 smb_fname->st = fsp->fsp_name->st;
5382 return NT_STATUS_OK;
5385 DEBUG(10, ("create_file_unixpath: %s\n", nt_errstr(status)));
5388 if (base_fsp && fsp->base_fsp == base_fsp) {
5390 * The close_file below will close
5395 close_file(req, fsp, ERROR_CLOSE);
5398 if (base_fsp != NULL) {
5399 close_file(req, base_fsp, ERROR_CLOSE);
5406 * Calculate the full path name given a relative fid.
5408 NTSTATUS get_relative_fid_filename(connection_struct *conn,
5409 struct smb_request *req,
5410 uint16_t root_dir_fid,
5411 const struct smb_filename *smb_fname,
5412 struct smb_filename **smb_fname_out)
5414 files_struct *dir_fsp;
5415 char *parent_fname = NULL;
5416 char *new_base_name = NULL;
5417 uint32_t ucf_flags = ucf_flags_from_smb_request(req);
5420 if (root_dir_fid == 0 || !smb_fname) {
5421 status = NT_STATUS_INTERNAL_ERROR;
5425 dir_fsp = file_fsp(req, root_dir_fid);
5427 if (dir_fsp == NULL) {
5428 status = NT_STATUS_INVALID_HANDLE;
5432 if (is_ntfs_stream_smb_fname(dir_fsp->fsp_name)) {
5433 status = NT_STATUS_INVALID_HANDLE;
5437 if (!dir_fsp->is_directory) {
5440 * Check to see if this is a mac fork of some kind.
5443 if ((conn->fs_capabilities & FILE_NAMED_STREAMS) &&
5444 is_ntfs_stream_smb_fname(smb_fname)) {
5445 status = NT_STATUS_OBJECT_PATH_NOT_FOUND;
5450 we need to handle the case when we get a
5451 relative open relative to a file and the
5452 pathname is blank - this is a reopen!
5453 (hint from demyn plantenberg)
5456 status = NT_STATUS_INVALID_HANDLE;
5460 if (ISDOT(dir_fsp->fsp_name->base_name)) {
5462 * We're at the toplevel dir, the final file name
5463 * must not contain ./, as this is filtered out
5464 * normally by srvstr_get_path and unix_convert
5465 * explicitly rejects paths containing ./.
5467 parent_fname = talloc_strdup(talloc_tos(), "");
5468 if (parent_fname == NULL) {
5469 status = NT_STATUS_NO_MEMORY;
5473 size_t dir_name_len = strlen(dir_fsp->fsp_name->base_name);
5476 * Copy in the base directory name.
5479 parent_fname = talloc_array(talloc_tos(), char,
5481 if (parent_fname == NULL) {
5482 status = NT_STATUS_NO_MEMORY;
5485 memcpy(parent_fname, dir_fsp->fsp_name->base_name,
5489 * Ensure it ends in a '/'.
5490 * We used TALLOC_SIZE +2 to add space for the '/'.
5494 && (parent_fname[dir_name_len-1] != '\\')
5495 && (parent_fname[dir_name_len-1] != '/')) {
5496 parent_fname[dir_name_len] = '/';
5497 parent_fname[dir_name_len+1] = '\0';
5501 new_base_name = talloc_asprintf(talloc_tos(), "%s%s", parent_fname,
5502 smb_fname->base_name);
5503 if (new_base_name == NULL) {
5504 status = NT_STATUS_NO_MEMORY;
5508 status = filename_convert(req,
5514 if (!NT_STATUS_IS_OK(status)) {
5519 TALLOC_FREE(parent_fname);
5520 TALLOC_FREE(new_base_name);
5524 NTSTATUS create_file_default(connection_struct *conn,
5525 struct smb_request *req,
5526 uint16_t root_dir_fid,
5527 struct smb_filename *smb_fname,
5528 uint32_t access_mask,
5529 uint32_t share_access,
5530 uint32_t create_disposition,
5531 uint32_t create_options,
5532 uint32_t file_attributes,
5533 uint32_t oplock_request,
5534 struct smb2_lease *lease,
5535 uint64_t allocation_size,
5536 uint32_t private_flags,
5537 struct security_descriptor *sd,
5538 struct ea_list *ea_list,
5539 files_struct **result,
5541 const struct smb2_create_blobs *in_context_blobs,
5542 struct smb2_create_blobs *out_context_blobs)
5544 int info = FILE_WAS_OPENED;
5545 files_struct *fsp = NULL;
5547 bool stream_name = false;
5549 DEBUG(10,("create_file: access_mask = 0x%x "
5550 "file_attributes = 0x%x, share_access = 0x%x, "
5551 "create_disposition = 0x%x create_options = 0x%x "
5552 "oplock_request = 0x%x "
5553 "private_flags = 0x%x "
5554 "root_dir_fid = 0x%x, ea_list = 0x%p, sd = 0x%p, "
5556 (unsigned int)access_mask,
5557 (unsigned int)file_attributes,
5558 (unsigned int)share_access,
5559 (unsigned int)create_disposition,
5560 (unsigned int)create_options,
5561 (unsigned int)oplock_request,
5562 (unsigned int)private_flags,
5563 (unsigned int)root_dir_fid,
5564 ea_list, sd, smb_fname_str_dbg(smb_fname)));
5567 * Calculate the filename from the root_dir_if if necessary.
5570 if (root_dir_fid != 0) {
5571 struct smb_filename *smb_fname_out = NULL;
5572 status = get_relative_fid_filename(conn, req, root_dir_fid,
5573 smb_fname, &smb_fname_out);
5574 if (!NT_STATUS_IS_OK(status)) {
5577 smb_fname = smb_fname_out;
5581 * Check to see if this is a mac fork of some kind.
5584 stream_name = is_ntfs_stream_smb_fname(smb_fname);
5586 enum FAKE_FILE_TYPE fake_file_type;
5588 fake_file_type = is_fake_file(smb_fname);
5590 if (fake_file_type != FAKE_FILE_TYPE_NONE) {
5593 * Here we go! support for changing the disk quotas
5596 * We need to fake up to open this MAGIC QUOTA file
5597 * and return a valid FID.
5599 * w2k close this file directly after openening xp
5600 * also tries a QUERY_FILE_INFO on the file and then
5603 status = open_fake_file(req, conn, req->vuid,
5604 fake_file_type, smb_fname,
5606 if (!NT_STATUS_IS_OK(status)) {
5610 ZERO_STRUCT(smb_fname->st);
5614 if (!(conn->fs_capabilities & FILE_NAMED_STREAMS)) {
5615 status = NT_STATUS_OBJECT_NAME_NOT_FOUND;
5620 if (is_ntfs_default_stream_smb_fname(smb_fname)) {
5622 smb_fname->stream_name = NULL;
5623 /* We have to handle this error here. */
5624 if (create_options & FILE_DIRECTORY_FILE) {
5625 status = NT_STATUS_NOT_A_DIRECTORY;
5628 if (req != NULL && req->posix_pathnames) {
5629 ret = SMB_VFS_LSTAT(conn, smb_fname);
5631 ret = SMB_VFS_STAT(conn, smb_fname);
5634 if (ret == 0 && VALID_STAT_OF_DIR(smb_fname->st)) {
5635 status = NT_STATUS_FILE_IS_A_DIRECTORY;
5640 status = create_file_unixpath(
5641 conn, req, smb_fname, access_mask, share_access,
5642 create_disposition, create_options, file_attributes,
5643 oplock_request, lease, allocation_size, private_flags,
5647 if (!NT_STATUS_IS_OK(status)) {
5652 DEBUG(10, ("create_file: info=%d\n", info));
5655 if (pinfo != NULL) {
5658 return NT_STATUS_OK;
5661 DEBUG(10, ("create_file: %s\n", nt_errstr(status)));
5664 close_file(req, fsp, ERROR_CLOSE);