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"
40 extern const struct generic_mapping file_generic_mapping;
42 struct deferred_open_record {
43 bool delayed_for_oplocks;
48 /****************************************************************************
49 If the requester wanted DELETE_ACCESS and was rejected because
50 the file ACL didn't include DELETE_ACCESS, see if the parent ACL
52 ****************************************************************************/
54 static bool parent_override_delete(connection_struct *conn,
55 const struct smb_filename *smb_fname,
57 uint32_t rejected_mask)
59 if ((access_mask & DELETE_ACCESS) &&
60 (rejected_mask & DELETE_ACCESS) &&
61 can_delete_file_in_directory(conn, smb_fname)) {
67 /****************************************************************************
68 Check if we have open rights.
69 ****************************************************************************/
71 NTSTATUS smbd_check_access_rights(struct connection_struct *conn,
72 const struct smb_filename *smb_fname,
76 /* Check if we have rights to open. */
78 struct security_descriptor *sd = NULL;
79 uint32_t rejected_share_access;
80 uint32_t rejected_mask = access_mask;
81 uint32_t do_not_check_mask = 0;
83 rejected_share_access = access_mask & ~(conn->share_access);
85 if (rejected_share_access) {
86 DEBUG(10, ("smbd_check_access_rights: rejected share access 0x%x "
88 (unsigned int)access_mask,
89 smb_fname_str_dbg(smb_fname),
90 (unsigned int)rejected_share_access ));
91 return NT_STATUS_ACCESS_DENIED;
94 if (!use_privs && get_current_uid(conn) == (uid_t)0) {
95 /* I'm sorry sir, I didn't know you were root... */
96 DEBUG(10,("smbd_check_access_rights: root override "
97 "on %s. Granting 0x%x\n",
98 smb_fname_str_dbg(smb_fname),
99 (unsigned int)access_mask ));
103 if ((access_mask & DELETE_ACCESS) && !lp_acl_check_permissions(SNUM(conn))) {
104 DEBUG(10,("smbd_check_access_rights: not checking ACL "
105 "on DELETE_ACCESS on file %s. Granting 0x%x\n",
106 smb_fname_str_dbg(smb_fname),
107 (unsigned int)access_mask ));
111 if (access_mask == DELETE_ACCESS &&
112 VALID_STAT(smb_fname->st) &&
113 S_ISLNK(smb_fname->st.st_ex_mode)) {
114 /* We can always delete a symlink. */
115 DEBUG(10,("smbd_check_access_rights: not checking ACL "
116 "on DELETE_ACCESS on symlink %s.\n",
117 smb_fname_str_dbg(smb_fname) ));
121 status = SMB_VFS_GET_NT_ACL(conn, smb_fname->base_name,
124 SECINFO_DACL), talloc_tos(), &sd);
126 if (!NT_STATUS_IS_OK(status)) {
127 DEBUG(10, ("smbd_check_access_rights: Could not get acl "
129 smb_fname_str_dbg(smb_fname),
132 if (NT_STATUS_EQUAL(status, NT_STATUS_ACCESS_DENIED)) {
140 * If we can access the path to this file, by
141 * default we have FILE_READ_ATTRIBUTES from the
142 * containing directory. See the section:
143 * "Algorithm to Check Access to an Existing File"
146 * se_file_access_check() also takes care of
147 * owner WRITE_DAC and READ_CONTROL.
149 do_not_check_mask = FILE_READ_ATTRIBUTES;
152 * Samba 3.6 and earlier granted execute access even
153 * if the ACL did not contain execute rights.
154 * Samba 4.0 is more correct and checks it.
155 * The compatibilty mode allows to skip this check
156 * to smoothen upgrades.
158 if (lp_acl_allow_execute_always(SNUM(conn))) {
159 do_not_check_mask |= FILE_EXECUTE;
162 status = se_file_access_check(sd,
163 get_current_nttok(conn),
165 (access_mask & ~do_not_check_mask),
168 DEBUG(10,("smbd_check_access_rights: file %s requesting "
169 "0x%x returning 0x%x (%s)\n",
170 smb_fname_str_dbg(smb_fname),
171 (unsigned int)access_mask,
172 (unsigned int)rejected_mask,
173 nt_errstr(status) ));
175 if (!NT_STATUS_IS_OK(status)) {
176 if (DEBUGLEVEL >= 10) {
177 DEBUG(10,("smbd_check_access_rights: acl for %s is:\n",
178 smb_fname_str_dbg(smb_fname) ));
179 NDR_PRINT_DEBUG(security_descriptor, sd);
185 if (NT_STATUS_IS_OK(status) ||
186 !NT_STATUS_EQUAL(status, NT_STATUS_ACCESS_DENIED)) {
190 /* Here we know status == NT_STATUS_ACCESS_DENIED. */
194 if ((access_mask & FILE_WRITE_ATTRIBUTES) &&
195 (rejected_mask & FILE_WRITE_ATTRIBUTES) &&
196 !lp_store_dos_attributes(SNUM(conn)) &&
197 (lp_map_readonly(SNUM(conn)) ||
198 lp_map_archive(SNUM(conn)) ||
199 lp_map_hidden(SNUM(conn)) ||
200 lp_map_system(SNUM(conn)))) {
201 rejected_mask &= ~FILE_WRITE_ATTRIBUTES;
203 DEBUG(10,("smbd_check_access_rights: "
205 "FILE_WRITE_ATTRIBUTES "
207 smb_fname_str_dbg(smb_fname)));
210 if (parent_override_delete(conn,
214 /* Were we trying to do an open
215 * for delete and didn't get DELETE
216 * access (only) ? Check if the
217 * directory allows DELETE_CHILD.
219 * http://blogs.msdn.com/oldnewthing/archive/2004/06/04/148426.aspx
222 rejected_mask &= ~DELETE_ACCESS;
224 DEBUG(10,("smbd_check_access_rights: "
228 smb_fname_str_dbg(smb_fname)));
231 if (rejected_mask != 0) {
232 return NT_STATUS_ACCESS_DENIED;
237 static NTSTATUS check_parent_access(struct connection_struct *conn,
238 struct smb_filename *smb_fname,
239 uint32_t access_mask)
242 char *parent_dir = NULL;
243 struct security_descriptor *parent_sd = NULL;
244 uint32_t access_granted = 0;
246 if (!parent_dirname(talloc_tos(),
247 smb_fname->base_name,
250 return NT_STATUS_NO_MEMORY;
253 if (get_current_uid(conn) == (uid_t)0) {
254 /* I'm sorry sir, I didn't know you were root... */
255 DEBUG(10,("check_parent_access: root override "
256 "on %s. Granting 0x%x\n",
257 smb_fname_str_dbg(smb_fname),
258 (unsigned int)access_mask ));
262 status = SMB_VFS_GET_NT_ACL(conn,
268 if (!NT_STATUS_IS_OK(status)) {
269 DEBUG(5,("check_parent_access: SMB_VFS_GET_NT_ACL failed for "
270 "%s with error %s\n",
277 * If we can access the path to this file, by
278 * default we have FILE_READ_ATTRIBUTES from the
279 * containing directory. See the section:
280 * "Algorithm to Check Access to an Existing File"
283 * se_file_access_check() also takes care of
284 * owner WRITE_DAC and READ_CONTROL.
286 status = se_file_access_check(parent_sd,
287 get_current_nttok(conn),
289 (access_mask & ~FILE_READ_ATTRIBUTES),
291 if(!NT_STATUS_IS_OK(status)) {
292 DEBUG(5,("check_parent_access: access check "
293 "on directory %s for "
294 "path %s for mask 0x%x returned (0x%x) %s\n",
296 smb_fname->base_name,
299 nt_errstr(status) ));
306 /****************************************************************************
307 Ensure when opening a base file for a stream open that we have permissions
308 to do so given the access mask on the base file.
309 ****************************************************************************/
311 static NTSTATUS check_base_file_access(struct connection_struct *conn,
312 struct smb_filename *smb_fname,
313 uint32_t access_mask)
317 status = smbd_calculate_access_mask(conn, smb_fname,
321 if (!NT_STATUS_IS_OK(status)) {
322 DEBUG(10, ("smbd_calculate_access_mask "
323 "on file %s returned %s\n",
324 smb_fname_str_dbg(smb_fname),
329 if (access_mask & (FILE_WRITE_DATA|FILE_APPEND_DATA)) {
331 if (!CAN_WRITE(conn)) {
332 return NT_STATUS_ACCESS_DENIED;
334 dosattrs = dos_mode(conn, smb_fname);
335 if (IS_DOS_READONLY(dosattrs)) {
336 return NT_STATUS_ACCESS_DENIED;
340 return smbd_check_access_rights(conn,
346 /****************************************************************************
347 fd support routines - attempt to do a dos_open.
348 ****************************************************************************/
350 NTSTATUS fd_open(struct connection_struct *conn,
355 struct smb_filename *smb_fname = fsp->fsp_name;
356 NTSTATUS status = NT_STATUS_OK;
360 * Never follow symlinks on a POSIX client. The
361 * client should be doing this.
364 if (fsp->posix_open || !lp_follow_symlinks(SNUM(conn))) {
369 fsp->fh->fd = SMB_VFS_OPEN(conn, smb_fname, fsp, flags, mode);
370 if (fsp->fh->fd == -1) {
371 int posix_errno = errno;
373 #if defined(ENOTSUP) && defined(OSF1)
374 /* handle special Tru64 errno */
375 if (errno == ENOTSUP) {
380 /* fix broken NetBSD errno */
381 if (errno == EFTYPE) {
385 /* fix broken FreeBSD errno */
386 if (errno == EMLINK) {
389 #endif /* O_NOFOLLOW */
390 status = map_nt_error_from_unix(posix_errno);
391 if (errno == EMFILE) {
392 static time_t last_warned = 0L;
394 if (time((time_t *) NULL) > last_warned) {
395 DEBUG(0,("Too many open files, unable "
396 "to open more! smbd's max "
398 lp_max_open_files()));
399 last_warned = time((time_t *) NULL);
405 DEBUG(10,("fd_open: name %s, flags = 0%o mode = 0%o, fd = %d. %s\n",
406 smb_fname_str_dbg(smb_fname), flags, (int)mode, fsp->fh->fd,
407 (fsp->fh->fd == -1) ? strerror(errno) : "" ));
412 /****************************************************************************
413 Close the file associated with a fsp.
414 ****************************************************************************/
416 NTSTATUS fd_close(files_struct *fsp)
423 if (fsp->fh->fd == -1) {
424 return NT_STATUS_OK; /* What we used to call a stat open. */
426 if (fsp->fh->ref_count > 1) {
427 return NT_STATUS_OK; /* Shared handle. Only close last reference. */
430 ret = SMB_VFS_CLOSE(fsp);
433 return map_nt_error_from_unix(errno);
438 /****************************************************************************
439 Change the ownership of a file to that of the parent directory.
440 Do this by fd if possible.
441 ****************************************************************************/
443 void change_file_owner_to_parent(connection_struct *conn,
444 const char *inherit_from_dir,
447 struct smb_filename *smb_fname_parent;
450 smb_fname_parent = synthetic_smb_fname(talloc_tos(), inherit_from_dir,
452 if (smb_fname_parent == NULL) {
456 ret = SMB_VFS_STAT(conn, smb_fname_parent);
458 DEBUG(0,("change_file_owner_to_parent: failed to stat parent "
459 "directory %s. Error was %s\n",
460 smb_fname_str_dbg(smb_fname_parent),
462 TALLOC_FREE(smb_fname_parent);
466 if (smb_fname_parent->st.st_ex_uid == fsp->fsp_name->st.st_ex_uid) {
467 /* Already this uid - no need to change. */
468 DEBUG(10,("change_file_owner_to_parent: file %s "
469 "is already owned by uid %d\n",
471 (int)fsp->fsp_name->st.st_ex_uid ));
472 TALLOC_FREE(smb_fname_parent);
477 ret = SMB_VFS_FCHOWN(fsp, smb_fname_parent->st.st_ex_uid, (gid_t)-1);
480 DEBUG(0,("change_file_owner_to_parent: failed to fchown "
481 "file %s to parent directory uid %u. Error "
482 "was %s\n", fsp_str_dbg(fsp),
483 (unsigned int)smb_fname_parent->st.st_ex_uid,
486 DEBUG(10,("change_file_owner_to_parent: changed new file %s to "
487 "parent directory uid %u.\n", fsp_str_dbg(fsp),
488 (unsigned int)smb_fname_parent->st.st_ex_uid));
489 /* Ensure the uid entry is updated. */
490 fsp->fsp_name->st.st_ex_uid = smb_fname_parent->st.st_ex_uid;
493 TALLOC_FREE(smb_fname_parent);
496 NTSTATUS change_dir_owner_to_parent(connection_struct *conn,
497 const char *inherit_from_dir,
499 SMB_STRUCT_STAT *psbuf)
501 struct smb_filename *smb_fname_parent;
502 struct smb_filename *smb_fname_cwd = NULL;
503 char *saved_dir = NULL;
504 TALLOC_CTX *ctx = talloc_tos();
505 NTSTATUS status = NT_STATUS_OK;
508 smb_fname_parent = synthetic_smb_fname(ctx, inherit_from_dir,
510 if (smb_fname_parent == NULL) {
511 return NT_STATUS_NO_MEMORY;
514 ret = SMB_VFS_STAT(conn, smb_fname_parent);
516 status = map_nt_error_from_unix(errno);
517 DEBUG(0,("change_dir_owner_to_parent: failed to stat parent "
518 "directory %s. Error was %s\n",
519 smb_fname_str_dbg(smb_fname_parent),
524 /* We've already done an lstat into psbuf, and we know it's a
525 directory. If we can cd into the directory and the dev/ino
526 are the same then we can safely chown without races as
527 we're locking the directory in place by being in it. This
528 should work on any UNIX (thanks tridge :-). JRA.
531 saved_dir = vfs_GetWd(ctx,conn);
533 status = map_nt_error_from_unix(errno);
534 DEBUG(0,("change_dir_owner_to_parent: failed to get "
535 "current working directory. Error was %s\n",
540 /* Chdir into the new path. */
541 if (vfs_ChDir(conn, fname) == -1) {
542 status = map_nt_error_from_unix(errno);
543 DEBUG(0,("change_dir_owner_to_parent: failed to change "
544 "current working directory to %s. Error "
545 "was %s\n", fname, strerror(errno) ));
549 smb_fname_cwd = synthetic_smb_fname(ctx, ".", NULL, NULL);
550 if (smb_fname_cwd == NULL) {
551 status = NT_STATUS_NO_MEMORY;
555 ret = SMB_VFS_STAT(conn, smb_fname_cwd);
557 status = map_nt_error_from_unix(errno);
558 DEBUG(0,("change_dir_owner_to_parent: failed to stat "
559 "directory '.' (%s) Error was %s\n",
560 fname, strerror(errno)));
564 /* Ensure we're pointing at the same place. */
565 if (smb_fname_cwd->st.st_ex_dev != psbuf->st_ex_dev ||
566 smb_fname_cwd->st.st_ex_ino != psbuf->st_ex_ino) {
567 DEBUG(0,("change_dir_owner_to_parent: "
568 "device/inode on directory %s changed. "
569 "Refusing to chown !\n", fname ));
570 status = NT_STATUS_ACCESS_DENIED;
574 if (smb_fname_parent->st.st_ex_uid == smb_fname_cwd->st.st_ex_uid) {
575 /* Already this uid - no need to change. */
576 DEBUG(10,("change_dir_owner_to_parent: directory %s "
577 "is already owned by uid %d\n",
579 (int)smb_fname_cwd->st.st_ex_uid ));
580 status = NT_STATUS_OK;
585 ret = SMB_VFS_LCHOWN(conn, ".", smb_fname_parent->st.st_ex_uid,
589 status = map_nt_error_from_unix(errno);
590 DEBUG(10,("change_dir_owner_to_parent: failed to chown "
591 "directory %s to parent directory uid %u. "
592 "Error was %s\n", fname,
593 (unsigned int)smb_fname_parent->st.st_ex_uid,
596 DEBUG(10,("change_dir_owner_to_parent: changed ownership of new "
597 "directory %s to parent directory uid %u.\n",
598 fname, (unsigned int)smb_fname_parent->st.st_ex_uid ));
599 /* Ensure the uid entry is updated. */
600 psbuf->st_ex_uid = smb_fname_parent->st.st_ex_uid;
604 vfs_ChDir(conn,saved_dir);
606 TALLOC_FREE(smb_fname_parent);
607 TALLOC_FREE(smb_fname_cwd);
611 /****************************************************************************
612 Open a file - returning a guaranteed ATOMIC indication of if the
613 file was created or not.
614 ****************************************************************************/
616 static NTSTATUS fd_open_atomic(struct connection_struct *conn,
622 NTSTATUS status = NT_STATUS_UNSUCCESSFUL;
623 bool file_existed = VALID_STAT(fsp->fsp_name->st);
625 *file_created = false;
627 if (!(flags & O_CREAT)) {
629 * We're not creating the file, just pass through.
631 return fd_open(conn, fsp, flags, mode);
634 if (flags & O_EXCL) {
636 * Fail if already exists, just pass through.
638 status = fd_open(conn, fsp, flags, mode);
641 * Here we've opened with O_CREAT|O_EXCL. If that went
642 * NT_STATUS_OK, we *know* we created this file.
644 *file_created = NT_STATUS_IS_OK(status);
650 * Now it gets tricky. We have O_CREAT, but not O_EXCL.
651 * To know absolutely if we created the file or not,
652 * we can never call O_CREAT without O_EXCL. So if
653 * we think the file existed, try without O_CREAT|O_EXCL.
654 * If we think the file didn't exist, try with
655 * O_CREAT|O_EXCL. Keep bouncing between these two
656 * requests until either the file is created, or
657 * opened. Either way, we keep going until we get
658 * a returnable result (error, or open/create).
662 int curr_flags = flags;
665 /* Just try open, do not create. */
666 curr_flags &= ~(O_CREAT);
667 status = fd_open(conn, fsp, curr_flags, mode);
668 if (NT_STATUS_EQUAL(status,
669 NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
671 * Someone deleted it in the meantime.
674 file_existed = false;
675 DEBUG(10,("fd_open_atomic: file %s existed. "
677 smb_fname_str_dbg(fsp->fsp_name)));
681 /* Try create exclusively, fail if it exists. */
682 curr_flags |= O_EXCL;
683 status = fd_open(conn, fsp, curr_flags, mode);
684 if (NT_STATUS_EQUAL(status,
685 NT_STATUS_OBJECT_NAME_COLLISION)) {
687 * Someone created it in the meantime.
688 * Retry without O_CREAT.
691 DEBUG(10,("fd_open_atomic: file %s "
692 "did not exist. Retry.\n",
693 smb_fname_str_dbg(fsp->fsp_name)));
696 if (NT_STATUS_IS_OK(status)) {
698 * Here we've opened with O_CREAT|O_EXCL
699 * and got success. We *know* we created
702 *file_created = true;
705 /* Create is done, or failed. */
711 /****************************************************************************
713 ****************************************************************************/
715 static NTSTATUS open_file(files_struct *fsp,
716 connection_struct *conn,
717 struct smb_request *req,
718 const char *parent_dir,
721 uint32 access_mask, /* client requested access mask. */
722 uint32 open_access_mask, /* what we're actually using in the open. */
723 bool *p_file_created)
725 struct smb_filename *smb_fname = fsp->fsp_name;
726 NTSTATUS status = NT_STATUS_OK;
727 int accmode = (flags & O_ACCMODE);
728 int local_flags = flags;
729 bool file_existed = VALID_STAT(fsp->fsp_name->st);
734 /* Check permissions */
737 * This code was changed after seeing a client open request
738 * containing the open mode of (DENY_WRITE/read-only) with
739 * the 'create if not exist' bit set. The previous code
740 * would fail to open the file read only on a read-only share
741 * as it was checking the flags parameter directly against O_RDONLY,
742 * this was failing as the flags parameter was set to O_RDONLY|O_CREAT.
746 if (!CAN_WRITE(conn)) {
747 /* It's a read-only share - fail if we wanted to write. */
748 if(accmode != O_RDONLY || (flags & O_TRUNC) || (flags & O_APPEND)) {
749 DEBUG(3,("Permission denied opening %s\n",
750 smb_fname_str_dbg(smb_fname)));
751 return NT_STATUS_ACCESS_DENIED;
753 if (flags & O_CREAT) {
754 /* We don't want to write - but we must make sure that
755 O_CREAT doesn't create the file if we have write
756 access into the directory.
758 flags &= ~(O_CREAT|O_EXCL);
759 local_flags &= ~(O_CREAT|O_EXCL);
764 * This little piece of insanity is inspired by the
765 * fact that an NT client can open a file for O_RDONLY,
766 * but set the create disposition to FILE_EXISTS_TRUNCATE.
767 * If the client *can* write to the file, then it expects to
768 * truncate the file, even though it is opening for readonly.
769 * Quicken uses this stupid trick in backup file creation...
770 * Thanks *greatly* to "David W. Chapman Jr." <dwcjr@inethouston.net>
771 * for helping track this one down. It didn't bite us in 2.0.x
772 * as we always opened files read-write in that release. JRA.
775 if ((accmode == O_RDONLY) && ((flags & O_TRUNC) == O_TRUNC)) {
776 DEBUG(10,("open_file: truncate requested on read-only open "
777 "for file %s\n", smb_fname_str_dbg(smb_fname)));
778 local_flags = (flags & ~O_ACCMODE)|O_RDWR;
781 if ((open_access_mask & (FILE_READ_DATA|FILE_WRITE_DATA|FILE_APPEND_DATA|FILE_EXECUTE)) ||
782 (!file_existed && (local_flags & O_CREAT)) ||
783 ((local_flags & O_TRUNC) == O_TRUNC) ) {
787 #if defined(O_NONBLOCK) && defined(S_ISFIFO)
789 * We would block on opening a FIFO with no one else on the
790 * other end. Do what we used to do and add O_NONBLOCK to the
794 if (file_existed && S_ISFIFO(smb_fname->st.st_ex_mode)) {
795 local_flags &= ~O_TRUNC; /* Can't truncate a FIFO. */
796 local_flags |= O_NONBLOCK;
800 /* Don't create files with Microsoft wildcard characters. */
803 * wildcard characters are allowed in stream names
804 * only test the basefilename
806 wild = fsp->base_fsp->fsp_name->base_name;
808 wild = smb_fname->base_name;
810 if ((local_flags & O_CREAT) && !file_existed &&
812 return NT_STATUS_OBJECT_NAME_INVALID;
815 /* Can we access this file ? */
816 if (!fsp->base_fsp) {
817 /* Only do this check on non-stream open. */
819 status = smbd_check_access_rights(conn,
824 if (!NT_STATUS_IS_OK(status)) {
825 DEBUG(10, ("open_file: "
826 "smbd_check_access_rights "
827 "on file %s returned %s\n",
828 smb_fname_str_dbg(smb_fname),
832 if (!NT_STATUS_IS_OK(status) &&
833 !NT_STATUS_EQUAL(status,
834 NT_STATUS_OBJECT_NAME_NOT_FOUND))
839 if (NT_STATUS_EQUAL(status,
840 NT_STATUS_OBJECT_NAME_NOT_FOUND))
842 DEBUG(10, ("open_file: "
843 "file %s vanished since we "
844 "checked for existence.\n",
845 smb_fname_str_dbg(smb_fname)));
846 file_existed = false;
847 SET_STAT_INVALID(fsp->fsp_name->st);
852 if (!(local_flags & O_CREAT)) {
853 /* File didn't exist and no O_CREAT. */
854 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
857 status = check_parent_access(conn,
860 if (!NT_STATUS_IS_OK(status)) {
861 DEBUG(10, ("open_file: "
862 "check_parent_access on "
863 "file %s returned %s\n",
864 smb_fname_str_dbg(smb_fname),
865 nt_errstr(status) ));
872 * Actually do the open - if O_TRUNC is needed handle it
873 * below under the share mode lock.
875 status = fd_open_atomic(conn, fsp, local_flags & ~O_TRUNC,
876 unx_mode, p_file_created);
877 if (!NT_STATUS_IS_OK(status)) {
878 DEBUG(3,("Error opening file %s (%s) (local_flags=%d) "
879 "(flags=%d)\n", smb_fname_str_dbg(smb_fname),
880 nt_errstr(status),local_flags,flags));
884 ret = SMB_VFS_FSTAT(fsp, &smb_fname->st);
886 /* If we have an fd, this stat should succeed. */
887 DEBUG(0,("Error doing fstat on open file %s "
889 smb_fname_str_dbg(smb_fname),
891 status = map_nt_error_from_unix(errno);
896 if (*p_file_created) {
897 /* We created this file. */
899 bool need_re_stat = false;
900 /* Do all inheritance work after we've
901 done a successful fstat call and filled
902 in the stat struct in fsp->fsp_name. */
904 /* Inherit the ACL if required */
905 if (lp_inherit_permissions(SNUM(conn))) {
906 inherit_access_posix_acl(conn, parent_dir,
907 smb_fname->base_name,
912 /* Change the owner if required. */
913 if (lp_inherit_owner(SNUM(conn))) {
914 change_file_owner_to_parent(conn, parent_dir,
920 ret = SMB_VFS_FSTAT(fsp, &smb_fname->st);
921 /* If we have an fd, this stat should succeed. */
923 DEBUG(0,("Error doing fstat on open file %s "
925 smb_fname_str_dbg(smb_fname),
930 notify_fname(conn, NOTIFY_ACTION_ADDED,
931 FILE_NOTIFY_CHANGE_FILE_NAME,
932 smb_fname->base_name);
935 fsp->fh->fd = -1; /* What we used to call a stat open. */
937 /* File must exist for a stat open. */
938 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
941 status = smbd_check_access_rights(conn,
946 if (NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND) &&
948 S_ISLNK(smb_fname->st.st_ex_mode)) {
949 /* This is a POSIX stat open for delete
950 * or rename on a symlink that points
952 DEBUG(10,("open_file: allowing POSIX "
953 "open on bad symlink %s\n",
954 smb_fname_str_dbg(smb_fname)));
955 status = NT_STATUS_OK;
958 if (!NT_STATUS_IS_OK(status)) {
959 DEBUG(10,("open_file: "
960 "smbd_check_access_rights on file "
962 smb_fname_str_dbg(smb_fname),
963 nt_errstr(status) ));
969 * POSIX allows read-only opens of directories. We don't
970 * want to do this (we use a different code path for this)
971 * so catch a directory open and return an EISDIR. JRA.
974 if(S_ISDIR(smb_fname->st.st_ex_mode)) {
977 return NT_STATUS_FILE_IS_A_DIRECTORY;
980 fsp->file_id = vfs_file_id_from_sbuf(conn, &smb_fname->st);
981 fsp->vuid = req ? req->vuid : UID_FIELD_INVALID;
982 fsp->file_pid = req ? req->smbpid : 0;
983 fsp->can_lock = True;
984 fsp->can_read = ((access_mask & FILE_READ_DATA) != 0);
987 ((access_mask & (FILE_WRITE_DATA | FILE_APPEND_DATA)) != 0);
988 fsp->print_file = NULL;
989 fsp->modified = False;
990 fsp->sent_oplock_break = NO_BREAK_SENT;
991 fsp->is_directory = False;
992 if (conn->aio_write_behind_list &&
993 is_in_path(smb_fname->base_name, conn->aio_write_behind_list,
994 conn->case_sensitive)) {
995 fsp->aio_write_behind = True;
998 fsp->wcp = NULL; /* Write cache pointer. */
1000 DEBUG(2,("%s opened file %s read=%s write=%s (numopen=%d)\n",
1001 conn->session_info->unix_info->unix_name,
1002 smb_fname_str_dbg(smb_fname),
1003 BOOLSTR(fsp->can_read), BOOLSTR(fsp->can_write),
1004 conn->num_files_open));
1007 return NT_STATUS_OK;
1010 /****************************************************************************
1011 Check if we can open a file with a share mode.
1012 Returns True if conflict, False if not.
1013 ****************************************************************************/
1015 static bool share_conflict(struct share_mode_entry *entry,
1017 uint32 share_access)
1019 DEBUG(10,("share_conflict: entry->access_mask = 0x%x, "
1020 "entry->share_access = 0x%x, "
1021 "entry->private_options = 0x%x\n",
1022 (unsigned int)entry->access_mask,
1023 (unsigned int)entry->share_access,
1024 (unsigned int)entry->private_options));
1026 if (server_id_is_disconnected(&entry->pid)) {
1028 * note: cleanup should have been done by
1029 * delay_for_batch_oplocks()
1034 DEBUG(10,("share_conflict: access_mask = 0x%x, share_access = 0x%x\n",
1035 (unsigned int)access_mask, (unsigned int)share_access));
1037 if ((entry->access_mask & (FILE_WRITE_DATA|
1041 DELETE_ACCESS)) == 0) {
1042 DEBUG(10,("share_conflict: No conflict due to "
1043 "entry->access_mask = 0x%x\n",
1044 (unsigned int)entry->access_mask ));
1048 if ((access_mask & (FILE_WRITE_DATA|
1052 DELETE_ACCESS)) == 0) {
1053 DEBUG(10,("share_conflict: No conflict due to "
1054 "access_mask = 0x%x\n",
1055 (unsigned int)access_mask ));
1059 #if 1 /* JRA TEST - Superdebug. */
1060 #define CHECK_MASK(num, am, right, sa, share) \
1061 DEBUG(10,("share_conflict: [%d] am (0x%x) & right (0x%x) = 0x%x\n", \
1062 (unsigned int)(num), (unsigned int)(am), \
1063 (unsigned int)(right), (unsigned int)(am)&(right) )); \
1064 DEBUG(10,("share_conflict: [%d] sa (0x%x) & share (0x%x) = 0x%x\n", \
1065 (unsigned int)(num), (unsigned int)(sa), \
1066 (unsigned int)(share), (unsigned int)(sa)&(share) )); \
1067 if (((am) & (right)) && !((sa) & (share))) { \
1068 DEBUG(10,("share_conflict: check %d conflict am = 0x%x, right = 0x%x, \
1069 sa = 0x%x, share = 0x%x\n", (num), (unsigned int)(am), (unsigned int)(right), (unsigned int)(sa), \
1070 (unsigned int)(share) )); \
1074 #define CHECK_MASK(num, am, right, sa, share) \
1075 if (((am) & (right)) && !((sa) & (share))) { \
1076 DEBUG(10,("share_conflict: check %d conflict am = 0x%x, right = 0x%x, \
1077 sa = 0x%x, share = 0x%x\n", (num), (unsigned int)(am), (unsigned int)(right), (unsigned int)(sa), \
1078 (unsigned int)(share) )); \
1083 CHECK_MASK(1, entry->access_mask, FILE_WRITE_DATA | FILE_APPEND_DATA,
1084 share_access, FILE_SHARE_WRITE);
1085 CHECK_MASK(2, access_mask, FILE_WRITE_DATA | FILE_APPEND_DATA,
1086 entry->share_access, FILE_SHARE_WRITE);
1088 CHECK_MASK(3, entry->access_mask, FILE_READ_DATA | FILE_EXECUTE,
1089 share_access, FILE_SHARE_READ);
1090 CHECK_MASK(4, access_mask, FILE_READ_DATA | FILE_EXECUTE,
1091 entry->share_access, FILE_SHARE_READ);
1093 CHECK_MASK(5, entry->access_mask, DELETE_ACCESS,
1094 share_access, FILE_SHARE_DELETE);
1095 CHECK_MASK(6, access_mask, DELETE_ACCESS,
1096 entry->share_access, FILE_SHARE_DELETE);
1098 DEBUG(10,("share_conflict: No conflict.\n"));
1102 #if defined(DEVELOPER)
1103 static void validate_my_share_entries(struct smbd_server_connection *sconn,
1105 struct share_mode_entry *share_entry)
1107 struct server_id self = messaging_server_id(sconn->msg_ctx);
1110 if (!serverid_equal(&self, &share_entry->pid)) {
1114 if (share_entry->op_mid == 0) {
1115 /* INTERNAL_OPEN_ONLY */
1119 if (!is_valid_share_mode_entry(share_entry)) {
1123 fsp = file_find_dif(sconn, share_entry->id,
1124 share_entry->share_file_id);
1126 DEBUG(0,("validate_my_share_entries: PANIC : %s\n",
1127 share_mode_str(talloc_tos(), num, share_entry) ));
1128 smb_panic("validate_my_share_entries: Cannot match a "
1129 "share entry with an open file\n");
1132 if (((uint16)fsp->oplock_type) != share_entry->op_type) {
1141 DEBUG(0,("validate_my_share_entries: PANIC : %s\n",
1142 share_mode_str(talloc_tos(), num, share_entry) ));
1143 str = talloc_asprintf(talloc_tos(),
1144 "validate_my_share_entries: "
1145 "file %s, oplock_type = 0x%x, op_type = 0x%x\n",
1146 fsp->fsp_name->base_name,
1147 (unsigned int)fsp->oplock_type,
1148 (unsigned int)share_entry->op_type );
1154 bool is_stat_open(uint32 access_mask)
1156 const uint32_t stat_open_bits =
1157 (SYNCHRONIZE_ACCESS|
1158 FILE_READ_ATTRIBUTES|
1159 FILE_WRITE_ATTRIBUTES);
1161 return (((access_mask & stat_open_bits) != 0) &&
1162 ((access_mask & ~stat_open_bits) == 0));
1165 static bool has_delete_on_close(struct share_mode_lock *lck,
1168 struct share_mode_data *d = lck->data;
1171 if (d->num_share_modes == 0) {
1174 if (!is_delete_on_close_set(lck, name_hash)) {
1177 for (i=0; i<d->num_share_modes; i++) {
1178 if (!share_mode_stale_pid(d, i)) {
1185 /****************************************************************************
1186 Deal with share modes
1187 Invariant: Share mode must be locked on entry and exit.
1188 Returns -1 on error, or number of share modes on success (may be zero).
1189 ****************************************************************************/
1191 static NTSTATUS open_mode_check(connection_struct *conn,
1192 struct share_mode_lock *lck,
1194 uint32 share_access)
1198 if(lck->data->num_share_modes == 0) {
1199 return NT_STATUS_OK;
1202 if (is_stat_open(access_mask)) {
1203 /* Stat open that doesn't trigger oplock breaks or share mode
1204 * checks... ! JRA. */
1205 return NT_STATUS_OK;
1209 * Check if the share modes will give us access.
1212 #if defined(DEVELOPER)
1213 for(i = 0; i < lck->data->num_share_modes; i++) {
1214 validate_my_share_entries(conn->sconn, i,
1215 &lck->data->share_modes[i]);
1219 /* Now we check the share modes, after any oplock breaks. */
1220 for(i = 0; i < lck->data->num_share_modes; i++) {
1222 if (!is_valid_share_mode_entry(&lck->data->share_modes[i])) {
1226 /* someone else has a share lock on it, check to see if we can
1228 if (share_conflict(&lck->data->share_modes[i],
1229 access_mask, share_access)) {
1231 if (share_mode_stale_pid(lck->data, i)) {
1235 return NT_STATUS_SHARING_VIOLATION;
1239 return NT_STATUS_OK;
1243 * Send a break message to the oplock holder and delay the open for
1247 NTSTATUS send_break_message(struct messaging_context *msg_ctx,
1248 const struct share_mode_entry *exclusive,
1252 char msg[MSG_SMB_SHARE_MODE_ENTRY_SIZE];
1254 DEBUG(10, ("Sending break request to PID %s\n",
1255 procid_str_static(&exclusive->pid)));
1257 /* Create the message. */
1258 share_mode_entry_to_message(msg, exclusive);
1260 /* Overload entry->op_type */
1262 * This is a cut from uint32 to uint16, but so far only the lower 3
1263 * bits (LEASE_WRITE/HANDLE/READ are used anyway.
1265 SSVAL(msg,OP_BREAK_MSG_OP_TYPE_OFFSET, break_to);
1267 status = messaging_send_buf(msg_ctx, exclusive->pid,
1268 MSG_SMB_BREAK_REQUEST,
1269 (uint8 *)msg, sizeof(msg));
1270 if (!NT_STATUS_IS_OK(status)) {
1271 DEBUG(3, ("Could not send oplock break message: %s\n",
1272 nt_errstr(status)));
1279 * Do internal consistency checks on the share mode for a file.
1282 static bool validate_oplock_types(struct share_mode_lock *lck)
1284 struct share_mode_data *d = lck->data;
1286 bool ex_or_batch = false;
1287 bool level2 = false;
1288 bool no_oplock = false;
1289 uint32_t num_non_stat_opens = 0;
1292 for (i=0; i<d->num_share_modes; i++) {
1293 struct share_mode_entry *e = &d->share_modes[i];
1295 if (!is_valid_share_mode_entry(e)) {
1299 if (e->op_mid == 0) {
1300 /* INTERNAL_OPEN_ONLY */
1304 if (e->op_type == NO_OPLOCK && is_stat_open(e->access_mask)) {
1305 /* We ignore stat opens in the table - they
1306 always have NO_OPLOCK and never get or
1307 cause breaks. JRA. */
1311 num_non_stat_opens += 1;
1313 if (BATCH_OPLOCK_TYPE(e->op_type)) {
1314 /* batch - can only be one. */
1315 if (share_mode_stale_pid(d, i)) {
1316 DEBUG(10, ("Found stale batch oplock\n"));
1319 if (ex_or_batch || batch || level2 || no_oplock) {
1320 DEBUG(0, ("Bad batch oplock entry %u.",
1327 if (EXCLUSIVE_OPLOCK_TYPE(e->op_type)) {
1328 if (share_mode_stale_pid(d, i)) {
1329 DEBUG(10, ("Found stale duplicate oplock\n"));
1332 /* Exclusive or batch - can only be one. */
1333 if (ex_or_batch || level2 || no_oplock) {
1334 DEBUG(0, ("Bad exclusive or batch oplock "
1335 "entry %u.", (unsigned)i));
1341 if (LEVEL_II_OPLOCK_TYPE(e->op_type)) {
1342 if (batch || ex_or_batch) {
1343 if (share_mode_stale_pid(d, i)) {
1344 DEBUG(10, ("Found stale LevelII "
1348 DEBUG(0, ("Bad levelII oplock entry %u.",
1355 if (e->op_type == NO_OPLOCK) {
1356 if (batch || ex_or_batch) {
1357 if (share_mode_stale_pid(d, i)) {
1358 DEBUG(10, ("Found stale NO_OPLOCK "
1362 DEBUG(0, ("Bad no oplock entry %u.",
1370 remove_stale_share_mode_entries(d);
1372 if ((batch || ex_or_batch) && (num_non_stat_opens != 1)) {
1373 DEBUG(1, ("got batch (%d) or ex (%d) non-exclusively (%d)\n",
1374 (int)batch, (int)ex_or_batch,
1375 (int)d->num_share_modes));
1382 static bool delay_for_oplock(files_struct *fsp,
1384 const struct smb2_lease *lease,
1385 struct share_mode_lock *lck,
1386 bool have_sharing_violation,
1387 uint32_t create_disposition,
1388 bool first_open_attempt)
1390 struct share_mode_data *d = lck->data;
1393 bool will_overwrite;
1395 if ((oplock_request & INTERNAL_OPEN_ONLY) ||
1396 is_stat_open(fsp->access_mask)) {
1400 switch (create_disposition) {
1401 case FILE_SUPERSEDE:
1402 case FILE_OVERWRITE:
1403 case FILE_OVERWRITE_IF:
1404 will_overwrite = true;
1407 will_overwrite = false;
1411 for (i=0; i<d->num_share_modes; i++) {
1412 struct share_mode_entry *e = &d->share_modes[i];
1413 struct share_mode_lease *l = NULL;
1414 uint32_t e_lease_type = get_lease_type(d, e);
1416 uint32_t delay_mask = 0;
1418 if (e->op_type == LEASE_OPLOCK) {
1419 l = &d->leases[e->lease_idx];
1422 if (have_sharing_violation) {
1423 delay_mask = SMB2_LEASE_HANDLE;
1425 delay_mask = SMB2_LEASE_WRITE;
1428 break_to = e_lease_type & ~delay_mask;
1430 if (will_overwrite) {
1432 * we'll decide about SMB2_LEASE_READ later.
1434 * Maybe the break will be defered
1436 break_to &= ~SMB2_LEASE_HANDLE;
1439 DEBUG(10, ("entry %u: e_lease_type %u, will_overwrite: %u\n",
1440 (unsigned)i, (unsigned)e_lease_type,
1441 (unsigned)will_overwrite));
1443 if (lease != NULL && l != NULL) {
1446 ign = smb2_lease_equal(fsp_client_guid(fsp),
1455 if ((e_lease_type & ~break_to) == 0) {
1456 if (l != NULL && l->breaking) {
1462 if (share_mode_stale_pid(d, i)) {
1466 if (will_overwrite) {
1468 * If we break anyway break to NONE directly.
1469 * Otherwise vfs_set_filelen() will trigger the
1472 break_to &= ~(SMB2_LEASE_READ|SMB2_LEASE_WRITE);
1475 if (e->op_type != LEASE_OPLOCK) {
1477 * Oplocks only support breaking to R or NONE.
1479 break_to &= ~(SMB2_LEASE_HANDLE|SMB2_LEASE_WRITE);
1482 DEBUG(10, ("breaking from %d to %d\n",
1483 (int)e_lease_type, (int)break_to));
1484 send_break_message(fsp->conn->sconn->msg_ctx, e,
1486 if (e_lease_type & delay_mask) {
1489 if (l != NULL && l->breaking && !first_open_attempt) {
1498 static bool file_has_brlocks(files_struct *fsp)
1500 struct byte_range_lock *br_lck;
1502 br_lck = brl_get_locks_readonly(fsp);
1506 return (brl_num_locks(br_lck) > 0);
1509 int find_share_mode_lease(struct share_mode_data *d,
1510 const struct GUID *client_guid,
1511 const struct smb2_lease_key *key)
1515 for (i=0; i<d->num_leases; i++) {
1516 struct share_mode_lease *l = &d->leases[i];
1518 if (smb2_lease_equal(client_guid,
1529 struct fsp_lease *find_fsp_lease(struct files_struct *new_fsp,
1530 const struct smb2_lease_key *key,
1531 const struct share_mode_lease *l)
1533 struct files_struct *fsp;
1536 * TODO: Measure how expensive this loop is with thousands of open
1540 for (fsp = file_find_di_first(new_fsp->conn->sconn, new_fsp->file_id);
1542 fsp = file_find_di_next(fsp)) {
1544 if (fsp == new_fsp) {
1547 if (fsp->oplock_type != LEASE_OPLOCK) {
1550 if (smb2_lease_key_equal(&fsp->lease->lease.lease_key, key)) {
1551 fsp->lease->ref_count += 1;
1556 /* Not found - must be leased in another smbd. */
1557 new_fsp->lease = talloc_zero(new_fsp->conn->sconn, struct fsp_lease);
1558 if (new_fsp->lease == NULL) {
1561 new_fsp->lease->ref_count = 1;
1562 new_fsp->lease->sconn = new_fsp->conn->sconn;
1563 new_fsp->lease->lease.lease_key = *key;
1564 new_fsp->lease->lease.lease_state = l->current_state;
1566 * We internally treat all leases as V2 and update
1567 * the epoch, but when sending breaks it matters if
1568 * the requesting lease was v1 or v2.
1570 new_fsp->lease->lease.lease_version = l->lease_version;
1571 new_fsp->lease->lease.lease_epoch = l->epoch;
1572 return new_fsp->lease;
1575 static NTSTATUS grant_fsp_lease(struct files_struct *fsp,
1576 struct share_mode_lock *lck,
1577 const struct smb2_lease *lease,
1578 uint32_t *p_lease_idx,
1581 struct share_mode_data *d = lck->data;
1582 const struct GUID *client_guid = fsp_client_guid(fsp);
1583 struct share_mode_lease *tmp;
1587 idx = find_share_mode_lease(d, client_guid, &lease->lease_key);
1590 struct share_mode_lease *l = &d->leases[idx];
1592 uint32_t existing, requested;
1594 fsp->lease = find_fsp_lease(fsp, &lease->lease_key, l);
1595 if (fsp->lease == NULL) {
1596 DEBUG(1, ("Did not find existing lease for file %s\n",
1598 return NT_STATUS_NO_MEMORY;
1604 * Upgrade only if the requested lease is a strict upgrade.
1606 existing = l->current_state;
1607 requested = lease->lease_state;
1610 * Tricky: This test makes sure that "requested" is a
1611 * strict bitwise superset of "existing".
1613 do_upgrade = ((existing & requested) == existing);
1616 * Upgrade only if there's a change.
1618 do_upgrade &= (granted != existing);
1621 * Upgrade only if other leases don't prevent what was asked
1624 do_upgrade &= (granted == requested);
1627 * only upgrade if we are not in breaking state
1629 do_upgrade &= !l->breaking;
1631 DEBUG(10, ("existing=%"PRIu32", requested=%"PRIu32", "
1632 "granted=%"PRIu32", do_upgrade=%d\n",
1633 existing, requested, granted, (int)do_upgrade));
1636 l->current_state = granted;
1640 /* Ensure we're in sync with current lease state. */
1641 fsp_lease_update(lck, fsp_client_guid(fsp), fsp->lease);
1642 return NT_STATUS_OK;
1649 tmp = talloc_realloc(d, d->leases, struct share_mode_lease,
1655 return NT_STATUS_INSUFFICIENT_RESOURCES;
1659 fsp->lease = talloc_zero(fsp->conn->sconn, struct fsp_lease);
1660 if (fsp->lease == NULL) {
1661 return NT_STATUS_INSUFFICIENT_RESOURCES;
1663 fsp->lease->ref_count = 1;
1664 fsp->lease->sconn = fsp->conn->sconn;
1665 fsp->lease->lease.lease_version = lease->lease_version;
1666 fsp->lease->lease.lease_key = lease->lease_key;
1667 fsp->lease->lease.lease_state = granted;
1668 fsp->lease->lease.lease_epoch = lease->lease_epoch + 1;
1670 *p_lease_idx = d->num_leases;
1672 d->leases[d->num_leases] = (struct share_mode_lease) {
1673 .client_guid = *client_guid,
1674 .lease_key = fsp->lease->lease.lease_key,
1675 .current_state = fsp->lease->lease.lease_state,
1676 .lease_version = fsp->lease->lease.lease_version,
1677 .epoch = fsp->lease->lease.lease_epoch,
1680 status = leases_db_add(client_guid,
1683 fsp->conn->connectpath,
1684 fsp->fsp_name->base_name,
1685 fsp->fsp_name->stream_name);
1686 if (!NT_STATUS_IS_OK(status)) {
1687 DEBUG(10, ("%s: leases_db_add failed: %s\n", __func__,
1688 nt_errstr(status)));
1689 TALLOC_FREE(fsp->lease);
1690 return NT_STATUS_INSUFFICIENT_RESOURCES;
1696 return NT_STATUS_OK;
1699 static bool is_same_lease(const files_struct *fsp,
1700 const struct share_mode_data *d,
1701 const struct share_mode_entry *e,
1702 const struct smb2_lease *lease)
1704 if (e->op_type != LEASE_OPLOCK) {
1707 if (lease == NULL) {
1711 return smb2_lease_equal(fsp_client_guid(fsp),
1713 &d->leases[e->lease_idx].client_guid,
1714 &d->leases[e->lease_idx].lease_key);
1717 static NTSTATUS grant_fsp_oplock_type(struct smb_request *req,
1718 struct files_struct *fsp,
1719 struct share_mode_lock *lck,
1721 struct smb2_lease *lease)
1723 struct share_mode_data *d = lck->data;
1724 bool got_handle_lease = false;
1725 bool got_oplock = false;
1728 uint32_t lease_idx = UINT32_MAX;
1732 if (oplock_request & INTERNAL_OPEN_ONLY) {
1733 /* No oplocks on internal open. */
1734 oplock_request = NO_OPLOCK;
1735 DEBUG(10,("grant_fsp_oplock_type: oplock type 0x%x on file %s\n",
1736 fsp->oplock_type, fsp_str_dbg(fsp)));
1739 if (oplock_request == LEASE_OPLOCK) {
1740 if (lease == NULL) {
1742 * The SMB2 layer should have checked this
1744 return NT_STATUS_INTERNAL_ERROR;
1747 granted = lease->lease_state;
1749 if (lp_kernel_oplocks(SNUM(fsp->conn))) {
1750 DEBUG(10, ("No lease granted because kernel oplocks are enabled\n"));
1751 granted = SMB2_LEASE_NONE;
1753 if ((granted & (SMB2_LEASE_READ|SMB2_LEASE_WRITE)) == 0) {
1754 DEBUG(10, ("No read or write lease requested\n"));
1755 granted = SMB2_LEASE_NONE;
1757 if (granted == SMB2_LEASE_WRITE) {
1758 DEBUG(10, ("pure write lease requested\n"));
1759 granted = SMB2_LEASE_NONE;
1761 if (granted == (SMB2_LEASE_WRITE|SMB2_LEASE_HANDLE)) {
1762 DEBUG(10, ("write and handle lease requested\n"));
1763 granted = SMB2_LEASE_NONE;
1766 granted = map_oplock_to_lease_type(
1767 oplock_request & ~SAMBA_PRIVATE_OPLOCK_MASK);
1770 if (lp_locking(fsp->conn->params) && file_has_brlocks(fsp)) {
1771 DEBUG(10,("grant_fsp_oplock_type: file %s has byte range locks\n",
1773 granted &= ~SMB2_LEASE_READ;
1776 for (i=0; i<d->num_share_modes; i++) {
1777 struct share_mode_entry *e = &d->share_modes[i];
1778 uint32_t e_lease_type;
1780 e_lease_type = get_lease_type(d, e);
1782 if ((granted & SMB2_LEASE_WRITE) &&
1783 !is_same_lease(fsp, d, e, lease) &&
1784 !share_mode_stale_pid(d, i)) {
1786 * Can grant only one writer
1788 granted &= ~SMB2_LEASE_WRITE;
1791 if ((e_lease_type & SMB2_LEASE_HANDLE) && !got_handle_lease &&
1792 !share_mode_stale_pid(d, i)) {
1793 got_handle_lease = true;
1796 if ((e->op_type != LEASE_OPLOCK) && !got_oplock &&
1797 !share_mode_stale_pid(d, i)) {
1802 if ((granted & SMB2_LEASE_READ) && !(granted & SMB2_LEASE_WRITE)) {
1804 (global_client_caps & CAP_LEVEL_II_OPLOCKS) &&
1805 lp_level2_oplocks(SNUM(fsp->conn));
1807 if (!allow_level2) {
1808 granted = SMB2_LEASE_NONE;
1812 if (oplock_request == LEASE_OPLOCK) {
1814 granted &= ~SMB2_LEASE_HANDLE;
1817 fsp->oplock_type = LEASE_OPLOCK;
1819 status = grant_fsp_lease(fsp, lck, lease, &lease_idx,
1821 if (!NT_STATUS_IS_OK(status)) {
1825 *lease = fsp->lease->lease;
1826 DEBUG(10, ("lease_state=%d\n", lease->lease_state));
1828 if (got_handle_lease) {
1829 granted = SMB2_LEASE_NONE;
1833 case SMB2_LEASE_READ|SMB2_LEASE_WRITE|SMB2_LEASE_HANDLE:
1834 fsp->oplock_type = BATCH_OPLOCK|EXCLUSIVE_OPLOCK;
1836 case SMB2_LEASE_READ|SMB2_LEASE_WRITE:
1837 fsp->oplock_type = EXCLUSIVE_OPLOCK;
1839 case SMB2_LEASE_READ|SMB2_LEASE_HANDLE:
1840 case SMB2_LEASE_READ:
1841 fsp->oplock_type = LEVEL_II_OPLOCK;
1844 fsp->oplock_type = NO_OPLOCK;
1848 status = set_file_oplock(fsp);
1849 if (!NT_STATUS_IS_OK(status)) {
1851 * Could not get the kernel oplock
1853 fsp->oplock_type = NO_OPLOCK;
1857 ok = set_share_mode(lck, fsp, get_current_uid(fsp->conn),
1862 return NT_STATUS_NO_MEMORY;
1865 ok = update_num_read_oplocks(fsp, lck);
1867 del_share_mode(lck, fsp);
1868 return NT_STATUS_INTERNAL_ERROR;
1871 DEBUG(10,("grant_fsp_oplock_type: oplock type 0x%x on file %s\n",
1872 fsp->oplock_type, fsp_str_dbg(fsp)));
1874 return NT_STATUS_OK;
1877 static bool request_timed_out(struct timeval request_time,
1878 struct timeval timeout)
1880 struct timeval now, end_time;
1882 end_time = timeval_sum(&request_time, &timeout);
1883 return (timeval_compare(&end_time, &now) < 0);
1886 struct defer_open_state {
1887 struct smbXsrv_connection *xconn;
1891 static void defer_open_done(struct tevent_req *req);
1893 /****************************************************************************
1894 Handle the 1 second delay in returning a SHARING_VIOLATION error.
1895 ****************************************************************************/
1897 static void defer_open(struct share_mode_lock *lck,
1898 struct timeval request_time,
1899 struct timeval timeout,
1900 struct smb_request *req,
1901 struct deferred_open_record *state)
1903 struct deferred_open_record *open_rec;
1905 DEBUG(10,("defer_open_sharing_error: time [%u.%06u] adding deferred "
1906 "open entry for mid %llu\n",
1907 (unsigned int)request_time.tv_sec,
1908 (unsigned int)request_time.tv_usec,
1909 (unsigned long long)req->mid));
1911 open_rec = talloc(NULL, struct deferred_open_record);
1912 if (open_rec == NULL) {
1914 exit_server("talloc failed");
1920 struct defer_open_state *watch_state;
1921 struct tevent_req *watch_req;
1924 watch_state = talloc(open_rec, struct defer_open_state);
1925 if (watch_state == NULL) {
1926 exit_server("talloc failed");
1928 watch_state->xconn = req->xconn;
1929 watch_state->mid = req->mid;
1931 DEBUG(10, ("defering mid %llu\n",
1932 (unsigned long long)req->mid));
1934 watch_req = dbwrap_record_watch_send(
1935 watch_state, req->sconn->ev_ctx, lck->data->record,
1936 req->sconn->msg_ctx);
1937 if (watch_req == NULL) {
1938 exit_server("Could not watch share mode record");
1940 tevent_req_set_callback(watch_req, defer_open_done,
1943 ret = tevent_req_set_endtime(
1944 watch_req, req->sconn->ev_ctx,
1945 timeval_sum(&request_time, &timeout));
1949 if (!push_deferred_open_message_smb(req, request_time, timeout,
1950 state->id, open_rec)) {
1952 exit_server("push_deferred_open_message_smb failed");
1956 static void defer_open_done(struct tevent_req *req)
1958 struct defer_open_state *state = tevent_req_callback_data(
1959 req, struct defer_open_state);
1963 status = dbwrap_record_watch_recv(req, talloc_tos(), NULL);
1965 if (!NT_STATUS_IS_OK(status)) {
1966 DEBUG(5, ("dbwrap_record_watch_recv returned %s\n",
1967 nt_errstr(status)));
1969 * Even if it failed, retry anyway. TODO: We need a way to
1970 * tell a re-scheduled open about that error.
1974 DEBUG(10, ("scheduling mid %llu\n", (unsigned long long)state->mid));
1976 ret = schedule_deferred_open_message_smb(state->xconn, state->mid);
1982 /****************************************************************************
1983 On overwrite open ensure that the attributes match.
1984 ****************************************************************************/
1986 static bool open_match_attributes(connection_struct *conn,
1987 uint32 old_dos_attr,
1988 uint32 new_dos_attr,
1989 mode_t existing_unx_mode,
1990 mode_t new_unx_mode,
1991 mode_t *returned_unx_mode)
1993 uint32 noarch_old_dos_attr, noarch_new_dos_attr;
1995 noarch_old_dos_attr = (old_dos_attr & ~FILE_ATTRIBUTE_ARCHIVE);
1996 noarch_new_dos_attr = (new_dos_attr & ~FILE_ATTRIBUTE_ARCHIVE);
1998 if((noarch_old_dos_attr == 0 && noarch_new_dos_attr != 0) ||
1999 (noarch_old_dos_attr != 0 && ((noarch_old_dos_attr & noarch_new_dos_attr) == noarch_old_dos_attr))) {
2000 *returned_unx_mode = new_unx_mode;
2002 *returned_unx_mode = (mode_t)0;
2005 DEBUG(10,("open_match_attributes: old_dos_attr = 0x%x, "
2006 "existing_unx_mode = 0%o, new_dos_attr = 0x%x "
2007 "returned_unx_mode = 0%o\n",
2008 (unsigned int)old_dos_attr,
2009 (unsigned int)existing_unx_mode,
2010 (unsigned int)new_dos_attr,
2011 (unsigned int)*returned_unx_mode ));
2013 /* If we're mapping SYSTEM and HIDDEN ensure they match. */
2014 if (lp_map_system(SNUM(conn)) || lp_store_dos_attributes(SNUM(conn))) {
2015 if ((old_dos_attr & FILE_ATTRIBUTE_SYSTEM) &&
2016 !(new_dos_attr & FILE_ATTRIBUTE_SYSTEM)) {
2020 if (lp_map_hidden(SNUM(conn)) || lp_store_dos_attributes(SNUM(conn))) {
2021 if ((old_dos_attr & FILE_ATTRIBUTE_HIDDEN) &&
2022 !(new_dos_attr & FILE_ATTRIBUTE_HIDDEN)) {
2029 /****************************************************************************
2030 Special FCB or DOS processing in the case of a sharing violation.
2031 Try and find a duplicated file handle.
2032 ****************************************************************************/
2034 static NTSTATUS fcb_or_dos_open(struct smb_request *req,
2035 connection_struct *conn,
2036 files_struct *fsp_to_dup_into,
2037 const struct smb_filename *smb_fname,
2042 uint32 share_access,
2043 uint32 create_options)
2047 DEBUG(5,("fcb_or_dos_open: attempting old open semantics for "
2048 "file %s.\n", smb_fname_str_dbg(smb_fname)));
2050 for(fsp = file_find_di_first(conn->sconn, id); fsp;
2051 fsp = file_find_di_next(fsp)) {
2053 DEBUG(10,("fcb_or_dos_open: checking file %s, fd = %d, "
2054 "vuid = %llu, file_pid = %u, private_options = 0x%x "
2055 "access_mask = 0x%x\n", fsp_str_dbg(fsp),
2056 fsp->fh->fd, (unsigned long long)fsp->vuid,
2057 (unsigned int)fsp->file_pid,
2058 (unsigned int)fsp->fh->private_options,
2059 (unsigned int)fsp->access_mask ));
2061 if (fsp != fsp_to_dup_into &&
2062 fsp->fh->fd != -1 &&
2063 fsp->vuid == vuid &&
2064 fsp->file_pid == file_pid &&
2065 (fsp->fh->private_options & (NTCREATEX_OPTIONS_PRIVATE_DENY_DOS |
2066 NTCREATEX_OPTIONS_PRIVATE_DENY_FCB)) &&
2067 (fsp->access_mask & FILE_WRITE_DATA) &&
2068 strequal(fsp->fsp_name->base_name, smb_fname->base_name) &&
2069 strequal(fsp->fsp_name->stream_name,
2070 smb_fname->stream_name)) {
2071 DEBUG(10,("fcb_or_dos_open: file match\n"));
2077 return NT_STATUS_NOT_FOUND;
2080 /* quite an insane set of semantics ... */
2081 if (is_executable(smb_fname->base_name) &&
2082 (fsp->fh->private_options & NTCREATEX_OPTIONS_PRIVATE_DENY_DOS)) {
2083 DEBUG(10,("fcb_or_dos_open: file fail due to is_executable.\n"));
2084 return NT_STATUS_INVALID_PARAMETER;
2087 /* We need to duplicate this fsp. */
2088 return dup_file_fsp(req, fsp, access_mask, share_access,
2089 create_options, fsp_to_dup_into);
2092 static void schedule_defer_open(struct share_mode_lock *lck,
2094 struct timeval request_time,
2095 struct smb_request *req)
2097 struct deferred_open_record state;
2099 /* This is a relative time, added to the absolute
2100 request_time value to get the absolute timeout time.
2101 Note that if this is the second or greater time we enter
2102 this codepath for this particular request mid then
2103 request_time is left as the absolute time of the *first*
2104 time this request mid was processed. This is what allows
2105 the request to eventually time out. */
2107 struct timeval timeout;
2109 /* Normally the smbd we asked should respond within
2110 * OPLOCK_BREAK_TIMEOUT seconds regardless of whether
2111 * the client did, give twice the timeout as a safety
2112 * measure here in case the other smbd is stuck
2113 * somewhere else. */
2115 timeout = timeval_set(OPLOCK_BREAK_TIMEOUT*2, 0);
2117 /* Nothing actually uses state.delayed_for_oplocks
2118 but it's handy to differentiate in debug messages
2119 between a 30 second delay due to oplock break, and
2120 a 1 second delay for share mode conflicts. */
2122 state.delayed_for_oplocks = True;
2123 state.async_open = false;
2126 if (!request_timed_out(request_time, timeout)) {
2127 defer_open(lck, request_time, timeout, req, &state);
2131 /****************************************************************************
2132 Reschedule an open call that went asynchronous.
2133 ****************************************************************************/
2135 static void schedule_async_open(struct timeval request_time,
2136 struct smb_request *req)
2138 struct deferred_open_record state;
2139 struct timeval timeout;
2141 timeout = timeval_set(20, 0);
2144 state.delayed_for_oplocks = false;
2145 state.async_open = true;
2147 if (!request_timed_out(request_time, timeout)) {
2148 defer_open(NULL, request_time, timeout, req, &state);
2152 /****************************************************************************
2153 Work out what access_mask to use from what the client sent us.
2154 ****************************************************************************/
2156 static NTSTATUS smbd_calculate_maximum_allowed_access(
2157 connection_struct *conn,
2158 const struct smb_filename *smb_fname,
2160 uint32_t *p_access_mask)
2162 struct security_descriptor *sd;
2163 uint32_t access_granted;
2166 if (!use_privs && (get_current_uid(conn) == (uid_t)0)) {
2167 *p_access_mask |= FILE_GENERIC_ALL;
2168 return NT_STATUS_OK;
2171 status = SMB_VFS_GET_NT_ACL(conn, smb_fname->base_name,
2177 if (NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
2179 * File did not exist
2181 *p_access_mask = FILE_GENERIC_ALL;
2182 return NT_STATUS_OK;
2184 if (!NT_STATUS_IS_OK(status)) {
2185 DEBUG(10,("Could not get acl on file %s: %s\n",
2186 smb_fname_str_dbg(smb_fname),
2187 nt_errstr(status)));
2188 return NT_STATUS_ACCESS_DENIED;
2192 * If we can access the path to this file, by
2193 * default we have FILE_READ_ATTRIBUTES from the
2194 * containing directory. See the section:
2195 * "Algorithm to Check Access to an Existing File"
2198 * se_file_access_check()
2199 * also takes care of owner WRITE_DAC and READ_CONTROL.
2201 status = se_file_access_check(sd,
2202 get_current_nttok(conn),
2204 (*p_access_mask & ~FILE_READ_ATTRIBUTES),
2209 if (!NT_STATUS_IS_OK(status)) {
2210 DEBUG(10, ("Access denied on file %s: "
2211 "when calculating maximum access\n",
2212 smb_fname_str_dbg(smb_fname)));
2213 return NT_STATUS_ACCESS_DENIED;
2215 *p_access_mask = (access_granted | FILE_READ_ATTRIBUTES);
2217 if (!(access_granted & DELETE_ACCESS)) {
2218 if (can_delete_file_in_directory(conn, smb_fname)) {
2219 *p_access_mask |= DELETE_ACCESS;
2223 return NT_STATUS_OK;
2226 NTSTATUS smbd_calculate_access_mask(connection_struct *conn,
2227 const struct smb_filename *smb_fname,
2229 uint32_t access_mask,
2230 uint32_t *access_mask_out)
2233 uint32_t orig_access_mask = access_mask;
2234 uint32_t rejected_share_access;
2237 * Convert GENERIC bits to specific bits.
2240 se_map_generic(&access_mask, &file_generic_mapping);
2242 /* Calculate MAXIMUM_ALLOWED_ACCESS if requested. */
2243 if (access_mask & MAXIMUM_ALLOWED_ACCESS) {
2245 status = smbd_calculate_maximum_allowed_access(
2246 conn, smb_fname, use_privs, &access_mask);
2248 if (!NT_STATUS_IS_OK(status)) {
2252 access_mask &= conn->share_access;
2255 rejected_share_access = access_mask & ~(conn->share_access);
2257 if (rejected_share_access) {
2258 DEBUG(10, ("smbd_calculate_access_mask: Access denied on "
2259 "file %s: rejected by share access mask[0x%08X] "
2260 "orig[0x%08X] mapped[0x%08X] reject[0x%08X]\n",
2261 smb_fname_str_dbg(smb_fname),
2263 orig_access_mask, access_mask,
2264 rejected_share_access));
2265 return NT_STATUS_ACCESS_DENIED;
2268 *access_mask_out = access_mask;
2269 return NT_STATUS_OK;
2272 /****************************************************************************
2273 Remove the deferred open entry under lock.
2274 ****************************************************************************/
2276 /****************************************************************************
2277 Return true if this is a state pointer to an asynchronous create.
2278 ****************************************************************************/
2280 bool is_deferred_open_async(const struct deferred_open_record *rec)
2282 return rec->async_open;
2285 static bool clear_ads(uint32_t create_disposition)
2289 switch (create_disposition) {
2290 case FILE_SUPERSEDE:
2291 case FILE_OVERWRITE_IF:
2292 case FILE_OVERWRITE:
2301 static int disposition_to_open_flags(uint32_t create_disposition)
2306 * Currently we're using FILE_SUPERSEDE as the same as
2307 * FILE_OVERWRITE_IF but they really are
2308 * different. FILE_SUPERSEDE deletes an existing file
2309 * (requiring delete access) then recreates it.
2312 switch (create_disposition) {
2313 case FILE_SUPERSEDE:
2314 case FILE_OVERWRITE_IF:
2316 * If file exists replace/overwrite. If file doesn't
2319 ret = O_CREAT|O_TRUNC;
2324 * If file exists open. If file doesn't exist error.
2329 case FILE_OVERWRITE:
2331 * If file exists overwrite. If file doesn't exist
2339 * If file exists error. If file doesn't exist create.
2341 ret = O_CREAT|O_EXCL;
2346 * If file exists open. If file doesn't exist create.
2354 static int calculate_open_access_flags(uint32_t access_mask,
2356 uint32_t private_flags)
2358 bool need_write, need_read;
2361 * Note that we ignore the append flag as append does not
2362 * mean the same thing under DOS and Unix.
2365 need_write = (access_mask & (FILE_WRITE_DATA | FILE_APPEND_DATA));
2370 /* DENY_DOS opens are always underlying read-write on the
2371 file handle, no matter what the requested access mask
2375 ((private_flags & NTCREATEX_OPTIONS_PRIVATE_DENY_DOS) ||
2376 access_mask & (FILE_READ_ATTRIBUTES|FILE_READ_DATA|
2377 FILE_READ_EA|FILE_EXECUTE));
2385 /****************************************************************************
2386 Open a file with a share mode. Passed in an already created files_struct *.
2387 ****************************************************************************/
2389 static NTSTATUS open_file_ntcreate(connection_struct *conn,
2390 struct smb_request *req,
2391 uint32 access_mask, /* access bits (FILE_READ_DATA etc.) */
2392 uint32 share_access, /* share constants (FILE_SHARE_READ etc) */
2393 uint32 create_disposition, /* FILE_OPEN_IF etc. */
2394 uint32 create_options, /* options such as delete on close. */
2395 uint32 new_dos_attributes, /* attributes used for new file. */
2396 int oplock_request, /* internal Samba oplock codes. */
2397 struct smb2_lease *lease,
2398 /* Information (FILE_EXISTS etc.) */
2399 uint32_t private_flags, /* Samba specific flags. */
2403 struct smb_filename *smb_fname = fsp->fsp_name;
2406 bool file_existed = VALID_STAT(smb_fname->st);
2407 bool def_acl = False;
2408 bool posix_open = False;
2409 bool new_file_created = False;
2410 bool first_open_attempt = true;
2411 NTSTATUS fsp_open = NT_STATUS_ACCESS_DENIED;
2412 mode_t new_unx_mode = (mode_t)0;
2413 mode_t unx_mode = (mode_t)0;
2415 uint32 existing_dos_attributes = 0;
2416 struct timeval request_time = timeval_zero();
2417 struct share_mode_lock *lck = NULL;
2418 uint32 open_access_mask = access_mask;
2421 SMB_STRUCT_STAT saved_stat = smb_fname->st;
2422 struct timespec old_write_time;
2425 if (conn->printer) {
2427 * Printers are handled completely differently.
2428 * Most of the passed parameters are ignored.
2432 *pinfo = FILE_WAS_CREATED;
2435 DEBUG(10, ("open_file_ntcreate: printer open fname=%s\n",
2436 smb_fname_str_dbg(smb_fname)));
2439 DEBUG(0,("open_file_ntcreate: printer open without "
2440 "an SMB request!\n"));
2441 return NT_STATUS_INTERNAL_ERROR;
2444 return print_spool_open(fsp, smb_fname->base_name,
2448 if (!parent_dirname(talloc_tos(), smb_fname->base_name, &parent_dir,
2450 return NT_STATUS_NO_MEMORY;
2453 if (new_dos_attributes & FILE_FLAG_POSIX_SEMANTICS) {
2455 unx_mode = (mode_t)(new_dos_attributes & ~FILE_FLAG_POSIX_SEMANTICS);
2456 new_dos_attributes = 0;
2458 /* Windows allows a new file to be created and
2459 silently removes a FILE_ATTRIBUTE_DIRECTORY
2460 sent by the client. Do the same. */
2462 new_dos_attributes &= ~FILE_ATTRIBUTE_DIRECTORY;
2464 /* We add FILE_ATTRIBUTE_ARCHIVE to this as this mode is only used if the file is
2466 unx_mode = unix_mode(conn, new_dos_attributes | FILE_ATTRIBUTE_ARCHIVE,
2467 smb_fname, parent_dir);
2470 DEBUG(10, ("open_file_ntcreate: fname=%s, dos_attrs=0x%x "
2471 "access_mask=0x%x share_access=0x%x "
2472 "create_disposition = 0x%x create_options=0x%x "
2473 "unix mode=0%o oplock_request=%d private_flags = 0x%x\n",
2474 smb_fname_str_dbg(smb_fname), new_dos_attributes,
2475 access_mask, share_access, create_disposition,
2476 create_options, (unsigned int)unx_mode, oplock_request,
2477 (unsigned int)private_flags));
2480 /* Ensure req == NULL means INTERNAL_OPEN_ONLY */
2481 SMB_ASSERT(((oplock_request & INTERNAL_OPEN_ONLY) != 0));
2483 /* And req != NULL means no INTERNAL_OPEN_ONLY */
2484 SMB_ASSERT(((oplock_request & INTERNAL_OPEN_ONLY) == 0));
2488 * Only non-internal opens can be deferred at all
2492 struct deferred_open_record *open_rec;
2493 if (get_deferred_open_message_state(req,
2496 /* Remember the absolute time of the original
2497 request with this mid. We'll use it later to
2498 see if this has timed out. */
2500 /* If it was an async create retry, the file
2503 if (is_deferred_open_async(open_rec)) {
2504 SET_STAT_INVALID(smb_fname->st);
2505 file_existed = false;
2508 /* Ensure we don't reprocess this message. */
2509 remove_deferred_open_message_smb(req->xconn, req->mid);
2511 first_open_attempt = false;
2516 new_dos_attributes &= SAMBA_ATTRIBUTES_MASK;
2518 existing_dos_attributes = dos_mode(conn, smb_fname);
2522 /* ignore any oplock requests if oplocks are disabled */
2523 if (!lp_oplocks(SNUM(conn)) ||
2524 IS_VETO_OPLOCK_PATH(conn, smb_fname->base_name)) {
2525 /* Mask off everything except the private Samba bits. */
2526 oplock_request &= SAMBA_PRIVATE_OPLOCK_MASK;
2529 /* this is for OS/2 long file names - say we don't support them */
2530 if (!lp_posix_pathnames() && strstr(smb_fname->base_name,".+,;=[].")) {
2531 /* OS/2 Workplace shell fix may be main code stream in a later
2533 DEBUG(5,("open_file_ntcreate: OS/2 long filenames are not "
2535 if (use_nt_status()) {
2536 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
2538 return NT_STATUS_DOS(ERRDOS, ERRcannotopen);
2541 switch( create_disposition ) {
2543 /* If file exists open. If file doesn't exist error. */
2544 if (!file_existed) {
2545 DEBUG(5,("open_file_ntcreate: FILE_OPEN "
2546 "requested for file %s and file "
2548 smb_fname_str_dbg(smb_fname)));
2550 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
2554 case FILE_OVERWRITE:
2555 /* If file exists overwrite. If file doesn't exist
2557 if (!file_existed) {
2558 DEBUG(5,("open_file_ntcreate: FILE_OVERWRITE "
2559 "requested for file %s and file "
2561 smb_fname_str_dbg(smb_fname) ));
2563 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
2568 /* If file exists error. If file doesn't exist
2571 DEBUG(5,("open_file_ntcreate: FILE_CREATE "
2572 "requested for file %s and file "
2573 "already exists.\n",
2574 smb_fname_str_dbg(smb_fname)));
2575 if (S_ISDIR(smb_fname->st.st_ex_mode)) {
2580 return map_nt_error_from_unix(errno);
2584 case FILE_SUPERSEDE:
2585 case FILE_OVERWRITE_IF:
2589 return NT_STATUS_INVALID_PARAMETER;
2592 flags2 = disposition_to_open_flags(create_disposition);
2594 /* We only care about matching attributes on file exists and
2597 if (!posix_open && file_existed &&
2598 ((create_disposition == FILE_OVERWRITE) ||
2599 (create_disposition == FILE_OVERWRITE_IF))) {
2600 if (!open_match_attributes(conn, existing_dos_attributes,
2602 smb_fname->st.st_ex_mode,
2603 unx_mode, &new_unx_mode)) {
2604 DEBUG(5,("open_file_ntcreate: attributes missmatch "
2605 "for file %s (%x %x) (0%o, 0%o)\n",
2606 smb_fname_str_dbg(smb_fname),
2607 existing_dos_attributes,
2609 (unsigned int)smb_fname->st.st_ex_mode,
2610 (unsigned int)unx_mode ));
2612 return NT_STATUS_ACCESS_DENIED;
2616 status = smbd_calculate_access_mask(conn, smb_fname,
2620 if (!NT_STATUS_IS_OK(status)) {
2621 DEBUG(10, ("open_file_ntcreate: smbd_calculate_access_mask "
2622 "on file %s returned %s\n",
2623 smb_fname_str_dbg(smb_fname), nt_errstr(status)));
2627 open_access_mask = access_mask;
2629 if (flags2 & O_TRUNC) {
2630 open_access_mask |= FILE_WRITE_DATA; /* This will cause oplock breaks. */
2633 DEBUG(10, ("open_file_ntcreate: fname=%s, after mapping "
2634 "access_mask=0x%x\n", smb_fname_str_dbg(smb_fname),
2638 * Note that we ignore the append flag as append does not
2639 * mean the same thing under DOS and Unix.
2642 flags = calculate_open_access_flags(access_mask, oplock_request,
2646 * Currently we only look at FILE_WRITE_THROUGH for create options.
2650 if ((create_options & FILE_WRITE_THROUGH) && lp_strict_sync(SNUM(conn))) {
2655 if (posix_open && (access_mask & FILE_APPEND_DATA)) {
2659 if (!posix_open && !CAN_WRITE(conn)) {
2661 * We should really return a permission denied error if either
2662 * O_CREAT or O_TRUNC are set, but for compatibility with
2663 * older versions of Samba we just AND them out.
2665 flags2 &= ~(O_CREAT|O_TRUNC);
2668 if (first_open_attempt && lp_kernel_oplocks(SNUM(conn))) {
2670 * With kernel oplocks the open breaking an oplock
2671 * blocks until the oplock holder has given up the
2672 * oplock or closed the file. We prevent this by first
2673 * trying to open the file with O_NONBLOCK (see "man
2674 * fcntl" on Linux). For the second try, triggered by
2675 * an oplock break response, we do not need this
2678 * This is true under the assumption that only Samba
2679 * requests kernel oplocks. Once someone else like
2680 * NFSv4 starts to use that API, we will have to
2681 * modify this by communicating with the NFSv4 server.
2683 flags2 |= O_NONBLOCK;
2687 * Ensure we can't write on a read-only share or file.
2690 if (flags != O_RDONLY && file_existed &&
2691 (!CAN_WRITE(conn) || IS_DOS_READONLY(existing_dos_attributes))) {
2692 DEBUG(5,("open_file_ntcreate: write access requested for "
2693 "file %s on read only %s\n",
2694 smb_fname_str_dbg(smb_fname),
2695 !CAN_WRITE(conn) ? "share" : "file" ));
2697 return NT_STATUS_ACCESS_DENIED;
2700 fsp->file_id = vfs_file_id_from_sbuf(conn, &smb_fname->st);
2701 fsp->share_access = share_access;
2702 fsp->fh->private_options = private_flags;
2703 fsp->access_mask = open_access_mask; /* We change this to the
2704 * requested access_mask after
2705 * the open is done. */
2706 fsp->posix_open = posix_open;
2708 if (timeval_is_zero(&request_time)) {
2709 request_time = fsp->open_time;
2713 * Ensure we pay attention to default ACLs on directories if required.
2716 if ((flags2 & O_CREAT) && lp_inherit_acls(SNUM(conn)) &&
2717 (def_acl = directory_has_default_acl(conn, parent_dir))) {
2718 unx_mode = (0777 & lp_create_mask(SNUM(conn)));
2721 DEBUG(4,("calling open_file with flags=0x%X flags2=0x%X mode=0%o, "
2722 "access_mask = 0x%x, open_access_mask = 0x%x\n",
2723 (unsigned int)flags, (unsigned int)flags2,
2724 (unsigned int)unx_mode, (unsigned int)access_mask,
2725 (unsigned int)open_access_mask));
2727 fsp_open = open_file(fsp, conn, req, parent_dir,
2728 flags|flags2, unx_mode, access_mask,
2729 open_access_mask, &new_file_created);
2731 if (NT_STATUS_EQUAL(fsp_open, NT_STATUS_NETWORK_BUSY)) {
2732 struct deferred_open_record state;
2735 * EWOULDBLOCK/EAGAIN maps to NETWORK_BUSY.
2737 if (file_existed && S_ISFIFO(fsp->fsp_name->st.st_ex_mode)) {
2738 DEBUG(10, ("FIFO busy\n"));
2739 return NT_STATUS_NETWORK_BUSY;
2742 DEBUG(10, ("Internal open busy\n"));
2743 return NT_STATUS_NETWORK_BUSY;
2747 * From here on we assume this is an oplock break triggered
2750 lck = get_existing_share_mode_lock(talloc_tos(), fsp->file_id);
2752 state.delayed_for_oplocks = false;
2753 state.async_open = false;
2754 state.id = fsp->file_id;
2755 defer_open(NULL, request_time, timeval_set(0, 0),
2757 DEBUG(10, ("No share mode lock found after "
2758 "EWOULDBLOCK, retrying sync\n"));
2759 return NT_STATUS_SHARING_VIOLATION;
2762 if (!validate_oplock_types(lck)) {
2763 smb_panic("validate_oplock_types failed");
2766 if (delay_for_oplock(fsp, 0, lease, lck, false,
2767 create_disposition, first_open_attempt)) {
2768 schedule_defer_open(lck, fsp->file_id, request_time,
2771 DEBUG(10, ("Sent oplock break request to kernel "
2772 "oplock holder\n"));
2773 return NT_STATUS_SHARING_VIOLATION;
2777 * No oplock from Samba around. Immediately retry with
2780 state.delayed_for_oplocks = false;
2781 state.async_open = false;
2782 state.id = fsp->file_id;
2783 defer_open(lck, request_time, timeval_set(0, 0), req, &state);
2785 DEBUG(10, ("No Samba oplock around after EWOULDBLOCK. "
2786 "Retrying sync\n"));
2787 return NT_STATUS_SHARING_VIOLATION;
2790 if (!NT_STATUS_IS_OK(fsp_open)) {
2791 if (NT_STATUS_EQUAL(fsp_open, NT_STATUS_RETRY)) {
2792 schedule_async_open(request_time, req);
2797 if (new_file_created) {
2799 * As we atomically create using O_CREAT|O_EXCL,
2800 * then if new_file_created is true, then
2801 * file_existed *MUST* have been false (even
2802 * if the file was previously detected as being
2805 file_existed = false;
2808 if (file_existed && !check_same_dev_ino(&saved_stat, &smb_fname->st)) {
2810 * The file did exist, but some other (local or NFS)
2811 * process either renamed/unlinked and re-created the
2812 * file with different dev/ino after we walked the path,
2813 * but before we did the open. We could retry the
2814 * open but it's a rare enough case it's easier to
2815 * just fail the open to prevent creating any problems
2816 * in the open file db having the wrong dev/ino key.
2819 DEBUG(1,("open_file_ntcreate: file %s - dev/ino mismatch. "
2820 "Old (dev=0x%llu, ino =0x%llu). "
2821 "New (dev=0x%llu, ino=0x%llu). Failing open "
2822 " with NT_STATUS_ACCESS_DENIED.\n",
2823 smb_fname_str_dbg(smb_fname),
2824 (unsigned long long)saved_stat.st_ex_dev,
2825 (unsigned long long)saved_stat.st_ex_ino,
2826 (unsigned long long)smb_fname->st.st_ex_dev,
2827 (unsigned long long)smb_fname->st.st_ex_ino));
2828 return NT_STATUS_ACCESS_DENIED;
2831 old_write_time = smb_fname->st.st_ex_mtime;
2834 * Deal with the race condition where two smbd's detect the
2835 * file doesn't exist and do the create at the same time. One
2836 * of them will win and set a share mode, the other (ie. this
2837 * one) should check if the requested share mode for this
2838 * create is allowed.
2842 * Now the file exists and fsp is successfully opened,
2843 * fsp->dev and fsp->inode are valid and should replace the
2844 * dev=0,inode=0 from a non existent file. Spotted by
2845 * Nadav Danieli <nadavd@exanet.com>. JRA.
2850 lck = get_share_mode_lock(talloc_tos(), id,
2852 smb_fname, &old_write_time);
2855 DEBUG(0, ("open_file_ntcreate: Could not get share "
2856 "mode lock for %s\n",
2857 smb_fname_str_dbg(smb_fname)));
2859 return NT_STATUS_SHARING_VIOLATION;
2862 /* Get the types we need to examine. */
2863 if (!validate_oplock_types(lck)) {
2864 smb_panic("validate_oplock_types failed");
2867 if (has_delete_on_close(lck, fsp->name_hash)) {
2870 return NT_STATUS_DELETE_PENDING;
2873 status = open_mode_check(conn, lck,
2874 access_mask, share_access);
2876 if (NT_STATUS_EQUAL(status, NT_STATUS_SHARING_VIOLATION) ||
2877 (lck->data->num_share_modes > 0)) {
2879 * This comes from ancient times out of open_mode_check. I
2880 * have no clue whether this is still necessary. I can't think
2881 * of a case where this would actually matter further down in
2882 * this function. I leave it here for further investigation
2885 file_existed = true;
2888 if ((req != NULL) &&
2890 fsp, oplock_request, lease, lck,
2891 NT_STATUS_EQUAL(status, NT_STATUS_SHARING_VIOLATION),
2892 create_disposition, first_open_attempt)) {
2893 schedule_defer_open(lck, fsp->file_id, request_time, req);
2896 return NT_STATUS_SHARING_VIOLATION;
2899 if (!NT_STATUS_IS_OK(status)) {
2900 uint32 can_access_mask;
2901 bool can_access = True;
2903 SMB_ASSERT(NT_STATUS_EQUAL(status, NT_STATUS_SHARING_VIOLATION));
2905 /* Check if this can be done with the deny_dos and fcb
2908 (NTCREATEX_OPTIONS_PRIVATE_DENY_DOS|
2909 NTCREATEX_OPTIONS_PRIVATE_DENY_FCB)) {
2911 DEBUG(0, ("DOS open without an SMB "
2915 return NT_STATUS_INTERNAL_ERROR;
2918 /* Use the client requested access mask here,
2919 * not the one we open with. */
2920 status = fcb_or_dos_open(req,
2931 if (NT_STATUS_IS_OK(status)) {
2934 *pinfo = FILE_WAS_OPENED;
2936 return NT_STATUS_OK;
2941 * This next line is a subtlety we need for
2942 * MS-Access. If a file open will fail due to share
2943 * permissions and also for security (access) reasons,
2944 * we need to return the access failed error, not the
2945 * share error. We can't open the file due to kernel
2946 * oplock deadlock (it's possible we failed above on
2947 * the open_mode_check()) so use a userspace check.
2950 if (flags & O_RDWR) {
2951 can_access_mask = FILE_READ_DATA|FILE_WRITE_DATA;
2952 } else if (flags & O_WRONLY) {
2953 can_access_mask = FILE_WRITE_DATA;
2955 can_access_mask = FILE_READ_DATA;
2958 if (((can_access_mask & FILE_WRITE_DATA) &&
2959 !CAN_WRITE(conn)) ||
2960 !NT_STATUS_IS_OK(smbd_check_access_rights(conn,
2963 can_access_mask))) {
2968 * If we're returning a share violation, ensure we
2969 * cope with the braindead 1 second delay (SMB1 only).
2972 if (!(oplock_request & INTERNAL_OPEN_ONLY) &&
2973 !conn->sconn->using_smb2 &&
2974 lp_defer_sharing_violations()) {
2975 struct timeval timeout;
2976 struct deferred_open_record state;
2979 /* this is a hack to speed up torture tests
2981 timeout_usecs = lp_parm_int(SNUM(conn),
2982 "smbd","sharedelay",
2983 SHARING_VIOLATION_USEC_WAIT);
2985 /* This is a relative time, added to the absolute
2986 request_time value to get the absolute timeout time.
2987 Note that if this is the second or greater time we enter
2988 this codepath for this particular request mid then
2989 request_time is left as the absolute time of the *first*
2990 time this request mid was processed. This is what allows
2991 the request to eventually time out. */
2993 timeout = timeval_set(0, timeout_usecs);
2995 /* Nothing actually uses state.delayed_for_oplocks
2996 but it's handy to differentiate in debug messages
2997 between a 30 second delay due to oplock break, and
2998 a 1 second delay for share mode conflicts. */
3000 state.delayed_for_oplocks = False;
3001 state.async_open = false;
3005 && !request_timed_out(request_time,
3007 defer_open(lck, request_time, timeout,
3016 * We have detected a sharing violation here
3017 * so return the correct error code
3019 status = NT_STATUS_SHARING_VIOLATION;
3021 status = NT_STATUS_ACCESS_DENIED;
3026 /* Should we atomically (to the client at least) truncate ? */
3027 if ((!new_file_created) &&
3028 (flags2 & O_TRUNC) &&
3029 (!S_ISFIFO(fsp->fsp_name->st.st_ex_mode))) {
3032 ret = vfs_set_filelen(fsp, 0);
3034 status = map_nt_error_from_unix(errno);
3042 * We have the share entry *locked*.....
3045 /* Delete streams if create_disposition requires it */
3046 if (!new_file_created && clear_ads(create_disposition) &&
3047 !is_ntfs_stream_smb_fname(smb_fname)) {
3048 status = delete_all_streams(conn, smb_fname->base_name);
3049 if (!NT_STATUS_IS_OK(status)) {
3056 /* note that we ignore failure for the following. It is
3057 basically a hack for NFS, and NFS will never set one of
3058 these only read them. Nobody but Samba can ever set a deny
3059 mode and we have already checked our more authoritative
3060 locking database for permission to set this deny mode. If
3061 the kernel refuses the operations then the kernel is wrong.
3062 note that GPFS supports it as well - jmcd */
3064 if (fsp->fh->fd != -1 && lp_kernel_share_modes(SNUM(conn))) {
3066 ret_flock = SMB_VFS_KERNEL_FLOCK(fsp, share_access, access_mask);
3067 if(ret_flock == -1 ){
3072 return NT_STATUS_SHARING_VIOLATION;
3077 * At this point onwards, we can guarantee that the share entry
3078 * is locked, whether we created the file or not, and that the
3079 * deny mode is compatible with all current opens.
3083 * According to Samba4, SEC_FILE_READ_ATTRIBUTE is always granted,
3084 * but we don't have to store this - just ignore it on access check.
3086 if (conn->sconn->using_smb2) {
3088 * SMB2 doesn't return it (according to Microsoft tests).
3089 * Test Case: TestSuite_ScenarioNo009GrantedAccessTestS0
3090 * File created with access = 0x7 (Read, Write, Delete)
3091 * Query Info on file returns 0x87 (Read, Write, Delete, Read Attributes)
3093 fsp->access_mask = access_mask;
3095 /* But SMB1 does. */
3096 fsp->access_mask = access_mask | FILE_READ_ATTRIBUTES;
3101 * stat opens on existing files don't get oplocks or leases.
3103 * Note that we check for stat open on the *open_access_mask*,
3104 * i.e. the access mask we actually used to do the open,
3105 * not the one the client asked for (which is in
3106 * fsp->access_mask). This is due to the fact that
3107 * FILE_OVERWRITE and FILE_OVERWRITE_IF add in O_TRUNC,
3108 * which adds FILE_WRITE_DATA to open_access_mask.
3110 if (is_stat_open(open_access_mask)) {
3112 lease->lease_state = SMB2_LEASE_NONE;
3114 oplock_request = NO_OPLOCK;
3119 if (new_file_created) {
3120 info = FILE_WAS_CREATED;
3122 if (flags2 & O_TRUNC) {
3123 info = FILE_WAS_OVERWRITTEN;
3125 info = FILE_WAS_OPENED;
3134 * Setup the oplock info in both the shared memory and
3137 status = grant_fsp_oplock_type(req, fsp, lck, oplock_request, lease);
3138 if (!NT_STATUS_IS_OK(status)) {
3144 /* Handle strange delete on close create semantics. */
3145 if (create_options & FILE_DELETE_ON_CLOSE) {
3147 status = can_set_delete_on_close(fsp, new_dos_attributes);
3149 if (!NT_STATUS_IS_OK(status)) {
3150 /* Remember to delete the mode we just added. */
3151 del_share_mode(lck, fsp);
3156 /* Note that here we set the *inital* delete on close flag,
3157 not the regular one. The magic gets handled in close. */
3158 fsp->initial_delete_on_close = True;
3161 if (info != FILE_WAS_OPENED) {
3162 /* Files should be initially set as archive */
3163 if (lp_map_archive(SNUM(conn)) ||
3164 lp_store_dos_attributes(SNUM(conn))) {
3166 if (file_set_dosmode(conn, smb_fname,
3167 new_dos_attributes | FILE_ATTRIBUTE_ARCHIVE,
3168 parent_dir, true) == 0) {
3169 unx_mode = smb_fname->st.st_ex_mode;
3175 /* Determine sparse flag. */
3177 /* POSIX opens are sparse by default. */
3178 fsp->is_sparse = true;
3180 fsp->is_sparse = (file_existed &&
3181 (existing_dos_attributes & FILE_ATTRIBUTE_SPARSE));
3185 * Take care of inherited ACLs on created files - if default ACL not
3189 if (!posix_open && new_file_created && !def_acl) {
3191 int saved_errno = errno; /* We might get ENOSYS in the next
3194 if (SMB_VFS_FCHMOD_ACL(fsp, unx_mode) == -1 &&
3196 errno = saved_errno; /* Ignore ENOSYS */
3199 } else if (new_unx_mode) {
3203 /* Attributes need changing. File already existed. */
3206 int saved_errno = errno; /* We might get ENOSYS in the
3208 ret = SMB_VFS_FCHMOD_ACL(fsp, new_unx_mode);
3210 if (ret == -1 && errno == ENOSYS) {
3211 errno = saved_errno; /* Ignore ENOSYS */
3213 DEBUG(5, ("open_file_ntcreate: reset "
3214 "attributes of file %s to 0%o\n",
3215 smb_fname_str_dbg(smb_fname),
3216 (unsigned int)new_unx_mode));
3217 ret = 0; /* Don't do the fchmod below. */
3222 (SMB_VFS_FCHMOD(fsp, new_unx_mode) == -1))
3223 DEBUG(5, ("open_file_ntcreate: failed to reset "
3224 "attributes of file %s to 0%o\n",
3225 smb_fname_str_dbg(smb_fname),
3226 (unsigned int)new_unx_mode));
3231 * Deal with other opens having a modified write time.
3233 struct timespec write_time = get_share_mode_write_time(lck);
3235 if (!null_timespec(write_time)) {
3236 update_stat_ex_mtime(&fsp->fsp_name->st, write_time);
3242 return NT_STATUS_OK;
3245 static NTSTATUS mkdir_internal(connection_struct *conn,
3246 struct smb_filename *smb_dname,
3247 uint32 file_attributes)
3250 char *parent_dir = NULL;
3252 bool posix_open = false;
3253 bool need_re_stat = false;
3254 uint32_t access_mask = SEC_DIR_ADD_SUBDIR;
3256 if (!CAN_WRITE(conn) || (access_mask & ~(conn->share_access))) {
3257 DEBUG(5,("mkdir_internal: failing share access "
3258 "%s\n", lp_servicename(talloc_tos(), SNUM(conn))));
3259 return NT_STATUS_ACCESS_DENIED;
3262 if (!parent_dirname(talloc_tos(), smb_dname->base_name, &parent_dir,
3264 return NT_STATUS_NO_MEMORY;
3267 if (file_attributes & FILE_FLAG_POSIX_SEMANTICS) {
3269 mode = (mode_t)(file_attributes & ~FILE_FLAG_POSIX_SEMANTICS);
3271 mode = unix_mode(conn, FILE_ATTRIBUTE_DIRECTORY, smb_dname, parent_dir);
3274 status = check_parent_access(conn,
3277 if(!NT_STATUS_IS_OK(status)) {
3278 DEBUG(5,("mkdir_internal: check_parent_access "
3279 "on directory %s for path %s returned %s\n",
3281 smb_dname->base_name,
3282 nt_errstr(status) ));
3286 if (SMB_VFS_MKDIR(conn, smb_dname->base_name, mode) != 0) {
3287 return map_nt_error_from_unix(errno);
3290 /* Ensure we're checking for a symlink here.... */
3291 /* We don't want to get caught by a symlink racer. */
3293 if (SMB_VFS_LSTAT(conn, smb_dname) == -1) {
3294 DEBUG(2, ("Could not stat directory '%s' just created: %s\n",
3295 smb_fname_str_dbg(smb_dname), strerror(errno)));
3296 return map_nt_error_from_unix(errno);
3299 if (!S_ISDIR(smb_dname->st.st_ex_mode)) {
3300 DEBUG(0, ("Directory '%s' just created is not a directory !\n",
3301 smb_fname_str_dbg(smb_dname)));
3302 return NT_STATUS_NOT_A_DIRECTORY;
3305 if (lp_store_dos_attributes(SNUM(conn))) {
3307 file_set_dosmode(conn, smb_dname,
3308 file_attributes | FILE_ATTRIBUTE_DIRECTORY,
3313 if (lp_inherit_permissions(SNUM(conn))) {
3314 inherit_access_posix_acl(conn, parent_dir,
3315 smb_dname->base_name, mode);
3316 need_re_stat = true;
3321 * Check if high bits should have been set,
3322 * then (if bits are missing): add them.
3323 * Consider bits automagically set by UNIX, i.e. SGID bit from parent
3326 if ((mode & ~(S_IRWXU|S_IRWXG|S_IRWXO)) &&
3327 (mode & ~smb_dname->st.st_ex_mode)) {
3328 SMB_VFS_CHMOD(conn, smb_dname->base_name,
3329 (smb_dname->st.st_ex_mode |
3330 (mode & ~smb_dname->st.st_ex_mode)));
3331 need_re_stat = true;
3335 /* Change the owner if required. */
3336 if (lp_inherit_owner(SNUM(conn))) {
3337 change_dir_owner_to_parent(conn, parent_dir,
3338 smb_dname->base_name,
3340 need_re_stat = true;
3344 if (SMB_VFS_LSTAT(conn, smb_dname) == -1) {
3345 DEBUG(2, ("Could not stat directory '%s' just created: %s\n",
3346 smb_fname_str_dbg(smb_dname), strerror(errno)));
3347 return map_nt_error_from_unix(errno);
3351 notify_fname(conn, NOTIFY_ACTION_ADDED, FILE_NOTIFY_CHANGE_DIR_NAME,
3352 smb_dname->base_name);
3354 return NT_STATUS_OK;
3357 /****************************************************************************
3358 Open a directory from an NT SMB call.
3359 ****************************************************************************/
3361 static NTSTATUS open_directory(connection_struct *conn,
3362 struct smb_request *req,
3363 struct smb_filename *smb_dname,
3365 uint32 share_access,
3366 uint32 create_disposition,
3367 uint32 create_options,
3368 uint32 file_attributes,
3370 files_struct **result)
3372 files_struct *fsp = NULL;
3373 bool dir_existed = VALID_STAT(smb_dname->st) ? True : False;
3374 struct share_mode_lock *lck = NULL;
3376 struct timespec mtimespec;
3380 if (is_ntfs_stream_smb_fname(smb_dname)) {
3381 DEBUG(2, ("open_directory: %s is a stream name!\n",
3382 smb_fname_str_dbg(smb_dname)));
3383 return NT_STATUS_NOT_A_DIRECTORY;
3386 if (!(file_attributes & FILE_FLAG_POSIX_SEMANTICS)) {
3387 /* Ensure we have a directory attribute. */
3388 file_attributes |= FILE_ATTRIBUTE_DIRECTORY;
3391 DEBUG(5,("open_directory: opening directory %s, access_mask = 0x%x, "
3392 "share_access = 0x%x create_options = 0x%x, "
3393 "create_disposition = 0x%x, file_attributes = 0x%x\n",
3394 smb_fname_str_dbg(smb_dname),
3395 (unsigned int)access_mask,
3396 (unsigned int)share_access,
3397 (unsigned int)create_options,
3398 (unsigned int)create_disposition,
3399 (unsigned int)file_attributes));
3401 status = smbd_calculate_access_mask(conn, smb_dname, false,
3402 access_mask, &access_mask);
3403 if (!NT_STATUS_IS_OK(status)) {
3404 DEBUG(10, ("open_directory: smbd_calculate_access_mask "
3405 "on file %s returned %s\n",
3406 smb_fname_str_dbg(smb_dname),
3407 nt_errstr(status)));
3411 if ((access_mask & SEC_FLAG_SYSTEM_SECURITY) &&
3412 !security_token_has_privilege(get_current_nttok(conn),
3413 SEC_PRIV_SECURITY)) {
3414 DEBUG(10, ("open_directory: open on %s "
3415 "failed - SEC_FLAG_SYSTEM_SECURITY denied.\n",
3416 smb_fname_str_dbg(smb_dname)));
3417 return NT_STATUS_PRIVILEGE_NOT_HELD;
3420 switch( create_disposition ) {
3424 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3427 info = FILE_WAS_OPENED;
3432 /* If directory exists error. If directory doesn't
3436 status = NT_STATUS_OBJECT_NAME_COLLISION;
3437 DEBUG(2, ("open_directory: unable to create "
3438 "%s. Error was %s\n",
3439 smb_fname_str_dbg(smb_dname),
3440 nt_errstr(status)));
3444 status = mkdir_internal(conn, smb_dname,
3447 if (!NT_STATUS_IS_OK(status)) {
3448 DEBUG(2, ("open_directory: unable to create "
3449 "%s. Error was %s\n",
3450 smb_fname_str_dbg(smb_dname),
3451 nt_errstr(status)));
3455 info = FILE_WAS_CREATED;
3460 * If directory exists open. If directory doesn't
3465 status = NT_STATUS_OK;
3466 info = FILE_WAS_OPENED;
3468 status = mkdir_internal(conn, smb_dname,
3471 if (NT_STATUS_IS_OK(status)) {
3472 info = FILE_WAS_CREATED;
3474 /* Cope with create race. */
3475 if (!NT_STATUS_EQUAL(status,
3476 NT_STATUS_OBJECT_NAME_COLLISION)) {
3477 DEBUG(2, ("open_directory: unable to create "
3478 "%s. Error was %s\n",
3479 smb_fname_str_dbg(smb_dname),
3480 nt_errstr(status)));
3483 info = FILE_WAS_OPENED;
3489 case FILE_SUPERSEDE:
3490 case FILE_OVERWRITE:
3491 case FILE_OVERWRITE_IF:
3493 DEBUG(5,("open_directory: invalid create_disposition "
3494 "0x%x for directory %s\n",
3495 (unsigned int)create_disposition,
3496 smb_fname_str_dbg(smb_dname)));
3497 return NT_STATUS_INVALID_PARAMETER;
3500 if(!S_ISDIR(smb_dname->st.st_ex_mode)) {
3501 DEBUG(5,("open_directory: %s is not a directory !\n",
3502 smb_fname_str_dbg(smb_dname)));
3503 return NT_STATUS_NOT_A_DIRECTORY;
3506 if (info == FILE_WAS_OPENED) {
3507 status = smbd_check_access_rights(conn,
3511 if (!NT_STATUS_IS_OK(status)) {
3512 DEBUG(10, ("open_directory: smbd_check_access_rights on "
3513 "file %s failed with %s\n",
3514 smb_fname_str_dbg(smb_dname),
3515 nt_errstr(status)));
3520 status = file_new(req, conn, &fsp);
3521 if(!NT_STATUS_IS_OK(status)) {
3526 * Setup the files_struct for it.
3529 fsp->file_id = vfs_file_id_from_sbuf(conn, &smb_dname->st);
3530 fsp->vuid = req ? req->vuid : UID_FIELD_INVALID;
3531 fsp->file_pid = req ? req->smbpid : 0;
3532 fsp->can_lock = False;
3533 fsp->can_read = False;
3534 fsp->can_write = False;
3536 fsp->share_access = share_access;
3537 fsp->fh->private_options = 0;
3539 * According to Samba4, SEC_FILE_READ_ATTRIBUTE is always granted,
3541 fsp->access_mask = access_mask | FILE_READ_ATTRIBUTES;
3542 fsp->print_file = NULL;
3543 fsp->modified = False;
3544 fsp->oplock_type = NO_OPLOCK;
3545 fsp->sent_oplock_break = NO_BREAK_SENT;
3546 fsp->is_directory = True;
3547 fsp->posix_open = (file_attributes & FILE_FLAG_POSIX_SEMANTICS) ? True : False;
3548 status = fsp_set_smb_fname(fsp, smb_dname);
3549 if (!NT_STATUS_IS_OK(status)) {
3550 file_free(req, fsp);
3554 /* Don't store old timestamps for directory
3555 handles in the internal database. We don't
3556 update them in there if new objects
3557 are creaded in the directory. Currently
3558 we only update timestamps on file writes.
3561 ZERO_STRUCT(mtimespec);
3563 if (access_mask & (FILE_LIST_DIRECTORY|
3565 FILE_ADD_SUBDIRECTORY|
3568 FILE_DELETE_CHILD)) {
3570 status = fd_open(conn, fsp, O_RDONLY|O_DIRECTORY, 0);
3572 /* POSIX allows us to open a directory with O_RDONLY. */
3573 status = fd_open(conn, fsp, O_RDONLY, 0);
3575 if (!NT_STATUS_IS_OK(status)) {
3576 DEBUG(5, ("open_directory: Could not open fd for "
3578 smb_fname_str_dbg(smb_dname),
3579 nt_errstr(status)));
3580 file_free(req, fsp);
3585 DEBUG(10, ("Not opening Directory %s\n",
3586 smb_fname_str_dbg(smb_dname)));
3589 status = vfs_stat_fsp(fsp);
3590 if (!NT_STATUS_IS_OK(status)) {
3592 file_free(req, fsp);
3596 /* Ensure there was no race condition. */
3597 if (!check_same_stat(&smb_dname->st, &fsp->fsp_name->st)) {
3598 DEBUG(5,("open_directory: stat struct differs for "
3600 smb_fname_str_dbg(smb_dname)));
3602 file_free(req, fsp);
3603 return NT_STATUS_ACCESS_DENIED;
3606 lck = get_share_mode_lock(talloc_tos(), fsp->file_id,
3607 conn->connectpath, smb_dname,
3611 DEBUG(0, ("open_directory: Could not get share mode lock for "
3612 "%s\n", smb_fname_str_dbg(smb_dname)));
3614 file_free(req, fsp);
3615 return NT_STATUS_SHARING_VIOLATION;
3618 if (has_delete_on_close(lck, fsp->name_hash)) {
3621 file_free(req, fsp);
3622 return NT_STATUS_DELETE_PENDING;
3625 status = open_mode_check(conn, lck,
3626 access_mask, share_access);
3628 if (!NT_STATUS_IS_OK(status)) {
3631 file_free(req, fsp);
3635 ok = set_share_mode(lck, fsp, get_current_uid(conn),
3636 req ? req->mid : 0, NO_OPLOCK,
3641 file_free(req, fsp);
3642 return NT_STATUS_NO_MEMORY;
3645 /* For directories the delete on close bit at open time seems
3646 always to be honored on close... See test 19 in Samba4 BASE-DELETE. */
3647 if (create_options & FILE_DELETE_ON_CLOSE) {
3648 status = can_set_delete_on_close(fsp, 0);
3649 if (!NT_STATUS_IS_OK(status) && !NT_STATUS_EQUAL(status, NT_STATUS_DIRECTORY_NOT_EMPTY)) {
3650 del_share_mode(lck, fsp);
3653 file_free(req, fsp);
3657 if (NT_STATUS_IS_OK(status)) {
3658 /* Note that here we set the *inital* delete on close flag,
3659 not the regular one. The magic gets handled in close. */
3660 fsp->initial_delete_on_close = True;
3666 * Deal with other opens having a modified write time. Is this
3667 * possible for directories?
3669 struct timespec write_time = get_share_mode_write_time(lck);
3671 if (!null_timespec(write_time)) {
3672 update_stat_ex_mtime(&fsp->fsp_name->st, write_time);
3683 return NT_STATUS_OK;
3686 NTSTATUS create_directory(connection_struct *conn, struct smb_request *req,
3687 struct smb_filename *smb_dname)
3692 status = SMB_VFS_CREATE_FILE(
3695 0, /* root_dir_fid */
3696 smb_dname, /* fname */
3697 FILE_READ_ATTRIBUTES, /* access_mask */
3698 FILE_SHARE_NONE, /* share_access */
3699 FILE_CREATE, /* create_disposition*/
3700 FILE_DIRECTORY_FILE, /* create_options */
3701 FILE_ATTRIBUTE_DIRECTORY, /* file_attributes */
3702 0, /* oplock_request */
3704 0, /* allocation_size */
3705 0, /* private_flags */
3710 NULL, NULL); /* create context */
3712 if (NT_STATUS_IS_OK(status)) {
3713 close_file(req, fsp, NORMAL_CLOSE);
3719 /****************************************************************************
3720 Receive notification that one of our open files has been renamed by another
3722 ****************************************************************************/
3724 void msg_file_was_renamed(struct messaging_context *msg,
3727 struct server_id server_id,
3731 char *frm = (char *)data->data;
3733 const char *sharepath;
3734 const char *base_name;
3735 const char *stream_name;
3736 struct smb_filename *smb_fname = NULL;
3737 size_t sp_len, bn_len;
3739 struct smbd_server_connection *sconn =
3740 talloc_get_type_abort(private_data,
3741 struct smbd_server_connection);
3743 if (data->data == NULL
3744 || data->length < MSG_FILE_RENAMED_MIN_SIZE + 2) {
3745 DEBUG(0, ("msg_file_was_renamed: Got invalid msg len %d\n",
3746 (int)data->length));
3750 /* Unpack the message. */
3751 pull_file_id_24(frm, &id);
3752 sharepath = &frm[24];
3753 sp_len = strlen(sharepath);
3754 base_name = sharepath + sp_len + 1;
3755 bn_len = strlen(base_name);
3756 stream_name = sharepath + sp_len + 1 + bn_len + 1;
3758 /* stream_name must always be NULL if there is no stream. */
3759 if (stream_name[0] == '\0') {
3763 smb_fname = synthetic_smb_fname(talloc_tos(), base_name,
3765 if (smb_fname == NULL) {
3769 DEBUG(10,("msg_file_was_renamed: Got rename message for sharepath %s, new name %s, "
3771 sharepath, smb_fname_str_dbg(smb_fname),
3772 file_id_string_tos(&id)));
3774 for(fsp = file_find_di_first(sconn, id); fsp;
3775 fsp = file_find_di_next(fsp)) {
3776 if (memcmp(fsp->conn->connectpath, sharepath, sp_len) == 0) {
3778 DEBUG(10,("msg_file_was_renamed: renaming file %s from %s -> %s\n",
3779 fsp_fnum_dbg(fsp), fsp_str_dbg(fsp),
3780 smb_fname_str_dbg(smb_fname)));
3781 status = fsp_set_smb_fname(fsp, smb_fname);
3782 if (!NT_STATUS_IS_OK(status)) {
3787 /* Now we have the complete path we can work out if this is
3788 actually within this share and adjust newname accordingly. */
3789 DEBUG(10,("msg_file_was_renamed: share mismatch (sharepath %s "
3790 "not sharepath %s) "
3791 "%s from %s -> %s\n",
3792 fsp->conn->connectpath,
3796 smb_fname_str_dbg(smb_fname)));
3800 TALLOC_FREE(smb_fname);
3805 * If a main file is opened for delete, all streams need to be checked for
3806 * !FILE_SHARE_DELETE. Do this by opening with DELETE_ACCESS.
3807 * If that works, delete them all by setting the delete on close and close.
3810 NTSTATUS open_streams_for_delete(connection_struct *conn,
3813 struct stream_struct *stream_info = NULL;
3814 files_struct **streams = NULL;
3816 unsigned int num_streams = 0;
3817 TALLOC_CTX *frame = talloc_stackframe();
3820 status = vfs_streaminfo(conn, NULL, fname, talloc_tos(),
3821 &num_streams, &stream_info);
3823 if (NT_STATUS_EQUAL(status, NT_STATUS_NOT_IMPLEMENTED)
3824 || NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
3825 DEBUG(10, ("no streams around\n"));
3827 return NT_STATUS_OK;
3830 if (!NT_STATUS_IS_OK(status)) {
3831 DEBUG(10, ("vfs_streaminfo failed: %s\n",
3832 nt_errstr(status)));
3836 DEBUG(10, ("open_streams_for_delete found %d streams\n",
3839 if (num_streams == 0) {
3841 return NT_STATUS_OK;
3844 streams = talloc_array(talloc_tos(), files_struct *, num_streams);
3845 if (streams == NULL) {
3846 DEBUG(0, ("talloc failed\n"));
3847 status = NT_STATUS_NO_MEMORY;
3851 for (i=0; i<num_streams; i++) {
3852 struct smb_filename *smb_fname;
3854 if (strequal(stream_info[i].name, "::$DATA")) {
3859 smb_fname = synthetic_smb_fname(
3860 talloc_tos(), fname, stream_info[i].name, NULL);
3861 if (smb_fname == NULL) {
3862 status = NT_STATUS_NO_MEMORY;
3866 if (SMB_VFS_STAT(conn, smb_fname) == -1) {
3867 DEBUG(10, ("Unable to stat stream: %s\n",
3868 smb_fname_str_dbg(smb_fname)));
3871 status = SMB_VFS_CREATE_FILE(
3874 0, /* root_dir_fid */
3875 smb_fname, /* fname */
3876 DELETE_ACCESS, /* access_mask */
3877 (FILE_SHARE_READ | /* share_access */
3878 FILE_SHARE_WRITE | FILE_SHARE_DELETE),
3879 FILE_OPEN, /* create_disposition*/
3880 0, /* create_options */
3881 FILE_ATTRIBUTE_NORMAL, /* file_attributes */
3882 0, /* oplock_request */
3884 0, /* allocation_size */
3885 NTCREATEX_OPTIONS_PRIVATE_STREAM_DELETE, /* private_flags */
3888 &streams[i], /* result */
3890 NULL, NULL); /* create context */
3892 if (!NT_STATUS_IS_OK(status)) {
3893 DEBUG(10, ("Could not open stream %s: %s\n",
3894 smb_fname_str_dbg(smb_fname),
3895 nt_errstr(status)));
3897 TALLOC_FREE(smb_fname);
3900 TALLOC_FREE(smb_fname);
3904 * don't touch the variable "status" beyond this point :-)
3907 for (i -= 1 ; i >= 0; i--) {
3908 if (streams[i] == NULL) {
3912 DEBUG(10, ("Closing stream # %d, %s\n", i,
3913 fsp_str_dbg(streams[i])));
3914 close_file(NULL, streams[i], NORMAL_CLOSE);
3922 /*********************************************************************
3923 Create a default ACL by inheriting from the parent. If no inheritance
3924 from the parent available, don't set anything. This will leave the actual
3925 permissions the new file or directory already got from the filesystem
3926 as the NT ACL when read.
3927 *********************************************************************/
3929 static NTSTATUS inherit_new_acl(files_struct *fsp)
3931 TALLOC_CTX *frame = talloc_stackframe();
3932 char *parent_name = NULL;
3933 struct security_descriptor *parent_desc = NULL;
3934 NTSTATUS status = NT_STATUS_OK;
3935 struct security_descriptor *psd = NULL;
3936 const struct dom_sid *owner_sid = NULL;
3937 const struct dom_sid *group_sid = NULL;
3938 uint32_t security_info_sent = (SECINFO_OWNER | SECINFO_GROUP | SECINFO_DACL);
3939 struct security_token *token = fsp->conn->session_info->security_token;
3940 bool inherit_owner = lp_inherit_owner(SNUM(fsp->conn));
3941 bool inheritable_components = false;
3942 bool try_builtin_administrators = false;
3943 const struct dom_sid *BA_U_sid = NULL;
3944 const struct dom_sid *BA_G_sid = NULL;
3945 bool try_system = false;
3946 const struct dom_sid *SY_U_sid = NULL;
3947 const struct dom_sid *SY_G_sid = NULL;
3950 if (!parent_dirname(frame, fsp->fsp_name->base_name, &parent_name, NULL)) {
3952 return NT_STATUS_NO_MEMORY;
3955 status = SMB_VFS_GET_NT_ACL(fsp->conn,
3957 (SECINFO_OWNER | SECINFO_GROUP | SECINFO_DACL),
3960 if (!NT_STATUS_IS_OK(status)) {
3965 inheritable_components = sd_has_inheritable_components(parent_desc,
3968 if (!inheritable_components && !inherit_owner) {
3970 /* Nothing to inherit and not setting owner. */
3971 return NT_STATUS_OK;
3974 /* Create an inherited descriptor from the parent. */
3976 if (DEBUGLEVEL >= 10) {
3977 DEBUG(10,("inherit_new_acl: parent acl for %s is:\n",
3978 fsp_str_dbg(fsp) ));
3979 NDR_PRINT_DEBUG(security_descriptor, parent_desc);
3982 /* Inherit from parent descriptor if "inherit owner" set. */
3983 if (inherit_owner) {
3984 owner_sid = parent_desc->owner_sid;
3985 group_sid = parent_desc->group_sid;
3988 if (owner_sid == NULL) {
3989 if (security_token_has_builtin_administrators(token)) {
3990 try_builtin_administrators = true;
3991 } else if (security_token_is_system(token)) {
3992 try_builtin_administrators = true;
3997 if (group_sid == NULL &&
3998 token->num_sids == PRIMARY_GROUP_SID_INDEX)
4000 if (security_token_is_system(token)) {
4001 try_builtin_administrators = true;
4006 if (try_builtin_administrators) {
4011 ok = sids_to_unixids(&global_sid_Builtin_Administrators, 1, &ids);
4015 BA_U_sid = &global_sid_Builtin_Administrators;
4016 BA_G_sid = &global_sid_Builtin_Administrators;
4019 BA_U_sid = &global_sid_Builtin_Administrators;
4022 BA_G_sid = &global_sid_Builtin_Administrators;
4035 ok = sids_to_unixids(&global_sid_System, 1, &ids);
4039 SY_U_sid = &global_sid_System;
4040 SY_G_sid = &global_sid_System;
4043 SY_U_sid = &global_sid_System;
4046 SY_G_sid = &global_sid_System;
4054 if (owner_sid == NULL) {
4055 owner_sid = BA_U_sid;
4058 if (owner_sid == NULL) {
4059 owner_sid = SY_U_sid;
4062 if (group_sid == NULL) {
4063 group_sid = SY_G_sid;
4066 if (try_system && group_sid == NULL) {
4067 group_sid = BA_G_sid;
4070 if (owner_sid == NULL) {
4071 owner_sid = &token->sids[PRIMARY_USER_SID_INDEX];
4073 if (group_sid == NULL) {
4074 if (token->num_sids == PRIMARY_GROUP_SID_INDEX) {
4075 group_sid = &token->sids[PRIMARY_USER_SID_INDEX];
4077 group_sid = &token->sids[PRIMARY_GROUP_SID_INDEX];
4081 status = se_create_child_secdesc(frame,
4088 if (!NT_STATUS_IS_OK(status)) {
4093 /* If inheritable_components == false,
4094 se_create_child_secdesc()
4095 creates a security desriptor with a NULL dacl
4096 entry, but with SEC_DESC_DACL_PRESENT. We need
4097 to remove that flag. */
4099 if (!inheritable_components) {
4100 security_info_sent &= ~SECINFO_DACL;
4101 psd->type &= ~SEC_DESC_DACL_PRESENT;
4104 if (DEBUGLEVEL >= 10) {
4105 DEBUG(10,("inherit_new_acl: child acl for %s is:\n",
4106 fsp_str_dbg(fsp) ));
4107 NDR_PRINT_DEBUG(security_descriptor, psd);
4110 if (inherit_owner) {
4111 /* We need to be root to force this. */
4114 status = SMB_VFS_FSET_NT_ACL(fsp,
4117 if (inherit_owner) {
4125 * If we already have a lease, it must match the new file id. [MS-SMB2]
4126 * 3.3.5.9.8 speaks about INVALID_PARAMETER if an already used lease key is
4127 * used for a different file name.
4130 struct lease_fname_match_state {
4131 /* Input parameters. */
4132 const struct smb_filename *fname;
4135 /* Return parameters. */
4136 uint32_t num_file_ids;
4137 struct file_id *ids;
4138 NTSTATUS match_status;
4141 static void lease_fname_match_parser(
4142 uint32_t num_file_ids,
4143 struct file_id *ids, const char *filename, const char *stream_name,
4146 struct lease_fname_match_state *state =
4147 (struct lease_fname_match_state *)private_data;
4149 if (!strequal(filename, state->fname->base_name) ||
4150 !strequal(stream_name, state->fname->stream_name))
4152 /* Names don't match lease key. */
4153 state->match_status = NT_STATUS_INVALID_PARAMETER;
4157 if (state->file_existed &&
4158 num_file_ids == 1 &&
4159 file_id_equal(&ids[0],&state->id))
4161 /* Common case - non-dynamic share. We're ok.. */
4162 state->match_status = NT_STATUS_OK;
4167 * More than one file id, or not equal, or new file
4168 * being created and there's already an existing lease
4169 * on this (client_guid, lease id) pair.
4170 * Don't allow leases.
4173 state->match_status = NT_STATUS_OPLOCK_NOT_GRANTED;
4174 state->num_file_ids = num_file_ids;
4175 state->ids = talloc_memdup(talloc_tos(),
4177 num_file_ids * sizeof(struct file_id));
4178 if (state->ids == NULL) {
4179 state->match_status = NT_STATUS_NO_MEMORY;
4183 static NTSTATUS lease_match(connection_struct *conn,
4184 struct smb_request *req,
4185 struct smb2_lease_key *lease_key,
4186 const struct smb_filename *fname,
4187 uint16_t *p_version,
4190 struct smbd_server_connection *sconn = req->sconn;
4191 struct lease_fname_match_state state = {
4193 .match_status = NT_STATUS_OK
4198 state.file_existed = VALID_STAT(fname->st);
4199 if (state.file_existed) {
4200 state.id = vfs_file_id_from_sbuf(conn, &fname->st);
4202 memset(&state.id, '\0', sizeof(state.id));
4205 status = leases_db_parse(&sconn->client->connections->smb2.client.guid,
4206 lease_key, lease_fname_match_parser, &state);
4207 if (!NT_STATUS_IS_OK(status)) {
4209 * Not found or error means okay: We can make the lease pass
4211 return NT_STATUS_OK;
4213 if (!NT_STATUS_EQUAL(state.match_status, NT_STATUS_OPLOCK_NOT_GRANTED)) {
4215 * Anything but NT_STATUS_OPLOCK_NOT_GRANTED, let the caller
4218 return state.match_status;
4221 /* We have to break all existing leases. */
4222 for (i = 0; i < state.num_file_ids; i++) {
4223 struct share_mode_lock *lck;
4224 struct share_mode_data *d;
4227 if (file_id_equal(&state.ids[i], &state.id)) {
4228 /* Don't need to break our own file. */
4232 lck = get_existing_share_mode_lock(talloc_tos(), state.ids[i]);
4234 /* Race condition - file already closed. */
4238 for (j=0; j<d->num_share_modes; j++) {
4239 struct share_mode_entry *e = &d->share_modes[j];
4240 uint32_t e_lease_type = get_lease_type(d, e);
4241 struct share_mode_lease *l = NULL;
4243 if (share_mode_stale_pid(d, j)) {
4247 if (e->op_type == LEASE_OPLOCK) {
4248 l = &lck->data->leases[e->lease_idx];
4249 if (!smb2_lease_key_equal(&l->lease_key,
4253 *p_epoch = l->epoch;
4254 *p_version = l->lease_version;
4257 if (e_lease_type == SMB2_LEASE_NONE) {
4261 send_break_message(conn->sconn->msg_ctx, e,
4265 * Windows 7 and 8 lease clients
4266 * are broken in that they will not
4267 * respond to lease break requests
4268 * whilst waiting for an outstanding
4269 * open request on that lease handle
4270 * on the same TCP connection, due
4271 * to holding an internal inode lock.
4273 * This means we can't reschedule
4274 * ourselves here, but must return
4279 * Send the breaks and then return
4280 * SMB2_LEASE_NONE in the lease handle
4281 * to cause them to acknowledge the
4282 * lease break. Consulatation with
4283 * Microsoft engineering confirmed
4284 * this approach is safe.
4291 * Ensure we don't grant anything more so we
4294 return NT_STATUS_OPLOCK_NOT_GRANTED;
4298 * Wrapper around open_file_ntcreate and open_directory
4301 static NTSTATUS create_file_unixpath(connection_struct *conn,
4302 struct smb_request *req,
4303 struct smb_filename *smb_fname,
4304 uint32_t access_mask,
4305 uint32_t share_access,
4306 uint32_t create_disposition,
4307 uint32_t create_options,
4308 uint32_t file_attributes,
4309 uint32_t oplock_request,
4310 struct smb2_lease *lease,
4311 uint64_t allocation_size,
4312 uint32_t private_flags,
4313 struct security_descriptor *sd,
4314 struct ea_list *ea_list,
4316 files_struct **result,
4319 int info = FILE_WAS_OPENED;
4320 files_struct *base_fsp = NULL;
4321 files_struct *fsp = NULL;
4324 DEBUG(10,("create_file_unixpath: access_mask = 0x%x "
4325 "file_attributes = 0x%x, share_access = 0x%x, "
4326 "create_disposition = 0x%x create_options = 0x%x "
4327 "oplock_request = 0x%x private_flags = 0x%x "
4328 "ea_list = 0x%p, sd = 0x%p, "
4330 (unsigned int)access_mask,
4331 (unsigned int)file_attributes,
4332 (unsigned int)share_access,
4333 (unsigned int)create_disposition,
4334 (unsigned int)create_options,
4335 (unsigned int)oplock_request,
4336 (unsigned int)private_flags,
4337 ea_list, sd, smb_fname_str_dbg(smb_fname)));
4339 if (create_options & FILE_OPEN_BY_FILE_ID) {
4340 status = NT_STATUS_NOT_SUPPORTED;
4344 if (create_options & NTCREATEX_OPTIONS_INVALID_PARAM_MASK) {
4345 status = NT_STATUS_INVALID_PARAMETER;
4350 oplock_request |= INTERNAL_OPEN_ONLY;
4353 if (lease != NULL) {
4354 uint16_t epoch = lease->lease_epoch;
4355 uint16_t version = lease->lease_version;
4356 status = lease_match(conn,
4362 if (NT_STATUS_EQUAL(status, NT_STATUS_OPLOCK_NOT_GRANTED)) {
4363 /* Dynamic share file. No leases and update epoch... */
4364 lease->lease_state = SMB2_LEASE_NONE;
4365 lease->lease_epoch = epoch;
4366 lease->lease_version = version;
4367 } else if (!NT_STATUS_IS_OK(status)) {
4372 if ((conn->fs_capabilities & FILE_NAMED_STREAMS)
4373 && (access_mask & DELETE_ACCESS)
4374 && !is_ntfs_stream_smb_fname(smb_fname)) {
4376 * We can't open a file with DELETE access if any of the
4377 * streams is open without FILE_SHARE_DELETE
4379 status = open_streams_for_delete(conn, smb_fname->base_name);
4381 if (!NT_STATUS_IS_OK(status)) {
4386 if ((access_mask & SEC_FLAG_SYSTEM_SECURITY) &&
4387 !security_token_has_privilege(get_current_nttok(conn),
4388 SEC_PRIV_SECURITY)) {
4389 DEBUG(10, ("create_file_unixpath: open on %s "
4390 "failed - SEC_FLAG_SYSTEM_SECURITY denied.\n",
4391 smb_fname_str_dbg(smb_fname)));
4392 status = NT_STATUS_PRIVILEGE_NOT_HELD;
4396 if ((conn->fs_capabilities & FILE_NAMED_STREAMS)
4397 && is_ntfs_stream_smb_fname(smb_fname)
4398 && (!(private_flags & NTCREATEX_OPTIONS_PRIVATE_STREAM_DELETE))) {
4399 uint32 base_create_disposition;
4400 struct smb_filename *smb_fname_base = NULL;
4402 if (create_options & FILE_DIRECTORY_FILE) {
4403 status = NT_STATUS_NOT_A_DIRECTORY;
4407 switch (create_disposition) {
4409 base_create_disposition = FILE_OPEN;
4412 base_create_disposition = FILE_OPEN_IF;
4416 /* Create an smb_filename with stream_name == NULL. */
4417 smb_fname_base = synthetic_smb_fname(talloc_tos(),
4418 smb_fname->base_name,
4420 if (smb_fname_base == NULL) {
4421 status = NT_STATUS_NO_MEMORY;
4425 if (SMB_VFS_STAT(conn, smb_fname_base) == -1) {
4426 DEBUG(10, ("Unable to stat stream: %s\n",
4427 smb_fname_str_dbg(smb_fname_base)));
4430 * https://bugzilla.samba.org/show_bug.cgi?id=10229
4431 * We need to check if the requested access mask
4432 * could be used to open the underlying file (if
4433 * it existed), as we're passing in zero for the
4434 * access mask to the base filename.
4436 status = check_base_file_access(conn,
4440 if (!NT_STATUS_IS_OK(status)) {
4441 DEBUG(10, ("Permission check "
4442 "for base %s failed: "
4443 "%s\n", smb_fname->base_name,
4444 nt_errstr(status)));
4449 /* Open the base file. */
4450 status = create_file_unixpath(conn, NULL, smb_fname_base, 0,
4453 | FILE_SHARE_DELETE,
4454 base_create_disposition,
4455 0, 0, 0, NULL, 0, 0, NULL, NULL,
4457 TALLOC_FREE(smb_fname_base);
4459 if (!NT_STATUS_IS_OK(status)) {
4460 DEBUG(10, ("create_file_unixpath for base %s failed: "
4461 "%s\n", smb_fname->base_name,
4462 nt_errstr(status)));
4465 /* we don't need the low level fd */
4470 * If it's a request for a directory open, deal with it separately.
4473 if (create_options & FILE_DIRECTORY_FILE) {
4475 if (create_options & FILE_NON_DIRECTORY_FILE) {
4476 status = NT_STATUS_INVALID_PARAMETER;
4480 /* Can't open a temp directory. IFS kit test. */
4481 if (!(file_attributes & FILE_FLAG_POSIX_SEMANTICS) &&
4482 (file_attributes & FILE_ATTRIBUTE_TEMPORARY)) {
4483 status = NT_STATUS_INVALID_PARAMETER;
4488 * We will get a create directory here if the Win32
4489 * app specified a security descriptor in the
4490 * CreateDirectory() call.
4494 status = open_directory(
4495 conn, req, smb_fname, access_mask, share_access,
4496 create_disposition, create_options, file_attributes,
4501 * Ordinary file case.
4504 status = file_new(req, conn, &fsp);
4505 if(!NT_STATUS_IS_OK(status)) {
4509 status = fsp_set_smb_fname(fsp, smb_fname);
4510 if (!NT_STATUS_IS_OK(status)) {
4516 * We're opening the stream element of a
4517 * base_fsp we already opened. Set up the
4520 fsp->base_fsp = base_fsp;
4523 if (allocation_size) {
4524 fsp->initial_allocation_size = smb_roundup(fsp->conn,
4528 status = open_file_ntcreate(conn,
4541 if(!NT_STATUS_IS_OK(status)) {
4542 file_free(req, fsp);
4546 if (NT_STATUS_EQUAL(status, NT_STATUS_FILE_IS_A_DIRECTORY)) {
4548 /* A stream open never opens a directory */
4551 status = NT_STATUS_FILE_IS_A_DIRECTORY;
4556 * Fail the open if it was explicitly a non-directory
4560 if (create_options & FILE_NON_DIRECTORY_FILE) {
4561 status = NT_STATUS_FILE_IS_A_DIRECTORY;
4566 status = open_directory(
4567 conn, req, smb_fname, access_mask,
4568 share_access, create_disposition,
4569 create_options, file_attributes,
4574 if (!NT_STATUS_IS_OK(status)) {
4578 fsp->base_fsp = base_fsp;
4580 if ((ea_list != NULL) &&
4581 ((info == FILE_WAS_CREATED) || (info == FILE_WAS_OVERWRITTEN))) {
4582 status = set_ea(conn, fsp, fsp->fsp_name, ea_list);
4583 if (!NT_STATUS_IS_OK(status)) {
4588 if (!fsp->is_directory && S_ISDIR(fsp->fsp_name->st.st_ex_mode)) {
4589 status = NT_STATUS_ACCESS_DENIED;
4593 /* Save the requested allocation size. */
4594 if ((info == FILE_WAS_CREATED) || (info == FILE_WAS_OVERWRITTEN)) {
4596 && (allocation_size > fsp->fsp_name->st.st_ex_size)) {
4597 fsp->initial_allocation_size = smb_roundup(
4598 fsp->conn, allocation_size);
4599 if (fsp->is_directory) {
4600 /* Can't set allocation size on a directory. */
4601 status = NT_STATUS_ACCESS_DENIED;
4604 if (vfs_allocate_file_space(
4605 fsp, fsp->initial_allocation_size) == -1) {
4606 status = NT_STATUS_DISK_FULL;
4610 fsp->initial_allocation_size = smb_roundup(
4611 fsp->conn, (uint64_t)fsp->fsp_name->st.st_ex_size);
4614 fsp->initial_allocation_size = 0;
4617 if ((info == FILE_WAS_CREATED) && lp_nt_acl_support(SNUM(conn)) &&
4618 fsp->base_fsp == NULL) {
4621 * According to the MS documentation, the only time the security
4622 * descriptor is applied to the opened file is iff we *created* the
4623 * file; an existing file stays the same.
4625 * Also, it seems (from observation) that you can open the file with
4626 * any access mask but you can still write the sd. We need to override
4627 * the granted access before we call set_sd
4628 * Patch for bug #2242 from Tom Lackemann <cessnatomny@yahoo.com>.
4631 uint32_t sec_info_sent;
4632 uint32_t saved_access_mask = fsp->access_mask;
4634 sec_info_sent = get_sec_info(sd);
4636 fsp->access_mask = FILE_GENERIC_ALL;
4638 if (sec_info_sent & (SECINFO_OWNER|
4642 status = set_sd(fsp, sd, sec_info_sent);
4645 fsp->access_mask = saved_access_mask;
4647 if (!NT_STATUS_IS_OK(status)) {
4650 } else if (lp_inherit_acls(SNUM(conn))) {
4651 /* Inherit from parent. Errors here are not fatal. */
4652 status = inherit_new_acl(fsp);
4653 if (!NT_STATUS_IS_OK(status)) {
4654 DEBUG(10,("inherit_new_acl: failed for %s with %s\n",
4656 nt_errstr(status) ));
4661 if ((conn->fs_capabilities & FILE_FILE_COMPRESSION)
4662 && (create_options & FILE_NO_COMPRESSION)
4663 && (info == FILE_WAS_CREATED)) {
4664 status = SMB_VFS_SET_COMPRESSION(conn, fsp, fsp,
4665 COMPRESSION_FORMAT_NONE);
4666 if (!NT_STATUS_IS_OK(status)) {
4667 DEBUG(1, ("failed to disable compression: %s\n",
4668 nt_errstr(status)));
4672 DEBUG(10, ("create_file_unixpath: info=%d\n", info));
4675 if (pinfo != NULL) {
4679 smb_fname->st = fsp->fsp_name->st;
4681 return NT_STATUS_OK;
4684 DEBUG(10, ("create_file_unixpath: %s\n", nt_errstr(status)));
4687 if (base_fsp && fsp->base_fsp == base_fsp) {
4689 * The close_file below will close
4694 close_file(req, fsp, ERROR_CLOSE);
4697 if (base_fsp != NULL) {
4698 close_file(req, base_fsp, ERROR_CLOSE);
4705 * Calculate the full path name given a relative fid.
4707 NTSTATUS get_relative_fid_filename(connection_struct *conn,
4708 struct smb_request *req,
4709 uint16_t root_dir_fid,
4710 const struct smb_filename *smb_fname,
4711 struct smb_filename **smb_fname_out)
4713 files_struct *dir_fsp;
4714 char *parent_fname = NULL;
4715 char *new_base_name = NULL;
4718 if (root_dir_fid == 0 || !smb_fname) {
4719 status = NT_STATUS_INTERNAL_ERROR;
4723 dir_fsp = file_fsp(req, root_dir_fid);
4725 if (dir_fsp == NULL) {
4726 status = NT_STATUS_INVALID_HANDLE;
4730 if (is_ntfs_stream_smb_fname(dir_fsp->fsp_name)) {
4731 status = NT_STATUS_INVALID_HANDLE;
4735 if (!dir_fsp->is_directory) {
4738 * Check to see if this is a mac fork of some kind.
4741 if ((conn->fs_capabilities & FILE_NAMED_STREAMS) &&
4742 is_ntfs_stream_smb_fname(smb_fname)) {
4743 status = NT_STATUS_OBJECT_PATH_NOT_FOUND;
4748 we need to handle the case when we get a
4749 relative open relative to a file and the
4750 pathname is blank - this is a reopen!
4751 (hint from demyn plantenberg)
4754 status = NT_STATUS_INVALID_HANDLE;
4758 if (ISDOT(dir_fsp->fsp_name->base_name)) {
4760 * We're at the toplevel dir, the final file name
4761 * must not contain ./, as this is filtered out
4762 * normally by srvstr_get_path and unix_convert
4763 * explicitly rejects paths containing ./.
4765 parent_fname = talloc_strdup(talloc_tos(), "");
4766 if (parent_fname == NULL) {
4767 status = NT_STATUS_NO_MEMORY;
4771 size_t dir_name_len = strlen(dir_fsp->fsp_name->base_name);
4774 * Copy in the base directory name.
4777 parent_fname = talloc_array(talloc_tos(), char,
4779 if (parent_fname == NULL) {
4780 status = NT_STATUS_NO_MEMORY;
4783 memcpy(parent_fname, dir_fsp->fsp_name->base_name,
4787 * Ensure it ends in a '/'.
4788 * We used TALLOC_SIZE +2 to add space for the '/'.
4792 && (parent_fname[dir_name_len-1] != '\\')
4793 && (parent_fname[dir_name_len-1] != '/')) {
4794 parent_fname[dir_name_len] = '/';
4795 parent_fname[dir_name_len+1] = '\0';
4799 new_base_name = talloc_asprintf(talloc_tos(), "%s%s", parent_fname,
4800 smb_fname->base_name);
4801 if (new_base_name == NULL) {
4802 status = NT_STATUS_NO_MEMORY;
4806 status = filename_convert(req,
4808 req->flags2 & FLAGS2_DFS_PATHNAMES,
4813 if (!NT_STATUS_IS_OK(status)) {
4818 TALLOC_FREE(parent_fname);
4819 TALLOC_FREE(new_base_name);
4823 NTSTATUS create_file_default(connection_struct *conn,
4824 struct smb_request *req,
4825 uint16_t root_dir_fid,
4826 struct smb_filename *smb_fname,
4827 uint32_t access_mask,
4828 uint32_t share_access,
4829 uint32_t create_disposition,
4830 uint32_t create_options,
4831 uint32_t file_attributes,
4832 uint32_t oplock_request,
4833 struct smb2_lease *lease,
4834 uint64_t allocation_size,
4835 uint32_t private_flags,
4836 struct security_descriptor *sd,
4837 struct ea_list *ea_list,
4838 files_struct **result,
4840 const struct smb2_create_blobs *in_context_blobs,
4841 struct smb2_create_blobs *out_context_blobs)
4843 int info = FILE_WAS_OPENED;
4844 files_struct *fsp = NULL;
4846 bool stream_name = false;
4848 DEBUG(10,("create_file: access_mask = 0x%x "
4849 "file_attributes = 0x%x, share_access = 0x%x, "
4850 "create_disposition = 0x%x create_options = 0x%x "
4851 "oplock_request = 0x%x "
4852 "private_flags = 0x%x "
4853 "root_dir_fid = 0x%x, ea_list = 0x%p, sd = 0x%p, "
4855 (unsigned int)access_mask,
4856 (unsigned int)file_attributes,
4857 (unsigned int)share_access,
4858 (unsigned int)create_disposition,
4859 (unsigned int)create_options,
4860 (unsigned int)oplock_request,
4861 (unsigned int)private_flags,
4862 (unsigned int)root_dir_fid,
4863 ea_list, sd, smb_fname_str_dbg(smb_fname)));
4866 * Calculate the filename from the root_dir_if if necessary.
4869 if (root_dir_fid != 0) {
4870 struct smb_filename *smb_fname_out = NULL;
4871 status = get_relative_fid_filename(conn, req, root_dir_fid,
4872 smb_fname, &smb_fname_out);
4873 if (!NT_STATUS_IS_OK(status)) {
4876 smb_fname = smb_fname_out;
4880 * Check to see if this is a mac fork of some kind.
4883 stream_name = is_ntfs_stream_smb_fname(smb_fname);
4885 enum FAKE_FILE_TYPE fake_file_type;
4887 fake_file_type = is_fake_file(smb_fname);
4889 if (fake_file_type != FAKE_FILE_TYPE_NONE) {
4892 * Here we go! support for changing the disk quotas
4895 * We need to fake up to open this MAGIC QUOTA file
4896 * and return a valid FID.
4898 * w2k close this file directly after openening xp
4899 * also tries a QUERY_FILE_INFO on the file and then
4902 status = open_fake_file(req, conn, req->vuid,
4903 fake_file_type, smb_fname,
4905 if (!NT_STATUS_IS_OK(status)) {
4909 ZERO_STRUCT(smb_fname->st);
4913 if (!(conn->fs_capabilities & FILE_NAMED_STREAMS)) {
4914 status = NT_STATUS_OBJECT_NAME_NOT_FOUND;
4919 if (is_ntfs_default_stream_smb_fname(smb_fname)) {
4921 smb_fname->stream_name = NULL;
4922 /* We have to handle this error here. */
4923 if (create_options & FILE_DIRECTORY_FILE) {
4924 status = NT_STATUS_NOT_A_DIRECTORY;
4927 if (lp_posix_pathnames()) {
4928 ret = SMB_VFS_LSTAT(conn, smb_fname);
4930 ret = SMB_VFS_STAT(conn, smb_fname);
4933 if (ret == 0 && VALID_STAT_OF_DIR(smb_fname->st)) {
4934 status = NT_STATUS_FILE_IS_A_DIRECTORY;
4939 status = create_file_unixpath(
4940 conn, req, smb_fname, access_mask, share_access,
4941 create_disposition, create_options, file_attributes,
4942 oplock_request, lease, allocation_size, private_flags,
4946 if (!NT_STATUS_IS_OK(status)) {
4951 DEBUG(10, ("create_file: info=%d\n", info));
4954 if (pinfo != NULL) {
4957 return NT_STATUS_OK;
4960 DEBUG(10, ("create_file: %s\n", nt_errstr(status)));
4963 close_file(req, fsp, ERROR_CLOSE);