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
8 This program is free software; you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation; either version 3 of the License, or
11 (at your option) any later version.
13 This program is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with this program. If not, see <http://www.gnu.org/licenses/>.
23 #include "system/filesys.h"
25 #include "smbd/smbd.h"
26 #include "smbd/globals.h"
27 #include "fake_file.h"
28 #include "../libcli/security/security.h"
29 #include "../librpc/gen_ndr/ndr_security.h"
30 #include "../librpc/gen_ndr/open_files.h"
31 #include "../librpc/gen_ndr/idmap.h"
32 #include "../librpc/gen_ndr/ioctl.h"
33 #include "passdb/lookup_sid.h"
37 #include "source3/lib/dbwrap/dbwrap_watch.h"
38 #include "locking/leases_db.h"
39 #include "librpc/gen_ndr/ndr_leases_db.h"
41 extern const struct generic_mapping file_generic_mapping;
43 struct deferred_open_record {
44 bool delayed_for_oplocks;
49 /****************************************************************************
50 If the requester wanted DELETE_ACCESS and was rejected because
51 the file ACL didn't include DELETE_ACCESS, see if the parent ACL
53 ****************************************************************************/
55 static bool parent_override_delete(connection_struct *conn,
56 const struct smb_filename *smb_fname,
58 uint32_t rejected_mask)
60 if ((access_mask & DELETE_ACCESS) &&
61 (rejected_mask & DELETE_ACCESS) &&
62 can_delete_file_in_directory(conn, smb_fname)) {
68 /****************************************************************************
69 Check if we have open rights.
70 ****************************************************************************/
72 NTSTATUS smbd_check_access_rights(struct connection_struct *conn,
73 const struct smb_filename *smb_fname,
77 /* Check if we have rights to open. */
79 struct security_descriptor *sd = NULL;
80 uint32_t rejected_share_access;
81 uint32_t rejected_mask = access_mask;
82 uint32_t do_not_check_mask = 0;
84 rejected_share_access = access_mask & ~(conn->share_access);
86 if (rejected_share_access) {
87 DEBUG(10, ("smbd_check_access_rights: rejected share access 0x%x "
89 (unsigned int)access_mask,
90 smb_fname_str_dbg(smb_fname),
91 (unsigned int)rejected_share_access ));
92 return NT_STATUS_ACCESS_DENIED;
95 if (!use_privs && get_current_uid(conn) == (uid_t)0) {
96 /* I'm sorry sir, I didn't know you were root... */
97 DEBUG(10,("smbd_check_access_rights: root override "
98 "on %s. Granting 0x%x\n",
99 smb_fname_str_dbg(smb_fname),
100 (unsigned int)access_mask ));
104 if ((access_mask & DELETE_ACCESS) && !lp_acl_check_permissions(SNUM(conn))) {
105 DEBUG(10,("smbd_check_access_rights: not checking ACL "
106 "on DELETE_ACCESS on file %s. Granting 0x%x\n",
107 smb_fname_str_dbg(smb_fname),
108 (unsigned int)access_mask ));
112 if (access_mask == DELETE_ACCESS &&
113 VALID_STAT(smb_fname->st) &&
114 S_ISLNK(smb_fname->st.st_ex_mode)) {
115 /* We can always delete a symlink. */
116 DEBUG(10,("smbd_check_access_rights: not checking ACL "
117 "on DELETE_ACCESS on symlink %s.\n",
118 smb_fname_str_dbg(smb_fname) ));
122 status = SMB_VFS_GET_NT_ACL(conn, smb_fname,
125 SECINFO_DACL), talloc_tos(), &sd);
127 if (!NT_STATUS_IS_OK(status)) {
128 DEBUG(10, ("smbd_check_access_rights: Could not get acl "
130 smb_fname_str_dbg(smb_fname),
133 if (NT_STATUS_EQUAL(status, NT_STATUS_ACCESS_DENIED)) {
141 * If we can access the path to this file, by
142 * default we have FILE_READ_ATTRIBUTES from the
143 * containing directory. See the section:
144 * "Algorithm to Check Access to an Existing File"
147 * se_file_access_check() also takes care of
148 * owner WRITE_DAC and READ_CONTROL.
150 do_not_check_mask = FILE_READ_ATTRIBUTES;
153 * Samba 3.6 and earlier granted execute access even
154 * if the ACL did not contain execute rights.
155 * Samba 4.0 is more correct and checks it.
156 * The compatibilty mode allows one to skip this check
157 * to smoothen upgrades.
159 if (lp_acl_allow_execute_always(SNUM(conn))) {
160 do_not_check_mask |= FILE_EXECUTE;
163 status = se_file_access_check(sd,
164 get_current_nttok(conn),
166 (access_mask & ~do_not_check_mask),
169 DEBUG(10,("smbd_check_access_rights: file %s requesting "
170 "0x%x returning 0x%x (%s)\n",
171 smb_fname_str_dbg(smb_fname),
172 (unsigned int)access_mask,
173 (unsigned int)rejected_mask,
174 nt_errstr(status) ));
176 if (!NT_STATUS_IS_OK(status)) {
177 if (DEBUGLEVEL >= 10) {
178 DEBUG(10,("smbd_check_access_rights: acl for %s is:\n",
179 smb_fname_str_dbg(smb_fname) ));
180 NDR_PRINT_DEBUG(security_descriptor, sd);
186 if (NT_STATUS_IS_OK(status) ||
187 !NT_STATUS_EQUAL(status, NT_STATUS_ACCESS_DENIED)) {
191 /* Here we know status == NT_STATUS_ACCESS_DENIED. */
195 if ((access_mask & FILE_WRITE_ATTRIBUTES) &&
196 (rejected_mask & FILE_WRITE_ATTRIBUTES) &&
197 !lp_store_dos_attributes(SNUM(conn)) &&
198 (lp_map_readonly(SNUM(conn)) ||
199 lp_map_archive(SNUM(conn)) ||
200 lp_map_hidden(SNUM(conn)) ||
201 lp_map_system(SNUM(conn)))) {
202 rejected_mask &= ~FILE_WRITE_ATTRIBUTES;
204 DEBUG(10,("smbd_check_access_rights: "
206 "FILE_WRITE_ATTRIBUTES "
208 smb_fname_str_dbg(smb_fname)));
211 if (parent_override_delete(conn,
215 /* Were we trying to do an open
216 * for delete and didn't get DELETE
217 * access (only) ? Check if the
218 * directory allows DELETE_CHILD.
220 * http://blogs.msdn.com/oldnewthing/archive/2004/06/04/148426.aspx
223 rejected_mask &= ~DELETE_ACCESS;
225 DEBUG(10,("smbd_check_access_rights: "
229 smb_fname_str_dbg(smb_fname)));
232 if (rejected_mask != 0) {
233 return NT_STATUS_ACCESS_DENIED;
238 static NTSTATUS check_parent_access(struct connection_struct *conn,
239 struct smb_filename *smb_fname,
240 uint32_t access_mask)
243 char *parent_dir = NULL;
244 struct security_descriptor *parent_sd = NULL;
245 uint32_t access_granted = 0;
246 struct smb_filename *parent_smb_fname = NULL;
248 if (!parent_dirname(talloc_tos(),
249 smb_fname->base_name,
252 return NT_STATUS_NO_MEMORY;
255 parent_smb_fname = synthetic_smb_fname(talloc_tos(),
259 if (parent_smb_fname == NULL) {
260 return NT_STATUS_NO_MEMORY;
263 if (get_current_uid(conn) == (uid_t)0) {
264 /* I'm sorry sir, I didn't know you were root... */
265 DEBUG(10,("check_parent_access: root override "
266 "on %s. Granting 0x%x\n",
267 smb_fname_str_dbg(smb_fname),
268 (unsigned int)access_mask ));
272 status = SMB_VFS_GET_NT_ACL(conn,
278 if (!NT_STATUS_IS_OK(status)) {
279 DEBUG(5,("check_parent_access: SMB_VFS_GET_NT_ACL failed for "
280 "%s with error %s\n",
287 * If we can access the path to this file, by
288 * default we have FILE_READ_ATTRIBUTES from the
289 * containing directory. See the section:
290 * "Algorithm to Check Access to an Existing File"
293 * se_file_access_check() also takes care of
294 * owner WRITE_DAC and READ_CONTROL.
296 status = se_file_access_check(parent_sd,
297 get_current_nttok(conn),
299 (access_mask & ~FILE_READ_ATTRIBUTES),
301 if(!NT_STATUS_IS_OK(status)) {
302 DEBUG(5,("check_parent_access: access check "
303 "on directory %s for "
304 "path %s for mask 0x%x returned (0x%x) %s\n",
306 smb_fname->base_name,
309 nt_errstr(status) ));
316 /****************************************************************************
317 Ensure when opening a base file for a stream open that we have permissions
318 to do so given the access mask on the base file.
319 ****************************************************************************/
321 static NTSTATUS check_base_file_access(struct connection_struct *conn,
322 struct smb_filename *smb_fname,
323 uint32_t access_mask)
327 status = smbd_calculate_access_mask(conn, smb_fname,
331 if (!NT_STATUS_IS_OK(status)) {
332 DEBUG(10, ("smbd_calculate_access_mask "
333 "on file %s returned %s\n",
334 smb_fname_str_dbg(smb_fname),
339 if (access_mask & (FILE_WRITE_DATA|FILE_APPEND_DATA)) {
341 if (!CAN_WRITE(conn)) {
342 return NT_STATUS_ACCESS_DENIED;
344 dosattrs = dos_mode(conn, smb_fname);
345 if (IS_DOS_READONLY(dosattrs)) {
346 return NT_STATUS_ACCESS_DENIED;
350 return smbd_check_access_rights(conn,
356 /****************************************************************************
357 fd support routines - attempt to do a dos_open.
358 ****************************************************************************/
360 NTSTATUS fd_open(struct connection_struct *conn,
365 struct smb_filename *smb_fname = fsp->fsp_name;
366 NTSTATUS status = NT_STATUS_OK;
370 * Never follow symlinks on a POSIX client. The
371 * client should be doing this.
374 if ((fsp->posix_flags & FSP_POSIX_FLAGS_OPEN) || !lp_follow_symlinks(SNUM(conn))) {
379 fsp->fh->fd = SMB_VFS_OPEN(conn, smb_fname, fsp, flags, mode);
380 if (fsp->fh->fd == -1) {
381 int posix_errno = errno;
383 #if defined(ENOTSUP) && defined(OSF1)
384 /* handle special Tru64 errno */
385 if (errno == ENOTSUP) {
390 /* fix broken NetBSD errno */
391 if (errno == EFTYPE) {
395 /* fix broken FreeBSD errno */
396 if (errno == EMLINK) {
399 #endif /* O_NOFOLLOW */
400 status = map_nt_error_from_unix(posix_errno);
401 if (errno == EMFILE) {
402 static time_t last_warned = 0L;
404 if (time((time_t *) NULL) > last_warned) {
405 DEBUG(0,("Too many open files, unable "
406 "to open more! smbd's max "
408 lp_max_open_files()));
409 last_warned = time((time_t *) NULL);
415 DEBUG(10,("fd_open: name %s, flags = 0%o mode = 0%o, fd = %d. %s\n",
416 smb_fname_str_dbg(smb_fname), flags, (int)mode, fsp->fh->fd,
417 (fsp->fh->fd == -1) ? strerror(errno) : "" ));
422 /****************************************************************************
423 Close the file associated with a fsp.
424 ****************************************************************************/
426 NTSTATUS fd_close(files_struct *fsp)
433 if (fsp->fh->fd == -1) {
434 return NT_STATUS_OK; /* What we used to call a stat open. */
436 if (fsp->fh->ref_count > 1) {
437 return NT_STATUS_OK; /* Shared handle. Only close last reference. */
440 ret = SMB_VFS_CLOSE(fsp);
443 return map_nt_error_from_unix(errno);
448 /****************************************************************************
449 Change the ownership of a file to that of the parent directory.
450 Do this by fd if possible.
451 ****************************************************************************/
453 void change_file_owner_to_parent(connection_struct *conn,
454 const char *inherit_from_dir,
457 struct smb_filename *smb_fname_parent;
460 smb_fname_parent = synthetic_smb_fname(talloc_tos(), inherit_from_dir,
462 if (smb_fname_parent == NULL) {
466 ret = SMB_VFS_STAT(conn, smb_fname_parent);
468 DEBUG(0,("change_file_owner_to_parent: failed to stat parent "
469 "directory %s. Error was %s\n",
470 smb_fname_str_dbg(smb_fname_parent),
472 TALLOC_FREE(smb_fname_parent);
476 if (smb_fname_parent->st.st_ex_uid == fsp->fsp_name->st.st_ex_uid) {
477 /* Already this uid - no need to change. */
478 DEBUG(10,("change_file_owner_to_parent: file %s "
479 "is already owned by uid %d\n",
481 (int)fsp->fsp_name->st.st_ex_uid ));
482 TALLOC_FREE(smb_fname_parent);
487 ret = SMB_VFS_FCHOWN(fsp, smb_fname_parent->st.st_ex_uid, (gid_t)-1);
490 DEBUG(0,("change_file_owner_to_parent: failed to fchown "
491 "file %s to parent directory uid %u. Error "
492 "was %s\n", fsp_str_dbg(fsp),
493 (unsigned int)smb_fname_parent->st.st_ex_uid,
496 DEBUG(10,("change_file_owner_to_parent: changed new file %s to "
497 "parent directory uid %u.\n", fsp_str_dbg(fsp),
498 (unsigned int)smb_fname_parent->st.st_ex_uid));
499 /* Ensure the uid entry is updated. */
500 fsp->fsp_name->st.st_ex_uid = smb_fname_parent->st.st_ex_uid;
503 TALLOC_FREE(smb_fname_parent);
506 NTSTATUS change_dir_owner_to_parent(connection_struct *conn,
507 const char *inherit_from_dir,
509 SMB_STRUCT_STAT *psbuf)
511 struct smb_filename *smb_fname_parent;
512 struct smb_filename *smb_fname_cwd = NULL;
513 char *saved_dir = NULL;
514 TALLOC_CTX *ctx = talloc_tos();
515 NTSTATUS status = NT_STATUS_OK;
518 smb_fname_parent = synthetic_smb_fname(ctx, inherit_from_dir,
520 if (smb_fname_parent == NULL) {
521 return NT_STATUS_NO_MEMORY;
524 ret = SMB_VFS_STAT(conn, smb_fname_parent);
526 status = map_nt_error_from_unix(errno);
527 DEBUG(0,("change_dir_owner_to_parent: failed to stat parent "
528 "directory %s. Error was %s\n",
529 smb_fname_str_dbg(smb_fname_parent),
534 /* We've already done an lstat into psbuf, and we know it's a
535 directory. If we can cd into the directory and the dev/ino
536 are the same then we can safely chown without races as
537 we're locking the directory in place by being in it. This
538 should work on any UNIX (thanks tridge :-). JRA.
541 saved_dir = vfs_GetWd(ctx,conn);
543 status = map_nt_error_from_unix(errno);
544 DEBUG(0,("change_dir_owner_to_parent: failed to get "
545 "current working directory. Error was %s\n",
550 /* Chdir into the new path. */
551 if (vfs_ChDir(conn, fname) == -1) {
552 status = map_nt_error_from_unix(errno);
553 DEBUG(0,("change_dir_owner_to_parent: failed to change "
554 "current working directory to %s. Error "
555 "was %s\n", fname, strerror(errno) ));
559 smb_fname_cwd = synthetic_smb_fname(ctx, ".", NULL, NULL);
560 if (smb_fname_cwd == NULL) {
561 status = NT_STATUS_NO_MEMORY;
565 ret = SMB_VFS_STAT(conn, smb_fname_cwd);
567 status = map_nt_error_from_unix(errno);
568 DEBUG(0,("change_dir_owner_to_parent: failed to stat "
569 "directory '.' (%s) Error was %s\n",
570 fname, strerror(errno)));
574 /* Ensure we're pointing at the same place. */
575 if (smb_fname_cwd->st.st_ex_dev != psbuf->st_ex_dev ||
576 smb_fname_cwd->st.st_ex_ino != psbuf->st_ex_ino) {
577 DEBUG(0,("change_dir_owner_to_parent: "
578 "device/inode on directory %s changed. "
579 "Refusing to chown !\n", fname ));
580 status = NT_STATUS_ACCESS_DENIED;
584 if (smb_fname_parent->st.st_ex_uid == smb_fname_cwd->st.st_ex_uid) {
585 /* Already this uid - no need to change. */
586 DEBUG(10,("change_dir_owner_to_parent: directory %s "
587 "is already owned by uid %d\n",
589 (int)smb_fname_cwd->st.st_ex_uid ));
590 status = NT_STATUS_OK;
595 ret = SMB_VFS_LCHOWN(conn, ".", smb_fname_parent->st.st_ex_uid,
599 status = map_nt_error_from_unix(errno);
600 DEBUG(10,("change_dir_owner_to_parent: failed to chown "
601 "directory %s to parent directory uid %u. "
602 "Error was %s\n", fname,
603 (unsigned int)smb_fname_parent->st.st_ex_uid,
606 DEBUG(10,("change_dir_owner_to_parent: changed ownership of new "
607 "directory %s to parent directory uid %u.\n",
608 fname, (unsigned int)smb_fname_parent->st.st_ex_uid ));
609 /* Ensure the uid entry is updated. */
610 psbuf->st_ex_uid = smb_fname_parent->st.st_ex_uid;
614 vfs_ChDir(conn,saved_dir);
616 TALLOC_FREE(smb_fname_parent);
617 TALLOC_FREE(smb_fname_cwd);
621 /****************************************************************************
622 Open a file - returning a guaranteed ATOMIC indication of if the
623 file was created or not.
624 ****************************************************************************/
626 static NTSTATUS fd_open_atomic(struct connection_struct *conn,
632 NTSTATUS status = NT_STATUS_UNSUCCESSFUL;
633 bool file_existed = VALID_STAT(fsp->fsp_name->st);
635 *file_created = false;
637 if (!(flags & O_CREAT)) {
639 * We're not creating the file, just pass through.
641 return fd_open(conn, fsp, flags, mode);
644 if (flags & O_EXCL) {
646 * Fail if already exists, just pass through.
648 status = fd_open(conn, fsp, flags, mode);
651 * Here we've opened with O_CREAT|O_EXCL. If that went
652 * NT_STATUS_OK, we *know* we created this file.
654 *file_created = NT_STATUS_IS_OK(status);
660 * Now it gets tricky. We have O_CREAT, but not O_EXCL.
661 * To know absolutely if we created the file or not,
662 * we can never call O_CREAT without O_EXCL. So if
663 * we think the file existed, try without O_CREAT|O_EXCL.
664 * If we think the file didn't exist, try with
665 * O_CREAT|O_EXCL. Keep bouncing between these two
666 * requests until either the file is created, or
667 * opened. Either way, we keep going until we get
668 * a returnable result (error, or open/create).
672 int curr_flags = flags;
675 /* Just try open, do not create. */
676 curr_flags &= ~(O_CREAT);
677 status = fd_open(conn, fsp, curr_flags, mode);
678 if (NT_STATUS_EQUAL(status,
679 NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
681 * Someone deleted it in the meantime.
684 file_existed = false;
685 DEBUG(10,("fd_open_atomic: file %s existed. "
687 smb_fname_str_dbg(fsp->fsp_name)));
691 /* Try create exclusively, fail if it exists. */
692 curr_flags |= O_EXCL;
693 status = fd_open(conn, fsp, curr_flags, mode);
694 if (NT_STATUS_EQUAL(status,
695 NT_STATUS_OBJECT_NAME_COLLISION)) {
697 * Someone created it in the meantime.
698 * Retry without O_CREAT.
701 DEBUG(10,("fd_open_atomic: file %s "
702 "did not exist. Retry.\n",
703 smb_fname_str_dbg(fsp->fsp_name)));
706 if (NT_STATUS_IS_OK(status)) {
708 * Here we've opened with O_CREAT|O_EXCL
709 * and got success. We *know* we created
712 *file_created = true;
715 /* Create is done, or failed. */
721 /****************************************************************************
723 ****************************************************************************/
725 static NTSTATUS open_file(files_struct *fsp,
726 connection_struct *conn,
727 struct smb_request *req,
728 const char *parent_dir,
731 uint32_t access_mask, /* client requested access mask. */
732 uint32_t open_access_mask, /* what we're actually using in the open. */
733 bool *p_file_created)
735 struct smb_filename *smb_fname = fsp->fsp_name;
736 NTSTATUS status = NT_STATUS_OK;
737 int accmode = (flags & O_ACCMODE);
738 int local_flags = flags;
739 bool file_existed = VALID_STAT(fsp->fsp_name->st);
744 /* Check permissions */
747 * This code was changed after seeing a client open request
748 * containing the open mode of (DENY_WRITE/read-only) with
749 * the 'create if not exist' bit set. The previous code
750 * would fail to open the file read only on a read-only share
751 * as it was checking the flags parameter directly against O_RDONLY,
752 * this was failing as the flags parameter was set to O_RDONLY|O_CREAT.
756 if (!CAN_WRITE(conn)) {
757 /* It's a read-only share - fail if we wanted to write. */
758 if(accmode != O_RDONLY || (flags & O_TRUNC) || (flags & O_APPEND)) {
759 DEBUG(3,("Permission denied opening %s\n",
760 smb_fname_str_dbg(smb_fname)));
761 return NT_STATUS_ACCESS_DENIED;
763 if (flags & O_CREAT) {
764 /* We don't want to write - but we must make sure that
765 O_CREAT doesn't create the file if we have write
766 access into the directory.
768 flags &= ~(O_CREAT|O_EXCL);
769 local_flags &= ~(O_CREAT|O_EXCL);
774 * This little piece of insanity is inspired by the
775 * fact that an NT client can open a file for O_RDONLY,
776 * but set the create disposition to FILE_EXISTS_TRUNCATE.
777 * If the client *can* write to the file, then it expects to
778 * truncate the file, even though it is opening for readonly.
779 * Quicken uses this stupid trick in backup file creation...
780 * Thanks *greatly* to "David W. Chapman Jr." <dwcjr@inethouston.net>
781 * for helping track this one down. It didn't bite us in 2.0.x
782 * as we always opened files read-write in that release. JRA.
785 if ((accmode == O_RDONLY) && ((flags & O_TRUNC) == O_TRUNC)) {
786 DEBUG(10,("open_file: truncate requested on read-only open "
787 "for file %s\n", smb_fname_str_dbg(smb_fname)));
788 local_flags = (flags & ~O_ACCMODE)|O_RDWR;
791 if ((open_access_mask & (FILE_READ_DATA|FILE_WRITE_DATA|FILE_APPEND_DATA|FILE_EXECUTE)) ||
792 (!file_existed && (local_flags & O_CREAT)) ||
793 ((local_flags & O_TRUNC) == O_TRUNC) ) {
797 #if defined(O_NONBLOCK) && defined(S_ISFIFO)
799 * We would block on opening a FIFO with no one else on the
800 * other end. Do what we used to do and add O_NONBLOCK to the
804 if (file_existed && S_ISFIFO(smb_fname->st.st_ex_mode)) {
805 local_flags &= ~O_TRUNC; /* Can't truncate a FIFO. */
806 local_flags |= O_NONBLOCK;
810 /* Don't create files with Microsoft wildcard characters. */
813 * wildcard characters are allowed in stream names
814 * only test the basefilename
816 wild = fsp->base_fsp->fsp_name->base_name;
818 wild = smb_fname->base_name;
820 if ((local_flags & O_CREAT) && !file_existed &&
821 !(fsp->posix_flags & FSP_POSIX_FLAGS_PATHNAMES) &&
823 return NT_STATUS_OBJECT_NAME_INVALID;
826 /* Can we access this file ? */
827 if (!fsp->base_fsp) {
828 /* Only do this check on non-stream open. */
830 status = smbd_check_access_rights(conn,
835 if (!NT_STATUS_IS_OK(status)) {
836 DEBUG(10, ("open_file: "
837 "smbd_check_access_rights "
838 "on file %s returned %s\n",
839 smb_fname_str_dbg(smb_fname),
843 if (!NT_STATUS_IS_OK(status) &&
844 !NT_STATUS_EQUAL(status,
845 NT_STATUS_OBJECT_NAME_NOT_FOUND))
850 if (NT_STATUS_EQUAL(status,
851 NT_STATUS_OBJECT_NAME_NOT_FOUND))
853 DEBUG(10, ("open_file: "
854 "file %s vanished since we "
855 "checked for existence.\n",
856 smb_fname_str_dbg(smb_fname)));
857 file_existed = false;
858 SET_STAT_INVALID(fsp->fsp_name->st);
863 if (!(local_flags & O_CREAT)) {
864 /* File didn't exist and no O_CREAT. */
865 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
868 status = check_parent_access(conn,
871 if (!NT_STATUS_IS_OK(status)) {
872 DEBUG(10, ("open_file: "
873 "check_parent_access on "
874 "file %s returned %s\n",
875 smb_fname_str_dbg(smb_fname),
876 nt_errstr(status) ));
883 * Actually do the open - if O_TRUNC is needed handle it
884 * below under the share mode lock.
886 status = fd_open_atomic(conn, fsp, local_flags & ~O_TRUNC,
887 unx_mode, p_file_created);
888 if (!NT_STATUS_IS_OK(status)) {
889 DEBUG(3,("Error opening file %s (%s) (local_flags=%d) "
890 "(flags=%d)\n", smb_fname_str_dbg(smb_fname),
891 nt_errstr(status),local_flags,flags));
895 ret = SMB_VFS_FSTAT(fsp, &smb_fname->st);
897 /* If we have an fd, this stat should succeed. */
898 DEBUG(0,("Error doing fstat on open file %s "
900 smb_fname_str_dbg(smb_fname),
902 status = map_nt_error_from_unix(errno);
907 if (*p_file_created) {
908 /* We created this file. */
910 bool need_re_stat = false;
911 /* Do all inheritance work after we've
912 done a successful fstat call and filled
913 in the stat struct in fsp->fsp_name. */
915 /* Inherit the ACL if required */
916 if (lp_inherit_permissions(SNUM(conn))) {
917 inherit_access_posix_acl(conn, parent_dir,
918 smb_fname->base_name,
923 /* Change the owner if required. */
924 if (lp_inherit_owner(SNUM(conn))) {
925 change_file_owner_to_parent(conn, parent_dir,
931 ret = SMB_VFS_FSTAT(fsp, &smb_fname->st);
932 /* If we have an fd, this stat should succeed. */
934 DEBUG(0,("Error doing fstat on open file %s "
936 smb_fname_str_dbg(smb_fname),
941 notify_fname(conn, NOTIFY_ACTION_ADDED,
942 FILE_NOTIFY_CHANGE_FILE_NAME,
943 smb_fname->base_name);
946 fsp->fh->fd = -1; /* What we used to call a stat open. */
948 /* File must exist for a stat open. */
949 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
952 status = smbd_check_access_rights(conn,
957 if (NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND) &&
958 (fsp->posix_flags & FSP_POSIX_FLAGS_OPEN) &&
959 S_ISLNK(smb_fname->st.st_ex_mode)) {
960 /* This is a POSIX stat open for delete
961 * or rename on a symlink that points
963 DEBUG(10,("open_file: allowing POSIX "
964 "open on bad symlink %s\n",
965 smb_fname_str_dbg(smb_fname)));
966 status = NT_STATUS_OK;
969 if (!NT_STATUS_IS_OK(status)) {
970 DEBUG(10,("open_file: "
971 "smbd_check_access_rights on file "
973 smb_fname_str_dbg(smb_fname),
974 nt_errstr(status) ));
980 * POSIX allows read-only opens of directories. We don't
981 * want to do this (we use a different code path for this)
982 * so catch a directory open and return an EISDIR. JRA.
985 if(S_ISDIR(smb_fname->st.st_ex_mode)) {
988 return NT_STATUS_FILE_IS_A_DIRECTORY;
991 fsp->file_id = vfs_file_id_from_sbuf(conn, &smb_fname->st);
992 fsp->vuid = req ? req->vuid : UID_FIELD_INVALID;
993 fsp->file_pid = req ? req->smbpid : 0;
994 fsp->can_lock = True;
995 fsp->can_read = ((access_mask & FILE_READ_DATA) != 0);
998 ((access_mask & (FILE_WRITE_DATA | FILE_APPEND_DATA)) != 0);
999 fsp->print_file = NULL;
1000 fsp->modified = False;
1001 fsp->sent_oplock_break = NO_BREAK_SENT;
1002 fsp->is_directory = False;
1003 if (conn->aio_write_behind_list &&
1004 is_in_path(smb_fname->base_name, conn->aio_write_behind_list,
1005 conn->case_sensitive)) {
1006 fsp->aio_write_behind = True;
1009 fsp->wcp = NULL; /* Write cache pointer. */
1011 DEBUG(2,("%s opened file %s read=%s write=%s (numopen=%d)\n",
1012 conn->session_info->unix_info->unix_name,
1013 smb_fname_str_dbg(smb_fname),
1014 BOOLSTR(fsp->can_read), BOOLSTR(fsp->can_write),
1015 conn->num_files_open));
1018 return NT_STATUS_OK;
1021 /****************************************************************************
1022 Check if we can open a file with a share mode.
1023 Returns True if conflict, False if not.
1024 ****************************************************************************/
1026 static bool share_conflict(struct share_mode_entry *entry,
1027 uint32_t access_mask,
1028 uint32_t share_access)
1030 DEBUG(10,("share_conflict: entry->access_mask = 0x%x, "
1031 "entry->share_access = 0x%x, "
1032 "entry->private_options = 0x%x\n",
1033 (unsigned int)entry->access_mask,
1034 (unsigned int)entry->share_access,
1035 (unsigned int)entry->private_options));
1037 if (server_id_is_disconnected(&entry->pid)) {
1039 * note: cleanup should have been done by
1040 * delay_for_batch_oplocks()
1045 DEBUG(10,("share_conflict: access_mask = 0x%x, share_access = 0x%x\n",
1046 (unsigned int)access_mask, (unsigned int)share_access));
1048 if ((entry->access_mask & (FILE_WRITE_DATA|
1052 DELETE_ACCESS)) == 0) {
1053 DEBUG(10,("share_conflict: No conflict due to "
1054 "entry->access_mask = 0x%x\n",
1055 (unsigned int)entry->access_mask ));
1059 if ((access_mask & (FILE_WRITE_DATA|
1063 DELETE_ACCESS)) == 0) {
1064 DEBUG(10,("share_conflict: No conflict due to "
1065 "access_mask = 0x%x\n",
1066 (unsigned int)access_mask ));
1070 #if 1 /* JRA TEST - Superdebug. */
1071 #define CHECK_MASK(num, am, right, sa, share) \
1072 DEBUG(10,("share_conflict: [%d] am (0x%x) & right (0x%x) = 0x%x\n", \
1073 (unsigned int)(num), (unsigned int)(am), \
1074 (unsigned int)(right), (unsigned int)(am)&(right) )); \
1075 DEBUG(10,("share_conflict: [%d] sa (0x%x) & share (0x%x) = 0x%x\n", \
1076 (unsigned int)(num), (unsigned int)(sa), \
1077 (unsigned int)(share), (unsigned int)(sa)&(share) )); \
1078 if (((am) & (right)) && !((sa) & (share))) { \
1079 DEBUG(10,("share_conflict: check %d conflict am = 0x%x, right = 0x%x, \
1080 sa = 0x%x, share = 0x%x\n", (num), (unsigned int)(am), (unsigned int)(right), (unsigned int)(sa), \
1081 (unsigned int)(share) )); \
1085 #define CHECK_MASK(num, am, right, sa, share) \
1086 if (((am) & (right)) && !((sa) & (share))) { \
1087 DEBUG(10,("share_conflict: check %d conflict am = 0x%x, right = 0x%x, \
1088 sa = 0x%x, share = 0x%x\n", (num), (unsigned int)(am), (unsigned int)(right), (unsigned int)(sa), \
1089 (unsigned int)(share) )); \
1094 CHECK_MASK(1, entry->access_mask, FILE_WRITE_DATA | FILE_APPEND_DATA,
1095 share_access, FILE_SHARE_WRITE);
1096 CHECK_MASK(2, access_mask, FILE_WRITE_DATA | FILE_APPEND_DATA,
1097 entry->share_access, FILE_SHARE_WRITE);
1099 CHECK_MASK(3, entry->access_mask, FILE_READ_DATA | FILE_EXECUTE,
1100 share_access, FILE_SHARE_READ);
1101 CHECK_MASK(4, access_mask, FILE_READ_DATA | FILE_EXECUTE,
1102 entry->share_access, FILE_SHARE_READ);
1104 CHECK_MASK(5, entry->access_mask, DELETE_ACCESS,
1105 share_access, FILE_SHARE_DELETE);
1106 CHECK_MASK(6, access_mask, DELETE_ACCESS,
1107 entry->share_access, FILE_SHARE_DELETE);
1109 DEBUG(10,("share_conflict: No conflict.\n"));
1113 #if defined(DEVELOPER)
1114 static void validate_my_share_entries(struct smbd_server_connection *sconn,
1116 struct share_mode_entry *share_entry)
1118 struct server_id self = messaging_server_id(sconn->msg_ctx);
1121 if (!serverid_equal(&self, &share_entry->pid)) {
1125 if (share_entry->op_mid == 0) {
1126 /* INTERNAL_OPEN_ONLY */
1130 if (!is_valid_share_mode_entry(share_entry)) {
1134 fsp = file_find_dif(sconn, share_entry->id,
1135 share_entry->share_file_id);
1137 DEBUG(0,("validate_my_share_entries: PANIC : %s\n",
1138 share_mode_str(talloc_tos(), num, share_entry) ));
1139 smb_panic("validate_my_share_entries: Cannot match a "
1140 "share entry with an open file\n");
1143 if (((uint16_t)fsp->oplock_type) != share_entry->op_type) {
1152 DEBUG(0,("validate_my_share_entries: PANIC : %s\n",
1153 share_mode_str(talloc_tos(), num, share_entry) ));
1154 str = talloc_asprintf(talloc_tos(),
1155 "validate_my_share_entries: "
1156 "file %s, oplock_type = 0x%x, op_type = 0x%x\n",
1157 fsp->fsp_name->base_name,
1158 (unsigned int)fsp->oplock_type,
1159 (unsigned int)share_entry->op_type );
1165 bool is_stat_open(uint32_t access_mask)
1167 const uint32_t stat_open_bits =
1168 (SYNCHRONIZE_ACCESS|
1169 FILE_READ_ATTRIBUTES|
1170 FILE_WRITE_ATTRIBUTES);
1172 return (((access_mask & stat_open_bits) != 0) &&
1173 ((access_mask & ~stat_open_bits) == 0));
1176 static bool has_delete_on_close(struct share_mode_lock *lck,
1179 struct share_mode_data *d = lck->data;
1182 if (d->num_share_modes == 0) {
1185 if (!is_delete_on_close_set(lck, name_hash)) {
1188 for (i=0; i<d->num_share_modes; i++) {
1189 if (!share_mode_stale_pid(d, i)) {
1196 /****************************************************************************
1197 Deal with share modes
1198 Invariant: Share mode must be locked on entry and exit.
1199 Returns -1 on error, or number of share modes on success (may be zero).
1200 ****************************************************************************/
1202 static NTSTATUS open_mode_check(connection_struct *conn,
1203 struct share_mode_lock *lck,
1204 uint32_t access_mask,
1205 uint32_t share_access)
1209 if(lck->data->num_share_modes == 0) {
1210 return NT_STATUS_OK;
1213 if (is_stat_open(access_mask)) {
1214 /* Stat open that doesn't trigger oplock breaks or share mode
1215 * checks... ! JRA. */
1216 return NT_STATUS_OK;
1220 * Check if the share modes will give us access.
1223 #if defined(DEVELOPER)
1224 for(i = 0; i < lck->data->num_share_modes; i++) {
1225 validate_my_share_entries(conn->sconn, i,
1226 &lck->data->share_modes[i]);
1230 /* Now we check the share modes, after any oplock breaks. */
1231 for(i = 0; i < lck->data->num_share_modes; i++) {
1233 if (!is_valid_share_mode_entry(&lck->data->share_modes[i])) {
1237 /* someone else has a share lock on it, check to see if we can
1239 if (share_conflict(&lck->data->share_modes[i],
1240 access_mask, share_access)) {
1242 if (share_mode_stale_pid(lck->data, i)) {
1246 return NT_STATUS_SHARING_VIOLATION;
1250 return NT_STATUS_OK;
1254 * Send a break message to the oplock holder and delay the open for
1258 NTSTATUS send_break_message(struct messaging_context *msg_ctx,
1259 const struct share_mode_entry *exclusive,
1263 char msg[MSG_SMB_SHARE_MODE_ENTRY_SIZE];
1264 struct server_id_buf tmp;
1266 DEBUG(10, ("Sending break request to PID %s\n",
1267 server_id_str_buf(exclusive->pid, &tmp)));
1269 /* Create the message. */
1270 share_mode_entry_to_message(msg, exclusive);
1272 /* Overload entry->op_type */
1274 * This is a cut from uint32_t to uint16_t, but so far only the lower 3
1275 * bits (LEASE_WRITE/HANDLE/READ are used anyway.
1277 SSVAL(msg,OP_BREAK_MSG_OP_TYPE_OFFSET, break_to);
1279 status = messaging_send_buf(msg_ctx, exclusive->pid,
1280 MSG_SMB_BREAK_REQUEST,
1281 (uint8_t *)msg, sizeof(msg));
1282 if (!NT_STATUS_IS_OK(status)) {
1283 DEBUG(3, ("Could not send oplock break message: %s\n",
1284 nt_errstr(status)));
1291 * Do internal consistency checks on the share mode for a file.
1294 static bool validate_oplock_types(struct share_mode_lock *lck)
1296 struct share_mode_data *d = lck->data;
1298 bool ex_or_batch = false;
1299 bool level2 = false;
1300 bool no_oplock = false;
1301 uint32_t num_non_stat_opens = 0;
1304 for (i=0; i<d->num_share_modes; i++) {
1305 struct share_mode_entry *e = &d->share_modes[i];
1307 if (!is_valid_share_mode_entry(e)) {
1311 if (e->op_mid == 0) {
1312 /* INTERNAL_OPEN_ONLY */
1316 if (e->op_type == NO_OPLOCK && is_stat_open(e->access_mask)) {
1317 /* We ignore stat opens in the table - they
1318 always have NO_OPLOCK and never get or
1319 cause breaks. JRA. */
1323 num_non_stat_opens += 1;
1325 if (BATCH_OPLOCK_TYPE(e->op_type)) {
1326 /* batch - can only be one. */
1327 if (share_mode_stale_pid(d, i)) {
1328 DEBUG(10, ("Found stale batch oplock\n"));
1331 if (ex_or_batch || batch || level2 || no_oplock) {
1332 DEBUG(0, ("Bad batch oplock entry %u.",
1339 if (EXCLUSIVE_OPLOCK_TYPE(e->op_type)) {
1340 if (share_mode_stale_pid(d, i)) {
1341 DEBUG(10, ("Found stale duplicate oplock\n"));
1344 /* Exclusive or batch - can only be one. */
1345 if (ex_or_batch || level2 || no_oplock) {
1346 DEBUG(0, ("Bad exclusive or batch oplock "
1347 "entry %u.", (unsigned)i));
1353 if (LEVEL_II_OPLOCK_TYPE(e->op_type)) {
1354 if (batch || ex_or_batch) {
1355 if (share_mode_stale_pid(d, i)) {
1356 DEBUG(10, ("Found stale LevelII "
1360 DEBUG(0, ("Bad levelII oplock entry %u.",
1367 if (e->op_type == NO_OPLOCK) {
1368 if (batch || ex_or_batch) {
1369 if (share_mode_stale_pid(d, i)) {
1370 DEBUG(10, ("Found stale NO_OPLOCK "
1374 DEBUG(0, ("Bad no oplock entry %u.",
1382 remove_stale_share_mode_entries(d);
1384 if ((batch || ex_or_batch) && (num_non_stat_opens != 1)) {
1385 DEBUG(1, ("got batch (%d) or ex (%d) non-exclusively (%d)\n",
1386 (int)batch, (int)ex_or_batch,
1387 (int)d->num_share_modes));
1394 static bool delay_for_oplock(files_struct *fsp,
1396 const struct smb2_lease *lease,
1397 struct share_mode_lock *lck,
1398 bool have_sharing_violation,
1399 uint32_t create_disposition,
1400 bool first_open_attempt)
1402 struct share_mode_data *d = lck->data;
1405 bool will_overwrite;
1407 if ((oplock_request & INTERNAL_OPEN_ONLY) ||
1408 is_stat_open(fsp->access_mask)) {
1412 switch (create_disposition) {
1413 case FILE_SUPERSEDE:
1414 case FILE_OVERWRITE:
1415 case FILE_OVERWRITE_IF:
1416 will_overwrite = true;
1419 will_overwrite = false;
1423 for (i=0; i<d->num_share_modes; i++) {
1424 struct share_mode_entry *e = &d->share_modes[i];
1425 struct share_mode_lease *l = NULL;
1426 uint32_t e_lease_type = get_lease_type(d, e);
1428 uint32_t delay_mask = 0;
1430 if (e->op_type == LEASE_OPLOCK) {
1431 l = &d->leases[e->lease_idx];
1434 if (have_sharing_violation) {
1435 delay_mask = SMB2_LEASE_HANDLE;
1437 delay_mask = SMB2_LEASE_WRITE;
1440 break_to = e_lease_type & ~delay_mask;
1442 if (will_overwrite) {
1444 * we'll decide about SMB2_LEASE_READ later.
1446 * Maybe the break will be defered
1448 break_to &= ~SMB2_LEASE_HANDLE;
1451 DEBUG(10, ("entry %u: e_lease_type %u, will_overwrite: %u\n",
1452 (unsigned)i, (unsigned)e_lease_type,
1453 (unsigned)will_overwrite));
1455 if (lease != NULL && l != NULL) {
1458 ign = smb2_lease_equal(fsp_client_guid(fsp),
1467 if ((e_lease_type & ~break_to) == 0) {
1468 if (l != NULL && l->breaking) {
1474 if (share_mode_stale_pid(d, i)) {
1478 if (will_overwrite) {
1480 * If we break anyway break to NONE directly.
1481 * Otherwise vfs_set_filelen() will trigger the
1484 break_to &= ~(SMB2_LEASE_READ|SMB2_LEASE_WRITE);
1487 if (e->op_type != LEASE_OPLOCK) {
1489 * Oplocks only support breaking to R or NONE.
1491 break_to &= ~(SMB2_LEASE_HANDLE|SMB2_LEASE_WRITE);
1494 DEBUG(10, ("breaking from %d to %d\n",
1495 (int)e_lease_type, (int)break_to));
1496 send_break_message(fsp->conn->sconn->msg_ctx, e,
1498 if (e_lease_type & delay_mask) {
1501 if (l != NULL && l->breaking && !first_open_attempt) {
1510 static bool file_has_brlocks(files_struct *fsp)
1512 struct byte_range_lock *br_lck;
1514 br_lck = brl_get_locks_readonly(fsp);
1518 return (brl_num_locks(br_lck) > 0);
1521 int find_share_mode_lease(struct share_mode_data *d,
1522 const struct GUID *client_guid,
1523 const struct smb2_lease_key *key)
1527 for (i=0; i<d->num_leases; i++) {
1528 struct share_mode_lease *l = &d->leases[i];
1530 if (smb2_lease_equal(client_guid,
1541 struct fsp_lease *find_fsp_lease(struct files_struct *new_fsp,
1542 const struct smb2_lease_key *key,
1543 const struct share_mode_lease *l)
1545 struct files_struct *fsp;
1548 * TODO: Measure how expensive this loop is with thousands of open
1552 for (fsp = file_find_di_first(new_fsp->conn->sconn, new_fsp->file_id);
1554 fsp = file_find_di_next(fsp)) {
1556 if (fsp == new_fsp) {
1559 if (fsp->oplock_type != LEASE_OPLOCK) {
1562 if (smb2_lease_key_equal(&fsp->lease->lease.lease_key, key)) {
1563 fsp->lease->ref_count += 1;
1568 /* Not found - must be leased in another smbd. */
1569 new_fsp->lease = talloc_zero(new_fsp->conn->sconn, struct fsp_lease);
1570 if (new_fsp->lease == NULL) {
1573 new_fsp->lease->ref_count = 1;
1574 new_fsp->lease->sconn = new_fsp->conn->sconn;
1575 new_fsp->lease->lease.lease_key = *key;
1576 new_fsp->lease->lease.lease_state = l->current_state;
1578 * We internally treat all leases as V2 and update
1579 * the epoch, but when sending breaks it matters if
1580 * the requesting lease was v1 or v2.
1582 new_fsp->lease->lease.lease_version = l->lease_version;
1583 new_fsp->lease->lease.lease_epoch = l->epoch;
1584 return new_fsp->lease;
1587 static NTSTATUS grant_fsp_lease(struct files_struct *fsp,
1588 struct share_mode_lock *lck,
1589 const struct smb2_lease *lease,
1590 uint32_t *p_lease_idx,
1593 struct share_mode_data *d = lck->data;
1594 const struct GUID *client_guid = fsp_client_guid(fsp);
1595 struct share_mode_lease *tmp;
1599 idx = find_share_mode_lease(d, client_guid, &lease->lease_key);
1602 struct share_mode_lease *l = &d->leases[idx];
1604 uint32_t existing, requested;
1606 fsp->lease = find_fsp_lease(fsp, &lease->lease_key, l);
1607 if (fsp->lease == NULL) {
1608 DEBUG(1, ("Did not find existing lease for file %s\n",
1610 return NT_STATUS_NO_MEMORY;
1616 * Upgrade only if the requested lease is a strict upgrade.
1618 existing = l->current_state;
1619 requested = lease->lease_state;
1622 * Tricky: This test makes sure that "requested" is a
1623 * strict bitwise superset of "existing".
1625 do_upgrade = ((existing & requested) == existing);
1628 * Upgrade only if there's a change.
1630 do_upgrade &= (granted != existing);
1633 * Upgrade only if other leases don't prevent what was asked
1636 do_upgrade &= (granted == requested);
1639 * only upgrade if we are not in breaking state
1641 do_upgrade &= !l->breaking;
1643 DEBUG(10, ("existing=%"PRIu32", requested=%"PRIu32", "
1644 "granted=%"PRIu32", do_upgrade=%d\n",
1645 existing, requested, granted, (int)do_upgrade));
1648 l->current_state = granted;
1652 /* Ensure we're in sync with current lease state. */
1653 fsp_lease_update(lck, fsp_client_guid(fsp), fsp->lease);
1654 return NT_STATUS_OK;
1661 tmp = talloc_realloc(d, d->leases, struct share_mode_lease,
1667 return NT_STATUS_INSUFFICIENT_RESOURCES;
1671 fsp->lease = talloc_zero(fsp->conn->sconn, struct fsp_lease);
1672 if (fsp->lease == NULL) {
1673 return NT_STATUS_INSUFFICIENT_RESOURCES;
1675 fsp->lease->ref_count = 1;
1676 fsp->lease->sconn = fsp->conn->sconn;
1677 fsp->lease->lease.lease_version = lease->lease_version;
1678 fsp->lease->lease.lease_key = lease->lease_key;
1679 fsp->lease->lease.lease_state = granted;
1680 fsp->lease->lease.lease_epoch = lease->lease_epoch + 1;
1682 *p_lease_idx = d->num_leases;
1684 d->leases[d->num_leases] = (struct share_mode_lease) {
1685 .client_guid = *client_guid,
1686 .lease_key = fsp->lease->lease.lease_key,
1687 .current_state = fsp->lease->lease.lease_state,
1688 .lease_version = fsp->lease->lease.lease_version,
1689 .epoch = fsp->lease->lease.lease_epoch,
1692 status = leases_db_add(client_guid,
1695 fsp->conn->connectpath,
1696 fsp->fsp_name->base_name,
1697 fsp->fsp_name->stream_name);
1698 if (!NT_STATUS_IS_OK(status)) {
1699 DEBUG(10, ("%s: leases_db_add failed: %s\n", __func__,
1700 nt_errstr(status)));
1701 TALLOC_FREE(fsp->lease);
1702 return NT_STATUS_INSUFFICIENT_RESOURCES;
1708 return NT_STATUS_OK;
1711 static bool is_same_lease(const files_struct *fsp,
1712 const struct share_mode_data *d,
1713 const struct share_mode_entry *e,
1714 const struct smb2_lease *lease)
1716 if (e->op_type != LEASE_OPLOCK) {
1719 if (lease == NULL) {
1723 return smb2_lease_equal(fsp_client_guid(fsp),
1725 &d->leases[e->lease_idx].client_guid,
1726 &d->leases[e->lease_idx].lease_key);
1729 static NTSTATUS grant_fsp_oplock_type(struct smb_request *req,
1730 struct files_struct *fsp,
1731 struct share_mode_lock *lck,
1733 struct smb2_lease *lease)
1735 struct share_mode_data *d = lck->data;
1736 bool got_handle_lease = false;
1737 bool got_oplock = false;
1740 uint32_t lease_idx = UINT32_MAX;
1744 if (oplock_request & INTERNAL_OPEN_ONLY) {
1745 /* No oplocks on internal open. */
1746 oplock_request = NO_OPLOCK;
1747 DEBUG(10,("grant_fsp_oplock_type: oplock type 0x%x on file %s\n",
1748 fsp->oplock_type, fsp_str_dbg(fsp)));
1751 if (oplock_request == LEASE_OPLOCK) {
1752 if (lease == NULL) {
1754 * The SMB2 layer should have checked this
1756 return NT_STATUS_INTERNAL_ERROR;
1759 granted = lease->lease_state;
1761 if (lp_kernel_oplocks(SNUM(fsp->conn))) {
1762 DEBUG(10, ("No lease granted because kernel oplocks are enabled\n"));
1763 granted = SMB2_LEASE_NONE;
1765 if ((granted & (SMB2_LEASE_READ|SMB2_LEASE_WRITE)) == 0) {
1766 DEBUG(10, ("No read or write lease requested\n"));
1767 granted = SMB2_LEASE_NONE;
1769 if (granted == SMB2_LEASE_WRITE) {
1770 DEBUG(10, ("pure write lease requested\n"));
1771 granted = SMB2_LEASE_NONE;
1773 if (granted == (SMB2_LEASE_WRITE|SMB2_LEASE_HANDLE)) {
1774 DEBUG(10, ("write and handle lease requested\n"));
1775 granted = SMB2_LEASE_NONE;
1778 granted = map_oplock_to_lease_type(
1779 oplock_request & ~SAMBA_PRIVATE_OPLOCK_MASK);
1782 if (lp_locking(fsp->conn->params) && file_has_brlocks(fsp)) {
1783 DEBUG(10,("grant_fsp_oplock_type: file %s has byte range locks\n",
1785 granted &= ~SMB2_LEASE_READ;
1788 for (i=0; i<d->num_share_modes; i++) {
1789 struct share_mode_entry *e = &d->share_modes[i];
1790 uint32_t e_lease_type;
1792 e_lease_type = get_lease_type(d, e);
1794 if ((granted & SMB2_LEASE_WRITE) &&
1795 !is_same_lease(fsp, d, e, lease) &&
1796 !share_mode_stale_pid(d, i)) {
1798 * Can grant only one writer
1800 granted &= ~SMB2_LEASE_WRITE;
1803 if ((e_lease_type & SMB2_LEASE_HANDLE) && !got_handle_lease &&
1804 !share_mode_stale_pid(d, i)) {
1805 got_handle_lease = true;
1808 if ((e->op_type != LEASE_OPLOCK) && !got_oplock &&
1809 !share_mode_stale_pid(d, i)) {
1814 if ((granted & SMB2_LEASE_READ) && !(granted & SMB2_LEASE_WRITE)) {
1816 (global_client_caps & CAP_LEVEL_II_OPLOCKS) &&
1817 lp_level2_oplocks(SNUM(fsp->conn));
1819 if (!allow_level2) {
1820 granted = SMB2_LEASE_NONE;
1824 if (oplock_request == LEASE_OPLOCK) {
1826 granted &= ~SMB2_LEASE_HANDLE;
1829 fsp->oplock_type = LEASE_OPLOCK;
1831 status = grant_fsp_lease(fsp, lck, lease, &lease_idx,
1833 if (!NT_STATUS_IS_OK(status)) {
1837 *lease = fsp->lease->lease;
1838 DEBUG(10, ("lease_state=%d\n", lease->lease_state));
1840 if (got_handle_lease) {
1841 granted = SMB2_LEASE_NONE;
1845 case SMB2_LEASE_READ|SMB2_LEASE_WRITE|SMB2_LEASE_HANDLE:
1846 fsp->oplock_type = BATCH_OPLOCK|EXCLUSIVE_OPLOCK;
1848 case SMB2_LEASE_READ|SMB2_LEASE_WRITE:
1849 fsp->oplock_type = EXCLUSIVE_OPLOCK;
1851 case SMB2_LEASE_READ|SMB2_LEASE_HANDLE:
1852 case SMB2_LEASE_READ:
1853 fsp->oplock_type = LEVEL_II_OPLOCK;
1856 fsp->oplock_type = NO_OPLOCK;
1860 status = set_file_oplock(fsp);
1861 if (!NT_STATUS_IS_OK(status)) {
1863 * Could not get the kernel oplock
1865 fsp->oplock_type = NO_OPLOCK;
1869 ok = set_share_mode(lck, fsp, get_current_uid(fsp->conn),
1874 return NT_STATUS_NO_MEMORY;
1877 ok = update_num_read_oplocks(fsp, lck);
1879 del_share_mode(lck, fsp);
1880 return NT_STATUS_INTERNAL_ERROR;
1883 DEBUG(10,("grant_fsp_oplock_type: oplock type 0x%x on file %s\n",
1884 fsp->oplock_type, fsp_str_dbg(fsp)));
1886 return NT_STATUS_OK;
1889 static bool request_timed_out(struct timeval request_time,
1890 struct timeval timeout)
1892 struct timeval now, end_time;
1894 end_time = timeval_sum(&request_time, &timeout);
1895 return (timeval_compare(&end_time, &now) < 0);
1898 struct defer_open_state {
1899 struct smbXsrv_connection *xconn;
1903 static void defer_open_done(struct tevent_req *req);
1905 /****************************************************************************
1906 Handle the 1 second delay in returning a SHARING_VIOLATION error.
1907 ****************************************************************************/
1909 static void defer_open(struct share_mode_lock *lck,
1910 struct timeval request_time,
1911 struct timeval timeout,
1912 struct smb_request *req,
1913 struct deferred_open_record *state)
1915 struct deferred_open_record *open_rec;
1917 DEBUG(10,("defer_open_sharing_error: time [%u.%06u] adding deferred "
1918 "open entry for mid %llu\n",
1919 (unsigned int)request_time.tv_sec,
1920 (unsigned int)request_time.tv_usec,
1921 (unsigned long long)req->mid));
1923 open_rec = talloc(NULL, struct deferred_open_record);
1924 if (open_rec == NULL) {
1926 exit_server("talloc failed");
1932 struct defer_open_state *watch_state;
1933 struct tevent_req *watch_req;
1936 watch_state = talloc(open_rec, struct defer_open_state);
1937 if (watch_state == NULL) {
1938 exit_server("talloc failed");
1940 watch_state->xconn = req->xconn;
1941 watch_state->mid = req->mid;
1943 DEBUG(10, ("defering mid %llu\n",
1944 (unsigned long long)req->mid));
1946 watch_req = dbwrap_record_watch_send(
1947 watch_state, req->sconn->ev_ctx, lck->data->record,
1948 req->sconn->msg_ctx);
1949 if (watch_req == NULL) {
1950 exit_server("Could not watch share mode record");
1952 tevent_req_set_callback(watch_req, defer_open_done,
1955 ret = tevent_req_set_endtime(
1956 watch_req, req->sconn->ev_ctx,
1957 timeval_sum(&request_time, &timeout));
1961 if (!push_deferred_open_message_smb(req, request_time, timeout,
1962 state->id, open_rec)) {
1964 exit_server("push_deferred_open_message_smb failed");
1968 static void defer_open_done(struct tevent_req *req)
1970 struct defer_open_state *state = tevent_req_callback_data(
1971 req, struct defer_open_state);
1975 status = dbwrap_record_watch_recv(req, talloc_tos(), NULL);
1977 if (!NT_STATUS_IS_OK(status)) {
1978 DEBUG(5, ("dbwrap_record_watch_recv returned %s\n",
1979 nt_errstr(status)));
1981 * Even if it failed, retry anyway. TODO: We need a way to
1982 * tell a re-scheduled open about that error.
1986 DEBUG(10, ("scheduling mid %llu\n", (unsigned long long)state->mid));
1988 ret = schedule_deferred_open_message_smb(state->xconn, state->mid);
1994 /****************************************************************************
1995 On overwrite open ensure that the attributes match.
1996 ****************************************************************************/
1998 static bool open_match_attributes(connection_struct *conn,
1999 uint32_t old_dos_attr,
2000 uint32_t new_dos_attr,
2001 mode_t existing_unx_mode,
2002 mode_t new_unx_mode,
2003 mode_t *returned_unx_mode)
2005 uint32_t noarch_old_dos_attr, noarch_new_dos_attr;
2007 noarch_old_dos_attr = (old_dos_attr & ~FILE_ATTRIBUTE_ARCHIVE);
2008 noarch_new_dos_attr = (new_dos_attr & ~FILE_ATTRIBUTE_ARCHIVE);
2010 if((noarch_old_dos_attr == 0 && noarch_new_dos_attr != 0) ||
2011 (noarch_old_dos_attr != 0 && ((noarch_old_dos_attr & noarch_new_dos_attr) == noarch_old_dos_attr))) {
2012 *returned_unx_mode = new_unx_mode;
2014 *returned_unx_mode = (mode_t)0;
2017 DEBUG(10,("open_match_attributes: old_dos_attr = 0x%x, "
2018 "existing_unx_mode = 0%o, new_dos_attr = 0x%x "
2019 "returned_unx_mode = 0%o\n",
2020 (unsigned int)old_dos_attr,
2021 (unsigned int)existing_unx_mode,
2022 (unsigned int)new_dos_attr,
2023 (unsigned int)*returned_unx_mode ));
2025 /* If we're mapping SYSTEM and HIDDEN ensure they match. */
2026 if (lp_map_system(SNUM(conn)) || lp_store_dos_attributes(SNUM(conn))) {
2027 if ((old_dos_attr & FILE_ATTRIBUTE_SYSTEM) &&
2028 !(new_dos_attr & FILE_ATTRIBUTE_SYSTEM)) {
2032 if (lp_map_hidden(SNUM(conn)) || lp_store_dos_attributes(SNUM(conn))) {
2033 if ((old_dos_attr & FILE_ATTRIBUTE_HIDDEN) &&
2034 !(new_dos_attr & FILE_ATTRIBUTE_HIDDEN)) {
2041 /****************************************************************************
2042 Special FCB or DOS processing in the case of a sharing violation.
2043 Try and find a duplicated file handle.
2044 ****************************************************************************/
2046 static NTSTATUS fcb_or_dos_open(struct smb_request *req,
2047 connection_struct *conn,
2048 files_struct *fsp_to_dup_into,
2049 const struct smb_filename *smb_fname,
2053 uint32_t access_mask,
2054 uint32_t share_access,
2055 uint32_t create_options)
2059 DEBUG(5,("fcb_or_dos_open: attempting old open semantics for "
2060 "file %s.\n", smb_fname_str_dbg(smb_fname)));
2062 for(fsp = file_find_di_first(conn->sconn, id); fsp;
2063 fsp = file_find_di_next(fsp)) {
2065 DEBUG(10,("fcb_or_dos_open: checking file %s, fd = %d, "
2066 "vuid = %llu, file_pid = %u, private_options = 0x%x "
2067 "access_mask = 0x%x\n", fsp_str_dbg(fsp),
2068 fsp->fh->fd, (unsigned long long)fsp->vuid,
2069 (unsigned int)fsp->file_pid,
2070 (unsigned int)fsp->fh->private_options,
2071 (unsigned int)fsp->access_mask ));
2073 if (fsp != fsp_to_dup_into &&
2074 fsp->fh->fd != -1 &&
2075 fsp->vuid == vuid &&
2076 fsp->file_pid == file_pid &&
2077 (fsp->fh->private_options & (NTCREATEX_OPTIONS_PRIVATE_DENY_DOS |
2078 NTCREATEX_OPTIONS_PRIVATE_DENY_FCB)) &&
2079 (fsp->access_mask & FILE_WRITE_DATA) &&
2080 strequal(fsp->fsp_name->base_name, smb_fname->base_name) &&
2081 strequal(fsp->fsp_name->stream_name,
2082 smb_fname->stream_name)) {
2083 DEBUG(10,("fcb_or_dos_open: file match\n"));
2089 return NT_STATUS_NOT_FOUND;
2092 /* quite an insane set of semantics ... */
2093 if (is_executable(smb_fname->base_name) &&
2094 (fsp->fh->private_options & NTCREATEX_OPTIONS_PRIVATE_DENY_DOS)) {
2095 DEBUG(10,("fcb_or_dos_open: file fail due to is_executable.\n"));
2096 return NT_STATUS_INVALID_PARAMETER;
2099 /* We need to duplicate this fsp. */
2100 return dup_file_fsp(req, fsp, access_mask, share_access,
2101 create_options, fsp_to_dup_into);
2104 static void schedule_defer_open(struct share_mode_lock *lck,
2106 struct timeval request_time,
2107 struct smb_request *req)
2109 struct deferred_open_record state;
2111 /* This is a relative time, added to the absolute
2112 request_time value to get the absolute timeout time.
2113 Note that if this is the second or greater time we enter
2114 this codepath for this particular request mid then
2115 request_time is left as the absolute time of the *first*
2116 time this request mid was processed. This is what allows
2117 the request to eventually time out. */
2119 struct timeval timeout;
2121 /* Normally the smbd we asked should respond within
2122 * OPLOCK_BREAK_TIMEOUT seconds regardless of whether
2123 * the client did, give twice the timeout as a safety
2124 * measure here in case the other smbd is stuck
2125 * somewhere else. */
2127 timeout = timeval_set(OPLOCK_BREAK_TIMEOUT*2, 0);
2129 /* Nothing actually uses state.delayed_for_oplocks
2130 but it's handy to differentiate in debug messages
2131 between a 30 second delay due to oplock break, and
2132 a 1 second delay for share mode conflicts. */
2134 state.delayed_for_oplocks = True;
2135 state.async_open = false;
2138 if (!request_timed_out(request_time, timeout)) {
2139 defer_open(lck, request_time, timeout, req, &state);
2143 /****************************************************************************
2144 Reschedule an open call that went asynchronous.
2145 ****************************************************************************/
2147 static void schedule_async_open(struct timeval request_time,
2148 struct smb_request *req)
2150 struct deferred_open_record state;
2151 struct timeval timeout;
2153 timeout = timeval_set(20, 0);
2156 state.delayed_for_oplocks = false;
2157 state.async_open = true;
2159 if (!request_timed_out(request_time, timeout)) {
2160 defer_open(NULL, request_time, timeout, req, &state);
2164 /****************************************************************************
2165 Work out what access_mask to use from what the client sent us.
2166 ****************************************************************************/
2168 static NTSTATUS smbd_calculate_maximum_allowed_access(
2169 connection_struct *conn,
2170 const struct smb_filename *smb_fname,
2172 uint32_t *p_access_mask)
2174 struct security_descriptor *sd;
2175 uint32_t access_granted;
2178 if (!use_privs && (get_current_uid(conn) == (uid_t)0)) {
2179 *p_access_mask |= FILE_GENERIC_ALL;
2180 return NT_STATUS_OK;
2183 status = SMB_VFS_GET_NT_ACL(conn, smb_fname,
2189 if (NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
2191 * File did not exist
2193 *p_access_mask = FILE_GENERIC_ALL;
2194 return NT_STATUS_OK;
2196 if (!NT_STATUS_IS_OK(status)) {
2197 DEBUG(10,("Could not get acl on file %s: %s\n",
2198 smb_fname_str_dbg(smb_fname),
2199 nt_errstr(status)));
2200 return NT_STATUS_ACCESS_DENIED;
2204 * If we can access the path to this file, by
2205 * default we have FILE_READ_ATTRIBUTES from the
2206 * containing directory. See the section:
2207 * "Algorithm to Check Access to an Existing File"
2210 * se_file_access_check()
2211 * also takes care of owner WRITE_DAC and READ_CONTROL.
2213 status = se_file_access_check(sd,
2214 get_current_nttok(conn),
2216 (*p_access_mask & ~FILE_READ_ATTRIBUTES),
2221 if (!NT_STATUS_IS_OK(status)) {
2222 DEBUG(10, ("Access denied on file %s: "
2223 "when calculating maximum access\n",
2224 smb_fname_str_dbg(smb_fname)));
2225 return NT_STATUS_ACCESS_DENIED;
2227 *p_access_mask = (access_granted | FILE_READ_ATTRIBUTES);
2229 if (!(access_granted & DELETE_ACCESS)) {
2230 if (can_delete_file_in_directory(conn, smb_fname)) {
2231 *p_access_mask |= DELETE_ACCESS;
2235 return NT_STATUS_OK;
2238 NTSTATUS smbd_calculate_access_mask(connection_struct *conn,
2239 const struct smb_filename *smb_fname,
2241 uint32_t access_mask,
2242 uint32_t *access_mask_out)
2245 uint32_t orig_access_mask = access_mask;
2246 uint32_t rejected_share_access;
2249 * Convert GENERIC bits to specific bits.
2252 se_map_generic(&access_mask, &file_generic_mapping);
2254 /* Calculate MAXIMUM_ALLOWED_ACCESS if requested. */
2255 if (access_mask & MAXIMUM_ALLOWED_ACCESS) {
2257 status = smbd_calculate_maximum_allowed_access(
2258 conn, smb_fname, use_privs, &access_mask);
2260 if (!NT_STATUS_IS_OK(status)) {
2264 access_mask &= conn->share_access;
2267 rejected_share_access = access_mask & ~(conn->share_access);
2269 if (rejected_share_access) {
2270 DEBUG(10, ("smbd_calculate_access_mask: Access denied on "
2271 "file %s: rejected by share access mask[0x%08X] "
2272 "orig[0x%08X] mapped[0x%08X] reject[0x%08X]\n",
2273 smb_fname_str_dbg(smb_fname),
2275 orig_access_mask, access_mask,
2276 rejected_share_access));
2277 return NT_STATUS_ACCESS_DENIED;
2280 *access_mask_out = access_mask;
2281 return NT_STATUS_OK;
2284 /****************************************************************************
2285 Remove the deferred open entry under lock.
2286 ****************************************************************************/
2288 /****************************************************************************
2289 Return true if this is a state pointer to an asynchronous create.
2290 ****************************************************************************/
2292 bool is_deferred_open_async(const struct deferred_open_record *rec)
2294 return rec->async_open;
2297 static bool clear_ads(uint32_t create_disposition)
2301 switch (create_disposition) {
2302 case FILE_SUPERSEDE:
2303 case FILE_OVERWRITE_IF:
2304 case FILE_OVERWRITE:
2313 static int disposition_to_open_flags(uint32_t create_disposition)
2318 * Currently we're using FILE_SUPERSEDE as the same as
2319 * FILE_OVERWRITE_IF but they really are
2320 * different. FILE_SUPERSEDE deletes an existing file
2321 * (requiring delete access) then recreates it.
2324 switch (create_disposition) {
2325 case FILE_SUPERSEDE:
2326 case FILE_OVERWRITE_IF:
2328 * If file exists replace/overwrite. If file doesn't
2331 ret = O_CREAT|O_TRUNC;
2336 * If file exists open. If file doesn't exist error.
2341 case FILE_OVERWRITE:
2343 * If file exists overwrite. If file doesn't exist
2351 * If file exists error. If file doesn't exist create.
2353 ret = O_CREAT|O_EXCL;
2358 * If file exists open. If file doesn't exist create.
2366 static int calculate_open_access_flags(uint32_t access_mask,
2367 uint32_t private_flags)
2369 bool need_write, need_read;
2372 * Note that we ignore the append flag as append does not
2373 * mean the same thing under DOS and Unix.
2376 need_write = (access_mask & (FILE_WRITE_DATA | FILE_APPEND_DATA));
2381 /* DENY_DOS opens are always underlying read-write on the
2382 file handle, no matter what the requested access mask
2386 ((private_flags & NTCREATEX_OPTIONS_PRIVATE_DENY_DOS) ||
2387 access_mask & (FILE_READ_ATTRIBUTES|FILE_READ_DATA|
2388 FILE_READ_EA|FILE_EXECUTE));
2396 /****************************************************************************
2397 Open a file with a share mode. Passed in an already created files_struct *.
2398 ****************************************************************************/
2400 static NTSTATUS open_file_ntcreate(connection_struct *conn,
2401 struct smb_request *req,
2402 uint32_t access_mask, /* access bits (FILE_READ_DATA etc.) */
2403 uint32_t share_access, /* share constants (FILE_SHARE_READ etc) */
2404 uint32_t create_disposition, /* FILE_OPEN_IF etc. */
2405 uint32_t create_options, /* options such as delete on close. */
2406 uint32_t new_dos_attributes, /* attributes used for new file. */
2407 int oplock_request, /* internal Samba oplock codes. */
2408 struct smb2_lease *lease,
2409 /* Information (FILE_EXISTS etc.) */
2410 uint32_t private_flags, /* Samba specific flags. */
2414 struct smb_filename *smb_fname = fsp->fsp_name;
2417 bool file_existed = VALID_STAT(smb_fname->st);
2418 bool def_acl = False;
2419 bool posix_open = False;
2420 bool new_file_created = False;
2421 bool first_open_attempt = true;
2422 NTSTATUS fsp_open = NT_STATUS_ACCESS_DENIED;
2423 mode_t new_unx_mode = (mode_t)0;
2424 mode_t unx_mode = (mode_t)0;
2426 uint32_t existing_dos_attributes = 0;
2427 struct timeval request_time = timeval_zero();
2428 struct share_mode_lock *lck = NULL;
2429 uint32_t open_access_mask = access_mask;
2432 SMB_STRUCT_STAT saved_stat = smb_fname->st;
2433 struct timespec old_write_time;
2436 if (conn->printer) {
2438 * Printers are handled completely differently.
2439 * Most of the passed parameters are ignored.
2443 *pinfo = FILE_WAS_CREATED;
2446 DEBUG(10, ("open_file_ntcreate: printer open fname=%s\n",
2447 smb_fname_str_dbg(smb_fname)));
2450 DEBUG(0,("open_file_ntcreate: printer open without "
2451 "an SMB request!\n"));
2452 return NT_STATUS_INTERNAL_ERROR;
2455 return print_spool_open(fsp, smb_fname->base_name,
2459 if (!parent_dirname(talloc_tos(), smb_fname->base_name, &parent_dir,
2461 return NT_STATUS_NO_MEMORY;
2464 if (new_dos_attributes & FILE_FLAG_POSIX_SEMANTICS) {
2466 unx_mode = (mode_t)(new_dos_attributes & ~FILE_FLAG_POSIX_SEMANTICS);
2467 new_dos_attributes = 0;
2469 /* Windows allows a new file to be created and
2470 silently removes a FILE_ATTRIBUTE_DIRECTORY
2471 sent by the client. Do the same. */
2473 new_dos_attributes &= ~FILE_ATTRIBUTE_DIRECTORY;
2475 /* We add FILE_ATTRIBUTE_ARCHIVE to this as this mode is only used if the file is
2477 unx_mode = unix_mode(conn, new_dos_attributes | FILE_ATTRIBUTE_ARCHIVE,
2478 smb_fname, parent_dir);
2481 DEBUG(10, ("open_file_ntcreate: fname=%s, dos_attrs=0x%x "
2482 "access_mask=0x%x share_access=0x%x "
2483 "create_disposition = 0x%x create_options=0x%x "
2484 "unix mode=0%o oplock_request=%d private_flags = 0x%x\n",
2485 smb_fname_str_dbg(smb_fname), new_dos_attributes,
2486 access_mask, share_access, create_disposition,
2487 create_options, (unsigned int)unx_mode, oplock_request,
2488 (unsigned int)private_flags));
2491 /* Ensure req == NULL means INTERNAL_OPEN_ONLY */
2492 SMB_ASSERT(((oplock_request & INTERNAL_OPEN_ONLY) != 0));
2494 /* And req != NULL means no INTERNAL_OPEN_ONLY */
2495 SMB_ASSERT(((oplock_request & INTERNAL_OPEN_ONLY) == 0));
2499 * Only non-internal opens can be deferred at all
2503 struct deferred_open_record *open_rec;
2504 if (get_deferred_open_message_state(req,
2507 /* Remember the absolute time of the original
2508 request with this mid. We'll use it later to
2509 see if this has timed out. */
2511 /* If it was an async create retry, the file
2514 if (is_deferred_open_async(open_rec)) {
2515 SET_STAT_INVALID(smb_fname->st);
2516 file_existed = false;
2519 /* Ensure we don't reprocess this message. */
2520 remove_deferred_open_message_smb(req->xconn, req->mid);
2522 first_open_attempt = false;
2527 new_dos_attributes &= SAMBA_ATTRIBUTES_MASK;
2529 existing_dos_attributes = dos_mode(conn, smb_fname);
2533 /* ignore any oplock requests if oplocks are disabled */
2534 if (!lp_oplocks(SNUM(conn)) ||
2535 IS_VETO_OPLOCK_PATH(conn, smb_fname->base_name)) {
2536 /* Mask off everything except the private Samba bits. */
2537 oplock_request &= SAMBA_PRIVATE_OPLOCK_MASK;
2540 /* this is for OS/2 long file names - say we don't support them */
2541 if (req != NULL && !req->posix_pathnames &&
2542 strstr(smb_fname->base_name,".+,;=[].")) {
2543 /* OS/2 Workplace shell fix may be main code stream in a later
2545 DEBUG(5,("open_file_ntcreate: OS/2 long filenames are not "
2547 if (use_nt_status()) {
2548 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
2550 return NT_STATUS_DOS(ERRDOS, ERRcannotopen);
2553 switch( create_disposition ) {
2555 /* If file exists open. If file doesn't exist error. */
2556 if (!file_existed) {
2557 DEBUG(5,("open_file_ntcreate: FILE_OPEN "
2558 "requested for file %s and file "
2560 smb_fname_str_dbg(smb_fname)));
2562 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
2566 case FILE_OVERWRITE:
2567 /* If file exists overwrite. If file doesn't exist
2569 if (!file_existed) {
2570 DEBUG(5,("open_file_ntcreate: FILE_OVERWRITE "
2571 "requested for file %s and file "
2573 smb_fname_str_dbg(smb_fname) ));
2575 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
2580 /* If file exists error. If file doesn't exist
2583 DEBUG(5,("open_file_ntcreate: FILE_CREATE "
2584 "requested for file %s and file "
2585 "already exists.\n",
2586 smb_fname_str_dbg(smb_fname)));
2587 if (S_ISDIR(smb_fname->st.st_ex_mode)) {
2592 return map_nt_error_from_unix(errno);
2596 case FILE_SUPERSEDE:
2597 case FILE_OVERWRITE_IF:
2601 return NT_STATUS_INVALID_PARAMETER;
2604 flags2 = disposition_to_open_flags(create_disposition);
2606 /* We only care about matching attributes on file exists and
2609 if (!posix_open && file_existed &&
2610 ((create_disposition == FILE_OVERWRITE) ||
2611 (create_disposition == FILE_OVERWRITE_IF))) {
2612 if (!open_match_attributes(conn, existing_dos_attributes,
2614 smb_fname->st.st_ex_mode,
2615 unx_mode, &new_unx_mode)) {
2616 DEBUG(5,("open_file_ntcreate: attributes missmatch "
2617 "for file %s (%x %x) (0%o, 0%o)\n",
2618 smb_fname_str_dbg(smb_fname),
2619 existing_dos_attributes,
2621 (unsigned int)smb_fname->st.st_ex_mode,
2622 (unsigned int)unx_mode ));
2624 return NT_STATUS_ACCESS_DENIED;
2628 status = smbd_calculate_access_mask(conn, smb_fname,
2632 if (!NT_STATUS_IS_OK(status)) {
2633 DEBUG(10, ("open_file_ntcreate: smbd_calculate_access_mask "
2634 "on file %s returned %s\n",
2635 smb_fname_str_dbg(smb_fname), nt_errstr(status)));
2639 open_access_mask = access_mask;
2641 if (flags2 & O_TRUNC) {
2642 open_access_mask |= FILE_WRITE_DATA; /* This will cause oplock breaks. */
2645 DEBUG(10, ("open_file_ntcreate: fname=%s, after mapping "
2646 "access_mask=0x%x\n", smb_fname_str_dbg(smb_fname),
2650 * Note that we ignore the append flag as append does not
2651 * mean the same thing under DOS and Unix.
2654 flags = calculate_open_access_flags(access_mask, private_flags);
2657 * Currently we only look at FILE_WRITE_THROUGH for create options.
2661 if ((create_options & FILE_WRITE_THROUGH) && lp_strict_sync(SNUM(conn))) {
2666 if (posix_open && (access_mask & FILE_APPEND_DATA)) {
2670 if (!posix_open && !CAN_WRITE(conn)) {
2672 * We should really return a permission denied error if either
2673 * O_CREAT or O_TRUNC are set, but for compatibility with
2674 * older versions of Samba we just AND them out.
2676 flags2 &= ~(O_CREAT|O_TRUNC);
2679 if (first_open_attempt && lp_kernel_oplocks(SNUM(conn))) {
2681 * With kernel oplocks the open breaking an oplock
2682 * blocks until the oplock holder has given up the
2683 * oplock or closed the file. We prevent this by first
2684 * trying to open the file with O_NONBLOCK (see "man
2685 * fcntl" on Linux). For the second try, triggered by
2686 * an oplock break response, we do not need this
2689 * This is true under the assumption that only Samba
2690 * requests kernel oplocks. Once someone else like
2691 * NFSv4 starts to use that API, we will have to
2692 * modify this by communicating with the NFSv4 server.
2694 flags2 |= O_NONBLOCK;
2698 * Ensure we can't write on a read-only share or file.
2701 if (flags != O_RDONLY && file_existed &&
2702 (!CAN_WRITE(conn) || IS_DOS_READONLY(existing_dos_attributes))) {
2703 DEBUG(5,("open_file_ntcreate: write access requested for "
2704 "file %s on read only %s\n",
2705 smb_fname_str_dbg(smb_fname),
2706 !CAN_WRITE(conn) ? "share" : "file" ));
2708 return NT_STATUS_ACCESS_DENIED;
2711 fsp->file_id = vfs_file_id_from_sbuf(conn, &smb_fname->st);
2712 fsp->share_access = share_access;
2713 fsp->fh->private_options = private_flags;
2714 fsp->access_mask = open_access_mask; /* We change this to the
2715 * requested access_mask after
2716 * the open is done. */
2718 fsp->posix_flags |= FSP_POSIX_FLAGS_ALL;
2721 if (timeval_is_zero(&request_time)) {
2722 request_time = fsp->open_time;
2726 * Ensure we pay attention to default ACLs on directories if required.
2729 if ((flags2 & O_CREAT) && lp_inherit_acls(SNUM(conn)) &&
2730 (def_acl = directory_has_default_acl(conn, parent_dir))) {
2731 unx_mode = (0777 & lp_create_mask(SNUM(conn)));
2734 DEBUG(4,("calling open_file with flags=0x%X flags2=0x%X mode=0%o, "
2735 "access_mask = 0x%x, open_access_mask = 0x%x\n",
2736 (unsigned int)flags, (unsigned int)flags2,
2737 (unsigned int)unx_mode, (unsigned int)access_mask,
2738 (unsigned int)open_access_mask));
2740 fsp_open = open_file(fsp, conn, req, parent_dir,
2741 flags|flags2, unx_mode, access_mask,
2742 open_access_mask, &new_file_created);
2744 if (NT_STATUS_EQUAL(fsp_open, NT_STATUS_NETWORK_BUSY)) {
2745 struct deferred_open_record state;
2748 * EWOULDBLOCK/EAGAIN maps to NETWORK_BUSY.
2750 if (file_existed && S_ISFIFO(fsp->fsp_name->st.st_ex_mode)) {
2751 DEBUG(10, ("FIFO busy\n"));
2752 return NT_STATUS_NETWORK_BUSY;
2755 DEBUG(10, ("Internal open busy\n"));
2756 return NT_STATUS_NETWORK_BUSY;
2760 * From here on we assume this is an oplock break triggered
2763 lck = get_existing_share_mode_lock(talloc_tos(), fsp->file_id);
2765 state.delayed_for_oplocks = false;
2766 state.async_open = false;
2767 state.id = fsp->file_id;
2768 defer_open(NULL, request_time, timeval_set(0, 0),
2770 DEBUG(10, ("No share mode lock found after "
2771 "EWOULDBLOCK, retrying sync\n"));
2772 return NT_STATUS_SHARING_VIOLATION;
2775 if (!validate_oplock_types(lck)) {
2776 smb_panic("validate_oplock_types failed");
2779 if (delay_for_oplock(fsp, 0, lease, lck, false,
2780 create_disposition, first_open_attempt)) {
2781 schedule_defer_open(lck, fsp->file_id, request_time,
2784 DEBUG(10, ("Sent oplock break request to kernel "
2785 "oplock holder\n"));
2786 return NT_STATUS_SHARING_VIOLATION;
2790 * No oplock from Samba around. Immediately retry with
2793 state.delayed_for_oplocks = false;
2794 state.async_open = false;
2795 state.id = fsp->file_id;
2796 defer_open(lck, request_time, timeval_set(0, 0), req, &state);
2798 DEBUG(10, ("No Samba oplock around after EWOULDBLOCK. "
2799 "Retrying sync\n"));
2800 return NT_STATUS_SHARING_VIOLATION;
2803 if (!NT_STATUS_IS_OK(fsp_open)) {
2804 if (NT_STATUS_EQUAL(fsp_open, NT_STATUS_RETRY)) {
2805 schedule_async_open(request_time, req);
2810 if (new_file_created) {
2812 * As we atomically create using O_CREAT|O_EXCL,
2813 * then if new_file_created is true, then
2814 * file_existed *MUST* have been false (even
2815 * if the file was previously detected as being
2818 file_existed = false;
2821 if (file_existed && !check_same_dev_ino(&saved_stat, &smb_fname->st)) {
2823 * The file did exist, but some other (local or NFS)
2824 * process either renamed/unlinked and re-created the
2825 * file with different dev/ino after we walked the path,
2826 * but before we did the open. We could retry the
2827 * open but it's a rare enough case it's easier to
2828 * just fail the open to prevent creating any problems
2829 * in the open file db having the wrong dev/ino key.
2832 DEBUG(1,("open_file_ntcreate: file %s - dev/ino mismatch. "
2833 "Old (dev=0x%llu, ino =0x%llu). "
2834 "New (dev=0x%llu, ino=0x%llu). Failing open "
2835 " with NT_STATUS_ACCESS_DENIED.\n",
2836 smb_fname_str_dbg(smb_fname),
2837 (unsigned long long)saved_stat.st_ex_dev,
2838 (unsigned long long)saved_stat.st_ex_ino,
2839 (unsigned long long)smb_fname->st.st_ex_dev,
2840 (unsigned long long)smb_fname->st.st_ex_ino));
2841 return NT_STATUS_ACCESS_DENIED;
2844 old_write_time = smb_fname->st.st_ex_mtime;
2847 * Deal with the race condition where two smbd's detect the
2848 * file doesn't exist and do the create at the same time. One
2849 * of them will win and set a share mode, the other (ie. this
2850 * one) should check if the requested share mode for this
2851 * create is allowed.
2855 * Now the file exists and fsp is successfully opened,
2856 * fsp->dev and fsp->inode are valid and should replace the
2857 * dev=0,inode=0 from a non existent file. Spotted by
2858 * Nadav Danieli <nadavd@exanet.com>. JRA.
2863 lck = get_share_mode_lock(talloc_tos(), id,
2865 smb_fname, &old_write_time);
2868 DEBUG(0, ("open_file_ntcreate: Could not get share "
2869 "mode lock for %s\n",
2870 smb_fname_str_dbg(smb_fname)));
2872 return NT_STATUS_SHARING_VIOLATION;
2875 /* Get the types we need to examine. */
2876 if (!validate_oplock_types(lck)) {
2877 smb_panic("validate_oplock_types failed");
2880 if (has_delete_on_close(lck, fsp->name_hash)) {
2883 return NT_STATUS_DELETE_PENDING;
2886 status = open_mode_check(conn, lck,
2887 access_mask, share_access);
2889 if (NT_STATUS_EQUAL(status, NT_STATUS_SHARING_VIOLATION) ||
2890 (lck->data->num_share_modes > 0)) {
2892 * This comes from ancient times out of open_mode_check. I
2893 * have no clue whether this is still necessary. I can't think
2894 * of a case where this would actually matter further down in
2895 * this function. I leave it here for further investigation
2898 file_existed = true;
2901 if ((req != NULL) &&
2903 fsp, oplock_request, lease, lck,
2904 NT_STATUS_EQUAL(status, NT_STATUS_SHARING_VIOLATION),
2905 create_disposition, first_open_attempt)) {
2906 schedule_defer_open(lck, fsp->file_id, request_time, req);
2909 return NT_STATUS_SHARING_VIOLATION;
2912 if (!NT_STATUS_IS_OK(status)) {
2913 uint32_t can_access_mask;
2914 bool can_access = True;
2916 SMB_ASSERT(NT_STATUS_EQUAL(status, NT_STATUS_SHARING_VIOLATION));
2918 /* Check if this can be done with the deny_dos and fcb
2921 (NTCREATEX_OPTIONS_PRIVATE_DENY_DOS|
2922 NTCREATEX_OPTIONS_PRIVATE_DENY_FCB)) {
2924 DEBUG(0, ("DOS open without an SMB "
2928 return NT_STATUS_INTERNAL_ERROR;
2931 /* Use the client requested access mask here,
2932 * not the one we open with. */
2933 status = fcb_or_dos_open(req,
2944 if (NT_STATUS_IS_OK(status)) {
2947 *pinfo = FILE_WAS_OPENED;
2949 return NT_STATUS_OK;
2954 * This next line is a subtlety we need for
2955 * MS-Access. If a file open will fail due to share
2956 * permissions and also for security (access) reasons,
2957 * we need to return the access failed error, not the
2958 * share error. We can't open the file due to kernel
2959 * oplock deadlock (it's possible we failed above on
2960 * the open_mode_check()) so use a userspace check.
2963 if (flags & O_RDWR) {
2964 can_access_mask = FILE_READ_DATA|FILE_WRITE_DATA;
2965 } else if (flags & O_WRONLY) {
2966 can_access_mask = FILE_WRITE_DATA;
2968 can_access_mask = FILE_READ_DATA;
2971 if (((can_access_mask & FILE_WRITE_DATA) &&
2972 !CAN_WRITE(conn)) ||
2973 !NT_STATUS_IS_OK(smbd_check_access_rights(conn,
2976 can_access_mask))) {
2981 * If we're returning a share violation, ensure we
2982 * cope with the braindead 1 second delay (SMB1 only).
2985 if (!(oplock_request & INTERNAL_OPEN_ONLY) &&
2986 !conn->sconn->using_smb2 &&
2987 lp_defer_sharing_violations()) {
2988 struct timeval timeout;
2989 struct deferred_open_record state;
2992 /* this is a hack to speed up torture tests
2994 timeout_usecs = lp_parm_int(SNUM(conn),
2995 "smbd","sharedelay",
2996 SHARING_VIOLATION_USEC_WAIT);
2998 /* This is a relative time, added to the absolute
2999 request_time value to get the absolute timeout time.
3000 Note that if this is the second or greater time we enter
3001 this codepath for this particular request mid then
3002 request_time is left as the absolute time of the *first*
3003 time this request mid was processed. This is what allows
3004 the request to eventually time out. */
3006 timeout = timeval_set(0, timeout_usecs);
3008 /* Nothing actually uses state.delayed_for_oplocks
3009 but it's handy to differentiate in debug messages
3010 between a 30 second delay due to oplock break, and
3011 a 1 second delay for share mode conflicts. */
3013 state.delayed_for_oplocks = False;
3014 state.async_open = false;
3018 && !request_timed_out(request_time,
3020 defer_open(lck, request_time, timeout,
3029 * We have detected a sharing violation here
3030 * so return the correct error code
3032 status = NT_STATUS_SHARING_VIOLATION;
3034 status = NT_STATUS_ACCESS_DENIED;
3039 /* Should we atomically (to the client at least) truncate ? */
3040 if ((!new_file_created) &&
3041 (flags2 & O_TRUNC) &&
3042 (!S_ISFIFO(fsp->fsp_name->st.st_ex_mode))) {
3045 ret = vfs_set_filelen(fsp, 0);
3047 status = map_nt_error_from_unix(errno);
3055 * We have the share entry *locked*.....
3058 /* Delete streams if create_disposition requires it */
3059 if (!new_file_created && clear_ads(create_disposition) &&
3060 !is_ntfs_stream_smb_fname(smb_fname)) {
3061 status = delete_all_streams(conn, smb_fname->base_name);
3062 if (!NT_STATUS_IS_OK(status)) {
3069 /* note that we ignore failure for the following. It is
3070 basically a hack for NFS, and NFS will never set one of
3071 these only read them. Nobody but Samba can ever set a deny
3072 mode and we have already checked our more authoritative
3073 locking database for permission to set this deny mode. If
3074 the kernel refuses the operations then the kernel is wrong.
3075 note that GPFS supports it as well - jmcd */
3077 if (fsp->fh->fd != -1 && lp_kernel_share_modes(SNUM(conn))) {
3080 * Beware: streams implementing VFS modules may
3081 * implement streams in a way that fsp will have the
3082 * basefile open in the fsp fd, so lacking a distinct
3083 * fd for the stream kernel_flock will apply on the
3084 * basefile which is wrong. The actual check is
3085 * deffered to the VFS module implementing the
3086 * kernel_flock call.
3088 ret_flock = SMB_VFS_KERNEL_FLOCK(fsp, share_access, access_mask);
3089 if(ret_flock == -1 ){
3094 return NT_STATUS_SHARING_VIOLATION;
3099 * At this point onwards, we can guarantee that the share entry
3100 * is locked, whether we created the file or not, and that the
3101 * deny mode is compatible with all current opens.
3105 * According to Samba4, SEC_FILE_READ_ATTRIBUTE is always granted,
3106 * but we don't have to store this - just ignore it on access check.
3108 if (conn->sconn->using_smb2) {
3110 * SMB2 doesn't return it (according to Microsoft tests).
3111 * Test Case: TestSuite_ScenarioNo009GrantedAccessTestS0
3112 * File created with access = 0x7 (Read, Write, Delete)
3113 * Query Info on file returns 0x87 (Read, Write, Delete, Read Attributes)
3115 fsp->access_mask = access_mask;
3117 /* But SMB1 does. */
3118 fsp->access_mask = access_mask | FILE_READ_ATTRIBUTES;
3123 * stat opens on existing files don't get oplocks.
3124 * They can get leases.
3126 * Note that we check for stat open on the *open_access_mask*,
3127 * i.e. the access mask we actually used to do the open,
3128 * not the one the client asked for (which is in
3129 * fsp->access_mask). This is due to the fact that
3130 * FILE_OVERWRITE and FILE_OVERWRITE_IF add in O_TRUNC,
3131 * which adds FILE_WRITE_DATA to open_access_mask.
3133 if (is_stat_open(open_access_mask) && lease == NULL) {
3134 oplock_request = NO_OPLOCK;
3138 if (new_file_created) {
3139 info = FILE_WAS_CREATED;
3141 if (flags2 & O_TRUNC) {
3142 info = FILE_WAS_OVERWRITTEN;
3144 info = FILE_WAS_OPENED;
3153 * Setup the oplock info in both the shared memory and
3156 status = grant_fsp_oplock_type(req, fsp, lck, oplock_request, lease);
3157 if (!NT_STATUS_IS_OK(status)) {
3163 /* Handle strange delete on close create semantics. */
3164 if (create_options & FILE_DELETE_ON_CLOSE) {
3166 status = can_set_delete_on_close(fsp, new_dos_attributes);
3168 if (!NT_STATUS_IS_OK(status)) {
3169 /* Remember to delete the mode we just added. */
3170 del_share_mode(lck, fsp);
3175 /* Note that here we set the *inital* delete on close flag,
3176 not the regular one. The magic gets handled in close. */
3177 fsp->initial_delete_on_close = True;
3180 if (info != FILE_WAS_OPENED) {
3181 /* Overwritten files should be initially set as archive */
3182 if ((info == FILE_WAS_OVERWRITTEN && lp_map_archive(SNUM(conn))) ||
3183 lp_store_dos_attributes(SNUM(conn))) {
3185 if (file_set_dosmode(conn, smb_fname,
3186 new_dos_attributes | FILE_ATTRIBUTE_ARCHIVE,
3187 parent_dir, true) == 0) {
3188 unx_mode = smb_fname->st.st_ex_mode;
3194 /* Determine sparse flag. */
3196 /* POSIX opens are sparse by default. */
3197 fsp->is_sparse = true;
3199 fsp->is_sparse = (file_existed &&
3200 (existing_dos_attributes & FILE_ATTRIBUTE_SPARSE));
3204 * Take care of inherited ACLs on created files - if default ACL not
3208 if (!posix_open && new_file_created && !def_acl) {
3210 int saved_errno = errno; /* We might get ENOSYS in the next
3213 if (SMB_VFS_FCHMOD_ACL(fsp, unx_mode) == -1 &&
3215 errno = saved_errno; /* Ignore ENOSYS */
3218 } else if (new_unx_mode) {
3222 /* Attributes need changing. File already existed. */
3225 int saved_errno = errno; /* We might get ENOSYS in the
3227 ret = SMB_VFS_FCHMOD_ACL(fsp, new_unx_mode);
3229 if (ret == -1 && errno == ENOSYS) {
3230 errno = saved_errno; /* Ignore ENOSYS */
3232 DEBUG(5, ("open_file_ntcreate: reset "
3233 "attributes of file %s to 0%o\n",
3234 smb_fname_str_dbg(smb_fname),
3235 (unsigned int)new_unx_mode));
3236 ret = 0; /* Don't do the fchmod below. */
3241 (SMB_VFS_FCHMOD(fsp, new_unx_mode) == -1))
3242 DEBUG(5, ("open_file_ntcreate: failed to reset "
3243 "attributes of file %s to 0%o\n",
3244 smb_fname_str_dbg(smb_fname),
3245 (unsigned int)new_unx_mode));
3250 * Deal with other opens having a modified write time.
3252 struct timespec write_time = get_share_mode_write_time(lck);
3254 if (!null_timespec(write_time)) {
3255 update_stat_ex_mtime(&fsp->fsp_name->st, write_time);
3261 return NT_STATUS_OK;
3264 static NTSTATUS mkdir_internal(connection_struct *conn,
3265 struct smb_filename *smb_dname,
3266 uint32_t file_attributes)
3269 char *parent_dir = NULL;
3271 bool posix_open = false;
3272 bool need_re_stat = false;
3273 uint32_t access_mask = SEC_DIR_ADD_SUBDIR;
3275 if (!CAN_WRITE(conn) || (access_mask & ~(conn->share_access))) {
3276 DEBUG(5,("mkdir_internal: failing share access "
3277 "%s\n", lp_servicename(talloc_tos(), SNUM(conn))));
3278 return NT_STATUS_ACCESS_DENIED;
3281 if (!parent_dirname(talloc_tos(), smb_dname->base_name, &parent_dir,
3283 return NT_STATUS_NO_MEMORY;
3286 if (file_attributes & FILE_FLAG_POSIX_SEMANTICS) {
3288 mode = (mode_t)(file_attributes & ~FILE_FLAG_POSIX_SEMANTICS);
3290 mode = unix_mode(conn, FILE_ATTRIBUTE_DIRECTORY, smb_dname, parent_dir);
3293 status = check_parent_access(conn,
3296 if(!NT_STATUS_IS_OK(status)) {
3297 DEBUG(5,("mkdir_internal: check_parent_access "
3298 "on directory %s for path %s returned %s\n",
3300 smb_dname->base_name,
3301 nt_errstr(status) ));
3305 if (SMB_VFS_MKDIR(conn, smb_dname, mode) != 0) {
3306 return map_nt_error_from_unix(errno);
3309 /* Ensure we're checking for a symlink here.... */
3310 /* We don't want to get caught by a symlink racer. */
3312 if (SMB_VFS_LSTAT(conn, smb_dname) == -1) {
3313 DEBUG(2, ("Could not stat directory '%s' just created: %s\n",
3314 smb_fname_str_dbg(smb_dname), strerror(errno)));
3315 return map_nt_error_from_unix(errno);
3318 if (!S_ISDIR(smb_dname->st.st_ex_mode)) {
3319 DEBUG(0, ("Directory '%s' just created is not a directory !\n",
3320 smb_fname_str_dbg(smb_dname)));
3321 return NT_STATUS_NOT_A_DIRECTORY;
3324 if (lp_store_dos_attributes(SNUM(conn))) {
3326 file_set_dosmode(conn, smb_dname,
3327 file_attributes | FILE_ATTRIBUTE_DIRECTORY,
3332 if (lp_inherit_permissions(SNUM(conn))) {
3333 inherit_access_posix_acl(conn, parent_dir,
3334 smb_dname->base_name, mode);
3335 need_re_stat = true;
3340 * Check if high bits should have been set,
3341 * then (if bits are missing): add them.
3342 * Consider bits automagically set by UNIX, i.e. SGID bit from parent
3345 if ((mode & ~(S_IRWXU|S_IRWXG|S_IRWXO)) &&
3346 (mode & ~smb_dname->st.st_ex_mode)) {
3347 SMB_VFS_CHMOD(conn, smb_dname->base_name,
3348 (smb_dname->st.st_ex_mode |
3349 (mode & ~smb_dname->st.st_ex_mode)));
3350 need_re_stat = true;
3354 /* Change the owner if required. */
3355 if (lp_inherit_owner(SNUM(conn))) {
3356 change_dir_owner_to_parent(conn, parent_dir,
3357 smb_dname->base_name,
3359 need_re_stat = true;
3363 if (SMB_VFS_LSTAT(conn, smb_dname) == -1) {
3364 DEBUG(2, ("Could not stat directory '%s' just created: %s\n",
3365 smb_fname_str_dbg(smb_dname), strerror(errno)));
3366 return map_nt_error_from_unix(errno);
3370 notify_fname(conn, NOTIFY_ACTION_ADDED, FILE_NOTIFY_CHANGE_DIR_NAME,
3371 smb_dname->base_name);
3373 return NT_STATUS_OK;
3376 /****************************************************************************
3377 Open a directory from an NT SMB call.
3378 ****************************************************************************/
3380 static NTSTATUS open_directory(connection_struct *conn,
3381 struct smb_request *req,
3382 struct smb_filename *smb_dname,
3383 uint32_t access_mask,
3384 uint32_t share_access,
3385 uint32_t create_disposition,
3386 uint32_t create_options,
3387 uint32_t file_attributes,
3389 files_struct **result)
3391 files_struct *fsp = NULL;
3392 bool dir_existed = VALID_STAT(smb_dname->st) ? True : False;
3393 struct share_mode_lock *lck = NULL;
3395 struct timespec mtimespec;
3399 if (is_ntfs_stream_smb_fname(smb_dname)) {
3400 DEBUG(2, ("open_directory: %s is a stream name!\n",
3401 smb_fname_str_dbg(smb_dname)));
3402 return NT_STATUS_NOT_A_DIRECTORY;
3405 if (!(file_attributes & FILE_FLAG_POSIX_SEMANTICS)) {
3406 /* Ensure we have a directory attribute. */
3407 file_attributes |= FILE_ATTRIBUTE_DIRECTORY;
3410 DEBUG(5,("open_directory: opening directory %s, access_mask = 0x%x, "
3411 "share_access = 0x%x create_options = 0x%x, "
3412 "create_disposition = 0x%x, file_attributes = 0x%x\n",
3413 smb_fname_str_dbg(smb_dname),
3414 (unsigned int)access_mask,
3415 (unsigned int)share_access,
3416 (unsigned int)create_options,
3417 (unsigned int)create_disposition,
3418 (unsigned int)file_attributes));
3420 status = smbd_calculate_access_mask(conn, smb_dname, false,
3421 access_mask, &access_mask);
3422 if (!NT_STATUS_IS_OK(status)) {
3423 DEBUG(10, ("open_directory: smbd_calculate_access_mask "
3424 "on file %s returned %s\n",
3425 smb_fname_str_dbg(smb_dname),
3426 nt_errstr(status)));
3430 if ((access_mask & SEC_FLAG_SYSTEM_SECURITY) &&
3431 !security_token_has_privilege(get_current_nttok(conn),
3432 SEC_PRIV_SECURITY)) {
3433 DEBUG(10, ("open_directory: open on %s "
3434 "failed - SEC_FLAG_SYSTEM_SECURITY denied.\n",
3435 smb_fname_str_dbg(smb_dname)));
3436 return NT_STATUS_PRIVILEGE_NOT_HELD;
3439 switch( create_disposition ) {
3443 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3446 info = FILE_WAS_OPENED;
3451 /* If directory exists error. If directory doesn't
3455 status = NT_STATUS_OBJECT_NAME_COLLISION;
3456 DEBUG(2, ("open_directory: unable to create "
3457 "%s. Error was %s\n",
3458 smb_fname_str_dbg(smb_dname),
3459 nt_errstr(status)));
3463 status = mkdir_internal(conn, smb_dname,
3466 if (!NT_STATUS_IS_OK(status)) {
3467 DEBUG(2, ("open_directory: unable to create "
3468 "%s. Error was %s\n",
3469 smb_fname_str_dbg(smb_dname),
3470 nt_errstr(status)));
3474 info = FILE_WAS_CREATED;
3479 * If directory exists open. If directory doesn't
3484 status = NT_STATUS_OK;
3485 info = FILE_WAS_OPENED;
3487 status = mkdir_internal(conn, smb_dname,
3490 if (NT_STATUS_IS_OK(status)) {
3491 info = FILE_WAS_CREATED;
3493 /* Cope with create race. */
3494 if (!NT_STATUS_EQUAL(status,
3495 NT_STATUS_OBJECT_NAME_COLLISION)) {
3496 DEBUG(2, ("open_directory: unable to create "
3497 "%s. Error was %s\n",
3498 smb_fname_str_dbg(smb_dname),
3499 nt_errstr(status)));
3504 * If mkdir_internal() returned
3505 * NT_STATUS_OBJECT_NAME_COLLISION
3506 * we still must lstat the path.
3509 if (SMB_VFS_LSTAT(conn, smb_dname)
3511 DEBUG(2, ("Could not stat "
3512 "directory '%s' just "
3517 return map_nt_error_from_unix(
3521 info = FILE_WAS_OPENED;
3527 case FILE_SUPERSEDE:
3528 case FILE_OVERWRITE:
3529 case FILE_OVERWRITE_IF:
3531 DEBUG(5,("open_directory: invalid create_disposition "
3532 "0x%x for directory %s\n",
3533 (unsigned int)create_disposition,
3534 smb_fname_str_dbg(smb_dname)));
3535 return NT_STATUS_INVALID_PARAMETER;
3538 if(!S_ISDIR(smb_dname->st.st_ex_mode)) {
3539 DEBUG(5,("open_directory: %s is not a directory !\n",
3540 smb_fname_str_dbg(smb_dname)));
3541 return NT_STATUS_NOT_A_DIRECTORY;
3544 if (info == FILE_WAS_OPENED) {
3545 status = smbd_check_access_rights(conn,
3549 if (!NT_STATUS_IS_OK(status)) {
3550 DEBUG(10, ("open_directory: smbd_check_access_rights on "
3551 "file %s failed with %s\n",
3552 smb_fname_str_dbg(smb_dname),
3553 nt_errstr(status)));
3558 status = file_new(req, conn, &fsp);
3559 if(!NT_STATUS_IS_OK(status)) {
3564 * Setup the files_struct for it.
3567 fsp->file_id = vfs_file_id_from_sbuf(conn, &smb_dname->st);
3568 fsp->vuid = req ? req->vuid : UID_FIELD_INVALID;
3569 fsp->file_pid = req ? req->smbpid : 0;
3570 fsp->can_lock = False;
3571 fsp->can_read = False;
3572 fsp->can_write = False;
3574 fsp->share_access = share_access;
3575 fsp->fh->private_options = 0;
3577 * According to Samba4, SEC_FILE_READ_ATTRIBUTE is always granted,
3579 fsp->access_mask = access_mask | FILE_READ_ATTRIBUTES;
3580 fsp->print_file = NULL;
3581 fsp->modified = False;
3582 fsp->oplock_type = NO_OPLOCK;
3583 fsp->sent_oplock_break = NO_BREAK_SENT;
3584 fsp->is_directory = True;
3585 if (file_attributes & FILE_FLAG_POSIX_SEMANTICS) {
3586 fsp->posix_flags |= FSP_POSIX_FLAGS_ALL;
3588 status = fsp_set_smb_fname(fsp, smb_dname);
3589 if (!NT_STATUS_IS_OK(status)) {
3590 file_free(req, fsp);
3594 /* Don't store old timestamps for directory
3595 handles in the internal database. We don't
3596 update them in there if new objects
3597 are creaded in the directory. Currently
3598 we only update timestamps on file writes.
3601 ZERO_STRUCT(mtimespec);
3603 if (access_mask & (FILE_LIST_DIRECTORY|
3605 FILE_ADD_SUBDIRECTORY|
3608 FILE_DELETE_CHILD)) {
3610 status = fd_open(conn, fsp, O_RDONLY|O_DIRECTORY, 0);
3612 /* POSIX allows us to open a directory with O_RDONLY. */
3613 status = fd_open(conn, fsp, O_RDONLY, 0);
3615 if (!NT_STATUS_IS_OK(status)) {
3616 DEBUG(5, ("open_directory: Could not open fd for "
3618 smb_fname_str_dbg(smb_dname),
3619 nt_errstr(status)));
3620 file_free(req, fsp);
3625 DEBUG(10, ("Not opening Directory %s\n",
3626 smb_fname_str_dbg(smb_dname)));
3629 status = vfs_stat_fsp(fsp);
3630 if (!NT_STATUS_IS_OK(status)) {
3632 file_free(req, fsp);
3636 /* Ensure there was no race condition. */
3637 if (!check_same_stat(&smb_dname->st, &fsp->fsp_name->st)) {
3638 DEBUG(5,("open_directory: stat struct differs for "
3640 smb_fname_str_dbg(smb_dname)));
3642 file_free(req, fsp);
3643 return NT_STATUS_ACCESS_DENIED;
3646 lck = get_share_mode_lock(talloc_tos(), fsp->file_id,
3647 conn->connectpath, smb_dname,
3651 DEBUG(0, ("open_directory: Could not get share mode lock for "
3652 "%s\n", smb_fname_str_dbg(smb_dname)));
3654 file_free(req, fsp);
3655 return NT_STATUS_SHARING_VIOLATION;
3658 if (has_delete_on_close(lck, fsp->name_hash)) {
3661 file_free(req, fsp);
3662 return NT_STATUS_DELETE_PENDING;
3665 status = open_mode_check(conn, lck,
3666 access_mask, share_access);
3668 if (!NT_STATUS_IS_OK(status)) {
3671 file_free(req, fsp);
3675 ok = set_share_mode(lck, fsp, get_current_uid(conn),
3676 req ? req->mid : 0, NO_OPLOCK,
3681 file_free(req, fsp);
3682 return NT_STATUS_NO_MEMORY;
3685 /* For directories the delete on close bit at open time seems
3686 always to be honored on close... See test 19 in Samba4 BASE-DELETE. */
3687 if (create_options & FILE_DELETE_ON_CLOSE) {
3688 status = can_set_delete_on_close(fsp, 0);
3689 if (!NT_STATUS_IS_OK(status) && !NT_STATUS_EQUAL(status, NT_STATUS_DIRECTORY_NOT_EMPTY)) {
3690 del_share_mode(lck, fsp);
3693 file_free(req, fsp);
3697 if (NT_STATUS_IS_OK(status)) {
3698 /* Note that here we set the *inital* delete on close flag,
3699 not the regular one. The magic gets handled in close. */
3700 fsp->initial_delete_on_close = True;
3706 * Deal with other opens having a modified write time. Is this
3707 * possible for directories?
3709 struct timespec write_time = get_share_mode_write_time(lck);
3711 if (!null_timespec(write_time)) {
3712 update_stat_ex_mtime(&fsp->fsp_name->st, write_time);
3723 return NT_STATUS_OK;
3726 NTSTATUS create_directory(connection_struct *conn, struct smb_request *req,
3727 struct smb_filename *smb_dname)
3732 status = SMB_VFS_CREATE_FILE(
3735 0, /* root_dir_fid */
3736 smb_dname, /* fname */
3737 FILE_READ_ATTRIBUTES, /* access_mask */
3738 FILE_SHARE_NONE, /* share_access */
3739 FILE_CREATE, /* create_disposition*/
3740 FILE_DIRECTORY_FILE, /* create_options */
3741 FILE_ATTRIBUTE_DIRECTORY, /* file_attributes */
3742 0, /* oplock_request */
3744 0, /* allocation_size */
3745 0, /* private_flags */
3750 NULL, NULL); /* create context */
3752 if (NT_STATUS_IS_OK(status)) {
3753 close_file(req, fsp, NORMAL_CLOSE);
3759 /****************************************************************************
3760 Receive notification that one of our open files has been renamed by another
3762 ****************************************************************************/
3764 void msg_file_was_renamed(struct messaging_context *msg,
3767 struct server_id server_id,
3771 char *frm = (char *)data->data;
3773 const char *sharepath;
3774 const char *base_name;
3775 const char *stream_name;
3776 struct smb_filename *smb_fname = NULL;
3777 size_t sp_len, bn_len;
3779 struct smbd_server_connection *sconn =
3780 talloc_get_type_abort(private_data,
3781 struct smbd_server_connection);
3783 if (data->data == NULL
3784 || data->length < MSG_FILE_RENAMED_MIN_SIZE + 2) {
3785 DEBUG(0, ("msg_file_was_renamed: Got invalid msg len %d\n",
3786 (int)data->length));
3790 /* Unpack the message. */
3791 pull_file_id_24(frm, &id);
3792 sharepath = &frm[24];
3793 sp_len = strlen(sharepath);
3794 base_name = sharepath + sp_len + 1;
3795 bn_len = strlen(base_name);
3796 stream_name = sharepath + sp_len + 1 + bn_len + 1;
3798 /* stream_name must always be NULL if there is no stream. */
3799 if (stream_name[0] == '\0') {
3803 smb_fname = synthetic_smb_fname(talloc_tos(), base_name,
3805 if (smb_fname == NULL) {
3809 DEBUG(10,("msg_file_was_renamed: Got rename message for sharepath %s, new name %s, "
3811 sharepath, smb_fname_str_dbg(smb_fname),
3812 file_id_string_tos(&id)));
3814 for(fsp = file_find_di_first(sconn, id); fsp;
3815 fsp = file_find_di_next(fsp)) {
3816 if (memcmp(fsp->conn->connectpath, sharepath, sp_len) == 0) {
3818 DEBUG(10,("msg_file_was_renamed: renaming file %s from %s -> %s\n",
3819 fsp_fnum_dbg(fsp), fsp_str_dbg(fsp),
3820 smb_fname_str_dbg(smb_fname)));
3821 status = fsp_set_smb_fname(fsp, smb_fname);
3822 if (!NT_STATUS_IS_OK(status)) {
3827 /* Now we have the complete path we can work out if this is
3828 actually within this share and adjust newname accordingly. */
3829 DEBUG(10,("msg_file_was_renamed: share mismatch (sharepath %s "
3830 "not sharepath %s) "
3831 "%s from %s -> %s\n",
3832 fsp->conn->connectpath,
3836 smb_fname_str_dbg(smb_fname)));
3840 TALLOC_FREE(smb_fname);
3845 * If a main file is opened for delete, all streams need to be checked for
3846 * !FILE_SHARE_DELETE. Do this by opening with DELETE_ACCESS.
3847 * If that works, delete them all by setting the delete on close and close.
3850 NTSTATUS open_streams_for_delete(connection_struct *conn,
3853 struct stream_struct *stream_info = NULL;
3854 files_struct **streams = NULL;
3856 unsigned int num_streams = 0;
3857 TALLOC_CTX *frame = talloc_stackframe();
3860 status = vfs_streaminfo(conn, NULL, fname, talloc_tos(),
3861 &num_streams, &stream_info);
3863 if (NT_STATUS_EQUAL(status, NT_STATUS_NOT_IMPLEMENTED)
3864 || NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
3865 DEBUG(10, ("no streams around\n"));
3867 return NT_STATUS_OK;
3870 if (!NT_STATUS_IS_OK(status)) {
3871 DEBUG(10, ("vfs_streaminfo failed: %s\n",
3872 nt_errstr(status)));
3876 DEBUG(10, ("open_streams_for_delete found %d streams\n",
3879 if (num_streams == 0) {
3881 return NT_STATUS_OK;
3884 streams = talloc_array(talloc_tos(), files_struct *, num_streams);
3885 if (streams == NULL) {
3886 DEBUG(0, ("talloc failed\n"));
3887 status = NT_STATUS_NO_MEMORY;
3891 for (i=0; i<num_streams; i++) {
3892 struct smb_filename *smb_fname;
3894 if (strequal(stream_info[i].name, "::$DATA")) {
3899 smb_fname = synthetic_smb_fname(
3900 talloc_tos(), fname, stream_info[i].name, NULL);
3901 if (smb_fname == NULL) {
3902 status = NT_STATUS_NO_MEMORY;
3906 if (SMB_VFS_STAT(conn, smb_fname) == -1) {
3907 DEBUG(10, ("Unable to stat stream: %s\n",
3908 smb_fname_str_dbg(smb_fname)));
3911 status = SMB_VFS_CREATE_FILE(
3914 0, /* root_dir_fid */
3915 smb_fname, /* fname */
3916 DELETE_ACCESS, /* access_mask */
3917 (FILE_SHARE_READ | /* share_access */
3918 FILE_SHARE_WRITE | FILE_SHARE_DELETE),
3919 FILE_OPEN, /* create_disposition*/
3920 0, /* create_options */
3921 FILE_ATTRIBUTE_NORMAL, /* file_attributes */
3922 0, /* oplock_request */
3924 0, /* allocation_size */
3925 NTCREATEX_OPTIONS_PRIVATE_STREAM_DELETE, /* private_flags */
3928 &streams[i], /* result */
3930 NULL, NULL); /* create context */
3932 if (!NT_STATUS_IS_OK(status)) {
3933 DEBUG(10, ("Could not open stream %s: %s\n",
3934 smb_fname_str_dbg(smb_fname),
3935 nt_errstr(status)));
3937 TALLOC_FREE(smb_fname);
3940 TALLOC_FREE(smb_fname);
3944 * don't touch the variable "status" beyond this point :-)
3947 for (i -= 1 ; i >= 0; i--) {
3948 if (streams[i] == NULL) {
3952 DEBUG(10, ("Closing stream # %d, %s\n", i,
3953 fsp_str_dbg(streams[i])));
3954 close_file(NULL, streams[i], NORMAL_CLOSE);
3962 /*********************************************************************
3963 Create a default ACL by inheriting from the parent. If no inheritance
3964 from the parent available, don't set anything. This will leave the actual
3965 permissions the new file or directory already got from the filesystem
3966 as the NT ACL when read.
3967 *********************************************************************/
3969 static NTSTATUS inherit_new_acl(files_struct *fsp)
3971 TALLOC_CTX *frame = talloc_stackframe();
3972 char *parent_name = NULL;
3973 struct security_descriptor *parent_desc = NULL;
3974 NTSTATUS status = NT_STATUS_OK;
3975 struct security_descriptor *psd = NULL;
3976 const struct dom_sid *owner_sid = NULL;
3977 const struct dom_sid *group_sid = NULL;
3978 uint32_t security_info_sent = (SECINFO_OWNER | SECINFO_GROUP | SECINFO_DACL);
3979 struct security_token *token = fsp->conn->session_info->security_token;
3980 bool inherit_owner = lp_inherit_owner(SNUM(fsp->conn));
3981 bool inheritable_components = false;
3982 bool try_builtin_administrators = false;
3983 const struct dom_sid *BA_U_sid = NULL;
3984 const struct dom_sid *BA_G_sid = NULL;
3985 bool try_system = false;
3986 const struct dom_sid *SY_U_sid = NULL;
3987 const struct dom_sid *SY_G_sid = NULL;
3989 struct smb_filename *parent_smb_fname = NULL;
3991 if (!parent_dirname(frame, fsp->fsp_name->base_name, &parent_name, NULL)) {
3993 return NT_STATUS_NO_MEMORY;
3995 parent_smb_fname = synthetic_smb_fname(talloc_tos(),
4000 if (parent_smb_fname == NULL) {
4002 return NT_STATUS_NO_MEMORY;
4005 status = SMB_VFS_GET_NT_ACL(fsp->conn,
4007 (SECINFO_OWNER | SECINFO_GROUP | SECINFO_DACL),
4010 if (!NT_STATUS_IS_OK(status)) {
4015 inheritable_components = sd_has_inheritable_components(parent_desc,
4018 if (!inheritable_components && !inherit_owner) {
4020 /* Nothing to inherit and not setting owner. */
4021 return NT_STATUS_OK;
4024 /* Create an inherited descriptor from the parent. */
4026 if (DEBUGLEVEL >= 10) {
4027 DEBUG(10,("inherit_new_acl: parent acl for %s is:\n",
4028 fsp_str_dbg(fsp) ));
4029 NDR_PRINT_DEBUG(security_descriptor, parent_desc);
4032 /* Inherit from parent descriptor if "inherit owner" set. */
4033 if (inherit_owner) {
4034 owner_sid = parent_desc->owner_sid;
4035 group_sid = parent_desc->group_sid;
4038 if (owner_sid == NULL) {
4039 if (security_token_has_builtin_administrators(token)) {
4040 try_builtin_administrators = true;
4041 } else if (security_token_is_system(token)) {
4042 try_builtin_administrators = true;
4047 if (group_sid == NULL &&
4048 token->num_sids == PRIMARY_GROUP_SID_INDEX)
4050 if (security_token_is_system(token)) {
4051 try_builtin_administrators = true;
4056 if (try_builtin_administrators) {
4061 ok = sids_to_unixids(&global_sid_Builtin_Administrators, 1, &ids);
4065 BA_U_sid = &global_sid_Builtin_Administrators;
4066 BA_G_sid = &global_sid_Builtin_Administrators;
4069 BA_U_sid = &global_sid_Builtin_Administrators;
4072 BA_G_sid = &global_sid_Builtin_Administrators;
4085 ok = sids_to_unixids(&global_sid_System, 1, &ids);
4089 SY_U_sid = &global_sid_System;
4090 SY_G_sid = &global_sid_System;
4093 SY_U_sid = &global_sid_System;
4096 SY_G_sid = &global_sid_System;
4104 if (owner_sid == NULL) {
4105 owner_sid = BA_U_sid;
4108 if (owner_sid == NULL) {
4109 owner_sid = SY_U_sid;
4112 if (group_sid == NULL) {
4113 group_sid = SY_G_sid;
4116 if (try_system && group_sid == NULL) {
4117 group_sid = BA_G_sid;
4120 if (owner_sid == NULL) {
4121 owner_sid = &token->sids[PRIMARY_USER_SID_INDEX];
4123 if (group_sid == NULL) {
4124 if (token->num_sids == PRIMARY_GROUP_SID_INDEX) {
4125 group_sid = &token->sids[PRIMARY_USER_SID_INDEX];
4127 group_sid = &token->sids[PRIMARY_GROUP_SID_INDEX];
4131 status = se_create_child_secdesc(frame,
4138 if (!NT_STATUS_IS_OK(status)) {
4143 /* If inheritable_components == false,
4144 se_create_child_secdesc()
4145 creates a security desriptor with a NULL dacl
4146 entry, but with SEC_DESC_DACL_PRESENT. We need
4147 to remove that flag. */
4149 if (!inheritable_components) {
4150 security_info_sent &= ~SECINFO_DACL;
4151 psd->type &= ~SEC_DESC_DACL_PRESENT;
4154 if (DEBUGLEVEL >= 10) {
4155 DEBUG(10,("inherit_new_acl: child acl for %s is:\n",
4156 fsp_str_dbg(fsp) ));
4157 NDR_PRINT_DEBUG(security_descriptor, psd);
4160 if (inherit_owner) {
4161 /* We need to be root to force this. */
4164 status = SMB_VFS_FSET_NT_ACL(fsp,
4167 if (inherit_owner) {
4175 * If we already have a lease, it must match the new file id. [MS-SMB2]
4176 * 3.3.5.9.8 speaks about INVALID_PARAMETER if an already used lease key is
4177 * used for a different file name.
4180 struct lease_match_state {
4181 /* Input parameters. */
4182 TALLOC_CTX *mem_ctx;
4183 const char *servicepath;
4184 const struct smb_filename *fname;
4187 /* Return parameters. */
4188 uint32_t num_file_ids;
4189 struct file_id *ids;
4190 NTSTATUS match_status;
4193 /*************************************************************
4194 File doesn't exist but this lease key+guid is already in use.
4196 This is only allowable in the dynamic share case where the
4197 service path must be different.
4199 There is a small race condition here in the multi-connection
4200 case where a client sends two create calls on different connections,
4201 where the file doesn't exist and one smbd creates the leases_db
4202 entry first, but this will get fixed by the multichannel cleanup
4203 when all identical client_guids get handled by a single smbd.
4204 **************************************************************/
4206 static void lease_match_parser_new_file(
4208 const struct leases_db_file *files,
4209 struct lease_match_state *state)
4213 for (i = 0; i < num_files; i++) {
4214 const struct leases_db_file *f = &files[i];
4215 if (strequal(state->servicepath, f->servicepath)) {
4216 state->match_status = NT_STATUS_INVALID_PARAMETER;
4221 /* Dynamic share case. Break leases on all other files. */
4222 state->match_status = leases_db_copy_file_ids(state->mem_ctx,
4226 if (!NT_STATUS_IS_OK(state->match_status)) {
4230 state->num_file_ids = num_files;
4231 state->match_status = NT_STATUS_OPLOCK_NOT_GRANTED;
4235 static void lease_match_parser(
4237 const struct leases_db_file *files,
4240 struct lease_match_state *state =
4241 (struct lease_match_state *)private_data;
4244 if (!state->file_existed) {
4246 * Deal with name mismatch or
4247 * possible dynamic share case separately
4248 * to make code clearer.
4250 lease_match_parser_new_file(num_files,
4257 state->match_status = NT_STATUS_OK;
4259 for (i = 0; i < num_files; i++) {
4260 const struct leases_db_file *f = &files[i];
4262 /* Everything should be the same. */
4263 if (!file_id_equal(&state->id, &f->id)) {
4264 /* This should catch all dynamic share cases. */
4265 state->match_status = NT_STATUS_OPLOCK_NOT_GRANTED;
4268 if (!strequal(f->servicepath, state->servicepath)) {
4269 state->match_status = NT_STATUS_INVALID_PARAMETER;
4272 if (!strequal(f->base_name, state->fname->base_name)) {
4273 state->match_status = NT_STATUS_INVALID_PARAMETER;
4276 if (!strequal(f->stream_name, state->fname->stream_name)) {
4277 state->match_status = NT_STATUS_INVALID_PARAMETER;
4282 if (NT_STATUS_IS_OK(state->match_status)) {
4284 * Common case - just opening another handle on a
4285 * file on a non-dynamic share.
4290 if (NT_STATUS_EQUAL(state->match_status, NT_STATUS_INVALID_PARAMETER)) {
4291 /* Mismatched path. Error back to client. */
4296 * File id mismatch. Dynamic share case NT_STATUS_OPLOCK_NOT_GRANTED.
4297 * Don't allow leases.
4300 state->match_status = leases_db_copy_file_ids(state->mem_ctx,
4304 if (!NT_STATUS_IS_OK(state->match_status)) {
4308 state->num_file_ids = num_files;
4309 state->match_status = NT_STATUS_OPLOCK_NOT_GRANTED;
4313 static NTSTATUS lease_match(connection_struct *conn,
4314 struct smb_request *req,
4315 struct smb2_lease_key *lease_key,
4316 const char *servicepath,
4317 const struct smb_filename *fname,
4318 uint16_t *p_version,
4321 struct smbd_server_connection *sconn = req->sconn;
4322 TALLOC_CTX *tos = talloc_tos();
4323 struct lease_match_state state = {
4325 .servicepath = servicepath,
4327 .match_status = NT_STATUS_OK
4332 state.file_existed = VALID_STAT(fname->st);
4333 if (state.file_existed) {
4334 state.id = vfs_file_id_from_sbuf(conn, &fname->st);
4336 memset(&state.id, '\0', sizeof(state.id));
4339 status = leases_db_parse(&sconn->client->connections->smb2.client.guid,
4340 lease_key, lease_match_parser, &state);
4341 if (!NT_STATUS_IS_OK(status)) {
4343 * Not found or error means okay: We can make the lease pass
4345 return NT_STATUS_OK;
4347 if (!NT_STATUS_EQUAL(state.match_status, NT_STATUS_OPLOCK_NOT_GRANTED)) {
4349 * Anything but NT_STATUS_OPLOCK_NOT_GRANTED, let the caller
4352 return state.match_status;
4355 /* We have to break all existing leases. */
4356 for (i = 0; i < state.num_file_ids; i++) {
4357 struct share_mode_lock *lck;
4358 struct share_mode_data *d;
4361 if (file_id_equal(&state.ids[i], &state.id)) {
4362 /* Don't need to break our own file. */
4366 lck = get_existing_share_mode_lock(talloc_tos(), state.ids[i]);
4368 /* Race condition - file already closed. */
4372 for (j=0; j<d->num_share_modes; j++) {
4373 struct share_mode_entry *e = &d->share_modes[j];
4374 uint32_t e_lease_type = get_lease_type(d, e);
4375 struct share_mode_lease *l = NULL;
4377 if (share_mode_stale_pid(d, j)) {
4381 if (e->op_type == LEASE_OPLOCK) {
4382 l = &lck->data->leases[e->lease_idx];
4383 if (!smb2_lease_key_equal(&l->lease_key,
4387 *p_epoch = l->epoch;
4388 *p_version = l->lease_version;
4391 if (e_lease_type == SMB2_LEASE_NONE) {
4395 send_break_message(conn->sconn->msg_ctx, e,
4399 * Windows 7 and 8 lease clients
4400 * are broken in that they will not
4401 * respond to lease break requests
4402 * whilst waiting for an outstanding
4403 * open request on that lease handle
4404 * on the same TCP connection, due
4405 * to holding an internal inode lock.
4407 * This means we can't reschedule
4408 * ourselves here, but must return
4413 * Send the breaks and then return
4414 * SMB2_LEASE_NONE in the lease handle
4415 * to cause them to acknowledge the
4416 * lease break. Consulatation with
4417 * Microsoft engineering confirmed
4418 * this approach is safe.
4425 * Ensure we don't grant anything more so we
4428 return NT_STATUS_OPLOCK_NOT_GRANTED;
4432 * Wrapper around open_file_ntcreate and open_directory
4435 static NTSTATUS create_file_unixpath(connection_struct *conn,
4436 struct smb_request *req,
4437 struct smb_filename *smb_fname,
4438 uint32_t access_mask,
4439 uint32_t share_access,
4440 uint32_t create_disposition,
4441 uint32_t create_options,
4442 uint32_t file_attributes,
4443 uint32_t oplock_request,
4444 struct smb2_lease *lease,
4445 uint64_t allocation_size,
4446 uint32_t private_flags,
4447 struct security_descriptor *sd,
4448 struct ea_list *ea_list,
4450 files_struct **result,
4453 int info = FILE_WAS_OPENED;
4454 files_struct *base_fsp = NULL;
4455 files_struct *fsp = NULL;
4458 DEBUG(10,("create_file_unixpath: access_mask = 0x%x "
4459 "file_attributes = 0x%x, share_access = 0x%x, "
4460 "create_disposition = 0x%x create_options = 0x%x "
4461 "oplock_request = 0x%x private_flags = 0x%x "
4462 "ea_list = 0x%p, sd = 0x%p, "
4464 (unsigned int)access_mask,
4465 (unsigned int)file_attributes,
4466 (unsigned int)share_access,
4467 (unsigned int)create_disposition,
4468 (unsigned int)create_options,
4469 (unsigned int)oplock_request,
4470 (unsigned int)private_flags,
4471 ea_list, sd, smb_fname_str_dbg(smb_fname)));
4473 if (create_options & FILE_OPEN_BY_FILE_ID) {
4474 status = NT_STATUS_NOT_SUPPORTED;
4478 if (create_options & NTCREATEX_OPTIONS_INVALID_PARAM_MASK) {
4479 status = NT_STATUS_INVALID_PARAMETER;
4484 oplock_request |= INTERNAL_OPEN_ONLY;
4487 if (lease != NULL) {
4488 uint16_t epoch = lease->lease_epoch;
4489 uint16_t version = lease->lease_version;
4490 status = lease_match(conn,
4497 if (NT_STATUS_EQUAL(status, NT_STATUS_OPLOCK_NOT_GRANTED)) {
4498 /* Dynamic share file. No leases and update epoch... */
4499 lease->lease_state = SMB2_LEASE_NONE;
4500 lease->lease_epoch = epoch;
4501 lease->lease_version = version;
4502 } else if (!NT_STATUS_IS_OK(status)) {
4507 if ((conn->fs_capabilities & FILE_NAMED_STREAMS)
4508 && (access_mask & DELETE_ACCESS)
4509 && !is_ntfs_stream_smb_fname(smb_fname)) {
4511 * We can't open a file with DELETE access if any of the
4512 * streams is open without FILE_SHARE_DELETE
4514 status = open_streams_for_delete(conn, smb_fname->base_name);
4516 if (!NT_STATUS_IS_OK(status)) {
4521 if ((access_mask & SEC_FLAG_SYSTEM_SECURITY) &&
4522 !security_token_has_privilege(get_current_nttok(conn),
4523 SEC_PRIV_SECURITY)) {
4524 DEBUG(10, ("create_file_unixpath: open on %s "
4525 "failed - SEC_FLAG_SYSTEM_SECURITY denied.\n",
4526 smb_fname_str_dbg(smb_fname)));
4527 status = NT_STATUS_PRIVILEGE_NOT_HELD;
4531 if ((conn->fs_capabilities & FILE_NAMED_STREAMS)
4532 && is_ntfs_stream_smb_fname(smb_fname)
4533 && (!(private_flags & NTCREATEX_OPTIONS_PRIVATE_STREAM_DELETE))) {
4534 uint32_t base_create_disposition;
4535 struct smb_filename *smb_fname_base = NULL;
4537 if (create_options & FILE_DIRECTORY_FILE) {
4538 status = NT_STATUS_NOT_A_DIRECTORY;
4542 switch (create_disposition) {
4544 base_create_disposition = FILE_OPEN;
4547 base_create_disposition = FILE_OPEN_IF;
4551 /* Create an smb_filename with stream_name == NULL. */
4552 smb_fname_base = synthetic_smb_fname(talloc_tos(),
4553 smb_fname->base_name,
4555 if (smb_fname_base == NULL) {
4556 status = NT_STATUS_NO_MEMORY;
4560 if (SMB_VFS_STAT(conn, smb_fname_base) == -1) {
4561 DEBUG(10, ("Unable to stat stream: %s\n",
4562 smb_fname_str_dbg(smb_fname_base)));
4565 * https://bugzilla.samba.org/show_bug.cgi?id=10229
4566 * We need to check if the requested access mask
4567 * could be used to open the underlying file (if
4568 * it existed), as we're passing in zero for the
4569 * access mask to the base filename.
4571 status = check_base_file_access(conn,
4575 if (!NT_STATUS_IS_OK(status)) {
4576 DEBUG(10, ("Permission check "
4577 "for base %s failed: "
4578 "%s\n", smb_fname->base_name,
4579 nt_errstr(status)));
4584 /* Open the base file. */
4585 status = create_file_unixpath(conn, NULL, smb_fname_base, 0,
4588 | FILE_SHARE_DELETE,
4589 base_create_disposition,
4590 0, 0, 0, NULL, 0, 0, NULL, NULL,
4592 TALLOC_FREE(smb_fname_base);
4594 if (!NT_STATUS_IS_OK(status)) {
4595 DEBUG(10, ("create_file_unixpath for base %s failed: "
4596 "%s\n", smb_fname->base_name,
4597 nt_errstr(status)));
4600 /* we don't need the low level fd */
4605 * If it's a request for a directory open, deal with it separately.
4608 if (create_options & FILE_DIRECTORY_FILE) {
4610 if (create_options & FILE_NON_DIRECTORY_FILE) {
4611 status = NT_STATUS_INVALID_PARAMETER;
4615 /* Can't open a temp directory. IFS kit test. */
4616 if (!(file_attributes & FILE_FLAG_POSIX_SEMANTICS) &&
4617 (file_attributes & FILE_ATTRIBUTE_TEMPORARY)) {
4618 status = NT_STATUS_INVALID_PARAMETER;
4623 * We will get a create directory here if the Win32
4624 * app specified a security descriptor in the
4625 * CreateDirectory() call.
4629 status = open_directory(
4630 conn, req, smb_fname, access_mask, share_access,
4631 create_disposition, create_options, file_attributes,
4636 * Ordinary file case.
4639 status = file_new(req, conn, &fsp);
4640 if(!NT_STATUS_IS_OK(status)) {
4644 status = fsp_set_smb_fname(fsp, smb_fname);
4645 if (!NT_STATUS_IS_OK(status)) {
4651 * We're opening the stream element of a
4652 * base_fsp we already opened. Set up the
4655 fsp->base_fsp = base_fsp;
4658 if (allocation_size) {
4659 fsp->initial_allocation_size = smb_roundup(fsp->conn,
4663 status = open_file_ntcreate(conn,
4676 if(!NT_STATUS_IS_OK(status)) {
4677 file_free(req, fsp);
4681 if (NT_STATUS_EQUAL(status, NT_STATUS_FILE_IS_A_DIRECTORY)) {
4683 /* A stream open never opens a directory */
4686 status = NT_STATUS_FILE_IS_A_DIRECTORY;
4691 * Fail the open if it was explicitly a non-directory
4695 if (create_options & FILE_NON_DIRECTORY_FILE) {
4696 status = NT_STATUS_FILE_IS_A_DIRECTORY;
4701 status = open_directory(
4702 conn, req, smb_fname, access_mask,
4703 share_access, create_disposition,
4704 create_options, file_attributes,
4709 if (!NT_STATUS_IS_OK(status)) {
4713 fsp->base_fsp = base_fsp;
4715 if ((ea_list != NULL) &&
4716 ((info == FILE_WAS_CREATED) || (info == FILE_WAS_OVERWRITTEN))) {
4717 status = set_ea(conn, fsp, fsp->fsp_name, ea_list);
4718 if (!NT_STATUS_IS_OK(status)) {
4723 if (!fsp->is_directory && S_ISDIR(fsp->fsp_name->st.st_ex_mode)) {
4724 status = NT_STATUS_ACCESS_DENIED;
4728 /* Save the requested allocation size. */
4729 if ((info == FILE_WAS_CREATED) || (info == FILE_WAS_OVERWRITTEN)) {
4730 if ((allocation_size > fsp->fsp_name->st.st_ex_size)
4731 && !(fsp->is_directory))
4733 fsp->initial_allocation_size = smb_roundup(
4734 fsp->conn, allocation_size);
4735 if (vfs_allocate_file_space(
4736 fsp, fsp->initial_allocation_size) == -1) {
4737 status = NT_STATUS_DISK_FULL;
4741 fsp->initial_allocation_size = smb_roundup(
4742 fsp->conn, (uint64_t)fsp->fsp_name->st.st_ex_size);
4745 fsp->initial_allocation_size = 0;
4748 if ((info == FILE_WAS_CREATED) && lp_nt_acl_support(SNUM(conn)) &&
4749 fsp->base_fsp == NULL) {
4752 * According to the MS documentation, the only time the security
4753 * descriptor is applied to the opened file is iff we *created* the
4754 * file; an existing file stays the same.
4756 * Also, it seems (from observation) that you can open the file with
4757 * any access mask but you can still write the sd. We need to override
4758 * the granted access before we call set_sd
4759 * Patch for bug #2242 from Tom Lackemann <cessnatomny@yahoo.com>.
4762 uint32_t sec_info_sent;
4763 uint32_t saved_access_mask = fsp->access_mask;
4765 sec_info_sent = get_sec_info(sd);
4767 fsp->access_mask = FILE_GENERIC_ALL;
4769 if (sec_info_sent & (SECINFO_OWNER|
4773 status = set_sd(fsp, sd, sec_info_sent);
4776 fsp->access_mask = saved_access_mask;
4778 if (!NT_STATUS_IS_OK(status)) {
4781 } else if (lp_inherit_acls(SNUM(conn))) {
4782 /* Inherit from parent. Errors here are not fatal. */
4783 status = inherit_new_acl(fsp);
4784 if (!NT_STATUS_IS_OK(status)) {
4785 DEBUG(10,("inherit_new_acl: failed for %s with %s\n",
4787 nt_errstr(status) ));
4792 if ((conn->fs_capabilities & FILE_FILE_COMPRESSION)
4793 && (create_options & FILE_NO_COMPRESSION)
4794 && (info == FILE_WAS_CREATED)) {
4795 status = SMB_VFS_SET_COMPRESSION(conn, fsp, fsp,
4796 COMPRESSION_FORMAT_NONE);
4797 if (!NT_STATUS_IS_OK(status)) {
4798 DEBUG(1, ("failed to disable compression: %s\n",
4799 nt_errstr(status)));
4803 DEBUG(10, ("create_file_unixpath: info=%d\n", info));
4806 if (pinfo != NULL) {
4810 smb_fname->st = fsp->fsp_name->st;
4812 return NT_STATUS_OK;
4815 DEBUG(10, ("create_file_unixpath: %s\n", nt_errstr(status)));
4818 if (base_fsp && fsp->base_fsp == base_fsp) {
4820 * The close_file below will close
4825 close_file(req, fsp, ERROR_CLOSE);
4828 if (base_fsp != NULL) {
4829 close_file(req, base_fsp, ERROR_CLOSE);
4836 * Calculate the full path name given a relative fid.
4838 NTSTATUS get_relative_fid_filename(connection_struct *conn,
4839 struct smb_request *req,
4840 uint16_t root_dir_fid,
4841 const struct smb_filename *smb_fname,
4842 struct smb_filename **smb_fname_out)
4844 files_struct *dir_fsp;
4845 char *parent_fname = NULL;
4846 char *new_base_name = NULL;
4847 uint32_t ucf_flags = ((req != NULL && req->posix_pathnames) ?
4848 UCF_POSIX_PATHNAMES : 0);
4851 if (root_dir_fid == 0 || !smb_fname) {
4852 status = NT_STATUS_INTERNAL_ERROR;
4856 dir_fsp = file_fsp(req, root_dir_fid);
4858 if (dir_fsp == NULL) {
4859 status = NT_STATUS_INVALID_HANDLE;
4863 if (is_ntfs_stream_smb_fname(dir_fsp->fsp_name)) {
4864 status = NT_STATUS_INVALID_HANDLE;
4868 if (!dir_fsp->is_directory) {
4871 * Check to see if this is a mac fork of some kind.
4874 if ((conn->fs_capabilities & FILE_NAMED_STREAMS) &&
4875 is_ntfs_stream_smb_fname(smb_fname)) {
4876 status = NT_STATUS_OBJECT_PATH_NOT_FOUND;
4881 we need to handle the case when we get a
4882 relative open relative to a file and the
4883 pathname is blank - this is a reopen!
4884 (hint from demyn plantenberg)
4887 status = NT_STATUS_INVALID_HANDLE;
4891 if (ISDOT(dir_fsp->fsp_name->base_name)) {
4893 * We're at the toplevel dir, the final file name
4894 * must not contain ./, as this is filtered out
4895 * normally by srvstr_get_path and unix_convert
4896 * explicitly rejects paths containing ./.
4898 parent_fname = talloc_strdup(talloc_tos(), "");
4899 if (parent_fname == NULL) {
4900 status = NT_STATUS_NO_MEMORY;
4904 size_t dir_name_len = strlen(dir_fsp->fsp_name->base_name);
4907 * Copy in the base directory name.
4910 parent_fname = talloc_array(talloc_tos(), char,
4912 if (parent_fname == NULL) {
4913 status = NT_STATUS_NO_MEMORY;
4916 memcpy(parent_fname, dir_fsp->fsp_name->base_name,
4920 * Ensure it ends in a '/'.
4921 * We used TALLOC_SIZE +2 to add space for the '/'.
4925 && (parent_fname[dir_name_len-1] != '\\')
4926 && (parent_fname[dir_name_len-1] != '/')) {
4927 parent_fname[dir_name_len] = '/';
4928 parent_fname[dir_name_len+1] = '\0';
4932 new_base_name = talloc_asprintf(talloc_tos(), "%s%s", parent_fname,
4933 smb_fname->base_name);
4934 if (new_base_name == NULL) {
4935 status = NT_STATUS_NO_MEMORY;
4939 status = filename_convert(req,
4941 req->flags2 & FLAGS2_DFS_PATHNAMES,
4946 if (!NT_STATUS_IS_OK(status)) {
4951 TALLOC_FREE(parent_fname);
4952 TALLOC_FREE(new_base_name);
4956 NTSTATUS create_file_default(connection_struct *conn,
4957 struct smb_request *req,
4958 uint16_t root_dir_fid,
4959 struct smb_filename *smb_fname,
4960 uint32_t access_mask,
4961 uint32_t share_access,
4962 uint32_t create_disposition,
4963 uint32_t create_options,
4964 uint32_t file_attributes,
4965 uint32_t oplock_request,
4966 struct smb2_lease *lease,
4967 uint64_t allocation_size,
4968 uint32_t private_flags,
4969 struct security_descriptor *sd,
4970 struct ea_list *ea_list,
4971 files_struct **result,
4973 const struct smb2_create_blobs *in_context_blobs,
4974 struct smb2_create_blobs *out_context_blobs)
4976 int info = FILE_WAS_OPENED;
4977 files_struct *fsp = NULL;
4979 bool stream_name = false;
4981 DEBUG(10,("create_file: access_mask = 0x%x "
4982 "file_attributes = 0x%x, share_access = 0x%x, "
4983 "create_disposition = 0x%x create_options = 0x%x "
4984 "oplock_request = 0x%x "
4985 "private_flags = 0x%x "
4986 "root_dir_fid = 0x%x, ea_list = 0x%p, sd = 0x%p, "
4988 (unsigned int)access_mask,
4989 (unsigned int)file_attributes,
4990 (unsigned int)share_access,
4991 (unsigned int)create_disposition,
4992 (unsigned int)create_options,
4993 (unsigned int)oplock_request,
4994 (unsigned int)private_flags,
4995 (unsigned int)root_dir_fid,
4996 ea_list, sd, smb_fname_str_dbg(smb_fname)));
4999 * Calculate the filename from the root_dir_if if necessary.
5002 if (root_dir_fid != 0) {
5003 struct smb_filename *smb_fname_out = NULL;
5004 status = get_relative_fid_filename(conn, req, root_dir_fid,
5005 smb_fname, &smb_fname_out);
5006 if (!NT_STATUS_IS_OK(status)) {
5009 smb_fname = smb_fname_out;
5013 * Check to see if this is a mac fork of some kind.
5016 stream_name = is_ntfs_stream_smb_fname(smb_fname);
5018 enum FAKE_FILE_TYPE fake_file_type;
5020 fake_file_type = is_fake_file(smb_fname);
5022 if (fake_file_type != FAKE_FILE_TYPE_NONE) {
5025 * Here we go! support for changing the disk quotas
5028 * We need to fake up to open this MAGIC QUOTA file
5029 * and return a valid FID.
5031 * w2k close this file directly after openening xp
5032 * also tries a QUERY_FILE_INFO on the file and then
5035 status = open_fake_file(req, conn, req->vuid,
5036 fake_file_type, smb_fname,
5038 if (!NT_STATUS_IS_OK(status)) {
5042 ZERO_STRUCT(smb_fname->st);
5046 if (!(conn->fs_capabilities & FILE_NAMED_STREAMS)) {
5047 status = NT_STATUS_OBJECT_NAME_NOT_FOUND;
5052 if (is_ntfs_default_stream_smb_fname(smb_fname)) {
5054 smb_fname->stream_name = NULL;
5055 /* We have to handle this error here. */
5056 if (create_options & FILE_DIRECTORY_FILE) {
5057 status = NT_STATUS_NOT_A_DIRECTORY;
5060 if (req != NULL && req->posix_pathnames) {
5061 ret = SMB_VFS_LSTAT(conn, smb_fname);
5063 ret = SMB_VFS_STAT(conn, smb_fname);
5066 if (ret == 0 && VALID_STAT_OF_DIR(smb_fname->st)) {
5067 status = NT_STATUS_FILE_IS_A_DIRECTORY;
5072 status = create_file_unixpath(
5073 conn, req, smb_fname, access_mask, share_access,
5074 create_disposition, create_options, file_attributes,
5075 oplock_request, lease, allocation_size, private_flags,
5079 if (!NT_STATUS_IS_OK(status)) {
5084 DEBUG(10, ("create_file: info=%d\n", info));
5087 if (pinfo != NULL) {
5090 return NT_STATUS_OK;
5093 DEBUG(10, ("create_file: %s\n", nt_errstr(status)));
5096 close_file(req, fsp, ERROR_CLOSE);