2 Unix SMB/CIFS implementation.
3 file opening and share modes
4 Copyright (C) Andrew Tridgell 1992-1998
5 Copyright (C) Jeremy Allison 2001-2004
6 Copyright (C) Volker Lendecke 2005
7 Copyright (C) Ralph Boehme 2017
9 This program is free software; you can redistribute it and/or modify
10 it under the terms of the GNU General Public License as published by
11 the Free Software Foundation; either version 3 of the License, or
12 (at your option) any later version.
14 This program is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 GNU General Public License for more details.
19 You should have received a copy of the GNU General Public License
20 along with this program. If not, see <http://www.gnu.org/licenses/>.
24 #include "smb1_utils.h"
25 #include "system/filesys.h"
26 #include "lib/util/server_id.h"
28 #include "smbd/smbd.h"
29 #include "smbd/globals.h"
30 #include "fake_file.h"
31 #include "../libcli/security/security.h"
32 #include "../librpc/gen_ndr/ndr_security.h"
33 #include "../librpc/gen_ndr/ndr_open_files.h"
34 #include "../librpc/gen_ndr/idmap.h"
35 #include "../librpc/gen_ndr/ioctl.h"
36 #include "passdb/lookup_sid.h"
40 #include "source3/lib/dbwrap/dbwrap_watch.h"
41 #include "locking/leases_db.h"
42 #include "librpc/gen_ndr/ndr_leases_db.h"
43 #include "lib/util/time_basic.h"
45 extern const struct generic_mapping file_generic_mapping;
47 struct deferred_open_record {
48 struct smbXsrv_connection *xconn;
54 * Timer for async opens, needed because they don't use a watch on
55 * a locking.tdb record. This is currently only used for real async
56 * opens and just terminates smbd if the async open times out.
58 struct tevent_timer *te;
61 /****************************************************************************
62 If the requester wanted DELETE_ACCESS and was rejected because
63 the file ACL didn't include DELETE_ACCESS, see if the parent ACL
65 ****************************************************************************/
67 static bool parent_override_delete(connection_struct *conn,
68 const struct smb_filename *smb_fname,
70 uint32_t rejected_mask)
72 if ((access_mask & DELETE_ACCESS) &&
73 (rejected_mask & DELETE_ACCESS) &&
74 can_delete_file_in_directory(conn, smb_fname)) {
80 /****************************************************************************
81 Check if we have open rights.
82 ****************************************************************************/
84 NTSTATUS smbd_check_access_rights(struct connection_struct *conn,
85 const struct smb_filename *smb_fname,
89 /* Check if we have rights to open. */
91 struct security_descriptor *sd = NULL;
92 uint32_t rejected_share_access;
93 uint32_t rejected_mask = access_mask;
94 uint32_t do_not_check_mask = 0;
96 rejected_share_access = access_mask & ~(conn->share_access);
98 if (rejected_share_access) {
99 DEBUG(10, ("smbd_check_access_rights: rejected share access 0x%x "
101 (unsigned int)access_mask,
102 smb_fname_str_dbg(smb_fname),
103 (unsigned int)rejected_share_access ));
104 return NT_STATUS_ACCESS_DENIED;
107 if (!use_privs && get_current_uid(conn) == (uid_t)0) {
108 /* I'm sorry sir, I didn't know you were root... */
109 DEBUG(10,("smbd_check_access_rights: root override "
110 "on %s. Granting 0x%x\n",
111 smb_fname_str_dbg(smb_fname),
112 (unsigned int)access_mask ));
116 if ((access_mask & DELETE_ACCESS) && !lp_acl_check_permissions(SNUM(conn))) {
117 DEBUG(10,("smbd_check_access_rights: not checking ACL "
118 "on DELETE_ACCESS on file %s. Granting 0x%x\n",
119 smb_fname_str_dbg(smb_fname),
120 (unsigned int)access_mask ));
124 if (access_mask == DELETE_ACCESS &&
125 VALID_STAT(smb_fname->st) &&
126 S_ISLNK(smb_fname->st.st_ex_mode)) {
127 /* We can always delete a symlink. */
128 DEBUG(10,("smbd_check_access_rights: not checking ACL "
129 "on DELETE_ACCESS on symlink %s.\n",
130 smb_fname_str_dbg(smb_fname) ));
134 status = SMB_VFS_GET_NT_ACL(conn, smb_fname,
137 SECINFO_DACL), talloc_tos(), &sd);
139 if (!NT_STATUS_IS_OK(status)) {
140 DEBUG(10, ("smbd_check_access_rights: Could not get acl "
142 smb_fname_str_dbg(smb_fname),
145 if (NT_STATUS_EQUAL(status, NT_STATUS_ACCESS_DENIED)) {
153 * If we can access the path to this file, by
154 * default we have FILE_READ_ATTRIBUTES from the
155 * containing directory. See the section:
156 * "Algorithm to Check Access to an Existing File"
159 * se_file_access_check() also takes care of
160 * owner WRITE_DAC and READ_CONTROL.
162 do_not_check_mask = FILE_READ_ATTRIBUTES;
165 * Samba 3.6 and earlier granted execute access even
166 * if the ACL did not contain execute rights.
167 * Samba 4.0 is more correct and checks it.
168 * The compatibilty mode allows one to skip this check
169 * to smoothen upgrades.
171 if (lp_acl_allow_execute_always(SNUM(conn))) {
172 do_not_check_mask |= FILE_EXECUTE;
175 status = se_file_access_check(sd,
176 get_current_nttok(conn),
178 (access_mask & ~do_not_check_mask),
181 DEBUG(10,("smbd_check_access_rights: file %s requesting "
182 "0x%x returning 0x%x (%s)\n",
183 smb_fname_str_dbg(smb_fname),
184 (unsigned int)access_mask,
185 (unsigned int)rejected_mask,
186 nt_errstr(status) ));
188 if (!NT_STATUS_IS_OK(status)) {
189 if (DEBUGLEVEL >= 10) {
190 DEBUG(10,("smbd_check_access_rights: acl for %s is:\n",
191 smb_fname_str_dbg(smb_fname) ));
192 NDR_PRINT_DEBUG(security_descriptor, sd);
198 if (NT_STATUS_IS_OK(status) ||
199 !NT_STATUS_EQUAL(status, NT_STATUS_ACCESS_DENIED)) {
203 /* Here we know status == NT_STATUS_ACCESS_DENIED. */
207 if ((access_mask & FILE_WRITE_ATTRIBUTES) &&
208 (rejected_mask & FILE_WRITE_ATTRIBUTES) &&
209 !lp_store_dos_attributes(SNUM(conn)) &&
210 (lp_map_readonly(SNUM(conn)) ||
211 lp_map_archive(SNUM(conn)) ||
212 lp_map_hidden(SNUM(conn)) ||
213 lp_map_system(SNUM(conn)))) {
214 rejected_mask &= ~FILE_WRITE_ATTRIBUTES;
216 DEBUG(10,("smbd_check_access_rights: "
218 "FILE_WRITE_ATTRIBUTES "
220 smb_fname_str_dbg(smb_fname)));
223 if (parent_override_delete(conn,
227 /* Were we trying to do an open
228 * for delete and didn't get DELETE
229 * access (only) ? Check if the
230 * directory allows DELETE_CHILD.
232 * http://blogs.msdn.com/oldnewthing/archive/2004/06/04/148426.aspx
235 rejected_mask &= ~DELETE_ACCESS;
237 DEBUG(10,("smbd_check_access_rights: "
241 smb_fname_str_dbg(smb_fname)));
244 if (rejected_mask != 0) {
245 return NT_STATUS_ACCESS_DENIED;
250 NTSTATUS check_parent_access(struct connection_struct *conn,
251 struct smb_filename *smb_fname,
252 uint32_t access_mask)
255 char *parent_dir = NULL;
256 struct security_descriptor *parent_sd = NULL;
257 uint32_t access_granted = 0;
258 struct smb_filename *parent_smb_fname = NULL;
259 struct share_mode_lock *lck = NULL;
260 struct file_id id = {0};
262 bool delete_on_close_set;
264 TALLOC_CTX *frame = talloc_stackframe();
266 if (!parent_dirname(frame,
267 smb_fname->base_name,
270 status = NT_STATUS_NO_MEMORY;
274 parent_smb_fname = synthetic_smb_fname(frame,
279 if (parent_smb_fname == NULL) {
280 status = NT_STATUS_NO_MEMORY;
284 if (get_current_uid(conn) == (uid_t)0) {
285 /* I'm sorry sir, I didn't know you were root... */
286 DEBUG(10,("check_parent_access: root override "
287 "on %s. Granting 0x%x\n",
288 smb_fname_str_dbg(smb_fname),
289 (unsigned int)access_mask ));
290 status = NT_STATUS_OK;
294 status = SMB_VFS_GET_NT_ACL(conn,
300 if (!NT_STATUS_IS_OK(status)) {
301 DEBUG(5,("check_parent_access: SMB_VFS_GET_NT_ACL failed for "
302 "%s with error %s\n",
309 * If we can access the path to this file, by
310 * default we have FILE_READ_ATTRIBUTES from the
311 * containing directory. See the section:
312 * "Algorithm to Check Access to an Existing File"
315 * se_file_access_check() also takes care of
316 * owner WRITE_DAC and READ_CONTROL.
318 status = se_file_access_check(parent_sd,
319 get_current_nttok(conn),
321 (access_mask & ~FILE_READ_ATTRIBUTES),
323 if(!NT_STATUS_IS_OK(status)) {
324 DEBUG(5,("check_parent_access: access check "
325 "on directory %s for "
326 "path %s for mask 0x%x returned (0x%x) %s\n",
328 smb_fname->base_name,
331 nt_errstr(status) ));
335 if (!(access_mask & (SEC_DIR_ADD_FILE | SEC_DIR_ADD_SUBDIR))) {
336 status = NT_STATUS_OK;
339 if (!lp_check_parent_directory_delete_on_close(SNUM(conn))) {
340 status = NT_STATUS_OK;
344 /* Check if the directory has delete-on-close set */
345 ret = SMB_VFS_STAT(conn, parent_smb_fname);
347 status = map_nt_error_from_unix(errno);
351 id = SMB_VFS_FILE_ID_CREATE(conn, &parent_smb_fname->st);
353 status = file_name_hash(conn, parent_smb_fname->base_name, &name_hash);
354 if (!NT_STATUS_IS_OK(status)) {
358 lck = get_existing_share_mode_lock(frame, id);
360 status = NT_STATUS_OK;
364 delete_on_close_set = is_delete_on_close_set(lck, name_hash);
365 if (delete_on_close_set) {
366 status = NT_STATUS_DELETE_PENDING;
370 status = NT_STATUS_OK;
377 /****************************************************************************
378 Ensure when opening a base file for a stream open that we have permissions
379 to do so given the access mask on the base file.
380 ****************************************************************************/
382 static NTSTATUS check_base_file_access(struct connection_struct *conn,
383 struct smb_filename *smb_fname,
384 uint32_t access_mask)
388 status = smbd_calculate_access_mask(conn, smb_fname,
392 if (!NT_STATUS_IS_OK(status)) {
393 DEBUG(10, ("smbd_calculate_access_mask "
394 "on file %s returned %s\n",
395 smb_fname_str_dbg(smb_fname),
400 if (access_mask & (FILE_WRITE_DATA|FILE_APPEND_DATA)) {
402 if (!CAN_WRITE(conn)) {
403 return NT_STATUS_ACCESS_DENIED;
405 dosattrs = dos_mode(conn, smb_fname);
406 if (IS_DOS_READONLY(dosattrs)) {
407 return NT_STATUS_ACCESS_DENIED;
411 return smbd_check_access_rights(conn,
417 /****************************************************************************
418 Handle differing symlink errno's
419 ****************************************************************************/
421 static int link_errno_convert(int err)
423 #if defined(ENOTSUP) && defined(OSF1)
424 /* handle special Tru64 errno */
425 if (err == ENOTSUP) {
430 /* fix broken NetBSD errno */
435 /* fix broken FreeBSD errno */
442 static int non_widelink_open(struct connection_struct *conn,
443 const struct smb_filename *conn_rootdir_fname,
445 struct smb_filename *smb_fname,
448 unsigned int link_depth);
450 /****************************************************************************
451 Follow a symlink in userspace.
452 ****************************************************************************/
454 static int process_symlink_open(struct connection_struct *conn,
455 const struct smb_filename *conn_rootdir_fname,
457 struct smb_filename *smb_fname,
460 unsigned int link_depth)
463 char *link_target = NULL;
464 struct smb_filename target_fname = {0};
466 struct smb_filename *oldwd_fname = NULL;
467 size_t rootdir_len = 0;
468 struct smb_filename *resolved_fname = NULL;
469 char *resolved_name = NULL;
470 bool matched = false;
474 * Ensure we don't get stuck in a symlink loop.
477 if (link_depth >= 20) {
482 /* Allocate space for the link target. */
483 link_target = talloc_array(talloc_tos(), char, PATH_MAX);
484 if (link_target == NULL) {
489 /* Read the link target. */
490 link_len = SMB_VFS_READLINK(conn,
494 if (link_len == -1) {
498 /* Ensure it's at least null terminated. */
499 link_target[link_len] = '\0';
500 target_fname = (struct smb_filename){ .base_name = link_target };
502 /* Convert to an absolute path. */
503 resolved_fname = SMB_VFS_REALPATH(conn, talloc_tos(), &target_fname);
504 if (resolved_fname == NULL) {
507 resolved_name = resolved_fname->base_name;
510 * We know conn_rootdir starts with '/' and
511 * does not end in '/'. FIXME ! Should we
514 rootdir_len = strlen(conn_rootdir_fname->base_name);
516 matched = (strncmp(conn_rootdir_fname->base_name,
525 * Turn into a path relative to the share root.
527 if (resolved_name[rootdir_len] == '\0') {
528 /* Link to the root of the share. */
529 TALLOC_FREE(smb_fname->base_name);
530 smb_fname->base_name = talloc_strdup(smb_fname, ".");
531 } else if (resolved_name[rootdir_len] == '/') {
532 TALLOC_FREE(smb_fname->base_name);
533 smb_fname->base_name = talloc_strdup(smb_fname,
534 &resolved_name[rootdir_len+1]);
540 if (smb_fname->base_name == NULL) {
545 oldwd_fname = vfs_GetWd(talloc_tos(), conn);
546 if (oldwd_fname == NULL) {
550 /* Ensure we operate from the root of the share. */
551 if (vfs_ChDir(conn, conn_rootdir_fname) == -1) {
555 /* And do it all again.. */
556 fd = non_widelink_open(conn,
569 TALLOC_FREE(resolved_fname);
570 TALLOC_FREE(link_target);
571 if (oldwd_fname != NULL) {
572 int ret = vfs_ChDir(conn, oldwd_fname);
574 smb_panic("unable to get back to old directory\n");
576 TALLOC_FREE(oldwd_fname);
578 if (saved_errno != 0) {
584 /****************************************************************************
586 ****************************************************************************/
588 static int non_widelink_open(struct connection_struct *conn,
589 const struct smb_filename *conn_rootdir_fname,
591 struct smb_filename *smb_fname,
594 unsigned int link_depth)
598 struct smb_filename *smb_fname_rel = NULL;
600 struct smb_filename *oldwd_fname = NULL;
601 char *parent_dir = NULL;
602 struct smb_filename parent_dir_fname = {0};
603 const char *final_component = NULL;
604 bool is_directory = false;
608 if (flags & O_DIRECTORY) {
614 parent_dir = talloc_strdup(talloc_tos(), smb_fname->base_name);
615 if (parent_dir == NULL) {
620 final_component = ".";
622 ok = parent_dirname(talloc_tos(),
623 smb_fname->base_name,
632 parent_dir_fname = (struct smb_filename) { .base_name = parent_dir };
634 oldwd_fname = vfs_GetWd(talloc_tos(), conn);
635 if (oldwd_fname == NULL) {
639 /* Pin parent directory in place. */
640 if (vfs_ChDir(conn, &parent_dir_fname) == -1) {
644 smb_fname_rel = synthetic_smb_fname(talloc_tos(),
646 smb_fname->stream_name,
649 if (smb_fname_rel == NULL) {
650 saved_errno = ENOMEM;
654 /* Ensure the relative path is below the share. */
655 status = check_reduced_name(conn, &parent_dir_fname, smb_fname_rel);
656 if (!NT_STATUS_IS_OK(status)) {
657 saved_errno = map_errno_from_nt_status(status);
664 struct smb_filename *tmp_name = fsp->fsp_name;
665 fsp->fsp_name = smb_fname_rel;
666 fd = SMB_VFS_OPEN(conn, smb_fname_rel, fsp, flags, mode);
667 fsp->fsp_name = tmp_name;
671 saved_errno = link_errno_convert(errno);
673 * Trying to open a symlink to a directory with O_NOFOLLOW and
674 * O_DIRECTORY can return either of ELOOP and ENOTDIR. So
675 * ENOTDIR really means: might be a symlink, but we're not sure.
676 * In this case, we just assume there's a symlink. If we were
677 * wrong, process_symlink_open() will return EINVAL. We check
678 * this below, and fall back to returning the initial
681 * BUG: https://bugzilla.samba.org/show_bug.cgi?id=12860
683 if (saved_errno == ELOOP || saved_errno == ENOTDIR) {
684 if (fsp->posix_flags & FSP_POSIX_FLAGS_OPEN) {
685 /* Never follow symlinks on posix open. */
688 if (!lp_follow_symlinks(SNUM(conn))) {
689 /* Explicitly no symlinks. */
693 * We may have a symlink. Follow in userspace
694 * to ensure it's under the share definition.
696 fd = process_symlink_open(conn,
704 if (saved_errno == ENOTDIR &&
707 * O_DIRECTORY on neither a directory,
708 * nor a symlink. Just return
709 * saved_errno from initial open()
714 link_errno_convert(errno);
721 TALLOC_FREE(parent_dir);
722 TALLOC_FREE(smb_fname_rel);
724 if (oldwd_fname != NULL) {
725 int ret = vfs_ChDir(conn, oldwd_fname);
727 smb_panic("unable to get back to old directory\n");
729 TALLOC_FREE(oldwd_fname);
731 if (saved_errno != 0) {
737 /****************************************************************************
738 fd support routines - attempt to do a dos_open.
739 ****************************************************************************/
741 NTSTATUS fd_open(struct connection_struct *conn,
746 struct smb_filename *smb_fname = fsp->fsp_name;
747 NTSTATUS status = NT_STATUS_OK;
750 * Never follow symlinks on a POSIX client. The
751 * client should be doing this.
754 if ((fsp->posix_flags & FSP_POSIX_FLAGS_OPEN) || !lp_follow_symlinks(SNUM(conn))) {
758 /* Ensure path is below share definition. */
759 if (!lp_widelinks(SNUM(conn))) {
760 struct smb_filename *conn_rootdir_fname = NULL;
761 const char *conn_rootdir = SMB_VFS_CONNECTPATH(conn,
765 if (conn_rootdir == NULL) {
766 return NT_STATUS_NO_MEMORY;
768 conn_rootdir_fname = synthetic_smb_fname(talloc_tos(),
773 if (conn_rootdir_fname == NULL) {
774 return NT_STATUS_NO_MEMORY;
778 * Only follow symlinks within a share
781 fsp->fh->fd = non_widelink_open(conn,
788 if (fsp->fh->fd == -1) {
791 TALLOC_FREE(conn_rootdir_fname);
792 if (saved_errno != 0) {
796 fsp->fh->fd = SMB_VFS_OPEN(conn, smb_fname, fsp, flags, mode);
799 if (fsp->fh->fd == -1) {
800 int posix_errno = link_errno_convert(errno);
801 status = map_nt_error_from_unix(posix_errno);
802 if (errno == EMFILE) {
803 static time_t last_warned = 0L;
805 if (time((time_t *) NULL) > last_warned) {
806 DEBUG(0,("Too many open files, unable "
807 "to open more! smbd's max "
809 lp_max_open_files()));
810 last_warned = time((time_t *) NULL);
816 DEBUG(10,("fd_open: name %s, flags = 0%o mode = 0%o, fd = %d. %s\n",
817 smb_fname_str_dbg(smb_fname), flags, (int)mode, fsp->fh->fd,
818 (fsp->fh->fd == -1) ? strerror(errno) : "" ));
823 /****************************************************************************
824 Close the file associated with a fsp.
825 ****************************************************************************/
827 NTSTATUS fd_close(files_struct *fsp)
834 if (fsp->fh->fd == -1) {
836 * Either a directory where the dptr_CloseDir() already closed
837 * the fd or a stat open.
841 if (fsp->fh->ref_count > 1) {
842 return NT_STATUS_OK; /* Shared handle. Only close last reference. */
845 ret = SMB_VFS_CLOSE(fsp);
848 return map_nt_error_from_unix(errno);
853 /****************************************************************************
854 Change the ownership of a file to that of the parent directory.
855 Do this by fd if possible.
856 ****************************************************************************/
858 void change_file_owner_to_parent(connection_struct *conn,
859 const char *inherit_from_dir,
862 struct smb_filename *smb_fname_parent;
865 smb_fname_parent = synthetic_smb_fname(talloc_tos(),
870 if (smb_fname_parent == NULL) {
874 ret = SMB_VFS_STAT(conn, smb_fname_parent);
876 DEBUG(0,("change_file_owner_to_parent: failed to stat parent "
877 "directory %s. Error was %s\n",
878 smb_fname_str_dbg(smb_fname_parent),
880 TALLOC_FREE(smb_fname_parent);
884 if (smb_fname_parent->st.st_ex_uid == fsp->fsp_name->st.st_ex_uid) {
885 /* Already this uid - no need to change. */
886 DEBUG(10,("change_file_owner_to_parent: file %s "
887 "is already owned by uid %d\n",
889 (int)fsp->fsp_name->st.st_ex_uid ));
890 TALLOC_FREE(smb_fname_parent);
895 ret = SMB_VFS_FCHOWN(fsp, smb_fname_parent->st.st_ex_uid, (gid_t)-1);
898 DEBUG(0,("change_file_owner_to_parent: failed to fchown "
899 "file %s to parent directory uid %u. Error "
900 "was %s\n", fsp_str_dbg(fsp),
901 (unsigned int)smb_fname_parent->st.st_ex_uid,
904 DEBUG(10,("change_file_owner_to_parent: changed new file %s to "
905 "parent directory uid %u.\n", fsp_str_dbg(fsp),
906 (unsigned int)smb_fname_parent->st.st_ex_uid));
907 /* Ensure the uid entry is updated. */
908 fsp->fsp_name->st.st_ex_uid = smb_fname_parent->st.st_ex_uid;
911 TALLOC_FREE(smb_fname_parent);
914 static NTSTATUS change_dir_owner_to_parent(connection_struct *conn,
915 const char *inherit_from_dir,
916 struct smb_filename *smb_dname,
917 SMB_STRUCT_STAT *psbuf)
919 struct smb_filename *smb_fname_parent;
920 struct smb_filename *smb_fname_cwd = NULL;
921 struct smb_filename *saved_dir_fname = NULL;
922 TALLOC_CTX *ctx = talloc_tos();
923 NTSTATUS status = NT_STATUS_OK;
926 smb_fname_parent = synthetic_smb_fname(ctx,
931 if (smb_fname_parent == NULL) {
932 return NT_STATUS_NO_MEMORY;
935 ret = SMB_VFS_STAT(conn, smb_fname_parent);
937 status = map_nt_error_from_unix(errno);
938 DEBUG(0,("change_dir_owner_to_parent: failed to stat parent "
939 "directory %s. Error was %s\n",
940 smb_fname_str_dbg(smb_fname_parent),
945 /* We've already done an lstat into psbuf, and we know it's a
946 directory. If we can cd into the directory and the dev/ino
947 are the same then we can safely chown without races as
948 we're locking the directory in place by being in it. This
949 should work on any UNIX (thanks tridge :-). JRA.
952 saved_dir_fname = vfs_GetWd(ctx,conn);
953 if (!saved_dir_fname) {
954 status = map_nt_error_from_unix(errno);
955 DEBUG(0,("change_dir_owner_to_parent: failed to get "
956 "current working directory. Error was %s\n",
961 /* Chdir into the new path. */
962 if (vfs_ChDir(conn, smb_dname) == -1) {
963 status = map_nt_error_from_unix(errno);
964 DEBUG(0,("change_dir_owner_to_parent: failed to change "
965 "current working directory to %s. Error "
966 "was %s\n", smb_dname->base_name, strerror(errno) ));
970 smb_fname_cwd = synthetic_smb_fname(ctx, ".", NULL, NULL, 0);
971 if (smb_fname_cwd == NULL) {
972 status = NT_STATUS_NO_MEMORY;
976 ret = SMB_VFS_STAT(conn, smb_fname_cwd);
978 status = map_nt_error_from_unix(errno);
979 DEBUG(0,("change_dir_owner_to_parent: failed to stat "
980 "directory '.' (%s) Error was %s\n",
981 smb_dname->base_name, strerror(errno)));
985 /* Ensure we're pointing at the same place. */
986 if (smb_fname_cwd->st.st_ex_dev != psbuf->st_ex_dev ||
987 smb_fname_cwd->st.st_ex_ino != psbuf->st_ex_ino) {
988 DEBUG(0,("change_dir_owner_to_parent: "
989 "device/inode on directory %s changed. "
990 "Refusing to chown !\n",
991 smb_dname->base_name ));
992 status = NT_STATUS_ACCESS_DENIED;
996 if (smb_fname_parent->st.st_ex_uid == smb_fname_cwd->st.st_ex_uid) {
997 /* Already this uid - no need to change. */
998 DEBUG(10,("change_dir_owner_to_parent: directory %s "
999 "is already owned by uid %d\n",
1000 smb_dname->base_name,
1001 (int)smb_fname_cwd->st.st_ex_uid ));
1002 status = NT_STATUS_OK;
1007 ret = SMB_VFS_LCHOWN(conn,
1009 smb_fname_parent->st.st_ex_uid,
1013 status = map_nt_error_from_unix(errno);
1014 DEBUG(10,("change_dir_owner_to_parent: failed to chown "
1015 "directory %s to parent directory uid %u. "
1017 smb_dname->base_name,
1018 (unsigned int)smb_fname_parent->st.st_ex_uid,
1021 DEBUG(10,("change_dir_owner_to_parent: changed ownership of new "
1022 "directory %s to parent directory uid %u.\n",
1023 smb_dname->base_name,
1024 (unsigned int)smb_fname_parent->st.st_ex_uid ));
1025 /* Ensure the uid entry is updated. */
1026 psbuf->st_ex_uid = smb_fname_parent->st.st_ex_uid;
1030 vfs_ChDir(conn, saved_dir_fname);
1032 TALLOC_FREE(saved_dir_fname);
1033 TALLOC_FREE(smb_fname_parent);
1034 TALLOC_FREE(smb_fname_cwd);
1038 /****************************************************************************
1039 Open a file - returning a guaranteed ATOMIC indication of if the
1040 file was created or not.
1041 ****************************************************************************/
1043 static NTSTATUS fd_open_atomic(struct connection_struct *conn,
1049 NTSTATUS status = NT_STATUS_UNSUCCESSFUL;
1050 NTSTATUS retry_status;
1051 bool file_existed = VALID_STAT(fsp->fsp_name->st);
1054 if (!(flags & O_CREAT)) {
1056 * We're not creating the file, just pass through.
1058 status = fd_open(conn, fsp, flags, mode);
1059 *file_created = false;
1063 if (flags & O_EXCL) {
1065 * Fail if already exists, just pass through.
1067 status = fd_open(conn, fsp, flags, mode);
1070 * Here we've opened with O_CREAT|O_EXCL. If that went
1071 * NT_STATUS_OK, we *know* we created this file.
1073 *file_created = NT_STATUS_IS_OK(status);
1079 * Now it gets tricky. We have O_CREAT, but not O_EXCL.
1080 * To know absolutely if we created the file or not,
1081 * we can never call O_CREAT without O_EXCL. So if
1082 * we think the file existed, try without O_CREAT|O_EXCL.
1083 * If we think the file didn't exist, try with
1086 * The big problem here is dangling symlinks. Opening
1087 * without O_NOFOLLOW means both bad symlink
1088 * and missing path return -1, ENOENT from open(). As POSIX
1089 * is pathname based it's not possible to tell
1090 * the difference between these two cases in a
1091 * non-racy way, so change to try only two attempts before
1094 * We don't have this problem for the O_NOFOLLOW
1095 * case as it just returns NT_STATUS_OBJECT_PATH_NOT_FOUND
1096 * mapped from the ELOOP POSIX error.
1100 curr_flags = flags & ~(O_CREAT);
1101 retry_status = NT_STATUS_OBJECT_NAME_NOT_FOUND;
1103 curr_flags = flags | O_EXCL;
1104 retry_status = NT_STATUS_OBJECT_NAME_COLLISION;
1107 status = fd_open(conn, fsp, curr_flags, mode);
1108 if (NT_STATUS_IS_OK(status)) {
1109 *file_created = !file_existed;
1110 return NT_STATUS_OK;
1112 if (NT_STATUS_EQUAL(status, retry_status)) {
1114 file_existed = !file_existed;
1116 DBG_DEBUG("File %s %s. Retry.\n",
1118 file_existed ? "existed" : "did not exist");
1121 curr_flags = flags & ~(O_CREAT);
1123 curr_flags = flags | O_EXCL;
1126 status = fd_open(conn, fsp, curr_flags, mode);
1129 *file_created = (NT_STATUS_IS_OK(status) && !file_existed);
1133 /****************************************************************************
1135 ****************************************************************************/
1137 static NTSTATUS open_file(files_struct *fsp,
1138 connection_struct *conn,
1139 struct smb_request *req,
1140 const char *parent_dir,
1143 uint32_t access_mask, /* client requested access mask. */
1144 uint32_t open_access_mask, /* what we're actually using in the open. */
1145 bool *p_file_created)
1147 struct smb_filename *smb_fname = fsp->fsp_name;
1148 NTSTATUS status = NT_STATUS_OK;
1149 int accmode = (flags & O_ACCMODE);
1150 int local_flags = flags;
1151 bool file_existed = VALID_STAT(fsp->fsp_name->st);
1156 /* Check permissions */
1159 * This code was changed after seeing a client open request
1160 * containing the open mode of (DENY_WRITE/read-only) with
1161 * the 'create if not exist' bit set. The previous code
1162 * would fail to open the file read only on a read-only share
1163 * as it was checking the flags parameter directly against O_RDONLY,
1164 * this was failing as the flags parameter was set to O_RDONLY|O_CREAT.
1168 if (!CAN_WRITE(conn)) {
1169 /* It's a read-only share - fail if we wanted to write. */
1170 if(accmode != O_RDONLY || (flags & O_TRUNC) || (flags & O_APPEND)) {
1171 DEBUG(3,("Permission denied opening %s\n",
1172 smb_fname_str_dbg(smb_fname)));
1173 return NT_STATUS_ACCESS_DENIED;
1175 if (flags & O_CREAT) {
1176 /* We don't want to write - but we must make sure that
1177 O_CREAT doesn't create the file if we have write
1178 access into the directory.
1180 flags &= ~(O_CREAT|O_EXCL);
1181 local_flags &= ~(O_CREAT|O_EXCL);
1186 * This little piece of insanity is inspired by the
1187 * fact that an NT client can open a file for O_RDONLY,
1188 * but set the create disposition to FILE_EXISTS_TRUNCATE.
1189 * If the client *can* write to the file, then it expects to
1190 * truncate the file, even though it is opening for readonly.
1191 * Quicken uses this stupid trick in backup file creation...
1192 * Thanks *greatly* to "David W. Chapman Jr." <dwcjr@inethouston.net>
1193 * for helping track this one down. It didn't bite us in 2.0.x
1194 * as we always opened files read-write in that release. JRA.
1197 if ((accmode == O_RDONLY) && ((flags & O_TRUNC) == O_TRUNC)) {
1198 DEBUG(10,("open_file: truncate requested on read-only open "
1199 "for file %s\n", smb_fname_str_dbg(smb_fname)));
1200 local_flags = (flags & ~O_ACCMODE)|O_RDWR;
1203 if ((open_access_mask & (FILE_READ_DATA|FILE_WRITE_DATA|
1204 FILE_APPEND_DATA|FILE_EXECUTE|
1205 WRITE_DAC_ACCESS|WRITE_OWNER_ACCESS|
1206 READ_CONTROL_ACCESS))||
1207 (!file_existed && (local_flags & O_CREAT)) ||
1208 ((local_flags & O_TRUNC) == O_TRUNC) ) {
1212 #if defined(O_NONBLOCK) && defined(S_ISFIFO)
1214 * We would block on opening a FIFO with no one else on the
1215 * other end. Do what we used to do and add O_NONBLOCK to the
1219 if (file_existed && S_ISFIFO(smb_fname->st.st_ex_mode)) {
1220 local_flags &= ~O_TRUNC; /* Can't truncate a FIFO. */
1221 local_flags |= O_NONBLOCK;
1225 /* Don't create files with Microsoft wildcard characters. */
1226 if (fsp->base_fsp) {
1228 * wildcard characters are allowed in stream names
1229 * only test the basefilename
1231 wild = fsp->base_fsp->fsp_name->base_name;
1233 wild = smb_fname->base_name;
1235 if ((local_flags & O_CREAT) && !file_existed &&
1236 !(fsp->posix_flags & FSP_POSIX_FLAGS_PATHNAMES) &&
1237 ms_has_wild(wild)) {
1238 return NT_STATUS_OBJECT_NAME_INVALID;
1241 /* Can we access this file ? */
1242 if (!fsp->base_fsp) {
1243 /* Only do this check on non-stream open. */
1245 status = smbd_check_access_rights(conn,
1250 if (!NT_STATUS_IS_OK(status)) {
1251 DEBUG(10, ("open_file: "
1252 "smbd_check_access_rights "
1253 "on file %s returned %s\n",
1254 smb_fname_str_dbg(smb_fname),
1255 nt_errstr(status)));
1258 if (!NT_STATUS_IS_OK(status) &&
1259 !NT_STATUS_EQUAL(status,
1260 NT_STATUS_OBJECT_NAME_NOT_FOUND))
1265 if (NT_STATUS_EQUAL(status,
1266 NT_STATUS_OBJECT_NAME_NOT_FOUND))
1268 DEBUG(10, ("open_file: "
1269 "file %s vanished since we "
1270 "checked for existence.\n",
1271 smb_fname_str_dbg(smb_fname)));
1272 file_existed = false;
1273 SET_STAT_INVALID(fsp->fsp_name->st);
1277 if (!file_existed) {
1278 if (!(local_flags & O_CREAT)) {
1279 /* File didn't exist and no O_CREAT. */
1280 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
1283 status = check_parent_access(conn,
1286 if (!NT_STATUS_IS_OK(status)) {
1287 DEBUG(10, ("open_file: "
1288 "check_parent_access on "
1289 "file %s returned %s\n",
1290 smb_fname_str_dbg(smb_fname),
1291 nt_errstr(status) ));
1298 * Actually do the open - if O_TRUNC is needed handle it
1299 * below under the share mode lock.
1301 status = fd_open_atomic(conn, fsp, local_flags & ~O_TRUNC,
1302 unx_mode, p_file_created);
1303 if (!NT_STATUS_IS_OK(status)) {
1304 DEBUG(3,("Error opening file %s (%s) (local_flags=%d) "
1305 "(flags=%d)\n", smb_fname_str_dbg(smb_fname),
1306 nt_errstr(status),local_flags,flags));
1310 if (local_flags & O_NONBLOCK) {
1312 * GPFS can return ETIMEDOUT for pread on
1313 * nonblocking file descriptors when files
1314 * migrated to tape need to be recalled. I
1315 * could imagine this happens elsewhere
1316 * too. With blocking file descriptors this
1319 ret = set_blocking(fsp->fh->fd, true);
1321 status = map_nt_error_from_unix(errno);
1322 DBG_WARNING("Could not set fd to blocking: "
1323 "%s\n", strerror(errno));
1329 ret = SMB_VFS_FSTAT(fsp, &smb_fname->st);
1331 /* If we have an fd, this stat should succeed. */
1332 DEBUG(0,("Error doing fstat on open file %s "
1334 smb_fname_str_dbg(smb_fname),
1336 status = map_nt_error_from_unix(errno);
1341 if (*p_file_created) {
1342 /* We created this file. */
1344 bool need_re_stat = false;
1345 /* Do all inheritance work after we've
1346 done a successful fstat call and filled
1347 in the stat struct in fsp->fsp_name. */
1349 /* Inherit the ACL if required */
1350 if (lp_inherit_permissions(SNUM(conn))) {
1351 inherit_access_posix_acl(conn, parent_dir,
1354 need_re_stat = true;
1357 /* Change the owner if required. */
1358 if (lp_inherit_owner(SNUM(conn)) != INHERIT_OWNER_NO) {
1359 change_file_owner_to_parent(conn, parent_dir,
1361 need_re_stat = true;
1365 ret = SMB_VFS_FSTAT(fsp, &smb_fname->st);
1366 /* If we have an fd, this stat should succeed. */
1368 DEBUG(0,("Error doing fstat on open file %s "
1370 smb_fname_str_dbg(smb_fname),
1375 notify_fname(conn, NOTIFY_ACTION_ADDED,
1376 FILE_NOTIFY_CHANGE_FILE_NAME,
1377 smb_fname->base_name);
1380 fsp->fh->fd = -1; /* What we used to call a stat open. */
1381 if (!file_existed) {
1382 /* File must exist for a stat open. */
1383 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
1386 status = smbd_check_access_rights(conn,
1391 if (NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND) &&
1392 (fsp->posix_flags & FSP_POSIX_FLAGS_OPEN) &&
1393 S_ISLNK(smb_fname->st.st_ex_mode)) {
1394 /* This is a POSIX stat open for delete
1395 * or rename on a symlink that points
1396 * nowhere. Allow. */
1397 DEBUG(10,("open_file: allowing POSIX "
1398 "open on bad symlink %s\n",
1399 smb_fname_str_dbg(smb_fname)));
1400 status = NT_STATUS_OK;
1403 if (!NT_STATUS_IS_OK(status)) {
1404 DEBUG(10,("open_file: "
1405 "smbd_check_access_rights on file "
1407 smb_fname_str_dbg(smb_fname),
1408 nt_errstr(status) ));
1414 * POSIX allows read-only opens of directories. We don't
1415 * want to do this (we use a different code path for this)
1416 * so catch a directory open and return an EISDIR. JRA.
1419 if(S_ISDIR(smb_fname->st.st_ex_mode)) {
1422 return NT_STATUS_FILE_IS_A_DIRECTORY;
1425 fsp->file_id = vfs_file_id_from_sbuf(conn, &smb_fname->st);
1426 fsp->vuid = req ? req->vuid : UID_FIELD_INVALID;
1427 fsp->file_pid = req ? req->smbpid : 0;
1428 fsp->can_lock = True;
1429 fsp->can_read = ((access_mask & FILE_READ_DATA) != 0);
1432 ((access_mask & (FILE_WRITE_DATA | FILE_APPEND_DATA)) != 0);
1433 fsp->print_file = NULL;
1434 fsp->modified = False;
1435 fsp->sent_oplock_break = NO_BREAK_SENT;
1436 fsp->is_directory = False;
1437 if (conn->aio_write_behind_list &&
1438 is_in_path(smb_fname->base_name, conn->aio_write_behind_list,
1439 conn->case_sensitive)) {
1440 fsp->aio_write_behind = True;
1443 fsp->wcp = NULL; /* Write cache pointer. */
1445 DEBUG(2,("%s opened file %s read=%s write=%s (numopen=%d)\n",
1446 conn->session_info->unix_info->unix_name,
1447 smb_fname_str_dbg(smb_fname),
1448 BOOLSTR(fsp->can_read), BOOLSTR(fsp->can_write),
1449 conn->num_files_open));
1452 return NT_STATUS_OK;
1455 /****************************************************************************
1456 Check if we can open a file with a share mode.
1457 Returns True if conflict, False if not.
1458 ****************************************************************************/
1460 static bool share_conflict(struct share_mode_entry *entry,
1461 uint32_t access_mask,
1462 uint32_t share_access)
1464 DBG_DEBUG("entry->access_mask = 0x%"PRIx32", "
1465 "entry->share_access = 0x%"PRIx32", "
1466 "entry->private_options = 0x%"PRIx32", "
1467 "access_mask = 0x%"PRIx32", "
1468 "share_access = 0x%"PRIx32"\n",
1470 entry->share_access,
1471 entry->private_options,
1475 if (server_id_is_disconnected(&entry->pid)) {
1479 if ((entry->access_mask & (FILE_WRITE_DATA|
1483 DELETE_ACCESS)) == 0) {
1484 DBG_DEBUG("No conflict due to "
1485 "entry->access_mask = 0x%"PRIx32"\n",
1486 entry->access_mask);
1490 if ((access_mask & (FILE_WRITE_DATA|
1494 DELETE_ACCESS)) == 0) {
1495 DBG_DEBUG("No conflict due to access_mask = 0x%"PRIx32"\n",
1500 #if 1 /* JRA TEST - Superdebug. */
1501 #define CHECK_MASK(num, am, right, sa, share) \
1502 DEBUG(10,("share_conflict: [%d] am (0x%x) & right (0x%x) = 0x%x\n", \
1503 (unsigned int)(num), (unsigned int)(am), \
1504 (unsigned int)(right), (unsigned int)(am)&(right) )); \
1505 DEBUG(10,("share_conflict: [%d] sa (0x%x) & share (0x%x) = 0x%x\n", \
1506 (unsigned int)(num), (unsigned int)(sa), \
1507 (unsigned int)(share), (unsigned int)(sa)&(share) )); \
1508 if (((am) & (right)) && !((sa) & (share))) { \
1509 DEBUG(10,("share_conflict: check %d conflict am = 0x%x, right = 0x%x, \
1510 sa = 0x%x, share = 0x%x\n", (num), (unsigned int)(am), (unsigned int)(right), (unsigned int)(sa), \
1511 (unsigned int)(share) )); \
1515 #define CHECK_MASK(num, am, right, sa, share) \
1516 if (((am) & (right)) && !((sa) & (share))) { \
1517 DEBUG(10,("share_conflict: check %d conflict am = 0x%x, right = 0x%x, \
1518 sa = 0x%x, share = 0x%x\n", (num), (unsigned int)(am), (unsigned int)(right), (unsigned int)(sa), \
1519 (unsigned int)(share) )); \
1524 CHECK_MASK(1, entry->access_mask, FILE_WRITE_DATA | FILE_APPEND_DATA,
1525 share_access, FILE_SHARE_WRITE);
1526 CHECK_MASK(2, access_mask, FILE_WRITE_DATA | FILE_APPEND_DATA,
1527 entry->share_access, FILE_SHARE_WRITE);
1529 CHECK_MASK(3, entry->access_mask, FILE_READ_DATA | FILE_EXECUTE,
1530 share_access, FILE_SHARE_READ);
1531 CHECK_MASK(4, access_mask, FILE_READ_DATA | FILE_EXECUTE,
1532 entry->share_access, FILE_SHARE_READ);
1534 CHECK_MASK(5, entry->access_mask, DELETE_ACCESS,
1535 share_access, FILE_SHARE_DELETE);
1536 CHECK_MASK(6, access_mask, DELETE_ACCESS,
1537 entry->share_access, FILE_SHARE_DELETE);
1539 DEBUG(10,("share_conflict: No conflict.\n"));
1543 #if defined(DEVELOPER)
1544 static void validate_my_share_entries(struct smbd_server_connection *sconn,
1545 const struct file_id id,
1547 struct share_mode_entry *share_entry)
1549 struct server_id self = messaging_server_id(sconn->msg_ctx);
1552 if (!serverid_equal(&self, &share_entry->pid)) {
1556 if (share_entry->op_mid == 0) {
1557 /* INTERNAL_OPEN_ONLY */
1561 if (!is_valid_share_mode_entry(share_entry)) {
1565 fsp = file_find_dif(sconn, id, share_entry->share_file_id);
1567 DBG_ERR("PANIC : %s\n",
1568 share_mode_str(talloc_tos(), num, &id,
1570 smb_panic("validate_my_share_entries: Cannot match a "
1571 "share entry with an open file\n");
1574 if (((uint16_t)fsp->oplock_type) != share_entry->op_type) {
1583 DBG_ERR("validate_my_share_entries: PANIC : %s\n",
1584 share_mode_str(talloc_tos(), num, &id,
1586 str = talloc_asprintf(talloc_tos(),
1587 "validate_my_share_entries: "
1588 "file %s, oplock_type = 0x%x, op_type = 0x%x\n",
1589 fsp->fsp_name->base_name,
1590 (unsigned int)fsp->oplock_type,
1591 (unsigned int)share_entry->op_type );
1597 bool is_stat_open(uint32_t access_mask)
1599 const uint32_t stat_open_bits =
1600 (SYNCHRONIZE_ACCESS|
1601 FILE_READ_ATTRIBUTES|
1602 FILE_WRITE_ATTRIBUTES);
1604 return (((access_mask & stat_open_bits) != 0) &&
1605 ((access_mask & ~stat_open_bits) == 0));
1608 static bool has_delete_on_close(struct share_mode_lock *lck,
1611 struct share_mode_data *d = lck->data;
1614 if (d->num_share_modes == 0) {
1617 if (!is_delete_on_close_set(lck, name_hash)) {
1620 for (i=0; i<d->num_share_modes; i++) {
1621 if (!share_mode_stale_pid(d, i)) {
1628 /****************************************************************************
1629 Deal with share modes
1630 Invariant: Share mode must be locked on entry and exit.
1631 Returns -1 on error, or number of share modes on success (may be zero).
1632 ****************************************************************************/
1634 static NTSTATUS open_mode_check(connection_struct *conn,
1635 struct share_mode_lock *lck,
1636 uint32_t access_mask,
1637 uint32_t share_access)
1641 if (is_stat_open(access_mask)) {
1642 /* Stat open that doesn't trigger oplock breaks or share mode
1643 * checks... ! JRA. */
1644 return NT_STATUS_OK;
1648 * Check if the share modes will give us access.
1651 #if defined(DEVELOPER)
1652 for(i = 0; i < lck->data->num_share_modes; i++) {
1653 validate_my_share_entries(conn->sconn, lck->data->id, i,
1654 &lck->data->share_modes[i]);
1658 for(i = 0; i < lck->data->num_share_modes; i++) {
1660 if (!is_valid_share_mode_entry(&lck->data->share_modes[i])) {
1664 /* someone else has a share lock on it, check to see if we can
1666 if (share_conflict(&lck->data->share_modes[i],
1667 access_mask, share_access)) {
1669 if (share_mode_stale_pid(lck->data, i)) {
1673 return NT_STATUS_SHARING_VIOLATION;
1677 return NT_STATUS_OK;
1681 * Send a break message to the oplock holder and delay the open for
1685 NTSTATUS send_break_message(struct messaging_context *msg_ctx,
1686 const struct file_id *id,
1687 const struct share_mode_entry *exclusive,
1690 struct oplock_break_message msg = {
1692 .share_file_id = exclusive->share_file_id,
1693 .break_to = break_to,
1695 enum ndr_err_code ndr_err;
1700 struct server_id_buf buf;
1701 DBG_DEBUG("Sending break message to %s\n",
1702 server_id_str_buf(exclusive->pid, &buf));
1703 NDR_PRINT_DEBUG(oplock_break_message, &msg);
1706 ndr_err = ndr_push_struct_blob(
1710 (ndr_push_flags_fn_t)ndr_push_oplock_break_message);
1711 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
1712 DBG_WARNING("ndr_push_oplock_break_message failed: %s\n",
1713 ndr_errstr(ndr_err));
1714 return ndr_map_error2ntstatus(ndr_err);
1717 status = messaging_send(
1718 msg_ctx, exclusive->pid, MSG_SMB_BREAK_REQUEST, &blob);
1719 TALLOC_FREE(blob.data);
1720 if (!NT_STATUS_IS_OK(status)) {
1721 DEBUG(3, ("Could not send oplock break message: %s\n",
1722 nt_errstr(status)));
1729 * Do internal consistency checks on the share mode for a file.
1732 static bool validate_oplock_types(struct share_mode_lock *lck)
1734 struct share_mode_data *d = lck->data;
1736 bool ex_or_batch = false;
1737 bool level2 = false;
1738 bool no_oplock = false;
1739 uint32_t num_non_stat_opens = 0;
1742 for (i=0; i<d->num_share_modes; i++) {
1743 struct share_mode_entry *e = &d->share_modes[i];
1745 if (!is_valid_share_mode_entry(e)) {
1749 if (e->op_mid == 0) {
1750 /* INTERNAL_OPEN_ONLY */
1754 if (e->op_type == NO_OPLOCK && is_stat_open(e->access_mask)) {
1755 /* We ignore stat opens in the table - they
1756 always have NO_OPLOCK and never get or
1757 cause breaks. JRA. */
1761 num_non_stat_opens += 1;
1763 if (BATCH_OPLOCK_TYPE(e->op_type)) {
1764 /* batch - can only be one. */
1765 if (share_mode_stale_pid(d, i)) {
1766 DEBUG(10, ("Found stale batch oplock\n"));
1769 if (ex_or_batch || batch || level2 || no_oplock) {
1770 DEBUG(0, ("Bad batch oplock entry %u.",
1777 if (EXCLUSIVE_OPLOCK_TYPE(e->op_type)) {
1778 if (share_mode_stale_pid(d, i)) {
1779 DEBUG(10, ("Found stale duplicate oplock\n"));
1782 /* Exclusive or batch - can only be one. */
1783 if (ex_or_batch || level2 || no_oplock) {
1784 DEBUG(0, ("Bad exclusive or batch oplock "
1785 "entry %u.", (unsigned)i));
1791 if (LEVEL_II_OPLOCK_TYPE(e->op_type)) {
1792 if (batch || ex_or_batch) {
1793 if (share_mode_stale_pid(d, i)) {
1794 DEBUG(10, ("Found stale LevelII "
1798 DEBUG(0, ("Bad levelII oplock entry %u.",
1805 if (e->op_type == NO_OPLOCK) {
1806 if (batch || ex_or_batch) {
1807 if (share_mode_stale_pid(d, i)) {
1808 DEBUG(10, ("Found stale NO_OPLOCK "
1812 DEBUG(0, ("Bad no oplock entry %u.",
1820 remove_stale_share_mode_entries(d);
1822 if ((batch || ex_or_batch) && (num_non_stat_opens != 1)) {
1823 DEBUG(1, ("got batch (%d) or ex (%d) non-exclusively (%d)\n",
1824 (int)batch, (int)ex_or_batch,
1825 (int)d->num_share_modes));
1832 static bool is_same_lease(const files_struct *fsp,
1833 const struct share_mode_entry *e,
1834 const struct smb2_lease *lease)
1836 if (e->op_type != LEASE_OPLOCK) {
1839 if (lease == NULL) {
1843 return smb2_lease_equal(fsp_client_guid(fsp),
1849 static bool delay_for_oplock(files_struct *fsp,
1851 const struct smb2_lease *lease,
1852 struct share_mode_lock *lck,
1853 bool have_sharing_violation,
1854 uint32_t create_disposition,
1855 bool first_open_attempt)
1857 struct share_mode_data *d = lck->data;
1860 bool will_overwrite;
1861 const uint32_t delay_mask = have_sharing_violation ?
1862 SMB2_LEASE_HANDLE : SMB2_LEASE_WRITE;
1864 if ((oplock_request & INTERNAL_OPEN_ONLY) ||
1865 is_stat_open(fsp->access_mask)) {
1869 switch (create_disposition) {
1870 case FILE_SUPERSEDE:
1871 case FILE_OVERWRITE:
1872 case FILE_OVERWRITE_IF:
1873 will_overwrite = true;
1876 will_overwrite = false;
1880 for (i=0; i<d->num_share_modes; i++) {
1881 struct share_mode_entry *e = &d->share_modes[i];
1882 bool e_is_lease = (e->op_type == LEASE_OPLOCK);
1883 uint32_t e_lease_type = get_lease_type(d, e);
1885 bool lease_is_breaking = false;
1890 if (lease != NULL) {
1891 bool our_lease = is_same_lease(fsp, e, lease);
1893 DBG_DEBUG("Ignoring our own lease\n");
1898 status = leases_db_get(
1902 NULL, /* current_state */
1904 NULL, /* breaking_to_requested */
1905 NULL, /* breaking_to_required */
1906 NULL, /* lease_version */
1908 SMB_ASSERT(NT_STATUS_IS_OK(status));
1911 break_to = e_lease_type & ~delay_mask;
1913 if (will_overwrite) {
1914 break_to &= ~(SMB2_LEASE_HANDLE|SMB2_LEASE_READ);
1917 DEBUG(10, ("entry %u: e_lease_type %u, will_overwrite: %u\n",
1918 (unsigned)i, (unsigned)e_lease_type,
1919 (unsigned)will_overwrite));
1921 if ((e_lease_type & ~break_to) == 0) {
1922 if (lease_is_breaking) {
1928 if (share_mode_stale_pid(d, i)) {
1932 if (will_overwrite) {
1934 * If we break anyway break to NONE directly.
1935 * Otherwise vfs_set_filelen() will trigger the
1938 break_to &= ~(SMB2_LEASE_READ|SMB2_LEASE_WRITE);
1943 * Oplocks only support breaking to R or NONE.
1945 break_to &= ~(SMB2_LEASE_HANDLE|SMB2_LEASE_WRITE);
1948 DEBUG(10, ("breaking from %d to %d\n",
1949 (int)e_lease_type, (int)break_to));
1950 send_break_message(fsp->conn->sconn->msg_ctx, &fsp->file_id,
1952 if (e_lease_type & delay_mask) {
1955 if (lease_is_breaking && !first_open_attempt) {
1963 static bool file_has_brlocks(files_struct *fsp)
1965 struct byte_range_lock *br_lck;
1967 br_lck = brl_get_locks_readonly(fsp);
1971 return (brl_num_locks(br_lck) > 0);
1974 struct fsp_lease *find_fsp_lease(struct files_struct *new_fsp,
1975 const struct smb2_lease_key *key,
1976 uint32_t current_state,
1977 uint16_t lease_version,
1978 uint16_t lease_epoch)
1980 struct files_struct *fsp;
1983 * TODO: Measure how expensive this loop is with thousands of open
1987 for (fsp = file_find_di_first(new_fsp->conn->sconn, new_fsp->file_id);
1989 fsp = file_find_di_next(fsp)) {
1991 if (fsp == new_fsp) {
1994 if (fsp->oplock_type != LEASE_OPLOCK) {
1997 if (smb2_lease_key_equal(&fsp->lease->lease.lease_key, key)) {
1998 fsp->lease->ref_count += 1;
2003 /* Not found - must be leased in another smbd. */
2004 new_fsp->lease = talloc_zero(new_fsp->conn->sconn, struct fsp_lease);
2005 if (new_fsp->lease == NULL) {
2008 new_fsp->lease->ref_count = 1;
2009 new_fsp->lease->sconn = new_fsp->conn->sconn;
2010 new_fsp->lease->lease.lease_key = *key;
2011 new_fsp->lease->lease.lease_state = current_state;
2013 * We internally treat all leases as V2 and update
2014 * the epoch, but when sending breaks it matters if
2015 * the requesting lease was v1 or v2.
2017 new_fsp->lease->lease.lease_version = lease_version;
2018 new_fsp->lease->lease.lease_epoch = lease_epoch;
2019 return new_fsp->lease;
2022 static NTSTATUS try_lease_upgrade(struct files_struct *fsp,
2023 struct share_mode_lock *lck,
2024 const struct GUID *client_guid,
2025 const struct smb2_lease *lease,
2029 uint32_t current_state, breaking_to_requested, breaking_to_required;
2031 uint16_t lease_version, epoch;
2032 uint32_t existing, requested;
2035 status = leases_db_get(
2041 &breaking_to_requested,
2042 &breaking_to_required,
2045 if (!NT_STATUS_IS_OK(status)) {
2049 fsp->lease = find_fsp_lease(
2055 if (fsp->lease == NULL) {
2056 DEBUG(1, ("Did not find existing lease for file %s\n",
2058 return NT_STATUS_NO_MEMORY;
2062 * Upgrade only if the requested lease is a strict upgrade.
2064 existing = current_state;
2065 requested = lease->lease_state;
2068 * Tricky: This test makes sure that "requested" is a
2069 * strict bitwise superset of "existing".
2071 do_upgrade = ((existing & requested) == existing);
2074 * Upgrade only if there's a change.
2076 do_upgrade &= (granted != existing);
2079 * Upgrade only if other leases don't prevent what was asked
2082 do_upgrade &= (granted == requested);
2085 * only upgrade if we are not in breaking state
2087 do_upgrade &= !breaking;
2089 DEBUG(10, ("existing=%"PRIu32", requested=%"PRIu32", "
2090 "granted=%"PRIu32", do_upgrade=%d\n",
2091 existing, requested, granted, (int)do_upgrade));
2094 NTSTATUS set_status;
2096 current_state = granted;
2099 set_status = leases_db_set(
2104 breaking_to_requested,
2105 breaking_to_required,
2109 if (!NT_STATUS_IS_OK(set_status)) {
2110 DBG_DEBUG("leases_db_set failed: %s\n",
2111 nt_errstr(set_status));
2116 fsp_lease_update(fsp);
2118 return NT_STATUS_OK;
2121 static NTSTATUS grant_new_fsp_lease(struct files_struct *fsp,
2122 struct share_mode_lock *lck,
2123 const struct GUID *client_guid,
2124 const struct smb2_lease *lease,
2127 struct share_mode_data *d = lck->data;
2130 fsp->lease = talloc_zero(fsp->conn->sconn, struct fsp_lease);
2131 if (fsp->lease == NULL) {
2132 return NT_STATUS_INSUFFICIENT_RESOURCES;
2134 fsp->lease->ref_count = 1;
2135 fsp->lease->sconn = fsp->conn->sconn;
2136 fsp->lease->lease.lease_version = lease->lease_version;
2137 fsp->lease->lease.lease_key = lease->lease_key;
2138 fsp->lease->lease.lease_state = granted;
2139 fsp->lease->lease.lease_epoch = lease->lease_epoch + 1;
2141 status = leases_db_add(client_guid,
2144 fsp->lease->lease.lease_state,
2145 fsp->lease->lease.lease_version,
2146 fsp->lease->lease.lease_epoch,
2147 fsp->conn->connectpath,
2148 fsp->fsp_name->base_name,
2149 fsp->fsp_name->stream_name);
2150 if (!NT_STATUS_IS_OK(status)) {
2151 DEBUG(10, ("%s: leases_db_add failed: %s\n", __func__,
2152 nt_errstr(status)));
2153 TALLOC_FREE(fsp->lease);
2154 return NT_STATUS_INSUFFICIENT_RESOURCES;
2159 return NT_STATUS_OK;
2162 static NTSTATUS grant_fsp_lease(struct files_struct *fsp,
2163 struct share_mode_lock *lck,
2164 const struct smb2_lease *lease,
2167 const struct GUID *client_guid = fsp_client_guid(fsp);
2170 status = try_lease_upgrade(fsp, lck, client_guid, lease, granted);
2172 if (NT_STATUS_EQUAL(status, NT_STATUS_NOT_FOUND)) {
2173 status = grant_new_fsp_lease(
2174 fsp, lck, client_guid, lease, granted);
2180 static int map_lease_type_to_oplock(uint32_t lease_type)
2182 int result = NO_OPLOCK;
2184 switch (lease_type) {
2185 case SMB2_LEASE_READ|SMB2_LEASE_WRITE|SMB2_LEASE_HANDLE:
2186 result = BATCH_OPLOCK|EXCLUSIVE_OPLOCK;
2188 case SMB2_LEASE_READ|SMB2_LEASE_WRITE:
2189 result = EXCLUSIVE_OPLOCK;
2191 case SMB2_LEASE_READ|SMB2_LEASE_HANDLE:
2192 case SMB2_LEASE_READ:
2193 result = LEVEL_II_OPLOCK;
2200 static NTSTATUS grant_fsp_oplock_type(struct smb_request *req,
2201 struct files_struct *fsp,
2202 struct share_mode_lock *lck,
2204 const struct smb2_lease *lease,
2205 uint32_t share_access,
2206 uint32_t access_mask)
2208 struct share_mode_data *d = lck->data;
2209 bool got_handle_lease = false;
2210 bool got_oplock = false;
2216 if (oplock_request & INTERNAL_OPEN_ONLY) {
2217 /* No oplocks on internal open. */
2218 oplock_request = NO_OPLOCK;
2219 DEBUG(10,("grant_fsp_oplock_type: oplock type 0x%x on file %s\n",
2220 fsp->oplock_type, fsp_str_dbg(fsp)));
2223 if (oplock_request == LEASE_OPLOCK) {
2224 if (lease == NULL) {
2226 * The SMB2 layer should have checked this
2228 return NT_STATUS_INTERNAL_ERROR;
2231 granted = lease->lease_state;
2233 if (lp_kernel_oplocks(SNUM(fsp->conn))) {
2234 DEBUG(10, ("No lease granted because kernel oplocks are enabled\n"));
2235 granted = SMB2_LEASE_NONE;
2237 if ((granted & (SMB2_LEASE_READ|SMB2_LEASE_WRITE)) == 0) {
2238 DEBUG(10, ("No read or write lease requested\n"));
2239 granted = SMB2_LEASE_NONE;
2241 if (granted == SMB2_LEASE_WRITE) {
2242 DEBUG(10, ("pure write lease requested\n"));
2243 granted = SMB2_LEASE_NONE;
2245 if (granted == (SMB2_LEASE_WRITE|SMB2_LEASE_HANDLE)) {
2246 DEBUG(10, ("write and handle lease requested\n"));
2247 granted = SMB2_LEASE_NONE;
2250 granted = map_oplock_to_lease_type(
2251 oplock_request & ~SAMBA_PRIVATE_OPLOCK_MASK);
2254 if (lp_locking(fsp->conn->params) && file_has_brlocks(fsp)) {
2255 DEBUG(10,("grant_fsp_oplock_type: file %s has byte range locks\n",
2257 granted &= ~SMB2_LEASE_READ;
2260 for (i=0; i<d->num_share_modes; i++) {
2261 struct share_mode_entry *e = &d->share_modes[i];
2263 if ((granted & SMB2_LEASE_WRITE) &&
2264 !is_same_lease(fsp, e, lease) &&
2265 !share_mode_stale_pid(d, i)) {
2267 * Can grant only one writer
2269 granted &= ~SMB2_LEASE_WRITE;
2272 if (!got_handle_lease) {
2273 uint32_t e_lease_type = get_lease_type(d, e);
2274 if ((e_lease_type & SMB2_LEASE_HANDLE) &&
2275 !share_mode_stale_pid(d, i)) {
2276 got_handle_lease = true;
2280 if ((e->op_type != LEASE_OPLOCK) && !got_oplock &&
2281 !share_mode_stale_pid(d, i)) {
2286 if ((granted & SMB2_LEASE_READ) && !(granted & SMB2_LEASE_WRITE)) {
2288 (global_client_caps & CAP_LEVEL_II_OPLOCKS) &&
2289 lp_level2_oplocks(SNUM(fsp->conn));
2291 if (!allow_level2) {
2292 granted = SMB2_LEASE_NONE;
2296 if (oplock_request == LEASE_OPLOCK) {
2298 granted &= ~SMB2_LEASE_HANDLE;
2301 fsp->oplock_type = LEASE_OPLOCK;
2303 status = grant_fsp_lease(fsp, lck, lease, granted);
2304 if (!NT_STATUS_IS_OK(status)) {
2309 DBG_DEBUG("lease_state=%d\n", fsp->lease->lease.lease_state);
2311 if (got_handle_lease) {
2312 granted = SMB2_LEASE_NONE;
2315 fsp->oplock_type = map_lease_type_to_oplock(granted);
2317 status = set_file_oplock(fsp);
2318 if (!NT_STATUS_IS_OK(status)) {
2320 * Could not get the kernel oplock
2322 fsp->oplock_type = NO_OPLOCK;
2326 ok = set_share_mode(
2329 get_current_uid(fsp->conn),
2335 if (fsp->oplock_type == LEASE_OPLOCK) {
2336 status = remove_lease_if_stale(
2338 fsp_client_guid(fsp),
2339 &fsp->lease->lease.lease_key);
2340 if (!NT_STATUS_IS_OK(status)) {
2341 DBG_WARNING("remove_lease_if_stale "
2346 return NT_STATUS_NO_MEMORY;
2349 if (granted & SMB2_LEASE_READ) {
2350 lck->data->flags |= SHARE_MODE_HAS_READ_LEASE;
2353 DEBUG(10,("grant_fsp_oplock_type: oplock type 0x%x on file %s\n",
2354 fsp->oplock_type, fsp_str_dbg(fsp)));
2356 return NT_STATUS_OK;
2359 static bool request_timed_out(struct smb_request *req, struct timeval timeout)
2361 struct timeval now, end_time;
2363 end_time = timeval_sum(&req->request_time, &timeout);
2364 return (timeval_compare(&end_time, &now) < 0);
2367 struct defer_open_state {
2368 struct smbXsrv_connection *xconn;
2372 static void defer_open_done(struct tevent_req *req);
2375 * Defer an open and watch a locking.tdb record
2377 * This defers an open that gets rescheduled once the locking.tdb record watch
2378 * is triggered by a change to the record.
2380 * It is used to defer opens that triggered an oplock break and for the SMB1
2381 * sharing violation delay.
2383 static void defer_open(struct share_mode_lock *lck,
2384 struct timeval timeout,
2385 struct smb_request *req,
2386 bool delayed_for_oplocks,
2389 struct deferred_open_record *open_rec = NULL;
2390 struct timeval abs_timeout;
2391 struct defer_open_state *watch_state;
2392 struct tevent_req *watch_req;
2393 struct timeval_buf tvbuf1, tvbuf2;
2396 abs_timeout = timeval_sum(&req->request_time, &timeout);
2398 DBG_DEBUG("request time [%s] timeout [%s] mid [%" PRIu64 "] "
2399 "delayed_for_oplocks [%s] file_id [%s]\n",
2400 timeval_str_buf(&req->request_time, false, true, &tvbuf1),
2401 timeval_str_buf(&abs_timeout, false, true, &tvbuf2),
2403 delayed_for_oplocks ? "yes" : "no",
2404 file_id_string_tos(&id));
2406 open_rec = talloc_zero(NULL, struct deferred_open_record);
2407 if (open_rec == NULL) {
2409 exit_server("talloc failed");
2412 watch_state = talloc(open_rec, struct defer_open_state);
2413 if (watch_state == NULL) {
2414 exit_server("talloc failed");
2416 watch_state->xconn = req->xconn;
2417 watch_state->mid = req->mid;
2419 DBG_DEBUG("defering mid %" PRIu64 "\n", req->mid);
2421 watch_req = dbwrap_watched_watch_send(watch_state,
2424 (struct server_id){0});
2425 if (watch_req == NULL) {
2426 exit_server("Could not watch share mode record");
2428 tevent_req_set_callback(watch_req, defer_open_done, watch_state);
2430 ok = tevent_req_set_endtime(watch_req, req->sconn->ev_ctx, abs_timeout);
2432 exit_server("tevent_req_set_endtime failed");
2435 ok = push_deferred_open_message_smb(req, timeout, id, open_rec);
2438 exit_server("push_deferred_open_message_smb failed");
2442 static void defer_open_done(struct tevent_req *req)
2444 struct defer_open_state *state = tevent_req_callback_data(
2445 req, struct defer_open_state);
2449 status = dbwrap_watched_watch_recv(req, NULL, NULL);
2451 if (!NT_STATUS_IS_OK(status)) {
2452 DEBUG(5, ("dbwrap_watched_watch_recv returned %s\n",
2453 nt_errstr(status)));
2455 * Even if it failed, retry anyway. TODO: We need a way to
2456 * tell a re-scheduled open about that error.
2460 DEBUG(10, ("scheduling mid %llu\n", (unsigned long long)state->mid));
2462 ret = schedule_deferred_open_message_smb(state->xconn, state->mid);
2468 * Actually attempt the kernel oplock polling open.
2471 static void poll_open_fn(struct tevent_context *ev,
2472 struct tevent_timer *te,
2473 struct timeval current_time,
2476 struct deferred_open_record *open_rec = talloc_get_type_abort(
2477 private_data, struct deferred_open_record);
2480 ok = schedule_deferred_open_message_smb(
2481 open_rec->xconn, open_rec->mid);
2483 exit_server("schedule_deferred_open_message_smb failed");
2485 DBG_DEBUG("timer fired. Retrying open !\n");
2488 static void poll_open_done(struct tevent_req *subreq);
2491 * Reschedule an open for 1 second from now, if not timed out.
2493 static bool setup_poll_open(
2494 struct smb_request *req,
2495 struct share_mode_lock *lck,
2497 struct timeval max_timeout,
2498 struct timeval interval)
2502 struct deferred_open_record *open_rec = NULL;
2503 struct timeval endtime, next_interval;
2505 if (request_timed_out(req, max_timeout)) {
2509 open_rec = talloc_zero(NULL, struct deferred_open_record);
2510 if (open_rec == NULL) {
2511 DBG_WARNING("talloc failed\n");
2514 open_rec->xconn = req->xconn;
2515 open_rec->mid = req->mid;
2518 * Make sure open_rec->te does not come later than the
2519 * request's maximum endtime.
2522 endtime = timeval_sum(&req->request_time, &max_timeout);
2523 next_interval = timeval_current_ofs(interval.tv_sec, interval.tv_usec);
2524 next_interval = timeval_min(&endtime, &next_interval);
2526 open_rec->te = tevent_add_timer(
2532 if (open_rec->te == NULL) {
2533 DBG_WARNING("tevent_add_timer failed\n");
2534 TALLOC_FREE(open_rec);
2539 struct tevent_req *watch_req = dbwrap_watched_watch_send(
2543 (struct server_id) {0});
2544 if (watch_req == NULL) {
2545 DBG_WARNING("dbwrap_watched_watch_send failed\n");
2546 TALLOC_FREE(open_rec);
2549 tevent_req_set_callback(watch_req, poll_open_done, open_rec);
2552 ok = push_deferred_open_message_smb(req, max_timeout, id, open_rec);
2554 DBG_WARNING("push_deferred_open_message_smb failed\n");
2555 TALLOC_FREE(open_rec);
2559 DBG_DEBUG("poll request time [%s] mid [%" PRIu64 "] file_id [%s]\n",
2560 timeval_string(talloc_tos(), &req->request_time, false),
2562 file_id_string_tos(&id));
2567 static void poll_open_done(struct tevent_req *subreq)
2569 struct deferred_open_record *open_rec = tevent_req_callback_data(
2570 subreq, struct deferred_open_record);
2574 status = dbwrap_watched_watch_recv(subreq, NULL, NULL);
2575 TALLOC_FREE(subreq);
2576 DBG_DEBUG("dbwrap_watched_watch_recv returned %s\n",
2579 ok = schedule_deferred_open_message_smb(
2580 open_rec->xconn, open_rec->mid);
2582 exit_server("schedule_deferred_open_message_smb failed");
2586 bool defer_smb1_sharing_violation(struct smb_request *req)
2591 if (!lp_defer_sharing_violations()) {
2596 * Try every 200msec up to (by default) one second. To be
2597 * precise, according to behaviour note <247> in [MS-CIFS],
2598 * the server tries 5 times. But up to one second should be
2602 timeout_usecs = lp_parm_int(
2606 SHARING_VIOLATION_USEC_WAIT);
2608 ok = setup_poll_open(
2611 (struct file_id) {0},
2612 (struct timeval) { .tv_usec = timeout_usecs },
2613 (struct timeval) { .tv_usec = 200000 });
2617 /****************************************************************************
2618 On overwrite open ensure that the attributes match.
2619 ****************************************************************************/
2621 static bool open_match_attributes(connection_struct *conn,
2622 uint32_t old_dos_attr,
2623 uint32_t new_dos_attr,
2624 mode_t new_unx_mode,
2625 mode_t *returned_unx_mode)
2627 uint32_t noarch_old_dos_attr, noarch_new_dos_attr;
2629 noarch_old_dos_attr = (old_dos_attr & ~FILE_ATTRIBUTE_ARCHIVE);
2630 noarch_new_dos_attr = (new_dos_attr & ~FILE_ATTRIBUTE_ARCHIVE);
2632 if((noarch_old_dos_attr == 0 && noarch_new_dos_attr != 0) ||
2633 (noarch_old_dos_attr != 0 && ((noarch_old_dos_attr & noarch_new_dos_attr) == noarch_old_dos_attr))) {
2634 *returned_unx_mode = new_unx_mode;
2636 *returned_unx_mode = (mode_t)0;
2639 DEBUG(10,("open_match_attributes: old_dos_attr = 0x%x, "
2640 "new_dos_attr = 0x%x "
2641 "returned_unx_mode = 0%o\n",
2642 (unsigned int)old_dos_attr,
2643 (unsigned int)new_dos_attr,
2644 (unsigned int)*returned_unx_mode ));
2646 /* If we're mapping SYSTEM and HIDDEN ensure they match. */
2647 if (lp_map_system(SNUM(conn)) || lp_store_dos_attributes(SNUM(conn))) {
2648 if ((old_dos_attr & FILE_ATTRIBUTE_SYSTEM) &&
2649 !(new_dos_attr & FILE_ATTRIBUTE_SYSTEM)) {
2653 if (lp_map_hidden(SNUM(conn)) || lp_store_dos_attributes(SNUM(conn))) {
2654 if ((old_dos_attr & FILE_ATTRIBUTE_HIDDEN) &&
2655 !(new_dos_attr & FILE_ATTRIBUTE_HIDDEN)) {
2662 static void schedule_defer_open(struct share_mode_lock *lck,
2664 struct smb_request *req)
2666 /* This is a relative time, added to the absolute
2667 request_time value to get the absolute timeout time.
2668 Note that if this is the second or greater time we enter
2669 this codepath for this particular request mid then
2670 request_time is left as the absolute time of the *first*
2671 time this request mid was processed. This is what allows
2672 the request to eventually time out. */
2674 struct timeval timeout;
2676 /* Normally the smbd we asked should respond within
2677 * OPLOCK_BREAK_TIMEOUT seconds regardless of whether
2678 * the client did, give twice the timeout as a safety
2679 * measure here in case the other smbd is stuck
2680 * somewhere else. */
2682 timeout = timeval_set(OPLOCK_BREAK_TIMEOUT*2, 0);
2684 if (request_timed_out(req, timeout)) {
2688 defer_open(lck, timeout, req, true, id);
2691 /****************************************************************************
2692 Reschedule an open call that went asynchronous.
2693 ****************************************************************************/
2695 static void schedule_async_open_timer(struct tevent_context *ev,
2696 struct tevent_timer *te,
2697 struct timeval current_time,
2700 exit_server("async open timeout");
2703 static void schedule_async_open(struct smb_request *req)
2705 struct deferred_open_record *open_rec = NULL;
2706 struct timeval timeout = timeval_set(20, 0);
2709 if (request_timed_out(req, timeout)) {
2713 open_rec = talloc_zero(NULL, struct deferred_open_record);
2714 if (open_rec == NULL) {
2715 exit_server("deferred_open_record_create failed");
2717 open_rec->async_open = true;
2719 ok = push_deferred_open_message_smb(
2720 req, timeout, (struct file_id){0}, open_rec);
2722 exit_server("push_deferred_open_message_smb failed");
2725 open_rec->te = tevent_add_timer(req->sconn->ev_ctx,
2727 timeval_current_ofs(20, 0),
2728 schedule_async_open_timer,
2730 if (open_rec->te == NULL) {
2731 exit_server("tevent_add_timer failed");
2735 /****************************************************************************
2736 Work out what access_mask to use from what the client sent us.
2737 ****************************************************************************/
2739 static NTSTATUS smbd_calculate_maximum_allowed_access(
2740 connection_struct *conn,
2741 const struct smb_filename *smb_fname,
2743 uint32_t *p_access_mask)
2745 struct security_descriptor *sd;
2746 uint32_t access_granted;
2749 if (!use_privs && (get_current_uid(conn) == (uid_t)0)) {
2750 *p_access_mask |= FILE_GENERIC_ALL;
2751 return NT_STATUS_OK;
2754 status = SMB_VFS_GET_NT_ACL(conn, smb_fname,
2760 if (NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
2762 * File did not exist
2764 *p_access_mask = FILE_GENERIC_ALL;
2765 return NT_STATUS_OK;
2767 if (!NT_STATUS_IS_OK(status)) {
2768 DEBUG(10,("Could not get acl on file %s: %s\n",
2769 smb_fname_str_dbg(smb_fname),
2770 nt_errstr(status)));
2771 return NT_STATUS_ACCESS_DENIED;
2775 * If we can access the path to this file, by
2776 * default we have FILE_READ_ATTRIBUTES from the
2777 * containing directory. See the section:
2778 * "Algorithm to Check Access to an Existing File"
2781 * se_file_access_check()
2782 * also takes care of owner WRITE_DAC and READ_CONTROL.
2784 status = se_file_access_check(sd,
2785 get_current_nttok(conn),
2787 (*p_access_mask & ~FILE_READ_ATTRIBUTES),
2792 if (!NT_STATUS_IS_OK(status)) {
2793 DEBUG(10, ("Access denied on file %s: "
2794 "when calculating maximum access\n",
2795 smb_fname_str_dbg(smb_fname)));
2796 return NT_STATUS_ACCESS_DENIED;
2798 *p_access_mask = (access_granted | FILE_READ_ATTRIBUTES);
2800 if (!(access_granted & DELETE_ACCESS)) {
2801 if (can_delete_file_in_directory(conn, smb_fname)) {
2802 *p_access_mask |= DELETE_ACCESS;
2806 return NT_STATUS_OK;
2809 NTSTATUS smbd_calculate_access_mask(connection_struct *conn,
2810 const struct smb_filename *smb_fname,
2812 uint32_t access_mask,
2813 uint32_t *access_mask_out)
2816 uint32_t orig_access_mask = access_mask;
2817 uint32_t rejected_share_access;
2819 if (access_mask & SEC_MASK_INVALID) {
2820 DBG_DEBUG("access_mask [%8x] contains invalid bits\n",
2822 return NT_STATUS_ACCESS_DENIED;
2826 * Convert GENERIC bits to specific bits.
2829 se_map_generic(&access_mask, &file_generic_mapping);
2831 /* Calculate MAXIMUM_ALLOWED_ACCESS if requested. */
2832 if (access_mask & MAXIMUM_ALLOWED_ACCESS) {
2834 status = smbd_calculate_maximum_allowed_access(
2835 conn, smb_fname, use_privs, &access_mask);
2837 if (!NT_STATUS_IS_OK(status)) {
2841 access_mask &= conn->share_access;
2844 rejected_share_access = access_mask & ~(conn->share_access);
2846 if (rejected_share_access) {
2847 DEBUG(10, ("smbd_calculate_access_mask: Access denied on "
2848 "file %s: rejected by share access mask[0x%08X] "
2849 "orig[0x%08X] mapped[0x%08X] reject[0x%08X]\n",
2850 smb_fname_str_dbg(smb_fname),
2852 orig_access_mask, access_mask,
2853 rejected_share_access));
2854 return NT_STATUS_ACCESS_DENIED;
2857 *access_mask_out = access_mask;
2858 return NT_STATUS_OK;
2861 /****************************************************************************
2862 Remove the deferred open entry under lock.
2863 ****************************************************************************/
2865 /****************************************************************************
2866 Return true if this is a state pointer to an asynchronous create.
2867 ****************************************************************************/
2869 bool is_deferred_open_async(const struct deferred_open_record *rec)
2871 return rec->async_open;
2874 static bool clear_ads(uint32_t create_disposition)
2878 switch (create_disposition) {
2879 case FILE_SUPERSEDE:
2880 case FILE_OVERWRITE_IF:
2881 case FILE_OVERWRITE:
2890 static int disposition_to_open_flags(uint32_t create_disposition)
2895 * Currently we're using FILE_SUPERSEDE as the same as
2896 * FILE_OVERWRITE_IF but they really are
2897 * different. FILE_SUPERSEDE deletes an existing file
2898 * (requiring delete access) then recreates it.
2901 switch (create_disposition) {
2902 case FILE_SUPERSEDE:
2903 case FILE_OVERWRITE_IF:
2905 * If file exists replace/overwrite. If file doesn't
2908 ret = O_CREAT|O_TRUNC;
2913 * If file exists open. If file doesn't exist error.
2918 case FILE_OVERWRITE:
2920 * If file exists overwrite. If file doesn't exist
2928 * If file exists error. If file doesn't exist create.
2930 ret = O_CREAT|O_EXCL;
2935 * If file exists open. If file doesn't exist create.
2943 static int calculate_open_access_flags(uint32_t access_mask,
2944 uint32_t private_flags)
2946 bool need_write, need_read;
2949 * Note that we ignore the append flag as append does not
2950 * mean the same thing under DOS and Unix.
2953 need_write = (access_mask & (FILE_WRITE_DATA | FILE_APPEND_DATA));
2958 /* DENY_DOS opens are always underlying read-write on the
2959 file handle, no matter what the requested access mask
2963 ((private_flags & NTCREATEX_OPTIONS_PRIVATE_DENY_DOS) ||
2964 access_mask & (FILE_READ_ATTRIBUTES|FILE_READ_DATA|
2965 FILE_READ_EA|FILE_EXECUTE));
2973 /****************************************************************************
2974 Open a file with a share mode. Passed in an already created files_struct *.
2975 ****************************************************************************/
2977 static NTSTATUS open_file_ntcreate(connection_struct *conn,
2978 struct smb_request *req,
2979 uint32_t access_mask, /* access bits (FILE_READ_DATA etc.) */
2980 uint32_t share_access, /* share constants (FILE_SHARE_READ etc) */
2981 uint32_t create_disposition, /* FILE_OPEN_IF etc. */
2982 uint32_t create_options, /* options such as delete on close. */
2983 uint32_t new_dos_attributes, /* attributes used for new file. */
2984 int oplock_request, /* internal Samba oplock codes. */
2985 const struct smb2_lease *lease,
2986 /* Information (FILE_EXISTS etc.) */
2987 uint32_t private_flags, /* Samba specific flags. */
2991 struct smb_filename *smb_fname = fsp->fsp_name;
2994 bool file_existed = VALID_STAT(smb_fname->st);
2995 bool def_acl = False;
2996 bool posix_open = False;
2997 bool new_file_created = False;
2998 bool first_open_attempt = true;
2999 NTSTATUS fsp_open = NT_STATUS_ACCESS_DENIED;
3000 mode_t new_unx_mode = (mode_t)0;
3001 mode_t unx_mode = (mode_t)0;
3003 uint32_t existing_dos_attributes = 0;
3004 struct share_mode_lock *lck = NULL;
3005 uint32_t open_access_mask = access_mask;
3008 SMB_STRUCT_STAT saved_stat = smb_fname->st;
3009 struct timespec old_write_time;
3012 if (conn->printer) {
3014 * Printers are handled completely differently.
3015 * Most of the passed parameters are ignored.
3019 *pinfo = FILE_WAS_CREATED;
3022 DEBUG(10, ("open_file_ntcreate: printer open fname=%s\n",
3023 smb_fname_str_dbg(smb_fname)));
3026 DEBUG(0,("open_file_ntcreate: printer open without "
3027 "an SMB request!\n"));
3028 return NT_STATUS_INTERNAL_ERROR;
3031 return print_spool_open(fsp, smb_fname->base_name,
3035 if (!parent_dirname(talloc_tos(), smb_fname->base_name, &parent_dir,
3037 return NT_STATUS_NO_MEMORY;
3040 if (new_dos_attributes & FILE_FLAG_POSIX_SEMANTICS) {
3042 unx_mode = (mode_t)(new_dos_attributes & ~FILE_FLAG_POSIX_SEMANTICS);
3043 new_dos_attributes = 0;
3045 /* Windows allows a new file to be created and
3046 silently removes a FILE_ATTRIBUTE_DIRECTORY
3047 sent by the client. Do the same. */
3049 new_dos_attributes &= ~FILE_ATTRIBUTE_DIRECTORY;
3051 /* We add FILE_ATTRIBUTE_ARCHIVE to this as this mode is only used if the file is
3053 unx_mode = unix_mode(conn, new_dos_attributes | FILE_ATTRIBUTE_ARCHIVE,
3054 smb_fname, parent_dir);
3057 DEBUG(10, ("open_file_ntcreate: fname=%s, dos_attrs=0x%x "
3058 "access_mask=0x%x share_access=0x%x "
3059 "create_disposition = 0x%x create_options=0x%x "
3060 "unix mode=0%o oplock_request=%d private_flags = 0x%x\n",
3061 smb_fname_str_dbg(smb_fname), new_dos_attributes,
3062 access_mask, share_access, create_disposition,
3063 create_options, (unsigned int)unx_mode, oplock_request,
3064 (unsigned int)private_flags));
3067 /* Ensure req == NULL means INTERNAL_OPEN_ONLY */
3068 SMB_ASSERT(oplock_request == INTERNAL_OPEN_ONLY);
3070 /* And req != NULL means no INTERNAL_OPEN_ONLY */
3071 SMB_ASSERT(((oplock_request & INTERNAL_OPEN_ONLY) == 0));
3075 * Only non-internal opens can be deferred at all
3079 struct deferred_open_record *open_rec;
3080 if (get_deferred_open_message_state(req, NULL, &open_rec)) {
3082 /* If it was an async create retry, the file
3085 if (is_deferred_open_async(open_rec)) {
3086 SET_STAT_INVALID(smb_fname->st);
3087 file_existed = false;
3090 /* Ensure we don't reprocess this message. */
3091 remove_deferred_open_message_smb(req->xconn, req->mid);
3093 first_open_attempt = false;
3098 new_dos_attributes &= SAMBA_ATTRIBUTES_MASK;
3101 * Only use stored DOS attributes for checks
3102 * against requested attributes (below via
3103 * open_match_attributes()), cf bug #11992
3104 * for details. -slow
3108 status = SMB_VFS_GET_DOS_ATTRIBUTES(conn, smb_fname, &attr);
3109 if (NT_STATUS_IS_OK(status)) {
3110 existing_dos_attributes = attr;
3115 /* ignore any oplock requests if oplocks are disabled */
3116 if (!lp_oplocks(SNUM(conn)) ||
3117 IS_VETO_OPLOCK_PATH(conn, smb_fname->base_name)) {
3118 /* Mask off everything except the private Samba bits. */
3119 oplock_request &= SAMBA_PRIVATE_OPLOCK_MASK;
3122 /* this is for OS/2 long file names - say we don't support them */
3123 if (req != NULL && !req->posix_pathnames &&
3124 strstr(smb_fname->base_name,".+,;=[].")) {
3125 /* OS/2 Workplace shell fix may be main code stream in a later
3127 DEBUG(5,("open_file_ntcreate: OS/2 long filenames are not "
3129 if (use_nt_status()) {
3130 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3132 return NT_STATUS_DOS(ERRDOS, ERRcannotopen);
3135 switch( create_disposition ) {
3137 /* If file exists open. If file doesn't exist error. */
3138 if (!file_existed) {
3139 DEBUG(5,("open_file_ntcreate: FILE_OPEN "
3140 "requested for file %s and file "
3142 smb_fname_str_dbg(smb_fname)));
3144 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3148 case FILE_OVERWRITE:
3149 /* If file exists overwrite. If file doesn't exist
3151 if (!file_existed) {
3152 DEBUG(5,("open_file_ntcreate: FILE_OVERWRITE "
3153 "requested for file %s and file "
3155 smb_fname_str_dbg(smb_fname) ));
3157 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3162 /* If file exists error. If file doesn't exist
3165 DEBUG(5,("open_file_ntcreate: FILE_CREATE "
3166 "requested for file %s and file "
3167 "already exists.\n",
3168 smb_fname_str_dbg(smb_fname)));
3169 if (S_ISDIR(smb_fname->st.st_ex_mode)) {
3174 return map_nt_error_from_unix(errno);
3178 case FILE_SUPERSEDE:
3179 case FILE_OVERWRITE_IF:
3183 return NT_STATUS_INVALID_PARAMETER;
3186 flags2 = disposition_to_open_flags(create_disposition);
3188 /* We only care about matching attributes on file exists and
3191 if (!posix_open && file_existed &&
3192 ((create_disposition == FILE_OVERWRITE) ||
3193 (create_disposition == FILE_OVERWRITE_IF))) {
3194 if (!open_match_attributes(conn, existing_dos_attributes,
3196 unx_mode, &new_unx_mode)) {
3197 DEBUG(5,("open_file_ntcreate: attributes mismatch "
3198 "for file %s (%x %x) (0%o, 0%o)\n",
3199 smb_fname_str_dbg(smb_fname),
3200 existing_dos_attributes,
3202 (unsigned int)smb_fname->st.st_ex_mode,
3203 (unsigned int)unx_mode ));
3205 return NT_STATUS_ACCESS_DENIED;
3209 status = smbd_calculate_access_mask(conn, smb_fname,
3213 if (!NT_STATUS_IS_OK(status)) {
3214 DEBUG(10, ("open_file_ntcreate: smbd_calculate_access_mask "
3215 "on file %s returned %s\n",
3216 smb_fname_str_dbg(smb_fname), nt_errstr(status)));
3220 open_access_mask = access_mask;
3222 if (flags2 & O_TRUNC) {
3223 open_access_mask |= FILE_WRITE_DATA; /* This will cause oplock breaks. */
3226 DEBUG(10, ("open_file_ntcreate: fname=%s, after mapping "
3227 "access_mask=0x%x\n", smb_fname_str_dbg(smb_fname),
3231 * Note that we ignore the append flag as append does not
3232 * mean the same thing under DOS and Unix.
3235 flags = calculate_open_access_flags(access_mask, private_flags);
3238 * Currently we only look at FILE_WRITE_THROUGH for create options.
3242 if ((create_options & FILE_WRITE_THROUGH) && lp_strict_sync(SNUM(conn))) {
3247 if (posix_open && (access_mask & FILE_APPEND_DATA)) {
3251 if (!posix_open && !CAN_WRITE(conn)) {
3253 * We should really return a permission denied error if either
3254 * O_CREAT or O_TRUNC are set, but for compatibility with
3255 * older versions of Samba we just AND them out.
3257 flags2 &= ~(O_CREAT|O_TRUNC);
3261 * With kernel oplocks the open breaking an oplock
3262 * blocks until the oplock holder has given up the
3263 * oplock or closed the file. We prevent this by always
3264 * trying to open the file with O_NONBLOCK (see "man
3267 * If a process that doesn't use the smbd open files
3268 * database or communication methods holds a kernel
3269 * oplock we must periodically poll for available open
3272 flags2 |= O_NONBLOCK;
3275 * Ensure we can't write on a read-only share or file.
3278 if (flags != O_RDONLY && file_existed &&
3279 (!CAN_WRITE(conn) || IS_DOS_READONLY(existing_dos_attributes))) {
3280 DEBUG(5,("open_file_ntcreate: write access requested for "
3281 "file %s on read only %s\n",
3282 smb_fname_str_dbg(smb_fname),
3283 !CAN_WRITE(conn) ? "share" : "file" ));
3285 return NT_STATUS_ACCESS_DENIED;
3288 fsp->file_id = vfs_file_id_from_sbuf(conn, &smb_fname->st);
3289 fsp->fh->private_options = private_flags;
3290 fsp->access_mask = open_access_mask; /* We change this to the
3291 * requested access_mask after
3292 * the open is done. */
3294 fsp->posix_flags |= FSP_POSIX_FLAGS_ALL;
3297 if ((create_options & FILE_DELETE_ON_CLOSE) &&
3298 (flags2 & O_CREAT) &&
3300 /* Delete on close semantics for new files. */
3301 status = can_set_delete_on_close(fsp,
3302 new_dos_attributes);
3303 if (!NT_STATUS_IS_OK(status)) {
3310 * Ensure we pay attention to default ACLs on directories if required.
3313 if ((flags2 & O_CREAT) && lp_inherit_acls(SNUM(conn)) &&
3314 (def_acl = directory_has_default_acl(conn, parent_dir))) {
3315 unx_mode = (0777 & lp_create_mask(SNUM(conn)));
3318 DEBUG(4,("calling open_file with flags=0x%X flags2=0x%X mode=0%o, "
3319 "access_mask = 0x%x, open_access_mask = 0x%x\n",
3320 (unsigned int)flags, (unsigned int)flags2,
3321 (unsigned int)unx_mode, (unsigned int)access_mask,
3322 (unsigned int)open_access_mask));
3324 fsp_open = open_file(fsp, conn, req, parent_dir,
3325 flags|flags2, unx_mode, access_mask,
3326 open_access_mask, &new_file_created);
3328 if (NT_STATUS_EQUAL(fsp_open, NT_STATUS_NETWORK_BUSY)) {
3332 * This handles the kernel oplock case:
3334 * the file has an active kernel oplock and the open() returned
3335 * EWOULDBLOCK/EAGAIN which maps to NETWORK_BUSY.
3337 * "Samba locking.tdb oplocks" are handled below after acquiring
3338 * the sharemode lock with get_share_mode_lock().
3340 if (file_existed && S_ISFIFO(fsp->fsp_name->st.st_ex_mode)) {
3341 DEBUG(10, ("FIFO busy\n"));
3342 return NT_STATUS_NETWORK_BUSY;
3345 DEBUG(10, ("Internal open busy\n"));
3346 return NT_STATUS_NETWORK_BUSY;
3350 * From here on we assume this is an oplock break triggered
3353 lck = get_existing_share_mode_lock(talloc_tos(), fsp->file_id);
3356 * No oplock from Samba around. Set up a poll every 1
3357 * second to retry a non-blocking open until the time
3364 timeval_set(OPLOCK_BREAK_TIMEOUT*2, 0),
3366 DBG_DEBUG("No Samba oplock around after EWOULDBLOCK. "
3367 "Retrying with poll\n");
3368 return NT_STATUS_SHARING_VIOLATION;
3371 if (!validate_oplock_types(lck)) {
3372 smb_panic("validate_oplock_types failed");
3375 delay = delay_for_oplock(fsp, 0, lease, lck, false,
3377 first_open_attempt);
3379 schedule_defer_open(lck, fsp->file_id, req);
3381 DEBUG(10, ("Sent oplock break request to kernel "
3382 "oplock holder\n"));
3383 return NT_STATUS_SHARING_VIOLATION;
3387 * No oplock from Samba around. Set up a poll every 1
3388 * second to retry a non-blocking open until the time
3395 timeval_set(OPLOCK_BREAK_TIMEOUT*2, 0),
3399 DBG_DEBUG("No Samba oplock around after EWOULDBLOCK. "
3400 "Retrying with poll\n");
3401 return NT_STATUS_SHARING_VIOLATION;
3404 if (!NT_STATUS_IS_OK(fsp_open)) {
3405 if (NT_STATUS_EQUAL(fsp_open, NT_STATUS_RETRY)) {
3406 schedule_async_open(req);
3411 if (new_file_created) {
3413 * As we atomically create using O_CREAT|O_EXCL,
3414 * then if new_file_created is true, then
3415 * file_existed *MUST* have been false (even
3416 * if the file was previously detected as being
3419 file_existed = false;
3422 if (file_existed && !check_same_dev_ino(&saved_stat, &smb_fname->st)) {
3424 * The file did exist, but some other (local or NFS)
3425 * process either renamed/unlinked and re-created the
3426 * file with different dev/ino after we walked the path,
3427 * but before we did the open. We could retry the
3428 * open but it's a rare enough case it's easier to
3429 * just fail the open to prevent creating any problems
3430 * in the open file db having the wrong dev/ino key.
3433 DBG_WARNING("file %s - dev/ino mismatch. "
3434 "Old (dev=%ju, ino=%ju). "
3435 "New (dev=%ju, ino=%ju). Failing open "
3436 "with NT_STATUS_ACCESS_DENIED.\n",
3437 smb_fname_str_dbg(smb_fname),
3438 (uintmax_t)saved_stat.st_ex_dev,
3439 (uintmax_t)saved_stat.st_ex_ino,
3440 (uintmax_t)smb_fname->st.st_ex_dev,
3441 (uintmax_t)smb_fname->st.st_ex_ino);
3442 return NT_STATUS_ACCESS_DENIED;
3445 old_write_time = smb_fname->st.st_ex_mtime;
3448 * Deal with the race condition where two smbd's detect the
3449 * file doesn't exist and do the create at the same time. One
3450 * of them will win and set a share mode, the other (ie. this
3451 * one) should check if the requested share mode for this
3452 * create is allowed.
3456 * Now the file exists and fsp is successfully opened,
3457 * fsp->dev and fsp->inode are valid and should replace the
3458 * dev=0,inode=0 from a non existent file. Spotted by
3459 * Nadav Danieli <nadavd@exanet.com>. JRA.
3464 lck = get_share_mode_lock(talloc_tos(), id,
3466 smb_fname, &old_write_time);
3469 DEBUG(0, ("open_file_ntcreate: Could not get share "
3470 "mode lock for %s\n",
3471 smb_fname_str_dbg(smb_fname)));
3473 return NT_STATUS_SHARING_VIOLATION;
3476 /* Get the types we need to examine. */
3477 if (!validate_oplock_types(lck)) {
3478 smb_panic("validate_oplock_types failed");
3481 if (has_delete_on_close(lck, fsp->name_hash)) {
3484 return NT_STATUS_DELETE_PENDING;
3487 status = open_mode_check(conn, lck,
3488 access_mask, share_access);
3490 if (NT_STATUS_EQUAL(status, NT_STATUS_SHARING_VIOLATION) ||
3491 (lck->data->num_share_modes > 0)) {
3493 * This comes from ancient times out of open_mode_check. I
3494 * have no clue whether this is still necessary. I can't think
3495 * of a case where this would actually matter further down in
3496 * this function. I leave it here for further investigation
3499 file_existed = true;
3504 * Handle oplocks, deferring the request if delay_for_oplock()
3505 * triggered a break message and we have to wait for the break
3509 bool sharing_violation = NT_STATUS_EQUAL(
3510 status, NT_STATUS_SHARING_VIOLATION);
3512 delay = delay_for_oplock(fsp, oplock_request, lease, lck,
3515 first_open_attempt);
3517 schedule_defer_open(lck, fsp->file_id, req);
3520 return NT_STATUS_SHARING_VIOLATION;
3524 if (!NT_STATUS_IS_OK(status)) {
3526 SMB_ASSERT(NT_STATUS_EQUAL(status, NT_STATUS_SHARING_VIOLATION));
3531 return NT_STATUS_SHARING_VIOLATION;
3534 /* Should we atomically (to the client at least) truncate ? */
3535 if ((!new_file_created) &&
3536 (flags2 & O_TRUNC) &&
3537 (S_ISREG(fsp->fsp_name->st.st_ex_mode))) {
3540 ret = SMB_VFS_FTRUNCATE(fsp, 0);
3542 status = map_nt_error_from_unix(errno);
3547 notify_fname(fsp->conn, NOTIFY_ACTION_MODIFIED,
3548 FILE_NOTIFY_CHANGE_SIZE
3549 | FILE_NOTIFY_CHANGE_ATTRIBUTES,
3550 fsp->fsp_name->base_name);
3554 * We have the share entry *locked*.....
3557 /* Delete streams if create_disposition requires it */
3558 if (!new_file_created && clear_ads(create_disposition) &&
3559 !is_ntfs_stream_smb_fname(smb_fname)) {
3560 status = delete_all_streams(conn, smb_fname);
3561 if (!NT_STATUS_IS_OK(status)) {
3568 if (fsp->fh->fd != -1 && lp_kernel_share_modes(SNUM(conn))) {
3571 * Beware: streams implementing VFS modules may
3572 * implement streams in a way that fsp will have the
3573 * basefile open in the fsp fd, so lacking a distinct
3574 * fd for the stream kernel_flock will apply on the
3575 * basefile which is wrong. The actual check is
3576 * deferred to the VFS module implementing the
3577 * kernel_flock call.
3579 ret_flock = SMB_VFS_KERNEL_FLOCK(fsp, share_access, access_mask);
3580 if(ret_flock == -1 ){
3585 return NT_STATUS_SHARING_VIOLATION;
3588 fsp->kernel_share_modes_taken = true;
3592 * At this point onwards, we can guarantee that the share entry
3593 * is locked, whether we created the file or not, and that the
3594 * deny mode is compatible with all current opens.
3598 * According to Samba4, SEC_FILE_READ_ATTRIBUTE is always granted,
3599 * but we don't have to store this - just ignore it on access check.
3601 if (conn->sconn->using_smb2) {
3603 * SMB2 doesn't return it (according to Microsoft tests).
3604 * Test Case: TestSuite_ScenarioNo009GrantedAccessTestS0
3605 * File created with access = 0x7 (Read, Write, Delete)
3606 * Query Info on file returns 0x87 (Read, Write, Delete, Read Attributes)
3608 fsp->access_mask = access_mask;
3610 /* But SMB1 does. */
3611 fsp->access_mask = access_mask | FILE_READ_ATTRIBUTES;
3616 * stat opens on existing files don't get oplocks.
3617 * They can get leases.
3619 * Note that we check for stat open on the *open_access_mask*,
3620 * i.e. the access mask we actually used to do the open,
3621 * not the one the client asked for (which is in
3622 * fsp->access_mask). This is due to the fact that
3623 * FILE_OVERWRITE and FILE_OVERWRITE_IF add in O_TRUNC,
3624 * which adds FILE_WRITE_DATA to open_access_mask.
3626 if (is_stat_open(open_access_mask) && lease == NULL) {
3627 oplock_request = NO_OPLOCK;
3631 if (new_file_created) {
3632 info = FILE_WAS_CREATED;
3634 if (flags2 & O_TRUNC) {
3635 info = FILE_WAS_OVERWRITTEN;
3637 info = FILE_WAS_OPENED;
3646 * Setup the oplock info in both the shared memory and
3649 status = grant_fsp_oplock_type(
3657 if (!NT_STATUS_IS_OK(status)) {
3663 /* Handle strange delete on close create semantics. */
3664 if (create_options & FILE_DELETE_ON_CLOSE) {
3665 if (!new_file_created) {
3666 status = can_set_delete_on_close(fsp,
3667 existing_dos_attributes);
3669 if (!NT_STATUS_IS_OK(status)) {
3670 /* Remember to delete the mode we just added. */
3671 del_share_mode(lck, fsp);
3677 /* Note that here we set the *initial* delete on close flag,
3678 not the regular one. The magic gets handled in close. */
3679 fsp->initial_delete_on_close = True;
3682 if (info == FILE_WAS_CREATED) {
3683 smb_fname->st.st_ex_iflags &= ~ST_EX_IFLAG_CALCULATED_ITIME;
3686 if (info != FILE_WAS_OPENED) {
3687 /* Overwritten files should be initially set as archive */
3688 if ((info == FILE_WAS_OVERWRITTEN && lp_map_archive(SNUM(conn))) ||
3689 lp_store_dos_attributes(SNUM(conn))) {
3691 if (file_set_dosmode(conn, smb_fname,
3692 new_dos_attributes | FILE_ATTRIBUTE_ARCHIVE,
3693 parent_dir, true) == 0) {
3694 unx_mode = smb_fname->st.st_ex_mode;
3700 /* Determine sparse flag. */
3702 /* POSIX opens are sparse by default. */
3703 fsp->is_sparse = true;
3705 fsp->is_sparse = (file_existed &&
3706 (existing_dos_attributes & FILE_ATTRIBUTE_SPARSE));
3710 * Take care of inherited ACLs on created files - if default ACL not
3714 if (!posix_open && new_file_created && !def_acl) {
3715 if (unx_mode != smb_fname->st.st_ex_mode) {
3716 int ret = SMB_VFS_FCHMOD(fsp, unx_mode);
3718 DBG_INFO("failed to reset "
3719 "attributes of file %s to 0%o\n",
3720 smb_fname_str_dbg(smb_fname),
3721 (unsigned int)unx_mode);
3725 } else if (new_unx_mode) {
3727 * We only get here in the case of:
3729 * a). Not a POSIX open.
3730 * b). File already existed.
3731 * c). File was overwritten.
3732 * d). Requested DOS attributes didn't match
3733 * the DOS attributes on the existing file.
3735 * In that case new_unx_mode has been set
3736 * equal to the calculated mode (including
3737 * possible inheritance of the mode from the
3738 * containing directory).
3740 * Note this mode was calculated with the
3741 * DOS attribute FILE_ATTRIBUTE_ARCHIVE added,
3742 * so the mode change here is suitable for
3743 * an overwritten file.
3746 if (new_unx_mode != smb_fname->st.st_ex_mode) {
3747 int ret = SMB_VFS_FCHMOD(fsp, new_unx_mode);
3749 DBG_INFO("failed to reset "
3750 "attributes of file %s to 0%o\n",
3751 smb_fname_str_dbg(smb_fname),
3752 (unsigned int)new_unx_mode);
3759 * Deal with other opens having a modified write time.
3761 struct timespec write_time = get_share_mode_write_time(lck);
3763 if (!null_timespec(write_time)) {
3764 update_stat_ex_mtime(&fsp->fsp_name->st, write_time);
3770 return NT_STATUS_OK;
3773 static NTSTATUS mkdir_internal(connection_struct *conn,
3774 struct smb_filename *smb_dname,
3775 uint32_t file_attributes)
3778 char *parent_dir = NULL;
3780 bool posix_open = false;
3781 bool need_re_stat = false;
3782 uint32_t access_mask = SEC_DIR_ADD_SUBDIR;
3784 if (!CAN_WRITE(conn) || (access_mask & ~(conn->share_access))) {
3785 DEBUG(5,("mkdir_internal: failing share access "
3786 "%s\n", lp_servicename(talloc_tos(), SNUM(conn))));
3787 return NT_STATUS_ACCESS_DENIED;
3790 if (!parent_dirname(talloc_tos(), smb_dname->base_name, &parent_dir,
3792 return NT_STATUS_NO_MEMORY;
3795 if (file_attributes & FILE_FLAG_POSIX_SEMANTICS) {
3797 mode = (mode_t)(file_attributes & ~FILE_FLAG_POSIX_SEMANTICS);
3799 mode = unix_mode(conn, FILE_ATTRIBUTE_DIRECTORY, smb_dname, parent_dir);
3802 status = check_parent_access(conn,
3805 if(!NT_STATUS_IS_OK(status)) {
3806 DEBUG(5,("mkdir_internal: check_parent_access "
3807 "on directory %s for path %s returned %s\n",
3809 smb_dname->base_name,
3810 nt_errstr(status) ));
3814 if (SMB_VFS_MKDIR(conn, smb_dname, mode) != 0) {
3815 return map_nt_error_from_unix(errno);
3818 /* Ensure we're checking for a symlink here.... */
3819 /* We don't want to get caught by a symlink racer. */
3821 if (SMB_VFS_LSTAT(conn, smb_dname) == -1) {
3822 DEBUG(2, ("Could not stat directory '%s' just created: %s\n",
3823 smb_fname_str_dbg(smb_dname), strerror(errno)));
3824 return map_nt_error_from_unix(errno);
3827 if (!S_ISDIR(smb_dname->st.st_ex_mode)) {
3828 DEBUG(0, ("Directory '%s' just created is not a directory !\n",
3829 smb_fname_str_dbg(smb_dname)));
3830 return NT_STATUS_NOT_A_DIRECTORY;
3833 smb_dname->st.st_ex_iflags &= ~ST_EX_IFLAG_CALCULATED_ITIME;
3835 if (lp_store_dos_attributes(SNUM(conn))) {
3837 file_set_dosmode(conn, smb_dname,
3838 file_attributes | FILE_ATTRIBUTE_DIRECTORY,
3843 if (lp_inherit_permissions(SNUM(conn))) {
3844 inherit_access_posix_acl(conn, parent_dir,
3846 need_re_stat = true;
3851 * Check if high bits should have been set,
3852 * then (if bits are missing): add them.
3853 * Consider bits automagically set by UNIX, i.e. SGID bit from parent
3856 if ((mode & ~(S_IRWXU|S_IRWXG|S_IRWXO)) &&
3857 (mode & ~smb_dname->st.st_ex_mode)) {
3858 SMB_VFS_CHMOD(conn, smb_dname,
3859 (smb_dname->st.st_ex_mode |
3860 (mode & ~smb_dname->st.st_ex_mode)));
3861 need_re_stat = true;
3865 /* Change the owner if required. */
3866 if (lp_inherit_owner(SNUM(conn)) != INHERIT_OWNER_NO) {
3867 change_dir_owner_to_parent(conn, parent_dir,
3870 need_re_stat = true;
3874 if (SMB_VFS_LSTAT(conn, smb_dname) == -1) {
3875 DEBUG(2, ("Could not stat directory '%s' just created: %s\n",
3876 smb_fname_str_dbg(smb_dname), strerror(errno)));
3877 return map_nt_error_from_unix(errno);
3881 notify_fname(conn, NOTIFY_ACTION_ADDED, FILE_NOTIFY_CHANGE_DIR_NAME,
3882 smb_dname->base_name);
3884 return NT_STATUS_OK;
3887 /****************************************************************************
3888 Open a directory from an NT SMB call.
3889 ****************************************************************************/
3891 static NTSTATUS open_directory(connection_struct *conn,
3892 struct smb_request *req,
3893 struct smb_filename *smb_dname,
3894 uint32_t access_mask,
3895 uint32_t share_access,
3896 uint32_t create_disposition,
3897 uint32_t create_options,
3898 uint32_t file_attributes,
3900 files_struct **result)
3902 files_struct *fsp = NULL;
3903 bool dir_existed = VALID_STAT(smb_dname->st) ? True : False;
3904 struct share_mode_lock *lck = NULL;
3906 struct timespec mtimespec;
3910 if (is_ntfs_stream_smb_fname(smb_dname)) {
3911 DEBUG(2, ("open_directory: %s is a stream name!\n",
3912 smb_fname_str_dbg(smb_dname)));
3913 return NT_STATUS_NOT_A_DIRECTORY;
3916 if (!(file_attributes & FILE_FLAG_POSIX_SEMANTICS)) {
3917 /* Ensure we have a directory attribute. */
3918 file_attributes |= FILE_ATTRIBUTE_DIRECTORY;
3921 DEBUG(5,("open_directory: opening directory %s, access_mask = 0x%x, "
3922 "share_access = 0x%x create_options = 0x%x, "
3923 "create_disposition = 0x%x, file_attributes = 0x%x\n",
3924 smb_fname_str_dbg(smb_dname),
3925 (unsigned int)access_mask,
3926 (unsigned int)share_access,
3927 (unsigned int)create_options,
3928 (unsigned int)create_disposition,
3929 (unsigned int)file_attributes));
3931 status = smbd_calculate_access_mask(conn, smb_dname, false,
3932 access_mask, &access_mask);
3933 if (!NT_STATUS_IS_OK(status)) {
3934 DEBUG(10, ("open_directory: smbd_calculate_access_mask "
3935 "on file %s returned %s\n",
3936 smb_fname_str_dbg(smb_dname),
3937 nt_errstr(status)));
3941 if ((access_mask & SEC_FLAG_SYSTEM_SECURITY) &&
3942 !security_token_has_privilege(get_current_nttok(conn),
3943 SEC_PRIV_SECURITY)) {
3944 DEBUG(10, ("open_directory: open on %s "
3945 "failed - SEC_FLAG_SYSTEM_SECURITY denied.\n",
3946 smb_fname_str_dbg(smb_dname)));
3947 return NT_STATUS_PRIVILEGE_NOT_HELD;
3950 switch( create_disposition ) {
3954 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3957 info = FILE_WAS_OPENED;
3962 /* If directory exists error. If directory doesn't
3966 status = NT_STATUS_OBJECT_NAME_COLLISION;
3967 DEBUG(2, ("open_directory: unable to create "
3968 "%s. Error was %s\n",
3969 smb_fname_str_dbg(smb_dname),
3970 nt_errstr(status)));
3974 status = mkdir_internal(conn, smb_dname,
3977 if (!NT_STATUS_IS_OK(status)) {
3978 DEBUG(2, ("open_directory: unable to create "
3979 "%s. Error was %s\n",
3980 smb_fname_str_dbg(smb_dname),
3981 nt_errstr(status)));
3985 info = FILE_WAS_CREATED;
3990 * If directory exists open. If directory doesn't
3995 status = NT_STATUS_OK;
3996 info = FILE_WAS_OPENED;
3998 status = mkdir_internal(conn, smb_dname,
4001 if (NT_STATUS_IS_OK(status)) {
4002 info = FILE_WAS_CREATED;
4004 /* Cope with create race. */
4005 if (!NT_STATUS_EQUAL(status,
4006 NT_STATUS_OBJECT_NAME_COLLISION)) {
4007 DEBUG(2, ("open_directory: unable to create "
4008 "%s. Error was %s\n",
4009 smb_fname_str_dbg(smb_dname),
4010 nt_errstr(status)));
4015 * If mkdir_internal() returned
4016 * NT_STATUS_OBJECT_NAME_COLLISION
4017 * we still must lstat the path.
4020 if (SMB_VFS_LSTAT(conn, smb_dname)
4022 DEBUG(2, ("Could not stat "
4023 "directory '%s' just "
4028 return map_nt_error_from_unix(
4032 info = FILE_WAS_OPENED;
4038 case FILE_SUPERSEDE:
4039 case FILE_OVERWRITE:
4040 case FILE_OVERWRITE_IF:
4042 DEBUG(5,("open_directory: invalid create_disposition "
4043 "0x%x for directory %s\n",
4044 (unsigned int)create_disposition,
4045 smb_fname_str_dbg(smb_dname)));
4046 return NT_STATUS_INVALID_PARAMETER;
4049 if(!S_ISDIR(smb_dname->st.st_ex_mode)) {
4050 DEBUG(5,("open_directory: %s is not a directory !\n",
4051 smb_fname_str_dbg(smb_dname)));
4052 return NT_STATUS_NOT_A_DIRECTORY;
4055 if (info == FILE_WAS_OPENED) {
4056 status = smbd_check_access_rights(conn,
4060 if (!NT_STATUS_IS_OK(status)) {
4061 DEBUG(10, ("open_directory: smbd_check_access_rights on "
4062 "file %s failed with %s\n",
4063 smb_fname_str_dbg(smb_dname),
4064 nt_errstr(status)));
4069 status = file_new(req, conn, &fsp);
4070 if(!NT_STATUS_IS_OK(status)) {
4075 * Setup the files_struct for it.
4078 fsp->file_id = vfs_file_id_from_sbuf(conn, &smb_dname->st);
4079 fsp->vuid = req ? req->vuid : UID_FIELD_INVALID;
4080 fsp->file_pid = req ? req->smbpid : 0;
4081 fsp->can_lock = False;
4082 fsp->can_read = False;
4083 fsp->can_write = False;
4085 fsp->fh->private_options = 0;
4087 * According to Samba4, SEC_FILE_READ_ATTRIBUTE is always granted,
4089 fsp->access_mask = access_mask | FILE_READ_ATTRIBUTES;
4090 fsp->print_file = NULL;
4091 fsp->modified = False;
4092 fsp->oplock_type = NO_OPLOCK;
4093 fsp->sent_oplock_break = NO_BREAK_SENT;
4094 fsp->is_directory = True;
4095 if (file_attributes & FILE_FLAG_POSIX_SEMANTICS) {
4096 fsp->posix_flags |= FSP_POSIX_FLAGS_ALL;
4098 status = fsp_set_smb_fname(fsp, smb_dname);
4099 if (!NT_STATUS_IS_OK(status)) {
4100 file_free(req, fsp);
4104 /* Don't store old timestamps for directory
4105 handles in the internal database. We don't
4106 update them in there if new objects
4107 are creaded in the directory. Currently
4108 we only update timestamps on file writes.
4111 ZERO_STRUCT(mtimespec);
4114 status = fd_open(conn, fsp, O_RDONLY|O_DIRECTORY, 0);
4116 /* POSIX allows us to open a directory with O_RDONLY. */
4117 status = fd_open(conn, fsp, O_RDONLY, 0);
4119 if (!NT_STATUS_IS_OK(status)) {
4120 DBG_INFO("Could not open fd for "
4122 smb_fname_str_dbg(smb_dname),
4124 file_free(req, fsp);
4128 status = vfs_stat_fsp(fsp);
4129 if (!NT_STATUS_IS_OK(status)) {
4131 file_free(req, fsp);
4135 if(!S_ISDIR(fsp->fsp_name->st.st_ex_mode)) {
4136 DEBUG(5,("open_directory: %s is not a directory !\n",
4137 smb_fname_str_dbg(smb_dname)));
4139 file_free(req, fsp);
4140 return NT_STATUS_NOT_A_DIRECTORY;
4143 /* Ensure there was no race condition. We need to check
4144 * dev/inode but not permissions, as these can change
4146 if (!check_same_dev_ino(&smb_dname->st, &fsp->fsp_name->st)) {
4147 DEBUG(5,("open_directory: stat struct differs for "
4149 smb_fname_str_dbg(smb_dname)));
4151 file_free(req, fsp);
4152 return NT_STATUS_ACCESS_DENIED;
4155 lck = get_share_mode_lock(talloc_tos(), fsp->file_id,
4156 conn->connectpath, smb_dname,
4160 DEBUG(0, ("open_directory: Could not get share mode lock for "
4161 "%s\n", smb_fname_str_dbg(smb_dname)));
4163 file_free(req, fsp);
4164 return NT_STATUS_SHARING_VIOLATION;
4167 if (has_delete_on_close(lck, fsp->name_hash)) {
4170 file_free(req, fsp);
4171 return NT_STATUS_DELETE_PENDING;
4174 status = open_mode_check(conn, lck,
4175 access_mask, share_access);
4177 if (!NT_STATUS_IS_OK(status)) {
4180 file_free(req, fsp);
4184 ok = set_share_mode(
4187 get_current_uid(conn),
4195 file_free(req, fsp);
4196 return NT_STATUS_NO_MEMORY;
4199 /* For directories the delete on close bit at open time seems
4200 always to be honored on close... See test 19 in Samba4 BASE-DELETE. */
4201 if (create_options & FILE_DELETE_ON_CLOSE) {
4202 status = can_set_delete_on_close(fsp, 0);
4203 if (!NT_STATUS_IS_OK(status) && !NT_STATUS_EQUAL(status, NT_STATUS_DIRECTORY_NOT_EMPTY)) {
4204 del_share_mode(lck, fsp);
4207 file_free(req, fsp);
4211 if (NT_STATUS_IS_OK(status)) {
4212 /* Note that here we set the *initial* delete on close flag,
4213 not the regular one. The magic gets handled in close. */
4214 fsp->initial_delete_on_close = True;
4220 * Deal with other opens having a modified write time. Is this
4221 * possible for directories?
4223 struct timespec write_time = get_share_mode_write_time(lck);
4225 if (!null_timespec(write_time)) {
4226 update_stat_ex_mtime(&fsp->fsp_name->st, write_time);
4237 return NT_STATUS_OK;
4240 NTSTATUS create_directory(connection_struct *conn, struct smb_request *req,
4241 struct smb_filename *smb_dname)
4246 status = SMB_VFS_CREATE_FILE(
4249 0, /* root_dir_fid */
4250 smb_dname, /* fname */
4251 FILE_READ_ATTRIBUTES, /* access_mask */
4252 FILE_SHARE_NONE, /* share_access */
4253 FILE_CREATE, /* create_disposition*/
4254 FILE_DIRECTORY_FILE, /* create_options */
4255 FILE_ATTRIBUTE_DIRECTORY, /* file_attributes */
4256 0, /* oplock_request */
4258 0, /* allocation_size */
4259 0, /* private_flags */
4264 NULL, NULL); /* create context */
4266 if (NT_STATUS_IS_OK(status)) {
4267 close_file(req, fsp, NORMAL_CLOSE);
4273 /****************************************************************************
4274 Receive notification that one of our open files has been renamed by another
4276 ****************************************************************************/
4278 void msg_file_was_renamed(struct messaging_context *msg_ctx,
4281 struct server_id src,
4284 struct file_rename_message *msg = NULL;
4285 enum ndr_err_code ndr_err;
4287 struct smb_filename *smb_fname = NULL;
4288 struct smbd_server_connection *sconn =
4289 talloc_get_type_abort(private_data,
4290 struct smbd_server_connection);
4292 msg = talloc(talloc_tos(), struct file_rename_message);
4294 DBG_WARNING("talloc failed\n");
4298 ndr_err = ndr_pull_struct_blob_all(
4302 (ndr_pull_flags_fn_t)ndr_pull_file_rename_message);
4303 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
4304 DBG_DEBUG("ndr_pull_oplock_break_message failed: %s\n",
4305 ndr_errstr(ndr_err));
4308 if (DEBUGLEVEL >= 10) {
4309 struct server_id_buf buf;
4310 DBG_DEBUG("Got rename message from %s\n",
4311 server_id_str_buf(src, &buf));
4312 NDR_PRINT_DEBUG(file_rename_message, msg);
4315 /* stream_name must always be NULL if there is no stream. */
4316 if ((msg->stream_name != NULL) && (msg->stream_name[0] == '\0')) {
4317 msg->stream_name = NULL;
4320 smb_fname = synthetic_smb_fname(
4321 msg, msg->base_name, msg->stream_name, NULL, 0);
4322 if (smb_fname == NULL) {
4323 DBG_DEBUG("synthetic_smb_fname failed\n");
4327 fsp = file_find_dif(sconn, msg->id, msg->share_file_id);
4329 DBG_DEBUG("fsp not found\n");
4333 if (strcmp(fsp->conn->connectpath, msg->servicepath) == 0) {
4335 DBG_DEBUG("renaming file %s from %s -> %s\n",
4338 smb_fname_str_dbg(smb_fname));
4339 status = fsp_set_smb_fname(fsp, smb_fname);
4340 if (!NT_STATUS_IS_OK(status)) {
4341 DBG_DEBUG("fsp_set_smb_fname failed: %s\n",
4347 * Now we have the complete path we can work out if
4348 * this is actually within this share and adjust
4349 * newname accordingly.
4351 DBG_DEBUG("share mismatch (sharepath %s not sharepath %s) "
4352 "%s from %s -> %s\n",
4353 fsp->conn->connectpath,
4357 smb_fname_str_dbg(smb_fname));
4364 * If a main file is opened for delete, all streams need to be checked for
4365 * !FILE_SHARE_DELETE. Do this by opening with DELETE_ACCESS.
4366 * If that works, delete them all by setting the delete on close and close.
4369 static NTSTATUS open_streams_for_delete(connection_struct *conn,
4370 const struct smb_filename *smb_fname)
4372 struct stream_struct *stream_info = NULL;
4373 files_struct **streams = NULL;
4375 unsigned int i, num_streams = 0;
4376 TALLOC_CTX *frame = talloc_stackframe();
4379 status = vfs_streaminfo(conn, NULL, smb_fname, talloc_tos(),
4380 &num_streams, &stream_info);
4382 if (NT_STATUS_EQUAL(status, NT_STATUS_NOT_IMPLEMENTED)
4383 || NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
4384 DEBUG(10, ("no streams around\n"));
4386 return NT_STATUS_OK;
4389 if (!NT_STATUS_IS_OK(status)) {
4390 DEBUG(10, ("vfs_streaminfo failed: %s\n",
4391 nt_errstr(status)));
4395 DEBUG(10, ("open_streams_for_delete found %d streams\n",
4398 if (num_streams == 0) {
4400 return NT_STATUS_OK;
4403 streams = talloc_array(talloc_tos(), files_struct *, num_streams);
4404 if (streams == NULL) {
4405 DEBUG(0, ("talloc failed\n"));
4406 status = NT_STATUS_NO_MEMORY;
4410 for (i=0; i<num_streams; i++) {
4411 struct smb_filename *smb_fname_cp;
4413 if (strequal(stream_info[i].name, "::$DATA")) {
4418 smb_fname_cp = synthetic_smb_fname(talloc_tos(),
4419 smb_fname->base_name,
4420 stream_info[i].name,
4423 ~SMB_FILENAME_POSIX_PATH));
4424 if (smb_fname_cp == NULL) {
4425 status = NT_STATUS_NO_MEMORY;
4429 if (SMB_VFS_STAT(conn, smb_fname_cp) == -1) {
4430 DEBUG(10, ("Unable to stat stream: %s\n",
4431 smb_fname_str_dbg(smb_fname_cp)));
4434 status = SMB_VFS_CREATE_FILE(
4437 0, /* root_dir_fid */
4438 smb_fname_cp, /* fname */
4439 DELETE_ACCESS, /* access_mask */
4440 (FILE_SHARE_READ | /* share_access */
4441 FILE_SHARE_WRITE | FILE_SHARE_DELETE),
4442 FILE_OPEN, /* create_disposition*/
4443 0, /* create_options */
4444 FILE_ATTRIBUTE_NORMAL, /* file_attributes */
4445 0, /* oplock_request */
4447 0, /* allocation_size */
4448 NTCREATEX_OPTIONS_PRIVATE_STREAM_DELETE, /* private_flags */
4451 &streams[i], /* result */
4453 NULL, NULL); /* create context */
4455 if (!NT_STATUS_IS_OK(status)) {
4456 DEBUG(10, ("Could not open stream %s: %s\n",
4457 smb_fname_str_dbg(smb_fname_cp),
4458 nt_errstr(status)));
4460 TALLOC_FREE(smb_fname_cp);
4463 TALLOC_FREE(smb_fname_cp);
4467 * don't touch the variable "status" beyond this point :-)
4470 for (j = i-1 ; j >= 0; j--) {
4471 if (streams[j] == NULL) {
4475 DEBUG(10, ("Closing stream # %d, %s\n", j,
4476 fsp_str_dbg(streams[j])));
4477 close_file(NULL, streams[j], NORMAL_CLOSE);
4485 /*********************************************************************
4486 Create a default ACL by inheriting from the parent. If no inheritance
4487 from the parent available, don't set anything. This will leave the actual
4488 permissions the new file or directory already got from the filesystem
4489 as the NT ACL when read.
4490 *********************************************************************/
4492 static NTSTATUS inherit_new_acl(files_struct *fsp)
4494 TALLOC_CTX *frame = talloc_stackframe();
4495 char *parent_name = NULL;
4496 struct security_descriptor *parent_desc = NULL;
4497 NTSTATUS status = NT_STATUS_OK;
4498 struct security_descriptor *psd = NULL;
4499 const struct dom_sid *owner_sid = NULL;
4500 const struct dom_sid *group_sid = NULL;
4501 uint32_t security_info_sent = (SECINFO_OWNER | SECINFO_GROUP | SECINFO_DACL);
4502 struct security_token *token = fsp->conn->session_info->security_token;
4503 bool inherit_owner =
4504 (lp_inherit_owner(SNUM(fsp->conn)) == INHERIT_OWNER_WINDOWS_AND_UNIX);
4505 bool inheritable_components = false;
4506 bool try_builtin_administrators = false;
4507 const struct dom_sid *BA_U_sid = NULL;
4508 const struct dom_sid *BA_G_sid = NULL;
4509 bool try_system = false;
4510 const struct dom_sid *SY_U_sid = NULL;
4511 const struct dom_sid *SY_G_sid = NULL;
4513 struct smb_filename *parent_smb_fname = NULL;
4515 if (!parent_dirname(frame, fsp->fsp_name->base_name, &parent_name, NULL)) {
4517 return NT_STATUS_NO_MEMORY;
4519 parent_smb_fname = synthetic_smb_fname(talloc_tos(),
4523 fsp->fsp_name->flags);
4525 if (parent_smb_fname == NULL) {
4527 return NT_STATUS_NO_MEMORY;
4530 status = SMB_VFS_GET_NT_ACL(fsp->conn,
4532 (SECINFO_OWNER | SECINFO_GROUP | SECINFO_DACL),
4535 if (!NT_STATUS_IS_OK(status)) {
4540 inheritable_components = sd_has_inheritable_components(parent_desc,
4543 if (!inheritable_components && !inherit_owner) {
4545 /* Nothing to inherit and not setting owner. */
4546 return NT_STATUS_OK;
4549 /* Create an inherited descriptor from the parent. */
4551 if (DEBUGLEVEL >= 10) {
4552 DEBUG(10,("inherit_new_acl: parent acl for %s is:\n",
4553 fsp_str_dbg(fsp) ));
4554 NDR_PRINT_DEBUG(security_descriptor, parent_desc);
4557 /* Inherit from parent descriptor if "inherit owner" set. */
4558 if (inherit_owner) {
4559 owner_sid = parent_desc->owner_sid;
4560 group_sid = parent_desc->group_sid;
4563 if (owner_sid == NULL) {
4564 if (security_token_has_builtin_administrators(token)) {
4565 try_builtin_administrators = true;
4566 } else if (security_token_is_system(token)) {
4567 try_builtin_administrators = true;
4572 if (group_sid == NULL &&
4573 token->num_sids == PRIMARY_GROUP_SID_INDEX)
4575 if (security_token_is_system(token)) {
4576 try_builtin_administrators = true;
4581 if (try_builtin_administrators) {
4586 ok = sids_to_unixids(&global_sid_Builtin_Administrators, 1, &ids);
4590 BA_U_sid = &global_sid_Builtin_Administrators;
4591 BA_G_sid = &global_sid_Builtin_Administrators;
4594 BA_U_sid = &global_sid_Builtin_Administrators;
4597 BA_G_sid = &global_sid_Builtin_Administrators;
4610 ok = sids_to_unixids(&global_sid_System, 1, &ids);
4614 SY_U_sid = &global_sid_System;
4615 SY_G_sid = &global_sid_System;
4618 SY_U_sid = &global_sid_System;
4621 SY_G_sid = &global_sid_System;
4629 if (owner_sid == NULL) {
4630 owner_sid = BA_U_sid;
4633 if (owner_sid == NULL) {
4634 owner_sid = SY_U_sid;
4637 if (group_sid == NULL) {
4638 group_sid = SY_G_sid;
4641 if (try_system && group_sid == NULL) {
4642 group_sid = BA_G_sid;
4645 if (owner_sid == NULL) {
4646 owner_sid = &token->sids[PRIMARY_USER_SID_INDEX];
4648 if (group_sid == NULL) {
4649 if (token->num_sids == PRIMARY_GROUP_SID_INDEX) {
4650 group_sid = &token->sids[PRIMARY_USER_SID_INDEX];
4652 group_sid = &token->sids[PRIMARY_GROUP_SID_INDEX];
4656 status = se_create_child_secdesc(frame,
4663 if (!NT_STATUS_IS_OK(status)) {
4668 /* If inheritable_components == false,
4669 se_create_child_secdesc()
4670 creates a security descriptor with a NULL dacl
4671 entry, but with SEC_DESC_DACL_PRESENT. We need
4672 to remove that flag. */
4674 if (!inheritable_components) {
4675 security_info_sent &= ~SECINFO_DACL;
4676 psd->type &= ~SEC_DESC_DACL_PRESENT;
4679 if (DEBUGLEVEL >= 10) {
4680 DEBUG(10,("inherit_new_acl: child acl for %s is:\n",
4681 fsp_str_dbg(fsp) ));
4682 NDR_PRINT_DEBUG(security_descriptor, psd);
4685 if (inherit_owner) {
4686 /* We need to be root to force this. */
4689 status = SMB_VFS_FSET_NT_ACL(fsp,
4692 if (inherit_owner) {
4700 * If we already have a lease, it must match the new file id. [MS-SMB2]
4701 * 3.3.5.9.8 speaks about INVALID_PARAMETER if an already used lease key is
4702 * used for a different file name.
4705 struct lease_match_state {
4706 /* Input parameters. */
4707 TALLOC_CTX *mem_ctx;
4708 const char *servicepath;
4709 const struct smb_filename *fname;
4712 /* Return parameters. */
4713 uint32_t num_file_ids;
4714 struct file_id *ids;
4715 NTSTATUS match_status;
4718 /*************************************************************
4719 File doesn't exist but this lease key+guid is already in use.
4721 This is only allowable in the dynamic share case where the
4722 service path must be different.
4724 There is a small race condition here in the multi-connection
4725 case where a client sends two create calls on different connections,
4726 where the file doesn't exist and one smbd creates the leases_db
4727 entry first, but this will get fixed by the multichannel cleanup
4728 when all identical client_guids get handled by a single smbd.
4729 **************************************************************/
4731 static void lease_match_parser_new_file(
4733 const struct leases_db_file *files,
4734 struct lease_match_state *state)
4738 for (i = 0; i < num_files; i++) {
4739 const struct leases_db_file *f = &files[i];
4740 if (strequal(state->servicepath, f->servicepath)) {
4741 state->match_status = NT_STATUS_INVALID_PARAMETER;
4746 /* Dynamic share case. Break leases on all other files. */
4747 state->match_status = leases_db_copy_file_ids(state->mem_ctx,
4751 if (!NT_STATUS_IS_OK(state->match_status)) {
4755 state->num_file_ids = num_files;
4756 state->match_status = NT_STATUS_OPLOCK_NOT_GRANTED;
4760 static void lease_match_parser(
4762 const struct leases_db_file *files,
4765 struct lease_match_state *state =
4766 (struct lease_match_state *)private_data;
4769 if (!state->file_existed) {
4771 * Deal with name mismatch or
4772 * possible dynamic share case separately
4773 * to make code clearer.
4775 lease_match_parser_new_file(num_files,
4782 state->match_status = NT_STATUS_OK;
4784 for (i = 0; i < num_files; i++) {
4785 const struct leases_db_file *f = &files[i];
4787 /* Everything should be the same. */
4788 if (!file_id_equal(&state->id, &f->id)) {
4789 /* This should catch all dynamic share cases. */
4790 state->match_status = NT_STATUS_OPLOCK_NOT_GRANTED;
4793 if (!strequal(f->servicepath, state->servicepath)) {
4794 state->match_status = NT_STATUS_INVALID_PARAMETER;
4797 if (!strequal(f->base_name, state->fname->base_name)) {
4798 state->match_status = NT_STATUS_INVALID_PARAMETER;
4801 if (!strequal(f->stream_name, state->fname->stream_name)) {
4802 state->match_status = NT_STATUS_INVALID_PARAMETER;
4807 if (NT_STATUS_IS_OK(state->match_status)) {
4809 * Common case - just opening another handle on a
4810 * file on a non-dynamic share.
4815 if (NT_STATUS_EQUAL(state->match_status, NT_STATUS_INVALID_PARAMETER)) {
4816 /* Mismatched path. Error back to client. */
4821 * File id mismatch. Dynamic share case NT_STATUS_OPLOCK_NOT_GRANTED.
4822 * Don't allow leases.
4825 state->match_status = leases_db_copy_file_ids(state->mem_ctx,
4829 if (!NT_STATUS_IS_OK(state->match_status)) {
4833 state->num_file_ids = num_files;
4834 state->match_status = NT_STATUS_OPLOCK_NOT_GRANTED;
4838 static NTSTATUS lease_match(connection_struct *conn,
4839 struct smb_request *req,
4840 const struct smb2_lease_key *lease_key,
4841 const char *servicepath,
4842 const struct smb_filename *fname,
4843 uint16_t *p_version,
4846 struct smbd_server_connection *sconn = req->sconn;
4847 TALLOC_CTX *tos = talloc_tos();
4848 struct lease_match_state state = {
4850 .servicepath = servicepath,
4852 .match_status = NT_STATUS_OK
4857 state.file_existed = VALID_STAT(fname->st);
4858 if (state.file_existed) {
4859 state.id = vfs_file_id_from_sbuf(conn, &fname->st);
4862 status = leases_db_parse(&sconn->client->connections->smb2.client.guid,
4863 lease_key, lease_match_parser, &state);
4864 if (!NT_STATUS_IS_OK(status)) {
4866 * Not found or error means okay: We can make the lease pass
4868 return NT_STATUS_OK;
4870 if (!NT_STATUS_EQUAL(state.match_status, NT_STATUS_OPLOCK_NOT_GRANTED)) {
4872 * Anything but NT_STATUS_OPLOCK_NOT_GRANTED, let the caller
4875 return state.match_status;
4878 /* We have to break all existing leases. */
4879 for (i = 0; i < state.num_file_ids; i++) {
4880 struct share_mode_lock *lck;
4881 struct share_mode_data *d;
4882 struct share_mode_entry *lease_entry = NULL;
4885 if (file_id_equal(&state.ids[i], &state.id)) {
4886 /* Don't need to break our own file. */
4890 lck = get_existing_share_mode_lock(talloc_tos(), state.ids[i]);
4892 /* Race condition - file already closed. */
4896 for (j=0; j<d->num_share_modes; j++) {
4897 struct share_mode_entry *e = &d->share_modes[j];
4898 uint32_t e_lease_type = get_lease_type(d, e);
4900 if (share_mode_stale_pid(d, j)) {
4904 if (e->op_type == LEASE_OPLOCK) {
4905 if (!smb2_lease_key_equal(&e->lease_key,
4912 if (e_lease_type == SMB2_LEASE_NONE) {
4916 send_break_message(conn->sconn->msg_ctx, &d->id, e,
4920 * Windows 7 and 8 lease clients
4921 * are broken in that they will not
4922 * respond to lease break requests
4923 * whilst waiting for an outstanding
4924 * open request on that lease handle
4925 * on the same TCP connection, due
4926 * to holding an internal inode lock.
4928 * This means we can't reschedule
4929 * ourselves here, but must return
4934 * Send the breaks and then return
4935 * SMB2_LEASE_NONE in the lease handle
4936 * to cause them to acknowledge the
4937 * lease break. Consultation with
4938 * Microsoft engineering confirmed
4939 * this approach is safe.
4944 if (lease_entry != NULL) {
4945 status = leases_db_get(
4946 &lease_entry->client_guid,
4947 &lease_entry->lease_key,
4949 NULL, /* current_state */
4950 NULL, /* breaking */
4951 NULL, /* breaking_to_requested */
4952 NULL, /* breaking_to_required */
4953 p_version, /* lease_version */
4954 p_epoch); /* epoch */
4955 if (!NT_STATUS_IS_OK(status)) {
4956 DBG_WARNING("Could not find version/epoch: "
4965 * Ensure we don't grant anything more so we
4968 return NT_STATUS_OPLOCK_NOT_GRANTED;
4972 * Wrapper around open_file_ntcreate and open_directory
4975 static NTSTATUS create_file_unixpath(connection_struct *conn,
4976 struct smb_request *req,
4977 struct smb_filename *smb_fname,
4978 uint32_t access_mask,
4979 uint32_t share_access,
4980 uint32_t create_disposition,
4981 uint32_t create_options,
4982 uint32_t file_attributes,
4983 uint32_t oplock_request,
4984 const struct smb2_lease *lease,
4985 uint64_t allocation_size,
4986 uint32_t private_flags,
4987 struct security_descriptor *sd,
4988 struct ea_list *ea_list,
4990 files_struct **result,
4993 struct smb2_lease none_lease;
4994 int info = FILE_WAS_OPENED;
4995 files_struct *base_fsp = NULL;
4996 files_struct *fsp = NULL;
4999 DBG_DEBUG("create_file_unixpath: access_mask = 0x%x "
5000 "file_attributes = 0x%x, share_access = 0x%x, "
5001 "create_disposition = 0x%x create_options = 0x%x "
5002 "oplock_request = 0x%x private_flags = 0x%x "
5003 "ea_list = %p, sd = %p, "
5005 (unsigned int)access_mask,
5006 (unsigned int)file_attributes,
5007 (unsigned int)share_access,
5008 (unsigned int)create_disposition,
5009 (unsigned int)create_options,
5010 (unsigned int)oplock_request,
5011 (unsigned int)private_flags,
5012 ea_list, sd, smb_fname_str_dbg(smb_fname));
5014 if (create_options & FILE_OPEN_BY_FILE_ID) {
5015 status = NT_STATUS_NOT_SUPPORTED;
5019 if (create_options & NTCREATEX_OPTIONS_INVALID_PARAM_MASK) {
5020 status = NT_STATUS_INVALID_PARAMETER;
5025 oplock_request |= INTERNAL_OPEN_ONLY;
5028 if (lease != NULL) {
5029 uint16_t epoch = lease->lease_epoch;
5030 uint16_t version = lease->lease_version;
5033 DBG_WARNING("Got lease on internal open\n");
5034 status = NT_STATUS_INTERNAL_ERROR;
5038 status = lease_match(conn,
5045 if (NT_STATUS_EQUAL(status, NT_STATUS_OPLOCK_NOT_GRANTED)) {
5046 /* Dynamic share file. No leases and update epoch... */
5047 none_lease = *lease;
5048 none_lease.lease_state = SMB2_LEASE_NONE;
5049 none_lease.lease_epoch = epoch;
5050 none_lease.lease_version = version;
5051 lease = &none_lease;
5052 } else if (!NT_STATUS_IS_OK(status)) {
5057 if ((conn->fs_capabilities & FILE_NAMED_STREAMS)
5058 && (access_mask & DELETE_ACCESS)
5059 && !is_ntfs_stream_smb_fname(smb_fname)) {
5061 * We can't open a file with DELETE access if any of the
5062 * streams is open without FILE_SHARE_DELETE
5064 status = open_streams_for_delete(conn, smb_fname);
5066 if (!NT_STATUS_IS_OK(status)) {
5071 if ((access_mask & SEC_FLAG_SYSTEM_SECURITY) &&
5072 !security_token_has_privilege(get_current_nttok(conn),
5073 SEC_PRIV_SECURITY)) {
5074 DEBUG(10, ("create_file_unixpath: open on %s "
5075 "failed - SEC_FLAG_SYSTEM_SECURITY denied.\n",
5076 smb_fname_str_dbg(smb_fname)));
5077 status = NT_STATUS_PRIVILEGE_NOT_HELD;
5082 * Files or directories can't be opened DELETE_ON_CLOSE without
5084 * BUG: https://bugzilla.samba.org/show_bug.cgi?id=13358
5086 if (create_options & FILE_DELETE_ON_CLOSE) {
5087 if ((access_mask & DELETE_ACCESS) == 0) {
5088 status = NT_STATUS_INVALID_PARAMETER;
5093 if ((conn->fs_capabilities & FILE_NAMED_STREAMS)
5094 && is_ntfs_stream_smb_fname(smb_fname)
5095 && (!(private_flags & NTCREATEX_OPTIONS_PRIVATE_STREAM_DELETE))) {
5096 uint32_t base_create_disposition;
5097 struct smb_filename *smb_fname_base = NULL;
5098 uint32_t base_privflags;
5100 if (create_options & FILE_DIRECTORY_FILE) {
5101 status = NT_STATUS_NOT_A_DIRECTORY;
5105 switch (create_disposition) {
5107 base_create_disposition = FILE_OPEN;
5110 base_create_disposition = FILE_OPEN_IF;
5114 /* Create an smb_filename with stream_name == NULL. */
5115 smb_fname_base = synthetic_smb_fname(talloc_tos(),
5116 smb_fname->base_name,
5120 if (smb_fname_base == NULL) {
5121 status = NT_STATUS_NO_MEMORY;
5125 if (SMB_VFS_STAT(conn, smb_fname_base) == -1) {
5126 DEBUG(10, ("Unable to stat stream: %s\n",
5127 smb_fname_str_dbg(smb_fname_base)));
5130 * https://bugzilla.samba.org/show_bug.cgi?id=10229
5131 * We need to check if the requested access mask
5132 * could be used to open the underlying file (if
5133 * it existed), as we're passing in zero for the
5134 * access mask to the base filename.
5136 status = check_base_file_access(conn,
5140 if (!NT_STATUS_IS_OK(status)) {
5141 DEBUG(10, ("Permission check "
5142 "for base %s failed: "
5143 "%s\n", smb_fname->base_name,
5144 nt_errstr(status)));
5149 base_privflags = NTCREATEX_OPTIONS_PRIVATE_STREAM_BASEOPEN;
5151 /* Open the base file. */
5152 status = create_file_unixpath(conn, NULL, smb_fname_base, 0,
5155 | FILE_SHARE_DELETE,
5156 base_create_disposition,
5161 TALLOC_FREE(smb_fname_base);
5163 if (!NT_STATUS_IS_OK(status)) {
5164 DEBUG(10, ("create_file_unixpath for base %s failed: "
5165 "%s\n", smb_fname->base_name,
5166 nt_errstr(status)));
5169 /* we don't need the low level fd */
5174 * If it's a request for a directory open, deal with it separately.
5177 if (create_options & FILE_DIRECTORY_FILE) {
5179 if (create_options & FILE_NON_DIRECTORY_FILE) {
5180 status = NT_STATUS_INVALID_PARAMETER;
5184 /* Can't open a temp directory. IFS kit test. */
5185 if (!(file_attributes & FILE_FLAG_POSIX_SEMANTICS) &&
5186 (file_attributes & FILE_ATTRIBUTE_TEMPORARY)) {
5187 status = NT_STATUS_INVALID_PARAMETER;
5192 * We will get a create directory here if the Win32
5193 * app specified a security descriptor in the
5194 * CreateDirectory() call.
5198 status = open_directory(
5199 conn, req, smb_fname, access_mask, share_access,
5200 create_disposition, create_options, file_attributes,
5205 * Ordinary file case.
5208 status = file_new(req, conn, &fsp);
5209 if(!NT_STATUS_IS_OK(status)) {
5213 status = fsp_set_smb_fname(fsp, smb_fname);
5214 if (!NT_STATUS_IS_OK(status)) {
5220 * We're opening the stream element of a
5221 * base_fsp we already opened. Set up the
5224 fsp->base_fsp = base_fsp;
5227 if (allocation_size) {
5228 fsp->initial_allocation_size = smb_roundup(fsp->conn,
5232 status = open_file_ntcreate(conn,
5245 if(!NT_STATUS_IS_OK(status)) {
5246 file_free(req, fsp);
5250 if (NT_STATUS_EQUAL(status, NT_STATUS_FILE_IS_A_DIRECTORY)) {
5252 /* A stream open never opens a directory */
5255 status = NT_STATUS_FILE_IS_A_DIRECTORY;
5260 * Fail the open if it was explicitly a non-directory
5264 if (create_options & FILE_NON_DIRECTORY_FILE) {
5265 status = NT_STATUS_FILE_IS_A_DIRECTORY;
5270 status = open_directory(
5271 conn, req, smb_fname, access_mask,
5272 share_access, create_disposition,
5273 create_options, file_attributes,
5278 if (!NT_STATUS_IS_OK(status)) {
5282 fsp->base_fsp = base_fsp;
5284 if ((ea_list != NULL) &&
5285 ((info == FILE_WAS_CREATED) || (info == FILE_WAS_OVERWRITTEN))) {
5286 status = set_ea(conn, fsp, fsp->fsp_name, ea_list);
5287 if (!NT_STATUS_IS_OK(status)) {
5292 if (!fsp->is_directory && S_ISDIR(fsp->fsp_name->st.st_ex_mode)) {
5293 status = NT_STATUS_ACCESS_DENIED;
5297 /* Save the requested allocation size. */
5298 if ((info == FILE_WAS_CREATED) || (info == FILE_WAS_OVERWRITTEN)) {
5299 if ((allocation_size > (uint64_t)fsp->fsp_name->st.st_ex_size)
5300 && !(fsp->is_directory))
5302 fsp->initial_allocation_size = smb_roundup(
5303 fsp->conn, allocation_size);
5304 if (vfs_allocate_file_space(
5305 fsp, fsp->initial_allocation_size) == -1) {
5306 status = NT_STATUS_DISK_FULL;
5310 fsp->initial_allocation_size = smb_roundup(
5311 fsp->conn, (uint64_t)fsp->fsp_name->st.st_ex_size);
5314 fsp->initial_allocation_size = 0;
5317 if ((info == FILE_WAS_CREATED) && lp_nt_acl_support(SNUM(conn)) &&
5318 fsp->base_fsp == NULL) {
5321 * According to the MS documentation, the only time the security
5322 * descriptor is applied to the opened file is iff we *created* the
5323 * file; an existing file stays the same.
5325 * Also, it seems (from observation) that you can open the file with
5326 * any access mask but you can still write the sd. We need to override
5327 * the granted access before we call set_sd
5328 * Patch for bug #2242 from Tom Lackemann <cessnatomny@yahoo.com>.
5331 uint32_t sec_info_sent;
5332 uint32_t saved_access_mask = fsp->access_mask;
5334 sec_info_sent = get_sec_info(sd);
5336 fsp->access_mask = FILE_GENERIC_ALL;
5338 if (sec_info_sent & (SECINFO_OWNER|
5342 status = set_sd(fsp, sd, sec_info_sent);
5345 fsp->access_mask = saved_access_mask;
5347 if (!NT_STATUS_IS_OK(status)) {
5350 } else if (lp_inherit_acls(SNUM(conn))) {
5351 /* Inherit from parent. Errors here are not fatal. */
5352 status = inherit_new_acl(fsp);
5353 if (!NT_STATUS_IS_OK(status)) {
5354 DEBUG(10,("inherit_new_acl: failed for %s with %s\n",
5356 nt_errstr(status) ));
5361 if ((conn->fs_capabilities & FILE_FILE_COMPRESSION)
5362 && (create_options & FILE_NO_COMPRESSION)
5363 && (info == FILE_WAS_CREATED)) {
5364 status = SMB_VFS_SET_COMPRESSION(conn, fsp, fsp,
5365 COMPRESSION_FORMAT_NONE);
5366 if (!NT_STATUS_IS_OK(status)) {
5367 DEBUG(1, ("failed to disable compression: %s\n",
5368 nt_errstr(status)));
5372 DEBUG(10, ("create_file_unixpath: info=%d\n", info));
5375 if (pinfo != NULL) {
5379 smb_fname->st = fsp->fsp_name->st;
5381 return NT_STATUS_OK;
5384 DEBUG(10, ("create_file_unixpath: %s\n", nt_errstr(status)));
5387 if (base_fsp && fsp->base_fsp == base_fsp) {
5389 * The close_file below will close
5394 close_file(req, fsp, ERROR_CLOSE);
5397 if (base_fsp != NULL) {
5398 close_file(req, base_fsp, ERROR_CLOSE);
5405 * Calculate the full path name given a relative fid.
5407 static NTSTATUS get_relative_fid_filename(
5408 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,
5515 if (!NT_STATUS_IS_OK(status)) {
5520 TALLOC_FREE(parent_fname);
5521 TALLOC_FREE(new_base_name);
5525 NTSTATUS create_file_default(connection_struct *conn,
5526 struct smb_request *req,
5527 uint16_t root_dir_fid,
5528 struct smb_filename *smb_fname,
5529 uint32_t access_mask,
5530 uint32_t share_access,
5531 uint32_t create_disposition,
5532 uint32_t create_options,
5533 uint32_t file_attributes,
5534 uint32_t oplock_request,
5535 const struct smb2_lease *lease,
5536 uint64_t allocation_size,
5537 uint32_t private_flags,
5538 struct security_descriptor *sd,
5539 struct ea_list *ea_list,
5540 files_struct **result,
5542 const struct smb2_create_blobs *in_context_blobs,
5543 struct smb2_create_blobs *out_context_blobs)
5545 int info = FILE_WAS_OPENED;
5546 files_struct *fsp = NULL;
5548 bool stream_name = false;
5550 DBG_DEBUG("create_file: access_mask = 0x%x "
5551 "file_attributes = 0x%x, share_access = 0x%x, "
5552 "create_disposition = 0x%x create_options = 0x%x "
5553 "oplock_request = 0x%x "
5554 "private_flags = 0x%x "
5555 "root_dir_fid = 0x%x, ea_list = %p, sd = %p, "
5557 (unsigned int)access_mask,
5558 (unsigned int)file_attributes,
5559 (unsigned int)share_access,
5560 (unsigned int)create_disposition,
5561 (unsigned int)create_options,
5562 (unsigned int)oplock_request,
5563 (unsigned int)private_flags,
5564 (unsigned int)root_dir_fid,
5565 ea_list, sd, smb_fname_str_dbg(smb_fname));
5569 * Remember the absolute time of the original request
5570 * with this mid. We'll use it later to see if this
5573 get_deferred_open_message_state(req, &req->request_time, NULL);
5577 * Calculate the filename from the root_dir_if if necessary.
5580 if (root_dir_fid != 0) {
5581 struct smb_filename *smb_fname_out = NULL;
5582 status = get_relative_fid_filename(conn, req, root_dir_fid,
5583 smb_fname, &smb_fname_out);
5584 if (!NT_STATUS_IS_OK(status)) {
5587 smb_fname = smb_fname_out;
5591 * Check to see if this is a mac fork of some kind.
5594 stream_name = is_ntfs_stream_smb_fname(smb_fname);
5596 enum FAKE_FILE_TYPE fake_file_type;
5598 fake_file_type = is_fake_file(smb_fname);
5600 if (fake_file_type != FAKE_FILE_TYPE_NONE) {
5603 * Here we go! support for changing the disk quotas
5606 * We need to fake up to open this MAGIC QUOTA file
5607 * and return a valid FID.
5609 * w2k close this file directly after openening xp
5610 * also tries a QUERY_FILE_INFO on the file and then
5613 status = open_fake_file(req, conn, req->vuid,
5614 fake_file_type, smb_fname,
5616 if (!NT_STATUS_IS_OK(status)) {
5620 ZERO_STRUCT(smb_fname->st);
5624 if (!(conn->fs_capabilities & FILE_NAMED_STREAMS)) {
5625 status = NT_STATUS_OBJECT_NAME_NOT_FOUND;
5630 if (is_ntfs_default_stream_smb_fname(smb_fname)) {
5632 smb_fname->stream_name = NULL;
5633 /* We have to handle this error here. */
5634 if (create_options & FILE_DIRECTORY_FILE) {
5635 status = NT_STATUS_NOT_A_DIRECTORY;
5638 if (req != NULL && req->posix_pathnames) {
5639 ret = SMB_VFS_LSTAT(conn, smb_fname);
5641 ret = SMB_VFS_STAT(conn, smb_fname);
5644 if (ret == 0 && VALID_STAT_OF_DIR(smb_fname->st)) {
5645 status = NT_STATUS_FILE_IS_A_DIRECTORY;
5650 status = create_file_unixpath(
5651 conn, req, smb_fname, access_mask, share_access,
5652 create_disposition, create_options, file_attributes,
5653 oplock_request, lease, allocation_size, private_flags,
5657 if (!NT_STATUS_IS_OK(status)) {
5662 DEBUG(10, ("create_file: info=%d\n", info));
5665 if (pinfo != NULL) {
5668 return NT_STATUS_OK;
5671 DEBUG(10, ("create_file: %s\n", nt_errstr(status)));
5674 close_file(req, fsp, ERROR_CLOSE);