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 DEBUG(10,("share_conflict: entry->access_mask = 0x%x, "
1465 "entry->share_access = 0x%x, "
1466 "entry->private_options = 0x%x\n",
1467 (unsigned int)entry->access_mask,
1468 (unsigned int)entry->share_access,
1469 (unsigned int)entry->private_options));
1471 if (server_id_is_disconnected(&entry->pid)) {
1475 DEBUG(10,("share_conflict: access_mask = 0x%x, share_access = 0x%x\n",
1476 (unsigned int)access_mask, (unsigned int)share_access));
1478 if ((entry->access_mask & (FILE_WRITE_DATA|
1482 DELETE_ACCESS)) == 0) {
1483 DEBUG(10,("share_conflict: No conflict due to "
1484 "entry->access_mask = 0x%x\n",
1485 (unsigned int)entry->access_mask ));
1489 if ((access_mask & (FILE_WRITE_DATA|
1493 DELETE_ACCESS)) == 0) {
1494 DEBUG(10,("share_conflict: No conflict due to "
1495 "access_mask = 0x%x\n",
1496 (unsigned int)access_mask ));
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 /* Now we check the share modes, after any oplock breaks. */
1659 for(i = 0; i < lck->data->num_share_modes; i++) {
1661 if (!is_valid_share_mode_entry(&lck->data->share_modes[i])) {
1665 /* someone else has a share lock on it, check to see if we can
1667 if (share_conflict(&lck->data->share_modes[i],
1668 access_mask, share_access)) {
1670 if (share_mode_stale_pid(lck->data, i)) {
1674 return NT_STATUS_SHARING_VIOLATION;
1678 return NT_STATUS_OK;
1682 * Send a break message to the oplock holder and delay the open for
1686 NTSTATUS send_break_message(struct messaging_context *msg_ctx,
1687 const struct file_id *id,
1688 const struct share_mode_entry *exclusive,
1691 struct oplock_break_message msg = {
1693 .share_file_id = exclusive->share_file_id,
1694 .break_to = break_to,
1696 enum ndr_err_code ndr_err;
1701 struct server_id_buf buf;
1702 DBG_DEBUG("Sending break message to %s\n",
1703 server_id_str_buf(exclusive->pid, &buf));
1704 NDR_PRINT_DEBUG(oplock_break_message, &msg);
1707 ndr_err = ndr_push_struct_blob(
1711 (ndr_push_flags_fn_t)ndr_push_oplock_break_message);
1712 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
1713 DBG_WARNING("ndr_push_oplock_break_message failed: %s\n",
1714 ndr_errstr(ndr_err));
1715 return ndr_map_error2ntstatus(ndr_err);
1718 status = messaging_send(
1719 msg_ctx, exclusive->pid, MSG_SMB_BREAK_REQUEST, &blob);
1720 TALLOC_FREE(blob.data);
1721 if (!NT_STATUS_IS_OK(status)) {
1722 DEBUG(3, ("Could not send oplock break message: %s\n",
1723 nt_errstr(status)));
1730 * Do internal consistency checks on the share mode for a file.
1733 static bool validate_oplock_types(struct share_mode_lock *lck)
1735 struct share_mode_data *d = lck->data;
1737 bool ex_or_batch = false;
1738 bool level2 = false;
1739 bool no_oplock = false;
1740 uint32_t num_non_stat_opens = 0;
1743 for (i=0; i<d->num_share_modes; i++) {
1744 struct share_mode_entry *e = &d->share_modes[i];
1746 if (!is_valid_share_mode_entry(e)) {
1750 if (e->op_mid == 0) {
1751 /* INTERNAL_OPEN_ONLY */
1755 if (e->op_type == NO_OPLOCK && is_stat_open(e->access_mask)) {
1756 /* We ignore stat opens in the table - they
1757 always have NO_OPLOCK and never get or
1758 cause breaks. JRA. */
1762 num_non_stat_opens += 1;
1764 if (BATCH_OPLOCK_TYPE(e->op_type)) {
1765 /* batch - can only be one. */
1766 if (share_mode_stale_pid(d, i)) {
1767 DEBUG(10, ("Found stale batch oplock\n"));
1770 if (ex_or_batch || batch || level2 || no_oplock) {
1771 DEBUG(0, ("Bad batch oplock entry %u.",
1778 if (EXCLUSIVE_OPLOCK_TYPE(e->op_type)) {
1779 if (share_mode_stale_pid(d, i)) {
1780 DEBUG(10, ("Found stale duplicate oplock\n"));
1783 /* Exclusive or batch - can only be one. */
1784 if (ex_or_batch || level2 || no_oplock) {
1785 DEBUG(0, ("Bad exclusive or batch oplock "
1786 "entry %u.", (unsigned)i));
1792 if (LEVEL_II_OPLOCK_TYPE(e->op_type)) {
1793 if (batch || ex_or_batch) {
1794 if (share_mode_stale_pid(d, i)) {
1795 DEBUG(10, ("Found stale LevelII "
1799 DEBUG(0, ("Bad levelII oplock entry %u.",
1806 if (e->op_type == NO_OPLOCK) {
1807 if (batch || ex_or_batch) {
1808 if (share_mode_stale_pid(d, i)) {
1809 DEBUG(10, ("Found stale NO_OPLOCK "
1813 DEBUG(0, ("Bad no oplock entry %u.",
1821 remove_stale_share_mode_entries(d);
1823 if ((batch || ex_or_batch) && (num_non_stat_opens != 1)) {
1824 DEBUG(1, ("got batch (%d) or ex (%d) non-exclusively (%d)\n",
1825 (int)batch, (int)ex_or_batch,
1826 (int)d->num_share_modes));
1833 static bool delay_for_oplock(files_struct *fsp,
1835 const struct smb2_lease *lease,
1836 struct share_mode_lock *lck,
1837 bool have_sharing_violation,
1838 uint32_t create_disposition,
1839 bool first_open_attempt)
1841 struct share_mode_data *d = lck->data;
1844 bool will_overwrite;
1845 const uint32_t delay_mask = have_sharing_violation ?
1846 SMB2_LEASE_HANDLE : SMB2_LEASE_WRITE;
1848 if ((oplock_request & INTERNAL_OPEN_ONLY) ||
1849 is_stat_open(fsp->access_mask)) {
1853 switch (create_disposition) {
1854 case FILE_SUPERSEDE:
1855 case FILE_OVERWRITE:
1856 case FILE_OVERWRITE_IF:
1857 will_overwrite = true;
1860 will_overwrite = false;
1864 for (i=0; i<d->num_share_modes; i++) {
1865 struct share_mode_entry *e = &d->share_modes[i];
1866 bool e_is_lease = (e->op_type == LEASE_OPLOCK);
1867 uint32_t e_lease_type = get_lease_type(d, e);
1869 bool lease_is_breaking = false;
1874 if (lease != NULL) {
1875 bool our_lease = smb2_lease_equal(
1876 fsp_client_guid(fsp),
1881 DBG_DEBUG("Ignoring our own lease\n");
1886 status = leases_db_get(
1890 NULL, /* current_state */
1892 NULL, /* breaking_to_requested */
1893 NULL, /* breaking_to_required */
1894 NULL, /* lease_version */
1896 SMB_ASSERT(NT_STATUS_IS_OK(status));
1899 break_to = e_lease_type & ~delay_mask;
1901 if (will_overwrite) {
1902 break_to &= ~(SMB2_LEASE_HANDLE|SMB2_LEASE_READ);
1905 DEBUG(10, ("entry %u: e_lease_type %u, will_overwrite: %u\n",
1906 (unsigned)i, (unsigned)e_lease_type,
1907 (unsigned)will_overwrite));
1909 if ((e_lease_type & ~break_to) == 0) {
1910 if (lease_is_breaking) {
1916 if (share_mode_stale_pid(d, i)) {
1920 if (will_overwrite) {
1922 * If we break anyway break to NONE directly.
1923 * Otherwise vfs_set_filelen() will trigger the
1926 break_to &= ~(SMB2_LEASE_READ|SMB2_LEASE_WRITE);
1931 * Oplocks only support breaking to R or NONE.
1933 break_to &= ~(SMB2_LEASE_HANDLE|SMB2_LEASE_WRITE);
1936 DEBUG(10, ("breaking from %d to %d\n",
1937 (int)e_lease_type, (int)break_to));
1938 send_break_message(fsp->conn->sconn->msg_ctx, &fsp->file_id,
1940 if (e_lease_type & delay_mask) {
1943 if (lease_is_breaking && !first_open_attempt) {
1951 static bool file_has_brlocks(files_struct *fsp)
1953 struct byte_range_lock *br_lck;
1955 br_lck = brl_get_locks_readonly(fsp);
1959 return (brl_num_locks(br_lck) > 0);
1962 struct fsp_lease *find_fsp_lease(struct files_struct *new_fsp,
1963 const struct smb2_lease_key *key,
1964 uint32_t current_state,
1965 uint16_t lease_version,
1966 uint16_t lease_epoch)
1968 struct files_struct *fsp;
1971 * TODO: Measure how expensive this loop is with thousands of open
1975 for (fsp = file_find_di_first(new_fsp->conn->sconn, new_fsp->file_id);
1977 fsp = file_find_di_next(fsp)) {
1979 if (fsp == new_fsp) {
1982 if (fsp->oplock_type != LEASE_OPLOCK) {
1985 if (smb2_lease_key_equal(&fsp->lease->lease.lease_key, key)) {
1986 fsp->lease->ref_count += 1;
1991 /* Not found - must be leased in another smbd. */
1992 new_fsp->lease = talloc_zero(new_fsp->conn->sconn, struct fsp_lease);
1993 if (new_fsp->lease == NULL) {
1996 new_fsp->lease->ref_count = 1;
1997 new_fsp->lease->sconn = new_fsp->conn->sconn;
1998 new_fsp->lease->lease.lease_key = *key;
1999 new_fsp->lease->lease.lease_state = current_state;
2001 * We internally treat all leases as V2 and update
2002 * the epoch, but when sending breaks it matters if
2003 * the requesting lease was v1 or v2.
2005 new_fsp->lease->lease.lease_version = lease_version;
2006 new_fsp->lease->lease.lease_epoch = lease_epoch;
2007 return new_fsp->lease;
2010 static NTSTATUS try_lease_upgrade(struct files_struct *fsp,
2011 struct share_mode_lock *lck,
2012 const struct GUID *client_guid,
2013 const struct smb2_lease *lease,
2017 uint32_t current_state, breaking_to_requested, breaking_to_required;
2019 uint16_t lease_version, epoch;
2020 uint32_t existing, requested;
2023 status = leases_db_get(
2029 &breaking_to_requested,
2030 &breaking_to_required,
2033 if (!NT_STATUS_IS_OK(status)) {
2037 fsp->lease = find_fsp_lease(
2043 if (fsp->lease == NULL) {
2044 DEBUG(1, ("Did not find existing lease for file %s\n",
2046 return NT_STATUS_NO_MEMORY;
2050 * Upgrade only if the requested lease is a strict upgrade.
2052 existing = current_state;
2053 requested = lease->lease_state;
2056 * Tricky: This test makes sure that "requested" is a
2057 * strict bitwise superset of "existing".
2059 do_upgrade = ((existing & requested) == existing);
2062 * Upgrade only if there's a change.
2064 do_upgrade &= (granted != existing);
2067 * Upgrade only if other leases don't prevent what was asked
2070 do_upgrade &= (granted == requested);
2073 * only upgrade if we are not in breaking state
2075 do_upgrade &= !breaking;
2077 DEBUG(10, ("existing=%"PRIu32", requested=%"PRIu32", "
2078 "granted=%"PRIu32", do_upgrade=%d\n",
2079 existing, requested, granted, (int)do_upgrade));
2082 NTSTATUS set_status;
2084 current_state = granted;
2087 set_status = leases_db_set(
2092 breaking_to_requested,
2093 breaking_to_required,
2097 if (!NT_STATUS_IS_OK(set_status)) {
2098 DBG_DEBUG("leases_db_set failed: %s\n",
2099 nt_errstr(set_status));
2104 fsp_lease_update(fsp);
2106 return NT_STATUS_OK;
2109 static NTSTATUS grant_new_fsp_lease(struct files_struct *fsp,
2110 struct share_mode_lock *lck,
2111 const struct GUID *client_guid,
2112 const struct smb2_lease *lease,
2115 struct share_mode_data *d = lck->data;
2118 fsp->lease = talloc_zero(fsp->conn->sconn, struct fsp_lease);
2119 if (fsp->lease == NULL) {
2120 return NT_STATUS_INSUFFICIENT_RESOURCES;
2122 fsp->lease->ref_count = 1;
2123 fsp->lease->sconn = fsp->conn->sconn;
2124 fsp->lease->lease.lease_version = lease->lease_version;
2125 fsp->lease->lease.lease_key = lease->lease_key;
2126 fsp->lease->lease.lease_state = granted;
2127 fsp->lease->lease.lease_epoch = lease->lease_epoch + 1;
2129 status = leases_db_add(client_guid,
2132 fsp->lease->lease.lease_state,
2133 fsp->lease->lease.lease_version,
2134 fsp->lease->lease.lease_epoch,
2135 fsp->conn->connectpath,
2136 fsp->fsp_name->base_name,
2137 fsp->fsp_name->stream_name);
2138 if (!NT_STATUS_IS_OK(status)) {
2139 DEBUG(10, ("%s: leases_db_add failed: %s\n", __func__,
2140 nt_errstr(status)));
2141 TALLOC_FREE(fsp->lease);
2142 return NT_STATUS_INSUFFICIENT_RESOURCES;
2147 return NT_STATUS_OK;
2150 static NTSTATUS grant_fsp_lease(struct files_struct *fsp,
2151 struct share_mode_lock *lck,
2152 const struct smb2_lease *lease,
2155 const struct GUID *client_guid = fsp_client_guid(fsp);
2158 status = try_lease_upgrade(fsp, lck, client_guid, lease, granted);
2160 if (NT_STATUS_EQUAL(status, NT_STATUS_NOT_FOUND)) {
2161 status = grant_new_fsp_lease(
2162 fsp, lck, client_guid, lease, granted);
2168 static bool is_same_lease(const files_struct *fsp,
2169 const struct share_mode_data *d,
2170 const struct share_mode_entry *e,
2171 const struct smb2_lease *lease)
2173 if (e->op_type != LEASE_OPLOCK) {
2176 if (lease == NULL) {
2180 return smb2_lease_equal(fsp_client_guid(fsp),
2186 static int map_lease_type_to_oplock(uint32_t lease_type)
2188 int result = NO_OPLOCK;
2190 switch (lease_type) {
2191 case SMB2_LEASE_READ|SMB2_LEASE_WRITE|SMB2_LEASE_HANDLE:
2192 result = BATCH_OPLOCK|EXCLUSIVE_OPLOCK;
2194 case SMB2_LEASE_READ|SMB2_LEASE_WRITE:
2195 result = EXCLUSIVE_OPLOCK;
2197 case SMB2_LEASE_READ|SMB2_LEASE_HANDLE:
2198 case SMB2_LEASE_READ:
2199 result = LEVEL_II_OPLOCK;
2206 static NTSTATUS grant_fsp_oplock_type(struct smb_request *req,
2207 struct files_struct *fsp,
2208 struct share_mode_lock *lck,
2210 const struct smb2_lease *lease,
2211 uint32_t share_access,
2212 uint32_t access_mask)
2214 struct share_mode_data *d = lck->data;
2215 bool got_handle_lease = false;
2216 bool got_oplock = false;
2222 if (oplock_request & INTERNAL_OPEN_ONLY) {
2223 /* No oplocks on internal open. */
2224 oplock_request = NO_OPLOCK;
2225 DEBUG(10,("grant_fsp_oplock_type: oplock type 0x%x on file %s\n",
2226 fsp->oplock_type, fsp_str_dbg(fsp)));
2229 if (oplock_request == LEASE_OPLOCK) {
2230 if (lease == NULL) {
2232 * The SMB2 layer should have checked this
2234 return NT_STATUS_INTERNAL_ERROR;
2237 granted = lease->lease_state;
2239 if (lp_kernel_oplocks(SNUM(fsp->conn))) {
2240 DEBUG(10, ("No lease granted because kernel oplocks are enabled\n"));
2241 granted = SMB2_LEASE_NONE;
2243 if ((granted & (SMB2_LEASE_READ|SMB2_LEASE_WRITE)) == 0) {
2244 DEBUG(10, ("No read or write lease requested\n"));
2245 granted = SMB2_LEASE_NONE;
2247 if (granted == SMB2_LEASE_WRITE) {
2248 DEBUG(10, ("pure write lease requested\n"));
2249 granted = SMB2_LEASE_NONE;
2251 if (granted == (SMB2_LEASE_WRITE|SMB2_LEASE_HANDLE)) {
2252 DEBUG(10, ("write and handle lease requested\n"));
2253 granted = SMB2_LEASE_NONE;
2256 granted = map_oplock_to_lease_type(
2257 oplock_request & ~SAMBA_PRIVATE_OPLOCK_MASK);
2260 if (lp_locking(fsp->conn->params) && file_has_brlocks(fsp)) {
2261 DEBUG(10,("grant_fsp_oplock_type: file %s has byte range locks\n",
2263 granted &= ~SMB2_LEASE_READ;
2266 for (i=0; i<d->num_share_modes; i++) {
2267 struct share_mode_entry *e = &d->share_modes[i];
2268 uint32_t e_lease_type;
2270 e_lease_type = get_lease_type(d, e);
2272 if ((granted & SMB2_LEASE_WRITE) &&
2273 !is_same_lease(fsp, d, e, lease) &&
2274 !share_mode_stale_pid(d, i)) {
2276 * Can grant only one writer
2278 granted &= ~SMB2_LEASE_WRITE;
2281 if ((e_lease_type & SMB2_LEASE_HANDLE) && !got_handle_lease &&
2282 !share_mode_stale_pid(d, i)) {
2283 got_handle_lease = true;
2286 if ((e->op_type != LEASE_OPLOCK) && !got_oplock &&
2287 !share_mode_stale_pid(d, i)) {
2292 if ((granted & SMB2_LEASE_READ) && !(granted & SMB2_LEASE_WRITE)) {
2294 (global_client_caps & CAP_LEVEL_II_OPLOCKS) &&
2295 lp_level2_oplocks(SNUM(fsp->conn));
2297 if (!allow_level2) {
2298 granted = SMB2_LEASE_NONE;
2302 if (oplock_request == LEASE_OPLOCK) {
2304 granted &= ~SMB2_LEASE_HANDLE;
2307 fsp->oplock_type = LEASE_OPLOCK;
2309 status = grant_fsp_lease(fsp, lck, lease, granted);
2310 if (!NT_STATUS_IS_OK(status)) {
2315 DBG_DEBUG("lease_state=%d\n", fsp->lease->lease.lease_state);
2317 if (got_handle_lease) {
2318 granted = SMB2_LEASE_NONE;
2321 fsp->oplock_type = map_lease_type_to_oplock(granted);
2323 status = set_file_oplock(fsp);
2324 if (!NT_STATUS_IS_OK(status)) {
2326 * Could not get the kernel oplock
2328 fsp->oplock_type = NO_OPLOCK;
2332 ok = set_share_mode(
2335 get_current_uid(fsp->conn),
2341 if (fsp->oplock_type == LEASE_OPLOCK) {
2342 status = remove_lease_if_stale(
2344 fsp_client_guid(fsp),
2345 &fsp->lease->lease.lease_key);
2346 if (!NT_STATUS_IS_OK(status)) {
2347 DBG_WARNING("remove_lease_if_stale "
2352 return NT_STATUS_NO_MEMORY;
2355 if (granted & SMB2_LEASE_READ) {
2356 lck->data->flags |= SHARE_MODE_HAS_READ_LEASE;
2359 DEBUG(10,("grant_fsp_oplock_type: oplock type 0x%x on file %s\n",
2360 fsp->oplock_type, fsp_str_dbg(fsp)));
2362 return NT_STATUS_OK;
2365 static bool request_timed_out(struct smb_request *req, struct timeval timeout)
2367 struct timeval now, end_time;
2369 end_time = timeval_sum(&req->request_time, &timeout);
2370 return (timeval_compare(&end_time, &now) < 0);
2373 struct defer_open_state {
2374 struct smbXsrv_connection *xconn;
2378 static void defer_open_done(struct tevent_req *req);
2381 * Defer an open and watch a locking.tdb record
2383 * This defers an open that gets rescheduled once the locking.tdb record watch
2384 * is triggered by a change to the record.
2386 * It is used to defer opens that triggered an oplock break and for the SMB1
2387 * sharing violation delay.
2389 static void defer_open(struct share_mode_lock *lck,
2390 struct timeval timeout,
2391 struct smb_request *req,
2392 bool delayed_for_oplocks,
2395 struct deferred_open_record *open_rec = NULL;
2396 struct timeval abs_timeout;
2397 struct defer_open_state *watch_state;
2398 struct tevent_req *watch_req;
2399 struct timeval_buf tvbuf1, tvbuf2;
2402 abs_timeout = timeval_sum(&req->request_time, &timeout);
2404 DBG_DEBUG("request time [%s] timeout [%s] mid [%" PRIu64 "] "
2405 "delayed_for_oplocks [%s] file_id [%s]\n",
2406 timeval_str_buf(&req->request_time, false, true, &tvbuf1),
2407 timeval_str_buf(&abs_timeout, false, true, &tvbuf2),
2409 delayed_for_oplocks ? "yes" : "no",
2410 file_id_string_tos(&id));
2412 open_rec = talloc_zero(NULL, struct deferred_open_record);
2413 if (open_rec == NULL) {
2415 exit_server("talloc failed");
2418 watch_state = talloc(open_rec, struct defer_open_state);
2419 if (watch_state == NULL) {
2420 exit_server("talloc failed");
2422 watch_state->xconn = req->xconn;
2423 watch_state->mid = req->mid;
2425 DBG_DEBUG("defering mid %" PRIu64 "\n", req->mid);
2427 watch_req = dbwrap_watched_watch_send(watch_state,
2430 (struct server_id){0});
2431 if (watch_req == NULL) {
2432 exit_server("Could not watch share mode record");
2434 tevent_req_set_callback(watch_req, defer_open_done, watch_state);
2436 ok = tevent_req_set_endtime(watch_req, req->sconn->ev_ctx, abs_timeout);
2438 exit_server("tevent_req_set_endtime failed");
2441 ok = push_deferred_open_message_smb(req, timeout, id, open_rec);
2444 exit_server("push_deferred_open_message_smb failed");
2448 static void defer_open_done(struct tevent_req *req)
2450 struct defer_open_state *state = tevent_req_callback_data(
2451 req, struct defer_open_state);
2455 status = dbwrap_watched_watch_recv(req, NULL, NULL);
2457 if (!NT_STATUS_IS_OK(status)) {
2458 DEBUG(5, ("dbwrap_watched_watch_recv returned %s\n",
2459 nt_errstr(status)));
2461 * Even if it failed, retry anyway. TODO: We need a way to
2462 * tell a re-scheduled open about that error.
2466 DEBUG(10, ("scheduling mid %llu\n", (unsigned long long)state->mid));
2468 ret = schedule_deferred_open_message_smb(state->xconn, state->mid);
2474 * Actually attempt the kernel oplock polling open.
2477 static void poll_open_fn(struct tevent_context *ev,
2478 struct tevent_timer *te,
2479 struct timeval current_time,
2482 struct deferred_open_record *open_rec = talloc_get_type_abort(
2483 private_data, struct deferred_open_record);
2486 ok = schedule_deferred_open_message_smb(
2487 open_rec->xconn, open_rec->mid);
2489 exit_server("schedule_deferred_open_message_smb failed");
2491 DBG_DEBUG("timer fired. Retrying open !\n");
2495 * Reschedule an open for 1 second from now, if not timed out.
2497 static bool setup_poll_open(
2498 struct smb_request *req,
2500 struct timeval max_timeout,
2501 struct timeval interval)
2505 struct deferred_open_record *open_rec = NULL;
2506 struct timeval endtime, next_interval;
2508 if (request_timed_out(req, max_timeout)) {
2512 open_rec = talloc_zero(NULL, struct deferred_open_record);
2513 if (open_rec == NULL) {
2514 DBG_WARNING("talloc failed\n");
2517 open_rec->xconn = req->xconn;
2518 open_rec->mid = req->mid;
2521 * Make sure open_rec->te does not come later than the
2522 * request's maximum endtime.
2525 endtime = timeval_sum(&req->request_time, &max_timeout);
2526 next_interval = timeval_current_ofs(interval.tv_sec, interval.tv_usec);
2527 next_interval = timeval_min(&endtime, &next_interval);
2529 open_rec->te = tevent_add_timer(
2535 if (open_rec->te == NULL) {
2536 DBG_WARNING("tevent_add_timer failed\n");
2537 TALLOC_FREE(open_rec);
2541 ok = push_deferred_open_message_smb(req, max_timeout, id, open_rec);
2543 DBG_WARNING("push_deferred_open_message_smb failed\n");
2544 TALLOC_FREE(open_rec);
2548 DBG_DEBUG("poll request time [%s] mid [%" PRIu64 "] file_id [%s]\n",
2549 timeval_string(talloc_tos(), &req->request_time, false),
2551 file_id_string_tos(&id));
2556 bool defer_smb1_sharing_violation(struct smb_request *req)
2561 if (!lp_defer_sharing_violations()) {
2566 * Try every 200msec up to (by default) one second. To be
2567 * precise, according to behaviour note <247> in [MS-CIFS],
2568 * the server tries 5 times. But up to one second should be
2572 timeout_usecs = lp_parm_int(
2576 SHARING_VIOLATION_USEC_WAIT);
2578 ok = setup_poll_open(
2580 (struct file_id) {0},
2581 (struct timeval) { .tv_usec = timeout_usecs },
2582 (struct timeval) { .tv_usec = 200000 });
2586 /****************************************************************************
2587 On overwrite open ensure that the attributes match.
2588 ****************************************************************************/
2590 static bool open_match_attributes(connection_struct *conn,
2591 uint32_t old_dos_attr,
2592 uint32_t new_dos_attr,
2593 mode_t new_unx_mode,
2594 mode_t *returned_unx_mode)
2596 uint32_t noarch_old_dos_attr, noarch_new_dos_attr;
2598 noarch_old_dos_attr = (old_dos_attr & ~FILE_ATTRIBUTE_ARCHIVE);
2599 noarch_new_dos_attr = (new_dos_attr & ~FILE_ATTRIBUTE_ARCHIVE);
2601 if((noarch_old_dos_attr == 0 && noarch_new_dos_attr != 0) ||
2602 (noarch_old_dos_attr != 0 && ((noarch_old_dos_attr & noarch_new_dos_attr) == noarch_old_dos_attr))) {
2603 *returned_unx_mode = new_unx_mode;
2605 *returned_unx_mode = (mode_t)0;
2608 DEBUG(10,("open_match_attributes: old_dos_attr = 0x%x, "
2609 "new_dos_attr = 0x%x "
2610 "returned_unx_mode = 0%o\n",
2611 (unsigned int)old_dos_attr,
2612 (unsigned int)new_dos_attr,
2613 (unsigned int)*returned_unx_mode ));
2615 /* If we're mapping SYSTEM and HIDDEN ensure they match. */
2616 if (lp_map_system(SNUM(conn)) || lp_store_dos_attributes(SNUM(conn))) {
2617 if ((old_dos_attr & FILE_ATTRIBUTE_SYSTEM) &&
2618 !(new_dos_attr & FILE_ATTRIBUTE_SYSTEM)) {
2622 if (lp_map_hidden(SNUM(conn)) || lp_store_dos_attributes(SNUM(conn))) {
2623 if ((old_dos_attr & FILE_ATTRIBUTE_HIDDEN) &&
2624 !(new_dos_attr & FILE_ATTRIBUTE_HIDDEN)) {
2631 static void schedule_defer_open(struct share_mode_lock *lck,
2633 struct smb_request *req)
2635 /* This is a relative time, added to the absolute
2636 request_time value to get the absolute timeout time.
2637 Note that if this is the second or greater time we enter
2638 this codepath for this particular request mid then
2639 request_time is left as the absolute time of the *first*
2640 time this request mid was processed. This is what allows
2641 the request to eventually time out. */
2643 struct timeval timeout;
2645 /* Normally the smbd we asked should respond within
2646 * OPLOCK_BREAK_TIMEOUT seconds regardless of whether
2647 * the client did, give twice the timeout as a safety
2648 * measure here in case the other smbd is stuck
2649 * somewhere else. */
2651 timeout = timeval_set(OPLOCK_BREAK_TIMEOUT*2, 0);
2653 if (request_timed_out(req, timeout)) {
2657 defer_open(lck, timeout, req, true, id);
2660 /****************************************************************************
2661 Reschedule an open call that went asynchronous.
2662 ****************************************************************************/
2664 static void schedule_async_open_timer(struct tevent_context *ev,
2665 struct tevent_timer *te,
2666 struct timeval current_time,
2669 exit_server("async open timeout");
2672 static void schedule_async_open(struct smb_request *req)
2674 struct deferred_open_record *open_rec = NULL;
2675 struct timeval timeout = timeval_set(20, 0);
2678 if (request_timed_out(req, timeout)) {
2682 open_rec = talloc_zero(NULL, struct deferred_open_record);
2683 if (open_rec == NULL) {
2684 exit_server("deferred_open_record_create failed");
2686 open_rec->async_open = true;
2688 ok = push_deferred_open_message_smb(
2689 req, timeout, (struct file_id){0}, open_rec);
2691 exit_server("push_deferred_open_message_smb failed");
2694 open_rec->te = tevent_add_timer(req->sconn->ev_ctx,
2696 timeval_current_ofs(20, 0),
2697 schedule_async_open_timer,
2699 if (open_rec->te == NULL) {
2700 exit_server("tevent_add_timer failed");
2704 /****************************************************************************
2705 Work out what access_mask to use from what the client sent us.
2706 ****************************************************************************/
2708 static NTSTATUS smbd_calculate_maximum_allowed_access(
2709 connection_struct *conn,
2710 const struct smb_filename *smb_fname,
2712 uint32_t *p_access_mask)
2714 struct security_descriptor *sd;
2715 uint32_t access_granted;
2718 if (!use_privs && (get_current_uid(conn) == (uid_t)0)) {
2719 *p_access_mask |= FILE_GENERIC_ALL;
2720 return NT_STATUS_OK;
2723 status = SMB_VFS_GET_NT_ACL(conn, smb_fname,
2729 if (NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
2731 * File did not exist
2733 *p_access_mask = FILE_GENERIC_ALL;
2734 return NT_STATUS_OK;
2736 if (!NT_STATUS_IS_OK(status)) {
2737 DEBUG(10,("Could not get acl on file %s: %s\n",
2738 smb_fname_str_dbg(smb_fname),
2739 nt_errstr(status)));
2740 return NT_STATUS_ACCESS_DENIED;
2744 * If we can access the path to this file, by
2745 * default we have FILE_READ_ATTRIBUTES from the
2746 * containing directory. See the section:
2747 * "Algorithm to Check Access to an Existing File"
2750 * se_file_access_check()
2751 * also takes care of owner WRITE_DAC and READ_CONTROL.
2753 status = se_file_access_check(sd,
2754 get_current_nttok(conn),
2756 (*p_access_mask & ~FILE_READ_ATTRIBUTES),
2761 if (!NT_STATUS_IS_OK(status)) {
2762 DEBUG(10, ("Access denied on file %s: "
2763 "when calculating maximum access\n",
2764 smb_fname_str_dbg(smb_fname)));
2765 return NT_STATUS_ACCESS_DENIED;
2767 *p_access_mask = (access_granted | FILE_READ_ATTRIBUTES);
2769 if (!(access_granted & DELETE_ACCESS)) {
2770 if (can_delete_file_in_directory(conn, smb_fname)) {
2771 *p_access_mask |= DELETE_ACCESS;
2775 return NT_STATUS_OK;
2778 NTSTATUS smbd_calculate_access_mask(connection_struct *conn,
2779 const struct smb_filename *smb_fname,
2781 uint32_t access_mask,
2782 uint32_t *access_mask_out)
2785 uint32_t orig_access_mask = access_mask;
2786 uint32_t rejected_share_access;
2788 if (access_mask & SEC_MASK_INVALID) {
2789 DBG_DEBUG("access_mask [%8x] contains invalid bits\n",
2791 return NT_STATUS_ACCESS_DENIED;
2795 * Convert GENERIC bits to specific bits.
2798 se_map_generic(&access_mask, &file_generic_mapping);
2800 /* Calculate MAXIMUM_ALLOWED_ACCESS if requested. */
2801 if (access_mask & MAXIMUM_ALLOWED_ACCESS) {
2803 status = smbd_calculate_maximum_allowed_access(
2804 conn, smb_fname, use_privs, &access_mask);
2806 if (!NT_STATUS_IS_OK(status)) {
2810 access_mask &= conn->share_access;
2813 rejected_share_access = access_mask & ~(conn->share_access);
2815 if (rejected_share_access) {
2816 DEBUG(10, ("smbd_calculate_access_mask: Access denied on "
2817 "file %s: rejected by share access mask[0x%08X] "
2818 "orig[0x%08X] mapped[0x%08X] reject[0x%08X]\n",
2819 smb_fname_str_dbg(smb_fname),
2821 orig_access_mask, access_mask,
2822 rejected_share_access));
2823 return NT_STATUS_ACCESS_DENIED;
2826 *access_mask_out = access_mask;
2827 return NT_STATUS_OK;
2830 /****************************************************************************
2831 Remove the deferred open entry under lock.
2832 ****************************************************************************/
2834 /****************************************************************************
2835 Return true if this is a state pointer to an asynchronous create.
2836 ****************************************************************************/
2838 bool is_deferred_open_async(const struct deferred_open_record *rec)
2840 return rec->async_open;
2843 static bool clear_ads(uint32_t create_disposition)
2847 switch (create_disposition) {
2848 case FILE_SUPERSEDE:
2849 case FILE_OVERWRITE_IF:
2850 case FILE_OVERWRITE:
2859 static int disposition_to_open_flags(uint32_t create_disposition)
2864 * Currently we're using FILE_SUPERSEDE as the same as
2865 * FILE_OVERWRITE_IF but they really are
2866 * different. FILE_SUPERSEDE deletes an existing file
2867 * (requiring delete access) then recreates it.
2870 switch (create_disposition) {
2871 case FILE_SUPERSEDE:
2872 case FILE_OVERWRITE_IF:
2874 * If file exists replace/overwrite. If file doesn't
2877 ret = O_CREAT|O_TRUNC;
2882 * If file exists open. If file doesn't exist error.
2887 case FILE_OVERWRITE:
2889 * If file exists overwrite. If file doesn't exist
2897 * If file exists error. If file doesn't exist create.
2899 ret = O_CREAT|O_EXCL;
2904 * If file exists open. If file doesn't exist create.
2912 static int calculate_open_access_flags(uint32_t access_mask,
2913 uint32_t private_flags)
2915 bool need_write, need_read;
2918 * Note that we ignore the append flag as append does not
2919 * mean the same thing under DOS and Unix.
2922 need_write = (access_mask & (FILE_WRITE_DATA | FILE_APPEND_DATA));
2927 /* DENY_DOS opens are always underlying read-write on the
2928 file handle, no matter what the requested access mask
2932 ((private_flags & NTCREATEX_OPTIONS_PRIVATE_DENY_DOS) ||
2933 access_mask & (FILE_READ_ATTRIBUTES|FILE_READ_DATA|
2934 FILE_READ_EA|FILE_EXECUTE));
2942 /****************************************************************************
2943 Open a file with a share mode. Passed in an already created files_struct *.
2944 ****************************************************************************/
2946 static NTSTATUS open_file_ntcreate(connection_struct *conn,
2947 struct smb_request *req,
2948 uint32_t access_mask, /* access bits (FILE_READ_DATA etc.) */
2949 uint32_t share_access, /* share constants (FILE_SHARE_READ etc) */
2950 uint32_t create_disposition, /* FILE_OPEN_IF etc. */
2951 uint32_t create_options, /* options such as delete on close. */
2952 uint32_t new_dos_attributes, /* attributes used for new file. */
2953 int oplock_request, /* internal Samba oplock codes. */
2954 const struct smb2_lease *lease,
2955 /* Information (FILE_EXISTS etc.) */
2956 uint32_t private_flags, /* Samba specific flags. */
2960 struct smb_filename *smb_fname = fsp->fsp_name;
2963 bool file_existed = VALID_STAT(smb_fname->st);
2964 bool def_acl = False;
2965 bool posix_open = False;
2966 bool new_file_created = False;
2967 bool first_open_attempt = true;
2968 NTSTATUS fsp_open = NT_STATUS_ACCESS_DENIED;
2969 mode_t new_unx_mode = (mode_t)0;
2970 mode_t unx_mode = (mode_t)0;
2972 uint32_t existing_dos_attributes = 0;
2973 struct share_mode_lock *lck = NULL;
2974 uint32_t open_access_mask = access_mask;
2977 SMB_STRUCT_STAT saved_stat = smb_fname->st;
2978 struct timespec old_write_time;
2981 if (conn->printer) {
2983 * Printers are handled completely differently.
2984 * Most of the passed parameters are ignored.
2988 *pinfo = FILE_WAS_CREATED;
2991 DEBUG(10, ("open_file_ntcreate: printer open fname=%s\n",
2992 smb_fname_str_dbg(smb_fname)));
2995 DEBUG(0,("open_file_ntcreate: printer open without "
2996 "an SMB request!\n"));
2997 return NT_STATUS_INTERNAL_ERROR;
3000 return print_spool_open(fsp, smb_fname->base_name,
3004 if (!parent_dirname(talloc_tos(), smb_fname->base_name, &parent_dir,
3006 return NT_STATUS_NO_MEMORY;
3009 if (new_dos_attributes & FILE_FLAG_POSIX_SEMANTICS) {
3011 unx_mode = (mode_t)(new_dos_attributes & ~FILE_FLAG_POSIX_SEMANTICS);
3012 new_dos_attributes = 0;
3014 /* Windows allows a new file to be created and
3015 silently removes a FILE_ATTRIBUTE_DIRECTORY
3016 sent by the client. Do the same. */
3018 new_dos_attributes &= ~FILE_ATTRIBUTE_DIRECTORY;
3020 /* We add FILE_ATTRIBUTE_ARCHIVE to this as this mode is only used if the file is
3022 unx_mode = unix_mode(conn, new_dos_attributes | FILE_ATTRIBUTE_ARCHIVE,
3023 smb_fname, parent_dir);
3026 DEBUG(10, ("open_file_ntcreate: fname=%s, dos_attrs=0x%x "
3027 "access_mask=0x%x share_access=0x%x "
3028 "create_disposition = 0x%x create_options=0x%x "
3029 "unix mode=0%o oplock_request=%d private_flags = 0x%x\n",
3030 smb_fname_str_dbg(smb_fname), new_dos_attributes,
3031 access_mask, share_access, create_disposition,
3032 create_options, (unsigned int)unx_mode, oplock_request,
3033 (unsigned int)private_flags));
3036 /* Ensure req == NULL means INTERNAL_OPEN_ONLY */
3037 SMB_ASSERT(oplock_request == INTERNAL_OPEN_ONLY);
3039 /* And req != NULL means no INTERNAL_OPEN_ONLY */
3040 SMB_ASSERT(((oplock_request & INTERNAL_OPEN_ONLY) == 0));
3044 * Only non-internal opens can be deferred at all
3048 struct deferred_open_record *open_rec;
3049 if (get_deferred_open_message_state(req, NULL, &open_rec)) {
3051 /* If it was an async create retry, the file
3054 if (is_deferred_open_async(open_rec)) {
3055 SET_STAT_INVALID(smb_fname->st);
3056 file_existed = false;
3059 /* Ensure we don't reprocess this message. */
3060 remove_deferred_open_message_smb(req->xconn, req->mid);
3062 first_open_attempt = false;
3067 new_dos_attributes &= SAMBA_ATTRIBUTES_MASK;
3070 * Only use stored DOS attributes for checks
3071 * against requested attributes (below via
3072 * open_match_attributes()), cf bug #11992
3073 * for details. -slow
3077 status = SMB_VFS_GET_DOS_ATTRIBUTES(conn, smb_fname, &attr);
3078 if (NT_STATUS_IS_OK(status)) {
3079 existing_dos_attributes = attr;
3084 /* ignore any oplock requests if oplocks are disabled */
3085 if (!lp_oplocks(SNUM(conn)) ||
3086 IS_VETO_OPLOCK_PATH(conn, smb_fname->base_name)) {
3087 /* Mask off everything except the private Samba bits. */
3088 oplock_request &= SAMBA_PRIVATE_OPLOCK_MASK;
3091 /* this is for OS/2 long file names - say we don't support them */
3092 if (req != NULL && !req->posix_pathnames &&
3093 strstr(smb_fname->base_name,".+,;=[].")) {
3094 /* OS/2 Workplace shell fix may be main code stream in a later
3096 DEBUG(5,("open_file_ntcreate: OS/2 long filenames are not "
3098 if (use_nt_status()) {
3099 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3101 return NT_STATUS_DOS(ERRDOS, ERRcannotopen);
3104 switch( create_disposition ) {
3106 /* If file exists open. If file doesn't exist error. */
3107 if (!file_existed) {
3108 DEBUG(5,("open_file_ntcreate: FILE_OPEN "
3109 "requested for file %s and file "
3111 smb_fname_str_dbg(smb_fname)));
3113 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3117 case FILE_OVERWRITE:
3118 /* If file exists overwrite. If file doesn't exist
3120 if (!file_existed) {
3121 DEBUG(5,("open_file_ntcreate: FILE_OVERWRITE "
3122 "requested for file %s and file "
3124 smb_fname_str_dbg(smb_fname) ));
3126 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3131 /* If file exists error. If file doesn't exist
3134 DEBUG(5,("open_file_ntcreate: FILE_CREATE "
3135 "requested for file %s and file "
3136 "already exists.\n",
3137 smb_fname_str_dbg(smb_fname)));
3138 if (S_ISDIR(smb_fname->st.st_ex_mode)) {
3143 return map_nt_error_from_unix(errno);
3147 case FILE_SUPERSEDE:
3148 case FILE_OVERWRITE_IF:
3152 return NT_STATUS_INVALID_PARAMETER;
3155 flags2 = disposition_to_open_flags(create_disposition);
3157 /* We only care about matching attributes on file exists and
3160 if (!posix_open && file_existed &&
3161 ((create_disposition == FILE_OVERWRITE) ||
3162 (create_disposition == FILE_OVERWRITE_IF))) {
3163 if (!open_match_attributes(conn, existing_dos_attributes,
3165 unx_mode, &new_unx_mode)) {
3166 DEBUG(5,("open_file_ntcreate: attributes mismatch "
3167 "for file %s (%x %x) (0%o, 0%o)\n",
3168 smb_fname_str_dbg(smb_fname),
3169 existing_dos_attributes,
3171 (unsigned int)smb_fname->st.st_ex_mode,
3172 (unsigned int)unx_mode ));
3174 return NT_STATUS_ACCESS_DENIED;
3178 status = smbd_calculate_access_mask(conn, smb_fname,
3182 if (!NT_STATUS_IS_OK(status)) {
3183 DEBUG(10, ("open_file_ntcreate: smbd_calculate_access_mask "
3184 "on file %s returned %s\n",
3185 smb_fname_str_dbg(smb_fname), nt_errstr(status)));
3189 open_access_mask = access_mask;
3191 if (flags2 & O_TRUNC) {
3192 open_access_mask |= FILE_WRITE_DATA; /* This will cause oplock breaks. */
3195 DEBUG(10, ("open_file_ntcreate: fname=%s, after mapping "
3196 "access_mask=0x%x\n", smb_fname_str_dbg(smb_fname),
3200 * Note that we ignore the append flag as append does not
3201 * mean the same thing under DOS and Unix.
3204 flags = calculate_open_access_flags(access_mask, private_flags);
3207 * Currently we only look at FILE_WRITE_THROUGH for create options.
3211 if ((create_options & FILE_WRITE_THROUGH) && lp_strict_sync(SNUM(conn))) {
3216 if (posix_open && (access_mask & FILE_APPEND_DATA)) {
3220 if (!posix_open && !CAN_WRITE(conn)) {
3222 * We should really return a permission denied error if either
3223 * O_CREAT or O_TRUNC are set, but for compatibility with
3224 * older versions of Samba we just AND them out.
3226 flags2 &= ~(O_CREAT|O_TRUNC);
3230 * With kernel oplocks the open breaking an oplock
3231 * blocks until the oplock holder has given up the
3232 * oplock or closed the file. We prevent this by always
3233 * trying to open the file with O_NONBLOCK (see "man
3236 * If a process that doesn't use the smbd open files
3237 * database or communication methods holds a kernel
3238 * oplock we must periodically poll for available open
3241 flags2 |= O_NONBLOCK;
3244 * Ensure we can't write on a read-only share or file.
3247 if (flags != O_RDONLY && file_existed &&
3248 (!CAN_WRITE(conn) || IS_DOS_READONLY(existing_dos_attributes))) {
3249 DEBUG(5,("open_file_ntcreate: write access requested for "
3250 "file %s on read only %s\n",
3251 smb_fname_str_dbg(smb_fname),
3252 !CAN_WRITE(conn) ? "share" : "file" ));
3254 return NT_STATUS_ACCESS_DENIED;
3257 fsp->file_id = vfs_file_id_from_sbuf(conn, &smb_fname->st);
3258 fsp->fh->private_options = private_flags;
3259 fsp->access_mask = open_access_mask; /* We change this to the
3260 * requested access_mask after
3261 * the open is done. */
3263 fsp->posix_flags |= FSP_POSIX_FLAGS_ALL;
3266 if ((create_options & FILE_DELETE_ON_CLOSE) &&
3267 (flags2 & O_CREAT) &&
3269 /* Delete on close semantics for new files. */
3270 status = can_set_delete_on_close(fsp,
3271 new_dos_attributes);
3272 if (!NT_STATUS_IS_OK(status)) {
3279 * Ensure we pay attention to default ACLs on directories if required.
3282 if ((flags2 & O_CREAT) && lp_inherit_acls(SNUM(conn)) &&
3283 (def_acl = directory_has_default_acl(conn, parent_dir))) {
3284 unx_mode = (0777 & lp_create_mask(SNUM(conn)));
3287 DEBUG(4,("calling open_file with flags=0x%X flags2=0x%X mode=0%o, "
3288 "access_mask = 0x%x, open_access_mask = 0x%x\n",
3289 (unsigned int)flags, (unsigned int)flags2,
3290 (unsigned int)unx_mode, (unsigned int)access_mask,
3291 (unsigned int)open_access_mask));
3293 fsp_open = open_file(fsp, conn, req, parent_dir,
3294 flags|flags2, unx_mode, access_mask,
3295 open_access_mask, &new_file_created);
3297 if (NT_STATUS_EQUAL(fsp_open, NT_STATUS_NETWORK_BUSY)) {
3301 * This handles the kernel oplock case:
3303 * the file has an active kernel oplock and the open() returned
3304 * EWOULDBLOCK/EAGAIN which maps to NETWORK_BUSY.
3306 * "Samba locking.tdb oplocks" are handled below after acquiring
3307 * the sharemode lock with get_share_mode_lock().
3309 if (file_existed && S_ISFIFO(fsp->fsp_name->st.st_ex_mode)) {
3310 DEBUG(10, ("FIFO busy\n"));
3311 return NT_STATUS_NETWORK_BUSY;
3314 DEBUG(10, ("Internal open busy\n"));
3315 return NT_STATUS_NETWORK_BUSY;
3319 * From here on we assume this is an oplock break triggered
3322 lck = get_existing_share_mode_lock(talloc_tos(), fsp->file_id);
3325 * No oplock from Samba around. Set up a poll every 1
3326 * second to retry a non-blocking open until the time
3332 timeval_set(OPLOCK_BREAK_TIMEOUT*2, 0),
3334 DBG_DEBUG("No Samba oplock around after EWOULDBLOCK. "
3335 "Retrying with poll\n");
3336 return NT_STATUS_SHARING_VIOLATION;
3339 if (!validate_oplock_types(lck)) {
3340 smb_panic("validate_oplock_types failed");
3343 delay = delay_for_oplock(fsp, 0, lease, lck, false,
3345 first_open_attempt);
3347 schedule_defer_open(lck, fsp->file_id, req);
3349 DEBUG(10, ("Sent oplock break request to kernel "
3350 "oplock holder\n"));
3351 return NT_STATUS_SHARING_VIOLATION;
3355 * No oplock from Samba around. Set up a poll every 1
3356 * second to retry a non-blocking open until the time
3362 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 (!NT_STATUS_IS_OK(fsp_open)) {
3372 if (NT_STATUS_EQUAL(fsp_open, NT_STATUS_RETRY)) {
3373 schedule_async_open(req);
3378 if (new_file_created) {
3380 * As we atomically create using O_CREAT|O_EXCL,
3381 * then if new_file_created is true, then
3382 * file_existed *MUST* have been false (even
3383 * if the file was previously detected as being
3386 file_existed = false;
3389 if (file_existed && !check_same_dev_ino(&saved_stat, &smb_fname->st)) {
3391 * The file did exist, but some other (local or NFS)
3392 * process either renamed/unlinked and re-created the
3393 * file with different dev/ino after we walked the path,
3394 * but before we did the open. We could retry the
3395 * open but it's a rare enough case it's easier to
3396 * just fail the open to prevent creating any problems
3397 * in the open file db having the wrong dev/ino key.
3400 DBG_WARNING("file %s - dev/ino mismatch. "
3401 "Old (dev=%ju, ino=%ju). "
3402 "New (dev=%ju, ino=%ju). Failing open "
3403 "with NT_STATUS_ACCESS_DENIED.\n",
3404 smb_fname_str_dbg(smb_fname),
3405 (uintmax_t)saved_stat.st_ex_dev,
3406 (uintmax_t)saved_stat.st_ex_ino,
3407 (uintmax_t)smb_fname->st.st_ex_dev,
3408 (uintmax_t)smb_fname->st.st_ex_ino);
3409 return NT_STATUS_ACCESS_DENIED;
3412 old_write_time = smb_fname->st.st_ex_mtime;
3415 * Deal with the race condition where two smbd's detect the
3416 * file doesn't exist and do the create at the same time. One
3417 * of them will win and set a share mode, the other (ie. this
3418 * one) should check if the requested share mode for this
3419 * create is allowed.
3423 * Now the file exists and fsp is successfully opened,
3424 * fsp->dev and fsp->inode are valid and should replace the
3425 * dev=0,inode=0 from a non existent file. Spotted by
3426 * Nadav Danieli <nadavd@exanet.com>. JRA.
3431 lck = get_share_mode_lock(talloc_tos(), id,
3433 smb_fname, &old_write_time);
3436 DEBUG(0, ("open_file_ntcreate: Could not get share "
3437 "mode lock for %s\n",
3438 smb_fname_str_dbg(smb_fname)));
3440 return NT_STATUS_SHARING_VIOLATION;
3443 /* Get the types we need to examine. */
3444 if (!validate_oplock_types(lck)) {
3445 smb_panic("validate_oplock_types failed");
3448 if (has_delete_on_close(lck, fsp->name_hash)) {
3451 return NT_STATUS_DELETE_PENDING;
3454 status = open_mode_check(conn, lck,
3455 access_mask, share_access);
3457 if (NT_STATUS_EQUAL(status, NT_STATUS_SHARING_VIOLATION) ||
3458 (lck->data->num_share_modes > 0)) {
3460 * This comes from ancient times out of open_mode_check. I
3461 * have no clue whether this is still necessary. I can't think
3462 * of a case where this would actually matter further down in
3463 * this function. I leave it here for further investigation
3466 file_existed = true;
3471 * Handle oplocks, deferring the request if delay_for_oplock()
3472 * triggered a break message and we have to wait for the break
3476 bool sharing_violation = NT_STATUS_EQUAL(
3477 status, NT_STATUS_SHARING_VIOLATION);
3479 delay = delay_for_oplock(fsp, oplock_request, lease, lck,
3482 first_open_attempt);
3484 schedule_defer_open(lck, fsp->file_id, req);
3487 return NT_STATUS_SHARING_VIOLATION;
3491 if (!NT_STATUS_IS_OK(status)) {
3493 SMB_ASSERT(NT_STATUS_EQUAL(status, NT_STATUS_SHARING_VIOLATION));
3498 return NT_STATUS_SHARING_VIOLATION;
3501 /* Should we atomically (to the client at least) truncate ? */
3502 if ((!new_file_created) &&
3503 (flags2 & O_TRUNC) &&
3504 (S_ISREG(fsp->fsp_name->st.st_ex_mode))) {
3507 ret = SMB_VFS_FTRUNCATE(fsp, 0);
3509 status = map_nt_error_from_unix(errno);
3514 notify_fname(fsp->conn, NOTIFY_ACTION_MODIFIED,
3515 FILE_NOTIFY_CHANGE_SIZE
3516 | FILE_NOTIFY_CHANGE_ATTRIBUTES,
3517 fsp->fsp_name->base_name);
3521 * We have the share entry *locked*.....
3524 /* Delete streams if create_disposition requires it */
3525 if (!new_file_created && clear_ads(create_disposition) &&
3526 !is_ntfs_stream_smb_fname(smb_fname)) {
3527 status = delete_all_streams(conn, smb_fname);
3528 if (!NT_STATUS_IS_OK(status)) {
3535 if (fsp->fh->fd != -1 && lp_kernel_share_modes(SNUM(conn))) {
3538 * Beware: streams implementing VFS modules may
3539 * implement streams in a way that fsp will have the
3540 * basefile open in the fsp fd, so lacking a distinct
3541 * fd for the stream kernel_flock will apply on the
3542 * basefile which is wrong. The actual check is
3543 * deferred to the VFS module implementing the
3544 * kernel_flock call.
3546 ret_flock = SMB_VFS_KERNEL_FLOCK(fsp, share_access, access_mask);
3547 if(ret_flock == -1 ){
3552 return NT_STATUS_SHARING_VIOLATION;
3555 fsp->kernel_share_modes_taken = true;
3559 * At this point onwards, we can guarantee that the share entry
3560 * is locked, whether we created the file or not, and that the
3561 * deny mode is compatible with all current opens.
3565 * According to Samba4, SEC_FILE_READ_ATTRIBUTE is always granted,
3566 * but we don't have to store this - just ignore it on access check.
3568 if (conn->sconn->using_smb2) {
3570 * SMB2 doesn't return it (according to Microsoft tests).
3571 * Test Case: TestSuite_ScenarioNo009GrantedAccessTestS0
3572 * File created with access = 0x7 (Read, Write, Delete)
3573 * Query Info on file returns 0x87 (Read, Write, Delete, Read Attributes)
3575 fsp->access_mask = access_mask;
3577 /* But SMB1 does. */
3578 fsp->access_mask = access_mask | FILE_READ_ATTRIBUTES;
3583 * stat opens on existing files don't get oplocks.
3584 * They can get leases.
3586 * Note that we check for stat open on the *open_access_mask*,
3587 * i.e. the access mask we actually used to do the open,
3588 * not the one the client asked for (which is in
3589 * fsp->access_mask). This is due to the fact that
3590 * FILE_OVERWRITE and FILE_OVERWRITE_IF add in O_TRUNC,
3591 * which adds FILE_WRITE_DATA to open_access_mask.
3593 if (is_stat_open(open_access_mask) && lease == NULL) {
3594 oplock_request = NO_OPLOCK;
3598 if (new_file_created) {
3599 info = FILE_WAS_CREATED;
3601 if (flags2 & O_TRUNC) {
3602 info = FILE_WAS_OVERWRITTEN;
3604 info = FILE_WAS_OPENED;
3613 * Setup the oplock info in both the shared memory and
3616 status = grant_fsp_oplock_type(
3624 if (!NT_STATUS_IS_OK(status)) {
3630 /* Handle strange delete on close create semantics. */
3631 if (create_options & FILE_DELETE_ON_CLOSE) {
3632 if (!new_file_created) {
3633 status = can_set_delete_on_close(fsp,
3634 existing_dos_attributes);
3636 if (!NT_STATUS_IS_OK(status)) {
3637 /* Remember to delete the mode we just added. */
3638 del_share_mode(lck, fsp);
3644 /* Note that here we set the *initial* delete on close flag,
3645 not the regular one. The magic gets handled in close. */
3646 fsp->initial_delete_on_close = True;
3649 if (info == FILE_WAS_CREATED) {
3650 smb_fname->st.st_ex_iflags &= ~ST_EX_IFLAG_CALCULATED_ITIME;
3653 if (info != FILE_WAS_OPENED) {
3654 /* Overwritten files should be initially set as archive */
3655 if ((info == FILE_WAS_OVERWRITTEN && lp_map_archive(SNUM(conn))) ||
3656 lp_store_dos_attributes(SNUM(conn))) {
3658 if (file_set_dosmode(conn, smb_fname,
3659 new_dos_attributes | FILE_ATTRIBUTE_ARCHIVE,
3660 parent_dir, true) == 0) {
3661 unx_mode = smb_fname->st.st_ex_mode;
3667 /* Determine sparse flag. */
3669 /* POSIX opens are sparse by default. */
3670 fsp->is_sparse = true;
3672 fsp->is_sparse = (file_existed &&
3673 (existing_dos_attributes & FILE_ATTRIBUTE_SPARSE));
3677 * Take care of inherited ACLs on created files - if default ACL not
3681 if (!posix_open && new_file_created && !def_acl) {
3682 if (unx_mode != smb_fname->st.st_ex_mode) {
3683 int ret = SMB_VFS_FCHMOD(fsp, unx_mode);
3685 DBG_INFO("failed to reset "
3686 "attributes of file %s to 0%o\n",
3687 smb_fname_str_dbg(smb_fname),
3688 (unsigned int)unx_mode);
3692 } else if (new_unx_mode) {
3694 * We only get here in the case of:
3696 * a). Not a POSIX open.
3697 * b). File already existed.
3698 * c). File was overwritten.
3699 * d). Requested DOS attributes didn't match
3700 * the DOS attributes on the existing file.
3702 * In that case new_unx_mode has been set
3703 * equal to the calculated mode (including
3704 * possible inheritance of the mode from the
3705 * containing directory).
3707 * Note this mode was calculated with the
3708 * DOS attribute FILE_ATTRIBUTE_ARCHIVE added,
3709 * so the mode change here is suitable for
3710 * an overwritten file.
3713 if (new_unx_mode != smb_fname->st.st_ex_mode) {
3714 int ret = SMB_VFS_FCHMOD(fsp, new_unx_mode);
3716 DBG_INFO("failed to reset "
3717 "attributes of file %s to 0%o\n",
3718 smb_fname_str_dbg(smb_fname),
3719 (unsigned int)new_unx_mode);
3726 * Deal with other opens having a modified write time.
3728 struct timespec write_time = get_share_mode_write_time(lck);
3730 if (!null_timespec(write_time)) {
3731 update_stat_ex_mtime(&fsp->fsp_name->st, write_time);
3737 return NT_STATUS_OK;
3740 static NTSTATUS mkdir_internal(connection_struct *conn,
3741 struct smb_filename *smb_dname,
3742 uint32_t file_attributes)
3745 char *parent_dir = NULL;
3747 bool posix_open = false;
3748 bool need_re_stat = false;
3749 uint32_t access_mask = SEC_DIR_ADD_SUBDIR;
3751 if (!CAN_WRITE(conn) || (access_mask & ~(conn->share_access))) {
3752 DEBUG(5,("mkdir_internal: failing share access "
3753 "%s\n", lp_servicename(talloc_tos(), SNUM(conn))));
3754 return NT_STATUS_ACCESS_DENIED;
3757 if (!parent_dirname(talloc_tos(), smb_dname->base_name, &parent_dir,
3759 return NT_STATUS_NO_MEMORY;
3762 if (file_attributes & FILE_FLAG_POSIX_SEMANTICS) {
3764 mode = (mode_t)(file_attributes & ~FILE_FLAG_POSIX_SEMANTICS);
3766 mode = unix_mode(conn, FILE_ATTRIBUTE_DIRECTORY, smb_dname, parent_dir);
3769 status = check_parent_access(conn,
3772 if(!NT_STATUS_IS_OK(status)) {
3773 DEBUG(5,("mkdir_internal: check_parent_access "
3774 "on directory %s for path %s returned %s\n",
3776 smb_dname->base_name,
3777 nt_errstr(status) ));
3781 if (SMB_VFS_MKDIR(conn, smb_dname, mode) != 0) {
3782 return map_nt_error_from_unix(errno);
3785 /* Ensure we're checking for a symlink here.... */
3786 /* We don't want to get caught by a symlink racer. */
3788 if (SMB_VFS_LSTAT(conn, smb_dname) == -1) {
3789 DEBUG(2, ("Could not stat directory '%s' just created: %s\n",
3790 smb_fname_str_dbg(smb_dname), strerror(errno)));
3791 return map_nt_error_from_unix(errno);
3794 if (!S_ISDIR(smb_dname->st.st_ex_mode)) {
3795 DEBUG(0, ("Directory '%s' just created is not a directory !\n",
3796 smb_fname_str_dbg(smb_dname)));
3797 return NT_STATUS_NOT_A_DIRECTORY;
3800 smb_dname->st.st_ex_iflags &= ~ST_EX_IFLAG_CALCULATED_ITIME;
3802 if (lp_store_dos_attributes(SNUM(conn))) {
3804 file_set_dosmode(conn, smb_dname,
3805 file_attributes | FILE_ATTRIBUTE_DIRECTORY,
3810 if (lp_inherit_permissions(SNUM(conn))) {
3811 inherit_access_posix_acl(conn, parent_dir,
3813 need_re_stat = true;
3818 * Check if high bits should have been set,
3819 * then (if bits are missing): add them.
3820 * Consider bits automagically set by UNIX, i.e. SGID bit from parent
3823 if ((mode & ~(S_IRWXU|S_IRWXG|S_IRWXO)) &&
3824 (mode & ~smb_dname->st.st_ex_mode)) {
3825 SMB_VFS_CHMOD(conn, smb_dname,
3826 (smb_dname->st.st_ex_mode |
3827 (mode & ~smb_dname->st.st_ex_mode)));
3828 need_re_stat = true;
3832 /* Change the owner if required. */
3833 if (lp_inherit_owner(SNUM(conn)) != INHERIT_OWNER_NO) {
3834 change_dir_owner_to_parent(conn, parent_dir,
3837 need_re_stat = true;
3841 if (SMB_VFS_LSTAT(conn, smb_dname) == -1) {
3842 DEBUG(2, ("Could not stat directory '%s' just created: %s\n",
3843 smb_fname_str_dbg(smb_dname), strerror(errno)));
3844 return map_nt_error_from_unix(errno);
3848 notify_fname(conn, NOTIFY_ACTION_ADDED, FILE_NOTIFY_CHANGE_DIR_NAME,
3849 smb_dname->base_name);
3851 return NT_STATUS_OK;
3854 /****************************************************************************
3855 Open a directory from an NT SMB call.
3856 ****************************************************************************/
3858 static NTSTATUS open_directory(connection_struct *conn,
3859 struct smb_request *req,
3860 struct smb_filename *smb_dname,
3861 uint32_t access_mask,
3862 uint32_t share_access,
3863 uint32_t create_disposition,
3864 uint32_t create_options,
3865 uint32_t file_attributes,
3867 files_struct **result)
3869 files_struct *fsp = NULL;
3870 bool dir_existed = VALID_STAT(smb_dname->st) ? True : False;
3871 struct share_mode_lock *lck = NULL;
3873 struct timespec mtimespec;
3877 if (is_ntfs_stream_smb_fname(smb_dname)) {
3878 DEBUG(2, ("open_directory: %s is a stream name!\n",
3879 smb_fname_str_dbg(smb_dname)));
3880 return NT_STATUS_NOT_A_DIRECTORY;
3883 if (!(file_attributes & FILE_FLAG_POSIX_SEMANTICS)) {
3884 /* Ensure we have a directory attribute. */
3885 file_attributes |= FILE_ATTRIBUTE_DIRECTORY;
3888 DEBUG(5,("open_directory: opening directory %s, access_mask = 0x%x, "
3889 "share_access = 0x%x create_options = 0x%x, "
3890 "create_disposition = 0x%x, file_attributes = 0x%x\n",
3891 smb_fname_str_dbg(smb_dname),
3892 (unsigned int)access_mask,
3893 (unsigned int)share_access,
3894 (unsigned int)create_options,
3895 (unsigned int)create_disposition,
3896 (unsigned int)file_attributes));
3898 status = smbd_calculate_access_mask(conn, smb_dname, false,
3899 access_mask, &access_mask);
3900 if (!NT_STATUS_IS_OK(status)) {
3901 DEBUG(10, ("open_directory: smbd_calculate_access_mask "
3902 "on file %s returned %s\n",
3903 smb_fname_str_dbg(smb_dname),
3904 nt_errstr(status)));
3908 if ((access_mask & SEC_FLAG_SYSTEM_SECURITY) &&
3909 !security_token_has_privilege(get_current_nttok(conn),
3910 SEC_PRIV_SECURITY)) {
3911 DEBUG(10, ("open_directory: open on %s "
3912 "failed - SEC_FLAG_SYSTEM_SECURITY denied.\n",
3913 smb_fname_str_dbg(smb_dname)));
3914 return NT_STATUS_PRIVILEGE_NOT_HELD;
3917 switch( create_disposition ) {
3921 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3924 info = FILE_WAS_OPENED;
3929 /* If directory exists error. If directory doesn't
3933 status = NT_STATUS_OBJECT_NAME_COLLISION;
3934 DEBUG(2, ("open_directory: unable to create "
3935 "%s. Error was %s\n",
3936 smb_fname_str_dbg(smb_dname),
3937 nt_errstr(status)));
3941 status = mkdir_internal(conn, smb_dname,
3944 if (!NT_STATUS_IS_OK(status)) {
3945 DEBUG(2, ("open_directory: unable to create "
3946 "%s. Error was %s\n",
3947 smb_fname_str_dbg(smb_dname),
3948 nt_errstr(status)));
3952 info = FILE_WAS_CREATED;
3957 * If directory exists open. If directory doesn't
3962 status = NT_STATUS_OK;
3963 info = FILE_WAS_OPENED;
3965 status = mkdir_internal(conn, smb_dname,
3968 if (NT_STATUS_IS_OK(status)) {
3969 info = FILE_WAS_CREATED;
3971 /* Cope with create race. */
3972 if (!NT_STATUS_EQUAL(status,
3973 NT_STATUS_OBJECT_NAME_COLLISION)) {
3974 DEBUG(2, ("open_directory: unable to create "
3975 "%s. Error was %s\n",
3976 smb_fname_str_dbg(smb_dname),
3977 nt_errstr(status)));
3982 * If mkdir_internal() returned
3983 * NT_STATUS_OBJECT_NAME_COLLISION
3984 * we still must lstat the path.
3987 if (SMB_VFS_LSTAT(conn, smb_dname)
3989 DEBUG(2, ("Could not stat "
3990 "directory '%s' just "
3995 return map_nt_error_from_unix(
3999 info = FILE_WAS_OPENED;
4005 case FILE_SUPERSEDE:
4006 case FILE_OVERWRITE:
4007 case FILE_OVERWRITE_IF:
4009 DEBUG(5,("open_directory: invalid create_disposition "
4010 "0x%x for directory %s\n",
4011 (unsigned int)create_disposition,
4012 smb_fname_str_dbg(smb_dname)));
4013 return NT_STATUS_INVALID_PARAMETER;
4016 if(!S_ISDIR(smb_dname->st.st_ex_mode)) {
4017 DEBUG(5,("open_directory: %s is not a directory !\n",
4018 smb_fname_str_dbg(smb_dname)));
4019 return NT_STATUS_NOT_A_DIRECTORY;
4022 if (info == FILE_WAS_OPENED) {
4023 status = smbd_check_access_rights(conn,
4027 if (!NT_STATUS_IS_OK(status)) {
4028 DEBUG(10, ("open_directory: smbd_check_access_rights on "
4029 "file %s failed with %s\n",
4030 smb_fname_str_dbg(smb_dname),
4031 nt_errstr(status)));
4036 status = file_new(req, conn, &fsp);
4037 if(!NT_STATUS_IS_OK(status)) {
4042 * Setup the files_struct for it.
4045 fsp->file_id = vfs_file_id_from_sbuf(conn, &smb_dname->st);
4046 fsp->vuid = req ? req->vuid : UID_FIELD_INVALID;
4047 fsp->file_pid = req ? req->smbpid : 0;
4048 fsp->can_lock = False;
4049 fsp->can_read = False;
4050 fsp->can_write = False;
4052 fsp->fh->private_options = 0;
4054 * According to Samba4, SEC_FILE_READ_ATTRIBUTE is always granted,
4056 fsp->access_mask = access_mask | FILE_READ_ATTRIBUTES;
4057 fsp->print_file = NULL;
4058 fsp->modified = False;
4059 fsp->oplock_type = NO_OPLOCK;
4060 fsp->sent_oplock_break = NO_BREAK_SENT;
4061 fsp->is_directory = True;
4062 if (file_attributes & FILE_FLAG_POSIX_SEMANTICS) {
4063 fsp->posix_flags |= FSP_POSIX_FLAGS_ALL;
4065 status = fsp_set_smb_fname(fsp, smb_dname);
4066 if (!NT_STATUS_IS_OK(status)) {
4067 file_free(req, fsp);
4071 /* Don't store old timestamps for directory
4072 handles in the internal database. We don't
4073 update them in there if new objects
4074 are creaded in the directory. Currently
4075 we only update timestamps on file writes.
4078 ZERO_STRUCT(mtimespec);
4081 status = fd_open(conn, fsp, O_RDONLY|O_DIRECTORY, 0);
4083 /* POSIX allows us to open a directory with O_RDONLY. */
4084 status = fd_open(conn, fsp, O_RDONLY, 0);
4086 if (!NT_STATUS_IS_OK(status)) {
4087 DBG_INFO("Could not open fd for "
4089 smb_fname_str_dbg(smb_dname),
4091 file_free(req, fsp);
4095 status = vfs_stat_fsp(fsp);
4096 if (!NT_STATUS_IS_OK(status)) {
4098 file_free(req, fsp);
4102 if(!S_ISDIR(fsp->fsp_name->st.st_ex_mode)) {
4103 DEBUG(5,("open_directory: %s is not a directory !\n",
4104 smb_fname_str_dbg(smb_dname)));
4106 file_free(req, fsp);
4107 return NT_STATUS_NOT_A_DIRECTORY;
4110 /* Ensure there was no race condition. We need to check
4111 * dev/inode but not permissions, as these can change
4113 if (!check_same_dev_ino(&smb_dname->st, &fsp->fsp_name->st)) {
4114 DEBUG(5,("open_directory: stat struct differs for "
4116 smb_fname_str_dbg(smb_dname)));
4118 file_free(req, fsp);
4119 return NT_STATUS_ACCESS_DENIED;
4122 lck = get_share_mode_lock(talloc_tos(), fsp->file_id,
4123 conn->connectpath, smb_dname,
4127 DEBUG(0, ("open_directory: Could not get share mode lock for "
4128 "%s\n", smb_fname_str_dbg(smb_dname)));
4130 file_free(req, fsp);
4131 return NT_STATUS_SHARING_VIOLATION;
4134 if (has_delete_on_close(lck, fsp->name_hash)) {
4137 file_free(req, fsp);
4138 return NT_STATUS_DELETE_PENDING;
4141 status = open_mode_check(conn, lck,
4142 access_mask, share_access);
4144 if (!NT_STATUS_IS_OK(status)) {
4147 file_free(req, fsp);
4151 ok = set_share_mode(
4154 get_current_uid(conn),
4162 file_free(req, fsp);
4163 return NT_STATUS_NO_MEMORY;
4166 /* For directories the delete on close bit at open time seems
4167 always to be honored on close... See test 19 in Samba4 BASE-DELETE. */
4168 if (create_options & FILE_DELETE_ON_CLOSE) {
4169 status = can_set_delete_on_close(fsp, 0);
4170 if (!NT_STATUS_IS_OK(status) && !NT_STATUS_EQUAL(status, NT_STATUS_DIRECTORY_NOT_EMPTY)) {
4171 del_share_mode(lck, fsp);
4174 file_free(req, fsp);
4178 if (NT_STATUS_IS_OK(status)) {
4179 /* Note that here we set the *initial* delete on close flag,
4180 not the regular one. The magic gets handled in close. */
4181 fsp->initial_delete_on_close = True;
4187 * Deal with other opens having a modified write time. Is this
4188 * possible for directories?
4190 struct timespec write_time = get_share_mode_write_time(lck);
4192 if (!null_timespec(write_time)) {
4193 update_stat_ex_mtime(&fsp->fsp_name->st, write_time);
4204 return NT_STATUS_OK;
4207 NTSTATUS create_directory(connection_struct *conn, struct smb_request *req,
4208 struct smb_filename *smb_dname)
4213 status = SMB_VFS_CREATE_FILE(
4216 0, /* root_dir_fid */
4217 smb_dname, /* fname */
4218 FILE_READ_ATTRIBUTES, /* access_mask */
4219 FILE_SHARE_NONE, /* share_access */
4220 FILE_CREATE, /* create_disposition*/
4221 FILE_DIRECTORY_FILE, /* create_options */
4222 FILE_ATTRIBUTE_DIRECTORY, /* file_attributes */
4223 0, /* oplock_request */
4225 0, /* allocation_size */
4226 0, /* private_flags */
4231 NULL, NULL); /* create context */
4233 if (NT_STATUS_IS_OK(status)) {
4234 close_file(req, fsp, NORMAL_CLOSE);
4240 /****************************************************************************
4241 Receive notification that one of our open files has been renamed by another
4243 ****************************************************************************/
4245 void msg_file_was_renamed(struct messaging_context *msg_ctx,
4248 struct server_id src,
4251 struct file_rename_message *msg = NULL;
4252 enum ndr_err_code ndr_err;
4254 struct smb_filename *smb_fname = NULL;
4255 struct smbd_server_connection *sconn =
4256 talloc_get_type_abort(private_data,
4257 struct smbd_server_connection);
4259 msg = talloc(talloc_tos(), struct file_rename_message);
4261 DBG_WARNING("talloc failed\n");
4265 ndr_err = ndr_pull_struct_blob_all(
4269 (ndr_pull_flags_fn_t)ndr_pull_file_rename_message);
4270 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
4271 DBG_DEBUG("ndr_pull_oplock_break_message failed: %s\n",
4272 ndr_errstr(ndr_err));
4275 if (DEBUGLEVEL >= 10) {
4276 struct server_id_buf buf;
4277 DBG_DEBUG("Got rename message from %s\n",
4278 server_id_str_buf(src, &buf));
4279 NDR_PRINT_DEBUG(file_rename_message, msg);
4282 /* stream_name must always be NULL if there is no stream. */
4283 if ((msg->stream_name != NULL) && (msg->stream_name[0] == '\0')) {
4284 msg->stream_name = NULL;
4287 smb_fname = synthetic_smb_fname(
4288 msg, msg->base_name, msg->stream_name, NULL, 0);
4289 if (smb_fname == NULL) {
4290 DBG_DEBUG("synthetic_smb_fname failed\n");
4294 fsp = file_find_dif(sconn, msg->id, msg->share_file_id);
4296 DBG_DEBUG("fsp not found\n");
4300 if (strcmp(fsp->conn->connectpath, msg->servicepath) == 0) {
4302 DBG_DEBUG("renaming file %s from %s -> %s\n",
4305 smb_fname_str_dbg(smb_fname));
4306 status = fsp_set_smb_fname(fsp, smb_fname);
4307 if (!NT_STATUS_IS_OK(status)) {
4308 DBG_DEBUG("fsp_set_smb_fname failed: %s\n",
4314 * Now we have the complete path we can work out if
4315 * this is actually within this share and adjust
4316 * newname accordingly.
4318 DBG_DEBUG("share mismatch (sharepath %s not sharepath %s) "
4319 "%s from %s -> %s\n",
4320 fsp->conn->connectpath,
4324 smb_fname_str_dbg(smb_fname));
4331 * If a main file is opened for delete, all streams need to be checked for
4332 * !FILE_SHARE_DELETE. Do this by opening with DELETE_ACCESS.
4333 * If that works, delete them all by setting the delete on close and close.
4336 static NTSTATUS open_streams_for_delete(connection_struct *conn,
4337 const struct smb_filename *smb_fname)
4339 struct stream_struct *stream_info = NULL;
4340 files_struct **streams = NULL;
4342 unsigned int i, num_streams = 0;
4343 TALLOC_CTX *frame = talloc_stackframe();
4346 status = vfs_streaminfo(conn, NULL, smb_fname, talloc_tos(),
4347 &num_streams, &stream_info);
4349 if (NT_STATUS_EQUAL(status, NT_STATUS_NOT_IMPLEMENTED)
4350 || NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
4351 DEBUG(10, ("no streams around\n"));
4353 return NT_STATUS_OK;
4356 if (!NT_STATUS_IS_OK(status)) {
4357 DEBUG(10, ("vfs_streaminfo failed: %s\n",
4358 nt_errstr(status)));
4362 DEBUG(10, ("open_streams_for_delete found %d streams\n",
4365 if (num_streams == 0) {
4367 return NT_STATUS_OK;
4370 streams = talloc_array(talloc_tos(), files_struct *, num_streams);
4371 if (streams == NULL) {
4372 DEBUG(0, ("talloc failed\n"));
4373 status = NT_STATUS_NO_MEMORY;
4377 for (i=0; i<num_streams; i++) {
4378 struct smb_filename *smb_fname_cp;
4380 if (strequal(stream_info[i].name, "::$DATA")) {
4385 smb_fname_cp = synthetic_smb_fname(talloc_tos(),
4386 smb_fname->base_name,
4387 stream_info[i].name,
4390 ~SMB_FILENAME_POSIX_PATH));
4391 if (smb_fname_cp == NULL) {
4392 status = NT_STATUS_NO_MEMORY;
4396 if (SMB_VFS_STAT(conn, smb_fname_cp) == -1) {
4397 DEBUG(10, ("Unable to stat stream: %s\n",
4398 smb_fname_str_dbg(smb_fname_cp)));
4401 status = SMB_VFS_CREATE_FILE(
4404 0, /* root_dir_fid */
4405 smb_fname_cp, /* fname */
4406 DELETE_ACCESS, /* access_mask */
4407 (FILE_SHARE_READ | /* share_access */
4408 FILE_SHARE_WRITE | FILE_SHARE_DELETE),
4409 FILE_OPEN, /* create_disposition*/
4410 0, /* create_options */
4411 FILE_ATTRIBUTE_NORMAL, /* file_attributes */
4412 0, /* oplock_request */
4414 0, /* allocation_size */
4415 NTCREATEX_OPTIONS_PRIVATE_STREAM_DELETE, /* private_flags */
4418 &streams[i], /* result */
4420 NULL, NULL); /* create context */
4422 if (!NT_STATUS_IS_OK(status)) {
4423 DEBUG(10, ("Could not open stream %s: %s\n",
4424 smb_fname_str_dbg(smb_fname_cp),
4425 nt_errstr(status)));
4427 TALLOC_FREE(smb_fname_cp);
4430 TALLOC_FREE(smb_fname_cp);
4434 * don't touch the variable "status" beyond this point :-)
4437 for (j = i-1 ; j >= 0; j--) {
4438 if (streams[j] == NULL) {
4442 DEBUG(10, ("Closing stream # %d, %s\n", j,
4443 fsp_str_dbg(streams[j])));
4444 close_file(NULL, streams[j], NORMAL_CLOSE);
4452 /*********************************************************************
4453 Create a default ACL by inheriting from the parent. If no inheritance
4454 from the parent available, don't set anything. This will leave the actual
4455 permissions the new file or directory already got from the filesystem
4456 as the NT ACL when read.
4457 *********************************************************************/
4459 static NTSTATUS inherit_new_acl(files_struct *fsp)
4461 TALLOC_CTX *frame = talloc_stackframe();
4462 char *parent_name = NULL;
4463 struct security_descriptor *parent_desc = NULL;
4464 NTSTATUS status = NT_STATUS_OK;
4465 struct security_descriptor *psd = NULL;
4466 const struct dom_sid *owner_sid = NULL;
4467 const struct dom_sid *group_sid = NULL;
4468 uint32_t security_info_sent = (SECINFO_OWNER | SECINFO_GROUP | SECINFO_DACL);
4469 struct security_token *token = fsp->conn->session_info->security_token;
4470 bool inherit_owner =
4471 (lp_inherit_owner(SNUM(fsp->conn)) == INHERIT_OWNER_WINDOWS_AND_UNIX);
4472 bool inheritable_components = false;
4473 bool try_builtin_administrators = false;
4474 const struct dom_sid *BA_U_sid = NULL;
4475 const struct dom_sid *BA_G_sid = NULL;
4476 bool try_system = false;
4477 const struct dom_sid *SY_U_sid = NULL;
4478 const struct dom_sid *SY_G_sid = NULL;
4480 struct smb_filename *parent_smb_fname = NULL;
4482 if (!parent_dirname(frame, fsp->fsp_name->base_name, &parent_name, NULL)) {
4484 return NT_STATUS_NO_MEMORY;
4486 parent_smb_fname = synthetic_smb_fname(talloc_tos(),
4490 fsp->fsp_name->flags);
4492 if (parent_smb_fname == NULL) {
4494 return NT_STATUS_NO_MEMORY;
4497 status = SMB_VFS_GET_NT_ACL(fsp->conn,
4499 (SECINFO_OWNER | SECINFO_GROUP | SECINFO_DACL),
4502 if (!NT_STATUS_IS_OK(status)) {
4507 inheritable_components = sd_has_inheritable_components(parent_desc,
4510 if (!inheritable_components && !inherit_owner) {
4512 /* Nothing to inherit and not setting owner. */
4513 return NT_STATUS_OK;
4516 /* Create an inherited descriptor from the parent. */
4518 if (DEBUGLEVEL >= 10) {
4519 DEBUG(10,("inherit_new_acl: parent acl for %s is:\n",
4520 fsp_str_dbg(fsp) ));
4521 NDR_PRINT_DEBUG(security_descriptor, parent_desc);
4524 /* Inherit from parent descriptor if "inherit owner" set. */
4525 if (inherit_owner) {
4526 owner_sid = parent_desc->owner_sid;
4527 group_sid = parent_desc->group_sid;
4530 if (owner_sid == NULL) {
4531 if (security_token_has_builtin_administrators(token)) {
4532 try_builtin_administrators = true;
4533 } else if (security_token_is_system(token)) {
4534 try_builtin_administrators = true;
4539 if (group_sid == NULL &&
4540 token->num_sids == PRIMARY_GROUP_SID_INDEX)
4542 if (security_token_is_system(token)) {
4543 try_builtin_administrators = true;
4548 if (try_builtin_administrators) {
4553 ok = sids_to_unixids(&global_sid_Builtin_Administrators, 1, &ids);
4557 BA_U_sid = &global_sid_Builtin_Administrators;
4558 BA_G_sid = &global_sid_Builtin_Administrators;
4561 BA_U_sid = &global_sid_Builtin_Administrators;
4564 BA_G_sid = &global_sid_Builtin_Administrators;
4577 ok = sids_to_unixids(&global_sid_System, 1, &ids);
4581 SY_U_sid = &global_sid_System;
4582 SY_G_sid = &global_sid_System;
4585 SY_U_sid = &global_sid_System;
4588 SY_G_sid = &global_sid_System;
4596 if (owner_sid == NULL) {
4597 owner_sid = BA_U_sid;
4600 if (owner_sid == NULL) {
4601 owner_sid = SY_U_sid;
4604 if (group_sid == NULL) {
4605 group_sid = SY_G_sid;
4608 if (try_system && group_sid == NULL) {
4609 group_sid = BA_G_sid;
4612 if (owner_sid == NULL) {
4613 owner_sid = &token->sids[PRIMARY_USER_SID_INDEX];
4615 if (group_sid == NULL) {
4616 if (token->num_sids == PRIMARY_GROUP_SID_INDEX) {
4617 group_sid = &token->sids[PRIMARY_USER_SID_INDEX];
4619 group_sid = &token->sids[PRIMARY_GROUP_SID_INDEX];
4623 status = se_create_child_secdesc(frame,
4630 if (!NT_STATUS_IS_OK(status)) {
4635 /* If inheritable_components == false,
4636 se_create_child_secdesc()
4637 creates a security descriptor with a NULL dacl
4638 entry, but with SEC_DESC_DACL_PRESENT. We need
4639 to remove that flag. */
4641 if (!inheritable_components) {
4642 security_info_sent &= ~SECINFO_DACL;
4643 psd->type &= ~SEC_DESC_DACL_PRESENT;
4646 if (DEBUGLEVEL >= 10) {
4647 DEBUG(10,("inherit_new_acl: child acl for %s is:\n",
4648 fsp_str_dbg(fsp) ));
4649 NDR_PRINT_DEBUG(security_descriptor, psd);
4652 if (inherit_owner) {
4653 /* We need to be root to force this. */
4656 status = SMB_VFS_FSET_NT_ACL(fsp,
4659 if (inherit_owner) {
4667 * If we already have a lease, it must match the new file id. [MS-SMB2]
4668 * 3.3.5.9.8 speaks about INVALID_PARAMETER if an already used lease key is
4669 * used for a different file name.
4672 struct lease_match_state {
4673 /* Input parameters. */
4674 TALLOC_CTX *mem_ctx;
4675 const char *servicepath;
4676 const struct smb_filename *fname;
4679 /* Return parameters. */
4680 uint32_t num_file_ids;
4681 struct file_id *ids;
4682 NTSTATUS match_status;
4685 /*************************************************************
4686 File doesn't exist but this lease key+guid is already in use.
4688 This is only allowable in the dynamic share case where the
4689 service path must be different.
4691 There is a small race condition here in the multi-connection
4692 case where a client sends two create calls on different connections,
4693 where the file doesn't exist and one smbd creates the leases_db
4694 entry first, but this will get fixed by the multichannel cleanup
4695 when all identical client_guids get handled by a single smbd.
4696 **************************************************************/
4698 static void lease_match_parser_new_file(
4700 const struct leases_db_file *files,
4701 struct lease_match_state *state)
4705 for (i = 0; i < num_files; i++) {
4706 const struct leases_db_file *f = &files[i];
4707 if (strequal(state->servicepath, f->servicepath)) {
4708 state->match_status = NT_STATUS_INVALID_PARAMETER;
4713 /* Dynamic share case. Break leases on all other files. */
4714 state->match_status = leases_db_copy_file_ids(state->mem_ctx,
4718 if (!NT_STATUS_IS_OK(state->match_status)) {
4722 state->num_file_ids = num_files;
4723 state->match_status = NT_STATUS_OPLOCK_NOT_GRANTED;
4727 static void lease_match_parser(
4729 const struct leases_db_file *files,
4732 struct lease_match_state *state =
4733 (struct lease_match_state *)private_data;
4736 if (!state->file_existed) {
4738 * Deal with name mismatch or
4739 * possible dynamic share case separately
4740 * to make code clearer.
4742 lease_match_parser_new_file(num_files,
4749 state->match_status = NT_STATUS_OK;
4751 for (i = 0; i < num_files; i++) {
4752 const struct leases_db_file *f = &files[i];
4754 /* Everything should be the same. */
4755 if (!file_id_equal(&state->id, &f->id)) {
4756 /* This should catch all dynamic share cases. */
4757 state->match_status = NT_STATUS_OPLOCK_NOT_GRANTED;
4760 if (!strequal(f->servicepath, state->servicepath)) {
4761 state->match_status = NT_STATUS_INVALID_PARAMETER;
4764 if (!strequal(f->base_name, state->fname->base_name)) {
4765 state->match_status = NT_STATUS_INVALID_PARAMETER;
4768 if (!strequal(f->stream_name, state->fname->stream_name)) {
4769 state->match_status = NT_STATUS_INVALID_PARAMETER;
4774 if (NT_STATUS_IS_OK(state->match_status)) {
4776 * Common case - just opening another handle on a
4777 * file on a non-dynamic share.
4782 if (NT_STATUS_EQUAL(state->match_status, NT_STATUS_INVALID_PARAMETER)) {
4783 /* Mismatched path. Error back to client. */
4788 * File id mismatch. Dynamic share case NT_STATUS_OPLOCK_NOT_GRANTED.
4789 * Don't allow leases.
4792 state->match_status = leases_db_copy_file_ids(state->mem_ctx,
4796 if (!NT_STATUS_IS_OK(state->match_status)) {
4800 state->num_file_ids = num_files;
4801 state->match_status = NT_STATUS_OPLOCK_NOT_GRANTED;
4805 static NTSTATUS lease_match(connection_struct *conn,
4806 struct smb_request *req,
4807 const struct smb2_lease_key *lease_key,
4808 const char *servicepath,
4809 const struct smb_filename *fname,
4810 uint16_t *p_version,
4813 struct smbd_server_connection *sconn = req->sconn;
4814 TALLOC_CTX *tos = talloc_tos();
4815 struct lease_match_state state = {
4817 .servicepath = servicepath,
4819 .match_status = NT_STATUS_OK
4824 state.file_existed = VALID_STAT(fname->st);
4825 if (state.file_existed) {
4826 state.id = vfs_file_id_from_sbuf(conn, &fname->st);
4829 status = leases_db_parse(&sconn->client->connections->smb2.client.guid,
4830 lease_key, lease_match_parser, &state);
4831 if (!NT_STATUS_IS_OK(status)) {
4833 * Not found or error means okay: We can make the lease pass
4835 return NT_STATUS_OK;
4837 if (!NT_STATUS_EQUAL(state.match_status, NT_STATUS_OPLOCK_NOT_GRANTED)) {
4839 * Anything but NT_STATUS_OPLOCK_NOT_GRANTED, let the caller
4842 return state.match_status;
4845 /* We have to break all existing leases. */
4846 for (i = 0; i < state.num_file_ids; i++) {
4847 struct share_mode_lock *lck;
4848 struct share_mode_data *d;
4849 struct share_mode_entry *lease_entry = NULL;
4852 if (file_id_equal(&state.ids[i], &state.id)) {
4853 /* Don't need to break our own file. */
4857 lck = get_existing_share_mode_lock(talloc_tos(), state.ids[i]);
4859 /* Race condition - file already closed. */
4863 for (j=0; j<d->num_share_modes; j++) {
4864 struct share_mode_entry *e = &d->share_modes[j];
4865 uint32_t e_lease_type = get_lease_type(d, e);
4867 if (share_mode_stale_pid(d, j)) {
4871 if (e->op_type == LEASE_OPLOCK) {
4872 if (!smb2_lease_key_equal(&e->lease_key,
4879 if (e_lease_type == SMB2_LEASE_NONE) {
4883 send_break_message(conn->sconn->msg_ctx, &d->id, e,
4887 * Windows 7 and 8 lease clients
4888 * are broken in that they will not
4889 * respond to lease break requests
4890 * whilst waiting for an outstanding
4891 * open request on that lease handle
4892 * on the same TCP connection, due
4893 * to holding an internal inode lock.
4895 * This means we can't reschedule
4896 * ourselves here, but must return
4901 * Send the breaks and then return
4902 * SMB2_LEASE_NONE in the lease handle
4903 * to cause them to acknowledge the
4904 * lease break. Consultation with
4905 * Microsoft engineering confirmed
4906 * this approach is safe.
4911 if (lease_entry != NULL) {
4912 status = leases_db_get(
4913 &lease_entry->client_guid,
4914 &lease_entry->lease_key,
4916 NULL, /* current_state */
4917 NULL, /* breaking */
4918 NULL, /* breaking_to_requested */
4919 NULL, /* breaking_to_required */
4920 p_version, /* lease_version */
4921 p_epoch); /* epoch */
4922 if (!NT_STATUS_IS_OK(status)) {
4923 DBG_WARNING("Could not find version/epoch: "
4932 * Ensure we don't grant anything more so we
4935 return NT_STATUS_OPLOCK_NOT_GRANTED;
4939 * Wrapper around open_file_ntcreate and open_directory
4942 static NTSTATUS create_file_unixpath(connection_struct *conn,
4943 struct smb_request *req,
4944 struct smb_filename *smb_fname,
4945 uint32_t access_mask,
4946 uint32_t share_access,
4947 uint32_t create_disposition,
4948 uint32_t create_options,
4949 uint32_t file_attributes,
4950 uint32_t oplock_request,
4951 const struct smb2_lease *lease,
4952 uint64_t allocation_size,
4953 uint32_t private_flags,
4954 struct security_descriptor *sd,
4955 struct ea_list *ea_list,
4957 files_struct **result,
4960 struct smb2_lease none_lease;
4961 int info = FILE_WAS_OPENED;
4962 files_struct *base_fsp = NULL;
4963 files_struct *fsp = NULL;
4966 DBG_DEBUG("create_file_unixpath: access_mask = 0x%x "
4967 "file_attributes = 0x%x, share_access = 0x%x, "
4968 "create_disposition = 0x%x create_options = 0x%x "
4969 "oplock_request = 0x%x private_flags = 0x%x "
4970 "ea_list = %p, sd = %p, "
4972 (unsigned int)access_mask,
4973 (unsigned int)file_attributes,
4974 (unsigned int)share_access,
4975 (unsigned int)create_disposition,
4976 (unsigned int)create_options,
4977 (unsigned int)oplock_request,
4978 (unsigned int)private_flags,
4979 ea_list, sd, smb_fname_str_dbg(smb_fname));
4981 if (create_options & FILE_OPEN_BY_FILE_ID) {
4982 status = NT_STATUS_NOT_SUPPORTED;
4986 if (create_options & NTCREATEX_OPTIONS_INVALID_PARAM_MASK) {
4987 status = NT_STATUS_INVALID_PARAMETER;
4992 oplock_request |= INTERNAL_OPEN_ONLY;
4995 if (lease != NULL) {
4996 uint16_t epoch = lease->lease_epoch;
4997 uint16_t version = lease->lease_version;
5000 DBG_WARNING("Got lease on internal open\n");
5001 status = NT_STATUS_INTERNAL_ERROR;
5005 status = lease_match(conn,
5012 if (NT_STATUS_EQUAL(status, NT_STATUS_OPLOCK_NOT_GRANTED)) {
5013 /* Dynamic share file. No leases and update epoch... */
5014 none_lease = *lease;
5015 none_lease.lease_state = SMB2_LEASE_NONE;
5016 none_lease.lease_epoch = epoch;
5017 none_lease.lease_version = version;
5018 lease = &none_lease;
5019 } else if (!NT_STATUS_IS_OK(status)) {
5024 if ((conn->fs_capabilities & FILE_NAMED_STREAMS)
5025 && (access_mask & DELETE_ACCESS)
5026 && !is_ntfs_stream_smb_fname(smb_fname)) {
5028 * We can't open a file with DELETE access if any of the
5029 * streams is open without FILE_SHARE_DELETE
5031 status = open_streams_for_delete(conn, smb_fname);
5033 if (!NT_STATUS_IS_OK(status)) {
5038 if ((access_mask & SEC_FLAG_SYSTEM_SECURITY) &&
5039 !security_token_has_privilege(get_current_nttok(conn),
5040 SEC_PRIV_SECURITY)) {
5041 DEBUG(10, ("create_file_unixpath: open on %s "
5042 "failed - SEC_FLAG_SYSTEM_SECURITY denied.\n",
5043 smb_fname_str_dbg(smb_fname)));
5044 status = NT_STATUS_PRIVILEGE_NOT_HELD;
5049 * Files or directories can't be opened DELETE_ON_CLOSE without
5051 * BUG: https://bugzilla.samba.org/show_bug.cgi?id=13358
5053 if (create_options & FILE_DELETE_ON_CLOSE) {
5054 if ((access_mask & DELETE_ACCESS) == 0) {
5055 status = NT_STATUS_INVALID_PARAMETER;
5060 if ((conn->fs_capabilities & FILE_NAMED_STREAMS)
5061 && is_ntfs_stream_smb_fname(smb_fname)
5062 && (!(private_flags & NTCREATEX_OPTIONS_PRIVATE_STREAM_DELETE))) {
5063 uint32_t base_create_disposition;
5064 struct smb_filename *smb_fname_base = NULL;
5065 uint32_t base_privflags;
5067 if (create_options & FILE_DIRECTORY_FILE) {
5068 status = NT_STATUS_NOT_A_DIRECTORY;
5072 switch (create_disposition) {
5074 base_create_disposition = FILE_OPEN;
5077 base_create_disposition = FILE_OPEN_IF;
5081 /* Create an smb_filename with stream_name == NULL. */
5082 smb_fname_base = synthetic_smb_fname(talloc_tos(),
5083 smb_fname->base_name,
5087 if (smb_fname_base == NULL) {
5088 status = NT_STATUS_NO_MEMORY;
5092 if (SMB_VFS_STAT(conn, smb_fname_base) == -1) {
5093 DEBUG(10, ("Unable to stat stream: %s\n",
5094 smb_fname_str_dbg(smb_fname_base)));
5097 * https://bugzilla.samba.org/show_bug.cgi?id=10229
5098 * We need to check if the requested access mask
5099 * could be used to open the underlying file (if
5100 * it existed), as we're passing in zero for the
5101 * access mask to the base filename.
5103 status = check_base_file_access(conn,
5107 if (!NT_STATUS_IS_OK(status)) {
5108 DEBUG(10, ("Permission check "
5109 "for base %s failed: "
5110 "%s\n", smb_fname->base_name,
5111 nt_errstr(status)));
5116 base_privflags = NTCREATEX_OPTIONS_PRIVATE_STREAM_BASEOPEN;
5118 /* Open the base file. */
5119 status = create_file_unixpath(conn, NULL, smb_fname_base, 0,
5122 | FILE_SHARE_DELETE,
5123 base_create_disposition,
5128 TALLOC_FREE(smb_fname_base);
5130 if (!NT_STATUS_IS_OK(status)) {
5131 DEBUG(10, ("create_file_unixpath for base %s failed: "
5132 "%s\n", smb_fname->base_name,
5133 nt_errstr(status)));
5136 /* we don't need the low level fd */
5141 * If it's a request for a directory open, deal with it separately.
5144 if (create_options & FILE_DIRECTORY_FILE) {
5146 if (create_options & FILE_NON_DIRECTORY_FILE) {
5147 status = NT_STATUS_INVALID_PARAMETER;
5151 /* Can't open a temp directory. IFS kit test. */
5152 if (!(file_attributes & FILE_FLAG_POSIX_SEMANTICS) &&
5153 (file_attributes & FILE_ATTRIBUTE_TEMPORARY)) {
5154 status = NT_STATUS_INVALID_PARAMETER;
5159 * We will get a create directory here if the Win32
5160 * app specified a security descriptor in the
5161 * CreateDirectory() call.
5165 status = open_directory(
5166 conn, req, smb_fname, access_mask, share_access,
5167 create_disposition, create_options, file_attributes,
5172 * Ordinary file case.
5175 status = file_new(req, conn, &fsp);
5176 if(!NT_STATUS_IS_OK(status)) {
5180 status = fsp_set_smb_fname(fsp, smb_fname);
5181 if (!NT_STATUS_IS_OK(status)) {
5187 * We're opening the stream element of a
5188 * base_fsp we already opened. Set up the
5191 fsp->base_fsp = base_fsp;
5194 if (allocation_size) {
5195 fsp->initial_allocation_size = smb_roundup(fsp->conn,
5199 status = open_file_ntcreate(conn,
5212 if(!NT_STATUS_IS_OK(status)) {
5213 file_free(req, fsp);
5217 if (NT_STATUS_EQUAL(status, NT_STATUS_FILE_IS_A_DIRECTORY)) {
5219 /* A stream open never opens a directory */
5222 status = NT_STATUS_FILE_IS_A_DIRECTORY;
5227 * Fail the open if it was explicitly a non-directory
5231 if (create_options & FILE_NON_DIRECTORY_FILE) {
5232 status = NT_STATUS_FILE_IS_A_DIRECTORY;
5237 status = open_directory(
5238 conn, req, smb_fname, access_mask,
5239 share_access, create_disposition,
5240 create_options, file_attributes,
5245 if (!NT_STATUS_IS_OK(status)) {
5249 fsp->base_fsp = base_fsp;
5251 if ((ea_list != NULL) &&
5252 ((info == FILE_WAS_CREATED) || (info == FILE_WAS_OVERWRITTEN))) {
5253 status = set_ea(conn, fsp, fsp->fsp_name, ea_list);
5254 if (!NT_STATUS_IS_OK(status)) {
5259 if (!fsp->is_directory && S_ISDIR(fsp->fsp_name->st.st_ex_mode)) {
5260 status = NT_STATUS_ACCESS_DENIED;
5264 /* Save the requested allocation size. */
5265 if ((info == FILE_WAS_CREATED) || (info == FILE_WAS_OVERWRITTEN)) {
5266 if ((allocation_size > (uint64_t)fsp->fsp_name->st.st_ex_size)
5267 && !(fsp->is_directory))
5269 fsp->initial_allocation_size = smb_roundup(
5270 fsp->conn, allocation_size);
5271 if (vfs_allocate_file_space(
5272 fsp, fsp->initial_allocation_size) == -1) {
5273 status = NT_STATUS_DISK_FULL;
5277 fsp->initial_allocation_size = smb_roundup(
5278 fsp->conn, (uint64_t)fsp->fsp_name->st.st_ex_size);
5281 fsp->initial_allocation_size = 0;
5284 if ((info == FILE_WAS_CREATED) && lp_nt_acl_support(SNUM(conn)) &&
5285 fsp->base_fsp == NULL) {
5288 * According to the MS documentation, the only time the security
5289 * descriptor is applied to the opened file is iff we *created* the
5290 * file; an existing file stays the same.
5292 * Also, it seems (from observation) that you can open the file with
5293 * any access mask but you can still write the sd. We need to override
5294 * the granted access before we call set_sd
5295 * Patch for bug #2242 from Tom Lackemann <cessnatomny@yahoo.com>.
5298 uint32_t sec_info_sent;
5299 uint32_t saved_access_mask = fsp->access_mask;
5301 sec_info_sent = get_sec_info(sd);
5303 fsp->access_mask = FILE_GENERIC_ALL;
5305 if (sec_info_sent & (SECINFO_OWNER|
5309 status = set_sd(fsp, sd, sec_info_sent);
5312 fsp->access_mask = saved_access_mask;
5314 if (!NT_STATUS_IS_OK(status)) {
5317 } else if (lp_inherit_acls(SNUM(conn))) {
5318 /* Inherit from parent. Errors here are not fatal. */
5319 status = inherit_new_acl(fsp);
5320 if (!NT_STATUS_IS_OK(status)) {
5321 DEBUG(10,("inherit_new_acl: failed for %s with %s\n",
5323 nt_errstr(status) ));
5328 if ((conn->fs_capabilities & FILE_FILE_COMPRESSION)
5329 && (create_options & FILE_NO_COMPRESSION)
5330 && (info == FILE_WAS_CREATED)) {
5331 status = SMB_VFS_SET_COMPRESSION(conn, fsp, fsp,
5332 COMPRESSION_FORMAT_NONE);
5333 if (!NT_STATUS_IS_OK(status)) {
5334 DEBUG(1, ("failed to disable compression: %s\n",
5335 nt_errstr(status)));
5339 DEBUG(10, ("create_file_unixpath: info=%d\n", info));
5342 if (pinfo != NULL) {
5346 smb_fname->st = fsp->fsp_name->st;
5348 return NT_STATUS_OK;
5351 DEBUG(10, ("create_file_unixpath: %s\n", nt_errstr(status)));
5354 if (base_fsp && fsp->base_fsp == base_fsp) {
5356 * The close_file below will close
5361 close_file(req, fsp, ERROR_CLOSE);
5364 if (base_fsp != NULL) {
5365 close_file(req, base_fsp, ERROR_CLOSE);
5372 * Calculate the full path name given a relative fid.
5374 static NTSTATUS get_relative_fid_filename(
5375 connection_struct *conn,
5376 struct smb_request *req,
5377 uint16_t root_dir_fid,
5378 const struct smb_filename *smb_fname,
5379 struct smb_filename **smb_fname_out)
5381 files_struct *dir_fsp;
5382 char *parent_fname = NULL;
5383 char *new_base_name = NULL;
5384 uint32_t ucf_flags = ucf_flags_from_smb_request(req);
5387 if (root_dir_fid == 0 || !smb_fname) {
5388 status = NT_STATUS_INTERNAL_ERROR;
5392 dir_fsp = file_fsp(req, root_dir_fid);
5394 if (dir_fsp == NULL) {
5395 status = NT_STATUS_INVALID_HANDLE;
5399 if (is_ntfs_stream_smb_fname(dir_fsp->fsp_name)) {
5400 status = NT_STATUS_INVALID_HANDLE;
5404 if (!dir_fsp->is_directory) {
5407 * Check to see if this is a mac fork of some kind.
5410 if ((conn->fs_capabilities & FILE_NAMED_STREAMS) &&
5411 is_ntfs_stream_smb_fname(smb_fname)) {
5412 status = NT_STATUS_OBJECT_PATH_NOT_FOUND;
5417 we need to handle the case when we get a
5418 relative open relative to a file and the
5419 pathname is blank - this is a reopen!
5420 (hint from demyn plantenberg)
5423 status = NT_STATUS_INVALID_HANDLE;
5427 if (ISDOT(dir_fsp->fsp_name->base_name)) {
5429 * We're at the toplevel dir, the final file name
5430 * must not contain ./, as this is filtered out
5431 * normally by srvstr_get_path and unix_convert
5432 * explicitly rejects paths containing ./.
5434 parent_fname = talloc_strdup(talloc_tos(), "");
5435 if (parent_fname == NULL) {
5436 status = NT_STATUS_NO_MEMORY;
5440 size_t dir_name_len = strlen(dir_fsp->fsp_name->base_name);
5443 * Copy in the base directory name.
5446 parent_fname = talloc_array(talloc_tos(), char,
5448 if (parent_fname == NULL) {
5449 status = NT_STATUS_NO_MEMORY;
5452 memcpy(parent_fname, dir_fsp->fsp_name->base_name,
5456 * Ensure it ends in a '/'.
5457 * We used TALLOC_SIZE +2 to add space for the '/'.
5461 && (parent_fname[dir_name_len-1] != '\\')
5462 && (parent_fname[dir_name_len-1] != '/')) {
5463 parent_fname[dir_name_len] = '/';
5464 parent_fname[dir_name_len+1] = '\0';
5468 new_base_name = talloc_asprintf(talloc_tos(), "%s%s", parent_fname,
5469 smb_fname->base_name);
5470 if (new_base_name == NULL) {
5471 status = NT_STATUS_NO_MEMORY;
5475 status = filename_convert(req,
5482 if (!NT_STATUS_IS_OK(status)) {
5487 TALLOC_FREE(parent_fname);
5488 TALLOC_FREE(new_base_name);
5492 NTSTATUS create_file_default(connection_struct *conn,
5493 struct smb_request *req,
5494 uint16_t root_dir_fid,
5495 struct smb_filename *smb_fname,
5496 uint32_t access_mask,
5497 uint32_t share_access,
5498 uint32_t create_disposition,
5499 uint32_t create_options,
5500 uint32_t file_attributes,
5501 uint32_t oplock_request,
5502 const struct smb2_lease *lease,
5503 uint64_t allocation_size,
5504 uint32_t private_flags,
5505 struct security_descriptor *sd,
5506 struct ea_list *ea_list,
5507 files_struct **result,
5509 const struct smb2_create_blobs *in_context_blobs,
5510 struct smb2_create_blobs *out_context_blobs)
5512 int info = FILE_WAS_OPENED;
5513 files_struct *fsp = NULL;
5515 bool stream_name = false;
5517 DBG_DEBUG("create_file: access_mask = 0x%x "
5518 "file_attributes = 0x%x, share_access = 0x%x, "
5519 "create_disposition = 0x%x create_options = 0x%x "
5520 "oplock_request = 0x%x "
5521 "private_flags = 0x%x "
5522 "root_dir_fid = 0x%x, ea_list = %p, sd = %p, "
5524 (unsigned int)access_mask,
5525 (unsigned int)file_attributes,
5526 (unsigned int)share_access,
5527 (unsigned int)create_disposition,
5528 (unsigned int)create_options,
5529 (unsigned int)oplock_request,
5530 (unsigned int)private_flags,
5531 (unsigned int)root_dir_fid,
5532 ea_list, sd, smb_fname_str_dbg(smb_fname));
5536 * Remember the absolute time of the original request
5537 * with this mid. We'll use it later to see if this
5540 get_deferred_open_message_state(req, &req->request_time, NULL);
5544 * Calculate the filename from the root_dir_if if necessary.
5547 if (root_dir_fid != 0) {
5548 struct smb_filename *smb_fname_out = NULL;
5549 status = get_relative_fid_filename(conn, req, root_dir_fid,
5550 smb_fname, &smb_fname_out);
5551 if (!NT_STATUS_IS_OK(status)) {
5554 smb_fname = smb_fname_out;
5558 * Check to see if this is a mac fork of some kind.
5561 stream_name = is_ntfs_stream_smb_fname(smb_fname);
5563 enum FAKE_FILE_TYPE fake_file_type;
5565 fake_file_type = is_fake_file(smb_fname);
5567 if (fake_file_type != FAKE_FILE_TYPE_NONE) {
5570 * Here we go! support for changing the disk quotas
5573 * We need to fake up to open this MAGIC QUOTA file
5574 * and return a valid FID.
5576 * w2k close this file directly after openening xp
5577 * also tries a QUERY_FILE_INFO on the file and then
5580 status = open_fake_file(req, conn, req->vuid,
5581 fake_file_type, smb_fname,
5583 if (!NT_STATUS_IS_OK(status)) {
5587 ZERO_STRUCT(smb_fname->st);
5591 if (!(conn->fs_capabilities & FILE_NAMED_STREAMS)) {
5592 status = NT_STATUS_OBJECT_NAME_NOT_FOUND;
5597 if (is_ntfs_default_stream_smb_fname(smb_fname)) {
5599 smb_fname->stream_name = NULL;
5600 /* We have to handle this error here. */
5601 if (create_options & FILE_DIRECTORY_FILE) {
5602 status = NT_STATUS_NOT_A_DIRECTORY;
5605 if (req != NULL && req->posix_pathnames) {
5606 ret = SMB_VFS_LSTAT(conn, smb_fname);
5608 ret = SMB_VFS_STAT(conn, smb_fname);
5611 if (ret == 0 && VALID_STAT_OF_DIR(smb_fname->st)) {
5612 status = NT_STATUS_FILE_IS_A_DIRECTORY;
5617 status = create_file_unixpath(
5618 conn, req, smb_fname, access_mask, share_access,
5619 create_disposition, create_options, file_attributes,
5620 oplock_request, lease, allocation_size, private_flags,
5624 if (!NT_STATUS_IS_OK(status)) {
5629 DEBUG(10, ("create_file: info=%d\n", info));
5632 if (pinfo != NULL) {
5635 return NT_STATUS_OK;
5638 DEBUG(10, ("create_file: %s\n", nt_errstr(status)));
5641 close_file(req, fsp, ERROR_CLOSE);