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(),
260 if (parent_smb_fname == NULL) {
261 return NT_STATUS_NO_MEMORY;
264 if (get_current_uid(conn) == (uid_t)0) {
265 /* I'm sorry sir, I didn't know you were root... */
266 DEBUG(10,("check_parent_access: root override "
267 "on %s. Granting 0x%x\n",
268 smb_fname_str_dbg(smb_fname),
269 (unsigned int)access_mask ));
273 status = SMB_VFS_GET_NT_ACL(conn,
279 if (!NT_STATUS_IS_OK(status)) {
280 DEBUG(5,("check_parent_access: SMB_VFS_GET_NT_ACL failed for "
281 "%s with error %s\n",
288 * If we can access the path to this file, by
289 * default we have FILE_READ_ATTRIBUTES from the
290 * containing directory. See the section:
291 * "Algorithm to Check Access to an Existing File"
294 * se_file_access_check() also takes care of
295 * owner WRITE_DAC and READ_CONTROL.
297 status = se_file_access_check(parent_sd,
298 get_current_nttok(conn),
300 (access_mask & ~FILE_READ_ATTRIBUTES),
302 if(!NT_STATUS_IS_OK(status)) {
303 DEBUG(5,("check_parent_access: access check "
304 "on directory %s for "
305 "path %s for mask 0x%x returned (0x%x) %s\n",
307 smb_fname->base_name,
310 nt_errstr(status) ));
317 /****************************************************************************
318 Ensure when opening a base file for a stream open that we have permissions
319 to do so given the access mask on the base file.
320 ****************************************************************************/
322 static NTSTATUS check_base_file_access(struct connection_struct *conn,
323 struct smb_filename *smb_fname,
324 uint32_t access_mask)
328 status = smbd_calculate_access_mask(conn, smb_fname,
332 if (!NT_STATUS_IS_OK(status)) {
333 DEBUG(10, ("smbd_calculate_access_mask "
334 "on file %s returned %s\n",
335 smb_fname_str_dbg(smb_fname),
340 if (access_mask & (FILE_WRITE_DATA|FILE_APPEND_DATA)) {
342 if (!CAN_WRITE(conn)) {
343 return NT_STATUS_ACCESS_DENIED;
345 dosattrs = dos_mode(conn, smb_fname);
346 if (IS_DOS_READONLY(dosattrs)) {
347 return NT_STATUS_ACCESS_DENIED;
351 return smbd_check_access_rights(conn,
357 /****************************************************************************
358 fd support routines - attempt to do a dos_open.
359 ****************************************************************************/
361 NTSTATUS fd_open(struct connection_struct *conn,
366 struct smb_filename *smb_fname = fsp->fsp_name;
367 NTSTATUS status = NT_STATUS_OK;
371 * Never follow symlinks on a POSIX client. The
372 * client should be doing this.
375 if ((fsp->posix_flags & FSP_POSIX_FLAGS_OPEN) || !lp_follow_symlinks(SNUM(conn))) {
380 fsp->fh->fd = SMB_VFS_OPEN(conn, smb_fname, fsp, flags, mode);
381 if (fsp->fh->fd == -1) {
382 int posix_errno = errno;
384 #if defined(ENOTSUP) && defined(OSF1)
385 /* handle special Tru64 errno */
386 if (errno == ENOTSUP) {
391 /* fix broken NetBSD errno */
392 if (errno == EFTYPE) {
396 /* fix broken FreeBSD errno */
397 if (errno == EMLINK) {
400 #endif /* O_NOFOLLOW */
401 status = map_nt_error_from_unix(posix_errno);
402 if (errno == EMFILE) {
403 static time_t last_warned = 0L;
405 if (time((time_t *) NULL) > last_warned) {
406 DEBUG(0,("Too many open files, unable "
407 "to open more! smbd's max "
409 lp_max_open_files()));
410 last_warned = time((time_t *) NULL);
416 DEBUG(10,("fd_open: name %s, flags = 0%o mode = 0%o, fd = %d. %s\n",
417 smb_fname_str_dbg(smb_fname), flags, (int)mode, fsp->fh->fd,
418 (fsp->fh->fd == -1) ? strerror(errno) : "" ));
423 /****************************************************************************
424 Close the file associated with a fsp.
425 ****************************************************************************/
427 NTSTATUS fd_close(files_struct *fsp)
434 if (fsp->fh->fd == -1) {
435 return NT_STATUS_OK; /* What we used to call a stat open. */
437 if (fsp->fh->ref_count > 1) {
438 return NT_STATUS_OK; /* Shared handle. Only close last reference. */
441 ret = SMB_VFS_CLOSE(fsp);
444 return map_nt_error_from_unix(errno);
449 /****************************************************************************
450 Change the ownership of a file to that of the parent directory.
451 Do this by fd if possible.
452 ****************************************************************************/
454 void change_file_owner_to_parent(connection_struct *conn,
455 const char *inherit_from_dir,
458 struct smb_filename *smb_fname_parent;
461 smb_fname_parent = synthetic_smb_fname(talloc_tos(),
466 if (smb_fname_parent == NULL) {
470 ret = SMB_VFS_STAT(conn, smb_fname_parent);
472 DEBUG(0,("change_file_owner_to_parent: failed to stat parent "
473 "directory %s. Error was %s\n",
474 smb_fname_str_dbg(smb_fname_parent),
476 TALLOC_FREE(smb_fname_parent);
480 if (smb_fname_parent->st.st_ex_uid == fsp->fsp_name->st.st_ex_uid) {
481 /* Already this uid - no need to change. */
482 DEBUG(10,("change_file_owner_to_parent: file %s "
483 "is already owned by uid %d\n",
485 (int)fsp->fsp_name->st.st_ex_uid ));
486 TALLOC_FREE(smb_fname_parent);
491 ret = SMB_VFS_FCHOWN(fsp, smb_fname_parent->st.st_ex_uid, (gid_t)-1);
494 DEBUG(0,("change_file_owner_to_parent: failed to fchown "
495 "file %s to parent directory uid %u. Error "
496 "was %s\n", fsp_str_dbg(fsp),
497 (unsigned int)smb_fname_parent->st.st_ex_uid,
500 DEBUG(10,("change_file_owner_to_parent: changed new file %s to "
501 "parent directory uid %u.\n", fsp_str_dbg(fsp),
502 (unsigned int)smb_fname_parent->st.st_ex_uid));
503 /* Ensure the uid entry is updated. */
504 fsp->fsp_name->st.st_ex_uid = smb_fname_parent->st.st_ex_uid;
507 TALLOC_FREE(smb_fname_parent);
510 NTSTATUS change_dir_owner_to_parent(connection_struct *conn,
511 const char *inherit_from_dir,
513 SMB_STRUCT_STAT *psbuf)
515 struct smb_filename *smb_fname_parent;
516 struct smb_filename *smb_fname_cwd = NULL;
517 char *saved_dir = NULL;
518 TALLOC_CTX *ctx = talloc_tos();
519 NTSTATUS status = NT_STATUS_OK;
522 smb_fname_parent = synthetic_smb_fname(ctx,
527 if (smb_fname_parent == NULL) {
528 return NT_STATUS_NO_MEMORY;
531 ret = SMB_VFS_STAT(conn, smb_fname_parent);
533 status = map_nt_error_from_unix(errno);
534 DEBUG(0,("change_dir_owner_to_parent: failed to stat parent "
535 "directory %s. Error was %s\n",
536 smb_fname_str_dbg(smb_fname_parent),
541 /* We've already done an lstat into psbuf, and we know it's a
542 directory. If we can cd into the directory and the dev/ino
543 are the same then we can safely chown without races as
544 we're locking the directory in place by being in it. This
545 should work on any UNIX (thanks tridge :-). JRA.
548 saved_dir = vfs_GetWd(ctx,conn);
550 status = map_nt_error_from_unix(errno);
551 DEBUG(0,("change_dir_owner_to_parent: failed to get "
552 "current working directory. Error was %s\n",
557 /* Chdir into the new path. */
558 if (vfs_ChDir(conn, fname) == -1) {
559 status = map_nt_error_from_unix(errno);
560 DEBUG(0,("change_dir_owner_to_parent: failed to change "
561 "current working directory to %s. Error "
562 "was %s\n", fname, strerror(errno) ));
566 smb_fname_cwd = synthetic_smb_fname(ctx, ".", NULL, NULL, 0);
567 if (smb_fname_cwd == NULL) {
568 status = NT_STATUS_NO_MEMORY;
572 ret = SMB_VFS_STAT(conn, smb_fname_cwd);
574 status = map_nt_error_from_unix(errno);
575 DEBUG(0,("change_dir_owner_to_parent: failed to stat "
576 "directory '.' (%s) Error was %s\n",
577 fname, strerror(errno)));
581 /* Ensure we're pointing at the same place. */
582 if (smb_fname_cwd->st.st_ex_dev != psbuf->st_ex_dev ||
583 smb_fname_cwd->st.st_ex_ino != psbuf->st_ex_ino) {
584 DEBUG(0,("change_dir_owner_to_parent: "
585 "device/inode on directory %s changed. "
586 "Refusing to chown !\n", fname ));
587 status = NT_STATUS_ACCESS_DENIED;
591 if (smb_fname_parent->st.st_ex_uid == smb_fname_cwd->st.st_ex_uid) {
592 /* Already this uid - no need to change. */
593 DEBUG(10,("change_dir_owner_to_parent: directory %s "
594 "is already owned by uid %d\n",
596 (int)smb_fname_cwd->st.st_ex_uid ));
597 status = NT_STATUS_OK;
602 ret = SMB_VFS_LCHOWN(conn,
604 smb_fname_parent->st.st_ex_uid,
608 status = map_nt_error_from_unix(errno);
609 DEBUG(10,("change_dir_owner_to_parent: failed to chown "
610 "directory %s to parent directory uid %u. "
611 "Error was %s\n", fname,
612 (unsigned int)smb_fname_parent->st.st_ex_uid,
615 DEBUG(10,("change_dir_owner_to_parent: changed ownership of new "
616 "directory %s to parent directory uid %u.\n",
617 fname, (unsigned int)smb_fname_parent->st.st_ex_uid ));
618 /* Ensure the uid entry is updated. */
619 psbuf->st_ex_uid = smb_fname_parent->st.st_ex_uid;
623 vfs_ChDir(conn,saved_dir);
625 TALLOC_FREE(smb_fname_parent);
626 TALLOC_FREE(smb_fname_cwd);
630 /****************************************************************************
631 Open a file - returning a guaranteed ATOMIC indication of if the
632 file was created or not.
633 ****************************************************************************/
635 static NTSTATUS fd_open_atomic(struct connection_struct *conn,
641 NTSTATUS status = NT_STATUS_UNSUCCESSFUL;
642 bool file_existed = VALID_STAT(fsp->fsp_name->st);
644 *file_created = false;
646 if (!(flags & O_CREAT)) {
648 * We're not creating the file, just pass through.
650 return fd_open(conn, fsp, flags, mode);
653 if (flags & O_EXCL) {
655 * Fail if already exists, just pass through.
657 status = fd_open(conn, fsp, flags, mode);
660 * Here we've opened with O_CREAT|O_EXCL. If that went
661 * NT_STATUS_OK, we *know* we created this file.
663 *file_created = NT_STATUS_IS_OK(status);
669 * Now it gets tricky. We have O_CREAT, but not O_EXCL.
670 * To know absolutely if we created the file or not,
671 * we can never call O_CREAT without O_EXCL. So if
672 * we think the file existed, try without O_CREAT|O_EXCL.
673 * If we think the file didn't exist, try with
674 * O_CREAT|O_EXCL. Keep bouncing between these two
675 * requests until either the file is created, or
676 * opened. Either way, we keep going until we get
677 * a returnable result (error, or open/create).
681 int curr_flags = flags;
684 /* Just try open, do not create. */
685 curr_flags &= ~(O_CREAT);
686 status = fd_open(conn, fsp, curr_flags, mode);
687 if (NT_STATUS_EQUAL(status,
688 NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
690 * Someone deleted it in the meantime.
693 file_existed = false;
694 DEBUG(10,("fd_open_atomic: file %s existed. "
696 smb_fname_str_dbg(fsp->fsp_name)));
700 /* Try create exclusively, fail if it exists. */
701 curr_flags |= O_EXCL;
702 status = fd_open(conn, fsp, curr_flags, mode);
703 if (NT_STATUS_EQUAL(status,
704 NT_STATUS_OBJECT_NAME_COLLISION)) {
706 * Someone created it in the meantime.
707 * Retry without O_CREAT.
710 DEBUG(10,("fd_open_atomic: file %s "
711 "did not exist. Retry.\n",
712 smb_fname_str_dbg(fsp->fsp_name)));
715 if (NT_STATUS_IS_OK(status)) {
717 * Here we've opened with O_CREAT|O_EXCL
718 * and got success. We *know* we created
721 *file_created = true;
724 /* Create is done, or failed. */
730 /****************************************************************************
732 ****************************************************************************/
734 static NTSTATUS open_file(files_struct *fsp,
735 connection_struct *conn,
736 struct smb_request *req,
737 const char *parent_dir,
740 uint32_t access_mask, /* client requested access mask. */
741 uint32_t open_access_mask, /* what we're actually using in the open. */
742 bool *p_file_created)
744 struct smb_filename *smb_fname = fsp->fsp_name;
745 NTSTATUS status = NT_STATUS_OK;
746 int accmode = (flags & O_ACCMODE);
747 int local_flags = flags;
748 bool file_existed = VALID_STAT(fsp->fsp_name->st);
753 /* Check permissions */
756 * This code was changed after seeing a client open request
757 * containing the open mode of (DENY_WRITE/read-only) with
758 * the 'create if not exist' bit set. The previous code
759 * would fail to open the file read only on a read-only share
760 * as it was checking the flags parameter directly against O_RDONLY,
761 * this was failing as the flags parameter was set to O_RDONLY|O_CREAT.
765 if (!CAN_WRITE(conn)) {
766 /* It's a read-only share - fail if we wanted to write. */
767 if(accmode != O_RDONLY || (flags & O_TRUNC) || (flags & O_APPEND)) {
768 DEBUG(3,("Permission denied opening %s\n",
769 smb_fname_str_dbg(smb_fname)));
770 return NT_STATUS_ACCESS_DENIED;
772 if (flags & O_CREAT) {
773 /* We don't want to write - but we must make sure that
774 O_CREAT doesn't create the file if we have write
775 access into the directory.
777 flags &= ~(O_CREAT|O_EXCL);
778 local_flags &= ~(O_CREAT|O_EXCL);
783 * This little piece of insanity is inspired by the
784 * fact that an NT client can open a file for O_RDONLY,
785 * but set the create disposition to FILE_EXISTS_TRUNCATE.
786 * If the client *can* write to the file, then it expects to
787 * truncate the file, even though it is opening for readonly.
788 * Quicken uses this stupid trick in backup file creation...
789 * Thanks *greatly* to "David W. Chapman Jr." <dwcjr@inethouston.net>
790 * for helping track this one down. It didn't bite us in 2.0.x
791 * as we always opened files read-write in that release. JRA.
794 if ((accmode == O_RDONLY) && ((flags & O_TRUNC) == O_TRUNC)) {
795 DEBUG(10,("open_file: truncate requested on read-only open "
796 "for file %s\n", smb_fname_str_dbg(smb_fname)));
797 local_flags = (flags & ~O_ACCMODE)|O_RDWR;
800 if ((open_access_mask & (FILE_READ_DATA|FILE_WRITE_DATA|FILE_APPEND_DATA|FILE_EXECUTE)) ||
801 (!file_existed && (local_flags & O_CREAT)) ||
802 ((local_flags & O_TRUNC) == O_TRUNC) ) {
806 #if defined(O_NONBLOCK) && defined(S_ISFIFO)
808 * We would block on opening a FIFO with no one else on the
809 * other end. Do what we used to do and add O_NONBLOCK to the
813 if (file_existed && S_ISFIFO(smb_fname->st.st_ex_mode)) {
814 local_flags &= ~O_TRUNC; /* Can't truncate a FIFO. */
815 local_flags |= O_NONBLOCK;
819 /* Don't create files with Microsoft wildcard characters. */
822 * wildcard characters are allowed in stream names
823 * only test the basefilename
825 wild = fsp->base_fsp->fsp_name->base_name;
827 wild = smb_fname->base_name;
829 if ((local_flags & O_CREAT) && !file_existed &&
830 !(fsp->posix_flags & FSP_POSIX_FLAGS_PATHNAMES) &&
832 return NT_STATUS_OBJECT_NAME_INVALID;
835 /* Can we access this file ? */
836 if (!fsp->base_fsp) {
837 /* Only do this check on non-stream open. */
839 status = smbd_check_access_rights(conn,
844 if (!NT_STATUS_IS_OK(status)) {
845 DEBUG(10, ("open_file: "
846 "smbd_check_access_rights "
847 "on file %s returned %s\n",
848 smb_fname_str_dbg(smb_fname),
852 if (!NT_STATUS_IS_OK(status) &&
853 !NT_STATUS_EQUAL(status,
854 NT_STATUS_OBJECT_NAME_NOT_FOUND))
859 if (NT_STATUS_EQUAL(status,
860 NT_STATUS_OBJECT_NAME_NOT_FOUND))
862 DEBUG(10, ("open_file: "
863 "file %s vanished since we "
864 "checked for existence.\n",
865 smb_fname_str_dbg(smb_fname)));
866 file_existed = false;
867 SET_STAT_INVALID(fsp->fsp_name->st);
872 if (!(local_flags & O_CREAT)) {
873 /* File didn't exist and no O_CREAT. */
874 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
877 status = check_parent_access(conn,
880 if (!NT_STATUS_IS_OK(status)) {
881 DEBUG(10, ("open_file: "
882 "check_parent_access on "
883 "file %s returned %s\n",
884 smb_fname_str_dbg(smb_fname),
885 nt_errstr(status) ));
892 * Actually do the open - if O_TRUNC is needed handle it
893 * below under the share mode lock.
895 status = fd_open_atomic(conn, fsp, local_flags & ~O_TRUNC,
896 unx_mode, p_file_created);
897 if (!NT_STATUS_IS_OK(status)) {
898 DEBUG(3,("Error opening file %s (%s) (local_flags=%d) "
899 "(flags=%d)\n", smb_fname_str_dbg(smb_fname),
900 nt_errstr(status),local_flags,flags));
904 ret = SMB_VFS_FSTAT(fsp, &smb_fname->st);
906 /* If we have an fd, this stat should succeed. */
907 DEBUG(0,("Error doing fstat on open file %s "
909 smb_fname_str_dbg(smb_fname),
911 status = map_nt_error_from_unix(errno);
916 if (*p_file_created) {
917 /* We created this file. */
919 bool need_re_stat = false;
920 /* Do all inheritance work after we've
921 done a successful fstat call and filled
922 in the stat struct in fsp->fsp_name. */
924 /* Inherit the ACL if required */
925 if (lp_inherit_permissions(SNUM(conn))) {
926 inherit_access_posix_acl(conn, parent_dir,
927 smb_fname->base_name,
932 /* Change the owner if required. */
933 if (lp_inherit_owner(SNUM(conn))) {
934 change_file_owner_to_parent(conn, parent_dir,
940 ret = SMB_VFS_FSTAT(fsp, &smb_fname->st);
941 /* If we have an fd, this stat should succeed. */
943 DEBUG(0,("Error doing fstat on open file %s "
945 smb_fname_str_dbg(smb_fname),
950 notify_fname(conn, NOTIFY_ACTION_ADDED,
951 FILE_NOTIFY_CHANGE_FILE_NAME,
952 smb_fname->base_name);
955 fsp->fh->fd = -1; /* What we used to call a stat open. */
957 /* File must exist for a stat open. */
958 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
961 status = smbd_check_access_rights(conn,
966 if (NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND) &&
967 (fsp->posix_flags & FSP_POSIX_FLAGS_OPEN) &&
968 S_ISLNK(smb_fname->st.st_ex_mode)) {
969 /* This is a POSIX stat open for delete
970 * or rename on a symlink that points
972 DEBUG(10,("open_file: allowing POSIX "
973 "open on bad symlink %s\n",
974 smb_fname_str_dbg(smb_fname)));
975 status = NT_STATUS_OK;
978 if (!NT_STATUS_IS_OK(status)) {
979 DEBUG(10,("open_file: "
980 "smbd_check_access_rights on file "
982 smb_fname_str_dbg(smb_fname),
983 nt_errstr(status) ));
989 * POSIX allows read-only opens of directories. We don't
990 * want to do this (we use a different code path for this)
991 * so catch a directory open and return an EISDIR. JRA.
994 if(S_ISDIR(smb_fname->st.st_ex_mode)) {
997 return NT_STATUS_FILE_IS_A_DIRECTORY;
1000 fsp->file_id = vfs_file_id_from_sbuf(conn, &smb_fname->st);
1001 fsp->vuid = req ? req->vuid : UID_FIELD_INVALID;
1002 fsp->file_pid = req ? req->smbpid : 0;
1003 fsp->can_lock = True;
1004 fsp->can_read = ((access_mask & FILE_READ_DATA) != 0);
1007 ((access_mask & (FILE_WRITE_DATA | FILE_APPEND_DATA)) != 0);
1008 fsp->print_file = NULL;
1009 fsp->modified = False;
1010 fsp->sent_oplock_break = NO_BREAK_SENT;
1011 fsp->is_directory = False;
1012 if (conn->aio_write_behind_list &&
1013 is_in_path(smb_fname->base_name, conn->aio_write_behind_list,
1014 conn->case_sensitive)) {
1015 fsp->aio_write_behind = True;
1018 fsp->wcp = NULL; /* Write cache pointer. */
1020 DEBUG(2,("%s opened file %s read=%s write=%s (numopen=%d)\n",
1021 conn->session_info->unix_info->unix_name,
1022 smb_fname_str_dbg(smb_fname),
1023 BOOLSTR(fsp->can_read), BOOLSTR(fsp->can_write),
1024 conn->num_files_open));
1027 return NT_STATUS_OK;
1030 /****************************************************************************
1031 Check if we can open a file with a share mode.
1032 Returns True if conflict, False if not.
1033 ****************************************************************************/
1035 static bool share_conflict(struct share_mode_entry *entry,
1036 uint32_t access_mask,
1037 uint32_t share_access)
1039 DEBUG(10,("share_conflict: entry->access_mask = 0x%x, "
1040 "entry->share_access = 0x%x, "
1041 "entry->private_options = 0x%x\n",
1042 (unsigned int)entry->access_mask,
1043 (unsigned int)entry->share_access,
1044 (unsigned int)entry->private_options));
1046 if (server_id_is_disconnected(&entry->pid)) {
1048 * note: cleanup should have been done by
1049 * delay_for_batch_oplocks()
1054 DEBUG(10,("share_conflict: access_mask = 0x%x, share_access = 0x%x\n",
1055 (unsigned int)access_mask, (unsigned int)share_access));
1057 if ((entry->access_mask & (FILE_WRITE_DATA|
1061 DELETE_ACCESS)) == 0) {
1062 DEBUG(10,("share_conflict: No conflict due to "
1063 "entry->access_mask = 0x%x\n",
1064 (unsigned int)entry->access_mask ));
1068 if ((access_mask & (FILE_WRITE_DATA|
1072 DELETE_ACCESS)) == 0) {
1073 DEBUG(10,("share_conflict: No conflict due to "
1074 "access_mask = 0x%x\n",
1075 (unsigned int)access_mask ));
1079 #if 1 /* JRA TEST - Superdebug. */
1080 #define CHECK_MASK(num, am, right, sa, share) \
1081 DEBUG(10,("share_conflict: [%d] am (0x%x) & right (0x%x) = 0x%x\n", \
1082 (unsigned int)(num), (unsigned int)(am), \
1083 (unsigned int)(right), (unsigned int)(am)&(right) )); \
1084 DEBUG(10,("share_conflict: [%d] sa (0x%x) & share (0x%x) = 0x%x\n", \
1085 (unsigned int)(num), (unsigned int)(sa), \
1086 (unsigned int)(share), (unsigned int)(sa)&(share) )); \
1087 if (((am) & (right)) && !((sa) & (share))) { \
1088 DEBUG(10,("share_conflict: check %d conflict am = 0x%x, right = 0x%x, \
1089 sa = 0x%x, share = 0x%x\n", (num), (unsigned int)(am), (unsigned int)(right), (unsigned int)(sa), \
1090 (unsigned int)(share) )); \
1094 #define CHECK_MASK(num, am, right, sa, share) \
1095 if (((am) & (right)) && !((sa) & (share))) { \
1096 DEBUG(10,("share_conflict: check %d conflict am = 0x%x, right = 0x%x, \
1097 sa = 0x%x, share = 0x%x\n", (num), (unsigned int)(am), (unsigned int)(right), (unsigned int)(sa), \
1098 (unsigned int)(share) )); \
1103 CHECK_MASK(1, entry->access_mask, FILE_WRITE_DATA | FILE_APPEND_DATA,
1104 share_access, FILE_SHARE_WRITE);
1105 CHECK_MASK(2, access_mask, FILE_WRITE_DATA | FILE_APPEND_DATA,
1106 entry->share_access, FILE_SHARE_WRITE);
1108 CHECK_MASK(3, entry->access_mask, FILE_READ_DATA | FILE_EXECUTE,
1109 share_access, FILE_SHARE_READ);
1110 CHECK_MASK(4, access_mask, FILE_READ_DATA | FILE_EXECUTE,
1111 entry->share_access, FILE_SHARE_READ);
1113 CHECK_MASK(5, entry->access_mask, DELETE_ACCESS,
1114 share_access, FILE_SHARE_DELETE);
1115 CHECK_MASK(6, access_mask, DELETE_ACCESS,
1116 entry->share_access, FILE_SHARE_DELETE);
1118 DEBUG(10,("share_conflict: No conflict.\n"));
1122 #if defined(DEVELOPER)
1123 static void validate_my_share_entries(struct smbd_server_connection *sconn,
1125 struct share_mode_entry *share_entry)
1127 struct server_id self = messaging_server_id(sconn->msg_ctx);
1130 if (!serverid_equal(&self, &share_entry->pid)) {
1134 if (share_entry->op_mid == 0) {
1135 /* INTERNAL_OPEN_ONLY */
1139 if (!is_valid_share_mode_entry(share_entry)) {
1143 fsp = file_find_dif(sconn, share_entry->id,
1144 share_entry->share_file_id);
1146 DEBUG(0,("validate_my_share_entries: PANIC : %s\n",
1147 share_mode_str(talloc_tos(), num, share_entry) ));
1148 smb_panic("validate_my_share_entries: Cannot match a "
1149 "share entry with an open file\n");
1152 if (((uint16_t)fsp->oplock_type) != share_entry->op_type) {
1161 DEBUG(0,("validate_my_share_entries: PANIC : %s\n",
1162 share_mode_str(talloc_tos(), num, share_entry) ));
1163 str = talloc_asprintf(talloc_tos(),
1164 "validate_my_share_entries: "
1165 "file %s, oplock_type = 0x%x, op_type = 0x%x\n",
1166 fsp->fsp_name->base_name,
1167 (unsigned int)fsp->oplock_type,
1168 (unsigned int)share_entry->op_type );
1174 bool is_stat_open(uint32_t access_mask)
1176 const uint32_t stat_open_bits =
1177 (SYNCHRONIZE_ACCESS|
1178 FILE_READ_ATTRIBUTES|
1179 FILE_WRITE_ATTRIBUTES);
1181 return (((access_mask & stat_open_bits) != 0) &&
1182 ((access_mask & ~stat_open_bits) == 0));
1185 static bool has_delete_on_close(struct share_mode_lock *lck,
1188 struct share_mode_data *d = lck->data;
1191 if (d->num_share_modes == 0) {
1194 if (!is_delete_on_close_set(lck, name_hash)) {
1197 for (i=0; i<d->num_share_modes; i++) {
1198 if (!share_mode_stale_pid(d, i)) {
1205 /****************************************************************************
1206 Deal with share modes
1207 Invariant: Share mode must be locked on entry and exit.
1208 Returns -1 on error, or number of share modes on success (may be zero).
1209 ****************************************************************************/
1211 static NTSTATUS open_mode_check(connection_struct *conn,
1212 struct share_mode_lock *lck,
1213 uint32_t access_mask,
1214 uint32_t share_access)
1218 if(lck->data->num_share_modes == 0) {
1219 return NT_STATUS_OK;
1222 if (is_stat_open(access_mask)) {
1223 /* Stat open that doesn't trigger oplock breaks or share mode
1224 * checks... ! JRA. */
1225 return NT_STATUS_OK;
1229 * Check if the share modes will give us access.
1232 #if defined(DEVELOPER)
1233 for(i = 0; i < lck->data->num_share_modes; i++) {
1234 validate_my_share_entries(conn->sconn, i,
1235 &lck->data->share_modes[i]);
1239 /* Now we check the share modes, after any oplock breaks. */
1240 for(i = 0; i < lck->data->num_share_modes; i++) {
1242 if (!is_valid_share_mode_entry(&lck->data->share_modes[i])) {
1246 /* someone else has a share lock on it, check to see if we can
1248 if (share_conflict(&lck->data->share_modes[i],
1249 access_mask, share_access)) {
1251 if (share_mode_stale_pid(lck->data, i)) {
1255 return NT_STATUS_SHARING_VIOLATION;
1259 return NT_STATUS_OK;
1263 * Send a break message to the oplock holder and delay the open for
1267 NTSTATUS send_break_message(struct messaging_context *msg_ctx,
1268 const struct share_mode_entry *exclusive,
1272 char msg[MSG_SMB_SHARE_MODE_ENTRY_SIZE];
1273 struct server_id_buf tmp;
1275 DEBUG(10, ("Sending break request to PID %s\n",
1276 server_id_str_buf(exclusive->pid, &tmp)));
1278 /* Create the message. */
1279 share_mode_entry_to_message(msg, exclusive);
1281 /* Overload entry->op_type */
1283 * This is a cut from uint32_t to uint16_t, but so far only the lower 3
1284 * bits (LEASE_WRITE/HANDLE/READ are used anyway.
1286 SSVAL(msg,OP_BREAK_MSG_OP_TYPE_OFFSET, break_to);
1288 status = messaging_send_buf(msg_ctx, exclusive->pid,
1289 MSG_SMB_BREAK_REQUEST,
1290 (uint8_t *)msg, sizeof(msg));
1291 if (!NT_STATUS_IS_OK(status)) {
1292 DEBUG(3, ("Could not send oplock break message: %s\n",
1293 nt_errstr(status)));
1300 * Do internal consistency checks on the share mode for a file.
1303 static bool validate_oplock_types(struct share_mode_lock *lck)
1305 struct share_mode_data *d = lck->data;
1307 bool ex_or_batch = false;
1308 bool level2 = false;
1309 bool no_oplock = false;
1310 uint32_t num_non_stat_opens = 0;
1313 for (i=0; i<d->num_share_modes; i++) {
1314 struct share_mode_entry *e = &d->share_modes[i];
1316 if (!is_valid_share_mode_entry(e)) {
1320 if (e->op_mid == 0) {
1321 /* INTERNAL_OPEN_ONLY */
1325 if (e->op_type == NO_OPLOCK && is_stat_open(e->access_mask)) {
1326 /* We ignore stat opens in the table - they
1327 always have NO_OPLOCK and never get or
1328 cause breaks. JRA. */
1332 num_non_stat_opens += 1;
1334 if (BATCH_OPLOCK_TYPE(e->op_type)) {
1335 /* batch - can only be one. */
1336 if (share_mode_stale_pid(d, i)) {
1337 DEBUG(10, ("Found stale batch oplock\n"));
1340 if (ex_or_batch || batch || level2 || no_oplock) {
1341 DEBUG(0, ("Bad batch oplock entry %u.",
1348 if (EXCLUSIVE_OPLOCK_TYPE(e->op_type)) {
1349 if (share_mode_stale_pid(d, i)) {
1350 DEBUG(10, ("Found stale duplicate oplock\n"));
1353 /* Exclusive or batch - can only be one. */
1354 if (ex_or_batch || level2 || no_oplock) {
1355 DEBUG(0, ("Bad exclusive or batch oplock "
1356 "entry %u.", (unsigned)i));
1362 if (LEVEL_II_OPLOCK_TYPE(e->op_type)) {
1363 if (batch || ex_or_batch) {
1364 if (share_mode_stale_pid(d, i)) {
1365 DEBUG(10, ("Found stale LevelII "
1369 DEBUG(0, ("Bad levelII oplock entry %u.",
1376 if (e->op_type == NO_OPLOCK) {
1377 if (batch || ex_or_batch) {
1378 if (share_mode_stale_pid(d, i)) {
1379 DEBUG(10, ("Found stale NO_OPLOCK "
1383 DEBUG(0, ("Bad no oplock entry %u.",
1391 remove_stale_share_mode_entries(d);
1393 if ((batch || ex_or_batch) && (num_non_stat_opens != 1)) {
1394 DEBUG(1, ("got batch (%d) or ex (%d) non-exclusively (%d)\n",
1395 (int)batch, (int)ex_or_batch,
1396 (int)d->num_share_modes));
1403 static bool delay_for_oplock(files_struct *fsp,
1405 const struct smb2_lease *lease,
1406 struct share_mode_lock *lck,
1407 bool have_sharing_violation,
1408 uint32_t create_disposition,
1409 bool first_open_attempt)
1411 struct share_mode_data *d = lck->data;
1414 bool will_overwrite;
1416 if ((oplock_request & INTERNAL_OPEN_ONLY) ||
1417 is_stat_open(fsp->access_mask)) {
1421 switch (create_disposition) {
1422 case FILE_SUPERSEDE:
1423 case FILE_OVERWRITE:
1424 case FILE_OVERWRITE_IF:
1425 will_overwrite = true;
1428 will_overwrite = false;
1432 for (i=0; i<d->num_share_modes; i++) {
1433 struct share_mode_entry *e = &d->share_modes[i];
1434 struct share_mode_lease *l = NULL;
1435 uint32_t e_lease_type = get_lease_type(d, e);
1437 uint32_t delay_mask = 0;
1439 if (e->op_type == LEASE_OPLOCK) {
1440 l = &d->leases[e->lease_idx];
1443 if (have_sharing_violation) {
1444 delay_mask = SMB2_LEASE_HANDLE;
1446 delay_mask = SMB2_LEASE_WRITE;
1449 break_to = e_lease_type & ~delay_mask;
1451 if (will_overwrite) {
1453 * we'll decide about SMB2_LEASE_READ later.
1455 * Maybe the break will be defered
1457 break_to &= ~SMB2_LEASE_HANDLE;
1460 DEBUG(10, ("entry %u: e_lease_type %u, will_overwrite: %u\n",
1461 (unsigned)i, (unsigned)e_lease_type,
1462 (unsigned)will_overwrite));
1464 if (lease != NULL && l != NULL) {
1467 ign = smb2_lease_equal(fsp_client_guid(fsp),
1476 if ((e_lease_type & ~break_to) == 0) {
1477 if (l != NULL && l->breaking) {
1483 if (share_mode_stale_pid(d, i)) {
1487 if (will_overwrite) {
1489 * If we break anyway break to NONE directly.
1490 * Otherwise vfs_set_filelen() will trigger the
1493 break_to &= ~(SMB2_LEASE_READ|SMB2_LEASE_WRITE);
1496 if (e->op_type != LEASE_OPLOCK) {
1498 * Oplocks only support breaking to R or NONE.
1500 break_to &= ~(SMB2_LEASE_HANDLE|SMB2_LEASE_WRITE);
1503 DEBUG(10, ("breaking from %d to %d\n",
1504 (int)e_lease_type, (int)break_to));
1505 send_break_message(fsp->conn->sconn->msg_ctx, e,
1507 if (e_lease_type & delay_mask) {
1510 if (l != NULL && l->breaking && !first_open_attempt) {
1519 static bool file_has_brlocks(files_struct *fsp)
1521 struct byte_range_lock *br_lck;
1523 br_lck = brl_get_locks_readonly(fsp);
1527 return (brl_num_locks(br_lck) > 0);
1530 int find_share_mode_lease(struct share_mode_data *d,
1531 const struct GUID *client_guid,
1532 const struct smb2_lease_key *key)
1536 for (i=0; i<d->num_leases; i++) {
1537 struct share_mode_lease *l = &d->leases[i];
1539 if (smb2_lease_equal(client_guid,
1550 struct fsp_lease *find_fsp_lease(struct files_struct *new_fsp,
1551 const struct smb2_lease_key *key,
1552 const struct share_mode_lease *l)
1554 struct files_struct *fsp;
1557 * TODO: Measure how expensive this loop is with thousands of open
1561 for (fsp = file_find_di_first(new_fsp->conn->sconn, new_fsp->file_id);
1563 fsp = file_find_di_next(fsp)) {
1565 if (fsp == new_fsp) {
1568 if (fsp->oplock_type != LEASE_OPLOCK) {
1571 if (smb2_lease_key_equal(&fsp->lease->lease.lease_key, key)) {
1572 fsp->lease->ref_count += 1;
1577 /* Not found - must be leased in another smbd. */
1578 new_fsp->lease = talloc_zero(new_fsp->conn->sconn, struct fsp_lease);
1579 if (new_fsp->lease == NULL) {
1582 new_fsp->lease->ref_count = 1;
1583 new_fsp->lease->sconn = new_fsp->conn->sconn;
1584 new_fsp->lease->lease.lease_key = *key;
1585 new_fsp->lease->lease.lease_state = l->current_state;
1587 * We internally treat all leases as V2 and update
1588 * the epoch, but when sending breaks it matters if
1589 * the requesting lease was v1 or v2.
1591 new_fsp->lease->lease.lease_version = l->lease_version;
1592 new_fsp->lease->lease.lease_epoch = l->epoch;
1593 return new_fsp->lease;
1596 static NTSTATUS grant_fsp_lease(struct files_struct *fsp,
1597 struct share_mode_lock *lck,
1598 const struct smb2_lease *lease,
1599 uint32_t *p_lease_idx,
1602 struct share_mode_data *d = lck->data;
1603 const struct GUID *client_guid = fsp_client_guid(fsp);
1604 struct share_mode_lease *tmp;
1608 idx = find_share_mode_lease(d, client_guid, &lease->lease_key);
1611 struct share_mode_lease *l = &d->leases[idx];
1613 uint32_t existing, requested;
1615 fsp->lease = find_fsp_lease(fsp, &lease->lease_key, l);
1616 if (fsp->lease == NULL) {
1617 DEBUG(1, ("Did not find existing lease for file %s\n",
1619 return NT_STATUS_NO_MEMORY;
1625 * Upgrade only if the requested lease is a strict upgrade.
1627 existing = l->current_state;
1628 requested = lease->lease_state;
1631 * Tricky: This test makes sure that "requested" is a
1632 * strict bitwise superset of "existing".
1634 do_upgrade = ((existing & requested) == existing);
1637 * Upgrade only if there's a change.
1639 do_upgrade &= (granted != existing);
1642 * Upgrade only if other leases don't prevent what was asked
1645 do_upgrade &= (granted == requested);
1648 * only upgrade if we are not in breaking state
1650 do_upgrade &= !l->breaking;
1652 DEBUG(10, ("existing=%"PRIu32", requested=%"PRIu32", "
1653 "granted=%"PRIu32", do_upgrade=%d\n",
1654 existing, requested, granted, (int)do_upgrade));
1657 l->current_state = granted;
1661 /* Ensure we're in sync with current lease state. */
1662 fsp_lease_update(lck, fsp_client_guid(fsp), fsp->lease);
1663 return NT_STATUS_OK;
1670 tmp = talloc_realloc(d, d->leases, struct share_mode_lease,
1676 return NT_STATUS_INSUFFICIENT_RESOURCES;
1680 fsp->lease = talloc_zero(fsp->conn->sconn, struct fsp_lease);
1681 if (fsp->lease == NULL) {
1682 return NT_STATUS_INSUFFICIENT_RESOURCES;
1684 fsp->lease->ref_count = 1;
1685 fsp->lease->sconn = fsp->conn->sconn;
1686 fsp->lease->lease.lease_version = lease->lease_version;
1687 fsp->lease->lease.lease_key = lease->lease_key;
1688 fsp->lease->lease.lease_state = granted;
1689 fsp->lease->lease.lease_epoch = lease->lease_epoch + 1;
1691 *p_lease_idx = d->num_leases;
1693 d->leases[d->num_leases] = (struct share_mode_lease) {
1694 .client_guid = *client_guid,
1695 .lease_key = fsp->lease->lease.lease_key,
1696 .current_state = fsp->lease->lease.lease_state,
1697 .lease_version = fsp->lease->lease.lease_version,
1698 .epoch = fsp->lease->lease.lease_epoch,
1701 status = leases_db_add(client_guid,
1704 fsp->conn->connectpath,
1705 fsp->fsp_name->base_name,
1706 fsp->fsp_name->stream_name);
1707 if (!NT_STATUS_IS_OK(status)) {
1708 DEBUG(10, ("%s: leases_db_add failed: %s\n", __func__,
1709 nt_errstr(status)));
1710 TALLOC_FREE(fsp->lease);
1711 return NT_STATUS_INSUFFICIENT_RESOURCES;
1717 return NT_STATUS_OK;
1720 static bool is_same_lease(const files_struct *fsp,
1721 const struct share_mode_data *d,
1722 const struct share_mode_entry *e,
1723 const struct smb2_lease *lease)
1725 if (e->op_type != LEASE_OPLOCK) {
1728 if (lease == NULL) {
1732 return smb2_lease_equal(fsp_client_guid(fsp),
1734 &d->leases[e->lease_idx].client_guid,
1735 &d->leases[e->lease_idx].lease_key);
1738 static NTSTATUS grant_fsp_oplock_type(struct smb_request *req,
1739 struct files_struct *fsp,
1740 struct share_mode_lock *lck,
1742 struct smb2_lease *lease)
1744 struct share_mode_data *d = lck->data;
1745 bool got_handle_lease = false;
1746 bool got_oplock = false;
1749 uint32_t lease_idx = UINT32_MAX;
1753 if (oplock_request & INTERNAL_OPEN_ONLY) {
1754 /* No oplocks on internal open. */
1755 oplock_request = NO_OPLOCK;
1756 DEBUG(10,("grant_fsp_oplock_type: oplock type 0x%x on file %s\n",
1757 fsp->oplock_type, fsp_str_dbg(fsp)));
1760 if (oplock_request == LEASE_OPLOCK) {
1761 if (lease == NULL) {
1763 * The SMB2 layer should have checked this
1765 return NT_STATUS_INTERNAL_ERROR;
1768 granted = lease->lease_state;
1770 if (lp_kernel_oplocks(SNUM(fsp->conn))) {
1771 DEBUG(10, ("No lease granted because kernel oplocks are enabled\n"));
1772 granted = SMB2_LEASE_NONE;
1774 if ((granted & (SMB2_LEASE_READ|SMB2_LEASE_WRITE)) == 0) {
1775 DEBUG(10, ("No read or write lease requested\n"));
1776 granted = SMB2_LEASE_NONE;
1778 if (granted == SMB2_LEASE_WRITE) {
1779 DEBUG(10, ("pure write lease requested\n"));
1780 granted = SMB2_LEASE_NONE;
1782 if (granted == (SMB2_LEASE_WRITE|SMB2_LEASE_HANDLE)) {
1783 DEBUG(10, ("write and handle lease requested\n"));
1784 granted = SMB2_LEASE_NONE;
1787 granted = map_oplock_to_lease_type(
1788 oplock_request & ~SAMBA_PRIVATE_OPLOCK_MASK);
1791 if (lp_locking(fsp->conn->params) && file_has_brlocks(fsp)) {
1792 DEBUG(10,("grant_fsp_oplock_type: file %s has byte range locks\n",
1794 granted &= ~SMB2_LEASE_READ;
1797 for (i=0; i<d->num_share_modes; i++) {
1798 struct share_mode_entry *e = &d->share_modes[i];
1799 uint32_t e_lease_type;
1801 e_lease_type = get_lease_type(d, e);
1803 if ((granted & SMB2_LEASE_WRITE) &&
1804 !is_same_lease(fsp, d, e, lease) &&
1805 !share_mode_stale_pid(d, i)) {
1807 * Can grant only one writer
1809 granted &= ~SMB2_LEASE_WRITE;
1812 if ((e_lease_type & SMB2_LEASE_HANDLE) && !got_handle_lease &&
1813 !share_mode_stale_pid(d, i)) {
1814 got_handle_lease = true;
1817 if ((e->op_type != LEASE_OPLOCK) && !got_oplock &&
1818 !share_mode_stale_pid(d, i)) {
1823 if ((granted & SMB2_LEASE_READ) && !(granted & SMB2_LEASE_WRITE)) {
1825 (global_client_caps & CAP_LEVEL_II_OPLOCKS) &&
1826 lp_level2_oplocks(SNUM(fsp->conn));
1828 if (!allow_level2) {
1829 granted = SMB2_LEASE_NONE;
1833 if (oplock_request == LEASE_OPLOCK) {
1835 granted &= ~SMB2_LEASE_HANDLE;
1838 fsp->oplock_type = LEASE_OPLOCK;
1840 status = grant_fsp_lease(fsp, lck, lease, &lease_idx,
1842 if (!NT_STATUS_IS_OK(status)) {
1846 *lease = fsp->lease->lease;
1847 DEBUG(10, ("lease_state=%d\n", lease->lease_state));
1849 if (got_handle_lease) {
1850 granted = SMB2_LEASE_NONE;
1854 case SMB2_LEASE_READ|SMB2_LEASE_WRITE|SMB2_LEASE_HANDLE:
1855 fsp->oplock_type = BATCH_OPLOCK|EXCLUSIVE_OPLOCK;
1857 case SMB2_LEASE_READ|SMB2_LEASE_WRITE:
1858 fsp->oplock_type = EXCLUSIVE_OPLOCK;
1860 case SMB2_LEASE_READ|SMB2_LEASE_HANDLE:
1861 case SMB2_LEASE_READ:
1862 fsp->oplock_type = LEVEL_II_OPLOCK;
1865 fsp->oplock_type = NO_OPLOCK;
1869 status = set_file_oplock(fsp);
1870 if (!NT_STATUS_IS_OK(status)) {
1872 * Could not get the kernel oplock
1874 fsp->oplock_type = NO_OPLOCK;
1878 ok = set_share_mode(lck, fsp, get_current_uid(fsp->conn),
1883 return NT_STATUS_NO_MEMORY;
1886 ok = update_num_read_oplocks(fsp, lck);
1888 del_share_mode(lck, fsp);
1889 return NT_STATUS_INTERNAL_ERROR;
1892 DEBUG(10,("grant_fsp_oplock_type: oplock type 0x%x on file %s\n",
1893 fsp->oplock_type, fsp_str_dbg(fsp)));
1895 return NT_STATUS_OK;
1898 static bool request_timed_out(struct timeval request_time,
1899 struct timeval timeout)
1901 struct timeval now, end_time;
1903 end_time = timeval_sum(&request_time, &timeout);
1904 return (timeval_compare(&end_time, &now) < 0);
1907 struct defer_open_state {
1908 struct smbXsrv_connection *xconn;
1912 static void defer_open_done(struct tevent_req *req);
1914 /****************************************************************************
1915 Handle the 1 second delay in returning a SHARING_VIOLATION error.
1916 ****************************************************************************/
1918 static void defer_open(struct share_mode_lock *lck,
1919 struct timeval request_time,
1920 struct timeval timeout,
1921 struct smb_request *req,
1922 struct deferred_open_record *state)
1924 struct deferred_open_record *open_rec;
1926 DEBUG(10,("defer_open_sharing_error: time [%u.%06u] adding deferred "
1927 "open entry for mid %llu\n",
1928 (unsigned int)request_time.tv_sec,
1929 (unsigned int)request_time.tv_usec,
1930 (unsigned long long)req->mid));
1932 open_rec = talloc(NULL, struct deferred_open_record);
1933 if (open_rec == NULL) {
1935 exit_server("talloc failed");
1941 struct defer_open_state *watch_state;
1942 struct tevent_req *watch_req;
1945 watch_state = talloc(open_rec, struct defer_open_state);
1946 if (watch_state == NULL) {
1947 exit_server("talloc failed");
1949 watch_state->xconn = req->xconn;
1950 watch_state->mid = req->mid;
1952 DEBUG(10, ("defering mid %llu\n",
1953 (unsigned long long)req->mid));
1955 watch_req = dbwrap_record_watch_send(
1956 watch_state, req->sconn->ev_ctx, lck->data->record,
1957 req->sconn->msg_ctx);
1958 if (watch_req == NULL) {
1959 exit_server("Could not watch share mode record");
1961 tevent_req_set_callback(watch_req, defer_open_done,
1964 ret = tevent_req_set_endtime(
1965 watch_req, req->sconn->ev_ctx,
1966 timeval_sum(&request_time, &timeout));
1970 if (!push_deferred_open_message_smb(req, request_time, timeout,
1971 state->id, open_rec)) {
1973 exit_server("push_deferred_open_message_smb failed");
1977 static void defer_open_done(struct tevent_req *req)
1979 struct defer_open_state *state = tevent_req_callback_data(
1980 req, struct defer_open_state);
1984 status = dbwrap_record_watch_recv(req, talloc_tos(), NULL);
1986 if (!NT_STATUS_IS_OK(status)) {
1987 DEBUG(5, ("dbwrap_record_watch_recv returned %s\n",
1988 nt_errstr(status)));
1990 * Even if it failed, retry anyway. TODO: We need a way to
1991 * tell a re-scheduled open about that error.
1995 DEBUG(10, ("scheduling mid %llu\n", (unsigned long long)state->mid));
1997 ret = schedule_deferred_open_message_smb(state->xconn, state->mid);
2003 /****************************************************************************
2004 On overwrite open ensure that the attributes match.
2005 ****************************************************************************/
2007 static bool open_match_attributes(connection_struct *conn,
2008 uint32_t old_dos_attr,
2009 uint32_t new_dos_attr,
2010 mode_t existing_unx_mode,
2011 mode_t new_unx_mode,
2012 mode_t *returned_unx_mode)
2014 uint32_t noarch_old_dos_attr, noarch_new_dos_attr;
2016 noarch_old_dos_attr = (old_dos_attr & ~FILE_ATTRIBUTE_ARCHIVE);
2017 noarch_new_dos_attr = (new_dos_attr & ~FILE_ATTRIBUTE_ARCHIVE);
2019 if((noarch_old_dos_attr == 0 && noarch_new_dos_attr != 0) ||
2020 (noarch_old_dos_attr != 0 && ((noarch_old_dos_attr & noarch_new_dos_attr) == noarch_old_dos_attr))) {
2021 *returned_unx_mode = new_unx_mode;
2023 *returned_unx_mode = (mode_t)0;
2026 DEBUG(10,("open_match_attributes: old_dos_attr = 0x%x, "
2027 "existing_unx_mode = 0%o, new_dos_attr = 0x%x "
2028 "returned_unx_mode = 0%o\n",
2029 (unsigned int)old_dos_attr,
2030 (unsigned int)existing_unx_mode,
2031 (unsigned int)new_dos_attr,
2032 (unsigned int)*returned_unx_mode ));
2034 /* If we're mapping SYSTEM and HIDDEN ensure they match. */
2035 if (lp_map_system(SNUM(conn)) || lp_store_dos_attributes(SNUM(conn))) {
2036 if ((old_dos_attr & FILE_ATTRIBUTE_SYSTEM) &&
2037 !(new_dos_attr & FILE_ATTRIBUTE_SYSTEM)) {
2041 if (lp_map_hidden(SNUM(conn)) || lp_store_dos_attributes(SNUM(conn))) {
2042 if ((old_dos_attr & FILE_ATTRIBUTE_HIDDEN) &&
2043 !(new_dos_attr & FILE_ATTRIBUTE_HIDDEN)) {
2050 /****************************************************************************
2051 Special FCB or DOS processing in the case of a sharing violation.
2052 Try and find a duplicated file handle.
2053 ****************************************************************************/
2055 static NTSTATUS fcb_or_dos_open(struct smb_request *req,
2056 connection_struct *conn,
2057 files_struct *fsp_to_dup_into,
2058 const struct smb_filename *smb_fname,
2062 uint32_t access_mask,
2063 uint32_t share_access,
2064 uint32_t create_options)
2068 DEBUG(5,("fcb_or_dos_open: attempting old open semantics for "
2069 "file %s.\n", smb_fname_str_dbg(smb_fname)));
2071 for(fsp = file_find_di_first(conn->sconn, id); fsp;
2072 fsp = file_find_di_next(fsp)) {
2074 DEBUG(10,("fcb_or_dos_open: checking file %s, fd = %d, "
2075 "vuid = %llu, file_pid = %u, private_options = 0x%x "
2076 "access_mask = 0x%x\n", fsp_str_dbg(fsp),
2077 fsp->fh->fd, (unsigned long long)fsp->vuid,
2078 (unsigned int)fsp->file_pid,
2079 (unsigned int)fsp->fh->private_options,
2080 (unsigned int)fsp->access_mask ));
2082 if (fsp != fsp_to_dup_into &&
2083 fsp->fh->fd != -1 &&
2084 fsp->vuid == vuid &&
2085 fsp->file_pid == file_pid &&
2086 (fsp->fh->private_options & (NTCREATEX_OPTIONS_PRIVATE_DENY_DOS |
2087 NTCREATEX_OPTIONS_PRIVATE_DENY_FCB)) &&
2088 (fsp->access_mask & FILE_WRITE_DATA) &&
2089 strequal(fsp->fsp_name->base_name, smb_fname->base_name) &&
2090 strequal(fsp->fsp_name->stream_name,
2091 smb_fname->stream_name)) {
2092 DEBUG(10,("fcb_or_dos_open: file match\n"));
2098 return NT_STATUS_NOT_FOUND;
2101 /* quite an insane set of semantics ... */
2102 if (is_executable(smb_fname->base_name) &&
2103 (fsp->fh->private_options & NTCREATEX_OPTIONS_PRIVATE_DENY_DOS)) {
2104 DEBUG(10,("fcb_or_dos_open: file fail due to is_executable.\n"));
2105 return NT_STATUS_INVALID_PARAMETER;
2108 /* We need to duplicate this fsp. */
2109 return dup_file_fsp(req, fsp, access_mask, share_access,
2110 create_options, fsp_to_dup_into);
2113 static void schedule_defer_open(struct share_mode_lock *lck,
2115 struct timeval request_time,
2116 struct smb_request *req)
2118 struct deferred_open_record state;
2120 /* This is a relative time, added to the absolute
2121 request_time value to get the absolute timeout time.
2122 Note that if this is the second or greater time we enter
2123 this codepath for this particular request mid then
2124 request_time is left as the absolute time of the *first*
2125 time this request mid was processed. This is what allows
2126 the request to eventually time out. */
2128 struct timeval timeout;
2130 /* Normally the smbd we asked should respond within
2131 * OPLOCK_BREAK_TIMEOUT seconds regardless of whether
2132 * the client did, give twice the timeout as a safety
2133 * measure here in case the other smbd is stuck
2134 * somewhere else. */
2136 timeout = timeval_set(OPLOCK_BREAK_TIMEOUT*2, 0);
2138 /* Nothing actually uses state.delayed_for_oplocks
2139 but it's handy to differentiate in debug messages
2140 between a 30 second delay due to oplock break, and
2141 a 1 second delay for share mode conflicts. */
2143 state.delayed_for_oplocks = True;
2144 state.async_open = false;
2147 if (!request_timed_out(request_time, timeout)) {
2148 defer_open(lck, request_time, timeout, req, &state);
2152 /****************************************************************************
2153 Reschedule an open call that went asynchronous.
2154 ****************************************************************************/
2156 static void schedule_async_open(struct timeval request_time,
2157 struct smb_request *req)
2159 struct deferred_open_record state;
2160 struct timeval timeout;
2162 timeout = timeval_set(20, 0);
2165 state.delayed_for_oplocks = false;
2166 state.async_open = true;
2168 if (!request_timed_out(request_time, timeout)) {
2169 defer_open(NULL, request_time, timeout, req, &state);
2173 /****************************************************************************
2174 Work out what access_mask to use from what the client sent us.
2175 ****************************************************************************/
2177 static NTSTATUS smbd_calculate_maximum_allowed_access(
2178 connection_struct *conn,
2179 const struct smb_filename *smb_fname,
2181 uint32_t *p_access_mask)
2183 struct security_descriptor *sd;
2184 uint32_t access_granted;
2187 if (!use_privs && (get_current_uid(conn) == (uid_t)0)) {
2188 *p_access_mask |= FILE_GENERIC_ALL;
2189 return NT_STATUS_OK;
2192 status = SMB_VFS_GET_NT_ACL(conn, smb_fname,
2198 if (NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
2200 * File did not exist
2202 *p_access_mask = FILE_GENERIC_ALL;
2203 return NT_STATUS_OK;
2205 if (!NT_STATUS_IS_OK(status)) {
2206 DEBUG(10,("Could not get acl on file %s: %s\n",
2207 smb_fname_str_dbg(smb_fname),
2208 nt_errstr(status)));
2209 return NT_STATUS_ACCESS_DENIED;
2213 * If we can access the path to this file, by
2214 * default we have FILE_READ_ATTRIBUTES from the
2215 * containing directory. See the section:
2216 * "Algorithm to Check Access to an Existing File"
2219 * se_file_access_check()
2220 * also takes care of owner WRITE_DAC and READ_CONTROL.
2222 status = se_file_access_check(sd,
2223 get_current_nttok(conn),
2225 (*p_access_mask & ~FILE_READ_ATTRIBUTES),
2230 if (!NT_STATUS_IS_OK(status)) {
2231 DEBUG(10, ("Access denied on file %s: "
2232 "when calculating maximum access\n",
2233 smb_fname_str_dbg(smb_fname)));
2234 return NT_STATUS_ACCESS_DENIED;
2236 *p_access_mask = (access_granted | FILE_READ_ATTRIBUTES);
2238 if (!(access_granted & DELETE_ACCESS)) {
2239 if (can_delete_file_in_directory(conn, smb_fname)) {
2240 *p_access_mask |= DELETE_ACCESS;
2244 return NT_STATUS_OK;
2247 NTSTATUS smbd_calculate_access_mask(connection_struct *conn,
2248 const struct smb_filename *smb_fname,
2250 uint32_t access_mask,
2251 uint32_t *access_mask_out)
2254 uint32_t orig_access_mask = access_mask;
2255 uint32_t rejected_share_access;
2258 * Convert GENERIC bits to specific bits.
2261 se_map_generic(&access_mask, &file_generic_mapping);
2263 /* Calculate MAXIMUM_ALLOWED_ACCESS if requested. */
2264 if (access_mask & MAXIMUM_ALLOWED_ACCESS) {
2266 status = smbd_calculate_maximum_allowed_access(
2267 conn, smb_fname, use_privs, &access_mask);
2269 if (!NT_STATUS_IS_OK(status)) {
2273 access_mask &= conn->share_access;
2276 rejected_share_access = access_mask & ~(conn->share_access);
2278 if (rejected_share_access) {
2279 DEBUG(10, ("smbd_calculate_access_mask: Access denied on "
2280 "file %s: rejected by share access mask[0x%08X] "
2281 "orig[0x%08X] mapped[0x%08X] reject[0x%08X]\n",
2282 smb_fname_str_dbg(smb_fname),
2284 orig_access_mask, access_mask,
2285 rejected_share_access));
2286 return NT_STATUS_ACCESS_DENIED;
2289 *access_mask_out = access_mask;
2290 return NT_STATUS_OK;
2293 /****************************************************************************
2294 Remove the deferred open entry under lock.
2295 ****************************************************************************/
2297 /****************************************************************************
2298 Return true if this is a state pointer to an asynchronous create.
2299 ****************************************************************************/
2301 bool is_deferred_open_async(const struct deferred_open_record *rec)
2303 return rec->async_open;
2306 static bool clear_ads(uint32_t create_disposition)
2310 switch (create_disposition) {
2311 case FILE_SUPERSEDE:
2312 case FILE_OVERWRITE_IF:
2313 case FILE_OVERWRITE:
2322 static int disposition_to_open_flags(uint32_t create_disposition)
2327 * Currently we're using FILE_SUPERSEDE as the same as
2328 * FILE_OVERWRITE_IF but they really are
2329 * different. FILE_SUPERSEDE deletes an existing file
2330 * (requiring delete access) then recreates it.
2333 switch (create_disposition) {
2334 case FILE_SUPERSEDE:
2335 case FILE_OVERWRITE_IF:
2337 * If file exists replace/overwrite. If file doesn't
2340 ret = O_CREAT|O_TRUNC;
2345 * If file exists open. If file doesn't exist error.
2350 case FILE_OVERWRITE:
2352 * If file exists overwrite. If file doesn't exist
2360 * If file exists error. If file doesn't exist create.
2362 ret = O_CREAT|O_EXCL;
2367 * If file exists open. If file doesn't exist create.
2375 static int calculate_open_access_flags(uint32_t access_mask,
2376 uint32_t private_flags)
2378 bool need_write, need_read;
2381 * Note that we ignore the append flag as append does not
2382 * mean the same thing under DOS and Unix.
2385 need_write = (access_mask & (FILE_WRITE_DATA | FILE_APPEND_DATA));
2390 /* DENY_DOS opens are always underlying read-write on the
2391 file handle, no matter what the requested access mask
2395 ((private_flags & NTCREATEX_OPTIONS_PRIVATE_DENY_DOS) ||
2396 access_mask & (FILE_READ_ATTRIBUTES|FILE_READ_DATA|
2397 FILE_READ_EA|FILE_EXECUTE));
2405 /****************************************************************************
2406 Open a file with a share mode. Passed in an already created files_struct *.
2407 ****************************************************************************/
2409 static NTSTATUS open_file_ntcreate(connection_struct *conn,
2410 struct smb_request *req,
2411 uint32_t access_mask, /* access bits (FILE_READ_DATA etc.) */
2412 uint32_t share_access, /* share constants (FILE_SHARE_READ etc) */
2413 uint32_t create_disposition, /* FILE_OPEN_IF etc. */
2414 uint32_t create_options, /* options such as delete on close. */
2415 uint32_t new_dos_attributes, /* attributes used for new file. */
2416 int oplock_request, /* internal Samba oplock codes. */
2417 struct smb2_lease *lease,
2418 /* Information (FILE_EXISTS etc.) */
2419 uint32_t private_flags, /* Samba specific flags. */
2423 struct smb_filename *smb_fname = fsp->fsp_name;
2426 bool file_existed = VALID_STAT(smb_fname->st);
2427 bool def_acl = False;
2428 bool posix_open = False;
2429 bool new_file_created = False;
2430 bool first_open_attempt = true;
2431 NTSTATUS fsp_open = NT_STATUS_ACCESS_DENIED;
2432 mode_t new_unx_mode = (mode_t)0;
2433 mode_t unx_mode = (mode_t)0;
2435 uint32_t existing_dos_attributes = 0;
2436 struct timeval request_time = timeval_zero();
2437 struct share_mode_lock *lck = NULL;
2438 uint32_t open_access_mask = access_mask;
2441 SMB_STRUCT_STAT saved_stat = smb_fname->st;
2442 struct timespec old_write_time;
2445 if (conn->printer) {
2447 * Printers are handled completely differently.
2448 * Most of the passed parameters are ignored.
2452 *pinfo = FILE_WAS_CREATED;
2455 DEBUG(10, ("open_file_ntcreate: printer open fname=%s\n",
2456 smb_fname_str_dbg(smb_fname)));
2459 DEBUG(0,("open_file_ntcreate: printer open without "
2460 "an SMB request!\n"));
2461 return NT_STATUS_INTERNAL_ERROR;
2464 return print_spool_open(fsp, smb_fname->base_name,
2468 if (!parent_dirname(talloc_tos(), smb_fname->base_name, &parent_dir,
2470 return NT_STATUS_NO_MEMORY;
2473 if (new_dos_attributes & FILE_FLAG_POSIX_SEMANTICS) {
2475 unx_mode = (mode_t)(new_dos_attributes & ~FILE_FLAG_POSIX_SEMANTICS);
2476 new_dos_attributes = 0;
2478 /* Windows allows a new file to be created and
2479 silently removes a FILE_ATTRIBUTE_DIRECTORY
2480 sent by the client. Do the same. */
2482 new_dos_attributes &= ~FILE_ATTRIBUTE_DIRECTORY;
2484 /* We add FILE_ATTRIBUTE_ARCHIVE to this as this mode is only used if the file is
2486 unx_mode = unix_mode(conn, new_dos_attributes | FILE_ATTRIBUTE_ARCHIVE,
2487 smb_fname, parent_dir);
2490 DEBUG(10, ("open_file_ntcreate: fname=%s, dos_attrs=0x%x "
2491 "access_mask=0x%x share_access=0x%x "
2492 "create_disposition = 0x%x create_options=0x%x "
2493 "unix mode=0%o oplock_request=%d private_flags = 0x%x\n",
2494 smb_fname_str_dbg(smb_fname), new_dos_attributes,
2495 access_mask, share_access, create_disposition,
2496 create_options, (unsigned int)unx_mode, oplock_request,
2497 (unsigned int)private_flags));
2500 /* Ensure req == NULL means INTERNAL_OPEN_ONLY */
2501 SMB_ASSERT(((oplock_request & INTERNAL_OPEN_ONLY) != 0));
2503 /* And req != NULL means no INTERNAL_OPEN_ONLY */
2504 SMB_ASSERT(((oplock_request & INTERNAL_OPEN_ONLY) == 0));
2508 * Only non-internal opens can be deferred at all
2512 struct deferred_open_record *open_rec;
2513 if (get_deferred_open_message_state(req,
2516 /* Remember the absolute time of the original
2517 request with this mid. We'll use it later to
2518 see if this has timed out. */
2520 /* If it was an async create retry, the file
2523 if (is_deferred_open_async(open_rec)) {
2524 SET_STAT_INVALID(smb_fname->st);
2525 file_existed = false;
2528 /* Ensure we don't reprocess this message. */
2529 remove_deferred_open_message_smb(req->xconn, req->mid);
2531 first_open_attempt = false;
2536 new_dos_attributes &= SAMBA_ATTRIBUTES_MASK;
2538 existing_dos_attributes = dos_mode(conn, smb_fname);
2542 /* ignore any oplock requests if oplocks are disabled */
2543 if (!lp_oplocks(SNUM(conn)) ||
2544 IS_VETO_OPLOCK_PATH(conn, smb_fname->base_name)) {
2545 /* Mask off everything except the private Samba bits. */
2546 oplock_request &= SAMBA_PRIVATE_OPLOCK_MASK;
2549 /* this is for OS/2 long file names - say we don't support them */
2550 if (req != NULL && !req->posix_pathnames &&
2551 strstr(smb_fname->base_name,".+,;=[].")) {
2552 /* OS/2 Workplace shell fix may be main code stream in a later
2554 DEBUG(5,("open_file_ntcreate: OS/2 long filenames are not "
2556 if (use_nt_status()) {
2557 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
2559 return NT_STATUS_DOS(ERRDOS, ERRcannotopen);
2562 switch( create_disposition ) {
2564 /* If file exists open. If file doesn't exist error. */
2565 if (!file_existed) {
2566 DEBUG(5,("open_file_ntcreate: FILE_OPEN "
2567 "requested for file %s and file "
2569 smb_fname_str_dbg(smb_fname)));
2571 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
2575 case FILE_OVERWRITE:
2576 /* If file exists overwrite. If file doesn't exist
2578 if (!file_existed) {
2579 DEBUG(5,("open_file_ntcreate: FILE_OVERWRITE "
2580 "requested for file %s and file "
2582 smb_fname_str_dbg(smb_fname) ));
2584 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
2589 /* If file exists error. If file doesn't exist
2592 DEBUG(5,("open_file_ntcreate: FILE_CREATE "
2593 "requested for file %s and file "
2594 "already exists.\n",
2595 smb_fname_str_dbg(smb_fname)));
2596 if (S_ISDIR(smb_fname->st.st_ex_mode)) {
2601 return map_nt_error_from_unix(errno);
2605 case FILE_SUPERSEDE:
2606 case FILE_OVERWRITE_IF:
2610 return NT_STATUS_INVALID_PARAMETER;
2613 flags2 = disposition_to_open_flags(create_disposition);
2615 /* We only care about matching attributes on file exists and
2618 if (!posix_open && file_existed &&
2619 ((create_disposition == FILE_OVERWRITE) ||
2620 (create_disposition == FILE_OVERWRITE_IF))) {
2621 if (!open_match_attributes(conn, existing_dos_attributes,
2623 smb_fname->st.st_ex_mode,
2624 unx_mode, &new_unx_mode)) {
2625 DEBUG(5,("open_file_ntcreate: attributes missmatch "
2626 "for file %s (%x %x) (0%o, 0%o)\n",
2627 smb_fname_str_dbg(smb_fname),
2628 existing_dos_attributes,
2630 (unsigned int)smb_fname->st.st_ex_mode,
2631 (unsigned int)unx_mode ));
2633 return NT_STATUS_ACCESS_DENIED;
2637 status = smbd_calculate_access_mask(conn, smb_fname,
2641 if (!NT_STATUS_IS_OK(status)) {
2642 DEBUG(10, ("open_file_ntcreate: smbd_calculate_access_mask "
2643 "on file %s returned %s\n",
2644 smb_fname_str_dbg(smb_fname), nt_errstr(status)));
2648 open_access_mask = access_mask;
2650 if (flags2 & O_TRUNC) {
2651 open_access_mask |= FILE_WRITE_DATA; /* This will cause oplock breaks. */
2654 DEBUG(10, ("open_file_ntcreate: fname=%s, after mapping "
2655 "access_mask=0x%x\n", smb_fname_str_dbg(smb_fname),
2659 * Note that we ignore the append flag as append does not
2660 * mean the same thing under DOS and Unix.
2663 flags = calculate_open_access_flags(access_mask, private_flags);
2666 * Currently we only look at FILE_WRITE_THROUGH for create options.
2670 if ((create_options & FILE_WRITE_THROUGH) && lp_strict_sync(SNUM(conn))) {
2675 if (posix_open && (access_mask & FILE_APPEND_DATA)) {
2679 if (!posix_open && !CAN_WRITE(conn)) {
2681 * We should really return a permission denied error if either
2682 * O_CREAT or O_TRUNC are set, but for compatibility with
2683 * older versions of Samba we just AND them out.
2685 flags2 &= ~(O_CREAT|O_TRUNC);
2688 if (first_open_attempt && lp_kernel_oplocks(SNUM(conn))) {
2690 * With kernel oplocks the open breaking an oplock
2691 * blocks until the oplock holder has given up the
2692 * oplock or closed the file. We prevent this by first
2693 * trying to open the file with O_NONBLOCK (see "man
2694 * fcntl" on Linux). For the second try, triggered by
2695 * an oplock break response, we do not need this
2698 * This is true under the assumption that only Samba
2699 * requests kernel oplocks. Once someone else like
2700 * NFSv4 starts to use that API, we will have to
2701 * modify this by communicating with the NFSv4 server.
2703 flags2 |= O_NONBLOCK;
2707 * Ensure we can't write on a read-only share or file.
2710 if (flags != O_RDONLY && file_existed &&
2711 (!CAN_WRITE(conn) || IS_DOS_READONLY(existing_dos_attributes))) {
2712 DEBUG(5,("open_file_ntcreate: write access requested for "
2713 "file %s on read only %s\n",
2714 smb_fname_str_dbg(smb_fname),
2715 !CAN_WRITE(conn) ? "share" : "file" ));
2717 return NT_STATUS_ACCESS_DENIED;
2720 fsp->file_id = vfs_file_id_from_sbuf(conn, &smb_fname->st);
2721 fsp->share_access = share_access;
2722 fsp->fh->private_options = private_flags;
2723 fsp->access_mask = open_access_mask; /* We change this to the
2724 * requested access_mask after
2725 * the open is done. */
2727 fsp->posix_flags |= FSP_POSIX_FLAGS_ALL;
2730 if (timeval_is_zero(&request_time)) {
2731 request_time = fsp->open_time;
2735 * Ensure we pay attention to default ACLs on directories if required.
2738 if ((flags2 & O_CREAT) && lp_inherit_acls(SNUM(conn)) &&
2739 (def_acl = directory_has_default_acl(conn, parent_dir))) {
2740 unx_mode = (0777 & lp_create_mask(SNUM(conn)));
2743 DEBUG(4,("calling open_file with flags=0x%X flags2=0x%X mode=0%o, "
2744 "access_mask = 0x%x, open_access_mask = 0x%x\n",
2745 (unsigned int)flags, (unsigned int)flags2,
2746 (unsigned int)unx_mode, (unsigned int)access_mask,
2747 (unsigned int)open_access_mask));
2749 fsp_open = open_file(fsp, conn, req, parent_dir,
2750 flags|flags2, unx_mode, access_mask,
2751 open_access_mask, &new_file_created);
2753 if (NT_STATUS_EQUAL(fsp_open, NT_STATUS_NETWORK_BUSY)) {
2754 struct deferred_open_record state;
2757 * EWOULDBLOCK/EAGAIN maps to NETWORK_BUSY.
2759 if (file_existed && S_ISFIFO(fsp->fsp_name->st.st_ex_mode)) {
2760 DEBUG(10, ("FIFO busy\n"));
2761 return NT_STATUS_NETWORK_BUSY;
2764 DEBUG(10, ("Internal open busy\n"));
2765 return NT_STATUS_NETWORK_BUSY;
2769 * From here on we assume this is an oplock break triggered
2772 lck = get_existing_share_mode_lock(talloc_tos(), fsp->file_id);
2774 state.delayed_for_oplocks = false;
2775 state.async_open = false;
2776 state.id = fsp->file_id;
2777 defer_open(NULL, request_time, timeval_set(0, 0),
2779 DEBUG(10, ("No share mode lock found after "
2780 "EWOULDBLOCK, retrying sync\n"));
2781 return NT_STATUS_SHARING_VIOLATION;
2784 if (!validate_oplock_types(lck)) {
2785 smb_panic("validate_oplock_types failed");
2788 if (delay_for_oplock(fsp, 0, lease, lck, false,
2789 create_disposition, first_open_attempt)) {
2790 schedule_defer_open(lck, fsp->file_id, request_time,
2793 DEBUG(10, ("Sent oplock break request to kernel "
2794 "oplock holder\n"));
2795 return NT_STATUS_SHARING_VIOLATION;
2799 * No oplock from Samba around. Immediately retry with
2802 state.delayed_for_oplocks = false;
2803 state.async_open = false;
2804 state.id = fsp->file_id;
2805 defer_open(lck, request_time, timeval_set(0, 0), req, &state);
2807 DEBUG(10, ("No Samba oplock around after EWOULDBLOCK. "
2808 "Retrying sync\n"));
2809 return NT_STATUS_SHARING_VIOLATION;
2812 if (!NT_STATUS_IS_OK(fsp_open)) {
2813 if (NT_STATUS_EQUAL(fsp_open, NT_STATUS_RETRY)) {
2814 schedule_async_open(request_time, req);
2819 if (new_file_created) {
2821 * As we atomically create using O_CREAT|O_EXCL,
2822 * then if new_file_created is true, then
2823 * file_existed *MUST* have been false (even
2824 * if the file was previously detected as being
2827 file_existed = false;
2830 if (file_existed && !check_same_dev_ino(&saved_stat, &smb_fname->st)) {
2832 * The file did exist, but some other (local or NFS)
2833 * process either renamed/unlinked and re-created the
2834 * file with different dev/ino after we walked the path,
2835 * but before we did the open. We could retry the
2836 * open but it's a rare enough case it's easier to
2837 * just fail the open to prevent creating any problems
2838 * in the open file db having the wrong dev/ino key.
2841 DEBUG(1,("open_file_ntcreate: file %s - dev/ino mismatch. "
2842 "Old (dev=0x%llu, ino =0x%llu). "
2843 "New (dev=0x%llu, ino=0x%llu). Failing open "
2844 " with NT_STATUS_ACCESS_DENIED.\n",
2845 smb_fname_str_dbg(smb_fname),
2846 (unsigned long long)saved_stat.st_ex_dev,
2847 (unsigned long long)saved_stat.st_ex_ino,
2848 (unsigned long long)smb_fname->st.st_ex_dev,
2849 (unsigned long long)smb_fname->st.st_ex_ino));
2850 return NT_STATUS_ACCESS_DENIED;
2853 old_write_time = smb_fname->st.st_ex_mtime;
2856 * Deal with the race condition where two smbd's detect the
2857 * file doesn't exist and do the create at the same time. One
2858 * of them will win and set a share mode, the other (ie. this
2859 * one) should check if the requested share mode for this
2860 * create is allowed.
2864 * Now the file exists and fsp is successfully opened,
2865 * fsp->dev and fsp->inode are valid and should replace the
2866 * dev=0,inode=0 from a non existent file. Spotted by
2867 * Nadav Danieli <nadavd@exanet.com>. JRA.
2872 lck = get_share_mode_lock(talloc_tos(), id,
2874 smb_fname, &old_write_time);
2877 DEBUG(0, ("open_file_ntcreate: Could not get share "
2878 "mode lock for %s\n",
2879 smb_fname_str_dbg(smb_fname)));
2881 return NT_STATUS_SHARING_VIOLATION;
2884 /* Get the types we need to examine. */
2885 if (!validate_oplock_types(lck)) {
2886 smb_panic("validate_oplock_types failed");
2889 if (has_delete_on_close(lck, fsp->name_hash)) {
2892 return NT_STATUS_DELETE_PENDING;
2895 status = open_mode_check(conn, lck,
2896 access_mask, share_access);
2898 if (NT_STATUS_EQUAL(status, NT_STATUS_SHARING_VIOLATION) ||
2899 (lck->data->num_share_modes > 0)) {
2901 * This comes from ancient times out of open_mode_check. I
2902 * have no clue whether this is still necessary. I can't think
2903 * of a case where this would actually matter further down in
2904 * this function. I leave it here for further investigation
2907 file_existed = true;
2910 if ((req != NULL) &&
2912 fsp, oplock_request, lease, lck,
2913 NT_STATUS_EQUAL(status, NT_STATUS_SHARING_VIOLATION),
2914 create_disposition, first_open_attempt)) {
2915 schedule_defer_open(lck, fsp->file_id, request_time, req);
2918 return NT_STATUS_SHARING_VIOLATION;
2921 if (!NT_STATUS_IS_OK(status)) {
2922 uint32_t can_access_mask;
2923 bool can_access = True;
2925 SMB_ASSERT(NT_STATUS_EQUAL(status, NT_STATUS_SHARING_VIOLATION));
2927 /* Check if this can be done with the deny_dos and fcb
2930 (NTCREATEX_OPTIONS_PRIVATE_DENY_DOS|
2931 NTCREATEX_OPTIONS_PRIVATE_DENY_FCB)) {
2933 DEBUG(0, ("DOS open without an SMB "
2937 return NT_STATUS_INTERNAL_ERROR;
2940 /* Use the client requested access mask here,
2941 * not the one we open with. */
2942 status = fcb_or_dos_open(req,
2953 if (NT_STATUS_IS_OK(status)) {
2956 *pinfo = FILE_WAS_OPENED;
2958 return NT_STATUS_OK;
2963 * This next line is a subtlety we need for
2964 * MS-Access. If a file open will fail due to share
2965 * permissions and also for security (access) reasons,
2966 * we need to return the access failed error, not the
2967 * share error. We can't open the file due to kernel
2968 * oplock deadlock (it's possible we failed above on
2969 * the open_mode_check()) so use a userspace check.
2972 if (flags & O_RDWR) {
2973 can_access_mask = FILE_READ_DATA|FILE_WRITE_DATA;
2974 } else if (flags & O_WRONLY) {
2975 can_access_mask = FILE_WRITE_DATA;
2977 can_access_mask = FILE_READ_DATA;
2980 if (((can_access_mask & FILE_WRITE_DATA) &&
2981 !CAN_WRITE(conn)) ||
2982 !NT_STATUS_IS_OK(smbd_check_access_rights(conn,
2985 can_access_mask))) {
2990 * If we're returning a share violation, ensure we
2991 * cope with the braindead 1 second delay (SMB1 only).
2994 if (!(oplock_request & INTERNAL_OPEN_ONLY) &&
2995 !conn->sconn->using_smb2 &&
2996 lp_defer_sharing_violations()) {
2997 struct timeval timeout;
2998 struct deferred_open_record state;
3001 /* this is a hack to speed up torture tests
3003 timeout_usecs = lp_parm_int(SNUM(conn),
3004 "smbd","sharedelay",
3005 SHARING_VIOLATION_USEC_WAIT);
3007 /* This is a relative time, added to the absolute
3008 request_time value to get the absolute timeout time.
3009 Note that if this is the second or greater time we enter
3010 this codepath for this particular request mid then
3011 request_time is left as the absolute time of the *first*
3012 time this request mid was processed. This is what allows
3013 the request to eventually time out. */
3015 timeout = timeval_set(0, timeout_usecs);
3017 /* Nothing actually uses state.delayed_for_oplocks
3018 but it's handy to differentiate in debug messages
3019 between a 30 second delay due to oplock break, and
3020 a 1 second delay for share mode conflicts. */
3022 state.delayed_for_oplocks = False;
3023 state.async_open = false;
3027 && !request_timed_out(request_time,
3029 defer_open(lck, request_time, timeout,
3038 * We have detected a sharing violation here
3039 * so return the correct error code
3041 status = NT_STATUS_SHARING_VIOLATION;
3043 status = NT_STATUS_ACCESS_DENIED;
3048 /* Should we atomically (to the client at least) truncate ? */
3049 if ((!new_file_created) &&
3050 (flags2 & O_TRUNC) &&
3051 (!S_ISFIFO(fsp->fsp_name->st.st_ex_mode))) {
3054 ret = vfs_set_filelen(fsp, 0);
3056 status = map_nt_error_from_unix(errno);
3064 * We have the share entry *locked*.....
3067 /* Delete streams if create_disposition requires it */
3068 if (!new_file_created && clear_ads(create_disposition) &&
3069 !is_ntfs_stream_smb_fname(smb_fname)) {
3070 status = delete_all_streams(conn, smb_fname);
3071 if (!NT_STATUS_IS_OK(status)) {
3078 /* note that we ignore failure for the following. It is
3079 basically a hack for NFS, and NFS will never set one of
3080 these only read them. Nobody but Samba can ever set a deny
3081 mode and we have already checked our more authoritative
3082 locking database for permission to set this deny mode. If
3083 the kernel refuses the operations then the kernel is wrong.
3084 note that GPFS supports it as well - jmcd */
3086 if (fsp->fh->fd != -1 && lp_kernel_share_modes(SNUM(conn))) {
3089 * Beware: streams implementing VFS modules may
3090 * implement streams in a way that fsp will have the
3091 * basefile open in the fsp fd, so lacking a distinct
3092 * fd for the stream kernel_flock will apply on the
3093 * basefile which is wrong. The actual check is
3094 * deffered to the VFS module implementing the
3095 * kernel_flock call.
3097 ret_flock = SMB_VFS_KERNEL_FLOCK(fsp, share_access, access_mask);
3098 if(ret_flock == -1 ){
3103 return NT_STATUS_SHARING_VIOLATION;
3106 fsp->kernel_share_modes_taken = true;
3110 * At this point onwards, we can guarantee that the share entry
3111 * is locked, whether we created the file or not, and that the
3112 * deny mode is compatible with all current opens.
3116 * According to Samba4, SEC_FILE_READ_ATTRIBUTE is always granted,
3117 * but we don't have to store this - just ignore it on access check.
3119 if (conn->sconn->using_smb2) {
3121 * SMB2 doesn't return it (according to Microsoft tests).
3122 * Test Case: TestSuite_ScenarioNo009GrantedAccessTestS0
3123 * File created with access = 0x7 (Read, Write, Delete)
3124 * Query Info on file returns 0x87 (Read, Write, Delete, Read Attributes)
3126 fsp->access_mask = access_mask;
3128 /* But SMB1 does. */
3129 fsp->access_mask = access_mask | FILE_READ_ATTRIBUTES;
3134 * stat opens on existing files don't get oplocks.
3135 * They can get leases.
3137 * Note that we check for stat open on the *open_access_mask*,
3138 * i.e. the access mask we actually used to do the open,
3139 * not the one the client asked for (which is in
3140 * fsp->access_mask). This is due to the fact that
3141 * FILE_OVERWRITE and FILE_OVERWRITE_IF add in O_TRUNC,
3142 * which adds FILE_WRITE_DATA to open_access_mask.
3144 if (is_stat_open(open_access_mask) && lease == NULL) {
3145 oplock_request = NO_OPLOCK;
3149 if (new_file_created) {
3150 info = FILE_WAS_CREATED;
3152 if (flags2 & O_TRUNC) {
3153 info = FILE_WAS_OVERWRITTEN;
3155 info = FILE_WAS_OPENED;
3164 * Setup the oplock info in both the shared memory and
3167 status = grant_fsp_oplock_type(req, fsp, lck, oplock_request, lease);
3168 if (!NT_STATUS_IS_OK(status)) {
3174 /* Handle strange delete on close create semantics. */
3175 if (create_options & FILE_DELETE_ON_CLOSE) {
3177 status = can_set_delete_on_close(fsp, new_dos_attributes);
3179 if (!NT_STATUS_IS_OK(status)) {
3180 /* Remember to delete the mode we just added. */
3181 del_share_mode(lck, fsp);
3186 /* Note that here we set the *inital* delete on close flag,
3187 not the regular one. The magic gets handled in close. */
3188 fsp->initial_delete_on_close = True;
3191 if (info != FILE_WAS_OPENED) {
3192 /* Overwritten files should be initially set as archive */
3193 if ((info == FILE_WAS_OVERWRITTEN && lp_map_archive(SNUM(conn))) ||
3194 lp_store_dos_attributes(SNUM(conn))) {
3196 if (file_set_dosmode(conn, smb_fname,
3197 new_dos_attributes | FILE_ATTRIBUTE_ARCHIVE,
3198 parent_dir, true) == 0) {
3199 unx_mode = smb_fname->st.st_ex_mode;
3205 /* Determine sparse flag. */
3207 /* POSIX opens are sparse by default. */
3208 fsp->is_sparse = true;
3210 fsp->is_sparse = (file_existed &&
3211 (existing_dos_attributes & FILE_ATTRIBUTE_SPARSE));
3215 * Take care of inherited ACLs on created files - if default ACL not
3219 if (!posix_open && new_file_created && !def_acl) {
3221 int saved_errno = errno; /* We might get ENOSYS in the next
3224 if (SMB_VFS_FCHMOD_ACL(fsp, unx_mode) == -1 &&
3226 errno = saved_errno; /* Ignore ENOSYS */
3229 } else if (new_unx_mode) {
3233 /* Attributes need changing. File already existed. */
3236 int saved_errno = errno; /* We might get ENOSYS in the
3238 ret = SMB_VFS_FCHMOD_ACL(fsp, new_unx_mode);
3240 if (ret == -1 && errno == ENOSYS) {
3241 errno = saved_errno; /* Ignore ENOSYS */
3243 DEBUG(5, ("open_file_ntcreate: reset "
3244 "attributes of file %s to 0%o\n",
3245 smb_fname_str_dbg(smb_fname),
3246 (unsigned int)new_unx_mode));
3247 ret = 0; /* Don't do the fchmod below. */
3252 (SMB_VFS_FCHMOD(fsp, new_unx_mode) == -1))
3253 DEBUG(5, ("open_file_ntcreate: failed to reset "
3254 "attributes of file %s to 0%o\n",
3255 smb_fname_str_dbg(smb_fname),
3256 (unsigned int)new_unx_mode));
3261 * Deal with other opens having a modified write time.
3263 struct timespec write_time = get_share_mode_write_time(lck);
3265 if (!null_timespec(write_time)) {
3266 update_stat_ex_mtime(&fsp->fsp_name->st, write_time);
3272 return NT_STATUS_OK;
3275 static NTSTATUS mkdir_internal(connection_struct *conn,
3276 struct smb_filename *smb_dname,
3277 uint32_t file_attributes)
3280 char *parent_dir = NULL;
3282 bool posix_open = false;
3283 bool need_re_stat = false;
3284 uint32_t access_mask = SEC_DIR_ADD_SUBDIR;
3286 if (!CAN_WRITE(conn) || (access_mask & ~(conn->share_access))) {
3287 DEBUG(5,("mkdir_internal: failing share access "
3288 "%s\n", lp_servicename(talloc_tos(), SNUM(conn))));
3289 return NT_STATUS_ACCESS_DENIED;
3292 if (!parent_dirname(talloc_tos(), smb_dname->base_name, &parent_dir,
3294 return NT_STATUS_NO_MEMORY;
3297 if (file_attributes & FILE_FLAG_POSIX_SEMANTICS) {
3299 mode = (mode_t)(file_attributes & ~FILE_FLAG_POSIX_SEMANTICS);
3301 mode = unix_mode(conn, FILE_ATTRIBUTE_DIRECTORY, smb_dname, parent_dir);
3304 status = check_parent_access(conn,
3307 if(!NT_STATUS_IS_OK(status)) {
3308 DEBUG(5,("mkdir_internal: check_parent_access "
3309 "on directory %s for path %s returned %s\n",
3311 smb_dname->base_name,
3312 nt_errstr(status) ));
3316 if (SMB_VFS_MKDIR(conn, smb_dname, mode) != 0) {
3317 return map_nt_error_from_unix(errno);
3320 /* Ensure we're checking for a symlink here.... */
3321 /* We don't want to get caught by a symlink racer. */
3323 if (SMB_VFS_LSTAT(conn, smb_dname) == -1) {
3324 DEBUG(2, ("Could not stat directory '%s' just created: %s\n",
3325 smb_fname_str_dbg(smb_dname), strerror(errno)));
3326 return map_nt_error_from_unix(errno);
3329 if (!S_ISDIR(smb_dname->st.st_ex_mode)) {
3330 DEBUG(0, ("Directory '%s' just created is not a directory !\n",
3331 smb_fname_str_dbg(smb_dname)));
3332 return NT_STATUS_NOT_A_DIRECTORY;
3335 if (lp_store_dos_attributes(SNUM(conn))) {
3337 file_set_dosmode(conn, smb_dname,
3338 file_attributes | FILE_ATTRIBUTE_DIRECTORY,
3343 if (lp_inherit_permissions(SNUM(conn))) {
3344 inherit_access_posix_acl(conn, parent_dir,
3345 smb_dname->base_name, mode);
3346 need_re_stat = true;
3351 * Check if high bits should have been set,
3352 * then (if bits are missing): add them.
3353 * Consider bits automagically set by UNIX, i.e. SGID bit from parent
3356 if ((mode & ~(S_IRWXU|S_IRWXG|S_IRWXO)) &&
3357 (mode & ~smb_dname->st.st_ex_mode)) {
3358 SMB_VFS_CHMOD(conn, smb_dname,
3359 (smb_dname->st.st_ex_mode |
3360 (mode & ~smb_dname->st.st_ex_mode)));
3361 need_re_stat = true;
3365 /* Change the owner if required. */
3366 if (lp_inherit_owner(SNUM(conn))) {
3367 change_dir_owner_to_parent(conn, parent_dir,
3368 smb_dname->base_name,
3370 need_re_stat = true;
3374 if (SMB_VFS_LSTAT(conn, smb_dname) == -1) {
3375 DEBUG(2, ("Could not stat directory '%s' just created: %s\n",
3376 smb_fname_str_dbg(smb_dname), strerror(errno)));
3377 return map_nt_error_from_unix(errno);
3381 notify_fname(conn, NOTIFY_ACTION_ADDED, FILE_NOTIFY_CHANGE_DIR_NAME,
3382 smb_dname->base_name);
3384 return NT_STATUS_OK;
3387 /****************************************************************************
3388 Open a directory from an NT SMB call.
3389 ****************************************************************************/
3391 static NTSTATUS open_directory(connection_struct *conn,
3392 struct smb_request *req,
3393 struct smb_filename *smb_dname,
3394 uint32_t access_mask,
3395 uint32_t share_access,
3396 uint32_t create_disposition,
3397 uint32_t create_options,
3398 uint32_t file_attributes,
3400 files_struct **result)
3402 files_struct *fsp = NULL;
3403 bool dir_existed = VALID_STAT(smb_dname->st) ? True : False;
3404 struct share_mode_lock *lck = NULL;
3406 struct timespec mtimespec;
3410 if (is_ntfs_stream_smb_fname(smb_dname)) {
3411 DEBUG(2, ("open_directory: %s is a stream name!\n",
3412 smb_fname_str_dbg(smb_dname)));
3413 return NT_STATUS_NOT_A_DIRECTORY;
3416 if (!(file_attributes & FILE_FLAG_POSIX_SEMANTICS)) {
3417 /* Ensure we have a directory attribute. */
3418 file_attributes |= FILE_ATTRIBUTE_DIRECTORY;
3421 DEBUG(5,("open_directory: opening directory %s, access_mask = 0x%x, "
3422 "share_access = 0x%x create_options = 0x%x, "
3423 "create_disposition = 0x%x, file_attributes = 0x%x\n",
3424 smb_fname_str_dbg(smb_dname),
3425 (unsigned int)access_mask,
3426 (unsigned int)share_access,
3427 (unsigned int)create_options,
3428 (unsigned int)create_disposition,
3429 (unsigned int)file_attributes));
3431 status = smbd_calculate_access_mask(conn, smb_dname, false,
3432 access_mask, &access_mask);
3433 if (!NT_STATUS_IS_OK(status)) {
3434 DEBUG(10, ("open_directory: smbd_calculate_access_mask "
3435 "on file %s returned %s\n",
3436 smb_fname_str_dbg(smb_dname),
3437 nt_errstr(status)));
3441 if ((access_mask & SEC_FLAG_SYSTEM_SECURITY) &&
3442 !security_token_has_privilege(get_current_nttok(conn),
3443 SEC_PRIV_SECURITY)) {
3444 DEBUG(10, ("open_directory: open on %s "
3445 "failed - SEC_FLAG_SYSTEM_SECURITY denied.\n",
3446 smb_fname_str_dbg(smb_dname)));
3447 return NT_STATUS_PRIVILEGE_NOT_HELD;
3450 switch( create_disposition ) {
3454 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3457 info = FILE_WAS_OPENED;
3462 /* If directory exists error. If directory doesn't
3466 status = NT_STATUS_OBJECT_NAME_COLLISION;
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 status = mkdir_internal(conn, smb_dname,
3477 if (!NT_STATUS_IS_OK(status)) {
3478 DEBUG(2, ("open_directory: unable to create "
3479 "%s. Error was %s\n",
3480 smb_fname_str_dbg(smb_dname),
3481 nt_errstr(status)));
3485 info = FILE_WAS_CREATED;
3490 * If directory exists open. If directory doesn't
3495 status = NT_STATUS_OK;
3496 info = FILE_WAS_OPENED;
3498 status = mkdir_internal(conn, smb_dname,
3501 if (NT_STATUS_IS_OK(status)) {
3502 info = FILE_WAS_CREATED;
3504 /* Cope with create race. */
3505 if (!NT_STATUS_EQUAL(status,
3506 NT_STATUS_OBJECT_NAME_COLLISION)) {
3507 DEBUG(2, ("open_directory: unable to create "
3508 "%s. Error was %s\n",
3509 smb_fname_str_dbg(smb_dname),
3510 nt_errstr(status)));
3515 * If mkdir_internal() returned
3516 * NT_STATUS_OBJECT_NAME_COLLISION
3517 * we still must lstat the path.
3520 if (SMB_VFS_LSTAT(conn, smb_dname)
3522 DEBUG(2, ("Could not stat "
3523 "directory '%s' just "
3528 return map_nt_error_from_unix(
3532 info = FILE_WAS_OPENED;
3538 case FILE_SUPERSEDE:
3539 case FILE_OVERWRITE:
3540 case FILE_OVERWRITE_IF:
3542 DEBUG(5,("open_directory: invalid create_disposition "
3543 "0x%x for directory %s\n",
3544 (unsigned int)create_disposition,
3545 smb_fname_str_dbg(smb_dname)));
3546 return NT_STATUS_INVALID_PARAMETER;
3549 if(!S_ISDIR(smb_dname->st.st_ex_mode)) {
3550 DEBUG(5,("open_directory: %s is not a directory !\n",
3551 smb_fname_str_dbg(smb_dname)));
3552 return NT_STATUS_NOT_A_DIRECTORY;
3555 if (info == FILE_WAS_OPENED) {
3556 status = smbd_check_access_rights(conn,
3560 if (!NT_STATUS_IS_OK(status)) {
3561 DEBUG(10, ("open_directory: smbd_check_access_rights on "
3562 "file %s failed with %s\n",
3563 smb_fname_str_dbg(smb_dname),
3564 nt_errstr(status)));
3569 status = file_new(req, conn, &fsp);
3570 if(!NT_STATUS_IS_OK(status)) {
3575 * Setup the files_struct for it.
3578 fsp->file_id = vfs_file_id_from_sbuf(conn, &smb_dname->st);
3579 fsp->vuid = req ? req->vuid : UID_FIELD_INVALID;
3580 fsp->file_pid = req ? req->smbpid : 0;
3581 fsp->can_lock = False;
3582 fsp->can_read = False;
3583 fsp->can_write = False;
3585 fsp->share_access = share_access;
3586 fsp->fh->private_options = 0;
3588 * According to Samba4, SEC_FILE_READ_ATTRIBUTE is always granted,
3590 fsp->access_mask = access_mask | FILE_READ_ATTRIBUTES;
3591 fsp->print_file = NULL;
3592 fsp->modified = False;
3593 fsp->oplock_type = NO_OPLOCK;
3594 fsp->sent_oplock_break = NO_BREAK_SENT;
3595 fsp->is_directory = True;
3596 if (file_attributes & FILE_FLAG_POSIX_SEMANTICS) {
3597 fsp->posix_flags |= FSP_POSIX_FLAGS_ALL;
3599 status = fsp_set_smb_fname(fsp, smb_dname);
3600 if (!NT_STATUS_IS_OK(status)) {
3601 file_free(req, fsp);
3605 /* Don't store old timestamps for directory
3606 handles in the internal database. We don't
3607 update them in there if new objects
3608 are creaded in the directory. Currently
3609 we only update timestamps on file writes.
3612 ZERO_STRUCT(mtimespec);
3614 if (access_mask & (FILE_LIST_DIRECTORY|
3616 FILE_ADD_SUBDIRECTORY|
3619 FILE_DELETE_CHILD)) {
3621 status = fd_open(conn, fsp, O_RDONLY|O_DIRECTORY, 0);
3623 /* POSIX allows us to open a directory with O_RDONLY. */
3624 status = fd_open(conn, fsp, O_RDONLY, 0);
3626 if (!NT_STATUS_IS_OK(status)) {
3627 DEBUG(5, ("open_directory: Could not open fd for "
3629 smb_fname_str_dbg(smb_dname),
3630 nt_errstr(status)));
3631 file_free(req, fsp);
3636 DEBUG(10, ("Not opening Directory %s\n",
3637 smb_fname_str_dbg(smb_dname)));
3640 status = vfs_stat_fsp(fsp);
3641 if (!NT_STATUS_IS_OK(status)) {
3643 file_free(req, fsp);
3647 if(!S_ISDIR(fsp->fsp_name->st.st_ex_mode)) {
3648 DEBUG(5,("open_directory: %s is not a directory !\n",
3649 smb_fname_str_dbg(smb_dname)));
3651 file_free(req, fsp);
3652 return NT_STATUS_NOT_A_DIRECTORY;
3655 /* Ensure there was no race condition. We need to check
3656 * dev/inode but not permissions, as these can change
3658 if (!check_same_dev_ino(&smb_dname->st, &fsp->fsp_name->st)) {
3659 DEBUG(5,("open_directory: stat struct differs for "
3661 smb_fname_str_dbg(smb_dname)));
3663 file_free(req, fsp);
3664 return NT_STATUS_ACCESS_DENIED;
3667 lck = get_share_mode_lock(talloc_tos(), fsp->file_id,
3668 conn->connectpath, smb_dname,
3672 DEBUG(0, ("open_directory: Could not get share mode lock for "
3673 "%s\n", smb_fname_str_dbg(smb_dname)));
3675 file_free(req, fsp);
3676 return NT_STATUS_SHARING_VIOLATION;
3679 if (has_delete_on_close(lck, fsp->name_hash)) {
3682 file_free(req, fsp);
3683 return NT_STATUS_DELETE_PENDING;
3686 status = open_mode_check(conn, lck,
3687 access_mask, share_access);
3689 if (!NT_STATUS_IS_OK(status)) {
3692 file_free(req, fsp);
3696 ok = set_share_mode(lck, fsp, get_current_uid(conn),
3697 req ? req->mid : 0, NO_OPLOCK,
3702 file_free(req, fsp);
3703 return NT_STATUS_NO_MEMORY;
3706 /* For directories the delete on close bit at open time seems
3707 always to be honored on close... See test 19 in Samba4 BASE-DELETE. */
3708 if (create_options & FILE_DELETE_ON_CLOSE) {
3709 status = can_set_delete_on_close(fsp, 0);
3710 if (!NT_STATUS_IS_OK(status) && !NT_STATUS_EQUAL(status, NT_STATUS_DIRECTORY_NOT_EMPTY)) {
3711 del_share_mode(lck, fsp);
3714 file_free(req, fsp);
3718 if (NT_STATUS_IS_OK(status)) {
3719 /* Note that here we set the *inital* delete on close flag,
3720 not the regular one. The magic gets handled in close. */
3721 fsp->initial_delete_on_close = True;
3727 * Deal with other opens having a modified write time. Is this
3728 * possible for directories?
3730 struct timespec write_time = get_share_mode_write_time(lck);
3732 if (!null_timespec(write_time)) {
3733 update_stat_ex_mtime(&fsp->fsp_name->st, write_time);
3744 return NT_STATUS_OK;
3747 NTSTATUS create_directory(connection_struct *conn, struct smb_request *req,
3748 struct smb_filename *smb_dname)
3753 status = SMB_VFS_CREATE_FILE(
3756 0, /* root_dir_fid */
3757 smb_dname, /* fname */
3758 FILE_READ_ATTRIBUTES, /* access_mask */
3759 FILE_SHARE_NONE, /* share_access */
3760 FILE_CREATE, /* create_disposition*/
3761 FILE_DIRECTORY_FILE, /* create_options */
3762 FILE_ATTRIBUTE_DIRECTORY, /* file_attributes */
3763 0, /* oplock_request */
3765 0, /* allocation_size */
3766 0, /* private_flags */
3771 NULL, NULL); /* create context */
3773 if (NT_STATUS_IS_OK(status)) {
3774 close_file(req, fsp, NORMAL_CLOSE);
3780 /****************************************************************************
3781 Receive notification that one of our open files has been renamed by another
3783 ****************************************************************************/
3785 void msg_file_was_renamed(struct messaging_context *msg,
3788 struct server_id server_id,
3792 char *frm = (char *)data->data;
3794 const char *sharepath;
3795 const char *base_name;
3796 const char *stream_name;
3797 struct smb_filename *smb_fname = NULL;
3798 size_t sp_len, bn_len;
3800 struct smbd_server_connection *sconn =
3801 talloc_get_type_abort(private_data,
3802 struct smbd_server_connection);
3804 if (data->data == NULL
3805 || data->length < MSG_FILE_RENAMED_MIN_SIZE + 2) {
3806 DEBUG(0, ("msg_file_was_renamed: Got invalid msg len %d\n",
3807 (int)data->length));
3811 /* Unpack the message. */
3812 pull_file_id_24(frm, &id);
3813 sharepath = &frm[24];
3814 sp_len = strlen(sharepath);
3815 base_name = sharepath + sp_len + 1;
3816 bn_len = strlen(base_name);
3817 stream_name = sharepath + sp_len + 1 + bn_len + 1;
3819 /* stream_name must always be NULL if there is no stream. */
3820 if (stream_name[0] == '\0') {
3824 smb_fname = synthetic_smb_fname(talloc_tos(),
3829 if (smb_fname == NULL) {
3833 DEBUG(10,("msg_file_was_renamed: Got rename message for sharepath %s, new name %s, "
3835 sharepath, smb_fname_str_dbg(smb_fname),
3836 file_id_string_tos(&id)));
3838 for(fsp = file_find_di_first(sconn, id); fsp;
3839 fsp = file_find_di_next(fsp)) {
3840 if (memcmp(fsp->conn->connectpath, sharepath, sp_len) == 0) {
3842 DEBUG(10,("msg_file_was_renamed: renaming file %s from %s -> %s\n",
3843 fsp_fnum_dbg(fsp), fsp_str_dbg(fsp),
3844 smb_fname_str_dbg(smb_fname)));
3845 status = fsp_set_smb_fname(fsp, smb_fname);
3846 if (!NT_STATUS_IS_OK(status)) {
3851 /* Now we have the complete path we can work out if this is
3852 actually within this share and adjust newname accordingly. */
3853 DEBUG(10,("msg_file_was_renamed: share mismatch (sharepath %s "
3854 "not sharepath %s) "
3855 "%s from %s -> %s\n",
3856 fsp->conn->connectpath,
3860 smb_fname_str_dbg(smb_fname)));
3864 TALLOC_FREE(smb_fname);
3869 * If a main file is opened for delete, all streams need to be checked for
3870 * !FILE_SHARE_DELETE. Do this by opening with DELETE_ACCESS.
3871 * If that works, delete them all by setting the delete on close and close.
3874 static NTSTATUS open_streams_for_delete(connection_struct *conn,
3875 const struct smb_filename *smb_fname)
3877 struct stream_struct *stream_info = NULL;
3878 files_struct **streams = NULL;
3880 unsigned int num_streams = 0;
3881 TALLOC_CTX *frame = talloc_stackframe();
3884 status = vfs_streaminfo(conn, NULL, smb_fname, talloc_tos(),
3885 &num_streams, &stream_info);
3887 if (NT_STATUS_EQUAL(status, NT_STATUS_NOT_IMPLEMENTED)
3888 || NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
3889 DEBUG(10, ("no streams around\n"));
3891 return NT_STATUS_OK;
3894 if (!NT_STATUS_IS_OK(status)) {
3895 DEBUG(10, ("vfs_streaminfo failed: %s\n",
3896 nt_errstr(status)));
3900 DEBUG(10, ("open_streams_for_delete found %d streams\n",
3903 if (num_streams == 0) {
3905 return NT_STATUS_OK;
3908 streams = talloc_array(talloc_tos(), files_struct *, num_streams);
3909 if (streams == NULL) {
3910 DEBUG(0, ("talloc failed\n"));
3911 status = NT_STATUS_NO_MEMORY;
3915 for (i=0; i<num_streams; i++) {
3916 struct smb_filename *smb_fname_cp;
3918 if (strequal(stream_info[i].name, "::$DATA")) {
3923 smb_fname_cp = synthetic_smb_fname(talloc_tos(),
3924 smb_fname->base_name,
3925 stream_info[i].name,
3928 if (smb_fname_cp == NULL) {
3929 status = NT_STATUS_NO_MEMORY;
3933 if (SMB_VFS_STAT(conn, smb_fname_cp) == -1) {
3934 DEBUG(10, ("Unable to stat stream: %s\n",
3935 smb_fname_str_dbg(smb_fname_cp)));
3938 status = SMB_VFS_CREATE_FILE(
3941 0, /* root_dir_fid */
3942 smb_fname_cp, /* fname */
3943 DELETE_ACCESS, /* access_mask */
3944 (FILE_SHARE_READ | /* share_access */
3945 FILE_SHARE_WRITE | FILE_SHARE_DELETE),
3946 FILE_OPEN, /* create_disposition*/
3947 0, /* create_options */
3948 FILE_ATTRIBUTE_NORMAL, /* file_attributes */
3949 0, /* oplock_request */
3951 0, /* allocation_size */
3952 NTCREATEX_OPTIONS_PRIVATE_STREAM_DELETE, /* private_flags */
3955 &streams[i], /* result */
3957 NULL, NULL); /* create context */
3959 if (!NT_STATUS_IS_OK(status)) {
3960 DEBUG(10, ("Could not open stream %s: %s\n",
3961 smb_fname_str_dbg(smb_fname_cp),
3962 nt_errstr(status)));
3964 TALLOC_FREE(smb_fname_cp);
3967 TALLOC_FREE(smb_fname_cp);
3971 * don't touch the variable "status" beyond this point :-)
3974 for (i -= 1 ; i >= 0; i--) {
3975 if (streams[i] == NULL) {
3979 DEBUG(10, ("Closing stream # %d, %s\n", i,
3980 fsp_str_dbg(streams[i])));
3981 close_file(NULL, streams[i], NORMAL_CLOSE);
3989 /*********************************************************************
3990 Create a default ACL by inheriting from the parent. If no inheritance
3991 from the parent available, don't set anything. This will leave the actual
3992 permissions the new file or directory already got from the filesystem
3993 as the NT ACL when read.
3994 *********************************************************************/
3996 static NTSTATUS inherit_new_acl(files_struct *fsp)
3998 TALLOC_CTX *frame = talloc_stackframe();
3999 char *parent_name = NULL;
4000 struct security_descriptor *parent_desc = NULL;
4001 NTSTATUS status = NT_STATUS_OK;
4002 struct security_descriptor *psd = NULL;
4003 const struct dom_sid *owner_sid = NULL;
4004 const struct dom_sid *group_sid = NULL;
4005 uint32_t security_info_sent = (SECINFO_OWNER | SECINFO_GROUP | SECINFO_DACL);
4006 struct security_token *token = fsp->conn->session_info->security_token;
4007 bool inherit_owner = lp_inherit_owner(SNUM(fsp->conn));
4008 bool inheritable_components = false;
4009 bool try_builtin_administrators = false;
4010 const struct dom_sid *BA_U_sid = NULL;
4011 const struct dom_sid *BA_G_sid = NULL;
4012 bool try_system = false;
4013 const struct dom_sid *SY_U_sid = NULL;
4014 const struct dom_sid *SY_G_sid = NULL;
4016 struct smb_filename *parent_smb_fname = NULL;
4018 if (!parent_dirname(frame, fsp->fsp_name->base_name, &parent_name, NULL)) {
4020 return NT_STATUS_NO_MEMORY;
4022 parent_smb_fname = synthetic_smb_fname(talloc_tos(),
4026 fsp->fsp_name->flags);
4028 if (parent_smb_fname == NULL) {
4030 return NT_STATUS_NO_MEMORY;
4033 status = SMB_VFS_GET_NT_ACL(fsp->conn,
4035 (SECINFO_OWNER | SECINFO_GROUP | SECINFO_DACL),
4038 if (!NT_STATUS_IS_OK(status)) {
4043 inheritable_components = sd_has_inheritable_components(parent_desc,
4046 if (!inheritable_components && !inherit_owner) {
4048 /* Nothing to inherit and not setting owner. */
4049 return NT_STATUS_OK;
4052 /* Create an inherited descriptor from the parent. */
4054 if (DEBUGLEVEL >= 10) {
4055 DEBUG(10,("inherit_new_acl: parent acl for %s is:\n",
4056 fsp_str_dbg(fsp) ));
4057 NDR_PRINT_DEBUG(security_descriptor, parent_desc);
4060 /* Inherit from parent descriptor if "inherit owner" set. */
4061 if (inherit_owner) {
4062 owner_sid = parent_desc->owner_sid;
4063 group_sid = parent_desc->group_sid;
4066 if (owner_sid == NULL) {
4067 if (security_token_has_builtin_administrators(token)) {
4068 try_builtin_administrators = true;
4069 } else if (security_token_is_system(token)) {
4070 try_builtin_administrators = true;
4075 if (group_sid == NULL &&
4076 token->num_sids == PRIMARY_GROUP_SID_INDEX)
4078 if (security_token_is_system(token)) {
4079 try_builtin_administrators = true;
4084 if (try_builtin_administrators) {
4089 ok = sids_to_unixids(&global_sid_Builtin_Administrators, 1, &ids);
4093 BA_U_sid = &global_sid_Builtin_Administrators;
4094 BA_G_sid = &global_sid_Builtin_Administrators;
4097 BA_U_sid = &global_sid_Builtin_Administrators;
4100 BA_G_sid = &global_sid_Builtin_Administrators;
4113 ok = sids_to_unixids(&global_sid_System, 1, &ids);
4117 SY_U_sid = &global_sid_System;
4118 SY_G_sid = &global_sid_System;
4121 SY_U_sid = &global_sid_System;
4124 SY_G_sid = &global_sid_System;
4132 if (owner_sid == NULL) {
4133 owner_sid = BA_U_sid;
4136 if (owner_sid == NULL) {
4137 owner_sid = SY_U_sid;
4140 if (group_sid == NULL) {
4141 group_sid = SY_G_sid;
4144 if (try_system && group_sid == NULL) {
4145 group_sid = BA_G_sid;
4148 if (owner_sid == NULL) {
4149 owner_sid = &token->sids[PRIMARY_USER_SID_INDEX];
4151 if (group_sid == NULL) {
4152 if (token->num_sids == PRIMARY_GROUP_SID_INDEX) {
4153 group_sid = &token->sids[PRIMARY_USER_SID_INDEX];
4155 group_sid = &token->sids[PRIMARY_GROUP_SID_INDEX];
4159 status = se_create_child_secdesc(frame,
4166 if (!NT_STATUS_IS_OK(status)) {
4171 /* If inheritable_components == false,
4172 se_create_child_secdesc()
4173 creates a security desriptor with a NULL dacl
4174 entry, but with SEC_DESC_DACL_PRESENT. We need
4175 to remove that flag. */
4177 if (!inheritable_components) {
4178 security_info_sent &= ~SECINFO_DACL;
4179 psd->type &= ~SEC_DESC_DACL_PRESENT;
4182 if (DEBUGLEVEL >= 10) {
4183 DEBUG(10,("inherit_new_acl: child acl for %s is:\n",
4184 fsp_str_dbg(fsp) ));
4185 NDR_PRINT_DEBUG(security_descriptor, psd);
4188 if (inherit_owner) {
4189 /* We need to be root to force this. */
4192 status = SMB_VFS_FSET_NT_ACL(fsp,
4195 if (inherit_owner) {
4203 * If we already have a lease, it must match the new file id. [MS-SMB2]
4204 * 3.3.5.9.8 speaks about INVALID_PARAMETER if an already used lease key is
4205 * used for a different file name.
4208 struct lease_match_state {
4209 /* Input parameters. */
4210 TALLOC_CTX *mem_ctx;
4211 const char *servicepath;
4212 const struct smb_filename *fname;
4215 /* Return parameters. */
4216 uint32_t num_file_ids;
4217 struct file_id *ids;
4218 NTSTATUS match_status;
4221 /*************************************************************
4222 File doesn't exist but this lease key+guid is already in use.
4224 This is only allowable in the dynamic share case where the
4225 service path must be different.
4227 There is a small race condition here in the multi-connection
4228 case where a client sends two create calls on different connections,
4229 where the file doesn't exist and one smbd creates the leases_db
4230 entry first, but this will get fixed by the multichannel cleanup
4231 when all identical client_guids get handled by a single smbd.
4232 **************************************************************/
4234 static void lease_match_parser_new_file(
4236 const struct leases_db_file *files,
4237 struct lease_match_state *state)
4241 for (i = 0; i < num_files; i++) {
4242 const struct leases_db_file *f = &files[i];
4243 if (strequal(state->servicepath, f->servicepath)) {
4244 state->match_status = NT_STATUS_INVALID_PARAMETER;
4249 /* Dynamic share case. Break leases on all other files. */
4250 state->match_status = leases_db_copy_file_ids(state->mem_ctx,
4254 if (!NT_STATUS_IS_OK(state->match_status)) {
4258 state->num_file_ids = num_files;
4259 state->match_status = NT_STATUS_OPLOCK_NOT_GRANTED;
4263 static void lease_match_parser(
4265 const struct leases_db_file *files,
4268 struct lease_match_state *state =
4269 (struct lease_match_state *)private_data;
4272 if (!state->file_existed) {
4274 * Deal with name mismatch or
4275 * possible dynamic share case separately
4276 * to make code clearer.
4278 lease_match_parser_new_file(num_files,
4285 state->match_status = NT_STATUS_OK;
4287 for (i = 0; i < num_files; i++) {
4288 const struct leases_db_file *f = &files[i];
4290 /* Everything should be the same. */
4291 if (!file_id_equal(&state->id, &f->id)) {
4292 /* This should catch all dynamic share cases. */
4293 state->match_status = NT_STATUS_OPLOCK_NOT_GRANTED;
4296 if (!strequal(f->servicepath, state->servicepath)) {
4297 state->match_status = NT_STATUS_INVALID_PARAMETER;
4300 if (!strequal(f->base_name, state->fname->base_name)) {
4301 state->match_status = NT_STATUS_INVALID_PARAMETER;
4304 if (!strequal(f->stream_name, state->fname->stream_name)) {
4305 state->match_status = NT_STATUS_INVALID_PARAMETER;
4310 if (NT_STATUS_IS_OK(state->match_status)) {
4312 * Common case - just opening another handle on a
4313 * file on a non-dynamic share.
4318 if (NT_STATUS_EQUAL(state->match_status, NT_STATUS_INVALID_PARAMETER)) {
4319 /* Mismatched path. Error back to client. */
4324 * File id mismatch. Dynamic share case NT_STATUS_OPLOCK_NOT_GRANTED.
4325 * Don't allow leases.
4328 state->match_status = leases_db_copy_file_ids(state->mem_ctx,
4332 if (!NT_STATUS_IS_OK(state->match_status)) {
4336 state->num_file_ids = num_files;
4337 state->match_status = NT_STATUS_OPLOCK_NOT_GRANTED;
4341 static NTSTATUS lease_match(connection_struct *conn,
4342 struct smb_request *req,
4343 struct smb2_lease_key *lease_key,
4344 const char *servicepath,
4345 const struct smb_filename *fname,
4346 uint16_t *p_version,
4349 struct smbd_server_connection *sconn = req->sconn;
4350 TALLOC_CTX *tos = talloc_tos();
4351 struct lease_match_state state = {
4353 .servicepath = servicepath,
4355 .match_status = NT_STATUS_OK
4360 state.file_existed = VALID_STAT(fname->st);
4361 if (state.file_existed) {
4362 state.id = vfs_file_id_from_sbuf(conn, &fname->st);
4364 memset(&state.id, '\0', sizeof(state.id));
4367 status = leases_db_parse(&sconn->client->connections->smb2.client.guid,
4368 lease_key, lease_match_parser, &state);
4369 if (!NT_STATUS_IS_OK(status)) {
4371 * Not found or error means okay: We can make the lease pass
4373 return NT_STATUS_OK;
4375 if (!NT_STATUS_EQUAL(state.match_status, NT_STATUS_OPLOCK_NOT_GRANTED)) {
4377 * Anything but NT_STATUS_OPLOCK_NOT_GRANTED, let the caller
4380 return state.match_status;
4383 /* We have to break all existing leases. */
4384 for (i = 0; i < state.num_file_ids; i++) {
4385 struct share_mode_lock *lck;
4386 struct share_mode_data *d;
4389 if (file_id_equal(&state.ids[i], &state.id)) {
4390 /* Don't need to break our own file. */
4394 lck = get_existing_share_mode_lock(talloc_tos(), state.ids[i]);
4396 /* Race condition - file already closed. */
4400 for (j=0; j<d->num_share_modes; j++) {
4401 struct share_mode_entry *e = &d->share_modes[j];
4402 uint32_t e_lease_type = get_lease_type(d, e);
4403 struct share_mode_lease *l = NULL;
4405 if (share_mode_stale_pid(d, j)) {
4409 if (e->op_type == LEASE_OPLOCK) {
4410 l = &lck->data->leases[e->lease_idx];
4411 if (!smb2_lease_key_equal(&l->lease_key,
4415 *p_epoch = l->epoch;
4416 *p_version = l->lease_version;
4419 if (e_lease_type == SMB2_LEASE_NONE) {
4423 send_break_message(conn->sconn->msg_ctx, e,
4427 * Windows 7 and 8 lease clients
4428 * are broken in that they will not
4429 * respond to lease break requests
4430 * whilst waiting for an outstanding
4431 * open request on that lease handle
4432 * on the same TCP connection, due
4433 * to holding an internal inode lock.
4435 * This means we can't reschedule
4436 * ourselves here, but must return
4441 * Send the breaks and then return
4442 * SMB2_LEASE_NONE in the lease handle
4443 * to cause them to acknowledge the
4444 * lease break. Consulatation with
4445 * Microsoft engineering confirmed
4446 * this approach is safe.
4453 * Ensure we don't grant anything more so we
4456 return NT_STATUS_OPLOCK_NOT_GRANTED;
4460 * Wrapper around open_file_ntcreate and open_directory
4463 static NTSTATUS create_file_unixpath(connection_struct *conn,
4464 struct smb_request *req,
4465 struct smb_filename *smb_fname,
4466 uint32_t access_mask,
4467 uint32_t share_access,
4468 uint32_t create_disposition,
4469 uint32_t create_options,
4470 uint32_t file_attributes,
4471 uint32_t oplock_request,
4472 struct smb2_lease *lease,
4473 uint64_t allocation_size,
4474 uint32_t private_flags,
4475 struct security_descriptor *sd,
4476 struct ea_list *ea_list,
4478 files_struct **result,
4481 int info = FILE_WAS_OPENED;
4482 files_struct *base_fsp = NULL;
4483 files_struct *fsp = NULL;
4486 DEBUG(10,("create_file_unixpath: access_mask = 0x%x "
4487 "file_attributes = 0x%x, share_access = 0x%x, "
4488 "create_disposition = 0x%x create_options = 0x%x "
4489 "oplock_request = 0x%x private_flags = 0x%x "
4490 "ea_list = 0x%p, sd = 0x%p, "
4492 (unsigned int)access_mask,
4493 (unsigned int)file_attributes,
4494 (unsigned int)share_access,
4495 (unsigned int)create_disposition,
4496 (unsigned int)create_options,
4497 (unsigned int)oplock_request,
4498 (unsigned int)private_flags,
4499 ea_list, sd, smb_fname_str_dbg(smb_fname)));
4501 if (create_options & FILE_OPEN_BY_FILE_ID) {
4502 status = NT_STATUS_NOT_SUPPORTED;
4506 if (create_options & NTCREATEX_OPTIONS_INVALID_PARAM_MASK) {
4507 status = NT_STATUS_INVALID_PARAMETER;
4512 oplock_request |= INTERNAL_OPEN_ONLY;
4515 if (lease != NULL) {
4516 uint16_t epoch = lease->lease_epoch;
4517 uint16_t version = lease->lease_version;
4518 status = lease_match(conn,
4525 if (NT_STATUS_EQUAL(status, NT_STATUS_OPLOCK_NOT_GRANTED)) {
4526 /* Dynamic share file. No leases and update epoch... */
4527 lease->lease_state = SMB2_LEASE_NONE;
4528 lease->lease_epoch = epoch;
4529 lease->lease_version = version;
4530 } else if (!NT_STATUS_IS_OK(status)) {
4535 if ((conn->fs_capabilities & FILE_NAMED_STREAMS)
4536 && (access_mask & DELETE_ACCESS)
4537 && !is_ntfs_stream_smb_fname(smb_fname)) {
4539 * We can't open a file with DELETE access if any of the
4540 * streams is open without FILE_SHARE_DELETE
4542 status = open_streams_for_delete(conn, smb_fname);
4544 if (!NT_STATUS_IS_OK(status)) {
4549 if ((access_mask & SEC_FLAG_SYSTEM_SECURITY) &&
4550 !security_token_has_privilege(get_current_nttok(conn),
4551 SEC_PRIV_SECURITY)) {
4552 DEBUG(10, ("create_file_unixpath: open on %s "
4553 "failed - SEC_FLAG_SYSTEM_SECURITY denied.\n",
4554 smb_fname_str_dbg(smb_fname)));
4555 status = NT_STATUS_PRIVILEGE_NOT_HELD;
4559 if ((conn->fs_capabilities & FILE_NAMED_STREAMS)
4560 && is_ntfs_stream_smb_fname(smb_fname)
4561 && (!(private_flags & NTCREATEX_OPTIONS_PRIVATE_STREAM_DELETE))) {
4562 uint32_t base_create_disposition;
4563 struct smb_filename *smb_fname_base = NULL;
4565 if (create_options & FILE_DIRECTORY_FILE) {
4566 status = NT_STATUS_NOT_A_DIRECTORY;
4570 switch (create_disposition) {
4572 base_create_disposition = FILE_OPEN;
4575 base_create_disposition = FILE_OPEN_IF;
4579 /* Create an smb_filename with stream_name == NULL. */
4580 smb_fname_base = synthetic_smb_fname(talloc_tos(),
4581 smb_fname->base_name,
4585 if (smb_fname_base == NULL) {
4586 status = NT_STATUS_NO_MEMORY;
4590 if (SMB_VFS_STAT(conn, smb_fname_base) == -1) {
4591 DEBUG(10, ("Unable to stat stream: %s\n",
4592 smb_fname_str_dbg(smb_fname_base)));
4595 * https://bugzilla.samba.org/show_bug.cgi?id=10229
4596 * We need to check if the requested access mask
4597 * could be used to open the underlying file (if
4598 * it existed), as we're passing in zero for the
4599 * access mask to the base filename.
4601 status = check_base_file_access(conn,
4605 if (!NT_STATUS_IS_OK(status)) {
4606 DEBUG(10, ("Permission check "
4607 "for base %s failed: "
4608 "%s\n", smb_fname->base_name,
4609 nt_errstr(status)));
4614 /* Open the base file. */
4615 status = create_file_unixpath(conn, NULL, smb_fname_base, 0,
4618 | FILE_SHARE_DELETE,
4619 base_create_disposition,
4620 0, 0, 0, NULL, 0, 0, NULL, NULL,
4622 TALLOC_FREE(smb_fname_base);
4624 if (!NT_STATUS_IS_OK(status)) {
4625 DEBUG(10, ("create_file_unixpath for base %s failed: "
4626 "%s\n", smb_fname->base_name,
4627 nt_errstr(status)));
4630 /* we don't need the low level fd */
4635 * If it's a request for a directory open, deal with it separately.
4638 if (create_options & FILE_DIRECTORY_FILE) {
4640 if (create_options & FILE_NON_DIRECTORY_FILE) {
4641 status = NT_STATUS_INVALID_PARAMETER;
4645 /* Can't open a temp directory. IFS kit test. */
4646 if (!(file_attributes & FILE_FLAG_POSIX_SEMANTICS) &&
4647 (file_attributes & FILE_ATTRIBUTE_TEMPORARY)) {
4648 status = NT_STATUS_INVALID_PARAMETER;
4653 * We will get a create directory here if the Win32
4654 * app specified a security descriptor in the
4655 * CreateDirectory() call.
4659 status = open_directory(
4660 conn, req, smb_fname, access_mask, share_access,
4661 create_disposition, create_options, file_attributes,
4666 * Ordinary file case.
4669 status = file_new(req, conn, &fsp);
4670 if(!NT_STATUS_IS_OK(status)) {
4674 status = fsp_set_smb_fname(fsp, smb_fname);
4675 if (!NT_STATUS_IS_OK(status)) {
4681 * We're opening the stream element of a
4682 * base_fsp we already opened. Set up the
4685 fsp->base_fsp = base_fsp;
4688 if (allocation_size) {
4689 fsp->initial_allocation_size = smb_roundup(fsp->conn,
4693 status = open_file_ntcreate(conn,
4706 if(!NT_STATUS_IS_OK(status)) {
4707 file_free(req, fsp);
4711 if (NT_STATUS_EQUAL(status, NT_STATUS_FILE_IS_A_DIRECTORY)) {
4713 /* A stream open never opens a directory */
4716 status = NT_STATUS_FILE_IS_A_DIRECTORY;
4721 * Fail the open if it was explicitly a non-directory
4725 if (create_options & FILE_NON_DIRECTORY_FILE) {
4726 status = NT_STATUS_FILE_IS_A_DIRECTORY;
4731 status = open_directory(
4732 conn, req, smb_fname, access_mask,
4733 share_access, create_disposition,
4734 create_options, file_attributes,
4739 if (!NT_STATUS_IS_OK(status)) {
4743 fsp->base_fsp = base_fsp;
4745 if ((ea_list != NULL) &&
4746 ((info == FILE_WAS_CREATED) || (info == FILE_WAS_OVERWRITTEN))) {
4747 status = set_ea(conn, fsp, fsp->fsp_name, ea_list);
4748 if (!NT_STATUS_IS_OK(status)) {
4753 if (!fsp->is_directory && S_ISDIR(fsp->fsp_name->st.st_ex_mode)) {
4754 status = NT_STATUS_ACCESS_DENIED;
4758 /* Save the requested allocation size. */
4759 if ((info == FILE_WAS_CREATED) || (info == FILE_WAS_OVERWRITTEN)) {
4760 if ((allocation_size > fsp->fsp_name->st.st_ex_size)
4761 && !(fsp->is_directory))
4763 fsp->initial_allocation_size = smb_roundup(
4764 fsp->conn, allocation_size);
4765 if (vfs_allocate_file_space(
4766 fsp, fsp->initial_allocation_size) == -1) {
4767 status = NT_STATUS_DISK_FULL;
4771 fsp->initial_allocation_size = smb_roundup(
4772 fsp->conn, (uint64_t)fsp->fsp_name->st.st_ex_size);
4775 fsp->initial_allocation_size = 0;
4778 if ((info == FILE_WAS_CREATED) && lp_nt_acl_support(SNUM(conn)) &&
4779 fsp->base_fsp == NULL) {
4782 * According to the MS documentation, the only time the security
4783 * descriptor is applied to the opened file is iff we *created* the
4784 * file; an existing file stays the same.
4786 * Also, it seems (from observation) that you can open the file with
4787 * any access mask but you can still write the sd. We need to override
4788 * the granted access before we call set_sd
4789 * Patch for bug #2242 from Tom Lackemann <cessnatomny@yahoo.com>.
4792 uint32_t sec_info_sent;
4793 uint32_t saved_access_mask = fsp->access_mask;
4795 sec_info_sent = get_sec_info(sd);
4797 fsp->access_mask = FILE_GENERIC_ALL;
4799 if (sec_info_sent & (SECINFO_OWNER|
4803 status = set_sd(fsp, sd, sec_info_sent);
4806 fsp->access_mask = saved_access_mask;
4808 if (!NT_STATUS_IS_OK(status)) {
4811 } else if (lp_inherit_acls(SNUM(conn))) {
4812 /* Inherit from parent. Errors here are not fatal. */
4813 status = inherit_new_acl(fsp);
4814 if (!NT_STATUS_IS_OK(status)) {
4815 DEBUG(10,("inherit_new_acl: failed for %s with %s\n",
4817 nt_errstr(status) ));
4822 if ((conn->fs_capabilities & FILE_FILE_COMPRESSION)
4823 && (create_options & FILE_NO_COMPRESSION)
4824 && (info == FILE_WAS_CREATED)) {
4825 status = SMB_VFS_SET_COMPRESSION(conn, fsp, fsp,
4826 COMPRESSION_FORMAT_NONE);
4827 if (!NT_STATUS_IS_OK(status)) {
4828 DEBUG(1, ("failed to disable compression: %s\n",
4829 nt_errstr(status)));
4833 DEBUG(10, ("create_file_unixpath: info=%d\n", info));
4836 if (pinfo != NULL) {
4840 smb_fname->st = fsp->fsp_name->st;
4842 return NT_STATUS_OK;
4845 DEBUG(10, ("create_file_unixpath: %s\n", nt_errstr(status)));
4848 if (base_fsp && fsp->base_fsp == base_fsp) {
4850 * The close_file below will close
4855 close_file(req, fsp, ERROR_CLOSE);
4858 if (base_fsp != NULL) {
4859 close_file(req, base_fsp, ERROR_CLOSE);
4866 * Calculate the full path name given a relative fid.
4868 NTSTATUS get_relative_fid_filename(connection_struct *conn,
4869 struct smb_request *req,
4870 uint16_t root_dir_fid,
4871 const struct smb_filename *smb_fname,
4872 struct smb_filename **smb_fname_out)
4874 files_struct *dir_fsp;
4875 char *parent_fname = NULL;
4876 char *new_base_name = NULL;
4877 uint32_t ucf_flags = ((req != NULL && req->posix_pathnames) ?
4878 UCF_POSIX_PATHNAMES : 0);
4881 if (root_dir_fid == 0 || !smb_fname) {
4882 status = NT_STATUS_INTERNAL_ERROR;
4886 dir_fsp = file_fsp(req, root_dir_fid);
4888 if (dir_fsp == NULL) {
4889 status = NT_STATUS_INVALID_HANDLE;
4893 if (is_ntfs_stream_smb_fname(dir_fsp->fsp_name)) {
4894 status = NT_STATUS_INVALID_HANDLE;
4898 if (!dir_fsp->is_directory) {
4901 * Check to see if this is a mac fork of some kind.
4904 if ((conn->fs_capabilities & FILE_NAMED_STREAMS) &&
4905 is_ntfs_stream_smb_fname(smb_fname)) {
4906 status = NT_STATUS_OBJECT_PATH_NOT_FOUND;
4911 we need to handle the case when we get a
4912 relative open relative to a file and the
4913 pathname is blank - this is a reopen!
4914 (hint from demyn plantenberg)
4917 status = NT_STATUS_INVALID_HANDLE;
4921 if (ISDOT(dir_fsp->fsp_name->base_name)) {
4923 * We're at the toplevel dir, the final file name
4924 * must not contain ./, as this is filtered out
4925 * normally by srvstr_get_path and unix_convert
4926 * explicitly rejects paths containing ./.
4928 parent_fname = talloc_strdup(talloc_tos(), "");
4929 if (parent_fname == NULL) {
4930 status = NT_STATUS_NO_MEMORY;
4934 size_t dir_name_len = strlen(dir_fsp->fsp_name->base_name);
4937 * Copy in the base directory name.
4940 parent_fname = talloc_array(talloc_tos(), char,
4942 if (parent_fname == NULL) {
4943 status = NT_STATUS_NO_MEMORY;
4946 memcpy(parent_fname, dir_fsp->fsp_name->base_name,
4950 * Ensure it ends in a '/'.
4951 * We used TALLOC_SIZE +2 to add space for the '/'.
4955 && (parent_fname[dir_name_len-1] != '\\')
4956 && (parent_fname[dir_name_len-1] != '/')) {
4957 parent_fname[dir_name_len] = '/';
4958 parent_fname[dir_name_len+1] = '\0';
4962 new_base_name = talloc_asprintf(talloc_tos(), "%s%s", parent_fname,
4963 smb_fname->base_name);
4964 if (new_base_name == NULL) {
4965 status = NT_STATUS_NO_MEMORY;
4969 status = filename_convert(req,
4971 req->flags2 & FLAGS2_DFS_PATHNAMES,
4976 if (!NT_STATUS_IS_OK(status)) {
4981 TALLOC_FREE(parent_fname);
4982 TALLOC_FREE(new_base_name);
4986 NTSTATUS create_file_default(connection_struct *conn,
4987 struct smb_request *req,
4988 uint16_t root_dir_fid,
4989 struct smb_filename *smb_fname,
4990 uint32_t access_mask,
4991 uint32_t share_access,
4992 uint32_t create_disposition,
4993 uint32_t create_options,
4994 uint32_t file_attributes,
4995 uint32_t oplock_request,
4996 struct smb2_lease *lease,
4997 uint64_t allocation_size,
4998 uint32_t private_flags,
4999 struct security_descriptor *sd,
5000 struct ea_list *ea_list,
5001 files_struct **result,
5003 const struct smb2_create_blobs *in_context_blobs,
5004 struct smb2_create_blobs *out_context_blobs)
5006 int info = FILE_WAS_OPENED;
5007 files_struct *fsp = NULL;
5009 bool stream_name = false;
5011 DEBUG(10,("create_file: access_mask = 0x%x "
5012 "file_attributes = 0x%x, share_access = 0x%x, "
5013 "create_disposition = 0x%x create_options = 0x%x "
5014 "oplock_request = 0x%x "
5015 "private_flags = 0x%x "
5016 "root_dir_fid = 0x%x, ea_list = 0x%p, sd = 0x%p, "
5018 (unsigned int)access_mask,
5019 (unsigned int)file_attributes,
5020 (unsigned int)share_access,
5021 (unsigned int)create_disposition,
5022 (unsigned int)create_options,
5023 (unsigned int)oplock_request,
5024 (unsigned int)private_flags,
5025 (unsigned int)root_dir_fid,
5026 ea_list, sd, smb_fname_str_dbg(smb_fname)));
5029 * Calculate the filename from the root_dir_if if necessary.
5032 if (root_dir_fid != 0) {
5033 struct smb_filename *smb_fname_out = NULL;
5034 status = get_relative_fid_filename(conn, req, root_dir_fid,
5035 smb_fname, &smb_fname_out);
5036 if (!NT_STATUS_IS_OK(status)) {
5039 smb_fname = smb_fname_out;
5043 * Check to see if this is a mac fork of some kind.
5046 stream_name = is_ntfs_stream_smb_fname(smb_fname);
5048 enum FAKE_FILE_TYPE fake_file_type;
5050 fake_file_type = is_fake_file(smb_fname);
5052 if (fake_file_type != FAKE_FILE_TYPE_NONE) {
5055 * Here we go! support for changing the disk quotas
5058 * We need to fake up to open this MAGIC QUOTA file
5059 * and return a valid FID.
5061 * w2k close this file directly after openening xp
5062 * also tries a QUERY_FILE_INFO on the file and then
5065 status = open_fake_file(req, conn, req->vuid,
5066 fake_file_type, smb_fname,
5068 if (!NT_STATUS_IS_OK(status)) {
5072 ZERO_STRUCT(smb_fname->st);
5076 if (!(conn->fs_capabilities & FILE_NAMED_STREAMS)) {
5077 status = NT_STATUS_OBJECT_NAME_NOT_FOUND;
5082 if (is_ntfs_default_stream_smb_fname(smb_fname)) {
5084 smb_fname->stream_name = NULL;
5085 /* We have to handle this error here. */
5086 if (create_options & FILE_DIRECTORY_FILE) {
5087 status = NT_STATUS_NOT_A_DIRECTORY;
5090 if (req != NULL && req->posix_pathnames) {
5091 ret = SMB_VFS_LSTAT(conn, smb_fname);
5093 ret = SMB_VFS_STAT(conn, smb_fname);
5096 if (ret == 0 && VALID_STAT_OF_DIR(smb_fname->st)) {
5097 status = NT_STATUS_FILE_IS_A_DIRECTORY;
5102 status = create_file_unixpath(
5103 conn, req, smb_fname, access_mask, share_access,
5104 create_disposition, create_options, file_attributes,
5105 oplock_request, lease, allocation_size, private_flags,
5109 if (!NT_STATUS_IS_OK(status)) {
5114 DEBUG(10, ("create_file: info=%d\n", info));
5117 if (pinfo != NULL) {
5120 return NT_STATUS_OK;
5123 DEBUG(10, ("create_file: %s\n", nt_errstr(status)));
5126 close_file(req, fsp, ERROR_CLOSE);