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 * For the samba kernel oplock case we use both a timeout and
62 * a watch on locking.tdb. This way in case it's smbd holding
63 * the kernel oplock we get directly notified for the retry
64 * once the kernel oplock is properly broken. Store the req
65 * here so that it can be timely discarded once the timer
68 struct tevent_req *watch_req;
71 /****************************************************************************
72 If the requester wanted DELETE_ACCESS and was rejected because
73 the file ACL didn't include DELETE_ACCESS, see if the parent ACL
75 ****************************************************************************/
77 static bool parent_override_delete(connection_struct *conn,
78 const struct smb_filename *smb_fname,
80 uint32_t rejected_mask)
82 if ((access_mask & DELETE_ACCESS) &&
83 (rejected_mask & DELETE_ACCESS) &&
84 can_delete_file_in_directory(conn,
93 /****************************************************************************
94 Check if we have open rights.
95 ****************************************************************************/
97 NTSTATUS smbd_check_access_rights(struct connection_struct *conn,
98 struct files_struct *dirfsp,
99 const struct smb_filename *smb_fname,
101 uint32_t access_mask)
103 /* Check if we have rights to open. */
105 struct security_descriptor *sd = NULL;
106 uint32_t rejected_share_access;
107 uint32_t rejected_mask = access_mask;
108 uint32_t do_not_check_mask = 0;
110 SMB_ASSERT(dirfsp == conn->cwd_fsp);
112 rejected_share_access = access_mask & ~(conn->share_access);
114 if (rejected_share_access) {
115 DEBUG(10, ("smbd_check_access_rights: rejected share access 0x%x "
117 (unsigned int)access_mask,
118 smb_fname_str_dbg(smb_fname),
119 (unsigned int)rejected_share_access ));
120 return NT_STATUS_ACCESS_DENIED;
123 if (!use_privs && get_current_uid(conn) == (uid_t)0) {
124 /* I'm sorry sir, I didn't know you were root... */
125 DEBUG(10,("smbd_check_access_rights: root override "
126 "on %s. Granting 0x%x\n",
127 smb_fname_str_dbg(smb_fname),
128 (unsigned int)access_mask ));
132 if ((access_mask & DELETE_ACCESS) && !lp_acl_check_permissions(SNUM(conn))) {
133 DEBUG(10,("smbd_check_access_rights: not checking ACL "
134 "on DELETE_ACCESS on file %s. Granting 0x%x\n",
135 smb_fname_str_dbg(smb_fname),
136 (unsigned int)access_mask ));
140 if (access_mask == DELETE_ACCESS &&
141 VALID_STAT(smb_fname->st) &&
142 S_ISLNK(smb_fname->st.st_ex_mode)) {
143 /* We can always delete a symlink. */
144 DEBUG(10,("smbd_check_access_rights: not checking ACL "
145 "on DELETE_ACCESS on symlink %s.\n",
146 smb_fname_str_dbg(smb_fname) ));
150 status = SMB_VFS_GET_NT_ACL(conn, smb_fname,
153 SECINFO_DACL), talloc_tos(), &sd);
155 if (!NT_STATUS_IS_OK(status)) {
156 DEBUG(10, ("smbd_check_access_rights: Could not get acl "
158 smb_fname_str_dbg(smb_fname),
161 if (NT_STATUS_EQUAL(status, NT_STATUS_ACCESS_DENIED)) {
169 * If we can access the path to this file, by
170 * default we have FILE_READ_ATTRIBUTES from the
171 * containing directory. See the section:
172 * "Algorithm to Check Access to an Existing File"
175 * se_file_access_check() also takes care of
176 * owner WRITE_DAC and READ_CONTROL.
178 do_not_check_mask = FILE_READ_ATTRIBUTES;
181 * Samba 3.6 and earlier granted execute access even
182 * if the ACL did not contain execute rights.
183 * Samba 4.0 is more correct and checks it.
184 * The compatibilty mode allows one to skip this check
185 * to smoothen upgrades.
187 if (lp_acl_allow_execute_always(SNUM(conn))) {
188 do_not_check_mask |= FILE_EXECUTE;
191 status = se_file_access_check(sd,
192 get_current_nttok(conn),
194 (access_mask & ~do_not_check_mask),
197 DEBUG(10,("smbd_check_access_rights: file %s requesting "
198 "0x%x returning 0x%x (%s)\n",
199 smb_fname_str_dbg(smb_fname),
200 (unsigned int)access_mask,
201 (unsigned int)rejected_mask,
202 nt_errstr(status) ));
204 if (!NT_STATUS_IS_OK(status)) {
205 if (DEBUGLEVEL >= 10) {
206 DEBUG(10,("smbd_check_access_rights: acl for %s is:\n",
207 smb_fname_str_dbg(smb_fname) ));
208 NDR_PRINT_DEBUG(security_descriptor, sd);
214 if (NT_STATUS_IS_OK(status) ||
215 !NT_STATUS_EQUAL(status, NT_STATUS_ACCESS_DENIED)) {
219 /* Here we know status == NT_STATUS_ACCESS_DENIED. */
223 if ((access_mask & FILE_WRITE_ATTRIBUTES) &&
224 (rejected_mask & FILE_WRITE_ATTRIBUTES) &&
225 !lp_store_dos_attributes(SNUM(conn)) &&
226 (lp_map_readonly(SNUM(conn)) ||
227 lp_map_archive(SNUM(conn)) ||
228 lp_map_hidden(SNUM(conn)) ||
229 lp_map_system(SNUM(conn)))) {
230 rejected_mask &= ~FILE_WRITE_ATTRIBUTES;
232 DEBUG(10,("smbd_check_access_rights: "
234 "FILE_WRITE_ATTRIBUTES "
236 smb_fname_str_dbg(smb_fname)));
239 if (parent_override_delete(conn,
243 /* Were we trying to do an open
244 * for delete and didn't get DELETE
245 * access (only) ? Check if the
246 * directory allows DELETE_CHILD.
248 * http://blogs.msdn.com/oldnewthing/archive/2004/06/04/148426.aspx
251 rejected_mask &= ~DELETE_ACCESS;
253 DEBUG(10,("smbd_check_access_rights: "
257 smb_fname_str_dbg(smb_fname)));
260 if (rejected_mask != 0) {
261 return NT_STATUS_ACCESS_DENIED;
266 NTSTATUS check_parent_access(struct connection_struct *conn,
267 struct files_struct *dirfsp,
268 struct smb_filename *smb_fname,
269 uint32_t access_mask)
272 struct security_descriptor *parent_sd = NULL;
273 uint32_t access_granted = 0;
274 struct smb_filename *parent_dir = NULL;
275 struct share_mode_lock *lck = NULL;
276 struct file_id id = {0};
278 bool delete_on_close_set;
280 TALLOC_CTX *frame = talloc_stackframe();
284 * NB. When dirfsp != conn->cwd_fsp, we must
285 * change parent_dir to be "." for the name here.
288 SMB_ASSERT(dirfsp == conn->cwd_fsp);
290 ok = parent_smb_fname(frame, smb_fname, &parent_dir, NULL);
292 status = NT_STATUS_NO_MEMORY;
296 if (get_current_uid(conn) == (uid_t)0) {
297 /* I'm sorry sir, I didn't know you were root... */
298 DEBUG(10,("check_parent_access: root override "
299 "on %s. Granting 0x%x\n",
300 smb_fname_str_dbg(smb_fname),
301 (unsigned int)access_mask ));
302 status = NT_STATUS_OK;
306 status = SMB_VFS_GET_NT_ACL(conn,
312 if (!NT_STATUS_IS_OK(status)) {
313 DEBUG(5,("check_parent_access: SMB_VFS_GET_NT_ACL failed for "
314 "%s with error %s\n",
315 smb_fname_str_dbg(parent_dir),
321 * If we can access the path to this file, by
322 * default we have FILE_READ_ATTRIBUTES from the
323 * containing directory. See the section:
324 * "Algorithm to Check Access to an Existing File"
327 * se_file_access_check() also takes care of
328 * owner WRITE_DAC and READ_CONTROL.
330 status = se_file_access_check(parent_sd,
331 get_current_nttok(conn),
333 (access_mask & ~FILE_READ_ATTRIBUTES),
335 if(!NT_STATUS_IS_OK(status)) {
336 DEBUG(5,("check_parent_access: access check "
337 "on directory %s for "
338 "path %s for mask 0x%x returned (0x%x) %s\n",
339 smb_fname_str_dbg(parent_dir),
340 smb_fname->base_name,
343 nt_errstr(status) ));
347 if (!(access_mask & (SEC_DIR_ADD_FILE | SEC_DIR_ADD_SUBDIR))) {
348 status = NT_STATUS_OK;
351 if (!lp_check_parent_directory_delete_on_close(SNUM(conn))) {
352 status = NT_STATUS_OK;
356 /* Check if the directory has delete-on-close set */
357 ret = SMB_VFS_STAT(conn, parent_dir);
359 status = map_nt_error_from_unix(errno);
363 id = SMB_VFS_FILE_ID_CREATE(conn, &parent_dir->st);
365 status = file_name_hash(conn, parent_dir->base_name, &name_hash);
366 if (!NT_STATUS_IS_OK(status)) {
370 lck = get_existing_share_mode_lock(frame, id);
372 status = NT_STATUS_OK;
376 delete_on_close_set = is_delete_on_close_set(lck, name_hash);
377 if (delete_on_close_set) {
378 status = NT_STATUS_DELETE_PENDING;
382 status = NT_STATUS_OK;
389 /****************************************************************************
390 Ensure when opening a base file for a stream open that we have permissions
391 to do so given the access mask on the base file.
392 ****************************************************************************/
394 static NTSTATUS check_base_file_access(struct connection_struct *conn,
395 struct smb_filename *smb_fname,
396 uint32_t access_mask)
400 status = smbd_calculate_access_mask(conn,
406 if (!NT_STATUS_IS_OK(status)) {
407 DEBUG(10, ("smbd_calculate_access_mask "
408 "on file %s returned %s\n",
409 smb_fname_str_dbg(smb_fname),
414 if (access_mask & (FILE_WRITE_DATA|FILE_APPEND_DATA)) {
416 if (!CAN_WRITE(conn)) {
417 return NT_STATUS_ACCESS_DENIED;
419 dosattrs = dos_mode(conn, smb_fname);
420 if (IS_DOS_READONLY(dosattrs)) {
421 return NT_STATUS_ACCESS_DENIED;
425 return smbd_check_access_rights(conn,
432 /****************************************************************************
433 Handle differing symlink errno's
434 ****************************************************************************/
436 static int link_errno_convert(int err)
438 #if defined(ENOTSUP) && defined(OSF1)
439 /* handle special Tru64 errno */
440 if (err == ENOTSUP) {
445 /* fix broken NetBSD errno */
450 /* fix broken FreeBSD errno */
457 static int non_widelink_open(struct connection_struct *conn,
458 const struct smb_filename *conn_rootdir_fname,
460 struct smb_filename *smb_fname,
463 unsigned int link_depth);
465 /****************************************************************************
466 Follow a symlink in userspace.
467 ****************************************************************************/
469 static int process_symlink_open(struct connection_struct *conn,
470 const struct smb_filename *conn_rootdir_fname,
472 struct smb_filename *smb_fname,
475 unsigned int link_depth)
478 char *link_target = NULL;
479 struct smb_filename target_fname = {0};
481 struct smb_filename *oldwd_fname = NULL;
482 size_t rootdir_len = 0;
483 struct smb_filename *resolved_fname = NULL;
484 char *resolved_name = NULL;
485 bool matched = false;
489 * Ensure we don't get stuck in a symlink loop.
492 if (link_depth >= 20) {
497 /* Allocate space for the link target. */
498 link_target = talloc_array(talloc_tos(), char, PATH_MAX);
499 if (link_target == NULL) {
504 /* Read the link target. */
505 link_len = SMB_VFS_READLINKAT(conn,
510 if (link_len == -1) {
514 /* Ensure it's at least null terminated. */
515 link_target[link_len] = '\0';
516 target_fname = (struct smb_filename){ .base_name = link_target };
518 /* Convert to an absolute path. */
519 resolved_fname = SMB_VFS_REALPATH(conn, talloc_tos(), &target_fname);
520 if (resolved_fname == NULL) {
523 resolved_name = resolved_fname->base_name;
526 * We know conn_rootdir starts with '/' and
527 * does not end in '/'. FIXME ! Should we
530 rootdir_len = strlen(conn_rootdir_fname->base_name);
532 matched = (strncmp(conn_rootdir_fname->base_name,
541 * Turn into a path relative to the share root.
543 if (resolved_name[rootdir_len] == '\0') {
544 /* Link to the root of the share. */
545 TALLOC_FREE(smb_fname->base_name);
546 smb_fname->base_name = talloc_strdup(smb_fname, ".");
547 } else if (resolved_name[rootdir_len] == '/') {
548 TALLOC_FREE(smb_fname->base_name);
549 smb_fname->base_name = talloc_strdup(smb_fname,
550 &resolved_name[rootdir_len+1]);
556 if (smb_fname->base_name == NULL) {
561 oldwd_fname = vfs_GetWd(talloc_tos(), conn);
562 if (oldwd_fname == NULL) {
566 /* Ensure we operate from the root of the share. */
567 if (vfs_ChDir(conn, conn_rootdir_fname) == -1) {
571 /* And do it all again.. */
572 fd = non_widelink_open(conn,
585 TALLOC_FREE(resolved_fname);
586 TALLOC_FREE(link_target);
587 if (oldwd_fname != NULL) {
588 int ret = vfs_ChDir(conn, oldwd_fname);
590 smb_panic("unable to get back to old directory\n");
592 TALLOC_FREE(oldwd_fname);
594 if (saved_errno != 0) {
600 /****************************************************************************
602 ****************************************************************************/
604 static int non_widelink_open(struct connection_struct *conn,
605 const struct smb_filename *conn_rootdir_fname,
607 struct smb_filename *smb_fname,
610 unsigned int link_depth)
614 struct smb_filename *smb_fname_rel = NULL;
616 struct smb_filename *oldwd_fname = NULL;
617 struct smb_filename *parent_dir_fname = NULL;
620 if (fsp->fsp_flags.is_directory) {
621 parent_dir_fname = cp_smb_filename(talloc_tos(), smb_fname);
622 if (parent_dir_fname == NULL) {
627 smb_fname_rel = synthetic_smb_fname(parent_dir_fname,
629 smb_fname->stream_name,
633 if (smb_fname_rel == NULL) {
638 ok = parent_smb_fname(talloc_tos(),
648 oldwd_fname = vfs_GetWd(talloc_tos(), conn);
649 if (oldwd_fname == NULL) {
653 /* Pin parent directory in place. */
654 if (vfs_ChDir(conn, parent_dir_fname) == -1) {
658 /* Ensure the relative path is below the share. */
659 status = check_reduced_name(conn, parent_dir_fname, smb_fname_rel);
660 if (!NT_STATUS_IS_OK(status)) {
661 saved_errno = map_errno_from_nt_status(status);
668 struct smb_filename *tmp_name = fsp->fsp_name;
669 fsp->fsp_name = smb_fname_rel;
670 fd = SMB_VFS_OPEN(conn, smb_fname_rel, fsp, flags, mode);
671 fsp->fsp_name = tmp_name;
675 saved_errno = link_errno_convert(errno);
677 * Trying to open a symlink to a directory with O_NOFOLLOW and
678 * O_DIRECTORY can return either of ELOOP and ENOTDIR. So
679 * ENOTDIR really means: might be a symlink, but we're not sure.
680 * In this case, we just assume there's a symlink. If we were
681 * wrong, process_symlink_open() will return EINVAL. We check
682 * this below, and fall back to returning the initial
685 * BUG: https://bugzilla.samba.org/show_bug.cgi?id=12860
687 if (saved_errno == ELOOP || saved_errno == ENOTDIR) {
688 if (fsp->posix_flags & FSP_POSIX_FLAGS_OPEN) {
689 /* Never follow symlinks on posix open. */
692 if (!lp_follow_symlinks(SNUM(conn))) {
693 /* Explicitly no symlinks. */
697 * We may have a symlink. Follow in userspace
698 * to ensure it's under the share definition.
700 fd = process_symlink_open(conn,
708 if (saved_errno == ENOTDIR &&
711 * O_DIRECTORY on neither a directory,
712 * nor a symlink. Just return
713 * saved_errno from initial open()
718 link_errno_convert(errno);
725 TALLOC_FREE(parent_dir_fname);
727 if (oldwd_fname != NULL) {
728 int ret = vfs_ChDir(conn, oldwd_fname);
730 smb_panic("unable to get back to old directory\n");
732 TALLOC_FREE(oldwd_fname);
734 if (saved_errno != 0) {
740 /****************************************************************************
741 fd support routines - attempt to do a dos_open.
742 ****************************************************************************/
744 NTSTATUS fd_open(struct connection_struct *conn,
749 struct smb_filename *smb_fname = fsp->fsp_name;
750 NTSTATUS status = NT_STATUS_OK;
751 struct smb_filename *conn_rootdir_fname = NULL;
752 const char *conn_rootdir;
756 * Never follow symlinks on a POSIX client. The
757 * client should be doing this.
760 if ((fsp->posix_flags & FSP_POSIX_FLAGS_OPEN) || !lp_follow_symlinks(SNUM(conn))) {
764 /* Ensure path is below share definition. */
765 conn_rootdir = SMB_VFS_CONNECTPATH(conn,
768 if (conn_rootdir == NULL) {
769 return NT_STATUS_NO_MEMORY;
771 conn_rootdir_fname = synthetic_smb_fname(talloc_tos(),
777 if (conn_rootdir_fname == NULL) {
778 return NT_STATUS_NO_MEMORY;
782 * Only follow symlinks within a share
785 fsp->fh->fd = non_widelink_open(conn,
792 if (fsp->fh->fd == -1) {
795 TALLOC_FREE(conn_rootdir_fname);
796 if (saved_errno != 0) {
800 if (fsp->fh->fd == -1) {
801 int posix_errno = link_errno_convert(errno);
802 status = map_nt_error_from_unix(posix_errno);
803 if (errno == EMFILE) {
804 static time_t last_warned = 0L;
806 if (time((time_t *) NULL) > last_warned) {
807 DEBUG(0,("Too many open files, unable "
808 "to open more! smbd's max "
810 lp_max_open_files()));
811 last_warned = time((time_t *) NULL);
817 DEBUG(10,("fd_open: name %s, flags = 0%o mode = 0%o, fd = %d. %s\n",
818 smb_fname_str_dbg(smb_fname), flags, (int)mode, fsp->fh->fd,
819 (fsp->fh->fd == -1) ? strerror(errno) : "" ));
824 /****************************************************************************
825 Close the file associated with a fsp.
826 ****************************************************************************/
828 NTSTATUS fd_close(files_struct *fsp)
835 if (fsp->fh->fd == -1) {
837 * Either a directory where the dptr_CloseDir() already closed
838 * the fd or a stat open.
842 if (fsp->fh->ref_count > 1) {
843 return NT_STATUS_OK; /* Shared handle. Only close last reference. */
846 ret = SMB_VFS_CLOSE(fsp);
849 return map_nt_error_from_unix(errno);
854 /****************************************************************************
855 Change the ownership of a file to that of the parent directory.
856 Do this by fd if possible.
857 ****************************************************************************/
859 void change_file_owner_to_parent(connection_struct *conn,
860 struct smb_filename *smb_fname_parent,
865 ret = SMB_VFS_STAT(conn, smb_fname_parent);
867 DEBUG(0,("change_file_owner_to_parent: failed to stat parent "
868 "directory %s. Error was %s\n",
869 smb_fname_str_dbg(smb_fname_parent),
871 TALLOC_FREE(smb_fname_parent);
875 if (smb_fname_parent->st.st_ex_uid == fsp->fsp_name->st.st_ex_uid) {
876 /* Already this uid - no need to change. */
877 DEBUG(10,("change_file_owner_to_parent: file %s "
878 "is already owned by uid %d\n",
880 (int)fsp->fsp_name->st.st_ex_uid ));
881 TALLOC_FREE(smb_fname_parent);
886 ret = SMB_VFS_FCHOWN(fsp, smb_fname_parent->st.st_ex_uid, (gid_t)-1);
889 DEBUG(0,("change_file_owner_to_parent: failed to fchown "
890 "file %s to parent directory uid %u. Error "
891 "was %s\n", fsp_str_dbg(fsp),
892 (unsigned int)smb_fname_parent->st.st_ex_uid,
895 DEBUG(10,("change_file_owner_to_parent: changed new file %s to "
896 "parent directory uid %u.\n", fsp_str_dbg(fsp),
897 (unsigned int)smb_fname_parent->st.st_ex_uid));
898 /* Ensure the uid entry is updated. */
899 fsp->fsp_name->st.st_ex_uid = smb_fname_parent->st.st_ex_uid;
903 static NTSTATUS change_dir_owner_to_parent(connection_struct *conn,
904 struct smb_filename *smb_fname_parent,
905 struct smb_filename *smb_dname,
906 SMB_STRUCT_STAT *psbuf)
908 struct smb_filename *smb_fname_cwd = NULL;
909 struct smb_filename *saved_dir_fname = NULL;
910 TALLOC_CTX *ctx = talloc_tos();
911 NTSTATUS status = NT_STATUS_OK;
914 ret = SMB_VFS_STAT(conn, smb_fname_parent);
916 status = map_nt_error_from_unix(errno);
917 DEBUG(0,("change_dir_owner_to_parent: failed to stat parent "
918 "directory %s. Error was %s\n",
919 smb_fname_str_dbg(smb_fname_parent),
924 /* We've already done an lstat into psbuf, and we know it's a
925 directory. If we can cd into the directory and the dev/ino
926 are the same then we can safely chown without races as
927 we're locking the directory in place by being in it. This
928 should work on any UNIX (thanks tridge :-). JRA.
931 saved_dir_fname = vfs_GetWd(ctx,conn);
932 if (!saved_dir_fname) {
933 status = map_nt_error_from_unix(errno);
934 DEBUG(0,("change_dir_owner_to_parent: failed to get "
935 "current working directory. Error was %s\n",
940 /* Chdir into the new path. */
941 if (vfs_ChDir(conn, smb_dname) == -1) {
942 status = map_nt_error_from_unix(errno);
943 DEBUG(0,("change_dir_owner_to_parent: failed to change "
944 "current working directory to %s. Error "
945 "was %s\n", smb_dname->base_name, strerror(errno) ));
949 smb_fname_cwd = synthetic_smb_fname(ctx,
955 if (smb_fname_cwd == NULL) {
956 status = NT_STATUS_NO_MEMORY;
960 ret = SMB_VFS_STAT(conn, smb_fname_cwd);
962 status = map_nt_error_from_unix(errno);
963 DEBUG(0,("change_dir_owner_to_parent: failed to stat "
964 "directory '.' (%s) Error was %s\n",
965 smb_dname->base_name, strerror(errno)));
969 /* Ensure we're pointing at the same place. */
970 if (smb_fname_cwd->st.st_ex_dev != psbuf->st_ex_dev ||
971 smb_fname_cwd->st.st_ex_ino != psbuf->st_ex_ino) {
972 DEBUG(0,("change_dir_owner_to_parent: "
973 "device/inode on directory %s changed. "
974 "Refusing to chown !\n",
975 smb_dname->base_name ));
976 status = NT_STATUS_ACCESS_DENIED;
980 if (smb_fname_parent->st.st_ex_uid == smb_fname_cwd->st.st_ex_uid) {
981 /* Already this uid - no need to change. */
982 DEBUG(10,("change_dir_owner_to_parent: directory %s "
983 "is already owned by uid %d\n",
984 smb_dname->base_name,
985 (int)smb_fname_cwd->st.st_ex_uid ));
986 status = NT_STATUS_OK;
991 ret = SMB_VFS_LCHOWN(conn,
993 smb_fname_parent->st.st_ex_uid,
997 status = map_nt_error_from_unix(errno);
998 DEBUG(10,("change_dir_owner_to_parent: failed to chown "
999 "directory %s to parent directory uid %u. "
1001 smb_dname->base_name,
1002 (unsigned int)smb_fname_parent->st.st_ex_uid,
1005 DEBUG(10,("change_dir_owner_to_parent: changed ownership of new "
1006 "directory %s to parent directory uid %u.\n",
1007 smb_dname->base_name,
1008 (unsigned int)smb_fname_parent->st.st_ex_uid ));
1009 /* Ensure the uid entry is updated. */
1010 psbuf->st_ex_uid = smb_fname_parent->st.st_ex_uid;
1014 vfs_ChDir(conn, saved_dir_fname);
1016 TALLOC_FREE(saved_dir_fname);
1017 TALLOC_FREE(smb_fname_cwd);
1021 /****************************************************************************
1022 Open a file - returning a guaranteed ATOMIC indication of if the
1023 file was created or not.
1024 ****************************************************************************/
1026 static NTSTATUS fd_open_atomic(struct connection_struct *conn,
1032 NTSTATUS status = NT_STATUS_UNSUCCESSFUL;
1033 NTSTATUS retry_status;
1034 bool file_existed = VALID_STAT(fsp->fsp_name->st);
1037 if (!(flags & O_CREAT)) {
1039 * We're not creating the file, just pass through.
1041 status = fd_open(conn, fsp, flags, mode);
1042 *file_created = false;
1046 if (flags & O_EXCL) {
1048 * Fail if already exists, just pass through.
1050 status = fd_open(conn, fsp, flags, mode);
1053 * Here we've opened with O_CREAT|O_EXCL. If that went
1054 * NT_STATUS_OK, we *know* we created this file.
1056 *file_created = NT_STATUS_IS_OK(status);
1062 * Now it gets tricky. We have O_CREAT, but not O_EXCL.
1063 * To know absolutely if we created the file or not,
1064 * we can never call O_CREAT without O_EXCL. So if
1065 * we think the file existed, try without O_CREAT|O_EXCL.
1066 * If we think the file didn't exist, try with
1069 * The big problem here is dangling symlinks. Opening
1070 * without O_NOFOLLOW means both bad symlink
1071 * and missing path return -1, ENOENT from open(). As POSIX
1072 * is pathname based it's not possible to tell
1073 * the difference between these two cases in a
1074 * non-racy way, so change to try only two attempts before
1077 * We don't have this problem for the O_NOFOLLOW
1078 * case as it just returns NT_STATUS_OBJECT_PATH_NOT_FOUND
1079 * mapped from the ELOOP POSIX error.
1083 curr_flags = flags & ~(O_CREAT);
1084 retry_status = NT_STATUS_OBJECT_NAME_NOT_FOUND;
1086 curr_flags = flags | O_EXCL;
1087 retry_status = NT_STATUS_OBJECT_NAME_COLLISION;
1090 status = fd_open(conn, fsp, curr_flags, mode);
1091 if (NT_STATUS_IS_OK(status)) {
1092 *file_created = !file_existed;
1093 return NT_STATUS_OK;
1095 if (NT_STATUS_EQUAL(status, retry_status)) {
1097 file_existed = !file_existed;
1099 DBG_DEBUG("File %s %s. Retry.\n",
1101 file_existed ? "existed" : "did not exist");
1104 curr_flags = flags & ~(O_CREAT);
1106 curr_flags = flags | O_EXCL;
1109 status = fd_open(conn, fsp, curr_flags, mode);
1112 *file_created = (NT_STATUS_IS_OK(status) && !file_existed);
1116 /****************************************************************************
1118 ****************************************************************************/
1120 static NTSTATUS open_file(files_struct *fsp,
1121 connection_struct *conn,
1122 struct smb_request *req,
1123 struct smb_filename *parent_dir,
1126 uint32_t access_mask, /* client requested access mask. */
1127 uint32_t open_access_mask, /* what we're actually using in the open. */
1128 bool *p_file_created)
1130 struct smb_filename *smb_fname = fsp->fsp_name;
1131 NTSTATUS status = NT_STATUS_OK;
1132 int accmode = (flags & O_ACCMODE);
1133 int local_flags = flags;
1134 bool file_existed = VALID_STAT(fsp->fsp_name->st);
1135 uint32_t need_fd_mask =
1141 WRITE_OWNER_ACCESS |
1142 SEC_FLAG_SYSTEM_SECURITY |
1143 READ_CONTROL_ACCESS;
1144 bool creating = !file_existed && (flags & O_CREAT);
1145 bool truncating = (flags & O_TRUNC);
1150 /* Check permissions */
1153 * This code was changed after seeing a client open request
1154 * containing the open mode of (DENY_WRITE/read-only) with
1155 * the 'create if not exist' bit set. The previous code
1156 * would fail to open the file read only on a read-only share
1157 * as it was checking the flags parameter directly against O_RDONLY,
1158 * this was failing as the flags parameter was set to O_RDONLY|O_CREAT.
1162 if (!CAN_WRITE(conn)) {
1163 /* It's a read-only share - fail if we wanted to write. */
1164 if(accmode != O_RDONLY || (flags & O_TRUNC) || (flags & O_APPEND)) {
1165 DEBUG(3,("Permission denied opening %s\n",
1166 smb_fname_str_dbg(smb_fname)));
1167 return NT_STATUS_ACCESS_DENIED;
1169 if (flags & O_CREAT) {
1170 /* We don't want to write - but we must make sure that
1171 O_CREAT doesn't create the file if we have write
1172 access into the directory.
1174 flags &= ~(O_CREAT|O_EXCL);
1175 local_flags &= ~(O_CREAT|O_EXCL);
1180 * This little piece of insanity is inspired by the
1181 * fact that an NT client can open a file for O_RDONLY,
1182 * but set the create disposition to FILE_EXISTS_TRUNCATE.
1183 * If the client *can* write to the file, then it expects to
1184 * truncate the file, even though it is opening for readonly.
1185 * Quicken uses this stupid trick in backup file creation...
1186 * Thanks *greatly* to "David W. Chapman Jr." <dwcjr@inethouston.net>
1187 * for helping track this one down. It didn't bite us in 2.0.x
1188 * as we always opened files read-write in that release. JRA.
1191 if ((accmode == O_RDONLY) && ((flags & O_TRUNC) == O_TRUNC)) {
1192 DEBUG(10,("open_file: truncate requested on read-only open "
1193 "for file %s\n", smb_fname_str_dbg(smb_fname)));
1194 local_flags = (flags & ~O_ACCMODE)|O_RDWR;
1197 if ((open_access_mask & need_fd_mask) || creating || truncating) {
1201 #if defined(O_NONBLOCK) && defined(S_ISFIFO)
1203 * We would block on opening a FIFO with no one else on the
1204 * other end. Do what we used to do and add O_NONBLOCK to the
1208 if (file_existed && S_ISFIFO(smb_fname->st.st_ex_mode)) {
1209 local_flags &= ~O_TRUNC; /* Can't truncate a FIFO. */
1210 local_flags |= O_NONBLOCK;
1215 /* Don't create files with Microsoft wildcard characters. */
1216 if (fsp->base_fsp) {
1218 * wildcard characters are allowed in stream names
1219 * only test the basefilename
1221 wild = fsp->base_fsp->fsp_name->base_name;
1223 wild = smb_fname->base_name;
1225 if ((local_flags & O_CREAT) && !file_existed &&
1226 !(fsp->posix_flags & FSP_POSIX_FLAGS_PATHNAMES) &&
1227 ms_has_wild(wild)) {
1228 return NT_STATUS_OBJECT_NAME_INVALID;
1231 /* Can we access this file ? */
1232 if (!fsp->base_fsp) {
1233 /* Only do this check on non-stream open. */
1235 status = smbd_check_access_rights(conn,
1241 if (!NT_STATUS_IS_OK(status)) {
1242 DEBUG(10, ("open_file: "
1243 "smbd_check_access_rights "
1244 "on file %s returned %s\n",
1245 smb_fname_str_dbg(smb_fname),
1246 nt_errstr(status)));
1249 if (!NT_STATUS_IS_OK(status) &&
1250 !NT_STATUS_EQUAL(status,
1251 NT_STATUS_OBJECT_NAME_NOT_FOUND))
1256 if (NT_STATUS_EQUAL(status,
1257 NT_STATUS_OBJECT_NAME_NOT_FOUND))
1259 DEBUG(10, ("open_file: "
1260 "file %s vanished since we "
1261 "checked for existence.\n",
1262 smb_fname_str_dbg(smb_fname)));
1263 file_existed = false;
1264 SET_STAT_INVALID(fsp->fsp_name->st);
1268 if (!file_existed) {
1269 if (!(local_flags & O_CREAT)) {
1270 /* File didn't exist and no O_CREAT. */
1271 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
1274 status = check_parent_access(conn,
1278 if (!NT_STATUS_IS_OK(status)) {
1279 DEBUG(10, ("open_file: "
1280 "check_parent_access on "
1281 "file %s returned %s\n",
1282 smb_fname_str_dbg(smb_fname),
1283 nt_errstr(status) ));
1290 * Actually do the open - if O_TRUNC is needed handle it
1291 * below under the share mode lock.
1293 status = fd_open_atomic(conn, fsp, local_flags & ~O_TRUNC,
1294 unx_mode, p_file_created);
1295 if (!NT_STATUS_IS_OK(status)) {
1296 DEBUG(3,("Error opening file %s (%s) (local_flags=%d) "
1297 "(flags=%d)\n", smb_fname_str_dbg(smb_fname),
1298 nt_errstr(status),local_flags,flags));
1302 if (local_flags & O_NONBLOCK) {
1304 * GPFS can return ETIMEDOUT for pread on
1305 * nonblocking file descriptors when files
1306 * migrated to tape need to be recalled. I
1307 * could imagine this happens elsewhere
1308 * too. With blocking file descriptors this
1311 ret = vfs_set_blocking(fsp, true);
1313 status = map_nt_error_from_unix(errno);
1314 DBG_WARNING("Could not set fd to blocking: "
1315 "%s\n", strerror(errno));
1321 ret = SMB_VFS_FSTAT(fsp, &smb_fname->st);
1323 /* If we have an fd, this stat should succeed. */
1324 DEBUG(0,("Error doing fstat on open file %s "
1326 smb_fname_str_dbg(smb_fname),
1328 status = map_nt_error_from_unix(errno);
1333 if (*p_file_created) {
1334 /* We created this file. */
1336 bool need_re_stat = false;
1337 /* Do all inheritance work after we've
1338 done a successful fstat call and filled
1339 in the stat struct in fsp->fsp_name. */
1341 /* Inherit the ACL if required */
1342 if (lp_inherit_permissions(SNUM(conn))) {
1343 inherit_access_posix_acl(conn,
1347 need_re_stat = true;
1350 /* Change the owner if required. */
1351 if (lp_inherit_owner(SNUM(conn)) != INHERIT_OWNER_NO) {
1352 change_file_owner_to_parent(conn,
1355 need_re_stat = true;
1359 ret = SMB_VFS_FSTAT(fsp, &smb_fname->st);
1360 /* If we have an fd, this stat should succeed. */
1362 DEBUG(0,("Error doing fstat on open file %s "
1364 smb_fname_str_dbg(smb_fname),
1369 notify_fname(conn, NOTIFY_ACTION_ADDED,
1370 FILE_NOTIFY_CHANGE_FILE_NAME,
1371 smb_fname->base_name);
1374 fsp->fh->fd = -1; /* What we used to call a stat open. */
1375 if (!file_existed) {
1376 /* File must exist for a stat open. */
1377 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
1380 status = smbd_check_access_rights(conn,
1386 if (NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND) &&
1387 (fsp->posix_flags & FSP_POSIX_FLAGS_OPEN) &&
1388 S_ISLNK(smb_fname->st.st_ex_mode)) {
1389 /* This is a POSIX stat open for delete
1390 * or rename on a symlink that points
1391 * nowhere. Allow. */
1392 DEBUG(10,("open_file: allowing POSIX "
1393 "open on bad symlink %s\n",
1394 smb_fname_str_dbg(smb_fname)));
1395 status = NT_STATUS_OK;
1398 if (!NT_STATUS_IS_OK(status)) {
1399 DEBUG(10,("open_file: "
1400 "smbd_check_access_rights on file "
1402 smb_fname_str_dbg(smb_fname),
1403 nt_errstr(status) ));
1409 * POSIX allows read-only opens of directories. We don't
1410 * want to do this (we use a different code path for this)
1411 * so catch a directory open and return an EISDIR. JRA.
1414 if(S_ISDIR(smb_fname->st.st_ex_mode)) {
1417 return NT_STATUS_FILE_IS_A_DIRECTORY;
1420 fsp->file_id = vfs_file_id_from_sbuf(conn, &smb_fname->st);
1421 fsp->vuid = req ? req->vuid : UID_FIELD_INVALID;
1422 fsp->file_pid = req ? req->smbpid : 0;
1423 fsp->fsp_flags.can_lock = true;
1424 fsp->fsp_flags.can_read = ((access_mask & FILE_READ_DATA) != 0);
1425 fsp->fsp_flags.can_write =
1427 ((access_mask & (FILE_WRITE_DATA | FILE_APPEND_DATA)) != 0);
1428 fsp->print_file = NULL;
1429 fsp->fsp_flags.modified = false;
1430 fsp->sent_oplock_break = NO_BREAK_SENT;
1431 fsp->fsp_flags.is_directory = false;
1432 if (conn->aio_write_behind_list &&
1433 is_in_path(smb_fname->base_name, conn->aio_write_behind_list,
1434 conn->case_sensitive)) {
1435 fsp->fsp_flags.aio_write_behind = true;
1438 DEBUG(2,("%s opened file %s read=%s write=%s (numopen=%d)\n",
1439 conn->session_info->unix_info->unix_name,
1440 smb_fname_str_dbg(smb_fname),
1441 BOOLSTR(fsp->fsp_flags.can_read),
1442 BOOLSTR(fsp->fsp_flags.can_write),
1443 conn->num_files_open));
1446 return NT_STATUS_OK;
1449 static bool mask_conflict(
1450 uint32_t new_access,
1451 uint32_t existing_access,
1452 uint32_t access_mask,
1453 uint32_t new_sharemode,
1454 uint32_t existing_sharemode,
1455 uint32_t sharemode_mask)
1457 bool want_access = (new_access & access_mask);
1458 bool allow_existing = (existing_sharemode & sharemode_mask);
1459 bool have_access = (existing_access & access_mask);
1460 bool allow_new = (new_sharemode & sharemode_mask);
1462 if (want_access && !allow_existing) {
1463 DBG_DEBUG("Access request 0x%"PRIx32"/0x%"PRIx32" conflicts "
1464 "with existing sharemode 0x%"PRIx32"/0x%"PRIx32"\n",
1471 if (have_access && !allow_new) {
1472 DBG_DEBUG("Sharemode request 0x%"PRIx32"/0x%"PRIx32" conflicts "
1473 "with existing access 0x%"PRIx32"/0x%"PRIx32"\n",
1483 /****************************************************************************
1484 Check if we can open a file with a share mode.
1485 Returns True if conflict, False if not.
1486 ****************************************************************************/
1488 static bool share_conflict(uint32_t e_access_mask,
1489 uint32_t e_share_access,
1490 uint32_t access_mask,
1491 uint32_t share_access)
1493 const uint32_t conflicting_access =
1501 DBG_DEBUG("existing access_mask = 0x%"PRIx32", "
1502 "existing share access = 0x%"PRIx32", "
1503 "access_mask = 0x%"PRIx32", "
1504 "share_access = 0x%"PRIx32"\n",
1510 if ((e_access_mask & conflicting_access) == 0) {
1511 DBG_DEBUG("No conflict due to "
1512 "existing access_mask = 0x%"PRIx32"\n",
1516 if ((access_mask & conflicting_access) == 0) {
1517 DBG_DEBUG("No conflict due to access_mask = 0x%"PRIx32"\n",
1522 conflict = mask_conflict(
1523 access_mask, e_access_mask, FILE_WRITE_DATA | FILE_APPEND_DATA,
1524 share_access, e_share_access, FILE_SHARE_WRITE);
1525 conflict |= mask_conflict(
1526 access_mask, e_access_mask, FILE_READ_DATA | FILE_EXECUTE,
1527 share_access, e_share_access, FILE_SHARE_READ);
1528 conflict |= mask_conflict(
1529 access_mask, e_access_mask, DELETE_ACCESS,
1530 share_access, e_share_access, FILE_SHARE_DELETE);
1532 DBG_DEBUG("conflict=%s\n", conflict ? "true" : "false");
1536 #if defined(DEVELOPER)
1538 struct validate_my_share_entries_state {
1539 struct smbd_server_connection *sconn;
1541 struct server_id self;
1544 static bool validate_my_share_entries_fn(
1545 struct share_mode_entry *e,
1549 struct validate_my_share_entries_state *state = private_data;
1552 if (!server_id_equal(&state->self, &e->pid)) {
1556 if (e->op_mid == 0) {
1557 /* INTERNAL_OPEN_ONLY */
1561 fsp = file_find_dif(state->sconn, state->fid, e->share_file_id);
1563 DBG_ERR("PANIC : %s\n",
1564 share_mode_str(talloc_tos(), 0, &state->fid, e));
1565 smb_panic("validate_my_share_entries: Cannot match a "
1566 "share entry with an open file\n");
1569 if (((uint16_t)fsp->oplock_type) != e->op_type) {
1578 DBG_ERR("validate_my_share_entries: PANIC : %s\n",
1579 share_mode_str(talloc_tos(), 0, &state->fid, e));
1580 str = talloc_asprintf(talloc_tos(),
1581 "validate_my_share_entries: "
1582 "file %s, oplock_type = 0x%x, op_type = 0x%x\n",
1583 fsp->fsp_name->base_name,
1584 (unsigned int)fsp->oplock_type,
1585 (unsigned int)e->op_type);
1594 * Allowed access mask for stat opens relevant to oplocks
1596 bool is_oplock_stat_open(uint32_t access_mask)
1598 const uint32_t stat_open_bits =
1599 (SYNCHRONIZE_ACCESS|
1600 FILE_READ_ATTRIBUTES|
1601 FILE_WRITE_ATTRIBUTES);
1603 return (((access_mask & stat_open_bits) != 0) &&
1604 ((access_mask & ~stat_open_bits) == 0));
1608 * Allowed access mask for stat opens relevant to leases
1610 bool is_lease_stat_open(uint32_t access_mask)
1612 const uint32_t stat_open_bits =
1613 (SYNCHRONIZE_ACCESS|
1614 FILE_READ_ATTRIBUTES|
1615 FILE_WRITE_ATTRIBUTES|
1616 READ_CONTROL_ACCESS);
1618 return (((access_mask & stat_open_bits) != 0) &&
1619 ((access_mask & ~stat_open_bits) == 0));
1622 struct has_delete_on_close_state {
1626 static bool has_delete_on_close_fn(
1627 struct share_mode_entry *e,
1631 struct has_delete_on_close_state *state = private_data;
1632 state->ret = !share_entry_stale_pid(e);
1636 static bool has_delete_on_close(struct share_mode_lock *lck,
1639 struct has_delete_on_close_state state = { .ret = false };
1642 if (!is_delete_on_close_set(lck, name_hash)) {
1646 ok= share_mode_forall_entries(lck, has_delete_on_close_fn, &state);
1648 DBG_DEBUG("share_mode_forall_entries failed\n");
1654 static void share_mode_flags_get(
1656 uint32_t *access_mask,
1657 uint32_t *share_mode,
1658 uint32_t *lease_type)
1660 if (access_mask != NULL) {
1662 ((flags & SHARE_MODE_ACCESS_READ) ?
1663 FILE_READ_DATA : 0) |
1664 ((flags & SHARE_MODE_ACCESS_WRITE) ?
1665 FILE_WRITE_DATA : 0) |
1666 ((flags & SHARE_MODE_ACCESS_DELETE) ?
1669 if (share_mode != NULL) {
1671 ((flags & SHARE_MODE_SHARE_READ) ?
1672 FILE_SHARE_READ : 0) |
1673 ((flags & SHARE_MODE_SHARE_WRITE) ?
1674 FILE_SHARE_WRITE : 0) |
1675 ((flags & SHARE_MODE_SHARE_DELETE) ?
1676 FILE_SHARE_DELETE : 0);
1678 if (lease_type != NULL) {
1680 ((flags & SHARE_MODE_LEASE_READ) ?
1681 SMB2_LEASE_READ : 0) |
1682 ((flags & SHARE_MODE_LEASE_WRITE) ?
1683 SMB2_LEASE_WRITE : 0) |
1684 ((flags & SHARE_MODE_LEASE_HANDLE) ?
1685 SMB2_LEASE_HANDLE : 0);
1689 static uint16_t share_mode_flags_set(
1691 uint32_t access_mask,
1692 uint32_t share_mode,
1693 uint32_t lease_type)
1695 if (access_mask != UINT32_MAX) {
1696 flags &= ~(SHARE_MODE_ACCESS_READ|
1697 SHARE_MODE_ACCESS_WRITE|
1698 SHARE_MODE_ACCESS_DELETE);
1699 flags |= (access_mask & (FILE_READ_DATA | FILE_EXECUTE)) ?
1700 SHARE_MODE_ACCESS_READ : 0;
1701 flags |= (access_mask & (FILE_WRITE_DATA | FILE_APPEND_DATA)) ?
1702 SHARE_MODE_ACCESS_WRITE : 0;
1703 flags |= (access_mask & (DELETE_ACCESS)) ?
1704 SHARE_MODE_ACCESS_DELETE : 0;
1706 if (share_mode != UINT32_MAX) {
1707 flags &= ~(SHARE_MODE_SHARE_READ|
1708 SHARE_MODE_SHARE_WRITE|
1709 SHARE_MODE_SHARE_DELETE);
1710 flags |= (share_mode & FILE_SHARE_READ) ?
1711 SHARE_MODE_SHARE_READ : 0;
1712 flags |= (share_mode & FILE_SHARE_WRITE) ?
1713 SHARE_MODE_SHARE_WRITE : 0;
1714 flags |= (share_mode & FILE_SHARE_DELETE) ?
1715 SHARE_MODE_SHARE_DELETE : 0;
1717 if (lease_type != UINT32_MAX) {
1718 flags &= ~(SHARE_MODE_LEASE_READ|
1719 SHARE_MODE_LEASE_WRITE|
1720 SHARE_MODE_LEASE_HANDLE);
1721 flags |= (lease_type & SMB2_LEASE_READ) ?
1722 SHARE_MODE_LEASE_READ : 0;
1723 flags |= (lease_type & SMB2_LEASE_WRITE) ?
1724 SHARE_MODE_LEASE_WRITE : 0;
1725 flags |= (lease_type & SMB2_LEASE_HANDLE) ?
1726 SHARE_MODE_LEASE_HANDLE : 0;
1732 static uint16_t share_mode_flags_restrict(
1734 uint32_t access_mask,
1735 uint32_t share_mode,
1736 uint32_t lease_type)
1738 uint32_t existing_access_mask, existing_share_mode;
1739 uint32_t existing_lease_type;
1742 share_mode_flags_get(
1744 &existing_access_mask,
1745 &existing_share_mode,
1746 &existing_lease_type);
1748 existing_access_mask |= access_mask;
1749 existing_share_mode &= share_mode;
1750 existing_lease_type |= lease_type;
1752 ret = share_mode_flags_set(
1754 existing_access_mask,
1755 existing_share_mode,
1756 existing_lease_type);
1760 /****************************************************************************
1761 Deal with share modes
1762 Invariant: Share mode must be locked on entry and exit.
1763 Returns -1 on error, or number of share modes on success (may be zero).
1764 ****************************************************************************/
1766 struct open_mode_check_state {
1768 uint32_t access_mask;
1769 uint32_t share_access;
1770 uint32_t lease_type;
1773 static bool open_mode_check_fn(
1774 struct share_mode_entry *e,
1778 struct open_mode_check_state *state = private_data;
1779 bool disconnected, stale;
1780 uint32_t access_mask, share_access, lease_type;
1782 disconnected = server_id_is_disconnected(&e->pid);
1787 access_mask = state->access_mask | e->access_mask;
1788 share_access = state->share_access & e->share_access;
1789 lease_type = state->lease_type | get_lease_type(e, state->fid);
1791 if ((access_mask == state->access_mask) &&
1792 (share_access == state->share_access) &&
1793 (lease_type == state->lease_type)) {
1797 stale = share_entry_stale_pid(e);
1802 state->access_mask = access_mask;
1803 state->share_access = share_access;
1804 state->lease_type = lease_type;
1809 static NTSTATUS open_mode_check(connection_struct *conn,
1810 struct share_mode_lock *lck,
1811 uint32_t access_mask,
1812 uint32_t share_access)
1814 struct share_mode_data *d = lck->data;
1815 struct open_mode_check_state state;
1817 bool ok, conflict, have_share_entries;
1819 if (is_oplock_stat_open(access_mask)) {
1820 /* Stat open that doesn't trigger oplock breaks or share mode
1821 * checks... ! JRA. */
1822 return NT_STATUS_OK;
1826 * Check if the share modes will give us access.
1829 #if defined(DEVELOPER)
1831 struct validate_my_share_entries_state validate_state = {
1832 .sconn = conn->sconn,
1834 .self = messaging_server_id(conn->sconn->msg_ctx),
1836 ok = share_mode_forall_entries(
1837 lck, validate_my_share_entries_fn, &validate_state);
1842 have_share_entries = share_mode_have_entries(lck);
1843 if (!have_share_entries) {
1845 * This is a fresh share mode lock where no conflicts
1848 return NT_STATUS_OK;
1851 share_mode_flags_get(
1852 d->flags, &state.access_mask, &state.share_access, NULL);
1854 conflict = share_conflict(
1860 DBG_DEBUG("No conflict due to share_mode_flags access\n");
1861 return NT_STATUS_OK;
1864 state = (struct open_mode_check_state) {
1866 .share_access = (FILE_SHARE_READ|
1872 * Walk the share mode array to recalculate d->flags
1875 ok = share_mode_forall_entries(lck, open_mode_check_fn, &state);
1877 DBG_DEBUG("share_mode_forall_entries failed\n");
1878 return NT_STATUS_INTERNAL_ERROR;
1881 new_flags = share_mode_flags_set(
1882 0, state.access_mask, state.share_access, state.lease_type);
1883 if (new_flags == d->flags) {
1885 * We only end up here if we had a sharing violation
1886 * from d->flags and have recalculated it.
1888 return NT_STATUS_SHARING_VIOLATION;
1891 d->flags = new_flags;
1894 conflict = share_conflict(
1900 DBG_DEBUG("No conflict due to share_mode_flags access\n");
1901 return NT_STATUS_OK;
1904 return NT_STATUS_SHARING_VIOLATION;
1908 * Send a break message to the oplock holder and delay the open for
1912 NTSTATUS send_break_message(struct messaging_context *msg_ctx,
1913 const struct file_id *id,
1914 const struct share_mode_entry *exclusive,
1917 struct oplock_break_message msg = {
1919 .share_file_id = exclusive->share_file_id,
1920 .break_to = break_to,
1922 enum ndr_err_code ndr_err;
1927 struct server_id_buf buf;
1928 DBG_DEBUG("Sending break message to %s\n",
1929 server_id_str_buf(exclusive->pid, &buf));
1930 NDR_PRINT_DEBUG(oplock_break_message, &msg);
1933 ndr_err = ndr_push_struct_blob(
1937 (ndr_push_flags_fn_t)ndr_push_oplock_break_message);
1938 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
1939 DBG_WARNING("ndr_push_oplock_break_message failed: %s\n",
1940 ndr_errstr(ndr_err));
1941 return ndr_map_error2ntstatus(ndr_err);
1944 status = messaging_send(
1945 msg_ctx, exclusive->pid, MSG_SMB_BREAK_REQUEST, &blob);
1946 TALLOC_FREE(blob.data);
1947 if (!NT_STATUS_IS_OK(status)) {
1948 DEBUG(3, ("Could not send oplock break message: %s\n",
1949 nt_errstr(status)));
1955 struct validate_oplock_types_state {
1961 uint32_t num_non_stat_opens;
1964 static bool validate_oplock_types_fn(
1965 struct share_mode_entry *e,
1969 struct validate_oplock_types_state *state = private_data;
1971 if (e->op_mid == 0) {
1972 /* INTERNAL_OPEN_ONLY */
1976 if (e->op_type == NO_OPLOCK && is_oplock_stat_open(e->access_mask)) {
1978 * We ignore stat opens in the table - they always
1979 * have NO_OPLOCK and never get or cause breaks. JRA.
1984 state->num_non_stat_opens += 1;
1986 if (BATCH_OPLOCK_TYPE(e->op_type)) {
1987 /* batch - can only be one. */
1988 if (share_entry_stale_pid(e)) {
1989 DBG_DEBUG("Found stale batch oplock\n");
1992 if (state->ex_or_batch ||
1996 DBG_ERR("Bad batch oplock entry\n");
1997 state->valid = false;
2000 state->batch = true;
2003 if (EXCLUSIVE_OPLOCK_TYPE(e->op_type)) {
2004 if (share_entry_stale_pid(e)) {
2005 DBG_DEBUG("Found stale duplicate oplock\n");
2008 /* Exclusive or batch - can only be one. */
2009 if (state->ex_or_batch ||
2012 DBG_ERR("Bad exclusive or batch oplock entry\n");
2013 state->valid = false;
2016 state->ex_or_batch = true;
2019 if (LEVEL_II_OPLOCK_TYPE(e->op_type)) {
2020 if (state->batch || state->ex_or_batch) {
2021 if (share_entry_stale_pid(e)) {
2022 DBG_DEBUG("Found stale LevelII oplock\n");
2025 DBG_DEBUG("Bad levelII oplock entry\n");
2026 state->valid = false;
2029 state->level2 = true;
2032 if (e->op_type == NO_OPLOCK) {
2033 if (state->batch || state->ex_or_batch) {
2034 if (share_entry_stale_pid(e)) {
2035 DBG_DEBUG("Found stale NO_OPLOCK entry\n");
2038 DBG_ERR("Bad no oplock entry\n");
2039 state->valid = false;
2042 state->no_oplock = true;
2049 * Do internal consistency checks on the share mode for a file.
2052 static bool validate_oplock_types(struct share_mode_lock *lck)
2054 struct validate_oplock_types_state state = { .valid = true };
2057 ok = share_mode_forall_entries(lck, validate_oplock_types_fn, &state);
2059 DBG_DEBUG("share_mode_forall_entries failed\n");
2063 DBG_DEBUG("Got invalid oplock configuration\n");
2067 if ((state.batch || state.ex_or_batch) &&
2068 (state.num_non_stat_opens != 1)) {
2069 DBG_WARNING("got batch (%d) or ex (%d) non-exclusively "
2072 (int)state.ex_or_batch,
2073 state.num_non_stat_opens);
2080 static bool is_same_lease(const files_struct *fsp,
2081 const struct share_mode_entry *e,
2082 const struct smb2_lease *lease)
2084 if (e->op_type != LEASE_OPLOCK) {
2087 if (lease == NULL) {
2091 return smb2_lease_equal(fsp_client_guid(fsp),
2097 static bool file_has_brlocks(files_struct *fsp)
2099 struct byte_range_lock *br_lck;
2101 br_lck = brl_get_locks_readonly(fsp);
2105 return (brl_num_locks(br_lck) > 0);
2108 struct fsp_lease *find_fsp_lease(struct files_struct *new_fsp,
2109 const struct smb2_lease_key *key,
2110 uint32_t current_state,
2111 uint16_t lease_version,
2112 uint16_t lease_epoch)
2114 struct files_struct *fsp;
2117 * TODO: Measure how expensive this loop is with thousands of open
2121 for (fsp = file_find_di_first(new_fsp->conn->sconn, new_fsp->file_id);
2123 fsp = file_find_di_next(fsp)) {
2125 if (fsp == new_fsp) {
2128 if (fsp->oplock_type != LEASE_OPLOCK) {
2131 if (smb2_lease_key_equal(&fsp->lease->lease.lease_key, key)) {
2132 fsp->lease->ref_count += 1;
2137 /* Not found - must be leased in another smbd. */
2138 new_fsp->lease = talloc_zero(new_fsp->conn->sconn, struct fsp_lease);
2139 if (new_fsp->lease == NULL) {
2142 new_fsp->lease->ref_count = 1;
2143 new_fsp->lease->sconn = new_fsp->conn->sconn;
2144 new_fsp->lease->lease.lease_key = *key;
2145 new_fsp->lease->lease.lease_state = current_state;
2147 * We internally treat all leases as V2 and update
2148 * the epoch, but when sending breaks it matters if
2149 * the requesting lease was v1 or v2.
2151 new_fsp->lease->lease.lease_version = lease_version;
2152 new_fsp->lease->lease.lease_epoch = lease_epoch;
2153 return new_fsp->lease;
2156 static NTSTATUS try_lease_upgrade(struct files_struct *fsp,
2157 struct share_mode_lock *lck,
2158 const struct GUID *client_guid,
2159 const struct smb2_lease *lease,
2163 uint32_t current_state, breaking_to_requested, breaking_to_required;
2165 uint16_t lease_version, epoch;
2166 uint32_t existing, requested;
2169 status = leases_db_get(
2175 &breaking_to_requested,
2176 &breaking_to_required,
2179 if (!NT_STATUS_IS_OK(status)) {
2183 fsp->lease = find_fsp_lease(
2189 if (fsp->lease == NULL) {
2190 DEBUG(1, ("Did not find existing lease for file %s\n",
2192 return NT_STATUS_NO_MEMORY;
2196 * Upgrade only if the requested lease is a strict upgrade.
2198 existing = current_state;
2199 requested = lease->lease_state;
2202 * Tricky: This test makes sure that "requested" is a
2203 * strict bitwise superset of "existing".
2205 do_upgrade = ((existing & requested) == existing);
2208 * Upgrade only if there's a change.
2210 do_upgrade &= (granted != existing);
2213 * Upgrade only if other leases don't prevent what was asked
2216 do_upgrade &= (granted == requested);
2219 * only upgrade if we are not in breaking state
2221 do_upgrade &= !breaking;
2223 DEBUG(10, ("existing=%"PRIu32", requested=%"PRIu32", "
2224 "granted=%"PRIu32", do_upgrade=%d\n",
2225 existing, requested, granted, (int)do_upgrade));
2228 NTSTATUS set_status;
2230 current_state = granted;
2233 set_status = leases_db_set(
2238 breaking_to_requested,
2239 breaking_to_required,
2243 if (!NT_STATUS_IS_OK(set_status)) {
2244 DBG_DEBUG("leases_db_set failed: %s\n",
2245 nt_errstr(set_status));
2250 fsp_lease_update(fsp);
2252 return NT_STATUS_OK;
2255 static NTSTATUS grant_new_fsp_lease(struct files_struct *fsp,
2256 struct share_mode_lock *lck,
2257 const struct GUID *client_guid,
2258 const struct smb2_lease *lease,
2261 struct share_mode_data *d = lck->data;
2264 fsp->lease = talloc_zero(fsp->conn->sconn, struct fsp_lease);
2265 if (fsp->lease == NULL) {
2266 return NT_STATUS_INSUFFICIENT_RESOURCES;
2268 fsp->lease->ref_count = 1;
2269 fsp->lease->sconn = fsp->conn->sconn;
2270 fsp->lease->lease.lease_version = lease->lease_version;
2271 fsp->lease->lease.lease_key = lease->lease_key;
2272 fsp->lease->lease.lease_state = granted;
2273 fsp->lease->lease.lease_epoch = lease->lease_epoch + 1;
2275 status = leases_db_add(client_guid,
2278 fsp->lease->lease.lease_state,
2279 fsp->lease->lease.lease_version,
2280 fsp->lease->lease.lease_epoch,
2281 fsp->conn->connectpath,
2282 fsp->fsp_name->base_name,
2283 fsp->fsp_name->stream_name);
2284 if (!NT_STATUS_IS_OK(status)) {
2285 DEBUG(10, ("%s: leases_db_add failed: %s\n", __func__,
2286 nt_errstr(status)));
2287 TALLOC_FREE(fsp->lease);
2288 return NT_STATUS_INSUFFICIENT_RESOURCES;
2293 return NT_STATUS_OK;
2296 static NTSTATUS grant_fsp_lease(struct files_struct *fsp,
2297 struct share_mode_lock *lck,
2298 const struct smb2_lease *lease,
2301 const struct GUID *client_guid = fsp_client_guid(fsp);
2304 status = try_lease_upgrade(fsp, lck, client_guid, lease, granted);
2306 if (NT_STATUS_EQUAL(status, NT_STATUS_NOT_FOUND)) {
2307 status = grant_new_fsp_lease(
2308 fsp, lck, client_guid, lease, granted);
2314 static int map_lease_type_to_oplock(uint32_t lease_type)
2316 int result = NO_OPLOCK;
2318 switch (lease_type) {
2319 case SMB2_LEASE_READ|SMB2_LEASE_WRITE|SMB2_LEASE_HANDLE:
2320 result = BATCH_OPLOCK|EXCLUSIVE_OPLOCK;
2322 case SMB2_LEASE_READ|SMB2_LEASE_WRITE:
2323 result = EXCLUSIVE_OPLOCK;
2325 case SMB2_LEASE_READ|SMB2_LEASE_HANDLE:
2326 case SMB2_LEASE_READ:
2327 result = LEVEL_II_OPLOCK;
2334 struct delay_for_oplock_state {
2335 struct files_struct *fsp;
2336 const struct smb2_lease *lease;
2337 bool will_overwrite;
2338 uint32_t delay_mask;
2339 bool first_open_attempt;
2340 bool got_handle_lease;
2342 bool have_other_lease;
2346 static bool delay_for_oplock_fn(
2347 struct share_mode_entry *e,
2351 struct delay_for_oplock_state *state = private_data;
2352 struct files_struct *fsp = state->fsp;
2353 const struct smb2_lease *lease = state->lease;
2354 bool e_is_lease = (e->op_type == LEASE_OPLOCK);
2355 uint32_t e_lease_type = get_lease_type(e, fsp->file_id);
2357 bool lease_is_breaking = false;
2362 if (lease != NULL) {
2363 bool our_lease = is_same_lease(fsp, e, lease);
2365 DBG_DEBUG("Ignoring our own lease\n");
2370 status = leases_db_get(
2374 NULL, /* current_state */
2376 NULL, /* breaking_to_requested */
2377 NULL, /* breaking_to_required */
2378 NULL, /* lease_version */
2380 SMB_ASSERT(NT_STATUS_IS_OK(status));
2383 if (!state->got_handle_lease &&
2384 ((e_lease_type & SMB2_LEASE_HANDLE) != 0) &&
2385 !share_entry_stale_pid(e)) {
2386 state->got_handle_lease = true;
2389 if (!state->got_oplock &&
2390 (e->op_type != LEASE_OPLOCK) &&
2391 !share_entry_stale_pid(e)) {
2392 state->got_oplock = true;
2395 if (!state->have_other_lease &&
2396 !is_same_lease(fsp, e, lease) &&
2397 !share_entry_stale_pid(e)) {
2398 state->have_other_lease = true;
2401 if (e_is_lease && is_lease_stat_open(fsp->access_mask)) {
2405 break_to = e_lease_type & ~state->delay_mask;
2407 if (state->will_overwrite) {
2408 break_to &= ~(SMB2_LEASE_HANDLE|SMB2_LEASE_READ);
2411 DBG_DEBUG("e_lease_type %u, will_overwrite: %u\n",
2412 (unsigned)e_lease_type,
2413 (unsigned)state->will_overwrite);
2415 if ((e_lease_type & ~break_to) == 0) {
2416 if (lease_is_breaking) {
2417 state->delay = true;
2422 if (share_entry_stale_pid(e)) {
2426 if (state->will_overwrite) {
2428 * If we break anyway break to NONE directly.
2429 * Otherwise vfs_set_filelen() will trigger the
2432 break_to &= ~(SMB2_LEASE_READ|SMB2_LEASE_WRITE);
2437 * Oplocks only support breaking to R or NONE.
2439 break_to &= ~(SMB2_LEASE_HANDLE|SMB2_LEASE_WRITE);
2442 DBG_DEBUG("breaking from %d to %d\n",
2446 fsp->conn->sconn->msg_ctx, &fsp->file_id, e, break_to);
2447 if (e_lease_type & state->delay_mask) {
2448 state->delay = true;
2450 if (lease_is_breaking && !state->first_open_attempt) {
2451 state->delay = true;
2457 static NTSTATUS delay_for_oplock(files_struct *fsp,
2459 const struct smb2_lease *lease,
2460 struct share_mode_lock *lck,
2461 bool have_sharing_violation,
2462 uint32_t create_disposition,
2463 bool first_open_attempt)
2465 struct delay_for_oplock_state state = {
2468 .first_open_attempt = first_open_attempt,
2474 if (is_oplock_stat_open(fsp->access_mask)) {
2478 state.delay_mask = have_sharing_violation ?
2479 SMB2_LEASE_HANDLE : SMB2_LEASE_WRITE;
2481 switch (create_disposition) {
2482 case FILE_SUPERSEDE:
2483 case FILE_OVERWRITE:
2484 case FILE_OVERWRITE_IF:
2485 state.will_overwrite = true;
2488 state.will_overwrite = false;
2492 ok = share_mode_forall_entries(lck, delay_for_oplock_fn, &state);
2494 return NT_STATUS_INTERNAL_ERROR;
2498 return NT_STATUS_RETRY;
2502 if (have_sharing_violation) {
2503 return NT_STATUS_SHARING_VIOLATION;
2506 if (oplock_request == LEASE_OPLOCK) {
2507 if (lease == NULL) {
2509 * The SMB2 layer should have checked this
2511 return NT_STATUS_INTERNAL_ERROR;
2514 granted = lease->lease_state;
2516 if (lp_kernel_oplocks(SNUM(fsp->conn))) {
2517 DEBUG(10, ("No lease granted because kernel oplocks are enabled\n"));
2518 granted = SMB2_LEASE_NONE;
2520 if ((granted & (SMB2_LEASE_READ|SMB2_LEASE_WRITE)) == 0) {
2521 DEBUG(10, ("No read or write lease requested\n"));
2522 granted = SMB2_LEASE_NONE;
2524 if (granted == SMB2_LEASE_WRITE) {
2525 DEBUG(10, ("pure write lease requested\n"));
2526 granted = SMB2_LEASE_NONE;
2528 if (granted == (SMB2_LEASE_WRITE|SMB2_LEASE_HANDLE)) {
2529 DEBUG(10, ("write and handle lease requested\n"));
2530 granted = SMB2_LEASE_NONE;
2533 granted = map_oplock_to_lease_type(
2534 oplock_request & ~SAMBA_PRIVATE_OPLOCK_MASK);
2537 if (lp_locking(fsp->conn->params) && file_has_brlocks(fsp)) {
2538 DBG_DEBUG("file %s has byte range locks\n",
2540 granted &= ~SMB2_LEASE_READ;
2543 if (state.have_other_lease) {
2545 * Can grant only one writer
2547 granted &= ~SMB2_LEASE_WRITE;
2550 if ((granted & SMB2_LEASE_READ) && !(granted & SMB2_LEASE_WRITE)) {
2552 (global_client_caps & CAP_LEVEL_II_OPLOCKS) &&
2553 lp_level2_oplocks(SNUM(fsp->conn));
2555 if (!allow_level2) {
2556 granted = SMB2_LEASE_NONE;
2560 if (oplock_request == LEASE_OPLOCK) {
2561 if (state.got_oplock) {
2562 granted &= ~SMB2_LEASE_HANDLE;
2565 fsp->oplock_type = LEASE_OPLOCK;
2567 status = grant_fsp_lease(fsp, lck, lease, granted);
2568 if (!NT_STATUS_IS_OK(status)) {
2573 DBG_DEBUG("lease_state=%d\n", fsp->lease->lease.lease_state);
2575 if (state.got_handle_lease) {
2576 granted = SMB2_LEASE_NONE;
2579 fsp->oplock_type = map_lease_type_to_oplock(granted);
2581 status = set_file_oplock(fsp);
2582 if (!NT_STATUS_IS_OK(status)) {
2584 * Could not get the kernel oplock
2586 fsp->oplock_type = NO_OPLOCK;
2590 if ((granted & SMB2_LEASE_READ) &&
2591 ((lck->data->flags & SHARE_MODE_LEASE_READ) == 0)) {
2592 lck->data->flags |= SHARE_MODE_LEASE_READ;
2593 lck->data->modified = true;
2596 DBG_DEBUG("oplock type 0x%x on file %s\n",
2597 fsp->oplock_type, fsp_str_dbg(fsp));
2599 return NT_STATUS_OK;
2602 static NTSTATUS handle_share_mode_lease(
2604 struct share_mode_lock *lck,
2605 uint32_t create_disposition,
2606 uint32_t access_mask,
2607 uint32_t share_access,
2609 const struct smb2_lease *lease,
2610 bool first_open_attempt)
2612 bool sharing_violation = false;
2615 status = open_mode_check(
2616 fsp->conn, lck, access_mask, share_access);
2617 if (NT_STATUS_EQUAL(status, NT_STATUS_SHARING_VIOLATION)) {
2618 sharing_violation = true;
2619 status = NT_STATUS_OK; /* handled later */
2622 if (!NT_STATUS_IS_OK(status)) {
2626 if (oplock_request == INTERNAL_OPEN_ONLY) {
2627 if (sharing_violation) {
2628 DBG_DEBUG("Sharing violation for internal open\n");
2629 return NT_STATUS_SHARING_VIOLATION;
2633 * Internal opens never do oplocks or leases. We don't
2634 * need to go through delay_for_oplock().
2636 fsp->oplock_type = NO_OPLOCK;
2638 return NT_STATUS_OK;
2641 status = delay_for_oplock(
2648 first_open_attempt);
2649 if (!NT_STATUS_IS_OK(status)) {
2653 return NT_STATUS_OK;
2656 static bool request_timed_out(struct smb_request *req, struct timeval timeout)
2658 struct timeval now, end_time;
2660 end_time = timeval_sum(&req->request_time, &timeout);
2661 return (timeval_compare(&end_time, &now) < 0);
2664 struct defer_open_state {
2665 struct smbXsrv_connection *xconn;
2669 static void defer_open_done(struct tevent_req *req);
2672 * Defer an open and watch a locking.tdb record
2674 * This defers an open that gets rescheduled once the locking.tdb record watch
2675 * is triggered by a change to the record.
2677 * It is used to defer opens that triggered an oplock break and for the SMB1
2678 * sharing violation delay.
2680 static void defer_open(struct share_mode_lock *lck,
2681 struct timeval timeout,
2682 struct smb_request *req,
2685 struct deferred_open_record *open_rec = NULL;
2686 struct timeval abs_timeout;
2687 struct defer_open_state *watch_state;
2688 struct tevent_req *watch_req;
2689 struct timeval_buf tvbuf1, tvbuf2;
2690 struct file_id_buf fbuf;
2693 abs_timeout = timeval_sum(&req->request_time, &timeout);
2695 DBG_DEBUG("request time [%s] timeout [%s] mid [%" PRIu64 "] "
2697 timeval_str_buf(&req->request_time, false, true, &tvbuf1),
2698 timeval_str_buf(&abs_timeout, false, true, &tvbuf2),
2700 file_id_str_buf(id, &fbuf));
2702 open_rec = talloc_zero(NULL, struct deferred_open_record);
2703 if (open_rec == NULL) {
2705 exit_server("talloc failed");
2708 watch_state = talloc(open_rec, struct defer_open_state);
2709 if (watch_state == NULL) {
2710 exit_server("talloc failed");
2712 watch_state->xconn = req->xconn;
2713 watch_state->mid = req->mid;
2715 DBG_DEBUG("defering mid %" PRIu64 "\n", req->mid);
2717 watch_req = share_mode_watch_send(
2721 (struct server_id){0});
2722 if (watch_req == NULL) {
2723 exit_server("Could not watch share mode record");
2725 tevent_req_set_callback(watch_req, defer_open_done, watch_state);
2727 ok = tevent_req_set_endtime(watch_req, req->sconn->ev_ctx, abs_timeout);
2729 exit_server("tevent_req_set_endtime failed");
2732 ok = push_deferred_open_message_smb(req, timeout, id, open_rec);
2735 exit_server("push_deferred_open_message_smb failed");
2739 static void defer_open_done(struct tevent_req *req)
2741 struct defer_open_state *state = tevent_req_callback_data(
2742 req, struct defer_open_state);
2746 status = share_mode_watch_recv(req, NULL, NULL);
2748 if (!NT_STATUS_IS_OK(status)) {
2749 DEBUG(5, ("dbwrap_watched_watch_recv returned %s\n",
2750 nt_errstr(status)));
2752 * Even if it failed, retry anyway. TODO: We need a way to
2753 * tell a re-scheduled open about that error.
2757 DEBUG(10, ("scheduling mid %llu\n", (unsigned long long)state->mid));
2759 ret = schedule_deferred_open_message_smb(state->xconn, state->mid);
2765 * Actually attempt the kernel oplock polling open.
2768 static void poll_open_fn(struct tevent_context *ev,
2769 struct tevent_timer *te,
2770 struct timeval current_time,
2773 struct deferred_open_record *open_rec = talloc_get_type_abort(
2774 private_data, struct deferred_open_record);
2777 TALLOC_FREE(open_rec->watch_req);
2779 ok = schedule_deferred_open_message_smb(
2780 open_rec->xconn, open_rec->mid);
2782 exit_server("schedule_deferred_open_message_smb failed");
2784 DBG_DEBUG("timer fired. Retrying open !\n");
2787 static void poll_open_done(struct tevent_req *subreq);
2790 * Reschedule an open for 1 second from now, if not timed out.
2792 static bool setup_poll_open(
2793 struct smb_request *req,
2794 struct share_mode_lock *lck,
2796 struct timeval max_timeout,
2797 struct timeval interval)
2800 struct deferred_open_record *open_rec = NULL;
2801 struct timeval endtime, next_interval;
2802 struct file_id_buf ftmp;
2804 if (request_timed_out(req, max_timeout)) {
2808 open_rec = talloc_zero(NULL, struct deferred_open_record);
2809 if (open_rec == NULL) {
2810 DBG_WARNING("talloc failed\n");
2813 open_rec->xconn = req->xconn;
2814 open_rec->mid = req->mid;
2817 * Make sure open_rec->te does not come later than the
2818 * request's maximum endtime.
2821 endtime = timeval_sum(&req->request_time, &max_timeout);
2822 next_interval = timeval_current_ofs(interval.tv_sec, interval.tv_usec);
2823 next_interval = timeval_min(&endtime, &next_interval);
2825 open_rec->te = tevent_add_timer(
2831 if (open_rec->te == NULL) {
2832 DBG_WARNING("tevent_add_timer failed\n");
2833 TALLOC_FREE(open_rec);
2838 open_rec->watch_req = share_mode_watch_send(
2842 (struct server_id) {0});
2843 if (open_rec->watch_req == NULL) {
2844 DBG_WARNING("share_mode_watch_send failed\n");
2845 TALLOC_FREE(open_rec);
2848 tevent_req_set_callback(
2849 open_rec->watch_req, poll_open_done, open_rec);
2852 ok = push_deferred_open_message_smb(req, max_timeout, id, open_rec);
2854 DBG_WARNING("push_deferred_open_message_smb failed\n");
2855 TALLOC_FREE(open_rec);
2859 DBG_DEBUG("poll request time [%s] mid [%" PRIu64 "] file_id [%s]\n",
2860 timeval_string(talloc_tos(), &req->request_time, false),
2862 file_id_str_buf(id, &ftmp));
2867 static void poll_open_done(struct tevent_req *subreq)
2869 struct deferred_open_record *open_rec = tevent_req_callback_data(
2870 subreq, struct deferred_open_record);
2874 status = share_mode_watch_recv(subreq, NULL, NULL);
2875 TALLOC_FREE(subreq);
2876 DBG_DEBUG("dbwrap_watched_watch_recv returned %s\n",
2879 ok = schedule_deferred_open_message_smb(
2880 open_rec->xconn, open_rec->mid);
2882 exit_server("schedule_deferred_open_message_smb failed");
2886 bool defer_smb1_sharing_violation(struct smb_request *req)
2891 if (!lp_defer_sharing_violations()) {
2896 * Try every 200msec up to (by default) one second. To be
2897 * precise, according to behaviour note <247> in [MS-CIFS],
2898 * the server tries 5 times. But up to one second should be
2902 timeout_usecs = lp_parm_int(
2906 SHARING_VIOLATION_USEC_WAIT);
2908 ok = setup_poll_open(
2911 (struct file_id) {0},
2912 (struct timeval) { .tv_usec = timeout_usecs },
2913 (struct timeval) { .tv_usec = 200000 });
2917 /****************************************************************************
2918 On overwrite open ensure that the attributes match.
2919 ****************************************************************************/
2921 static bool open_match_attributes(connection_struct *conn,
2922 uint32_t old_dos_attr,
2923 uint32_t new_dos_attr,
2924 mode_t new_unx_mode,
2925 mode_t *returned_unx_mode)
2927 uint32_t noarch_old_dos_attr, noarch_new_dos_attr;
2929 noarch_old_dos_attr = (old_dos_attr & ~FILE_ATTRIBUTE_ARCHIVE);
2930 noarch_new_dos_attr = (new_dos_attr & ~FILE_ATTRIBUTE_ARCHIVE);
2932 if((noarch_old_dos_attr == 0 && noarch_new_dos_attr != 0) ||
2933 (noarch_old_dos_attr != 0 && ((noarch_old_dos_attr & noarch_new_dos_attr) == noarch_old_dos_attr))) {
2934 *returned_unx_mode = new_unx_mode;
2936 *returned_unx_mode = (mode_t)0;
2939 DEBUG(10,("open_match_attributes: old_dos_attr = 0x%x, "
2940 "new_dos_attr = 0x%x "
2941 "returned_unx_mode = 0%o\n",
2942 (unsigned int)old_dos_attr,
2943 (unsigned int)new_dos_attr,
2944 (unsigned int)*returned_unx_mode ));
2946 /* If we're mapping SYSTEM and HIDDEN ensure they match. */
2947 if (lp_map_system(SNUM(conn)) || lp_store_dos_attributes(SNUM(conn))) {
2948 if ((old_dos_attr & FILE_ATTRIBUTE_SYSTEM) &&
2949 !(new_dos_attr & FILE_ATTRIBUTE_SYSTEM)) {
2953 if (lp_map_hidden(SNUM(conn)) || lp_store_dos_attributes(SNUM(conn))) {
2954 if ((old_dos_attr & FILE_ATTRIBUTE_HIDDEN) &&
2955 !(new_dos_attr & FILE_ATTRIBUTE_HIDDEN)) {
2962 static void schedule_defer_open(struct share_mode_lock *lck,
2964 struct smb_request *req)
2966 /* This is a relative time, added to the absolute
2967 request_time value to get the absolute timeout time.
2968 Note that if this is the second or greater time we enter
2969 this codepath for this particular request mid then
2970 request_time is left as the absolute time of the *first*
2971 time this request mid was processed. This is what allows
2972 the request to eventually time out. */
2974 struct timeval timeout;
2976 /* Normally the smbd we asked should respond within
2977 * OPLOCK_BREAK_TIMEOUT seconds regardless of whether
2978 * the client did, give twice the timeout as a safety
2979 * measure here in case the other smbd is stuck
2980 * somewhere else. */
2982 timeout = timeval_set(OPLOCK_BREAK_TIMEOUT*2, 0);
2984 if (request_timed_out(req, timeout)) {
2988 defer_open(lck, timeout, req, id);
2991 /****************************************************************************
2992 Reschedule an open call that went asynchronous.
2993 ****************************************************************************/
2995 static void schedule_async_open_timer(struct tevent_context *ev,
2996 struct tevent_timer *te,
2997 struct timeval current_time,
3000 exit_server("async open timeout");
3003 static void schedule_async_open(struct smb_request *req)
3005 struct deferred_open_record *open_rec = NULL;
3006 struct timeval timeout = timeval_set(20, 0);
3009 if (request_timed_out(req, timeout)) {
3013 open_rec = talloc_zero(NULL, struct deferred_open_record);
3014 if (open_rec == NULL) {
3015 exit_server("deferred_open_record_create failed");
3017 open_rec->async_open = true;
3019 ok = push_deferred_open_message_smb(
3020 req, timeout, (struct file_id){0}, open_rec);
3022 exit_server("push_deferred_open_message_smb failed");
3025 open_rec->te = tevent_add_timer(req->sconn->ev_ctx,
3027 timeval_current_ofs(20, 0),
3028 schedule_async_open_timer,
3030 if (open_rec->te == NULL) {
3031 exit_server("tevent_add_timer failed");
3035 /****************************************************************************
3036 Work out what access_mask to use from what the client sent us.
3037 ****************************************************************************/
3039 static NTSTATUS smbd_calculate_maximum_allowed_access(
3040 connection_struct *conn,
3041 struct files_struct *dirfsp,
3042 const struct smb_filename *smb_fname,
3044 uint32_t *p_access_mask)
3046 struct security_descriptor *sd;
3047 uint32_t access_granted;
3050 SMB_ASSERT(dirfsp == conn->cwd_fsp);
3052 if (!use_privs && (get_current_uid(conn) == (uid_t)0)) {
3053 *p_access_mask |= FILE_GENERIC_ALL;
3054 return NT_STATUS_OK;
3057 status = SMB_VFS_GET_NT_ACL(conn, smb_fname,
3063 if (NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
3065 * File did not exist
3067 *p_access_mask = FILE_GENERIC_ALL;
3068 return NT_STATUS_OK;
3070 if (!NT_STATUS_IS_OK(status)) {
3071 DEBUG(10,("Could not get acl on file %s: %s\n",
3072 smb_fname_str_dbg(smb_fname),
3073 nt_errstr(status)));
3074 return NT_STATUS_ACCESS_DENIED;
3078 * If we can access the path to this file, by
3079 * default we have FILE_READ_ATTRIBUTES from the
3080 * containing directory. See the section:
3081 * "Algorithm to Check Access to an Existing File"
3084 * se_file_access_check()
3085 * also takes care of owner WRITE_DAC and READ_CONTROL.
3087 status = se_file_access_check(sd,
3088 get_current_nttok(conn),
3090 (*p_access_mask & ~FILE_READ_ATTRIBUTES),
3095 if (!NT_STATUS_IS_OK(status)) {
3096 DEBUG(10, ("Access denied on file %s: "
3097 "when calculating maximum access\n",
3098 smb_fname_str_dbg(smb_fname)));
3099 return NT_STATUS_ACCESS_DENIED;
3101 *p_access_mask = (access_granted | FILE_READ_ATTRIBUTES);
3103 if (!(access_granted & DELETE_ACCESS)) {
3104 if (can_delete_file_in_directory(conn,
3108 *p_access_mask |= DELETE_ACCESS;
3112 return NT_STATUS_OK;
3115 NTSTATUS smbd_calculate_access_mask(connection_struct *conn,
3116 struct files_struct *dirfsp,
3117 const struct smb_filename *smb_fname,
3119 uint32_t access_mask,
3120 uint32_t *access_mask_out)
3123 uint32_t orig_access_mask = access_mask;
3124 uint32_t rejected_share_access;
3126 SMB_ASSERT(dirfsp == conn->cwd_fsp);
3128 if (access_mask & SEC_MASK_INVALID) {
3129 DBG_DEBUG("access_mask [%8x] contains invalid bits\n",
3131 return NT_STATUS_ACCESS_DENIED;
3135 * Convert GENERIC bits to specific bits.
3138 se_map_generic(&access_mask, &file_generic_mapping);
3140 /* Calculate MAXIMUM_ALLOWED_ACCESS if requested. */
3141 if (access_mask & MAXIMUM_ALLOWED_ACCESS) {
3143 status = smbd_calculate_maximum_allowed_access(conn,
3149 if (!NT_STATUS_IS_OK(status)) {
3153 access_mask &= conn->share_access;
3156 rejected_share_access = access_mask & ~(conn->share_access);
3158 if (rejected_share_access) {
3159 DEBUG(10, ("smbd_calculate_access_mask: Access denied on "
3160 "file %s: rejected by share access mask[0x%08X] "
3161 "orig[0x%08X] mapped[0x%08X] reject[0x%08X]\n",
3162 smb_fname_str_dbg(smb_fname),
3164 orig_access_mask, access_mask,
3165 rejected_share_access));
3166 return NT_STATUS_ACCESS_DENIED;
3169 *access_mask_out = access_mask;
3170 return NT_STATUS_OK;
3173 /****************************************************************************
3174 Remove the deferred open entry under lock.
3175 ****************************************************************************/
3177 /****************************************************************************
3178 Return true if this is a state pointer to an asynchronous create.
3179 ****************************************************************************/
3181 bool is_deferred_open_async(const struct deferred_open_record *rec)
3183 return rec->async_open;
3186 static bool clear_ads(uint32_t create_disposition)
3190 switch (create_disposition) {
3191 case FILE_SUPERSEDE:
3192 case FILE_OVERWRITE_IF:
3193 case FILE_OVERWRITE:
3202 static int disposition_to_open_flags(uint32_t create_disposition)
3207 * Currently we're using FILE_SUPERSEDE as the same as
3208 * FILE_OVERWRITE_IF but they really are
3209 * different. FILE_SUPERSEDE deletes an existing file
3210 * (requiring delete access) then recreates it.
3213 switch (create_disposition) {
3214 case FILE_SUPERSEDE:
3215 case FILE_OVERWRITE_IF:
3217 * If file exists replace/overwrite. If file doesn't
3220 ret = O_CREAT|O_TRUNC;
3225 * If file exists open. If file doesn't exist error.
3230 case FILE_OVERWRITE:
3232 * If file exists overwrite. If file doesn't exist
3240 * If file exists error. If file doesn't exist create.
3242 ret = O_CREAT|O_EXCL;
3247 * If file exists open. If file doesn't exist create.
3255 static int calculate_open_access_flags(uint32_t access_mask,
3256 uint32_t private_flags)
3258 bool need_write, need_read;
3261 * Note that we ignore the append flag as append does not
3262 * mean the same thing under DOS and Unix.
3265 need_write = (access_mask & (FILE_WRITE_DATA | FILE_APPEND_DATA));
3270 /* DENY_DOS opens are always underlying read-write on the
3271 file handle, no matter what the requested access mask
3275 ((private_flags & NTCREATEX_OPTIONS_PRIVATE_DENY_DOS) ||
3276 access_mask & (FILE_READ_ATTRIBUTES|FILE_READ_DATA|
3277 FILE_READ_EA|FILE_EXECUTE));
3285 /****************************************************************************
3286 Open a file with a share mode. Passed in an already created files_struct *.
3287 ****************************************************************************/
3289 static NTSTATUS open_file_ntcreate(connection_struct *conn,
3290 struct smb_request *req,
3291 uint32_t access_mask, /* access bits (FILE_READ_DATA etc.) */
3292 uint32_t share_access, /* share constants (FILE_SHARE_READ etc) */
3293 uint32_t create_disposition, /* FILE_OPEN_IF etc. */
3294 uint32_t create_options, /* options such as delete on close. */
3295 uint32_t new_dos_attributes, /* attributes used for new file. */
3296 int oplock_request, /* internal Samba oplock codes. */
3297 const struct smb2_lease *lease,
3298 /* Information (FILE_EXISTS etc.) */
3299 uint32_t private_flags, /* Samba specific flags. */
3303 struct smb_filename *smb_fname = fsp->fsp_name;
3306 bool file_existed = VALID_STAT(smb_fname->st);
3307 bool def_acl = False;
3308 bool posix_open = False;
3309 bool new_file_created = False;
3310 bool first_open_attempt = true;
3311 NTSTATUS fsp_open = NT_STATUS_ACCESS_DENIED;
3312 mode_t new_unx_mode = (mode_t)0;
3313 mode_t unx_mode = (mode_t)0;
3315 uint32_t existing_dos_attributes = 0;
3316 struct share_mode_lock *lck = NULL;
3317 uint32_t open_access_mask = access_mask;
3319 struct smb_filename *parent_dir_fname = NULL;
3320 SMB_STRUCT_STAT saved_stat = smb_fname->st;
3321 struct timespec old_write_time;
3323 bool setup_poll = false;
3326 if (conn->printer) {
3328 * Printers are handled completely differently.
3329 * Most of the passed parameters are ignored.
3333 *pinfo = FILE_WAS_CREATED;
3336 DEBUG(10, ("open_file_ntcreate: printer open fname=%s\n",
3337 smb_fname_str_dbg(smb_fname)));
3340 DEBUG(0,("open_file_ntcreate: printer open without "
3341 "an SMB request!\n"));
3342 return NT_STATUS_INTERNAL_ERROR;
3345 return print_spool_open(fsp, smb_fname->base_name,
3349 ok = parent_smb_fname(talloc_tos(),
3354 return NT_STATUS_NO_MEMORY;
3357 if (new_dos_attributes & FILE_FLAG_POSIX_SEMANTICS) {
3359 unx_mode = (mode_t)(new_dos_attributes & ~FILE_FLAG_POSIX_SEMANTICS);
3360 new_dos_attributes = 0;
3362 /* Windows allows a new file to be created and
3363 silently removes a FILE_ATTRIBUTE_DIRECTORY
3364 sent by the client. Do the same. */
3366 new_dos_attributes &= ~FILE_ATTRIBUTE_DIRECTORY;
3368 /* We add FILE_ATTRIBUTE_ARCHIVE to this as this mode is only used if the file is
3370 unx_mode = unix_mode(conn, new_dos_attributes | FILE_ATTRIBUTE_ARCHIVE,
3371 smb_fname, parent_dir_fname);
3374 DEBUG(10, ("open_file_ntcreate: fname=%s, dos_attrs=0x%x "
3375 "access_mask=0x%x share_access=0x%x "
3376 "create_disposition = 0x%x create_options=0x%x "
3377 "unix mode=0%o oplock_request=%d private_flags = 0x%x\n",
3378 smb_fname_str_dbg(smb_fname), new_dos_attributes,
3379 access_mask, share_access, create_disposition,
3380 create_options, (unsigned int)unx_mode, oplock_request,
3381 (unsigned int)private_flags));
3384 /* Ensure req == NULL means INTERNAL_OPEN_ONLY */
3385 SMB_ASSERT(oplock_request == INTERNAL_OPEN_ONLY);
3387 /* And req != NULL means no INTERNAL_OPEN_ONLY */
3388 SMB_ASSERT(((oplock_request & INTERNAL_OPEN_ONLY) == 0));
3392 * Only non-internal opens can be deferred at all
3396 struct deferred_open_record *open_rec;
3397 if (get_deferred_open_message_state(req, NULL, &open_rec)) {
3399 /* If it was an async create retry, the file
3402 if (is_deferred_open_async(open_rec)) {
3403 SET_STAT_INVALID(smb_fname->st);
3404 file_existed = false;
3407 /* Ensure we don't reprocess this message. */
3408 remove_deferred_open_message_smb(req->xconn, req->mid);
3410 first_open_attempt = false;
3415 new_dos_attributes &= SAMBA_ATTRIBUTES_MASK;
3418 * Only use stored DOS attributes for checks
3419 * against requested attributes (below via
3420 * open_match_attributes()), cf bug #11992
3421 * for details. -slow
3425 status = SMB_VFS_GET_DOS_ATTRIBUTES(conn, smb_fname, &attr);
3426 if (NT_STATUS_IS_OK(status)) {
3427 existing_dos_attributes = attr;
3432 /* ignore any oplock requests if oplocks are disabled */
3433 if (!lp_oplocks(SNUM(conn)) ||
3434 IS_VETO_OPLOCK_PATH(conn, smb_fname->base_name)) {
3435 /* Mask off everything except the private Samba bits. */
3436 oplock_request &= SAMBA_PRIVATE_OPLOCK_MASK;
3439 /* this is for OS/2 long file names - say we don't support them */
3440 if (req != NULL && !req->posix_pathnames &&
3441 strstr(smb_fname->base_name,".+,;=[].")) {
3442 /* OS/2 Workplace shell fix may be main code stream in a later
3444 DEBUG(5,("open_file_ntcreate: OS/2 long filenames are not "
3446 if (use_nt_status()) {
3447 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3449 return NT_STATUS_DOS(ERRDOS, ERRcannotopen);
3452 switch( create_disposition ) {
3454 /* If file exists open. If file doesn't exist error. */
3455 if (!file_existed) {
3456 DEBUG(5,("open_file_ntcreate: FILE_OPEN "
3457 "requested for file %s and file "
3459 smb_fname_str_dbg(smb_fname)));
3461 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3465 case FILE_OVERWRITE:
3466 /* If file exists overwrite. If file doesn't exist
3468 if (!file_existed) {
3469 DEBUG(5,("open_file_ntcreate: FILE_OVERWRITE "
3470 "requested for file %s and file "
3472 smb_fname_str_dbg(smb_fname) ));
3474 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3479 /* If file exists error. If file doesn't exist
3482 DEBUG(5,("open_file_ntcreate: FILE_CREATE "
3483 "requested for file %s and file "
3484 "already exists.\n",
3485 smb_fname_str_dbg(smb_fname)));
3486 if (S_ISDIR(smb_fname->st.st_ex_mode)) {
3491 return map_nt_error_from_unix(errno);
3495 case FILE_SUPERSEDE:
3496 case FILE_OVERWRITE_IF:
3500 return NT_STATUS_INVALID_PARAMETER;
3503 flags2 = disposition_to_open_flags(create_disposition);
3505 /* We only care about matching attributes on file exists and
3508 if (!posix_open && file_existed &&
3509 ((create_disposition == FILE_OVERWRITE) ||
3510 (create_disposition == FILE_OVERWRITE_IF))) {
3511 if (!open_match_attributes(conn, existing_dos_attributes,
3513 unx_mode, &new_unx_mode)) {
3514 DEBUG(5,("open_file_ntcreate: attributes mismatch "
3515 "for file %s (%x %x) (0%o, 0%o)\n",
3516 smb_fname_str_dbg(smb_fname),
3517 existing_dos_attributes,
3519 (unsigned int)smb_fname->st.st_ex_mode,
3520 (unsigned int)unx_mode ));
3522 return NT_STATUS_ACCESS_DENIED;
3526 status = smbd_calculate_access_mask(conn,
3532 if (!NT_STATUS_IS_OK(status)) {
3533 DEBUG(10, ("open_file_ntcreate: smbd_calculate_access_mask "
3534 "on file %s returned %s\n",
3535 smb_fname_str_dbg(smb_fname), nt_errstr(status)));
3539 open_access_mask = access_mask;
3541 if (flags2 & O_TRUNC) {
3542 open_access_mask |= FILE_WRITE_DATA; /* This will cause oplock breaks. */
3547 * stat opens on existing files don't get oplocks.
3548 * They can get leases.
3550 * Note that we check for stat open on the *open_access_mask*,
3551 * i.e. the access mask we actually used to do the open,
3552 * not the one the client asked for (which is in
3553 * fsp->access_mask). This is due to the fact that
3554 * FILE_OVERWRITE and FILE_OVERWRITE_IF add in O_TRUNC,
3555 * which adds FILE_WRITE_DATA to open_access_mask.
3557 if (is_oplock_stat_open(open_access_mask) && lease == NULL) {
3558 oplock_request = NO_OPLOCK;
3562 DEBUG(10, ("open_file_ntcreate: fname=%s, after mapping "
3563 "access_mask=0x%x\n", smb_fname_str_dbg(smb_fname),
3567 * Note that we ignore the append flag as append does not
3568 * mean the same thing under DOS and Unix.
3571 flags = calculate_open_access_flags(access_mask, private_flags);
3574 * Currently we only look at FILE_WRITE_THROUGH for create options.
3578 if ((create_options & FILE_WRITE_THROUGH) && lp_strict_sync(SNUM(conn))) {
3583 if (posix_open && (access_mask & FILE_APPEND_DATA)) {
3587 if (!posix_open && !CAN_WRITE(conn)) {
3589 * We should really return a permission denied error if either
3590 * O_CREAT or O_TRUNC are set, but for compatibility with
3591 * older versions of Samba we just AND them out.
3593 flags2 &= ~(O_CREAT|O_TRUNC);
3597 * With kernel oplocks the open breaking an oplock
3598 * blocks until the oplock holder has given up the
3599 * oplock or closed the file. We prevent this by always
3600 * trying to open the file with O_NONBLOCK (see "man
3603 * If a process that doesn't use the smbd open files
3604 * database or communication methods holds a kernel
3605 * oplock we must periodically poll for available open
3608 flags2 |= O_NONBLOCK;
3611 * Ensure we can't write on a read-only share or file.
3614 if (flags != O_RDONLY && file_existed &&
3615 (!CAN_WRITE(conn) || IS_DOS_READONLY(existing_dos_attributes))) {
3616 DEBUG(5,("open_file_ntcreate: write access requested for "
3617 "file %s on read only %s\n",
3618 smb_fname_str_dbg(smb_fname),
3619 !CAN_WRITE(conn) ? "share" : "file" ));
3621 return NT_STATUS_ACCESS_DENIED;
3624 if (VALID_STAT(smb_fname->st)) {
3626 * Only try and create a file id before open
3627 * for an existing file. For a file being created
3628 * this won't do anything useful until the file
3629 * exists and has a valid stat struct.
3631 fsp->file_id = vfs_file_id_from_sbuf(conn, &smb_fname->st);
3633 fsp->fh->private_options = private_flags;
3634 fsp->access_mask = open_access_mask; /* We change this to the
3635 * requested access_mask after
3636 * the open is done. */
3638 fsp->posix_flags |= FSP_POSIX_FLAGS_ALL;
3641 if ((create_options & FILE_DELETE_ON_CLOSE) &&
3642 (flags2 & O_CREAT) &&
3644 /* Delete on close semantics for new files. */
3645 status = can_set_delete_on_close(fsp,
3646 new_dos_attributes);
3647 if (!NT_STATUS_IS_OK(status)) {
3654 * Ensure we pay attention to default ACLs on directories if required.
3657 if ((flags2 & O_CREAT) && lp_inherit_acls(SNUM(conn)) &&
3658 (def_acl = directory_has_default_acl(conn,
3662 unx_mode = (0777 & lp_create_mask(SNUM(conn)));
3665 DEBUG(4,("calling open_file with flags=0x%X flags2=0x%X mode=0%o, "
3666 "access_mask = 0x%x, open_access_mask = 0x%x\n",
3667 (unsigned int)flags, (unsigned int)flags2,
3668 (unsigned int)unx_mode, (unsigned int)access_mask,
3669 (unsigned int)open_access_mask));
3671 fsp_open = open_file(fsp, conn, req, parent_dir_fname,
3672 flags|flags2, unx_mode, access_mask,
3673 open_access_mask, &new_file_created);
3675 if (NT_STATUS_EQUAL(fsp_open, NT_STATUS_NETWORK_BUSY)) {
3676 if (file_existed && S_ISFIFO(fsp->fsp_name->st.st_ex_mode)) {
3677 DEBUG(10, ("FIFO busy\n"));
3678 return NT_STATUS_NETWORK_BUSY;
3681 DEBUG(10, ("Internal open busy\n"));
3682 return NT_STATUS_NETWORK_BUSY;
3685 * This handles the kernel oplock case:
3687 * the file has an active kernel oplock and the open() returned
3688 * EWOULDBLOCK/EAGAIN which maps to NETWORK_BUSY.
3690 * "Samba locking.tdb oplocks" are handled below after acquiring
3691 * the sharemode lock with get_share_mode_lock().
3696 if (NT_STATUS_EQUAL(fsp_open, NT_STATUS_RETRY)) {
3698 * EINTR from the open(2) syscall. Just setup a retry
3699 * in a bit. We can't use the sys_write() tight retry
3700 * loop here, as we might have to actually deal with
3701 * lease-break signals to avoid a deadlock.
3708 * From here on we assume this is an oplock break triggered
3711 lck = get_existing_share_mode_lock(talloc_tos(), fsp->file_id);
3713 if ((lck != NULL) && !validate_oplock_types(lck)) {
3714 smb_panic("validate_oplock_types failed");
3718 * Retry once a second. If there's a share_mode_lock
3719 * around, also wait for it in case it was smbd
3720 * holding that kernel oplock that can quickly tell us
3721 * the oplock got removed.
3728 timeval_set(OPLOCK_BREAK_TIMEOUT*2, 0),
3733 return NT_STATUS_SHARING_VIOLATION;
3736 if (!NT_STATUS_IS_OK(fsp_open)) {
3737 bool wait_for_aio = NT_STATUS_EQUAL(
3738 fsp_open, NT_STATUS_MORE_PROCESSING_REQUIRED);
3740 schedule_async_open(req);
3745 if (new_file_created) {
3747 * As we atomically create using O_CREAT|O_EXCL,
3748 * then if new_file_created is true, then
3749 * file_existed *MUST* have been false (even
3750 * if the file was previously detected as being
3753 file_existed = false;
3756 if (file_existed && !check_same_dev_ino(&saved_stat, &smb_fname->st)) {
3758 * The file did exist, but some other (local or NFS)
3759 * process either renamed/unlinked and re-created the
3760 * file with different dev/ino after we walked the path,
3761 * but before we did the open. We could retry the
3762 * open but it's a rare enough case it's easier to
3763 * just fail the open to prevent creating any problems
3764 * in the open file db having the wrong dev/ino key.
3767 DBG_WARNING("file %s - dev/ino mismatch. "
3768 "Old (dev=%ju, ino=%ju). "
3769 "New (dev=%ju, ino=%ju). Failing open "
3770 "with NT_STATUS_ACCESS_DENIED.\n",
3771 smb_fname_str_dbg(smb_fname),
3772 (uintmax_t)saved_stat.st_ex_dev,
3773 (uintmax_t)saved_stat.st_ex_ino,
3774 (uintmax_t)smb_fname->st.st_ex_dev,
3775 (uintmax_t)smb_fname->st.st_ex_ino);
3776 return NT_STATUS_ACCESS_DENIED;
3779 old_write_time = smb_fname->st.st_ex_mtime;
3782 * Deal with the race condition where two smbd's detect the
3783 * file doesn't exist and do the create at the same time. One
3784 * of them will win and set a share mode, the other (ie. this
3785 * one) should check if the requested share mode for this
3786 * create is allowed.
3790 * Now the file exists and fsp is successfully opened,
3791 * fsp->dev and fsp->inode are valid and should replace the
3792 * dev=0,inode=0 from a non existent file. Spotted by
3793 * Nadav Danieli <nadavd@exanet.com>. JRA.
3798 lck = get_share_mode_lock(talloc_tos(), id,
3800 smb_fname, &old_write_time);
3803 DEBUG(0, ("open_file_ntcreate: Could not get share "
3804 "mode lock for %s\n",
3805 smb_fname_str_dbg(smb_fname)));
3807 return NT_STATUS_SHARING_VIOLATION;
3810 /* Get the types we need to examine. */
3811 if (!validate_oplock_types(lck)) {
3812 smb_panic("validate_oplock_types failed");
3815 if (has_delete_on_close(lck, fsp->name_hash)) {
3818 return NT_STATUS_DELETE_PENDING;
3821 status = handle_share_mode_lease(
3829 first_open_attempt);
3831 if (NT_STATUS_EQUAL(status, NT_STATUS_RETRY)) {
3832 schedule_defer_open(lck, fsp->file_id, req);
3835 return NT_STATUS_SHARING_VIOLATION;
3838 if (!NT_STATUS_IS_OK(status)) {
3845 struct share_mode_data *d = lck->data;
3846 uint16_t new_flags = share_mode_flags_restrict(
3847 d->flags, access_mask, share_access, UINT32_MAX);
3849 if (new_flags != d->flags) {
3850 d->flags = new_flags;
3855 ok = set_share_mode(
3858 get_current_uid(fsp->conn),
3864 if (fsp->oplock_type == LEASE_OPLOCK) {
3865 status = remove_lease_if_stale(
3867 fsp_client_guid(fsp),
3868 &fsp->lease->lease.lease_key);
3869 if (!NT_STATUS_IS_OK(status)) {
3870 DBG_WARNING("remove_lease_if_stale "
3875 return NT_STATUS_NO_MEMORY;
3878 /* Should we atomically (to the client at least) truncate ? */
3879 if ((!new_file_created) &&
3880 (flags2 & O_TRUNC) &&
3881 (S_ISREG(fsp->fsp_name->st.st_ex_mode))) {
3884 ret = SMB_VFS_FTRUNCATE(fsp, 0);
3886 status = map_nt_error_from_unix(errno);
3887 del_share_mode(lck, fsp);
3892 notify_fname(fsp->conn, NOTIFY_ACTION_MODIFIED,
3893 FILE_NOTIFY_CHANGE_SIZE
3894 | FILE_NOTIFY_CHANGE_ATTRIBUTES,
3895 fsp->fsp_name->base_name);
3899 * We have the share entry *locked*.....
3902 /* Delete streams if create_disposition requires it */
3903 if (!new_file_created && clear_ads(create_disposition) &&
3904 !is_ntfs_stream_smb_fname(smb_fname)) {
3905 status = delete_all_streams(conn, smb_fname);
3906 if (!NT_STATUS_IS_OK(status)) {
3907 del_share_mode(lck, fsp);
3914 if (fsp->fh->fd != -1 && lp_kernel_share_modes(SNUM(conn))) {
3917 * Beware: streams implementing VFS modules may
3918 * implement streams in a way that fsp will have the
3919 * basefile open in the fsp fd, so lacking a distinct
3920 * fd for the stream kernel_flock will apply on the
3921 * basefile which is wrong. The actual check is
3922 * deferred to the VFS module implementing the
3923 * kernel_flock call.
3925 ret_flock = SMB_VFS_KERNEL_FLOCK(fsp, share_access, access_mask);
3926 if(ret_flock == -1 ){
3928 del_share_mode(lck, fsp);
3932 return NT_STATUS_SHARING_VIOLATION;
3935 fsp->fsp_flags.kernel_share_modes_taken = true;
3939 * At this point onwards, we can guarantee that the share entry
3940 * is locked, whether we created the file or not, and that the
3941 * deny mode is compatible with all current opens.
3945 * According to Samba4, SEC_FILE_READ_ATTRIBUTE is always granted,
3946 * but we don't have to store this - just ignore it on access check.
3948 if (conn->sconn->using_smb2) {
3950 * SMB2 doesn't return it (according to Microsoft tests).
3951 * Test Case: TestSuite_ScenarioNo009GrantedAccessTestS0
3952 * File created with access = 0x7 (Read, Write, Delete)
3953 * Query Info on file returns 0x87 (Read, Write, Delete, Read Attributes)
3955 fsp->access_mask = access_mask;
3957 /* But SMB1 does. */
3958 fsp->access_mask = access_mask | FILE_READ_ATTRIBUTES;
3961 if (new_file_created) {
3962 info = FILE_WAS_CREATED;
3964 if (flags2 & O_TRUNC) {
3965 info = FILE_WAS_OVERWRITTEN;
3967 info = FILE_WAS_OPENED;
3975 /* Handle strange delete on close create semantics. */
3976 if (create_options & FILE_DELETE_ON_CLOSE) {
3977 if (!new_file_created) {
3978 status = can_set_delete_on_close(fsp,
3979 existing_dos_attributes);
3981 if (!NT_STATUS_IS_OK(status)) {
3982 /* Remember to delete the mode we just added. */
3983 del_share_mode(lck, fsp);
3989 /* Note that here we set the *initial* delete on close flag,
3990 not the regular one. The magic gets handled in close. */
3991 fsp->fsp_flags.initial_delete_on_close = true;
3995 * If we created a file and it's not a stream, this is the point where
3996 * we set the itime (aka invented time) that get's stored in the DOS
3997 * attribute xattr. The value is going to be either what the filesystem
3998 * provided or a copy of the creation date.
4000 * Either way, we turn the itime into a File-ID, unless the filesystem
4001 * provided one (unlikely).
4003 if (info == FILE_WAS_CREATED && !is_named_stream(smb_fname)) {
4004 smb_fname->st.st_ex_iflags &= ~ST_EX_IFLAG_CALCULATED_ITIME;
4006 if (lp_store_dos_attributes(SNUM(conn)) &&
4007 smb_fname->st.st_ex_iflags & ST_EX_IFLAG_CALCULATED_FILE_ID)
4011 file_id = make_file_id_from_itime(&smb_fname->st);
4012 update_stat_ex_file_id(&smb_fname->st, file_id);
4016 if (info != FILE_WAS_OPENED) {
4017 /* Overwritten files should be initially set as archive */
4018 if ((info == FILE_WAS_OVERWRITTEN && lp_map_archive(SNUM(conn))) ||
4019 lp_store_dos_attributes(SNUM(conn))) {
4020 (void)dos_mode(conn, smb_fname);
4022 if (file_set_dosmode(conn, smb_fname,
4023 new_dos_attributes | FILE_ATTRIBUTE_ARCHIVE,
4024 parent_dir_fname, true) == 0) {
4025 unx_mode = smb_fname->st.st_ex_mode;
4031 /* Determine sparse flag. */
4033 /* POSIX opens are sparse by default. */
4034 fsp->fsp_flags.is_sparse = true;
4036 fsp->fsp_flags.is_sparse =
4037 (existing_dos_attributes & FILE_ATTRIBUTE_SPARSE);
4041 * Take care of inherited ACLs on created files - if default ACL not
4045 if (!posix_open && new_file_created && !def_acl) {
4046 if (unx_mode != smb_fname->st.st_ex_mode) {
4047 int ret = SMB_VFS_FCHMOD(fsp, unx_mode);
4049 DBG_INFO("failed to reset "
4050 "attributes of file %s to 0%o\n",
4051 smb_fname_str_dbg(smb_fname),
4052 (unsigned int)unx_mode);
4056 } else if (new_unx_mode) {
4058 * We only get here in the case of:
4060 * a). Not a POSIX open.
4061 * b). File already existed.
4062 * c). File was overwritten.
4063 * d). Requested DOS attributes didn't match
4064 * the DOS attributes on the existing file.
4066 * In that case new_unx_mode has been set
4067 * equal to the calculated mode (including
4068 * possible inheritance of the mode from the
4069 * containing directory).
4071 * Note this mode was calculated with the
4072 * DOS attribute FILE_ATTRIBUTE_ARCHIVE added,
4073 * so the mode change here is suitable for
4074 * an overwritten file.
4077 if (new_unx_mode != smb_fname->st.st_ex_mode) {
4078 int ret = SMB_VFS_FCHMOD(fsp, new_unx_mode);
4080 DBG_INFO("failed to reset "
4081 "attributes of file %s to 0%o\n",
4082 smb_fname_str_dbg(smb_fname),
4083 (unsigned int)new_unx_mode);
4090 * Deal with other opens having a modified write time.
4092 struct timespec write_time = get_share_mode_write_time(lck);
4094 if (!is_omit_timespec(&write_time)) {
4095 update_stat_ex_mtime(&fsp->fsp_name->st, write_time);
4101 return NT_STATUS_OK;
4104 static NTSTATUS mkdir_internal(connection_struct *conn,
4105 struct smb_filename *smb_dname,
4106 uint32_t file_attributes)
4108 const struct loadparm_substitution *lp_sub =
4109 loadparm_s3_global_substitution();
4111 struct smb_filename *parent_dir_fname = NULL;
4113 bool posix_open = false;
4114 bool need_re_stat = false;
4115 uint32_t access_mask = SEC_DIR_ADD_SUBDIR;
4119 if (!CAN_WRITE(conn) || (access_mask & ~(conn->share_access))) {
4120 DEBUG(5,("mkdir_internal: failing share access "
4121 "%s\n", lp_servicename(talloc_tos(), lp_sub, SNUM(conn))));
4122 return NT_STATUS_ACCESS_DENIED;
4125 ok = parent_smb_fname(talloc_tos(),
4130 return NT_STATUS_NO_MEMORY;
4133 if (file_attributes & FILE_FLAG_POSIX_SEMANTICS) {
4135 mode = (mode_t)(file_attributes & ~FILE_FLAG_POSIX_SEMANTICS);
4137 mode = unix_mode(conn,
4138 FILE_ATTRIBUTE_DIRECTORY,
4143 status = check_parent_access(conn,
4147 if(!NT_STATUS_IS_OK(status)) {
4148 DEBUG(5,("mkdir_internal: check_parent_access "
4149 "on directory %s for path %s returned %s\n",
4150 smb_fname_str_dbg(parent_dir_fname),
4151 smb_dname->base_name,
4152 nt_errstr(status) ));
4156 ret = SMB_VFS_MKDIRAT(conn,
4161 return map_nt_error_from_unix(errno);
4164 /* Ensure we're checking for a symlink here.... */
4165 /* We don't want to get caught by a symlink racer. */
4167 if (SMB_VFS_LSTAT(conn, smb_dname) == -1) {
4168 DEBUG(2, ("Could not stat directory '%s' just created: %s\n",
4169 smb_fname_str_dbg(smb_dname), strerror(errno)));
4170 return map_nt_error_from_unix(errno);
4173 if (!S_ISDIR(smb_dname->st.st_ex_mode)) {
4174 DEBUG(0, ("Directory '%s' just created is not a directory !\n",
4175 smb_fname_str_dbg(smb_dname)));
4176 return NT_STATUS_NOT_A_DIRECTORY;
4179 smb_dname->st.st_ex_iflags &= ~ST_EX_IFLAG_CALCULATED_ITIME;
4181 if (lp_store_dos_attributes(SNUM(conn))) {
4182 if (smb_dname->st.st_ex_iflags & ST_EX_IFLAG_CALCULATED_FILE_ID)
4186 file_id = make_file_id_from_itime(&smb_dname->st);
4187 update_stat_ex_file_id(&smb_dname->st, file_id);
4191 file_set_dosmode(conn, smb_dname,
4192 file_attributes | FILE_ATTRIBUTE_DIRECTORY,
4193 parent_dir_fname, true);
4197 if (lp_inherit_permissions(SNUM(conn))) {
4198 inherit_access_posix_acl(conn, parent_dir_fname,
4200 need_re_stat = true;
4205 * Check if high bits should have been set,
4206 * then (if bits are missing): add them.
4207 * Consider bits automagically set by UNIX, i.e. SGID bit from parent
4210 if ((mode & ~(S_IRWXU|S_IRWXG|S_IRWXO)) &&
4211 (mode & ~smb_dname->st.st_ex_mode)) {
4212 SMB_VFS_CHMOD(conn, smb_dname,
4213 (smb_dname->st.st_ex_mode |
4214 (mode & ~smb_dname->st.st_ex_mode)));
4215 need_re_stat = true;
4219 /* Change the owner if required. */
4220 if (lp_inherit_owner(SNUM(conn)) != INHERIT_OWNER_NO) {
4221 change_dir_owner_to_parent(conn, parent_dir_fname,
4224 need_re_stat = true;
4228 if (SMB_VFS_LSTAT(conn, smb_dname) == -1) {
4229 DEBUG(2, ("Could not stat directory '%s' just created: %s\n",
4230 smb_fname_str_dbg(smb_dname), strerror(errno)));
4231 return map_nt_error_from_unix(errno);
4235 notify_fname(conn, NOTIFY_ACTION_ADDED, FILE_NOTIFY_CHANGE_DIR_NAME,
4236 smb_dname->base_name);
4238 return NT_STATUS_OK;
4241 /****************************************************************************
4242 Open a directory from an NT SMB call.
4243 ****************************************************************************/
4245 static NTSTATUS open_directory(connection_struct *conn,
4246 struct smb_request *req,
4247 struct smb_filename *smb_dname,
4248 uint32_t access_mask,
4249 uint32_t share_access,
4250 uint32_t create_disposition,
4251 uint32_t create_options,
4252 uint32_t file_attributes,
4254 files_struct **result)
4256 files_struct *fsp = NULL;
4257 bool dir_existed = VALID_STAT(smb_dname->st);
4258 struct share_mode_lock *lck = NULL;
4260 struct timespec mtimespec;
4264 if (is_ntfs_stream_smb_fname(smb_dname)) {
4265 DEBUG(2, ("open_directory: %s is a stream name!\n",
4266 smb_fname_str_dbg(smb_dname)));
4267 return NT_STATUS_NOT_A_DIRECTORY;
4270 if (!(file_attributes & FILE_FLAG_POSIX_SEMANTICS)) {
4271 /* Ensure we have a directory attribute. */
4272 file_attributes |= FILE_ATTRIBUTE_DIRECTORY;
4275 DBG_INFO("opening directory %s, access_mask = 0x%"PRIx32", "
4276 "share_access = 0x%"PRIx32" create_options = 0x%"PRIx32", "
4277 "create_disposition = 0x%"PRIx32", "
4278 "file_attributes = 0x%"PRIx32"\n",
4279 smb_fname_str_dbg(smb_dname),
4286 status = smbd_calculate_access_mask(conn,
4292 if (!NT_STATUS_IS_OK(status)) {
4293 DEBUG(10, ("open_directory: smbd_calculate_access_mask "
4294 "on file %s returned %s\n",
4295 smb_fname_str_dbg(smb_dname),
4296 nt_errstr(status)));
4300 if ((access_mask & SEC_FLAG_SYSTEM_SECURITY) &&
4301 !security_token_has_privilege(get_current_nttok(conn),
4302 SEC_PRIV_SECURITY)) {
4303 DEBUG(10, ("open_directory: open on %s "
4304 "failed - SEC_FLAG_SYSTEM_SECURITY denied.\n",
4305 smb_fname_str_dbg(smb_dname)));
4306 return NT_STATUS_PRIVILEGE_NOT_HELD;
4309 switch( create_disposition ) {
4313 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
4316 info = FILE_WAS_OPENED;
4321 /* If directory exists error. If directory doesn't
4325 status = NT_STATUS_OBJECT_NAME_COLLISION;
4326 DEBUG(2, ("open_directory: unable to create "
4327 "%s. Error was %s\n",
4328 smb_fname_str_dbg(smb_dname),
4329 nt_errstr(status)));
4333 status = mkdir_internal(conn, smb_dname,
4336 if (!NT_STATUS_IS_OK(status)) {
4337 DEBUG(2, ("open_directory: unable to create "
4338 "%s. Error was %s\n",
4339 smb_fname_str_dbg(smb_dname),
4340 nt_errstr(status)));
4344 info = FILE_WAS_CREATED;
4349 * If directory exists open. If directory doesn't
4354 status = NT_STATUS_OK;
4355 info = FILE_WAS_OPENED;
4357 status = mkdir_internal(conn, smb_dname,
4360 if (NT_STATUS_IS_OK(status)) {
4361 info = FILE_WAS_CREATED;
4363 /* Cope with create race. */
4364 if (!NT_STATUS_EQUAL(status,
4365 NT_STATUS_OBJECT_NAME_COLLISION)) {
4366 DEBUG(2, ("open_directory: unable to create "
4367 "%s. Error was %s\n",
4368 smb_fname_str_dbg(smb_dname),
4369 nt_errstr(status)));
4374 * If mkdir_internal() returned
4375 * NT_STATUS_OBJECT_NAME_COLLISION
4376 * we still must lstat the path.
4379 if (SMB_VFS_LSTAT(conn, smb_dname)
4381 DEBUG(2, ("Could not stat "
4382 "directory '%s' just "
4387 return map_nt_error_from_unix(
4391 info = FILE_WAS_OPENED;
4397 case FILE_SUPERSEDE:
4398 case FILE_OVERWRITE:
4399 case FILE_OVERWRITE_IF:
4401 DEBUG(5,("open_directory: invalid create_disposition "
4402 "0x%x for directory %s\n",
4403 (unsigned int)create_disposition,
4404 smb_fname_str_dbg(smb_dname)));
4405 return NT_STATUS_INVALID_PARAMETER;
4408 if(!S_ISDIR(smb_dname->st.st_ex_mode)) {
4409 DEBUG(5,("open_directory: %s is not a directory !\n",
4410 smb_fname_str_dbg(smb_dname)));
4411 return NT_STATUS_NOT_A_DIRECTORY;
4414 if (info == FILE_WAS_OPENED) {
4415 status = smbd_check_access_rights(conn,
4420 if (!NT_STATUS_IS_OK(status)) {
4421 DEBUG(10, ("open_directory: smbd_check_access_rights on "
4422 "file %s failed with %s\n",
4423 smb_fname_str_dbg(smb_dname),
4424 nt_errstr(status)));
4429 status = file_new(req, conn, &fsp);
4430 if(!NT_STATUS_IS_OK(status)) {
4435 * Setup the files_struct for it.
4438 fsp->file_id = vfs_file_id_from_sbuf(conn, &smb_dname->st);
4439 fsp->vuid = req ? req->vuid : UID_FIELD_INVALID;
4440 fsp->file_pid = req ? req->smbpid : 0;
4441 fsp->fsp_flags.can_lock = false;
4442 fsp->fsp_flags.can_read = false;
4443 fsp->fsp_flags.can_write = false;
4445 fsp->fh->private_options = 0;
4447 * According to Samba4, SEC_FILE_READ_ATTRIBUTE is always granted,
4449 fsp->access_mask = access_mask | FILE_READ_ATTRIBUTES;
4450 fsp->print_file = NULL;
4451 fsp->fsp_flags.modified = false;
4452 fsp->oplock_type = NO_OPLOCK;
4453 fsp->sent_oplock_break = NO_BREAK_SENT;
4454 fsp->fsp_flags.is_directory = true;
4455 if (file_attributes & FILE_FLAG_POSIX_SEMANTICS) {
4456 fsp->posix_flags |= FSP_POSIX_FLAGS_ALL;
4458 status = fsp_set_smb_fname(fsp, smb_dname);
4459 if (!NT_STATUS_IS_OK(status)) {
4460 file_free(req, fsp);
4464 /* Don't store old timestamps for directory
4465 handles in the internal database. We don't
4466 update them in there if new objects
4467 are created in the directory. Currently
4468 we only update timestamps on file writes.
4471 mtimespec = make_omit_timespec();
4474 status = fd_open(conn, fsp, O_RDONLY|O_DIRECTORY, 0);
4476 /* POSIX allows us to open a directory with O_RDONLY. */
4477 status = fd_open(conn, fsp, O_RDONLY, 0);
4479 if (!NT_STATUS_IS_OK(status)) {
4480 DBG_INFO("Could not open fd for "
4482 smb_fname_str_dbg(smb_dname),
4484 file_free(req, fsp);
4488 status = vfs_stat_fsp(fsp);
4489 if (!NT_STATUS_IS_OK(status)) {
4491 file_free(req, fsp);
4495 if(!S_ISDIR(fsp->fsp_name->st.st_ex_mode)) {
4496 DEBUG(5,("open_directory: %s is not a directory !\n",
4497 smb_fname_str_dbg(smb_dname)));
4499 file_free(req, fsp);
4500 return NT_STATUS_NOT_A_DIRECTORY;
4503 /* Ensure there was no race condition. We need to check
4504 * dev/inode but not permissions, as these can change
4506 if (!check_same_dev_ino(&smb_dname->st, &fsp->fsp_name->st)) {
4507 DEBUG(5,("open_directory: stat struct differs for "
4509 smb_fname_str_dbg(smb_dname)));
4511 file_free(req, fsp);
4512 return NT_STATUS_ACCESS_DENIED;
4515 lck = get_share_mode_lock(talloc_tos(), fsp->file_id,
4516 conn->connectpath, smb_dname,
4520 DEBUG(0, ("open_directory: Could not get share mode lock for "
4521 "%s\n", smb_fname_str_dbg(smb_dname)));
4523 file_free(req, fsp);
4524 return NT_STATUS_SHARING_VIOLATION;
4527 if (has_delete_on_close(lck, fsp->name_hash)) {
4530 file_free(req, fsp);
4531 return NT_STATUS_DELETE_PENDING;
4534 status = open_mode_check(conn, lck,
4535 access_mask, share_access);
4537 if (!NT_STATUS_IS_OK(status)) {
4540 file_free(req, fsp);
4545 struct share_mode_data *d = lck->data;
4546 uint16_t new_flags = share_mode_flags_restrict(
4547 d->flags, access_mask, share_access, UINT32_MAX);
4549 if (new_flags != d->flags) {
4550 d->flags = new_flags;
4555 ok = set_share_mode(
4558 get_current_uid(conn),
4566 file_free(req, fsp);
4567 return NT_STATUS_NO_MEMORY;
4570 /* For directories the delete on close bit at open time seems
4571 always to be honored on close... See test 19 in Samba4 BASE-DELETE. */
4572 if (create_options & FILE_DELETE_ON_CLOSE) {
4573 status = can_set_delete_on_close(fsp, 0);
4574 if (!NT_STATUS_IS_OK(status) && !NT_STATUS_EQUAL(status, NT_STATUS_DIRECTORY_NOT_EMPTY)) {
4575 del_share_mode(lck, fsp);
4578 file_free(req, fsp);
4582 if (NT_STATUS_IS_OK(status)) {
4583 /* Note that here we set the *initial* delete on close flag,
4584 not the regular one. The magic gets handled in close. */
4585 fsp->fsp_flags.initial_delete_on_close = true;
4591 * Deal with other opens having a modified write time. Is this
4592 * possible for directories?
4594 struct timespec write_time = get_share_mode_write_time(lck);
4596 if (!is_omit_timespec(&write_time)) {
4597 update_stat_ex_mtime(&fsp->fsp_name->st, write_time);
4608 return NT_STATUS_OK;
4611 NTSTATUS create_directory(connection_struct *conn, struct smb_request *req,
4612 struct smb_filename *smb_dname)
4617 status = SMB_VFS_CREATE_FILE(
4620 0, /* root_dir_fid */
4621 smb_dname, /* fname */
4622 FILE_READ_ATTRIBUTES, /* access_mask */
4623 FILE_SHARE_NONE, /* share_access */
4624 FILE_CREATE, /* create_disposition*/
4625 FILE_DIRECTORY_FILE, /* create_options */
4626 FILE_ATTRIBUTE_DIRECTORY, /* file_attributes */
4627 0, /* oplock_request */
4629 0, /* allocation_size */
4630 0, /* private_flags */
4635 NULL, NULL); /* create context */
4637 if (NT_STATUS_IS_OK(status)) {
4638 close_file(req, fsp, NORMAL_CLOSE);
4644 /****************************************************************************
4645 Receive notification that one of our open files has been renamed by another
4647 ****************************************************************************/
4649 void msg_file_was_renamed(struct messaging_context *msg_ctx,
4652 struct server_id src,
4655 struct file_rename_message *msg = NULL;
4656 enum ndr_err_code ndr_err;
4658 struct smb_filename *smb_fname = NULL;
4659 struct smbd_server_connection *sconn =
4660 talloc_get_type_abort(private_data,
4661 struct smbd_server_connection);
4663 msg = talloc(talloc_tos(), struct file_rename_message);
4665 DBG_WARNING("talloc failed\n");
4669 ndr_err = ndr_pull_struct_blob_all(
4673 (ndr_pull_flags_fn_t)ndr_pull_file_rename_message);
4674 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
4675 DBG_DEBUG("ndr_pull_oplock_break_message failed: %s\n",
4676 ndr_errstr(ndr_err));
4679 if (DEBUGLEVEL >= 10) {
4680 struct server_id_buf buf;
4681 DBG_DEBUG("Got rename message from %s\n",
4682 server_id_str_buf(src, &buf));
4683 NDR_PRINT_DEBUG(file_rename_message, msg);
4686 /* stream_name must always be NULL if there is no stream. */
4687 if ((msg->stream_name != NULL) && (msg->stream_name[0] == '\0')) {
4688 msg->stream_name = NULL;
4691 smb_fname = synthetic_smb_fname(msg,
4697 if (smb_fname == NULL) {
4698 DBG_DEBUG("synthetic_smb_fname failed\n");
4702 fsp = file_find_dif(sconn, msg->id, msg->share_file_id);
4704 DBG_DEBUG("fsp not found\n");
4708 if (strcmp(fsp->conn->connectpath, msg->servicepath) == 0) {
4710 DBG_DEBUG("renaming file %s from %s -> %s\n",
4713 smb_fname_str_dbg(smb_fname));
4714 status = fsp_set_smb_fname(fsp, smb_fname);
4715 if (!NT_STATUS_IS_OK(status)) {
4716 DBG_DEBUG("fsp_set_smb_fname failed: %s\n",
4722 * Now we have the complete path we can work out if
4723 * this is actually within this share and adjust
4724 * newname accordingly.
4726 DBG_DEBUG("share mismatch (sharepath %s not sharepath %s) "
4727 "%s from %s -> %s\n",
4728 fsp->conn->connectpath,
4732 smb_fname_str_dbg(smb_fname));
4739 * If a main file is opened for delete, all streams need to be checked for
4740 * !FILE_SHARE_DELETE. Do this by opening with DELETE_ACCESS.
4741 * If that works, delete them all by setting the delete on close and close.
4744 static NTSTATUS open_streams_for_delete(connection_struct *conn,
4745 const struct smb_filename *smb_fname)
4747 struct stream_struct *stream_info = NULL;
4748 files_struct **streams = NULL;
4750 unsigned int i, num_streams = 0;
4751 TALLOC_CTX *frame = talloc_stackframe();
4754 status = vfs_streaminfo(conn, NULL, smb_fname, talloc_tos(),
4755 &num_streams, &stream_info);
4757 if (NT_STATUS_EQUAL(status, NT_STATUS_NOT_IMPLEMENTED)
4758 || NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
4759 DEBUG(10, ("no streams around\n"));
4761 return NT_STATUS_OK;
4764 if (!NT_STATUS_IS_OK(status)) {
4765 DEBUG(10, ("vfs_streaminfo failed: %s\n",
4766 nt_errstr(status)));
4770 DEBUG(10, ("open_streams_for_delete found %d streams\n",
4773 if (num_streams == 0) {
4775 return NT_STATUS_OK;
4778 streams = talloc_array(talloc_tos(), files_struct *, num_streams);
4779 if (streams == NULL) {
4780 DEBUG(0, ("talloc failed\n"));
4781 status = NT_STATUS_NO_MEMORY;
4785 for (i=0; i<num_streams; i++) {
4786 struct smb_filename *smb_fname_cp;
4788 if (strequal(stream_info[i].name, "::$DATA")) {
4793 smb_fname_cp = synthetic_smb_fname(talloc_tos(),
4794 smb_fname->base_name,
4795 stream_info[i].name,
4799 ~SMB_FILENAME_POSIX_PATH));
4800 if (smb_fname_cp == NULL) {
4801 status = NT_STATUS_NO_MEMORY;
4805 if (SMB_VFS_STAT(conn, smb_fname_cp) == -1) {
4806 DEBUG(10, ("Unable to stat stream: %s\n",
4807 smb_fname_str_dbg(smb_fname_cp)));
4810 status = SMB_VFS_CREATE_FILE(
4813 0, /* root_dir_fid */
4814 smb_fname_cp, /* fname */
4815 DELETE_ACCESS, /* access_mask */
4816 (FILE_SHARE_READ | /* share_access */
4817 FILE_SHARE_WRITE | FILE_SHARE_DELETE),
4818 FILE_OPEN, /* create_disposition*/
4819 0, /* create_options */
4820 FILE_ATTRIBUTE_NORMAL, /* file_attributes */
4821 0, /* oplock_request */
4823 0, /* allocation_size */
4824 NTCREATEX_OPTIONS_PRIVATE_STREAM_DELETE, /* private_flags */
4827 &streams[i], /* result */
4829 NULL, NULL); /* create context */
4831 if (!NT_STATUS_IS_OK(status)) {
4832 DEBUG(10, ("Could not open stream %s: %s\n",
4833 smb_fname_str_dbg(smb_fname_cp),
4834 nt_errstr(status)));
4836 TALLOC_FREE(smb_fname_cp);
4839 TALLOC_FREE(smb_fname_cp);
4843 * don't touch the variable "status" beyond this point :-)
4846 for (j = i-1 ; j >= 0; j--) {
4847 if (streams[j] == NULL) {
4851 DEBUG(10, ("Closing stream # %d, %s\n", j,
4852 fsp_str_dbg(streams[j])));
4853 close_file(NULL, streams[j], NORMAL_CLOSE);
4861 /*********************************************************************
4862 Create a default ACL by inheriting from the parent. If no inheritance
4863 from the parent available, don't set anything. This will leave the actual
4864 permissions the new file or directory already got from the filesystem
4865 as the NT ACL when read.
4866 *********************************************************************/
4868 static NTSTATUS inherit_new_acl(files_struct *fsp)
4870 TALLOC_CTX *frame = talloc_stackframe();
4871 struct security_descriptor *parent_desc = NULL;
4872 NTSTATUS status = NT_STATUS_OK;
4873 struct security_descriptor *psd = NULL;
4874 const struct dom_sid *owner_sid = NULL;
4875 const struct dom_sid *group_sid = NULL;
4876 uint32_t security_info_sent = (SECINFO_OWNER | SECINFO_GROUP | SECINFO_DACL);
4877 struct security_token *token = fsp->conn->session_info->security_token;
4878 bool inherit_owner =
4879 (lp_inherit_owner(SNUM(fsp->conn)) == INHERIT_OWNER_WINDOWS_AND_UNIX);
4880 bool inheritable_components = false;
4881 bool try_builtin_administrators = false;
4882 const struct dom_sid *BA_U_sid = NULL;
4883 const struct dom_sid *BA_G_sid = NULL;
4884 bool try_system = false;
4885 const struct dom_sid *SY_U_sid = NULL;
4886 const struct dom_sid *SY_G_sid = NULL;
4888 struct smb_filename *parent_dir = NULL;
4891 ok = parent_smb_fname(frame,
4897 return NT_STATUS_NO_MEMORY;
4900 status = SMB_VFS_GET_NT_ACL(fsp->conn,
4902 (SECINFO_OWNER | SECINFO_GROUP | SECINFO_DACL),
4905 if (!NT_STATUS_IS_OK(status)) {
4910 inheritable_components = sd_has_inheritable_components(parent_desc,
4911 fsp->fsp_flags.is_directory);
4913 if (!inheritable_components && !inherit_owner) {
4915 /* Nothing to inherit and not setting owner. */
4916 return NT_STATUS_OK;
4919 /* Create an inherited descriptor from the parent. */
4921 if (DEBUGLEVEL >= 10) {
4922 DEBUG(10,("inherit_new_acl: parent acl for %s is:\n",
4923 fsp_str_dbg(fsp) ));
4924 NDR_PRINT_DEBUG(security_descriptor, parent_desc);
4927 /* Inherit from parent descriptor if "inherit owner" set. */
4928 if (inherit_owner) {
4929 owner_sid = parent_desc->owner_sid;
4930 group_sid = parent_desc->group_sid;
4933 if (owner_sid == NULL) {
4934 if (security_token_has_builtin_administrators(token)) {
4935 try_builtin_administrators = true;
4936 } else if (security_token_is_system(token)) {
4937 try_builtin_administrators = true;
4942 if (group_sid == NULL &&
4943 token->num_sids == PRIMARY_GROUP_SID_INDEX)
4945 if (security_token_is_system(token)) {
4946 try_builtin_administrators = true;
4951 if (try_builtin_administrators) {
4955 ok = sids_to_unixids(&global_sid_Builtin_Administrators, 1, &ids);
4959 BA_U_sid = &global_sid_Builtin_Administrators;
4960 BA_G_sid = &global_sid_Builtin_Administrators;
4963 BA_U_sid = &global_sid_Builtin_Administrators;
4966 BA_G_sid = &global_sid_Builtin_Administrators;
4978 ok = sids_to_unixids(&global_sid_System, 1, &ids);
4982 SY_U_sid = &global_sid_System;
4983 SY_G_sid = &global_sid_System;
4986 SY_U_sid = &global_sid_System;
4989 SY_G_sid = &global_sid_System;
4997 if (owner_sid == NULL) {
4998 owner_sid = BA_U_sid;
5001 if (owner_sid == NULL) {
5002 owner_sid = SY_U_sid;
5005 if (group_sid == NULL) {
5006 group_sid = SY_G_sid;
5009 if (try_system && group_sid == NULL) {
5010 group_sid = BA_G_sid;
5013 if (owner_sid == NULL) {
5014 owner_sid = &token->sids[PRIMARY_USER_SID_INDEX];
5016 if (group_sid == NULL) {
5017 if (token->num_sids == PRIMARY_GROUP_SID_INDEX) {
5018 group_sid = &token->sids[PRIMARY_USER_SID_INDEX];
5020 group_sid = &token->sids[PRIMARY_GROUP_SID_INDEX];
5024 status = se_create_child_secdesc(frame,
5030 fsp->fsp_flags.is_directory);
5031 if (!NT_STATUS_IS_OK(status)) {
5036 /* If inheritable_components == false,
5037 se_create_child_secdesc()
5038 creates a security descriptor with a NULL dacl
5039 entry, but with SEC_DESC_DACL_PRESENT. We need
5040 to remove that flag. */
5042 if (!inheritable_components) {
5043 security_info_sent &= ~SECINFO_DACL;
5044 psd->type &= ~SEC_DESC_DACL_PRESENT;
5047 if (DEBUGLEVEL >= 10) {
5048 DEBUG(10,("inherit_new_acl: child acl for %s is:\n",
5049 fsp_str_dbg(fsp) ));
5050 NDR_PRINT_DEBUG(security_descriptor, psd);
5053 if (inherit_owner) {
5054 /* We need to be root to force this. */
5057 status = SMB_VFS_FSET_NT_ACL(fsp,
5060 if (inherit_owner) {
5068 * If we already have a lease, it must match the new file id. [MS-SMB2]
5069 * 3.3.5.9.8 speaks about INVALID_PARAMETER if an already used lease key is
5070 * used for a different file name.
5073 struct lease_match_state {
5074 /* Input parameters. */
5075 TALLOC_CTX *mem_ctx;
5076 const char *servicepath;
5077 const struct smb_filename *fname;
5080 /* Return parameters. */
5081 uint32_t num_file_ids;
5082 struct file_id *ids;
5083 NTSTATUS match_status;
5086 /*************************************************************
5087 File doesn't exist but this lease key+guid is already in use.
5089 This is only allowable in the dynamic share case where the
5090 service path must be different.
5092 There is a small race condition here in the multi-connection
5093 case where a client sends two create calls on different connections,
5094 where the file doesn't exist and one smbd creates the leases_db
5095 entry first, but this will get fixed by the multichannel cleanup
5096 when all identical client_guids get handled by a single smbd.
5097 **************************************************************/
5099 static void lease_match_parser_new_file(
5101 const struct leases_db_file *files,
5102 struct lease_match_state *state)
5106 for (i = 0; i < num_files; i++) {
5107 const struct leases_db_file *f = &files[i];
5108 if (strequal(state->servicepath, f->servicepath)) {
5109 state->match_status = NT_STATUS_INVALID_PARAMETER;
5114 /* Dynamic share case. Break leases on all other files. */
5115 state->match_status = leases_db_copy_file_ids(state->mem_ctx,
5119 if (!NT_STATUS_IS_OK(state->match_status)) {
5123 state->num_file_ids = num_files;
5124 state->match_status = NT_STATUS_OPLOCK_NOT_GRANTED;
5128 static void lease_match_parser(
5130 const struct leases_db_file *files,
5133 struct lease_match_state *state =
5134 (struct lease_match_state *)private_data;
5137 if (!state->file_existed) {
5139 * Deal with name mismatch or
5140 * possible dynamic share case separately
5141 * to make code clearer.
5143 lease_match_parser_new_file(num_files,
5150 state->match_status = NT_STATUS_OK;
5152 for (i = 0; i < num_files; i++) {
5153 const struct leases_db_file *f = &files[i];
5155 /* Everything should be the same. */
5156 if (!file_id_equal(&state->id, &f->id)) {
5157 /* This should catch all dynamic share cases. */
5158 state->match_status = NT_STATUS_OPLOCK_NOT_GRANTED;
5161 if (!strequal(f->servicepath, state->servicepath)) {
5162 state->match_status = NT_STATUS_INVALID_PARAMETER;
5165 if (!strequal(f->base_name, state->fname->base_name)) {
5166 state->match_status = NT_STATUS_INVALID_PARAMETER;
5169 if (!strequal(f->stream_name, state->fname->stream_name)) {
5170 state->match_status = NT_STATUS_INVALID_PARAMETER;
5175 if (NT_STATUS_IS_OK(state->match_status)) {
5177 * Common case - just opening another handle on a
5178 * file on a non-dynamic share.
5183 if (NT_STATUS_EQUAL(state->match_status, NT_STATUS_INVALID_PARAMETER)) {
5184 /* Mismatched path. Error back to client. */
5189 * File id mismatch. Dynamic share case NT_STATUS_OPLOCK_NOT_GRANTED.
5190 * Don't allow leases.
5193 state->match_status = leases_db_copy_file_ids(state->mem_ctx,
5197 if (!NT_STATUS_IS_OK(state->match_status)) {
5201 state->num_file_ids = num_files;
5202 state->match_status = NT_STATUS_OPLOCK_NOT_GRANTED;
5206 struct lease_match_break_state {
5207 struct messaging_context *msg_ctx;
5208 const struct smb2_lease_key *lease_key;
5216 static bool lease_match_break_fn(
5217 struct share_mode_entry *e,
5220 struct lease_match_break_state *state = private_data;
5222 uint32_t e_lease_type;
5225 stale = share_entry_stale_pid(e);
5230 equal = smb2_lease_key_equal(&e->lease_key, state->lease_key);
5235 status = leases_db_get(
5239 NULL, /* current_state */
5240 NULL, /* breaking */
5241 NULL, /* breaking_to_requested */
5242 NULL, /* breaking_to_required */
5243 &state->version, /* lease_version */
5244 &state->epoch); /* epoch */
5245 if (NT_STATUS_IS_OK(status)) {
5246 state->found_lease = true;
5248 DBG_WARNING("Could not find version/epoch: %s\n",
5252 e_lease_type = get_lease_type(e, state->id);
5253 if (e_lease_type == SMB2_LEASE_NONE) {
5256 send_break_message(state->msg_ctx, &state->id, e, SMB2_LEASE_NONE);
5259 * Windows 7 and 8 lease clients are broken in that they will
5260 * not respond to lease break requests whilst waiting for an
5261 * outstanding open request on that lease handle on the same
5262 * TCP connection, due to holding an internal inode lock.
5264 * This means we can't reschedule ourselves here, but must
5265 * return from the create.
5269 * Send the breaks and then return SMB2_LEASE_NONE in the
5270 * lease handle to cause them to acknowledge the lease
5271 * break. Consultation with Microsoft engineering confirmed
5272 * this approach is safe.
5278 static NTSTATUS lease_match(connection_struct *conn,
5279 struct smb_request *req,
5280 const struct smb2_lease_key *lease_key,
5281 const char *servicepath,
5282 const struct smb_filename *fname,
5283 uint16_t *p_version,
5286 struct smbd_server_connection *sconn = req->sconn;
5287 TALLOC_CTX *tos = talloc_tos();
5288 struct lease_match_state state = {
5290 .servicepath = servicepath,
5292 .match_status = NT_STATUS_OK
5297 state.file_existed = VALID_STAT(fname->st);
5298 if (state.file_existed) {
5299 state.id = vfs_file_id_from_sbuf(conn, &fname->st);
5302 status = leases_db_parse(&sconn->client->connections->smb2.client.guid,
5303 lease_key, lease_match_parser, &state);
5304 if (!NT_STATUS_IS_OK(status)) {
5306 * Not found or error means okay: We can make the lease pass
5308 return NT_STATUS_OK;
5310 if (!NT_STATUS_EQUAL(state.match_status, NT_STATUS_OPLOCK_NOT_GRANTED)) {
5312 * Anything but NT_STATUS_OPLOCK_NOT_GRANTED, let the caller
5315 return state.match_status;
5318 /* We have to break all existing leases. */
5319 for (i = 0; i < state.num_file_ids; i++) {
5320 struct lease_match_break_state break_state = {
5321 .msg_ctx = conn->sconn->msg_ctx,
5322 .lease_key = lease_key,
5324 struct share_mode_lock *lck;
5327 if (file_id_equal(&state.ids[i], &state.id)) {
5328 /* Don't need to break our own file. */
5332 break_state.id = state.ids[i];
5334 lck = get_existing_share_mode_lock(
5335 talloc_tos(), break_state.id);
5337 /* Race condition - file already closed. */
5341 ok = share_mode_forall_leases(
5342 lck, lease_match_break_fn, &break_state);
5344 DBG_DEBUG("share_mode_forall_leases failed\n");
5350 if (break_state.found_lease) {
5351 *p_version = break_state.version;
5352 *p_epoch = break_state.epoch;
5356 * Ensure we don't grant anything more so we
5359 return NT_STATUS_OPLOCK_NOT_GRANTED;
5363 * Wrapper around open_file_ntcreate and open_directory
5366 static NTSTATUS create_file_unixpath(connection_struct *conn,
5367 struct smb_request *req,
5368 struct smb_filename *smb_fname,
5369 uint32_t access_mask,
5370 uint32_t share_access,
5371 uint32_t create_disposition,
5372 uint32_t create_options,
5373 uint32_t file_attributes,
5374 uint32_t oplock_request,
5375 const struct smb2_lease *lease,
5376 uint64_t allocation_size,
5377 uint32_t private_flags,
5378 struct security_descriptor *sd,
5379 struct ea_list *ea_list,
5381 files_struct **result,
5384 struct smb2_lease none_lease;
5385 int info = FILE_WAS_OPENED;
5386 files_struct *base_fsp = NULL;
5387 files_struct *fsp = NULL;
5390 DBG_DEBUG("create_file_unixpath: access_mask = 0x%x "
5391 "file_attributes = 0x%x, share_access = 0x%x, "
5392 "create_disposition = 0x%x create_options = 0x%x "
5393 "oplock_request = 0x%x private_flags = 0x%x "
5394 "ea_list = %p, sd = %p, "
5396 (unsigned int)access_mask,
5397 (unsigned int)file_attributes,
5398 (unsigned int)share_access,
5399 (unsigned int)create_disposition,
5400 (unsigned int)create_options,
5401 (unsigned int)oplock_request,
5402 (unsigned int)private_flags,
5403 ea_list, sd, smb_fname_str_dbg(smb_fname));
5405 if (create_options & FILE_OPEN_BY_FILE_ID) {
5406 status = NT_STATUS_NOT_SUPPORTED;
5410 if (create_options & NTCREATEX_OPTIONS_INVALID_PARAM_MASK) {
5411 status = NT_STATUS_INVALID_PARAMETER;
5416 oplock_request |= INTERNAL_OPEN_ONLY;
5419 if (lease != NULL) {
5420 uint16_t epoch = lease->lease_epoch;
5421 uint16_t version = lease->lease_version;
5424 DBG_WARNING("Got lease on internal open\n");
5425 status = NT_STATUS_INTERNAL_ERROR;
5429 status = lease_match(conn,
5436 if (NT_STATUS_EQUAL(status, NT_STATUS_OPLOCK_NOT_GRANTED)) {
5437 /* Dynamic share file. No leases and update epoch... */
5438 none_lease = *lease;
5439 none_lease.lease_state = SMB2_LEASE_NONE;
5440 none_lease.lease_epoch = epoch;
5441 none_lease.lease_version = version;
5442 lease = &none_lease;
5443 } else if (!NT_STATUS_IS_OK(status)) {
5448 if ((conn->fs_capabilities & FILE_NAMED_STREAMS)
5449 && (access_mask & DELETE_ACCESS)
5450 && !is_ntfs_stream_smb_fname(smb_fname)) {
5452 * We can't open a file with DELETE access if any of the
5453 * streams is open without FILE_SHARE_DELETE
5455 status = open_streams_for_delete(conn, smb_fname);
5457 if (!NT_STATUS_IS_OK(status)) {
5462 if (access_mask & SEC_FLAG_SYSTEM_SECURITY) {
5465 ok = security_token_has_privilege(get_current_nttok(conn),
5468 DBG_DEBUG("open on %s failed - "
5469 "SEC_FLAG_SYSTEM_SECURITY denied.\n",
5470 smb_fname_str_dbg(smb_fname));
5471 status = NT_STATUS_PRIVILEGE_NOT_HELD;
5475 if (conn->sconn->using_smb2 &&
5476 (access_mask == SEC_FLAG_SYSTEM_SECURITY))
5479 * No other bits set. Windows SMB2 refuses this.
5480 * See smbtorture3 SMB2-SACL test.
5482 * Note this is an SMB2-only behavior,
5483 * smbtorture3 SMB1-SYSTEM-SECURITY already tests
5484 * that SMB1 allows this.
5486 status = NT_STATUS_ACCESS_DENIED;
5492 * Files or directories can't be opened DELETE_ON_CLOSE without
5494 * BUG: https://bugzilla.samba.org/show_bug.cgi?id=13358
5496 if (create_options & FILE_DELETE_ON_CLOSE) {
5497 if ((access_mask & DELETE_ACCESS) == 0) {
5498 status = NT_STATUS_INVALID_PARAMETER;
5503 if ((conn->fs_capabilities & FILE_NAMED_STREAMS)
5504 && is_ntfs_stream_smb_fname(smb_fname)
5505 && (!(private_flags & NTCREATEX_OPTIONS_PRIVATE_STREAM_DELETE))) {
5506 uint32_t base_create_disposition;
5507 struct smb_filename *smb_fname_base = NULL;
5508 uint32_t base_privflags;
5510 if (create_options & FILE_DIRECTORY_FILE) {
5511 status = NT_STATUS_NOT_A_DIRECTORY;
5515 switch (create_disposition) {
5517 base_create_disposition = FILE_OPEN;
5520 base_create_disposition = FILE_OPEN_IF;
5524 /* Create an smb_filename with stream_name == NULL. */
5525 smb_fname_base = synthetic_smb_fname(talloc_tos(),
5526 smb_fname->base_name,
5531 if (smb_fname_base == NULL) {
5532 status = NT_STATUS_NO_MEMORY;
5536 if (SMB_VFS_STAT(conn, smb_fname_base) == -1) {
5537 DEBUG(10, ("Unable to stat stream: %s\n",
5538 smb_fname_str_dbg(smb_fname_base)));
5541 * https://bugzilla.samba.org/show_bug.cgi?id=10229
5542 * We need to check if the requested access mask
5543 * could be used to open the underlying file (if
5544 * it existed), as we're passing in zero for the
5545 * access mask to the base filename.
5547 status = check_base_file_access(conn,
5551 if (!NT_STATUS_IS_OK(status)) {
5552 DEBUG(10, ("Permission check "
5553 "for base %s failed: "
5554 "%s\n", smb_fname->base_name,
5555 nt_errstr(status)));
5560 base_privflags = NTCREATEX_OPTIONS_PRIVATE_STREAM_BASEOPEN;
5562 /* Open the base file. */
5563 status = create_file_unixpath(conn, NULL, smb_fname_base, 0,
5566 | FILE_SHARE_DELETE,
5567 base_create_disposition,
5572 TALLOC_FREE(smb_fname_base);
5574 if (!NT_STATUS_IS_OK(status)) {
5575 DEBUG(10, ("create_file_unixpath for base %s failed: "
5576 "%s\n", smb_fname->base_name,
5577 nt_errstr(status)));
5580 /* we don't need the low level fd */
5585 * If it's a request for a directory open, deal with it separately.
5588 if (create_options & FILE_DIRECTORY_FILE) {
5590 if (create_options & FILE_NON_DIRECTORY_FILE) {
5591 status = NT_STATUS_INVALID_PARAMETER;
5595 /* Can't open a temp directory. IFS kit test. */
5596 if (!(file_attributes & FILE_FLAG_POSIX_SEMANTICS) &&
5597 (file_attributes & FILE_ATTRIBUTE_TEMPORARY)) {
5598 status = NT_STATUS_INVALID_PARAMETER;
5603 * We will get a create directory here if the Win32
5604 * app specified a security descriptor in the
5605 * CreateDirectory() call.
5609 status = open_directory(
5610 conn, req, smb_fname, access_mask, share_access,
5611 create_disposition, create_options, file_attributes,
5616 * Ordinary file case.
5619 status = file_new(req, conn, &fsp);
5620 if(!NT_STATUS_IS_OK(status)) {
5624 status = fsp_set_smb_fname(fsp, smb_fname);
5625 if (!NT_STATUS_IS_OK(status)) {
5631 * We're opening the stream element of a
5632 * base_fsp we already opened. Set up the
5635 fsp->base_fsp = base_fsp;
5638 if (allocation_size) {
5639 fsp->initial_allocation_size = smb_roundup(fsp->conn,
5643 status = open_file_ntcreate(conn,
5656 if(!NT_STATUS_IS_OK(status)) {
5657 file_free(req, fsp);
5661 if (NT_STATUS_EQUAL(status, NT_STATUS_FILE_IS_A_DIRECTORY)) {
5663 /* A stream open never opens a directory */
5666 status = NT_STATUS_FILE_IS_A_DIRECTORY;
5671 * Fail the open if it was explicitly a non-directory
5675 if (create_options & FILE_NON_DIRECTORY_FILE) {
5676 status = NT_STATUS_FILE_IS_A_DIRECTORY;
5681 status = open_directory(
5682 conn, req, smb_fname, access_mask,
5683 share_access, create_disposition,
5684 create_options, file_attributes,
5689 if (!NT_STATUS_IS_OK(status)) {
5693 fsp->base_fsp = base_fsp;
5695 if ((ea_list != NULL) &&
5696 ((info == FILE_WAS_CREATED) || (info == FILE_WAS_OVERWRITTEN))) {
5697 status = set_ea(conn, fsp, fsp->fsp_name, ea_list);
5698 if (!NT_STATUS_IS_OK(status)) {
5703 if (!fsp->fsp_flags.is_directory &&
5704 S_ISDIR(fsp->fsp_name->st.st_ex_mode))
5706 status = NT_STATUS_ACCESS_DENIED;
5710 /* Save the requested allocation size. */
5711 if ((info == FILE_WAS_CREATED) || (info == FILE_WAS_OVERWRITTEN)) {
5712 if ((allocation_size > (uint64_t)fsp->fsp_name->st.st_ex_size)
5713 && !(fsp->fsp_flags.is_directory))
5715 fsp->initial_allocation_size = smb_roundup(
5716 fsp->conn, allocation_size);
5717 if (vfs_allocate_file_space(
5718 fsp, fsp->initial_allocation_size) == -1) {
5719 status = NT_STATUS_DISK_FULL;
5723 fsp->initial_allocation_size = smb_roundup(
5724 fsp->conn, (uint64_t)fsp->fsp_name->st.st_ex_size);
5727 fsp->initial_allocation_size = 0;
5730 if ((info == FILE_WAS_CREATED) && lp_nt_acl_support(SNUM(conn)) &&
5731 fsp->base_fsp == NULL) {
5734 * According to the MS documentation, the only time the security
5735 * descriptor is applied to the opened file is iff we *created* the
5736 * file; an existing file stays the same.
5738 * Also, it seems (from observation) that you can open the file with
5739 * any access mask but you can still write the sd. We need to override
5740 * the granted access before we call set_sd
5741 * Patch for bug #2242 from Tom Lackemann <cessnatomny@yahoo.com>.
5744 uint32_t sec_info_sent;
5745 uint32_t saved_access_mask = fsp->access_mask;
5747 sec_info_sent = get_sec_info(sd);
5749 fsp->access_mask = FILE_GENERIC_ALL;
5751 if (sec_info_sent & (SECINFO_OWNER|
5755 status = set_sd(fsp, sd, sec_info_sent);
5758 fsp->access_mask = saved_access_mask;
5760 if (!NT_STATUS_IS_OK(status)) {
5763 } else if (lp_inherit_acls(SNUM(conn))) {
5764 /* Inherit from parent. Errors here are not fatal. */
5765 status = inherit_new_acl(fsp);
5766 if (!NT_STATUS_IS_OK(status)) {
5767 DEBUG(10,("inherit_new_acl: failed for %s with %s\n",
5769 nt_errstr(status) ));
5774 if ((conn->fs_capabilities & FILE_FILE_COMPRESSION)
5775 && (create_options & FILE_NO_COMPRESSION)
5776 && (info == FILE_WAS_CREATED)) {
5777 status = SMB_VFS_SET_COMPRESSION(conn, fsp, fsp,
5778 COMPRESSION_FORMAT_NONE);
5779 if (!NT_STATUS_IS_OK(status)) {
5780 DEBUG(1, ("failed to disable compression: %s\n",
5781 nt_errstr(status)));
5785 DEBUG(10, ("create_file_unixpath: info=%d\n", info));
5788 if (pinfo != NULL) {
5792 smb_fname->st = fsp->fsp_name->st;
5794 return NT_STATUS_OK;
5797 DEBUG(10, ("create_file_unixpath: %s\n", nt_errstr(status)));
5800 if (base_fsp && fsp->base_fsp == base_fsp) {
5802 * The close_file below will close
5807 close_file(req, fsp, ERROR_CLOSE);
5810 if (base_fsp != NULL) {
5811 close_file(req, base_fsp, ERROR_CLOSE);
5818 * Calculate the full path name given a relative fid.
5820 static NTSTATUS get_relative_fid_filename(
5821 connection_struct *conn,
5822 struct smb_request *req,
5823 uint16_t root_dir_fid,
5824 const struct smb_filename *smb_fname,
5825 struct smb_filename **smb_fname_out)
5827 files_struct *dir_fsp;
5828 char *parent_fname = NULL;
5829 char *new_base_name = NULL;
5830 uint32_t ucf_flags = ucf_flags_from_smb_request(req);
5833 if (root_dir_fid == 0 || !smb_fname) {
5834 status = NT_STATUS_INTERNAL_ERROR;
5838 dir_fsp = file_fsp(req, root_dir_fid);
5840 if (dir_fsp == NULL) {
5841 status = NT_STATUS_INVALID_HANDLE;
5845 if (is_ntfs_stream_smb_fname(dir_fsp->fsp_name)) {
5846 status = NT_STATUS_INVALID_HANDLE;
5850 if (!dir_fsp->fsp_flags.is_directory) {
5853 * Check to see if this is a mac fork of some kind.
5856 if ((conn->fs_capabilities & FILE_NAMED_STREAMS) &&
5857 is_ntfs_stream_smb_fname(smb_fname)) {
5858 status = NT_STATUS_OBJECT_PATH_NOT_FOUND;
5863 we need to handle the case when we get a
5864 relative open relative to a file and the
5865 pathname is blank - this is a reopen!
5866 (hint from demyn plantenberg)
5869 status = NT_STATUS_INVALID_HANDLE;
5873 if (ISDOT(dir_fsp->fsp_name->base_name)) {
5875 * We're at the toplevel dir, the final file name
5876 * must not contain ./, as this is filtered out
5877 * normally by srvstr_get_path and unix_convert
5878 * explicitly rejects paths containing ./.
5880 parent_fname = talloc_strdup(talloc_tos(), "");
5881 if (parent_fname == NULL) {
5882 status = NT_STATUS_NO_MEMORY;
5886 size_t dir_name_len = strlen(dir_fsp->fsp_name->base_name);
5889 * Copy in the base directory name.
5892 parent_fname = talloc_array(talloc_tos(), char,
5894 if (parent_fname == NULL) {
5895 status = NT_STATUS_NO_MEMORY;
5898 memcpy(parent_fname, dir_fsp->fsp_name->base_name,
5902 * Ensure it ends in a '/'.
5903 * We used TALLOC_SIZE +2 to add space for the '/'.
5907 && (parent_fname[dir_name_len-1] != '\\')
5908 && (parent_fname[dir_name_len-1] != '/')) {
5909 parent_fname[dir_name_len] = '/';
5910 parent_fname[dir_name_len+1] = '\0';
5914 new_base_name = talloc_asprintf(talloc_tos(), "%s%s", parent_fname,
5915 smb_fname->base_name);
5916 if (new_base_name == NULL) {
5917 status = NT_STATUS_NO_MEMORY;
5921 status = filename_convert(req,
5928 if (!NT_STATUS_IS_OK(status)) {
5933 TALLOC_FREE(parent_fname);
5934 TALLOC_FREE(new_base_name);
5938 NTSTATUS create_file_default(connection_struct *conn,
5939 struct smb_request *req,
5940 uint16_t root_dir_fid,
5941 struct smb_filename *smb_fname,
5942 uint32_t access_mask,
5943 uint32_t share_access,
5944 uint32_t create_disposition,
5945 uint32_t create_options,
5946 uint32_t file_attributes,
5947 uint32_t oplock_request,
5948 const struct smb2_lease *lease,
5949 uint64_t allocation_size,
5950 uint32_t private_flags,
5951 struct security_descriptor *sd,
5952 struct ea_list *ea_list,
5953 files_struct **result,
5955 const struct smb2_create_blobs *in_context_blobs,
5956 struct smb2_create_blobs *out_context_blobs)
5958 int info = FILE_WAS_OPENED;
5959 files_struct *fsp = NULL;
5961 bool stream_name = false;
5962 struct smb2_create_blob *posx = NULL;
5964 DBG_DEBUG("create_file: access_mask = 0x%x "
5965 "file_attributes = 0x%x, share_access = 0x%x, "
5966 "create_disposition = 0x%x create_options = 0x%x "
5967 "oplock_request = 0x%x "
5968 "private_flags = 0x%x "
5969 "root_dir_fid = 0x%x, ea_list = %p, sd = %p, "
5971 (unsigned int)access_mask,
5972 (unsigned int)file_attributes,
5973 (unsigned int)share_access,
5974 (unsigned int)create_disposition,
5975 (unsigned int)create_options,
5976 (unsigned int)oplock_request,
5977 (unsigned int)private_flags,
5978 (unsigned int)root_dir_fid,
5979 ea_list, sd, smb_fname_str_dbg(smb_fname));
5983 * Remember the absolute time of the original request
5984 * with this mid. We'll use it later to see if this
5987 get_deferred_open_message_state(req, &req->request_time, NULL);
5991 * Calculate the filename from the root_dir_if if necessary.
5994 if (root_dir_fid != 0) {
5995 struct smb_filename *smb_fname_out = NULL;
5996 status = get_relative_fid_filename(conn, req, root_dir_fid,
5997 smb_fname, &smb_fname_out);
5998 if (!NT_STATUS_IS_OK(status)) {
6001 smb_fname = smb_fname_out;
6005 * Check to see if this is a mac fork of some kind.
6008 stream_name = is_ntfs_stream_smb_fname(smb_fname);
6010 enum FAKE_FILE_TYPE fake_file_type;
6012 fake_file_type = is_fake_file(smb_fname);
6014 if (fake_file_type != FAKE_FILE_TYPE_NONE) {
6017 * Here we go! support for changing the disk quotas
6020 * We need to fake up to open this MAGIC QUOTA file
6021 * and return a valid FID.
6023 * w2k close this file directly after openening xp
6024 * also tries a QUERY_FILE_INFO on the file and then
6027 status = open_fake_file(req, conn, req->vuid,
6028 fake_file_type, smb_fname,
6030 if (!NT_STATUS_IS_OK(status)) {
6034 ZERO_STRUCT(smb_fname->st);
6038 if (!(conn->fs_capabilities & FILE_NAMED_STREAMS)) {
6039 status = NT_STATUS_OBJECT_NAME_NOT_FOUND;
6044 if (is_ntfs_default_stream_smb_fname(smb_fname)) {
6046 smb_fname->stream_name = NULL;
6047 /* We have to handle this error here. */
6048 if (create_options & FILE_DIRECTORY_FILE) {
6049 status = NT_STATUS_NOT_A_DIRECTORY;
6052 if (req != NULL && req->posix_pathnames) {
6053 ret = SMB_VFS_LSTAT(conn, smb_fname);
6055 ret = SMB_VFS_STAT(conn, smb_fname);
6058 if (ret == 0 && VALID_STAT_OF_DIR(smb_fname->st)) {
6059 status = NT_STATUS_FILE_IS_A_DIRECTORY;
6064 posx = smb2_create_blob_find(
6065 in_context_blobs, SMB2_CREATE_TAG_POSIX);
6067 uint32_t wire_mode_bits = 0;
6068 mode_t mode_bits = 0;
6069 SMB_STRUCT_STAT sbuf = { 0 };
6070 enum perm_type ptype =
6071 (create_options & FILE_DIRECTORY_FILE) ?
6072 PERM_NEW_DIR : PERM_NEW_FILE;
6074 if (posx->data.length != 4) {
6075 status = NT_STATUS_INVALID_PARAMETER;
6079 wire_mode_bits = IVAL(posx->data.data, 0);
6080 status = unix_perms_from_wire(
6081 conn, &sbuf, wire_mode_bits, ptype, &mode_bits);
6082 if (!NT_STATUS_IS_OK(status)) {
6086 * Remove type info from mode, leaving only the
6087 * permissions and setuid/gid bits.
6089 mode_bits &= ~S_IFMT;
6091 file_attributes = (FILE_FLAG_POSIX_SEMANTICS | mode_bits);
6094 status = create_file_unixpath(
6095 conn, req, smb_fname, access_mask, share_access,
6096 create_disposition, create_options, file_attributes,
6097 oplock_request, lease, allocation_size, private_flags,
6101 if (!NT_STATUS_IS_OK(status)) {
6106 DEBUG(10, ("create_file: info=%d\n", info));
6109 if (pinfo != NULL) {
6112 return NT_STATUS_OK;
6115 DEBUG(10, ("create_file: %s\n", nt_errstr(status)));
6118 close_file(req, fsp, ERROR_CLOSE);