2 Unix SMB/CIFS implementation.
3 file opening and share modes
4 Copyright (C) Andrew Tridgell 1992-1998
5 Copyright (C) Jeremy Allison 2001-2004
6 Copyright (C) Volker Lendecke 2005
8 This program is free software; you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation; either version 3 of the License, or
11 (at your option) any later version.
13 This program is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with this program. If not, see <http://www.gnu.org/licenses/>.
23 #include "system/filesys.h"
25 #include "smbd/smbd.h"
26 #include "smbd/globals.h"
27 #include "fake_file.h"
28 #include "../libcli/security/security.h"
29 #include "../librpc/gen_ndr/ndr_security.h"
30 #include "../librpc/gen_ndr/open_files.h"
31 #include "../librpc/gen_ndr/idmap.h"
32 #include "../librpc/gen_ndr/ioctl.h"
33 #include "passdb/lookup_sid.h"
37 #include "source3/lib/dbwrap/dbwrap_watch.h"
38 #include "locking/leases_db.h"
39 #include "librpc/gen_ndr/ndr_leases_db.h"
41 extern const struct generic_mapping file_generic_mapping;
43 struct deferred_open_record {
44 bool delayed_for_oplocks;
49 /****************************************************************************
50 If the requester wanted DELETE_ACCESS and was rejected because
51 the file ACL didn't include DELETE_ACCESS, see if the parent ACL
53 ****************************************************************************/
55 static bool parent_override_delete(connection_struct *conn,
56 const struct smb_filename *smb_fname,
58 uint32_t rejected_mask)
60 if ((access_mask & DELETE_ACCESS) &&
61 (rejected_mask & DELETE_ACCESS) &&
62 can_delete_file_in_directory(conn, smb_fname)) {
68 /****************************************************************************
69 Check if we have open rights.
70 ****************************************************************************/
72 NTSTATUS smbd_check_access_rights(struct connection_struct *conn,
73 const struct smb_filename *smb_fname,
77 /* Check if we have rights to open. */
79 struct security_descriptor *sd = NULL;
80 uint32_t rejected_share_access;
81 uint32_t rejected_mask = access_mask;
82 uint32_t do_not_check_mask = 0;
84 rejected_share_access = access_mask & ~(conn->share_access);
86 if (rejected_share_access) {
87 DEBUG(10, ("smbd_check_access_rights: rejected share access 0x%x "
89 (unsigned int)access_mask,
90 smb_fname_str_dbg(smb_fname),
91 (unsigned int)rejected_share_access ));
92 return NT_STATUS_ACCESS_DENIED;
95 if (!use_privs && get_current_uid(conn) == (uid_t)0) {
96 /* I'm sorry sir, I didn't know you were root... */
97 DEBUG(10,("smbd_check_access_rights: root override "
98 "on %s. Granting 0x%x\n",
99 smb_fname_str_dbg(smb_fname),
100 (unsigned int)access_mask ));
104 if ((access_mask & DELETE_ACCESS) && !lp_acl_check_permissions(SNUM(conn))) {
105 DEBUG(10,("smbd_check_access_rights: not checking ACL "
106 "on DELETE_ACCESS on file %s. Granting 0x%x\n",
107 smb_fname_str_dbg(smb_fname),
108 (unsigned int)access_mask ));
112 if (access_mask == DELETE_ACCESS &&
113 VALID_STAT(smb_fname->st) &&
114 S_ISLNK(smb_fname->st.st_ex_mode)) {
115 /* We can always delete a symlink. */
116 DEBUG(10,("smbd_check_access_rights: not checking ACL "
117 "on DELETE_ACCESS on symlink %s.\n",
118 smb_fname_str_dbg(smb_fname) ));
122 status = SMB_VFS_GET_NT_ACL(conn, smb_fname,
125 SECINFO_DACL), talloc_tos(), &sd);
127 if (!NT_STATUS_IS_OK(status)) {
128 DEBUG(10, ("smbd_check_access_rights: Could not get acl "
130 smb_fname_str_dbg(smb_fname),
133 if (NT_STATUS_EQUAL(status, NT_STATUS_ACCESS_DENIED)) {
141 * If we can access the path to this file, by
142 * default we have FILE_READ_ATTRIBUTES from the
143 * containing directory. See the section:
144 * "Algorithm to Check Access to an Existing File"
147 * se_file_access_check() also takes care of
148 * owner WRITE_DAC and READ_CONTROL.
150 do_not_check_mask = FILE_READ_ATTRIBUTES;
153 * Samba 3.6 and earlier granted execute access even
154 * if the ACL did not contain execute rights.
155 * Samba 4.0 is more correct and checks it.
156 * The compatibilty mode allows one to skip this check
157 * to smoothen upgrades.
159 if (lp_acl_allow_execute_always(SNUM(conn))) {
160 do_not_check_mask |= FILE_EXECUTE;
163 status = se_file_access_check(sd,
164 get_current_nttok(conn),
166 (access_mask & ~do_not_check_mask),
169 DEBUG(10,("smbd_check_access_rights: file %s requesting "
170 "0x%x returning 0x%x (%s)\n",
171 smb_fname_str_dbg(smb_fname),
172 (unsigned int)access_mask,
173 (unsigned int)rejected_mask,
174 nt_errstr(status) ));
176 if (!NT_STATUS_IS_OK(status)) {
177 if (DEBUGLEVEL >= 10) {
178 DEBUG(10,("smbd_check_access_rights: acl for %s is:\n",
179 smb_fname_str_dbg(smb_fname) ));
180 NDR_PRINT_DEBUG(security_descriptor, sd);
186 if (NT_STATUS_IS_OK(status) ||
187 !NT_STATUS_EQUAL(status, NT_STATUS_ACCESS_DENIED)) {
191 /* Here we know status == NT_STATUS_ACCESS_DENIED. */
195 if ((access_mask & FILE_WRITE_ATTRIBUTES) &&
196 (rejected_mask & FILE_WRITE_ATTRIBUTES) &&
197 !lp_store_dos_attributes(SNUM(conn)) &&
198 (lp_map_readonly(SNUM(conn)) ||
199 lp_map_archive(SNUM(conn)) ||
200 lp_map_hidden(SNUM(conn)) ||
201 lp_map_system(SNUM(conn)))) {
202 rejected_mask &= ~FILE_WRITE_ATTRIBUTES;
204 DEBUG(10,("smbd_check_access_rights: "
206 "FILE_WRITE_ATTRIBUTES "
208 smb_fname_str_dbg(smb_fname)));
211 if (parent_override_delete(conn,
215 /* Were we trying to do an open
216 * for delete and didn't get DELETE
217 * access (only) ? Check if the
218 * directory allows DELETE_CHILD.
220 * http://blogs.msdn.com/oldnewthing/archive/2004/06/04/148426.aspx
223 rejected_mask &= ~DELETE_ACCESS;
225 DEBUG(10,("smbd_check_access_rights: "
229 smb_fname_str_dbg(smb_fname)));
232 if (rejected_mask != 0) {
233 return NT_STATUS_ACCESS_DENIED;
238 static NTSTATUS check_parent_access(struct connection_struct *conn,
239 struct smb_filename *smb_fname,
240 uint32_t access_mask)
243 char *parent_dir = NULL;
244 struct security_descriptor *parent_sd = NULL;
245 uint32_t access_granted = 0;
246 struct smb_filename *parent_smb_fname = NULL;
248 if (!parent_dirname(talloc_tos(),
249 smb_fname->base_name,
252 return NT_STATUS_NO_MEMORY;
255 parent_smb_fname = synthetic_smb_fname(talloc_tos(),
259 if (parent_smb_fname == NULL) {
260 return NT_STATUS_NO_MEMORY;
263 if (get_current_uid(conn) == (uid_t)0) {
264 /* I'm sorry sir, I didn't know you were root... */
265 DEBUG(10,("check_parent_access: root override "
266 "on %s. Granting 0x%x\n",
267 smb_fname_str_dbg(smb_fname),
268 (unsigned int)access_mask ));
272 status = SMB_VFS_GET_NT_ACL(conn,
278 if (!NT_STATUS_IS_OK(status)) {
279 DEBUG(5,("check_parent_access: SMB_VFS_GET_NT_ACL failed for "
280 "%s with error %s\n",
287 * If we can access the path to this file, by
288 * default we have FILE_READ_ATTRIBUTES from the
289 * containing directory. See the section:
290 * "Algorithm to Check Access to an Existing File"
293 * se_file_access_check() also takes care of
294 * owner WRITE_DAC and READ_CONTROL.
296 status = se_file_access_check(parent_sd,
297 get_current_nttok(conn),
299 (access_mask & ~FILE_READ_ATTRIBUTES),
301 if(!NT_STATUS_IS_OK(status)) {
302 DEBUG(5,("check_parent_access: access check "
303 "on directory %s for "
304 "path %s for mask 0x%x returned (0x%x) %s\n",
306 smb_fname->base_name,
309 nt_errstr(status) ));
316 /****************************************************************************
317 Ensure when opening a base file for a stream open that we have permissions
318 to do so given the access mask on the base file.
319 ****************************************************************************/
321 static NTSTATUS check_base_file_access(struct connection_struct *conn,
322 struct smb_filename *smb_fname,
323 uint32_t access_mask)
327 status = smbd_calculate_access_mask(conn, smb_fname,
331 if (!NT_STATUS_IS_OK(status)) {
332 DEBUG(10, ("smbd_calculate_access_mask "
333 "on file %s returned %s\n",
334 smb_fname_str_dbg(smb_fname),
339 if (access_mask & (FILE_WRITE_DATA|FILE_APPEND_DATA)) {
341 if (!CAN_WRITE(conn)) {
342 return NT_STATUS_ACCESS_DENIED;
344 dosattrs = dos_mode(conn, smb_fname);
345 if (IS_DOS_READONLY(dosattrs)) {
346 return NT_STATUS_ACCESS_DENIED;
350 return smbd_check_access_rights(conn,
356 /****************************************************************************
357 fd support routines - attempt to do a dos_open.
358 ****************************************************************************/
360 NTSTATUS fd_open(struct connection_struct *conn,
365 struct smb_filename *smb_fname = fsp->fsp_name;
366 NTSTATUS status = NT_STATUS_OK;
370 * Never follow symlinks on a POSIX client. The
371 * client should be doing this.
374 if ((fsp->posix_flags & FSP_POSIX_FLAGS_OPEN) || !lp_follow_symlinks(SNUM(conn))) {
379 fsp->fh->fd = SMB_VFS_OPEN(conn, smb_fname, fsp, flags, mode);
380 if (fsp->fh->fd == -1) {
381 int posix_errno = errno;
383 #if defined(ENOTSUP) && defined(OSF1)
384 /* handle special Tru64 errno */
385 if (errno == ENOTSUP) {
390 /* fix broken NetBSD errno */
391 if (errno == EFTYPE) {
395 /* fix broken FreeBSD errno */
396 if (errno == EMLINK) {
399 #endif /* O_NOFOLLOW */
400 status = map_nt_error_from_unix(posix_errno);
401 if (errno == EMFILE) {
402 static time_t last_warned = 0L;
404 if (time((time_t *) NULL) > last_warned) {
405 DEBUG(0,("Too many open files, unable "
406 "to open more! smbd's max "
408 lp_max_open_files()));
409 last_warned = time((time_t *) NULL);
415 DEBUG(10,("fd_open: name %s, flags = 0%o mode = 0%o, fd = %d. %s\n",
416 smb_fname_str_dbg(smb_fname), flags, (int)mode, fsp->fh->fd,
417 (fsp->fh->fd == -1) ? strerror(errno) : "" ));
422 /****************************************************************************
423 Close the file associated with a fsp.
424 ****************************************************************************/
426 NTSTATUS fd_close(files_struct *fsp)
433 if (fsp->fh->fd == -1) {
434 return NT_STATUS_OK; /* What we used to call a stat open. */
436 if (fsp->fh->ref_count > 1) {
437 return NT_STATUS_OK; /* Shared handle. Only close last reference. */
440 ret = SMB_VFS_CLOSE(fsp);
443 return map_nt_error_from_unix(errno);
448 /****************************************************************************
449 Change the ownership of a file to that of the parent directory.
450 Do this by fd if possible.
451 ****************************************************************************/
453 void change_file_owner_to_parent(connection_struct *conn,
454 const char *inherit_from_dir,
457 struct smb_filename *smb_fname_parent;
460 smb_fname_parent = synthetic_smb_fname(talloc_tos(), inherit_from_dir,
462 if (smb_fname_parent == NULL) {
466 ret = SMB_VFS_STAT(conn, smb_fname_parent);
468 DEBUG(0,("change_file_owner_to_parent: failed to stat parent "
469 "directory %s. Error was %s\n",
470 smb_fname_str_dbg(smb_fname_parent),
472 TALLOC_FREE(smb_fname_parent);
476 if (smb_fname_parent->st.st_ex_uid == fsp->fsp_name->st.st_ex_uid) {
477 /* Already this uid - no need to change. */
478 DEBUG(10,("change_file_owner_to_parent: file %s "
479 "is already owned by uid %d\n",
481 (int)fsp->fsp_name->st.st_ex_uid ));
482 TALLOC_FREE(smb_fname_parent);
487 ret = SMB_VFS_FCHOWN(fsp, smb_fname_parent->st.st_ex_uid, (gid_t)-1);
490 DEBUG(0,("change_file_owner_to_parent: failed to fchown "
491 "file %s to parent directory uid %u. Error "
492 "was %s\n", fsp_str_dbg(fsp),
493 (unsigned int)smb_fname_parent->st.st_ex_uid,
496 DEBUG(10,("change_file_owner_to_parent: changed new file %s to "
497 "parent directory uid %u.\n", fsp_str_dbg(fsp),
498 (unsigned int)smb_fname_parent->st.st_ex_uid));
499 /* Ensure the uid entry is updated. */
500 fsp->fsp_name->st.st_ex_uid = smb_fname_parent->st.st_ex_uid;
503 TALLOC_FREE(smb_fname_parent);
506 NTSTATUS change_dir_owner_to_parent(connection_struct *conn,
507 const char *inherit_from_dir,
509 SMB_STRUCT_STAT *psbuf)
511 struct smb_filename *smb_fname_parent;
512 struct smb_filename *smb_fname_cwd = NULL;
513 char *saved_dir = NULL;
514 TALLOC_CTX *ctx = talloc_tos();
515 NTSTATUS status = NT_STATUS_OK;
518 smb_fname_parent = synthetic_smb_fname(ctx, inherit_from_dir,
520 if (smb_fname_parent == NULL) {
521 return NT_STATUS_NO_MEMORY;
524 ret = SMB_VFS_STAT(conn, smb_fname_parent);
526 status = map_nt_error_from_unix(errno);
527 DEBUG(0,("change_dir_owner_to_parent: failed to stat parent "
528 "directory %s. Error was %s\n",
529 smb_fname_str_dbg(smb_fname_parent),
534 /* We've already done an lstat into psbuf, and we know it's a
535 directory. If we can cd into the directory and the dev/ino
536 are the same then we can safely chown without races as
537 we're locking the directory in place by being in it. This
538 should work on any UNIX (thanks tridge :-). JRA.
541 saved_dir = vfs_GetWd(ctx,conn);
543 status = map_nt_error_from_unix(errno);
544 DEBUG(0,("change_dir_owner_to_parent: failed to get "
545 "current working directory. Error was %s\n",
550 /* Chdir into the new path. */
551 if (vfs_ChDir(conn, fname) == -1) {
552 status = map_nt_error_from_unix(errno);
553 DEBUG(0,("change_dir_owner_to_parent: failed to change "
554 "current working directory to %s. Error "
555 "was %s\n", fname, strerror(errno) ));
559 smb_fname_cwd = synthetic_smb_fname(ctx, ".", NULL, NULL);
560 if (smb_fname_cwd == NULL) {
561 status = NT_STATUS_NO_MEMORY;
565 ret = SMB_VFS_STAT(conn, smb_fname_cwd);
567 status = map_nt_error_from_unix(errno);
568 DEBUG(0,("change_dir_owner_to_parent: failed to stat "
569 "directory '.' (%s) Error was %s\n",
570 fname, strerror(errno)));
574 /* Ensure we're pointing at the same place. */
575 if (smb_fname_cwd->st.st_ex_dev != psbuf->st_ex_dev ||
576 smb_fname_cwd->st.st_ex_ino != psbuf->st_ex_ino) {
577 DEBUG(0,("change_dir_owner_to_parent: "
578 "device/inode on directory %s changed. "
579 "Refusing to chown !\n", fname ));
580 status = NT_STATUS_ACCESS_DENIED;
584 if (smb_fname_parent->st.st_ex_uid == smb_fname_cwd->st.st_ex_uid) {
585 /* Already this uid - no need to change. */
586 DEBUG(10,("change_dir_owner_to_parent: directory %s "
587 "is already owned by uid %d\n",
589 (int)smb_fname_cwd->st.st_ex_uid ));
590 status = NT_STATUS_OK;
595 ret = SMB_VFS_LCHOWN(conn,
597 smb_fname_parent->st.st_ex_uid,
601 status = map_nt_error_from_unix(errno);
602 DEBUG(10,("change_dir_owner_to_parent: failed to chown "
603 "directory %s to parent directory uid %u. "
604 "Error was %s\n", fname,
605 (unsigned int)smb_fname_parent->st.st_ex_uid,
608 DEBUG(10,("change_dir_owner_to_parent: changed ownership of new "
609 "directory %s to parent directory uid %u.\n",
610 fname, (unsigned int)smb_fname_parent->st.st_ex_uid ));
611 /* Ensure the uid entry is updated. */
612 psbuf->st_ex_uid = smb_fname_parent->st.st_ex_uid;
616 vfs_ChDir(conn,saved_dir);
618 TALLOC_FREE(smb_fname_parent);
619 TALLOC_FREE(smb_fname_cwd);
623 /****************************************************************************
624 Open a file - returning a guaranteed ATOMIC indication of if the
625 file was created or not.
626 ****************************************************************************/
628 static NTSTATUS fd_open_atomic(struct connection_struct *conn,
634 NTSTATUS status = NT_STATUS_UNSUCCESSFUL;
635 bool file_existed = VALID_STAT(fsp->fsp_name->st);
637 *file_created = false;
639 if (!(flags & O_CREAT)) {
641 * We're not creating the file, just pass through.
643 return fd_open(conn, fsp, flags, mode);
646 if (flags & O_EXCL) {
648 * Fail if already exists, just pass through.
650 status = fd_open(conn, fsp, flags, mode);
653 * Here we've opened with O_CREAT|O_EXCL. If that went
654 * NT_STATUS_OK, we *know* we created this file.
656 *file_created = NT_STATUS_IS_OK(status);
662 * Now it gets tricky. We have O_CREAT, but not O_EXCL.
663 * To know absolutely if we created the file or not,
664 * we can never call O_CREAT without O_EXCL. So if
665 * we think the file existed, try without O_CREAT|O_EXCL.
666 * If we think the file didn't exist, try with
667 * O_CREAT|O_EXCL. Keep bouncing between these two
668 * requests until either the file is created, or
669 * opened. Either way, we keep going until we get
670 * a returnable result (error, or open/create).
674 int curr_flags = flags;
677 /* Just try open, do not create. */
678 curr_flags &= ~(O_CREAT);
679 status = fd_open(conn, fsp, curr_flags, mode);
680 if (NT_STATUS_EQUAL(status,
681 NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
683 * Someone deleted it in the meantime.
686 file_existed = false;
687 DEBUG(10,("fd_open_atomic: file %s existed. "
689 smb_fname_str_dbg(fsp->fsp_name)));
693 /* Try create exclusively, fail if it exists. */
694 curr_flags |= O_EXCL;
695 status = fd_open(conn, fsp, curr_flags, mode);
696 if (NT_STATUS_EQUAL(status,
697 NT_STATUS_OBJECT_NAME_COLLISION)) {
699 * Someone created it in the meantime.
700 * Retry without O_CREAT.
703 DEBUG(10,("fd_open_atomic: file %s "
704 "did not exist. Retry.\n",
705 smb_fname_str_dbg(fsp->fsp_name)));
708 if (NT_STATUS_IS_OK(status)) {
710 * Here we've opened with O_CREAT|O_EXCL
711 * and got success. We *know* we created
714 *file_created = true;
717 /* Create is done, or failed. */
723 /****************************************************************************
725 ****************************************************************************/
727 static NTSTATUS open_file(files_struct *fsp,
728 connection_struct *conn,
729 struct smb_request *req,
730 const char *parent_dir,
733 uint32_t access_mask, /* client requested access mask. */
734 uint32_t open_access_mask, /* what we're actually using in the open. */
735 bool *p_file_created)
737 struct smb_filename *smb_fname = fsp->fsp_name;
738 NTSTATUS status = NT_STATUS_OK;
739 int accmode = (flags & O_ACCMODE);
740 int local_flags = flags;
741 bool file_existed = VALID_STAT(fsp->fsp_name->st);
746 /* Check permissions */
749 * This code was changed after seeing a client open request
750 * containing the open mode of (DENY_WRITE/read-only) with
751 * the 'create if not exist' bit set. The previous code
752 * would fail to open the file read only on a read-only share
753 * as it was checking the flags parameter directly against O_RDONLY,
754 * this was failing as the flags parameter was set to O_RDONLY|O_CREAT.
758 if (!CAN_WRITE(conn)) {
759 /* It's a read-only share - fail if we wanted to write. */
760 if(accmode != O_RDONLY || (flags & O_TRUNC) || (flags & O_APPEND)) {
761 DEBUG(3,("Permission denied opening %s\n",
762 smb_fname_str_dbg(smb_fname)));
763 return NT_STATUS_ACCESS_DENIED;
765 if (flags & O_CREAT) {
766 /* We don't want to write - but we must make sure that
767 O_CREAT doesn't create the file if we have write
768 access into the directory.
770 flags &= ~(O_CREAT|O_EXCL);
771 local_flags &= ~(O_CREAT|O_EXCL);
776 * This little piece of insanity is inspired by the
777 * fact that an NT client can open a file for O_RDONLY,
778 * but set the create disposition to FILE_EXISTS_TRUNCATE.
779 * If the client *can* write to the file, then it expects to
780 * truncate the file, even though it is opening for readonly.
781 * Quicken uses this stupid trick in backup file creation...
782 * Thanks *greatly* to "David W. Chapman Jr." <dwcjr@inethouston.net>
783 * for helping track this one down. It didn't bite us in 2.0.x
784 * as we always opened files read-write in that release. JRA.
787 if ((accmode == O_RDONLY) && ((flags & O_TRUNC) == O_TRUNC)) {
788 DEBUG(10,("open_file: truncate requested on read-only open "
789 "for file %s\n", smb_fname_str_dbg(smb_fname)));
790 local_flags = (flags & ~O_ACCMODE)|O_RDWR;
793 if ((open_access_mask & (FILE_READ_DATA|FILE_WRITE_DATA|FILE_APPEND_DATA|FILE_EXECUTE)) ||
794 (!file_existed && (local_flags & O_CREAT)) ||
795 ((local_flags & O_TRUNC) == O_TRUNC) ) {
799 #if defined(O_NONBLOCK) && defined(S_ISFIFO)
801 * We would block on opening a FIFO with no one else on the
802 * other end. Do what we used to do and add O_NONBLOCK to the
806 if (file_existed && S_ISFIFO(smb_fname->st.st_ex_mode)) {
807 local_flags &= ~O_TRUNC; /* Can't truncate a FIFO. */
808 local_flags |= O_NONBLOCK;
812 /* Don't create files with Microsoft wildcard characters. */
815 * wildcard characters are allowed in stream names
816 * only test the basefilename
818 wild = fsp->base_fsp->fsp_name->base_name;
820 wild = smb_fname->base_name;
822 if ((local_flags & O_CREAT) && !file_existed &&
823 !(fsp->posix_flags & FSP_POSIX_FLAGS_PATHNAMES) &&
825 return NT_STATUS_OBJECT_NAME_INVALID;
828 /* Can we access this file ? */
829 if (!fsp->base_fsp) {
830 /* Only do this check on non-stream open. */
832 status = smbd_check_access_rights(conn,
837 if (!NT_STATUS_IS_OK(status)) {
838 DEBUG(10, ("open_file: "
839 "smbd_check_access_rights "
840 "on file %s returned %s\n",
841 smb_fname_str_dbg(smb_fname),
845 if (!NT_STATUS_IS_OK(status) &&
846 !NT_STATUS_EQUAL(status,
847 NT_STATUS_OBJECT_NAME_NOT_FOUND))
852 if (NT_STATUS_EQUAL(status,
853 NT_STATUS_OBJECT_NAME_NOT_FOUND))
855 DEBUG(10, ("open_file: "
856 "file %s vanished since we "
857 "checked for existence.\n",
858 smb_fname_str_dbg(smb_fname)));
859 file_existed = false;
860 SET_STAT_INVALID(fsp->fsp_name->st);
865 if (!(local_flags & O_CREAT)) {
866 /* File didn't exist and no O_CREAT. */
867 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
870 status = check_parent_access(conn,
873 if (!NT_STATUS_IS_OK(status)) {
874 DEBUG(10, ("open_file: "
875 "check_parent_access on "
876 "file %s returned %s\n",
877 smb_fname_str_dbg(smb_fname),
878 nt_errstr(status) ));
885 * Actually do the open - if O_TRUNC is needed handle it
886 * below under the share mode lock.
888 status = fd_open_atomic(conn, fsp, local_flags & ~O_TRUNC,
889 unx_mode, p_file_created);
890 if (!NT_STATUS_IS_OK(status)) {
891 DEBUG(3,("Error opening file %s (%s) (local_flags=%d) "
892 "(flags=%d)\n", smb_fname_str_dbg(smb_fname),
893 nt_errstr(status),local_flags,flags));
897 ret = SMB_VFS_FSTAT(fsp, &smb_fname->st);
899 /* If we have an fd, this stat should succeed. */
900 DEBUG(0,("Error doing fstat on open file %s "
902 smb_fname_str_dbg(smb_fname),
904 status = map_nt_error_from_unix(errno);
909 if (*p_file_created) {
910 /* We created this file. */
912 bool need_re_stat = false;
913 /* Do all inheritance work after we've
914 done a successful fstat call and filled
915 in the stat struct in fsp->fsp_name. */
917 /* Inherit the ACL if required */
918 if (lp_inherit_permissions(SNUM(conn))) {
919 inherit_access_posix_acl(conn, parent_dir,
920 smb_fname->base_name,
925 /* Change the owner if required. */
926 if (lp_inherit_owner(SNUM(conn))) {
927 change_file_owner_to_parent(conn, parent_dir,
933 ret = SMB_VFS_FSTAT(fsp, &smb_fname->st);
934 /* If we have an fd, this stat should succeed. */
936 DEBUG(0,("Error doing fstat on open file %s "
938 smb_fname_str_dbg(smb_fname),
943 notify_fname(conn, NOTIFY_ACTION_ADDED,
944 FILE_NOTIFY_CHANGE_FILE_NAME,
945 smb_fname->base_name);
948 fsp->fh->fd = -1; /* What we used to call a stat open. */
950 /* File must exist for a stat open. */
951 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
954 status = smbd_check_access_rights(conn,
959 if (NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND) &&
960 (fsp->posix_flags & FSP_POSIX_FLAGS_OPEN) &&
961 S_ISLNK(smb_fname->st.st_ex_mode)) {
962 /* This is a POSIX stat open for delete
963 * or rename on a symlink that points
965 DEBUG(10,("open_file: allowing POSIX "
966 "open on bad symlink %s\n",
967 smb_fname_str_dbg(smb_fname)));
968 status = NT_STATUS_OK;
971 if (!NT_STATUS_IS_OK(status)) {
972 DEBUG(10,("open_file: "
973 "smbd_check_access_rights on file "
975 smb_fname_str_dbg(smb_fname),
976 nt_errstr(status) ));
982 * POSIX allows read-only opens of directories. We don't
983 * want to do this (we use a different code path for this)
984 * so catch a directory open and return an EISDIR. JRA.
987 if(S_ISDIR(smb_fname->st.st_ex_mode)) {
990 return NT_STATUS_FILE_IS_A_DIRECTORY;
993 fsp->file_id = vfs_file_id_from_sbuf(conn, &smb_fname->st);
994 fsp->vuid = req ? req->vuid : UID_FIELD_INVALID;
995 fsp->file_pid = req ? req->smbpid : 0;
996 fsp->can_lock = True;
997 fsp->can_read = ((access_mask & FILE_READ_DATA) != 0);
1000 ((access_mask & (FILE_WRITE_DATA | FILE_APPEND_DATA)) != 0);
1001 fsp->print_file = NULL;
1002 fsp->modified = False;
1003 fsp->sent_oplock_break = NO_BREAK_SENT;
1004 fsp->is_directory = False;
1005 if (conn->aio_write_behind_list &&
1006 is_in_path(smb_fname->base_name, conn->aio_write_behind_list,
1007 conn->case_sensitive)) {
1008 fsp->aio_write_behind = True;
1011 fsp->wcp = NULL; /* Write cache pointer. */
1013 DEBUG(2,("%s opened file %s read=%s write=%s (numopen=%d)\n",
1014 conn->session_info->unix_info->unix_name,
1015 smb_fname_str_dbg(smb_fname),
1016 BOOLSTR(fsp->can_read), BOOLSTR(fsp->can_write),
1017 conn->num_files_open));
1020 return NT_STATUS_OK;
1023 /****************************************************************************
1024 Check if we can open a file with a share mode.
1025 Returns True if conflict, False if not.
1026 ****************************************************************************/
1028 static bool share_conflict(struct share_mode_entry *entry,
1029 uint32_t access_mask,
1030 uint32_t share_access)
1032 DEBUG(10,("share_conflict: entry->access_mask = 0x%x, "
1033 "entry->share_access = 0x%x, "
1034 "entry->private_options = 0x%x\n",
1035 (unsigned int)entry->access_mask,
1036 (unsigned int)entry->share_access,
1037 (unsigned int)entry->private_options));
1039 if (server_id_is_disconnected(&entry->pid)) {
1041 * note: cleanup should have been done by
1042 * delay_for_batch_oplocks()
1047 DEBUG(10,("share_conflict: access_mask = 0x%x, share_access = 0x%x\n",
1048 (unsigned int)access_mask, (unsigned int)share_access));
1050 if ((entry->access_mask & (FILE_WRITE_DATA|
1054 DELETE_ACCESS)) == 0) {
1055 DEBUG(10,("share_conflict: No conflict due to "
1056 "entry->access_mask = 0x%x\n",
1057 (unsigned int)entry->access_mask ));
1061 if ((access_mask & (FILE_WRITE_DATA|
1065 DELETE_ACCESS)) == 0) {
1066 DEBUG(10,("share_conflict: No conflict due to "
1067 "access_mask = 0x%x\n",
1068 (unsigned int)access_mask ));
1072 #if 1 /* JRA TEST - Superdebug. */
1073 #define CHECK_MASK(num, am, right, sa, share) \
1074 DEBUG(10,("share_conflict: [%d] am (0x%x) & right (0x%x) = 0x%x\n", \
1075 (unsigned int)(num), (unsigned int)(am), \
1076 (unsigned int)(right), (unsigned int)(am)&(right) )); \
1077 DEBUG(10,("share_conflict: [%d] sa (0x%x) & share (0x%x) = 0x%x\n", \
1078 (unsigned int)(num), (unsigned int)(sa), \
1079 (unsigned int)(share), (unsigned int)(sa)&(share) )); \
1080 if (((am) & (right)) && !((sa) & (share))) { \
1081 DEBUG(10,("share_conflict: check %d conflict am = 0x%x, right = 0x%x, \
1082 sa = 0x%x, share = 0x%x\n", (num), (unsigned int)(am), (unsigned int)(right), (unsigned int)(sa), \
1083 (unsigned int)(share) )); \
1087 #define CHECK_MASK(num, am, right, sa, share) \
1088 if (((am) & (right)) && !((sa) & (share))) { \
1089 DEBUG(10,("share_conflict: check %d conflict am = 0x%x, right = 0x%x, \
1090 sa = 0x%x, share = 0x%x\n", (num), (unsigned int)(am), (unsigned int)(right), (unsigned int)(sa), \
1091 (unsigned int)(share) )); \
1096 CHECK_MASK(1, entry->access_mask, FILE_WRITE_DATA | FILE_APPEND_DATA,
1097 share_access, FILE_SHARE_WRITE);
1098 CHECK_MASK(2, access_mask, FILE_WRITE_DATA | FILE_APPEND_DATA,
1099 entry->share_access, FILE_SHARE_WRITE);
1101 CHECK_MASK(3, entry->access_mask, FILE_READ_DATA | FILE_EXECUTE,
1102 share_access, FILE_SHARE_READ);
1103 CHECK_MASK(4, access_mask, FILE_READ_DATA | FILE_EXECUTE,
1104 entry->share_access, FILE_SHARE_READ);
1106 CHECK_MASK(5, entry->access_mask, DELETE_ACCESS,
1107 share_access, FILE_SHARE_DELETE);
1108 CHECK_MASK(6, access_mask, DELETE_ACCESS,
1109 entry->share_access, FILE_SHARE_DELETE);
1111 DEBUG(10,("share_conflict: No conflict.\n"));
1115 #if defined(DEVELOPER)
1116 static void validate_my_share_entries(struct smbd_server_connection *sconn,
1118 struct share_mode_entry *share_entry)
1120 struct server_id self = messaging_server_id(sconn->msg_ctx);
1123 if (!serverid_equal(&self, &share_entry->pid)) {
1127 if (share_entry->op_mid == 0) {
1128 /* INTERNAL_OPEN_ONLY */
1132 if (!is_valid_share_mode_entry(share_entry)) {
1136 fsp = file_find_dif(sconn, share_entry->id,
1137 share_entry->share_file_id);
1139 DEBUG(0,("validate_my_share_entries: PANIC : %s\n",
1140 share_mode_str(talloc_tos(), num, share_entry) ));
1141 smb_panic("validate_my_share_entries: Cannot match a "
1142 "share entry with an open file\n");
1145 if (((uint16_t)fsp->oplock_type) != share_entry->op_type) {
1154 DEBUG(0,("validate_my_share_entries: PANIC : %s\n",
1155 share_mode_str(talloc_tos(), num, share_entry) ));
1156 str = talloc_asprintf(talloc_tos(),
1157 "validate_my_share_entries: "
1158 "file %s, oplock_type = 0x%x, op_type = 0x%x\n",
1159 fsp->fsp_name->base_name,
1160 (unsigned int)fsp->oplock_type,
1161 (unsigned int)share_entry->op_type );
1167 bool is_stat_open(uint32_t access_mask)
1169 const uint32_t stat_open_bits =
1170 (SYNCHRONIZE_ACCESS|
1171 FILE_READ_ATTRIBUTES|
1172 FILE_WRITE_ATTRIBUTES);
1174 return (((access_mask & stat_open_bits) != 0) &&
1175 ((access_mask & ~stat_open_bits) == 0));
1178 static bool has_delete_on_close(struct share_mode_lock *lck,
1181 struct share_mode_data *d = lck->data;
1184 if (d->num_share_modes == 0) {
1187 if (!is_delete_on_close_set(lck, name_hash)) {
1190 for (i=0; i<d->num_share_modes; i++) {
1191 if (!share_mode_stale_pid(d, i)) {
1198 /****************************************************************************
1199 Deal with share modes
1200 Invariant: Share mode must be locked on entry and exit.
1201 Returns -1 on error, or number of share modes on success (may be zero).
1202 ****************************************************************************/
1204 static NTSTATUS open_mode_check(connection_struct *conn,
1205 struct share_mode_lock *lck,
1206 uint32_t access_mask,
1207 uint32_t share_access)
1211 if(lck->data->num_share_modes == 0) {
1212 return NT_STATUS_OK;
1215 if (is_stat_open(access_mask)) {
1216 /* Stat open that doesn't trigger oplock breaks or share mode
1217 * checks... ! JRA. */
1218 return NT_STATUS_OK;
1222 * Check if the share modes will give us access.
1225 #if defined(DEVELOPER)
1226 for(i = 0; i < lck->data->num_share_modes; i++) {
1227 validate_my_share_entries(conn->sconn, i,
1228 &lck->data->share_modes[i]);
1232 /* Now we check the share modes, after any oplock breaks. */
1233 for(i = 0; i < lck->data->num_share_modes; i++) {
1235 if (!is_valid_share_mode_entry(&lck->data->share_modes[i])) {
1239 /* someone else has a share lock on it, check to see if we can
1241 if (share_conflict(&lck->data->share_modes[i],
1242 access_mask, share_access)) {
1244 if (share_mode_stale_pid(lck->data, i)) {
1248 return NT_STATUS_SHARING_VIOLATION;
1252 return NT_STATUS_OK;
1256 * Send a break message to the oplock holder and delay the open for
1260 NTSTATUS send_break_message(struct messaging_context *msg_ctx,
1261 const struct share_mode_entry *exclusive,
1265 char msg[MSG_SMB_SHARE_MODE_ENTRY_SIZE];
1266 struct server_id_buf tmp;
1268 DEBUG(10, ("Sending break request to PID %s\n",
1269 server_id_str_buf(exclusive->pid, &tmp)));
1271 /* Create the message. */
1272 share_mode_entry_to_message(msg, exclusive);
1274 /* Overload entry->op_type */
1276 * This is a cut from uint32_t to uint16_t, but so far only the lower 3
1277 * bits (LEASE_WRITE/HANDLE/READ are used anyway.
1279 SSVAL(msg,OP_BREAK_MSG_OP_TYPE_OFFSET, break_to);
1281 status = messaging_send_buf(msg_ctx, exclusive->pid,
1282 MSG_SMB_BREAK_REQUEST,
1283 (uint8_t *)msg, sizeof(msg));
1284 if (!NT_STATUS_IS_OK(status)) {
1285 DEBUG(3, ("Could not send oplock break message: %s\n",
1286 nt_errstr(status)));
1293 * Do internal consistency checks on the share mode for a file.
1296 static bool validate_oplock_types(struct share_mode_lock *lck)
1298 struct share_mode_data *d = lck->data;
1300 bool ex_or_batch = false;
1301 bool level2 = false;
1302 bool no_oplock = false;
1303 uint32_t num_non_stat_opens = 0;
1306 for (i=0; i<d->num_share_modes; i++) {
1307 struct share_mode_entry *e = &d->share_modes[i];
1309 if (!is_valid_share_mode_entry(e)) {
1313 if (e->op_mid == 0) {
1314 /* INTERNAL_OPEN_ONLY */
1318 if (e->op_type == NO_OPLOCK && is_stat_open(e->access_mask)) {
1319 /* We ignore stat opens in the table - they
1320 always have NO_OPLOCK and never get or
1321 cause breaks. JRA. */
1325 num_non_stat_opens += 1;
1327 if (BATCH_OPLOCK_TYPE(e->op_type)) {
1328 /* batch - can only be one. */
1329 if (share_mode_stale_pid(d, i)) {
1330 DEBUG(10, ("Found stale batch oplock\n"));
1333 if (ex_or_batch || batch || level2 || no_oplock) {
1334 DEBUG(0, ("Bad batch oplock entry %u.",
1341 if (EXCLUSIVE_OPLOCK_TYPE(e->op_type)) {
1342 if (share_mode_stale_pid(d, i)) {
1343 DEBUG(10, ("Found stale duplicate oplock\n"));
1346 /* Exclusive or batch - can only be one. */
1347 if (ex_or_batch || level2 || no_oplock) {
1348 DEBUG(0, ("Bad exclusive or batch oplock "
1349 "entry %u.", (unsigned)i));
1355 if (LEVEL_II_OPLOCK_TYPE(e->op_type)) {
1356 if (batch || ex_or_batch) {
1357 if (share_mode_stale_pid(d, i)) {
1358 DEBUG(10, ("Found stale LevelII "
1362 DEBUG(0, ("Bad levelII oplock entry %u.",
1369 if (e->op_type == NO_OPLOCK) {
1370 if (batch || ex_or_batch) {
1371 if (share_mode_stale_pid(d, i)) {
1372 DEBUG(10, ("Found stale NO_OPLOCK "
1376 DEBUG(0, ("Bad no oplock entry %u.",
1384 remove_stale_share_mode_entries(d);
1386 if ((batch || ex_or_batch) && (num_non_stat_opens != 1)) {
1387 DEBUG(1, ("got batch (%d) or ex (%d) non-exclusively (%d)\n",
1388 (int)batch, (int)ex_or_batch,
1389 (int)d->num_share_modes));
1396 static bool delay_for_oplock(files_struct *fsp,
1398 const struct smb2_lease *lease,
1399 struct share_mode_lock *lck,
1400 bool have_sharing_violation,
1401 uint32_t create_disposition,
1402 bool first_open_attempt)
1404 struct share_mode_data *d = lck->data;
1407 bool will_overwrite;
1409 if ((oplock_request & INTERNAL_OPEN_ONLY) ||
1410 is_stat_open(fsp->access_mask)) {
1414 switch (create_disposition) {
1415 case FILE_SUPERSEDE:
1416 case FILE_OVERWRITE:
1417 case FILE_OVERWRITE_IF:
1418 will_overwrite = true;
1421 will_overwrite = false;
1425 for (i=0; i<d->num_share_modes; i++) {
1426 struct share_mode_entry *e = &d->share_modes[i];
1427 struct share_mode_lease *l = NULL;
1428 uint32_t e_lease_type = get_lease_type(d, e);
1430 uint32_t delay_mask = 0;
1432 if (e->op_type == LEASE_OPLOCK) {
1433 l = &d->leases[e->lease_idx];
1436 if (have_sharing_violation) {
1437 delay_mask = SMB2_LEASE_HANDLE;
1439 delay_mask = SMB2_LEASE_WRITE;
1442 break_to = e_lease_type & ~delay_mask;
1444 if (will_overwrite) {
1446 * we'll decide about SMB2_LEASE_READ later.
1448 * Maybe the break will be defered
1450 break_to &= ~SMB2_LEASE_HANDLE;
1453 DEBUG(10, ("entry %u: e_lease_type %u, will_overwrite: %u\n",
1454 (unsigned)i, (unsigned)e_lease_type,
1455 (unsigned)will_overwrite));
1457 if (lease != NULL && l != NULL) {
1460 ign = smb2_lease_equal(fsp_client_guid(fsp),
1469 if ((e_lease_type & ~break_to) == 0) {
1470 if (l != NULL && l->breaking) {
1476 if (share_mode_stale_pid(d, i)) {
1480 if (will_overwrite) {
1482 * If we break anyway break to NONE directly.
1483 * Otherwise vfs_set_filelen() will trigger the
1486 break_to &= ~(SMB2_LEASE_READ|SMB2_LEASE_WRITE);
1489 if (e->op_type != LEASE_OPLOCK) {
1491 * Oplocks only support breaking to R or NONE.
1493 break_to &= ~(SMB2_LEASE_HANDLE|SMB2_LEASE_WRITE);
1496 DEBUG(10, ("breaking from %d to %d\n",
1497 (int)e_lease_type, (int)break_to));
1498 send_break_message(fsp->conn->sconn->msg_ctx, e,
1500 if (e_lease_type & delay_mask) {
1503 if (l != NULL && l->breaking && !first_open_attempt) {
1512 static bool file_has_brlocks(files_struct *fsp)
1514 struct byte_range_lock *br_lck;
1516 br_lck = brl_get_locks_readonly(fsp);
1520 return (brl_num_locks(br_lck) > 0);
1523 int find_share_mode_lease(struct share_mode_data *d,
1524 const struct GUID *client_guid,
1525 const struct smb2_lease_key *key)
1529 for (i=0; i<d->num_leases; i++) {
1530 struct share_mode_lease *l = &d->leases[i];
1532 if (smb2_lease_equal(client_guid,
1543 struct fsp_lease *find_fsp_lease(struct files_struct *new_fsp,
1544 const struct smb2_lease_key *key,
1545 const struct share_mode_lease *l)
1547 struct files_struct *fsp;
1550 * TODO: Measure how expensive this loop is with thousands of open
1554 for (fsp = file_find_di_first(new_fsp->conn->sconn, new_fsp->file_id);
1556 fsp = file_find_di_next(fsp)) {
1558 if (fsp == new_fsp) {
1561 if (fsp->oplock_type != LEASE_OPLOCK) {
1564 if (smb2_lease_key_equal(&fsp->lease->lease.lease_key, key)) {
1565 fsp->lease->ref_count += 1;
1570 /* Not found - must be leased in another smbd. */
1571 new_fsp->lease = talloc_zero(new_fsp->conn->sconn, struct fsp_lease);
1572 if (new_fsp->lease == NULL) {
1575 new_fsp->lease->ref_count = 1;
1576 new_fsp->lease->sconn = new_fsp->conn->sconn;
1577 new_fsp->lease->lease.lease_key = *key;
1578 new_fsp->lease->lease.lease_state = l->current_state;
1580 * We internally treat all leases as V2 and update
1581 * the epoch, but when sending breaks it matters if
1582 * the requesting lease was v1 or v2.
1584 new_fsp->lease->lease.lease_version = l->lease_version;
1585 new_fsp->lease->lease.lease_epoch = l->epoch;
1586 return new_fsp->lease;
1589 static NTSTATUS grant_fsp_lease(struct files_struct *fsp,
1590 struct share_mode_lock *lck,
1591 const struct smb2_lease *lease,
1592 uint32_t *p_lease_idx,
1595 struct share_mode_data *d = lck->data;
1596 const struct GUID *client_guid = fsp_client_guid(fsp);
1597 struct share_mode_lease *tmp;
1601 idx = find_share_mode_lease(d, client_guid, &lease->lease_key);
1604 struct share_mode_lease *l = &d->leases[idx];
1606 uint32_t existing, requested;
1608 fsp->lease = find_fsp_lease(fsp, &lease->lease_key, l);
1609 if (fsp->lease == NULL) {
1610 DEBUG(1, ("Did not find existing lease for file %s\n",
1612 return NT_STATUS_NO_MEMORY;
1618 * Upgrade only if the requested lease is a strict upgrade.
1620 existing = l->current_state;
1621 requested = lease->lease_state;
1624 * Tricky: This test makes sure that "requested" is a
1625 * strict bitwise superset of "existing".
1627 do_upgrade = ((existing & requested) == existing);
1630 * Upgrade only if there's a change.
1632 do_upgrade &= (granted != existing);
1635 * Upgrade only if other leases don't prevent what was asked
1638 do_upgrade &= (granted == requested);
1641 * only upgrade if we are not in breaking state
1643 do_upgrade &= !l->breaking;
1645 DEBUG(10, ("existing=%"PRIu32", requested=%"PRIu32", "
1646 "granted=%"PRIu32", do_upgrade=%d\n",
1647 existing, requested, granted, (int)do_upgrade));
1650 l->current_state = granted;
1654 /* Ensure we're in sync with current lease state. */
1655 fsp_lease_update(lck, fsp_client_guid(fsp), fsp->lease);
1656 return NT_STATUS_OK;
1663 tmp = talloc_realloc(d, d->leases, struct share_mode_lease,
1669 return NT_STATUS_INSUFFICIENT_RESOURCES;
1673 fsp->lease = talloc_zero(fsp->conn->sconn, struct fsp_lease);
1674 if (fsp->lease == NULL) {
1675 return NT_STATUS_INSUFFICIENT_RESOURCES;
1677 fsp->lease->ref_count = 1;
1678 fsp->lease->sconn = fsp->conn->sconn;
1679 fsp->lease->lease.lease_version = lease->lease_version;
1680 fsp->lease->lease.lease_key = lease->lease_key;
1681 fsp->lease->lease.lease_state = granted;
1682 fsp->lease->lease.lease_epoch = lease->lease_epoch + 1;
1684 *p_lease_idx = d->num_leases;
1686 d->leases[d->num_leases] = (struct share_mode_lease) {
1687 .client_guid = *client_guid,
1688 .lease_key = fsp->lease->lease.lease_key,
1689 .current_state = fsp->lease->lease.lease_state,
1690 .lease_version = fsp->lease->lease.lease_version,
1691 .epoch = fsp->lease->lease.lease_epoch,
1694 status = leases_db_add(client_guid,
1697 fsp->conn->connectpath,
1698 fsp->fsp_name->base_name,
1699 fsp->fsp_name->stream_name);
1700 if (!NT_STATUS_IS_OK(status)) {
1701 DEBUG(10, ("%s: leases_db_add failed: %s\n", __func__,
1702 nt_errstr(status)));
1703 TALLOC_FREE(fsp->lease);
1704 return NT_STATUS_INSUFFICIENT_RESOURCES;
1710 return NT_STATUS_OK;
1713 static bool is_same_lease(const files_struct *fsp,
1714 const struct share_mode_data *d,
1715 const struct share_mode_entry *e,
1716 const struct smb2_lease *lease)
1718 if (e->op_type != LEASE_OPLOCK) {
1721 if (lease == NULL) {
1725 return smb2_lease_equal(fsp_client_guid(fsp),
1727 &d->leases[e->lease_idx].client_guid,
1728 &d->leases[e->lease_idx].lease_key);
1731 static NTSTATUS grant_fsp_oplock_type(struct smb_request *req,
1732 struct files_struct *fsp,
1733 struct share_mode_lock *lck,
1735 struct smb2_lease *lease)
1737 struct share_mode_data *d = lck->data;
1738 bool got_handle_lease = false;
1739 bool got_oplock = false;
1742 uint32_t lease_idx = UINT32_MAX;
1746 if (oplock_request & INTERNAL_OPEN_ONLY) {
1747 /* No oplocks on internal open. */
1748 oplock_request = NO_OPLOCK;
1749 DEBUG(10,("grant_fsp_oplock_type: oplock type 0x%x on file %s\n",
1750 fsp->oplock_type, fsp_str_dbg(fsp)));
1753 if (oplock_request == LEASE_OPLOCK) {
1754 if (lease == NULL) {
1756 * The SMB2 layer should have checked this
1758 return NT_STATUS_INTERNAL_ERROR;
1761 granted = lease->lease_state;
1763 if (lp_kernel_oplocks(SNUM(fsp->conn))) {
1764 DEBUG(10, ("No lease granted because kernel oplocks are enabled\n"));
1765 granted = SMB2_LEASE_NONE;
1767 if ((granted & (SMB2_LEASE_READ|SMB2_LEASE_WRITE)) == 0) {
1768 DEBUG(10, ("No read or write lease requested\n"));
1769 granted = SMB2_LEASE_NONE;
1771 if (granted == SMB2_LEASE_WRITE) {
1772 DEBUG(10, ("pure write lease requested\n"));
1773 granted = SMB2_LEASE_NONE;
1775 if (granted == (SMB2_LEASE_WRITE|SMB2_LEASE_HANDLE)) {
1776 DEBUG(10, ("write and handle lease requested\n"));
1777 granted = SMB2_LEASE_NONE;
1780 granted = map_oplock_to_lease_type(
1781 oplock_request & ~SAMBA_PRIVATE_OPLOCK_MASK);
1784 if (lp_locking(fsp->conn->params) && file_has_brlocks(fsp)) {
1785 DEBUG(10,("grant_fsp_oplock_type: file %s has byte range locks\n",
1787 granted &= ~SMB2_LEASE_READ;
1790 for (i=0; i<d->num_share_modes; i++) {
1791 struct share_mode_entry *e = &d->share_modes[i];
1792 uint32_t e_lease_type;
1794 e_lease_type = get_lease_type(d, e);
1796 if ((granted & SMB2_LEASE_WRITE) &&
1797 !is_same_lease(fsp, d, e, lease) &&
1798 !share_mode_stale_pid(d, i)) {
1800 * Can grant only one writer
1802 granted &= ~SMB2_LEASE_WRITE;
1805 if ((e_lease_type & SMB2_LEASE_HANDLE) && !got_handle_lease &&
1806 !share_mode_stale_pid(d, i)) {
1807 got_handle_lease = true;
1810 if ((e->op_type != LEASE_OPLOCK) && !got_oplock &&
1811 !share_mode_stale_pid(d, i)) {
1816 if ((granted & SMB2_LEASE_READ) && !(granted & SMB2_LEASE_WRITE)) {
1818 (global_client_caps & CAP_LEVEL_II_OPLOCKS) &&
1819 lp_level2_oplocks(SNUM(fsp->conn));
1821 if (!allow_level2) {
1822 granted = SMB2_LEASE_NONE;
1826 if (oplock_request == LEASE_OPLOCK) {
1828 granted &= ~SMB2_LEASE_HANDLE;
1831 fsp->oplock_type = LEASE_OPLOCK;
1833 status = grant_fsp_lease(fsp, lck, lease, &lease_idx,
1835 if (!NT_STATUS_IS_OK(status)) {
1839 *lease = fsp->lease->lease;
1840 DEBUG(10, ("lease_state=%d\n", lease->lease_state));
1842 if (got_handle_lease) {
1843 granted = SMB2_LEASE_NONE;
1847 case SMB2_LEASE_READ|SMB2_LEASE_WRITE|SMB2_LEASE_HANDLE:
1848 fsp->oplock_type = BATCH_OPLOCK|EXCLUSIVE_OPLOCK;
1850 case SMB2_LEASE_READ|SMB2_LEASE_WRITE:
1851 fsp->oplock_type = EXCLUSIVE_OPLOCK;
1853 case SMB2_LEASE_READ|SMB2_LEASE_HANDLE:
1854 case SMB2_LEASE_READ:
1855 fsp->oplock_type = LEVEL_II_OPLOCK;
1858 fsp->oplock_type = NO_OPLOCK;
1862 status = set_file_oplock(fsp);
1863 if (!NT_STATUS_IS_OK(status)) {
1865 * Could not get the kernel oplock
1867 fsp->oplock_type = NO_OPLOCK;
1871 ok = set_share_mode(lck, fsp, get_current_uid(fsp->conn),
1876 return NT_STATUS_NO_MEMORY;
1879 ok = update_num_read_oplocks(fsp, lck);
1881 del_share_mode(lck, fsp);
1882 return NT_STATUS_INTERNAL_ERROR;
1885 DEBUG(10,("grant_fsp_oplock_type: oplock type 0x%x on file %s\n",
1886 fsp->oplock_type, fsp_str_dbg(fsp)));
1888 return NT_STATUS_OK;
1891 static bool request_timed_out(struct timeval request_time,
1892 struct timeval timeout)
1894 struct timeval now, end_time;
1896 end_time = timeval_sum(&request_time, &timeout);
1897 return (timeval_compare(&end_time, &now) < 0);
1900 struct defer_open_state {
1901 struct smbXsrv_connection *xconn;
1905 static void defer_open_done(struct tevent_req *req);
1907 /****************************************************************************
1908 Handle the 1 second delay in returning a SHARING_VIOLATION error.
1909 ****************************************************************************/
1911 static void defer_open(struct share_mode_lock *lck,
1912 struct timeval request_time,
1913 struct timeval timeout,
1914 struct smb_request *req,
1915 struct deferred_open_record *state)
1917 struct deferred_open_record *open_rec;
1919 DEBUG(10,("defer_open_sharing_error: time [%u.%06u] adding deferred "
1920 "open entry for mid %llu\n",
1921 (unsigned int)request_time.tv_sec,
1922 (unsigned int)request_time.tv_usec,
1923 (unsigned long long)req->mid));
1925 open_rec = talloc(NULL, struct deferred_open_record);
1926 if (open_rec == NULL) {
1928 exit_server("talloc failed");
1934 struct defer_open_state *watch_state;
1935 struct tevent_req *watch_req;
1938 watch_state = talloc(open_rec, struct defer_open_state);
1939 if (watch_state == NULL) {
1940 exit_server("talloc failed");
1942 watch_state->xconn = req->xconn;
1943 watch_state->mid = req->mid;
1945 DEBUG(10, ("defering mid %llu\n",
1946 (unsigned long long)req->mid));
1948 watch_req = dbwrap_record_watch_send(
1949 watch_state, req->sconn->ev_ctx, lck->data->record,
1950 req->sconn->msg_ctx);
1951 if (watch_req == NULL) {
1952 exit_server("Could not watch share mode record");
1954 tevent_req_set_callback(watch_req, defer_open_done,
1957 ret = tevent_req_set_endtime(
1958 watch_req, req->sconn->ev_ctx,
1959 timeval_sum(&request_time, &timeout));
1963 if (!push_deferred_open_message_smb(req, request_time, timeout,
1964 state->id, open_rec)) {
1966 exit_server("push_deferred_open_message_smb failed");
1970 static void defer_open_done(struct tevent_req *req)
1972 struct defer_open_state *state = tevent_req_callback_data(
1973 req, struct defer_open_state);
1977 status = dbwrap_record_watch_recv(req, talloc_tos(), NULL);
1979 if (!NT_STATUS_IS_OK(status)) {
1980 DEBUG(5, ("dbwrap_record_watch_recv returned %s\n",
1981 nt_errstr(status)));
1983 * Even if it failed, retry anyway. TODO: We need a way to
1984 * tell a re-scheduled open about that error.
1988 DEBUG(10, ("scheduling mid %llu\n", (unsigned long long)state->mid));
1990 ret = schedule_deferred_open_message_smb(state->xconn, state->mid);
1996 /****************************************************************************
1997 On overwrite open ensure that the attributes match.
1998 ****************************************************************************/
2000 static bool open_match_attributes(connection_struct *conn,
2001 uint32_t old_dos_attr,
2002 uint32_t new_dos_attr,
2003 mode_t existing_unx_mode,
2004 mode_t new_unx_mode,
2005 mode_t *returned_unx_mode)
2007 uint32_t noarch_old_dos_attr, noarch_new_dos_attr;
2009 noarch_old_dos_attr = (old_dos_attr & ~FILE_ATTRIBUTE_ARCHIVE);
2010 noarch_new_dos_attr = (new_dos_attr & ~FILE_ATTRIBUTE_ARCHIVE);
2012 if((noarch_old_dos_attr == 0 && noarch_new_dos_attr != 0) ||
2013 (noarch_old_dos_attr != 0 && ((noarch_old_dos_attr & noarch_new_dos_attr) == noarch_old_dos_attr))) {
2014 *returned_unx_mode = new_unx_mode;
2016 *returned_unx_mode = (mode_t)0;
2019 DEBUG(10,("open_match_attributes: old_dos_attr = 0x%x, "
2020 "existing_unx_mode = 0%o, new_dos_attr = 0x%x "
2021 "returned_unx_mode = 0%o\n",
2022 (unsigned int)old_dos_attr,
2023 (unsigned int)existing_unx_mode,
2024 (unsigned int)new_dos_attr,
2025 (unsigned int)*returned_unx_mode ));
2027 /* If we're mapping SYSTEM and HIDDEN ensure they match. */
2028 if (lp_map_system(SNUM(conn)) || lp_store_dos_attributes(SNUM(conn))) {
2029 if ((old_dos_attr & FILE_ATTRIBUTE_SYSTEM) &&
2030 !(new_dos_attr & FILE_ATTRIBUTE_SYSTEM)) {
2034 if (lp_map_hidden(SNUM(conn)) || lp_store_dos_attributes(SNUM(conn))) {
2035 if ((old_dos_attr & FILE_ATTRIBUTE_HIDDEN) &&
2036 !(new_dos_attr & FILE_ATTRIBUTE_HIDDEN)) {
2043 /****************************************************************************
2044 Special FCB or DOS processing in the case of a sharing violation.
2045 Try and find a duplicated file handle.
2046 ****************************************************************************/
2048 static NTSTATUS fcb_or_dos_open(struct smb_request *req,
2049 connection_struct *conn,
2050 files_struct *fsp_to_dup_into,
2051 const struct smb_filename *smb_fname,
2055 uint32_t access_mask,
2056 uint32_t share_access,
2057 uint32_t create_options)
2061 DEBUG(5,("fcb_or_dos_open: attempting old open semantics for "
2062 "file %s.\n", smb_fname_str_dbg(smb_fname)));
2064 for(fsp = file_find_di_first(conn->sconn, id); fsp;
2065 fsp = file_find_di_next(fsp)) {
2067 DEBUG(10,("fcb_or_dos_open: checking file %s, fd = %d, "
2068 "vuid = %llu, file_pid = %u, private_options = 0x%x "
2069 "access_mask = 0x%x\n", fsp_str_dbg(fsp),
2070 fsp->fh->fd, (unsigned long long)fsp->vuid,
2071 (unsigned int)fsp->file_pid,
2072 (unsigned int)fsp->fh->private_options,
2073 (unsigned int)fsp->access_mask ));
2075 if (fsp != fsp_to_dup_into &&
2076 fsp->fh->fd != -1 &&
2077 fsp->vuid == vuid &&
2078 fsp->file_pid == file_pid &&
2079 (fsp->fh->private_options & (NTCREATEX_OPTIONS_PRIVATE_DENY_DOS |
2080 NTCREATEX_OPTIONS_PRIVATE_DENY_FCB)) &&
2081 (fsp->access_mask & FILE_WRITE_DATA) &&
2082 strequal(fsp->fsp_name->base_name, smb_fname->base_name) &&
2083 strequal(fsp->fsp_name->stream_name,
2084 smb_fname->stream_name)) {
2085 DEBUG(10,("fcb_or_dos_open: file match\n"));
2091 return NT_STATUS_NOT_FOUND;
2094 /* quite an insane set of semantics ... */
2095 if (is_executable(smb_fname->base_name) &&
2096 (fsp->fh->private_options & NTCREATEX_OPTIONS_PRIVATE_DENY_DOS)) {
2097 DEBUG(10,("fcb_or_dos_open: file fail due to is_executable.\n"));
2098 return NT_STATUS_INVALID_PARAMETER;
2101 /* We need to duplicate this fsp. */
2102 return dup_file_fsp(req, fsp, access_mask, share_access,
2103 create_options, fsp_to_dup_into);
2106 static void schedule_defer_open(struct share_mode_lock *lck,
2108 struct timeval request_time,
2109 struct smb_request *req)
2111 struct deferred_open_record state;
2113 /* This is a relative time, added to the absolute
2114 request_time value to get the absolute timeout time.
2115 Note that if this is the second or greater time we enter
2116 this codepath for this particular request mid then
2117 request_time is left as the absolute time of the *first*
2118 time this request mid was processed. This is what allows
2119 the request to eventually time out. */
2121 struct timeval timeout;
2123 /* Normally the smbd we asked should respond within
2124 * OPLOCK_BREAK_TIMEOUT seconds regardless of whether
2125 * the client did, give twice the timeout as a safety
2126 * measure here in case the other smbd is stuck
2127 * somewhere else. */
2129 timeout = timeval_set(OPLOCK_BREAK_TIMEOUT*2, 0);
2131 /* Nothing actually uses state.delayed_for_oplocks
2132 but it's handy to differentiate in debug messages
2133 between a 30 second delay due to oplock break, and
2134 a 1 second delay for share mode conflicts. */
2136 state.delayed_for_oplocks = True;
2137 state.async_open = false;
2140 if (!request_timed_out(request_time, timeout)) {
2141 defer_open(lck, request_time, timeout, req, &state);
2145 /****************************************************************************
2146 Reschedule an open call that went asynchronous.
2147 ****************************************************************************/
2149 static void schedule_async_open(struct timeval request_time,
2150 struct smb_request *req)
2152 struct deferred_open_record state;
2153 struct timeval timeout;
2155 timeout = timeval_set(20, 0);
2158 state.delayed_for_oplocks = false;
2159 state.async_open = true;
2161 if (!request_timed_out(request_time, timeout)) {
2162 defer_open(NULL, request_time, timeout, req, &state);
2166 /****************************************************************************
2167 Work out what access_mask to use from what the client sent us.
2168 ****************************************************************************/
2170 static NTSTATUS smbd_calculate_maximum_allowed_access(
2171 connection_struct *conn,
2172 const struct smb_filename *smb_fname,
2174 uint32_t *p_access_mask)
2176 struct security_descriptor *sd;
2177 uint32_t access_granted;
2180 if (!use_privs && (get_current_uid(conn) == (uid_t)0)) {
2181 *p_access_mask |= FILE_GENERIC_ALL;
2182 return NT_STATUS_OK;
2185 status = SMB_VFS_GET_NT_ACL(conn, smb_fname,
2191 if (NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
2193 * File did not exist
2195 *p_access_mask = FILE_GENERIC_ALL;
2196 return NT_STATUS_OK;
2198 if (!NT_STATUS_IS_OK(status)) {
2199 DEBUG(10,("Could not get acl on file %s: %s\n",
2200 smb_fname_str_dbg(smb_fname),
2201 nt_errstr(status)));
2202 return NT_STATUS_ACCESS_DENIED;
2206 * If we can access the path to this file, by
2207 * default we have FILE_READ_ATTRIBUTES from the
2208 * containing directory. See the section:
2209 * "Algorithm to Check Access to an Existing File"
2212 * se_file_access_check()
2213 * also takes care of owner WRITE_DAC and READ_CONTROL.
2215 status = se_file_access_check(sd,
2216 get_current_nttok(conn),
2218 (*p_access_mask & ~FILE_READ_ATTRIBUTES),
2223 if (!NT_STATUS_IS_OK(status)) {
2224 DEBUG(10, ("Access denied on file %s: "
2225 "when calculating maximum access\n",
2226 smb_fname_str_dbg(smb_fname)));
2227 return NT_STATUS_ACCESS_DENIED;
2229 *p_access_mask = (access_granted | FILE_READ_ATTRIBUTES);
2231 if (!(access_granted & DELETE_ACCESS)) {
2232 if (can_delete_file_in_directory(conn, smb_fname)) {
2233 *p_access_mask |= DELETE_ACCESS;
2237 return NT_STATUS_OK;
2240 NTSTATUS smbd_calculate_access_mask(connection_struct *conn,
2241 const struct smb_filename *smb_fname,
2243 uint32_t access_mask,
2244 uint32_t *access_mask_out)
2247 uint32_t orig_access_mask = access_mask;
2248 uint32_t rejected_share_access;
2251 * Convert GENERIC bits to specific bits.
2254 se_map_generic(&access_mask, &file_generic_mapping);
2256 /* Calculate MAXIMUM_ALLOWED_ACCESS if requested. */
2257 if (access_mask & MAXIMUM_ALLOWED_ACCESS) {
2259 status = smbd_calculate_maximum_allowed_access(
2260 conn, smb_fname, use_privs, &access_mask);
2262 if (!NT_STATUS_IS_OK(status)) {
2266 access_mask &= conn->share_access;
2269 rejected_share_access = access_mask & ~(conn->share_access);
2271 if (rejected_share_access) {
2272 DEBUG(10, ("smbd_calculate_access_mask: Access denied on "
2273 "file %s: rejected by share access mask[0x%08X] "
2274 "orig[0x%08X] mapped[0x%08X] reject[0x%08X]\n",
2275 smb_fname_str_dbg(smb_fname),
2277 orig_access_mask, access_mask,
2278 rejected_share_access));
2279 return NT_STATUS_ACCESS_DENIED;
2282 *access_mask_out = access_mask;
2283 return NT_STATUS_OK;
2286 /****************************************************************************
2287 Remove the deferred open entry under lock.
2288 ****************************************************************************/
2290 /****************************************************************************
2291 Return true if this is a state pointer to an asynchronous create.
2292 ****************************************************************************/
2294 bool is_deferred_open_async(const struct deferred_open_record *rec)
2296 return rec->async_open;
2299 static bool clear_ads(uint32_t create_disposition)
2303 switch (create_disposition) {
2304 case FILE_SUPERSEDE:
2305 case FILE_OVERWRITE_IF:
2306 case FILE_OVERWRITE:
2315 static int disposition_to_open_flags(uint32_t create_disposition)
2320 * Currently we're using FILE_SUPERSEDE as the same as
2321 * FILE_OVERWRITE_IF but they really are
2322 * different. FILE_SUPERSEDE deletes an existing file
2323 * (requiring delete access) then recreates it.
2326 switch (create_disposition) {
2327 case FILE_SUPERSEDE:
2328 case FILE_OVERWRITE_IF:
2330 * If file exists replace/overwrite. If file doesn't
2333 ret = O_CREAT|O_TRUNC;
2338 * If file exists open. If file doesn't exist error.
2343 case FILE_OVERWRITE:
2345 * If file exists overwrite. If file doesn't exist
2353 * If file exists error. If file doesn't exist create.
2355 ret = O_CREAT|O_EXCL;
2360 * If file exists open. If file doesn't exist create.
2368 static int calculate_open_access_flags(uint32_t access_mask,
2369 uint32_t private_flags)
2371 bool need_write, need_read;
2374 * Note that we ignore the append flag as append does not
2375 * mean the same thing under DOS and Unix.
2378 need_write = (access_mask & (FILE_WRITE_DATA | FILE_APPEND_DATA));
2383 /* DENY_DOS opens are always underlying read-write on the
2384 file handle, no matter what the requested access mask
2388 ((private_flags & NTCREATEX_OPTIONS_PRIVATE_DENY_DOS) ||
2389 access_mask & (FILE_READ_ATTRIBUTES|FILE_READ_DATA|
2390 FILE_READ_EA|FILE_EXECUTE));
2398 /****************************************************************************
2399 Open a file with a share mode. Passed in an already created files_struct *.
2400 ****************************************************************************/
2402 static NTSTATUS open_file_ntcreate(connection_struct *conn,
2403 struct smb_request *req,
2404 uint32_t access_mask, /* access bits (FILE_READ_DATA etc.) */
2405 uint32_t share_access, /* share constants (FILE_SHARE_READ etc) */
2406 uint32_t create_disposition, /* FILE_OPEN_IF etc. */
2407 uint32_t create_options, /* options such as delete on close. */
2408 uint32_t new_dos_attributes, /* attributes used for new file. */
2409 int oplock_request, /* internal Samba oplock codes. */
2410 struct smb2_lease *lease,
2411 /* Information (FILE_EXISTS etc.) */
2412 uint32_t private_flags, /* Samba specific flags. */
2416 struct smb_filename *smb_fname = fsp->fsp_name;
2419 bool file_existed = VALID_STAT(smb_fname->st);
2420 bool def_acl = False;
2421 bool posix_open = False;
2422 bool new_file_created = False;
2423 bool first_open_attempt = true;
2424 NTSTATUS fsp_open = NT_STATUS_ACCESS_DENIED;
2425 mode_t new_unx_mode = (mode_t)0;
2426 mode_t unx_mode = (mode_t)0;
2428 uint32_t existing_dos_attributes = 0;
2429 struct timeval request_time = timeval_zero();
2430 struct share_mode_lock *lck = NULL;
2431 uint32_t open_access_mask = access_mask;
2434 SMB_STRUCT_STAT saved_stat = smb_fname->st;
2435 struct timespec old_write_time;
2438 if (conn->printer) {
2440 * Printers are handled completely differently.
2441 * Most of the passed parameters are ignored.
2445 *pinfo = FILE_WAS_CREATED;
2448 DEBUG(10, ("open_file_ntcreate: printer open fname=%s\n",
2449 smb_fname_str_dbg(smb_fname)));
2452 DEBUG(0,("open_file_ntcreate: printer open without "
2453 "an SMB request!\n"));
2454 return NT_STATUS_INTERNAL_ERROR;
2457 return print_spool_open(fsp, smb_fname->base_name,
2461 if (!parent_dirname(talloc_tos(), smb_fname->base_name, &parent_dir,
2463 return NT_STATUS_NO_MEMORY;
2466 if (new_dos_attributes & FILE_FLAG_POSIX_SEMANTICS) {
2468 unx_mode = (mode_t)(new_dos_attributes & ~FILE_FLAG_POSIX_SEMANTICS);
2469 new_dos_attributes = 0;
2471 /* Windows allows a new file to be created and
2472 silently removes a FILE_ATTRIBUTE_DIRECTORY
2473 sent by the client. Do the same. */
2475 new_dos_attributes &= ~FILE_ATTRIBUTE_DIRECTORY;
2477 /* We add FILE_ATTRIBUTE_ARCHIVE to this as this mode is only used if the file is
2479 unx_mode = unix_mode(conn, new_dos_attributes | FILE_ATTRIBUTE_ARCHIVE,
2480 smb_fname, parent_dir);
2483 DEBUG(10, ("open_file_ntcreate: fname=%s, dos_attrs=0x%x "
2484 "access_mask=0x%x share_access=0x%x "
2485 "create_disposition = 0x%x create_options=0x%x "
2486 "unix mode=0%o oplock_request=%d private_flags = 0x%x\n",
2487 smb_fname_str_dbg(smb_fname), new_dos_attributes,
2488 access_mask, share_access, create_disposition,
2489 create_options, (unsigned int)unx_mode, oplock_request,
2490 (unsigned int)private_flags));
2493 /* Ensure req == NULL means INTERNAL_OPEN_ONLY */
2494 SMB_ASSERT(((oplock_request & INTERNAL_OPEN_ONLY) != 0));
2496 /* And req != NULL means no INTERNAL_OPEN_ONLY */
2497 SMB_ASSERT(((oplock_request & INTERNAL_OPEN_ONLY) == 0));
2501 * Only non-internal opens can be deferred at all
2505 struct deferred_open_record *open_rec;
2506 if (get_deferred_open_message_state(req,
2509 /* Remember the absolute time of the original
2510 request with this mid. We'll use it later to
2511 see if this has timed out. */
2513 /* If it was an async create retry, the file
2516 if (is_deferred_open_async(open_rec)) {
2517 SET_STAT_INVALID(smb_fname->st);
2518 file_existed = false;
2521 /* Ensure we don't reprocess this message. */
2522 remove_deferred_open_message_smb(req->xconn, req->mid);
2524 first_open_attempt = false;
2529 new_dos_attributes &= SAMBA_ATTRIBUTES_MASK;
2531 existing_dos_attributes = dos_mode(conn, smb_fname);
2535 /* ignore any oplock requests if oplocks are disabled */
2536 if (!lp_oplocks(SNUM(conn)) ||
2537 IS_VETO_OPLOCK_PATH(conn, smb_fname->base_name)) {
2538 /* Mask off everything except the private Samba bits. */
2539 oplock_request &= SAMBA_PRIVATE_OPLOCK_MASK;
2542 /* this is for OS/2 long file names - say we don't support them */
2543 if (req != NULL && !req->posix_pathnames &&
2544 strstr(smb_fname->base_name,".+,;=[].")) {
2545 /* OS/2 Workplace shell fix may be main code stream in a later
2547 DEBUG(5,("open_file_ntcreate: OS/2 long filenames are not "
2549 if (use_nt_status()) {
2550 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
2552 return NT_STATUS_DOS(ERRDOS, ERRcannotopen);
2555 switch( create_disposition ) {
2557 /* If file exists open. If file doesn't exist error. */
2558 if (!file_existed) {
2559 DEBUG(5,("open_file_ntcreate: FILE_OPEN "
2560 "requested for file %s and file "
2562 smb_fname_str_dbg(smb_fname)));
2564 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
2568 case FILE_OVERWRITE:
2569 /* If file exists overwrite. If file doesn't exist
2571 if (!file_existed) {
2572 DEBUG(5,("open_file_ntcreate: FILE_OVERWRITE "
2573 "requested for file %s and file "
2575 smb_fname_str_dbg(smb_fname) ));
2577 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
2582 /* If file exists error. If file doesn't exist
2585 DEBUG(5,("open_file_ntcreate: FILE_CREATE "
2586 "requested for file %s and file "
2587 "already exists.\n",
2588 smb_fname_str_dbg(smb_fname)));
2589 if (S_ISDIR(smb_fname->st.st_ex_mode)) {
2594 return map_nt_error_from_unix(errno);
2598 case FILE_SUPERSEDE:
2599 case FILE_OVERWRITE_IF:
2603 return NT_STATUS_INVALID_PARAMETER;
2606 flags2 = disposition_to_open_flags(create_disposition);
2608 /* We only care about matching attributes on file exists and
2611 if (!posix_open && file_existed &&
2612 ((create_disposition == FILE_OVERWRITE) ||
2613 (create_disposition == FILE_OVERWRITE_IF))) {
2614 if (!open_match_attributes(conn, existing_dos_attributes,
2616 smb_fname->st.st_ex_mode,
2617 unx_mode, &new_unx_mode)) {
2618 DEBUG(5,("open_file_ntcreate: attributes missmatch "
2619 "for file %s (%x %x) (0%o, 0%o)\n",
2620 smb_fname_str_dbg(smb_fname),
2621 existing_dos_attributes,
2623 (unsigned int)smb_fname->st.st_ex_mode,
2624 (unsigned int)unx_mode ));
2626 return NT_STATUS_ACCESS_DENIED;
2630 status = smbd_calculate_access_mask(conn, smb_fname,
2634 if (!NT_STATUS_IS_OK(status)) {
2635 DEBUG(10, ("open_file_ntcreate: smbd_calculate_access_mask "
2636 "on file %s returned %s\n",
2637 smb_fname_str_dbg(smb_fname), nt_errstr(status)));
2641 open_access_mask = access_mask;
2643 if (flags2 & O_TRUNC) {
2644 open_access_mask |= FILE_WRITE_DATA; /* This will cause oplock breaks. */
2647 DEBUG(10, ("open_file_ntcreate: fname=%s, after mapping "
2648 "access_mask=0x%x\n", smb_fname_str_dbg(smb_fname),
2652 * Note that we ignore the append flag as append does not
2653 * mean the same thing under DOS and Unix.
2656 flags = calculate_open_access_flags(access_mask, private_flags);
2659 * Currently we only look at FILE_WRITE_THROUGH for create options.
2663 if ((create_options & FILE_WRITE_THROUGH) && lp_strict_sync(SNUM(conn))) {
2668 if (posix_open && (access_mask & FILE_APPEND_DATA)) {
2672 if (!posix_open && !CAN_WRITE(conn)) {
2674 * We should really return a permission denied error if either
2675 * O_CREAT or O_TRUNC are set, but for compatibility with
2676 * older versions of Samba we just AND them out.
2678 flags2 &= ~(O_CREAT|O_TRUNC);
2681 if (first_open_attempt && lp_kernel_oplocks(SNUM(conn))) {
2683 * With kernel oplocks the open breaking an oplock
2684 * blocks until the oplock holder has given up the
2685 * oplock or closed the file. We prevent this by first
2686 * trying to open the file with O_NONBLOCK (see "man
2687 * fcntl" on Linux). For the second try, triggered by
2688 * an oplock break response, we do not need this
2691 * This is true under the assumption that only Samba
2692 * requests kernel oplocks. Once someone else like
2693 * NFSv4 starts to use that API, we will have to
2694 * modify this by communicating with the NFSv4 server.
2696 flags2 |= O_NONBLOCK;
2700 * Ensure we can't write on a read-only share or file.
2703 if (flags != O_RDONLY && file_existed &&
2704 (!CAN_WRITE(conn) || IS_DOS_READONLY(existing_dos_attributes))) {
2705 DEBUG(5,("open_file_ntcreate: write access requested for "
2706 "file %s on read only %s\n",
2707 smb_fname_str_dbg(smb_fname),
2708 !CAN_WRITE(conn) ? "share" : "file" ));
2710 return NT_STATUS_ACCESS_DENIED;
2713 fsp->file_id = vfs_file_id_from_sbuf(conn, &smb_fname->st);
2714 fsp->share_access = share_access;
2715 fsp->fh->private_options = private_flags;
2716 fsp->access_mask = open_access_mask; /* We change this to the
2717 * requested access_mask after
2718 * the open is done. */
2720 fsp->posix_flags |= FSP_POSIX_FLAGS_ALL;
2723 if (timeval_is_zero(&request_time)) {
2724 request_time = fsp->open_time;
2728 * Ensure we pay attention to default ACLs on directories if required.
2731 if ((flags2 & O_CREAT) && lp_inherit_acls(SNUM(conn)) &&
2732 (def_acl = directory_has_default_acl(conn, parent_dir))) {
2733 unx_mode = (0777 & lp_create_mask(SNUM(conn)));
2736 DEBUG(4,("calling open_file with flags=0x%X flags2=0x%X mode=0%o, "
2737 "access_mask = 0x%x, open_access_mask = 0x%x\n",
2738 (unsigned int)flags, (unsigned int)flags2,
2739 (unsigned int)unx_mode, (unsigned int)access_mask,
2740 (unsigned int)open_access_mask));
2742 fsp_open = open_file(fsp, conn, req, parent_dir,
2743 flags|flags2, unx_mode, access_mask,
2744 open_access_mask, &new_file_created);
2746 if (NT_STATUS_EQUAL(fsp_open, NT_STATUS_NETWORK_BUSY)) {
2747 struct deferred_open_record state;
2750 * EWOULDBLOCK/EAGAIN maps to NETWORK_BUSY.
2752 if (file_existed && S_ISFIFO(fsp->fsp_name->st.st_ex_mode)) {
2753 DEBUG(10, ("FIFO busy\n"));
2754 return NT_STATUS_NETWORK_BUSY;
2757 DEBUG(10, ("Internal open busy\n"));
2758 return NT_STATUS_NETWORK_BUSY;
2762 * From here on we assume this is an oplock break triggered
2765 lck = get_existing_share_mode_lock(talloc_tos(), fsp->file_id);
2767 state.delayed_for_oplocks = false;
2768 state.async_open = false;
2769 state.id = fsp->file_id;
2770 defer_open(NULL, request_time, timeval_set(0, 0),
2772 DEBUG(10, ("No share mode lock found after "
2773 "EWOULDBLOCK, retrying sync\n"));
2774 return NT_STATUS_SHARING_VIOLATION;
2777 if (!validate_oplock_types(lck)) {
2778 smb_panic("validate_oplock_types failed");
2781 if (delay_for_oplock(fsp, 0, lease, lck, false,
2782 create_disposition, first_open_attempt)) {
2783 schedule_defer_open(lck, fsp->file_id, request_time,
2786 DEBUG(10, ("Sent oplock break request to kernel "
2787 "oplock holder\n"));
2788 return NT_STATUS_SHARING_VIOLATION;
2792 * No oplock from Samba around. Immediately retry with
2795 state.delayed_for_oplocks = false;
2796 state.async_open = false;
2797 state.id = fsp->file_id;
2798 defer_open(lck, request_time, timeval_set(0, 0), req, &state);
2800 DEBUG(10, ("No Samba oplock around after EWOULDBLOCK. "
2801 "Retrying sync\n"));
2802 return NT_STATUS_SHARING_VIOLATION;
2805 if (!NT_STATUS_IS_OK(fsp_open)) {
2806 if (NT_STATUS_EQUAL(fsp_open, NT_STATUS_RETRY)) {
2807 schedule_async_open(request_time, req);
2812 if (new_file_created) {
2814 * As we atomically create using O_CREAT|O_EXCL,
2815 * then if new_file_created is true, then
2816 * file_existed *MUST* have been false (even
2817 * if the file was previously detected as being
2820 file_existed = false;
2823 if (file_existed && !check_same_dev_ino(&saved_stat, &smb_fname->st)) {
2825 * The file did exist, but some other (local or NFS)
2826 * process either renamed/unlinked and re-created the
2827 * file with different dev/ino after we walked the path,
2828 * but before we did the open. We could retry the
2829 * open but it's a rare enough case it's easier to
2830 * just fail the open to prevent creating any problems
2831 * in the open file db having the wrong dev/ino key.
2834 DEBUG(1,("open_file_ntcreate: file %s - dev/ino mismatch. "
2835 "Old (dev=0x%llu, ino =0x%llu). "
2836 "New (dev=0x%llu, ino=0x%llu). Failing open "
2837 " with NT_STATUS_ACCESS_DENIED.\n",
2838 smb_fname_str_dbg(smb_fname),
2839 (unsigned long long)saved_stat.st_ex_dev,
2840 (unsigned long long)saved_stat.st_ex_ino,
2841 (unsigned long long)smb_fname->st.st_ex_dev,
2842 (unsigned long long)smb_fname->st.st_ex_ino));
2843 return NT_STATUS_ACCESS_DENIED;
2846 old_write_time = smb_fname->st.st_ex_mtime;
2849 * Deal with the race condition where two smbd's detect the
2850 * file doesn't exist and do the create at the same time. One
2851 * of them will win and set a share mode, the other (ie. this
2852 * one) should check if the requested share mode for this
2853 * create is allowed.
2857 * Now the file exists and fsp is successfully opened,
2858 * fsp->dev and fsp->inode are valid and should replace the
2859 * dev=0,inode=0 from a non existent file. Spotted by
2860 * Nadav Danieli <nadavd@exanet.com>. JRA.
2865 lck = get_share_mode_lock(talloc_tos(), id,
2867 smb_fname, &old_write_time);
2870 DEBUG(0, ("open_file_ntcreate: Could not get share "
2871 "mode lock for %s\n",
2872 smb_fname_str_dbg(smb_fname)));
2874 return NT_STATUS_SHARING_VIOLATION;
2877 /* Get the types we need to examine. */
2878 if (!validate_oplock_types(lck)) {
2879 smb_panic("validate_oplock_types failed");
2882 if (has_delete_on_close(lck, fsp->name_hash)) {
2885 return NT_STATUS_DELETE_PENDING;
2888 status = open_mode_check(conn, lck,
2889 access_mask, share_access);
2891 if (NT_STATUS_EQUAL(status, NT_STATUS_SHARING_VIOLATION) ||
2892 (lck->data->num_share_modes > 0)) {
2894 * This comes from ancient times out of open_mode_check. I
2895 * have no clue whether this is still necessary. I can't think
2896 * of a case where this would actually matter further down in
2897 * this function. I leave it here for further investigation
2900 file_existed = true;
2903 if ((req != NULL) &&
2905 fsp, oplock_request, lease, lck,
2906 NT_STATUS_EQUAL(status, NT_STATUS_SHARING_VIOLATION),
2907 create_disposition, first_open_attempt)) {
2908 schedule_defer_open(lck, fsp->file_id, request_time, req);
2911 return NT_STATUS_SHARING_VIOLATION;
2914 if (!NT_STATUS_IS_OK(status)) {
2915 uint32_t can_access_mask;
2916 bool can_access = True;
2918 SMB_ASSERT(NT_STATUS_EQUAL(status, NT_STATUS_SHARING_VIOLATION));
2920 /* Check if this can be done with the deny_dos and fcb
2923 (NTCREATEX_OPTIONS_PRIVATE_DENY_DOS|
2924 NTCREATEX_OPTIONS_PRIVATE_DENY_FCB)) {
2926 DEBUG(0, ("DOS open without an SMB "
2930 return NT_STATUS_INTERNAL_ERROR;
2933 /* Use the client requested access mask here,
2934 * not the one we open with. */
2935 status = fcb_or_dos_open(req,
2946 if (NT_STATUS_IS_OK(status)) {
2949 *pinfo = FILE_WAS_OPENED;
2951 return NT_STATUS_OK;
2956 * This next line is a subtlety we need for
2957 * MS-Access. If a file open will fail due to share
2958 * permissions and also for security (access) reasons,
2959 * we need to return the access failed error, not the
2960 * share error. We can't open the file due to kernel
2961 * oplock deadlock (it's possible we failed above on
2962 * the open_mode_check()) so use a userspace check.
2965 if (flags & O_RDWR) {
2966 can_access_mask = FILE_READ_DATA|FILE_WRITE_DATA;
2967 } else if (flags & O_WRONLY) {
2968 can_access_mask = FILE_WRITE_DATA;
2970 can_access_mask = FILE_READ_DATA;
2973 if (((can_access_mask & FILE_WRITE_DATA) &&
2974 !CAN_WRITE(conn)) ||
2975 !NT_STATUS_IS_OK(smbd_check_access_rights(conn,
2978 can_access_mask))) {
2983 * If we're returning a share violation, ensure we
2984 * cope with the braindead 1 second delay (SMB1 only).
2987 if (!(oplock_request & INTERNAL_OPEN_ONLY) &&
2988 !conn->sconn->using_smb2 &&
2989 lp_defer_sharing_violations()) {
2990 struct timeval timeout;
2991 struct deferred_open_record state;
2994 /* this is a hack to speed up torture tests
2996 timeout_usecs = lp_parm_int(SNUM(conn),
2997 "smbd","sharedelay",
2998 SHARING_VIOLATION_USEC_WAIT);
3000 /* This is a relative time, added to the absolute
3001 request_time value to get the absolute timeout time.
3002 Note that if this is the second or greater time we enter
3003 this codepath for this particular request mid then
3004 request_time is left as the absolute time of the *first*
3005 time this request mid was processed. This is what allows
3006 the request to eventually time out. */
3008 timeout = timeval_set(0, timeout_usecs);
3010 /* Nothing actually uses state.delayed_for_oplocks
3011 but it's handy to differentiate in debug messages
3012 between a 30 second delay due to oplock break, and
3013 a 1 second delay for share mode conflicts. */
3015 state.delayed_for_oplocks = False;
3016 state.async_open = false;
3020 && !request_timed_out(request_time,
3022 defer_open(lck, request_time, timeout,
3031 * We have detected a sharing violation here
3032 * so return the correct error code
3034 status = NT_STATUS_SHARING_VIOLATION;
3036 status = NT_STATUS_ACCESS_DENIED;
3041 /* Should we atomically (to the client at least) truncate ? */
3042 if ((!new_file_created) &&
3043 (flags2 & O_TRUNC) &&
3044 (!S_ISFIFO(fsp->fsp_name->st.st_ex_mode))) {
3047 ret = vfs_set_filelen(fsp, 0);
3049 status = map_nt_error_from_unix(errno);
3057 * We have the share entry *locked*.....
3060 /* Delete streams if create_disposition requires it */
3061 if (!new_file_created && clear_ads(create_disposition) &&
3062 !is_ntfs_stream_smb_fname(smb_fname)) {
3063 status = delete_all_streams(conn, smb_fname);
3064 if (!NT_STATUS_IS_OK(status)) {
3071 /* note that we ignore failure for the following. It is
3072 basically a hack for NFS, and NFS will never set one of
3073 these only read them. Nobody but Samba can ever set a deny
3074 mode and we have already checked our more authoritative
3075 locking database for permission to set this deny mode. If
3076 the kernel refuses the operations then the kernel is wrong.
3077 note that GPFS supports it as well - jmcd */
3079 if (fsp->fh->fd != -1 && lp_kernel_share_modes(SNUM(conn))) {
3082 * Beware: streams implementing VFS modules may
3083 * implement streams in a way that fsp will have the
3084 * basefile open in the fsp fd, so lacking a distinct
3085 * fd for the stream kernel_flock will apply on the
3086 * basefile which is wrong. The actual check is
3087 * deffered to the VFS module implementing the
3088 * kernel_flock call.
3090 ret_flock = SMB_VFS_KERNEL_FLOCK(fsp, share_access, access_mask);
3091 if(ret_flock == -1 ){
3096 return NT_STATUS_SHARING_VIOLATION;
3101 * At this point onwards, we can guarantee that the share entry
3102 * is locked, whether we created the file or not, and that the
3103 * deny mode is compatible with all current opens.
3107 * According to Samba4, SEC_FILE_READ_ATTRIBUTE is always granted,
3108 * but we don't have to store this - just ignore it on access check.
3110 if (conn->sconn->using_smb2) {
3112 * SMB2 doesn't return it (according to Microsoft tests).
3113 * Test Case: TestSuite_ScenarioNo009GrantedAccessTestS0
3114 * File created with access = 0x7 (Read, Write, Delete)
3115 * Query Info on file returns 0x87 (Read, Write, Delete, Read Attributes)
3117 fsp->access_mask = access_mask;
3119 /* But SMB1 does. */
3120 fsp->access_mask = access_mask | FILE_READ_ATTRIBUTES;
3125 * stat opens on existing files don't get oplocks.
3126 * They can get leases.
3128 * Note that we check for stat open on the *open_access_mask*,
3129 * i.e. the access mask we actually used to do the open,
3130 * not the one the client asked for (which is in
3131 * fsp->access_mask). This is due to the fact that
3132 * FILE_OVERWRITE and FILE_OVERWRITE_IF add in O_TRUNC,
3133 * which adds FILE_WRITE_DATA to open_access_mask.
3135 if (is_stat_open(open_access_mask) && lease == NULL) {
3136 oplock_request = NO_OPLOCK;
3140 if (new_file_created) {
3141 info = FILE_WAS_CREATED;
3143 if (flags2 & O_TRUNC) {
3144 info = FILE_WAS_OVERWRITTEN;
3146 info = FILE_WAS_OPENED;
3155 * Setup the oplock info in both the shared memory and
3158 status = grant_fsp_oplock_type(req, fsp, lck, oplock_request, lease);
3159 if (!NT_STATUS_IS_OK(status)) {
3165 /* Handle strange delete on close create semantics. */
3166 if (create_options & FILE_DELETE_ON_CLOSE) {
3168 status = can_set_delete_on_close(fsp, new_dos_attributes);
3170 if (!NT_STATUS_IS_OK(status)) {
3171 /* Remember to delete the mode we just added. */
3172 del_share_mode(lck, fsp);
3177 /* Note that here we set the *inital* delete on close flag,
3178 not the regular one. The magic gets handled in close. */
3179 fsp->initial_delete_on_close = True;
3182 if (info != FILE_WAS_OPENED) {
3183 /* Overwritten files should be initially set as archive */
3184 if ((info == FILE_WAS_OVERWRITTEN && lp_map_archive(SNUM(conn))) ||
3185 lp_store_dos_attributes(SNUM(conn))) {
3187 if (file_set_dosmode(conn, smb_fname,
3188 new_dos_attributes | FILE_ATTRIBUTE_ARCHIVE,
3189 parent_dir, true) == 0) {
3190 unx_mode = smb_fname->st.st_ex_mode;
3196 /* Determine sparse flag. */
3198 /* POSIX opens are sparse by default. */
3199 fsp->is_sparse = true;
3201 fsp->is_sparse = (file_existed &&
3202 (existing_dos_attributes & FILE_ATTRIBUTE_SPARSE));
3206 * Take care of inherited ACLs on created files - if default ACL not
3210 if (!posix_open && new_file_created && !def_acl) {
3212 int saved_errno = errno; /* We might get ENOSYS in the next
3215 if (SMB_VFS_FCHMOD_ACL(fsp, unx_mode) == -1 &&
3217 errno = saved_errno; /* Ignore ENOSYS */
3220 } else if (new_unx_mode) {
3224 /* Attributes need changing. File already existed. */
3227 int saved_errno = errno; /* We might get ENOSYS in the
3229 ret = SMB_VFS_FCHMOD_ACL(fsp, new_unx_mode);
3231 if (ret == -1 && errno == ENOSYS) {
3232 errno = saved_errno; /* Ignore ENOSYS */
3234 DEBUG(5, ("open_file_ntcreate: reset "
3235 "attributes of file %s to 0%o\n",
3236 smb_fname_str_dbg(smb_fname),
3237 (unsigned int)new_unx_mode));
3238 ret = 0; /* Don't do the fchmod below. */
3243 (SMB_VFS_FCHMOD(fsp, new_unx_mode) == -1))
3244 DEBUG(5, ("open_file_ntcreate: failed to reset "
3245 "attributes of file %s to 0%o\n",
3246 smb_fname_str_dbg(smb_fname),
3247 (unsigned int)new_unx_mode));
3252 * Deal with other opens having a modified write time.
3254 struct timespec write_time = get_share_mode_write_time(lck);
3256 if (!null_timespec(write_time)) {
3257 update_stat_ex_mtime(&fsp->fsp_name->st, write_time);
3263 return NT_STATUS_OK;
3266 static NTSTATUS mkdir_internal(connection_struct *conn,
3267 struct smb_filename *smb_dname,
3268 uint32_t file_attributes)
3271 char *parent_dir = NULL;
3273 bool posix_open = false;
3274 bool need_re_stat = false;
3275 uint32_t access_mask = SEC_DIR_ADD_SUBDIR;
3277 if (!CAN_WRITE(conn) || (access_mask & ~(conn->share_access))) {
3278 DEBUG(5,("mkdir_internal: failing share access "
3279 "%s\n", lp_servicename(talloc_tos(), SNUM(conn))));
3280 return NT_STATUS_ACCESS_DENIED;
3283 if (!parent_dirname(talloc_tos(), smb_dname->base_name, &parent_dir,
3285 return NT_STATUS_NO_MEMORY;
3288 if (file_attributes & FILE_FLAG_POSIX_SEMANTICS) {
3290 mode = (mode_t)(file_attributes & ~FILE_FLAG_POSIX_SEMANTICS);
3292 mode = unix_mode(conn, FILE_ATTRIBUTE_DIRECTORY, smb_dname, parent_dir);
3295 status = check_parent_access(conn,
3298 if(!NT_STATUS_IS_OK(status)) {
3299 DEBUG(5,("mkdir_internal: check_parent_access "
3300 "on directory %s for path %s returned %s\n",
3302 smb_dname->base_name,
3303 nt_errstr(status) ));
3307 if (SMB_VFS_MKDIR(conn, smb_dname, mode) != 0) {
3308 return map_nt_error_from_unix(errno);
3311 /* Ensure we're checking for a symlink here.... */
3312 /* We don't want to get caught by a symlink racer. */
3314 if (SMB_VFS_LSTAT(conn, smb_dname) == -1) {
3315 DEBUG(2, ("Could not stat directory '%s' just created: %s\n",
3316 smb_fname_str_dbg(smb_dname), strerror(errno)));
3317 return map_nt_error_from_unix(errno);
3320 if (!S_ISDIR(smb_dname->st.st_ex_mode)) {
3321 DEBUG(0, ("Directory '%s' just created is not a directory !\n",
3322 smb_fname_str_dbg(smb_dname)));
3323 return NT_STATUS_NOT_A_DIRECTORY;
3326 if (lp_store_dos_attributes(SNUM(conn))) {
3328 file_set_dosmode(conn, smb_dname,
3329 file_attributes | FILE_ATTRIBUTE_DIRECTORY,
3334 if (lp_inherit_permissions(SNUM(conn))) {
3335 inherit_access_posix_acl(conn, parent_dir,
3336 smb_dname->base_name, mode);
3337 need_re_stat = true;
3342 * Check if high bits should have been set,
3343 * then (if bits are missing): add them.
3344 * Consider bits automagically set by UNIX, i.e. SGID bit from parent
3347 if ((mode & ~(S_IRWXU|S_IRWXG|S_IRWXO)) &&
3348 (mode & ~smb_dname->st.st_ex_mode)) {
3349 SMB_VFS_CHMOD(conn, smb_dname,
3350 (smb_dname->st.st_ex_mode |
3351 (mode & ~smb_dname->st.st_ex_mode)));
3352 need_re_stat = true;
3356 /* Change the owner if required. */
3357 if (lp_inherit_owner(SNUM(conn))) {
3358 change_dir_owner_to_parent(conn, parent_dir,
3359 smb_dname->base_name,
3361 need_re_stat = true;
3365 if (SMB_VFS_LSTAT(conn, smb_dname) == -1) {
3366 DEBUG(2, ("Could not stat directory '%s' just created: %s\n",
3367 smb_fname_str_dbg(smb_dname), strerror(errno)));
3368 return map_nt_error_from_unix(errno);
3372 notify_fname(conn, NOTIFY_ACTION_ADDED, FILE_NOTIFY_CHANGE_DIR_NAME,
3373 smb_dname->base_name);
3375 return NT_STATUS_OK;
3378 /****************************************************************************
3379 Open a directory from an NT SMB call.
3380 ****************************************************************************/
3382 static NTSTATUS open_directory(connection_struct *conn,
3383 struct smb_request *req,
3384 struct smb_filename *smb_dname,
3385 uint32_t access_mask,
3386 uint32_t share_access,
3387 uint32_t create_disposition,
3388 uint32_t create_options,
3389 uint32_t file_attributes,
3391 files_struct **result)
3393 files_struct *fsp = NULL;
3394 bool dir_existed = VALID_STAT(smb_dname->st) ? True : False;
3395 struct share_mode_lock *lck = NULL;
3397 struct timespec mtimespec;
3401 if (is_ntfs_stream_smb_fname(smb_dname)) {
3402 DEBUG(2, ("open_directory: %s is a stream name!\n",
3403 smb_fname_str_dbg(smb_dname)));
3404 return NT_STATUS_NOT_A_DIRECTORY;
3407 if (!(file_attributes & FILE_FLAG_POSIX_SEMANTICS)) {
3408 /* Ensure we have a directory attribute. */
3409 file_attributes |= FILE_ATTRIBUTE_DIRECTORY;
3412 DEBUG(5,("open_directory: opening directory %s, access_mask = 0x%x, "
3413 "share_access = 0x%x create_options = 0x%x, "
3414 "create_disposition = 0x%x, file_attributes = 0x%x\n",
3415 smb_fname_str_dbg(smb_dname),
3416 (unsigned int)access_mask,
3417 (unsigned int)share_access,
3418 (unsigned int)create_options,
3419 (unsigned int)create_disposition,
3420 (unsigned int)file_attributes));
3422 status = smbd_calculate_access_mask(conn, smb_dname, false,
3423 access_mask, &access_mask);
3424 if (!NT_STATUS_IS_OK(status)) {
3425 DEBUG(10, ("open_directory: smbd_calculate_access_mask "
3426 "on file %s returned %s\n",
3427 smb_fname_str_dbg(smb_dname),
3428 nt_errstr(status)));
3432 if ((access_mask & SEC_FLAG_SYSTEM_SECURITY) &&
3433 !security_token_has_privilege(get_current_nttok(conn),
3434 SEC_PRIV_SECURITY)) {
3435 DEBUG(10, ("open_directory: open on %s "
3436 "failed - SEC_FLAG_SYSTEM_SECURITY denied.\n",
3437 smb_fname_str_dbg(smb_dname)));
3438 return NT_STATUS_PRIVILEGE_NOT_HELD;
3441 switch( create_disposition ) {
3445 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3448 info = FILE_WAS_OPENED;
3453 /* If directory exists error. If directory doesn't
3457 status = NT_STATUS_OBJECT_NAME_COLLISION;
3458 DEBUG(2, ("open_directory: unable to create "
3459 "%s. Error was %s\n",
3460 smb_fname_str_dbg(smb_dname),
3461 nt_errstr(status)));
3465 status = mkdir_internal(conn, smb_dname,
3468 if (!NT_STATUS_IS_OK(status)) {
3469 DEBUG(2, ("open_directory: unable to create "
3470 "%s. Error was %s\n",
3471 smb_fname_str_dbg(smb_dname),
3472 nt_errstr(status)));
3476 info = FILE_WAS_CREATED;
3481 * If directory exists open. If directory doesn't
3486 status = NT_STATUS_OK;
3487 info = FILE_WAS_OPENED;
3489 status = mkdir_internal(conn, smb_dname,
3492 if (NT_STATUS_IS_OK(status)) {
3493 info = FILE_WAS_CREATED;
3495 /* Cope with create race. */
3496 if (!NT_STATUS_EQUAL(status,
3497 NT_STATUS_OBJECT_NAME_COLLISION)) {
3498 DEBUG(2, ("open_directory: unable to create "
3499 "%s. Error was %s\n",
3500 smb_fname_str_dbg(smb_dname),
3501 nt_errstr(status)));
3506 * If mkdir_internal() returned
3507 * NT_STATUS_OBJECT_NAME_COLLISION
3508 * we still must lstat the path.
3511 if (SMB_VFS_LSTAT(conn, smb_dname)
3513 DEBUG(2, ("Could not stat "
3514 "directory '%s' just "
3519 return map_nt_error_from_unix(
3523 info = FILE_WAS_OPENED;
3529 case FILE_SUPERSEDE:
3530 case FILE_OVERWRITE:
3531 case FILE_OVERWRITE_IF:
3533 DEBUG(5,("open_directory: invalid create_disposition "
3534 "0x%x for directory %s\n",
3535 (unsigned int)create_disposition,
3536 smb_fname_str_dbg(smb_dname)));
3537 return NT_STATUS_INVALID_PARAMETER;
3540 if(!S_ISDIR(smb_dname->st.st_ex_mode)) {
3541 DEBUG(5,("open_directory: %s is not a directory !\n",
3542 smb_fname_str_dbg(smb_dname)));
3543 return NT_STATUS_NOT_A_DIRECTORY;
3546 if (info == FILE_WAS_OPENED) {
3547 status = smbd_check_access_rights(conn,
3551 if (!NT_STATUS_IS_OK(status)) {
3552 DEBUG(10, ("open_directory: smbd_check_access_rights on "
3553 "file %s failed with %s\n",
3554 smb_fname_str_dbg(smb_dname),
3555 nt_errstr(status)));
3560 status = file_new(req, conn, &fsp);
3561 if(!NT_STATUS_IS_OK(status)) {
3566 * Setup the files_struct for it.
3569 fsp->file_id = vfs_file_id_from_sbuf(conn, &smb_dname->st);
3570 fsp->vuid = req ? req->vuid : UID_FIELD_INVALID;
3571 fsp->file_pid = req ? req->smbpid : 0;
3572 fsp->can_lock = False;
3573 fsp->can_read = False;
3574 fsp->can_write = False;
3576 fsp->share_access = share_access;
3577 fsp->fh->private_options = 0;
3579 * According to Samba4, SEC_FILE_READ_ATTRIBUTE is always granted,
3581 fsp->access_mask = access_mask | FILE_READ_ATTRIBUTES;
3582 fsp->print_file = NULL;
3583 fsp->modified = False;
3584 fsp->oplock_type = NO_OPLOCK;
3585 fsp->sent_oplock_break = NO_BREAK_SENT;
3586 fsp->is_directory = True;
3587 if (file_attributes & FILE_FLAG_POSIX_SEMANTICS) {
3588 fsp->posix_flags |= FSP_POSIX_FLAGS_ALL;
3590 status = fsp_set_smb_fname(fsp, smb_dname);
3591 if (!NT_STATUS_IS_OK(status)) {
3592 file_free(req, fsp);
3596 /* Don't store old timestamps for directory
3597 handles in the internal database. We don't
3598 update them in there if new objects
3599 are creaded in the directory. Currently
3600 we only update timestamps on file writes.
3603 ZERO_STRUCT(mtimespec);
3605 if (access_mask & (FILE_LIST_DIRECTORY|
3607 FILE_ADD_SUBDIRECTORY|
3610 FILE_DELETE_CHILD)) {
3612 status = fd_open(conn, fsp, O_RDONLY|O_DIRECTORY, 0);
3614 /* POSIX allows us to open a directory with O_RDONLY. */
3615 status = fd_open(conn, fsp, O_RDONLY, 0);
3617 if (!NT_STATUS_IS_OK(status)) {
3618 DEBUG(5, ("open_directory: Could not open fd for "
3620 smb_fname_str_dbg(smb_dname),
3621 nt_errstr(status)));
3622 file_free(req, fsp);
3627 DEBUG(10, ("Not opening Directory %s\n",
3628 smb_fname_str_dbg(smb_dname)));
3631 status = vfs_stat_fsp(fsp);
3632 if (!NT_STATUS_IS_OK(status)) {
3634 file_free(req, fsp);
3638 /* Ensure there was no race condition. */
3639 if (!check_same_stat(&smb_dname->st, &fsp->fsp_name->st)) {
3640 DEBUG(5,("open_directory: stat struct differs for "
3642 smb_fname_str_dbg(smb_dname)));
3644 file_free(req, fsp);
3645 return NT_STATUS_ACCESS_DENIED;
3648 lck = get_share_mode_lock(talloc_tos(), fsp->file_id,
3649 conn->connectpath, smb_dname,
3653 DEBUG(0, ("open_directory: Could not get share mode lock for "
3654 "%s\n", smb_fname_str_dbg(smb_dname)));
3656 file_free(req, fsp);
3657 return NT_STATUS_SHARING_VIOLATION;
3660 if (has_delete_on_close(lck, fsp->name_hash)) {
3663 file_free(req, fsp);
3664 return NT_STATUS_DELETE_PENDING;
3667 status = open_mode_check(conn, lck,
3668 access_mask, share_access);
3670 if (!NT_STATUS_IS_OK(status)) {
3673 file_free(req, fsp);
3677 ok = set_share_mode(lck, fsp, get_current_uid(conn),
3678 req ? req->mid : 0, NO_OPLOCK,
3683 file_free(req, fsp);
3684 return NT_STATUS_NO_MEMORY;
3687 /* For directories the delete on close bit at open time seems
3688 always to be honored on close... See test 19 in Samba4 BASE-DELETE. */
3689 if (create_options & FILE_DELETE_ON_CLOSE) {
3690 status = can_set_delete_on_close(fsp, 0);
3691 if (!NT_STATUS_IS_OK(status) && !NT_STATUS_EQUAL(status, NT_STATUS_DIRECTORY_NOT_EMPTY)) {
3692 del_share_mode(lck, fsp);
3695 file_free(req, fsp);
3699 if (NT_STATUS_IS_OK(status)) {
3700 /* Note that here we set the *inital* delete on close flag,
3701 not the regular one. The magic gets handled in close. */
3702 fsp->initial_delete_on_close = True;
3708 * Deal with other opens having a modified write time. Is this
3709 * possible for directories?
3711 struct timespec write_time = get_share_mode_write_time(lck);
3713 if (!null_timespec(write_time)) {
3714 update_stat_ex_mtime(&fsp->fsp_name->st, write_time);
3725 return NT_STATUS_OK;
3728 NTSTATUS create_directory(connection_struct *conn, struct smb_request *req,
3729 struct smb_filename *smb_dname)
3734 status = SMB_VFS_CREATE_FILE(
3737 0, /* root_dir_fid */
3738 smb_dname, /* fname */
3739 FILE_READ_ATTRIBUTES, /* access_mask */
3740 FILE_SHARE_NONE, /* share_access */
3741 FILE_CREATE, /* create_disposition*/
3742 FILE_DIRECTORY_FILE, /* create_options */
3743 FILE_ATTRIBUTE_DIRECTORY, /* file_attributes */
3744 0, /* oplock_request */
3746 0, /* allocation_size */
3747 0, /* private_flags */
3752 NULL, NULL); /* create context */
3754 if (NT_STATUS_IS_OK(status)) {
3755 close_file(req, fsp, NORMAL_CLOSE);
3761 /****************************************************************************
3762 Receive notification that one of our open files has been renamed by another
3764 ****************************************************************************/
3766 void msg_file_was_renamed(struct messaging_context *msg,
3769 struct server_id server_id,
3773 char *frm = (char *)data->data;
3775 const char *sharepath;
3776 const char *base_name;
3777 const char *stream_name;
3778 struct smb_filename *smb_fname = NULL;
3779 size_t sp_len, bn_len;
3781 struct smbd_server_connection *sconn =
3782 talloc_get_type_abort(private_data,
3783 struct smbd_server_connection);
3785 if (data->data == NULL
3786 || data->length < MSG_FILE_RENAMED_MIN_SIZE + 2) {
3787 DEBUG(0, ("msg_file_was_renamed: Got invalid msg len %d\n",
3788 (int)data->length));
3792 /* Unpack the message. */
3793 pull_file_id_24(frm, &id);
3794 sharepath = &frm[24];
3795 sp_len = strlen(sharepath);
3796 base_name = sharepath + sp_len + 1;
3797 bn_len = strlen(base_name);
3798 stream_name = sharepath + sp_len + 1 + bn_len + 1;
3800 /* stream_name must always be NULL if there is no stream. */
3801 if (stream_name[0] == '\0') {
3805 smb_fname = synthetic_smb_fname(talloc_tos(), base_name,
3807 if (smb_fname == NULL) {
3811 DEBUG(10,("msg_file_was_renamed: Got rename message for sharepath %s, new name %s, "
3813 sharepath, smb_fname_str_dbg(smb_fname),
3814 file_id_string_tos(&id)));
3816 for(fsp = file_find_di_first(sconn, id); fsp;
3817 fsp = file_find_di_next(fsp)) {
3818 if (memcmp(fsp->conn->connectpath, sharepath, sp_len) == 0) {
3820 DEBUG(10,("msg_file_was_renamed: renaming file %s from %s -> %s\n",
3821 fsp_fnum_dbg(fsp), fsp_str_dbg(fsp),
3822 smb_fname_str_dbg(smb_fname)));
3823 status = fsp_set_smb_fname(fsp, smb_fname);
3824 if (!NT_STATUS_IS_OK(status)) {
3829 /* Now we have the complete path we can work out if this is
3830 actually within this share and adjust newname accordingly. */
3831 DEBUG(10,("msg_file_was_renamed: share mismatch (sharepath %s "
3832 "not sharepath %s) "
3833 "%s from %s -> %s\n",
3834 fsp->conn->connectpath,
3838 smb_fname_str_dbg(smb_fname)));
3842 TALLOC_FREE(smb_fname);
3847 * If a main file is opened for delete, all streams need to be checked for
3848 * !FILE_SHARE_DELETE. Do this by opening with DELETE_ACCESS.
3849 * If that works, delete them all by setting the delete on close and close.
3852 static NTSTATUS open_streams_for_delete(connection_struct *conn,
3853 const struct smb_filename *smb_fname)
3855 struct stream_struct *stream_info = NULL;
3856 files_struct **streams = NULL;
3858 unsigned int num_streams = 0;
3859 TALLOC_CTX *frame = talloc_stackframe();
3862 status = vfs_streaminfo(conn, NULL, smb_fname, talloc_tos(),
3863 &num_streams, &stream_info);
3865 if (NT_STATUS_EQUAL(status, NT_STATUS_NOT_IMPLEMENTED)
3866 || NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
3867 DEBUG(10, ("no streams around\n"));
3869 return NT_STATUS_OK;
3872 if (!NT_STATUS_IS_OK(status)) {
3873 DEBUG(10, ("vfs_streaminfo failed: %s\n",
3874 nt_errstr(status)));
3878 DEBUG(10, ("open_streams_for_delete found %d streams\n",
3881 if (num_streams == 0) {
3883 return NT_STATUS_OK;
3886 streams = talloc_array(talloc_tos(), files_struct *, num_streams);
3887 if (streams == NULL) {
3888 DEBUG(0, ("talloc failed\n"));
3889 status = NT_STATUS_NO_MEMORY;
3893 for (i=0; i<num_streams; i++) {
3894 struct smb_filename *smb_fname_cp;
3896 if (strequal(stream_info[i].name, "::$DATA")) {
3901 smb_fname_cp = synthetic_smb_fname(talloc_tos(),
3902 smb_fname->base_name,
3903 stream_info[i].name,
3905 if (smb_fname_cp == NULL) {
3906 status = NT_STATUS_NO_MEMORY;
3910 if (SMB_VFS_STAT(conn, smb_fname_cp) == -1) {
3911 DEBUG(10, ("Unable to stat stream: %s\n",
3912 smb_fname_str_dbg(smb_fname_cp)));
3915 status = SMB_VFS_CREATE_FILE(
3918 0, /* root_dir_fid */
3919 smb_fname_cp, /* fname */
3920 DELETE_ACCESS, /* access_mask */
3921 (FILE_SHARE_READ | /* share_access */
3922 FILE_SHARE_WRITE | FILE_SHARE_DELETE),
3923 FILE_OPEN, /* create_disposition*/
3924 0, /* create_options */
3925 FILE_ATTRIBUTE_NORMAL, /* file_attributes */
3926 0, /* oplock_request */
3928 0, /* allocation_size */
3929 NTCREATEX_OPTIONS_PRIVATE_STREAM_DELETE, /* private_flags */
3932 &streams[i], /* result */
3934 NULL, NULL); /* create context */
3936 if (!NT_STATUS_IS_OK(status)) {
3937 DEBUG(10, ("Could not open stream %s: %s\n",
3938 smb_fname_str_dbg(smb_fname_cp),
3939 nt_errstr(status)));
3941 TALLOC_FREE(smb_fname_cp);
3944 TALLOC_FREE(smb_fname_cp);
3948 * don't touch the variable "status" beyond this point :-)
3951 for (i -= 1 ; i >= 0; i--) {
3952 if (streams[i] == NULL) {
3956 DEBUG(10, ("Closing stream # %d, %s\n", i,
3957 fsp_str_dbg(streams[i])));
3958 close_file(NULL, streams[i], NORMAL_CLOSE);
3966 /*********************************************************************
3967 Create a default ACL by inheriting from the parent. If no inheritance
3968 from the parent available, don't set anything. This will leave the actual
3969 permissions the new file or directory already got from the filesystem
3970 as the NT ACL when read.
3971 *********************************************************************/
3973 static NTSTATUS inherit_new_acl(files_struct *fsp)
3975 TALLOC_CTX *frame = talloc_stackframe();
3976 char *parent_name = NULL;
3977 struct security_descriptor *parent_desc = NULL;
3978 NTSTATUS status = NT_STATUS_OK;
3979 struct security_descriptor *psd = NULL;
3980 const struct dom_sid *owner_sid = NULL;
3981 const struct dom_sid *group_sid = NULL;
3982 uint32_t security_info_sent = (SECINFO_OWNER | SECINFO_GROUP | SECINFO_DACL);
3983 struct security_token *token = fsp->conn->session_info->security_token;
3984 bool inherit_owner = lp_inherit_owner(SNUM(fsp->conn));
3985 bool inheritable_components = false;
3986 bool try_builtin_administrators = false;
3987 const struct dom_sid *BA_U_sid = NULL;
3988 const struct dom_sid *BA_G_sid = NULL;
3989 bool try_system = false;
3990 const struct dom_sid *SY_U_sid = NULL;
3991 const struct dom_sid *SY_G_sid = NULL;
3993 struct smb_filename *parent_smb_fname = NULL;
3995 if (!parent_dirname(frame, fsp->fsp_name->base_name, &parent_name, NULL)) {
3997 return NT_STATUS_NO_MEMORY;
3999 parent_smb_fname = synthetic_smb_fname(talloc_tos(),
4004 if (parent_smb_fname == NULL) {
4006 return NT_STATUS_NO_MEMORY;
4009 status = SMB_VFS_GET_NT_ACL(fsp->conn,
4011 (SECINFO_OWNER | SECINFO_GROUP | SECINFO_DACL),
4014 if (!NT_STATUS_IS_OK(status)) {
4019 inheritable_components = sd_has_inheritable_components(parent_desc,
4022 if (!inheritable_components && !inherit_owner) {
4024 /* Nothing to inherit and not setting owner. */
4025 return NT_STATUS_OK;
4028 /* Create an inherited descriptor from the parent. */
4030 if (DEBUGLEVEL >= 10) {
4031 DEBUG(10,("inherit_new_acl: parent acl for %s is:\n",
4032 fsp_str_dbg(fsp) ));
4033 NDR_PRINT_DEBUG(security_descriptor, parent_desc);
4036 /* Inherit from parent descriptor if "inherit owner" set. */
4037 if (inherit_owner) {
4038 owner_sid = parent_desc->owner_sid;
4039 group_sid = parent_desc->group_sid;
4042 if (owner_sid == NULL) {
4043 if (security_token_has_builtin_administrators(token)) {
4044 try_builtin_administrators = true;
4045 } else if (security_token_is_system(token)) {
4046 try_builtin_administrators = true;
4051 if (group_sid == NULL &&
4052 token->num_sids == PRIMARY_GROUP_SID_INDEX)
4054 if (security_token_is_system(token)) {
4055 try_builtin_administrators = true;
4060 if (try_builtin_administrators) {
4065 ok = sids_to_unixids(&global_sid_Builtin_Administrators, 1, &ids);
4069 BA_U_sid = &global_sid_Builtin_Administrators;
4070 BA_G_sid = &global_sid_Builtin_Administrators;
4073 BA_U_sid = &global_sid_Builtin_Administrators;
4076 BA_G_sid = &global_sid_Builtin_Administrators;
4089 ok = sids_to_unixids(&global_sid_System, 1, &ids);
4093 SY_U_sid = &global_sid_System;
4094 SY_G_sid = &global_sid_System;
4097 SY_U_sid = &global_sid_System;
4100 SY_G_sid = &global_sid_System;
4108 if (owner_sid == NULL) {
4109 owner_sid = BA_U_sid;
4112 if (owner_sid == NULL) {
4113 owner_sid = SY_U_sid;
4116 if (group_sid == NULL) {
4117 group_sid = SY_G_sid;
4120 if (try_system && group_sid == NULL) {
4121 group_sid = BA_G_sid;
4124 if (owner_sid == NULL) {
4125 owner_sid = &token->sids[PRIMARY_USER_SID_INDEX];
4127 if (group_sid == NULL) {
4128 if (token->num_sids == PRIMARY_GROUP_SID_INDEX) {
4129 group_sid = &token->sids[PRIMARY_USER_SID_INDEX];
4131 group_sid = &token->sids[PRIMARY_GROUP_SID_INDEX];
4135 status = se_create_child_secdesc(frame,
4142 if (!NT_STATUS_IS_OK(status)) {
4147 /* If inheritable_components == false,
4148 se_create_child_secdesc()
4149 creates a security desriptor with a NULL dacl
4150 entry, but with SEC_DESC_DACL_PRESENT. We need
4151 to remove that flag. */
4153 if (!inheritable_components) {
4154 security_info_sent &= ~SECINFO_DACL;
4155 psd->type &= ~SEC_DESC_DACL_PRESENT;
4158 if (DEBUGLEVEL >= 10) {
4159 DEBUG(10,("inherit_new_acl: child acl for %s is:\n",
4160 fsp_str_dbg(fsp) ));
4161 NDR_PRINT_DEBUG(security_descriptor, psd);
4164 if (inherit_owner) {
4165 /* We need to be root to force this. */
4168 status = SMB_VFS_FSET_NT_ACL(fsp,
4171 if (inherit_owner) {
4179 * If we already have a lease, it must match the new file id. [MS-SMB2]
4180 * 3.3.5.9.8 speaks about INVALID_PARAMETER if an already used lease key is
4181 * used for a different file name.
4184 struct lease_match_state {
4185 /* Input parameters. */
4186 TALLOC_CTX *mem_ctx;
4187 const char *servicepath;
4188 const struct smb_filename *fname;
4191 /* Return parameters. */
4192 uint32_t num_file_ids;
4193 struct file_id *ids;
4194 NTSTATUS match_status;
4197 /*************************************************************
4198 File doesn't exist but this lease key+guid is already in use.
4200 This is only allowable in the dynamic share case where the
4201 service path must be different.
4203 There is a small race condition here in the multi-connection
4204 case where a client sends two create calls on different connections,
4205 where the file doesn't exist and one smbd creates the leases_db
4206 entry first, but this will get fixed by the multichannel cleanup
4207 when all identical client_guids get handled by a single smbd.
4208 **************************************************************/
4210 static void lease_match_parser_new_file(
4212 const struct leases_db_file *files,
4213 struct lease_match_state *state)
4217 for (i = 0; i < num_files; i++) {
4218 const struct leases_db_file *f = &files[i];
4219 if (strequal(state->servicepath, f->servicepath)) {
4220 state->match_status = NT_STATUS_INVALID_PARAMETER;
4225 /* Dynamic share case. Break leases on all other files. */
4226 state->match_status = leases_db_copy_file_ids(state->mem_ctx,
4230 if (!NT_STATUS_IS_OK(state->match_status)) {
4234 state->num_file_ids = num_files;
4235 state->match_status = NT_STATUS_OPLOCK_NOT_GRANTED;
4239 static void lease_match_parser(
4241 const struct leases_db_file *files,
4244 struct lease_match_state *state =
4245 (struct lease_match_state *)private_data;
4248 if (!state->file_existed) {
4250 * Deal with name mismatch or
4251 * possible dynamic share case separately
4252 * to make code clearer.
4254 lease_match_parser_new_file(num_files,
4261 state->match_status = NT_STATUS_OK;
4263 for (i = 0; i < num_files; i++) {
4264 const struct leases_db_file *f = &files[i];
4266 /* Everything should be the same. */
4267 if (!file_id_equal(&state->id, &f->id)) {
4268 /* This should catch all dynamic share cases. */
4269 state->match_status = NT_STATUS_OPLOCK_NOT_GRANTED;
4272 if (!strequal(f->servicepath, state->servicepath)) {
4273 state->match_status = NT_STATUS_INVALID_PARAMETER;
4276 if (!strequal(f->base_name, state->fname->base_name)) {
4277 state->match_status = NT_STATUS_INVALID_PARAMETER;
4280 if (!strequal(f->stream_name, state->fname->stream_name)) {
4281 state->match_status = NT_STATUS_INVALID_PARAMETER;
4286 if (NT_STATUS_IS_OK(state->match_status)) {
4288 * Common case - just opening another handle on a
4289 * file on a non-dynamic share.
4294 if (NT_STATUS_EQUAL(state->match_status, NT_STATUS_INVALID_PARAMETER)) {
4295 /* Mismatched path. Error back to client. */
4300 * File id mismatch. Dynamic share case NT_STATUS_OPLOCK_NOT_GRANTED.
4301 * Don't allow leases.
4304 state->match_status = leases_db_copy_file_ids(state->mem_ctx,
4308 if (!NT_STATUS_IS_OK(state->match_status)) {
4312 state->num_file_ids = num_files;
4313 state->match_status = NT_STATUS_OPLOCK_NOT_GRANTED;
4317 static NTSTATUS lease_match(connection_struct *conn,
4318 struct smb_request *req,
4319 struct smb2_lease_key *lease_key,
4320 const char *servicepath,
4321 const struct smb_filename *fname,
4322 uint16_t *p_version,
4325 struct smbd_server_connection *sconn = req->sconn;
4326 TALLOC_CTX *tos = talloc_tos();
4327 struct lease_match_state state = {
4329 .servicepath = servicepath,
4331 .match_status = NT_STATUS_OK
4336 state.file_existed = VALID_STAT(fname->st);
4337 if (state.file_existed) {
4338 state.id = vfs_file_id_from_sbuf(conn, &fname->st);
4340 memset(&state.id, '\0', sizeof(state.id));
4343 status = leases_db_parse(&sconn->client->connections->smb2.client.guid,
4344 lease_key, lease_match_parser, &state);
4345 if (!NT_STATUS_IS_OK(status)) {
4347 * Not found or error means okay: We can make the lease pass
4349 return NT_STATUS_OK;
4351 if (!NT_STATUS_EQUAL(state.match_status, NT_STATUS_OPLOCK_NOT_GRANTED)) {
4353 * Anything but NT_STATUS_OPLOCK_NOT_GRANTED, let the caller
4356 return state.match_status;
4359 /* We have to break all existing leases. */
4360 for (i = 0; i < state.num_file_ids; i++) {
4361 struct share_mode_lock *lck;
4362 struct share_mode_data *d;
4365 if (file_id_equal(&state.ids[i], &state.id)) {
4366 /* Don't need to break our own file. */
4370 lck = get_existing_share_mode_lock(talloc_tos(), state.ids[i]);
4372 /* Race condition - file already closed. */
4376 for (j=0; j<d->num_share_modes; j++) {
4377 struct share_mode_entry *e = &d->share_modes[j];
4378 uint32_t e_lease_type = get_lease_type(d, e);
4379 struct share_mode_lease *l = NULL;
4381 if (share_mode_stale_pid(d, j)) {
4385 if (e->op_type == LEASE_OPLOCK) {
4386 l = &lck->data->leases[e->lease_idx];
4387 if (!smb2_lease_key_equal(&l->lease_key,
4391 *p_epoch = l->epoch;
4392 *p_version = l->lease_version;
4395 if (e_lease_type == SMB2_LEASE_NONE) {
4399 send_break_message(conn->sconn->msg_ctx, e,
4403 * Windows 7 and 8 lease clients
4404 * are broken in that they will not
4405 * respond to lease break requests
4406 * whilst waiting for an outstanding
4407 * open request on that lease handle
4408 * on the same TCP connection, due
4409 * to holding an internal inode lock.
4411 * This means we can't reschedule
4412 * ourselves here, but must return
4417 * Send the breaks and then return
4418 * SMB2_LEASE_NONE in the lease handle
4419 * to cause them to acknowledge the
4420 * lease break. Consulatation with
4421 * Microsoft engineering confirmed
4422 * this approach is safe.
4429 * Ensure we don't grant anything more so we
4432 return NT_STATUS_OPLOCK_NOT_GRANTED;
4436 * Wrapper around open_file_ntcreate and open_directory
4439 static NTSTATUS create_file_unixpath(connection_struct *conn,
4440 struct smb_request *req,
4441 struct smb_filename *smb_fname,
4442 uint32_t access_mask,
4443 uint32_t share_access,
4444 uint32_t create_disposition,
4445 uint32_t create_options,
4446 uint32_t file_attributes,
4447 uint32_t oplock_request,
4448 struct smb2_lease *lease,
4449 uint64_t allocation_size,
4450 uint32_t private_flags,
4451 struct security_descriptor *sd,
4452 struct ea_list *ea_list,
4454 files_struct **result,
4457 int info = FILE_WAS_OPENED;
4458 files_struct *base_fsp = NULL;
4459 files_struct *fsp = NULL;
4462 DEBUG(10,("create_file_unixpath: access_mask = 0x%x "
4463 "file_attributes = 0x%x, share_access = 0x%x, "
4464 "create_disposition = 0x%x create_options = 0x%x "
4465 "oplock_request = 0x%x private_flags = 0x%x "
4466 "ea_list = 0x%p, sd = 0x%p, "
4468 (unsigned int)access_mask,
4469 (unsigned int)file_attributes,
4470 (unsigned int)share_access,
4471 (unsigned int)create_disposition,
4472 (unsigned int)create_options,
4473 (unsigned int)oplock_request,
4474 (unsigned int)private_flags,
4475 ea_list, sd, smb_fname_str_dbg(smb_fname)));
4477 if (create_options & FILE_OPEN_BY_FILE_ID) {
4478 status = NT_STATUS_NOT_SUPPORTED;
4482 if (create_options & NTCREATEX_OPTIONS_INVALID_PARAM_MASK) {
4483 status = NT_STATUS_INVALID_PARAMETER;
4488 oplock_request |= INTERNAL_OPEN_ONLY;
4491 if (lease != NULL) {
4492 uint16_t epoch = lease->lease_epoch;
4493 uint16_t version = lease->lease_version;
4494 status = lease_match(conn,
4501 if (NT_STATUS_EQUAL(status, NT_STATUS_OPLOCK_NOT_GRANTED)) {
4502 /* Dynamic share file. No leases and update epoch... */
4503 lease->lease_state = SMB2_LEASE_NONE;
4504 lease->lease_epoch = epoch;
4505 lease->lease_version = version;
4506 } else if (!NT_STATUS_IS_OK(status)) {
4511 if ((conn->fs_capabilities & FILE_NAMED_STREAMS)
4512 && (access_mask & DELETE_ACCESS)
4513 && !is_ntfs_stream_smb_fname(smb_fname)) {
4515 * We can't open a file with DELETE access if any of the
4516 * streams is open without FILE_SHARE_DELETE
4518 status = open_streams_for_delete(conn, smb_fname);
4520 if (!NT_STATUS_IS_OK(status)) {
4525 if ((access_mask & SEC_FLAG_SYSTEM_SECURITY) &&
4526 !security_token_has_privilege(get_current_nttok(conn),
4527 SEC_PRIV_SECURITY)) {
4528 DEBUG(10, ("create_file_unixpath: open on %s "
4529 "failed - SEC_FLAG_SYSTEM_SECURITY denied.\n",
4530 smb_fname_str_dbg(smb_fname)));
4531 status = NT_STATUS_PRIVILEGE_NOT_HELD;
4535 if ((conn->fs_capabilities & FILE_NAMED_STREAMS)
4536 && is_ntfs_stream_smb_fname(smb_fname)
4537 && (!(private_flags & NTCREATEX_OPTIONS_PRIVATE_STREAM_DELETE))) {
4538 uint32_t base_create_disposition;
4539 struct smb_filename *smb_fname_base = NULL;
4541 if (create_options & FILE_DIRECTORY_FILE) {
4542 status = NT_STATUS_NOT_A_DIRECTORY;
4546 switch (create_disposition) {
4548 base_create_disposition = FILE_OPEN;
4551 base_create_disposition = FILE_OPEN_IF;
4555 /* Create an smb_filename with stream_name == NULL. */
4556 smb_fname_base = synthetic_smb_fname(talloc_tos(),
4557 smb_fname->base_name,
4559 if (smb_fname_base == NULL) {
4560 status = NT_STATUS_NO_MEMORY;
4564 if (SMB_VFS_STAT(conn, smb_fname_base) == -1) {
4565 DEBUG(10, ("Unable to stat stream: %s\n",
4566 smb_fname_str_dbg(smb_fname_base)));
4569 * https://bugzilla.samba.org/show_bug.cgi?id=10229
4570 * We need to check if the requested access mask
4571 * could be used to open the underlying file (if
4572 * it existed), as we're passing in zero for the
4573 * access mask to the base filename.
4575 status = check_base_file_access(conn,
4579 if (!NT_STATUS_IS_OK(status)) {
4580 DEBUG(10, ("Permission check "
4581 "for base %s failed: "
4582 "%s\n", smb_fname->base_name,
4583 nt_errstr(status)));
4588 /* Open the base file. */
4589 status = create_file_unixpath(conn, NULL, smb_fname_base, 0,
4592 | FILE_SHARE_DELETE,
4593 base_create_disposition,
4594 0, 0, 0, NULL, 0, 0, NULL, NULL,
4596 TALLOC_FREE(smb_fname_base);
4598 if (!NT_STATUS_IS_OK(status)) {
4599 DEBUG(10, ("create_file_unixpath for base %s failed: "
4600 "%s\n", smb_fname->base_name,
4601 nt_errstr(status)));
4604 /* we don't need the low level fd */
4609 * If it's a request for a directory open, deal with it separately.
4612 if (create_options & FILE_DIRECTORY_FILE) {
4614 if (create_options & FILE_NON_DIRECTORY_FILE) {
4615 status = NT_STATUS_INVALID_PARAMETER;
4619 /* Can't open a temp directory. IFS kit test. */
4620 if (!(file_attributes & FILE_FLAG_POSIX_SEMANTICS) &&
4621 (file_attributes & FILE_ATTRIBUTE_TEMPORARY)) {
4622 status = NT_STATUS_INVALID_PARAMETER;
4627 * We will get a create directory here if the Win32
4628 * app specified a security descriptor in the
4629 * CreateDirectory() call.
4633 status = open_directory(
4634 conn, req, smb_fname, access_mask, share_access,
4635 create_disposition, create_options, file_attributes,
4640 * Ordinary file case.
4643 status = file_new(req, conn, &fsp);
4644 if(!NT_STATUS_IS_OK(status)) {
4648 status = fsp_set_smb_fname(fsp, smb_fname);
4649 if (!NT_STATUS_IS_OK(status)) {
4655 * We're opening the stream element of a
4656 * base_fsp we already opened. Set up the
4659 fsp->base_fsp = base_fsp;
4662 if (allocation_size) {
4663 fsp->initial_allocation_size = smb_roundup(fsp->conn,
4667 status = open_file_ntcreate(conn,
4680 if(!NT_STATUS_IS_OK(status)) {
4681 file_free(req, fsp);
4685 if (NT_STATUS_EQUAL(status, NT_STATUS_FILE_IS_A_DIRECTORY)) {
4687 /* A stream open never opens a directory */
4690 status = NT_STATUS_FILE_IS_A_DIRECTORY;
4695 * Fail the open if it was explicitly a non-directory
4699 if (create_options & FILE_NON_DIRECTORY_FILE) {
4700 status = NT_STATUS_FILE_IS_A_DIRECTORY;
4705 status = open_directory(
4706 conn, req, smb_fname, access_mask,
4707 share_access, create_disposition,
4708 create_options, file_attributes,
4713 if (!NT_STATUS_IS_OK(status)) {
4717 fsp->base_fsp = base_fsp;
4719 if ((ea_list != NULL) &&
4720 ((info == FILE_WAS_CREATED) || (info == FILE_WAS_OVERWRITTEN))) {
4721 status = set_ea(conn, fsp, fsp->fsp_name, ea_list);
4722 if (!NT_STATUS_IS_OK(status)) {
4727 if (!fsp->is_directory && S_ISDIR(fsp->fsp_name->st.st_ex_mode)) {
4728 status = NT_STATUS_ACCESS_DENIED;
4732 /* Save the requested allocation size. */
4733 if ((info == FILE_WAS_CREATED) || (info == FILE_WAS_OVERWRITTEN)) {
4734 if ((allocation_size > fsp->fsp_name->st.st_ex_size)
4735 && !(fsp->is_directory))
4737 fsp->initial_allocation_size = smb_roundup(
4738 fsp->conn, allocation_size);
4739 if (vfs_allocate_file_space(
4740 fsp, fsp->initial_allocation_size) == -1) {
4741 status = NT_STATUS_DISK_FULL;
4745 fsp->initial_allocation_size = smb_roundup(
4746 fsp->conn, (uint64_t)fsp->fsp_name->st.st_ex_size);
4749 fsp->initial_allocation_size = 0;
4752 if ((info == FILE_WAS_CREATED) && lp_nt_acl_support(SNUM(conn)) &&
4753 fsp->base_fsp == NULL) {
4756 * According to the MS documentation, the only time the security
4757 * descriptor is applied to the opened file is iff we *created* the
4758 * file; an existing file stays the same.
4760 * Also, it seems (from observation) that you can open the file with
4761 * any access mask but you can still write the sd. We need to override
4762 * the granted access before we call set_sd
4763 * Patch for bug #2242 from Tom Lackemann <cessnatomny@yahoo.com>.
4766 uint32_t sec_info_sent;
4767 uint32_t saved_access_mask = fsp->access_mask;
4769 sec_info_sent = get_sec_info(sd);
4771 fsp->access_mask = FILE_GENERIC_ALL;
4773 if (sec_info_sent & (SECINFO_OWNER|
4777 status = set_sd(fsp, sd, sec_info_sent);
4780 fsp->access_mask = saved_access_mask;
4782 if (!NT_STATUS_IS_OK(status)) {
4785 } else if (lp_inherit_acls(SNUM(conn))) {
4786 /* Inherit from parent. Errors here are not fatal. */
4787 status = inherit_new_acl(fsp);
4788 if (!NT_STATUS_IS_OK(status)) {
4789 DEBUG(10,("inherit_new_acl: failed for %s with %s\n",
4791 nt_errstr(status) ));
4796 if ((conn->fs_capabilities & FILE_FILE_COMPRESSION)
4797 && (create_options & FILE_NO_COMPRESSION)
4798 && (info == FILE_WAS_CREATED)) {
4799 status = SMB_VFS_SET_COMPRESSION(conn, fsp, fsp,
4800 COMPRESSION_FORMAT_NONE);
4801 if (!NT_STATUS_IS_OK(status)) {
4802 DEBUG(1, ("failed to disable compression: %s\n",
4803 nt_errstr(status)));
4807 DEBUG(10, ("create_file_unixpath: info=%d\n", info));
4810 if (pinfo != NULL) {
4814 smb_fname->st = fsp->fsp_name->st;
4816 return NT_STATUS_OK;
4819 DEBUG(10, ("create_file_unixpath: %s\n", nt_errstr(status)));
4822 if (base_fsp && fsp->base_fsp == base_fsp) {
4824 * The close_file below will close
4829 close_file(req, fsp, ERROR_CLOSE);
4832 if (base_fsp != NULL) {
4833 close_file(req, base_fsp, ERROR_CLOSE);
4840 * Calculate the full path name given a relative fid.
4842 NTSTATUS get_relative_fid_filename(connection_struct *conn,
4843 struct smb_request *req,
4844 uint16_t root_dir_fid,
4845 const struct smb_filename *smb_fname,
4846 struct smb_filename **smb_fname_out)
4848 files_struct *dir_fsp;
4849 char *parent_fname = NULL;
4850 char *new_base_name = NULL;
4851 uint32_t ucf_flags = ((req != NULL && req->posix_pathnames) ?
4852 UCF_POSIX_PATHNAMES : 0);
4855 if (root_dir_fid == 0 || !smb_fname) {
4856 status = NT_STATUS_INTERNAL_ERROR;
4860 dir_fsp = file_fsp(req, root_dir_fid);
4862 if (dir_fsp == NULL) {
4863 status = NT_STATUS_INVALID_HANDLE;
4867 if (is_ntfs_stream_smb_fname(dir_fsp->fsp_name)) {
4868 status = NT_STATUS_INVALID_HANDLE;
4872 if (!dir_fsp->is_directory) {
4875 * Check to see if this is a mac fork of some kind.
4878 if ((conn->fs_capabilities & FILE_NAMED_STREAMS) &&
4879 is_ntfs_stream_smb_fname(smb_fname)) {
4880 status = NT_STATUS_OBJECT_PATH_NOT_FOUND;
4885 we need to handle the case when we get a
4886 relative open relative to a file and the
4887 pathname is blank - this is a reopen!
4888 (hint from demyn plantenberg)
4891 status = NT_STATUS_INVALID_HANDLE;
4895 if (ISDOT(dir_fsp->fsp_name->base_name)) {
4897 * We're at the toplevel dir, the final file name
4898 * must not contain ./, as this is filtered out
4899 * normally by srvstr_get_path and unix_convert
4900 * explicitly rejects paths containing ./.
4902 parent_fname = talloc_strdup(talloc_tos(), "");
4903 if (parent_fname == NULL) {
4904 status = NT_STATUS_NO_MEMORY;
4908 size_t dir_name_len = strlen(dir_fsp->fsp_name->base_name);
4911 * Copy in the base directory name.
4914 parent_fname = talloc_array(talloc_tos(), char,
4916 if (parent_fname == NULL) {
4917 status = NT_STATUS_NO_MEMORY;
4920 memcpy(parent_fname, dir_fsp->fsp_name->base_name,
4924 * Ensure it ends in a '/'.
4925 * We used TALLOC_SIZE +2 to add space for the '/'.
4929 && (parent_fname[dir_name_len-1] != '\\')
4930 && (parent_fname[dir_name_len-1] != '/')) {
4931 parent_fname[dir_name_len] = '/';
4932 parent_fname[dir_name_len+1] = '\0';
4936 new_base_name = talloc_asprintf(talloc_tos(), "%s%s", parent_fname,
4937 smb_fname->base_name);
4938 if (new_base_name == NULL) {
4939 status = NT_STATUS_NO_MEMORY;
4943 status = filename_convert(req,
4945 req->flags2 & FLAGS2_DFS_PATHNAMES,
4950 if (!NT_STATUS_IS_OK(status)) {
4955 TALLOC_FREE(parent_fname);
4956 TALLOC_FREE(new_base_name);
4960 NTSTATUS create_file_default(connection_struct *conn,
4961 struct smb_request *req,
4962 uint16_t root_dir_fid,
4963 struct smb_filename *smb_fname,
4964 uint32_t access_mask,
4965 uint32_t share_access,
4966 uint32_t create_disposition,
4967 uint32_t create_options,
4968 uint32_t file_attributes,
4969 uint32_t oplock_request,
4970 struct smb2_lease *lease,
4971 uint64_t allocation_size,
4972 uint32_t private_flags,
4973 struct security_descriptor *sd,
4974 struct ea_list *ea_list,
4975 files_struct **result,
4977 const struct smb2_create_blobs *in_context_blobs,
4978 struct smb2_create_blobs *out_context_blobs)
4980 int info = FILE_WAS_OPENED;
4981 files_struct *fsp = NULL;
4983 bool stream_name = false;
4985 DEBUG(10,("create_file: access_mask = 0x%x "
4986 "file_attributes = 0x%x, share_access = 0x%x, "
4987 "create_disposition = 0x%x create_options = 0x%x "
4988 "oplock_request = 0x%x "
4989 "private_flags = 0x%x "
4990 "root_dir_fid = 0x%x, ea_list = 0x%p, sd = 0x%p, "
4992 (unsigned int)access_mask,
4993 (unsigned int)file_attributes,
4994 (unsigned int)share_access,
4995 (unsigned int)create_disposition,
4996 (unsigned int)create_options,
4997 (unsigned int)oplock_request,
4998 (unsigned int)private_flags,
4999 (unsigned int)root_dir_fid,
5000 ea_list, sd, smb_fname_str_dbg(smb_fname)));
5003 * Calculate the filename from the root_dir_if if necessary.
5006 if (root_dir_fid != 0) {
5007 struct smb_filename *smb_fname_out = NULL;
5008 status = get_relative_fid_filename(conn, req, root_dir_fid,
5009 smb_fname, &smb_fname_out);
5010 if (!NT_STATUS_IS_OK(status)) {
5013 smb_fname = smb_fname_out;
5017 * Check to see if this is a mac fork of some kind.
5020 stream_name = is_ntfs_stream_smb_fname(smb_fname);
5022 enum FAKE_FILE_TYPE fake_file_type;
5024 fake_file_type = is_fake_file(smb_fname);
5026 if (fake_file_type != FAKE_FILE_TYPE_NONE) {
5029 * Here we go! support for changing the disk quotas
5032 * We need to fake up to open this MAGIC QUOTA file
5033 * and return a valid FID.
5035 * w2k close this file directly after openening xp
5036 * also tries a QUERY_FILE_INFO on the file and then
5039 status = open_fake_file(req, conn, req->vuid,
5040 fake_file_type, smb_fname,
5042 if (!NT_STATUS_IS_OK(status)) {
5046 ZERO_STRUCT(smb_fname->st);
5050 if (!(conn->fs_capabilities & FILE_NAMED_STREAMS)) {
5051 status = NT_STATUS_OBJECT_NAME_NOT_FOUND;
5056 if (is_ntfs_default_stream_smb_fname(smb_fname)) {
5058 smb_fname->stream_name = NULL;
5059 /* We have to handle this error here. */
5060 if (create_options & FILE_DIRECTORY_FILE) {
5061 status = NT_STATUS_NOT_A_DIRECTORY;
5064 if (req != NULL && req->posix_pathnames) {
5065 ret = SMB_VFS_LSTAT(conn, smb_fname);
5067 ret = SMB_VFS_STAT(conn, smb_fname);
5070 if (ret == 0 && VALID_STAT_OF_DIR(smb_fname->st)) {
5071 status = NT_STATUS_FILE_IS_A_DIRECTORY;
5076 status = create_file_unixpath(
5077 conn, req, smb_fname, access_mask, share_access,
5078 create_disposition, create_options, file_attributes,
5079 oplock_request, lease, allocation_size, private_flags,
5083 if (!NT_STATUS_IS_OK(status)) {
5088 DEBUG(10, ("create_file: info=%d\n", info));
5091 if (pinfo != NULL) {
5094 return NT_STATUS_OK;
5097 DEBUG(10, ("create_file: %s\n", nt_errstr(status)));
5100 close_file(req, fsp, ERROR_CLOSE);