s3:smbd: also call handle_share_mode_lease for directories
[Samba.git] / source3 / smbd / open.c
blob06eeaa346768cbac4149e844b0249e06e6cf59f8
1 /*
2 Unix SMB/CIFS implementation.
3 file opening and share modes
4 Copyright (C) Andrew Tridgell 1992-1998
5 Copyright (C) Jeremy Allison 2001-2004
6 Copyright (C) Volker Lendecke 2005
7 Copyright (C) Ralph Boehme 2017
9 This program is free software; you can redistribute it and/or modify
10 it under the terms of the GNU General Public License as published by
11 the Free Software Foundation; either version 3 of the License, or
12 (at your option) any later version.
14 This program is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 GNU General Public License for more details.
19 You should have received a copy of the GNU General Public License
20 along with this program. If not, see <http://www.gnu.org/licenses/>.
23 #include "includes.h"
24 #include "system/filesys.h"
25 #include "lib/util/server_id.h"
26 #include "printing.h"
27 #include "locking/share_mode_lock.h"
28 #include "smbd/smbd.h"
29 #include "smbd/globals.h"
30 #include "fake_file.h"
31 #include "../libcli/security/security.h"
32 #include "../librpc/gen_ndr/ndr_security.h"
33 #include "../librpc/gen_ndr/ndr_open_files.h"
34 #include "../librpc/gen_ndr/idmap.h"
35 #include "../librpc/gen_ndr/ioctl.h"
36 #include "passdb/lookup_sid.h"
37 #include "auth.h"
38 #include "serverid.h"
39 #include "messages.h"
40 #include "source3/lib/dbwrap/dbwrap_watch.h"
41 #include "locking/leases_db.h"
42 #include "librpc/gen_ndr/ndr_leases_db.h"
43 #include "lib/util/time_basic.h"
45 extern const struct generic_mapping file_generic_mapping;
47 struct deferred_open_record {
48 struct smbXsrv_connection *xconn;
49 uint64_t mid;
51 bool async_open;
54 * Timer for async opens, needed because they don't use a watch on
55 * a locking.tdb record. This is currently only used for real async
56 * opens and just terminates smbd if the async open times out.
58 struct tevent_timer *te;
61 * For the samba kernel oplock case we use both a timeout and
62 * a watch on locking.tdb. This way in case it's smbd holding
63 * the kernel oplock we get directly notified for the retry
64 * once the kernel oplock is properly broken. Store the req
65 * here so that it can be timely discarded once the timer
66 * above fires.
68 struct tevent_req *watch_req;
71 /****************************************************************************
72 If the requester wanted DELETE_ACCESS and was rejected because
73 the file ACL didn't include DELETE_ACCESS, see if the parent ACL
74 overrides this.
75 ****************************************************************************/
77 static bool parent_override_delete(connection_struct *conn,
78 struct files_struct *dirfsp,
79 const struct smb_filename *smb_fname,
80 uint32_t access_mask,
81 uint32_t rejected_mask)
83 if ((access_mask & DELETE_ACCESS) &&
84 (rejected_mask & DELETE_ACCESS) &&
85 can_delete_file_in_directory(conn,
86 dirfsp,
87 smb_fname))
89 return true;
91 return false;
94 /****************************************************************************
95 Check if we have open rights.
96 ****************************************************************************/
98 static NTSTATUS smbd_check_access_rights_fname(
99 struct connection_struct *conn,
100 const struct smb_filename *smb_fname,
101 bool use_privs,
102 uint32_t access_mask,
103 uint32_t do_not_check_mask)
105 uint32_t rejected_share_access;
106 uint32_t effective_access;
108 rejected_share_access = access_mask & ~(conn->share_access);
110 if (rejected_share_access) {
111 DBG_DEBUG("rejected share access 0x%"PRIx32" on "
112 "%s (0x%"PRIx32")\n",
113 access_mask,
114 smb_fname_str_dbg(smb_fname),
115 rejected_share_access);
116 return NT_STATUS_ACCESS_DENIED;
119 effective_access = access_mask & ~do_not_check_mask;
120 if (effective_access == 0) {
121 DBG_DEBUG("do_not_check_mask override on %s. Granting 0x%x for free.\n",
122 smb_fname_str_dbg(smb_fname),
123 (unsigned int)access_mask);
124 return NT_STATUS_OK;
127 if (!use_privs && get_current_uid(conn) == (uid_t)0) {
128 /* I'm sorry sir, I didn't know you were root... */
129 DBG_DEBUG("root override on %s. Granting 0x%x\n",
130 smb_fname_str_dbg(smb_fname),
131 (unsigned int)access_mask);
132 return NT_STATUS_OK;
135 if ((access_mask & DELETE_ACCESS) &&
136 !lp_acl_check_permissions(SNUM(conn)))
138 DBG_DEBUG("Not checking ACL on DELETE_ACCESS on file %s. "
139 "Granting 0x%"PRIx32"\n",
140 smb_fname_str_dbg(smb_fname),
141 access_mask);
142 return NT_STATUS_OK;
145 if (access_mask == DELETE_ACCESS &&
146 VALID_STAT(smb_fname->st) &&
147 S_ISLNK(smb_fname->st.st_ex_mode))
149 /* We can always delete a symlink. */
150 DBG_DEBUG("Not checking ACL on DELETE_ACCESS on symlink %s.\n",
151 smb_fname_str_dbg(smb_fname));
152 return NT_STATUS_OK;
155 return NT_STATUS_MORE_PROCESSING_REQUIRED;
158 static NTSTATUS smbd_check_access_rights_sd(
159 struct connection_struct *conn,
160 struct files_struct *dirfsp,
161 const struct smb_filename *smb_fname,
162 struct security_descriptor *sd,
163 bool use_privs,
164 uint32_t access_mask,
165 uint32_t do_not_check_mask)
167 uint32_t rejected_mask = access_mask;
168 NTSTATUS status;
170 if (sd == NULL) {
171 goto access_denied;
174 status = se_file_access_check(sd,
175 get_current_nttok(conn),
176 use_privs,
177 (access_mask & ~do_not_check_mask),
178 &rejected_mask);
180 DBG_DEBUG("File [%s] requesting [0x%"PRIx32"] "
181 "returning [0x%"PRIx32"] (%s)\n",
182 smb_fname_str_dbg(smb_fname),
183 access_mask,
184 rejected_mask,
185 nt_errstr(status));
187 if (!NT_STATUS_IS_OK(status)) {
188 if (DEBUGLEVEL >= 10) {
189 DBG_DEBUG("acl for %s is:\n",
190 smb_fname_str_dbg(smb_fname));
191 NDR_PRINT_DEBUG(security_descriptor, sd);
195 TALLOC_FREE(sd);
197 if (NT_STATUS_IS_OK(status) ||
198 !NT_STATUS_EQUAL(status, NT_STATUS_ACCESS_DENIED))
200 return status;
203 /* Here we know status == NT_STATUS_ACCESS_DENIED. */
205 access_denied:
207 if ((access_mask & FILE_WRITE_ATTRIBUTES) &&
208 (rejected_mask & FILE_WRITE_ATTRIBUTES) &&
209 !lp_store_dos_attributes(SNUM(conn)) &&
210 (lp_map_readonly(SNUM(conn)) ||
211 lp_map_archive(SNUM(conn)) ||
212 lp_map_hidden(SNUM(conn)) ||
213 lp_map_system(SNUM(conn))))
215 rejected_mask &= ~FILE_WRITE_ATTRIBUTES;
217 DBG_DEBUG("overrode FILE_WRITE_ATTRIBUTES on file %s\n",
218 smb_fname_str_dbg(smb_fname));
221 if (parent_override_delete(conn,
222 dirfsp,
223 smb_fname,
224 access_mask,
225 rejected_mask))
228 * Were we trying to do an open for delete and didn't get DELETE
229 * access. Check if the directory allows DELETE_CHILD.
230 * See here:
231 * http://blogs.msdn.com/oldnewthing/archive/2004/06/04/148426.aspx
232 * for details.
235 rejected_mask &= ~DELETE_ACCESS;
237 DBG_DEBUG("Overrode DELETE_ACCESS on file %s\n",
238 smb_fname_str_dbg(smb_fname));
241 if (rejected_mask != 0) {
242 return NT_STATUS_ACCESS_DENIED;
244 return NT_STATUS_OK;
247 NTSTATUS smbd_check_access_rights_fsp(struct files_struct *dirfsp,
248 struct files_struct *fsp,
249 bool use_privs,
250 uint32_t access_mask)
252 struct security_descriptor *sd = NULL;
253 uint32_t do_not_check_mask = 0;
254 NTSTATUS status;
256 /* Cope with fake/printer fsp's. */
257 if (fsp->fake_file_handle != NULL || fsp->print_file != NULL) {
258 if ((fsp->access_mask & access_mask) != access_mask) {
259 return NT_STATUS_ACCESS_DENIED;
261 return NT_STATUS_OK;
264 if (fsp_get_pathref_fd(fsp) == -1) {
266 * This is a POSIX open on a symlink. For the pathname
267 * version of this function we used to return the st_mode
268 * bits turned into an NT ACL. For a symlink the mode bits
269 * are always rwxrwxrwx which means the pathname version always
270 * returned NT_STATUS_OK for a symlink. For the handle reference
271 * to a symlink use the handle access bits.
273 if ((fsp->access_mask & access_mask) != access_mask) {
274 return NT_STATUS_ACCESS_DENIED;
276 return NT_STATUS_OK;
280 * If we can access the path to this file, by
281 * default we have FILE_READ_ATTRIBUTES from the
282 * containing directory. See the section:
283 * "Algorithm to Check Access to an Existing File"
284 * in MS-FSA.pdf.
286 * se_file_access_check() also takes care of
287 * owner WRITE_DAC and READ_CONTROL.
289 do_not_check_mask = FILE_READ_ATTRIBUTES;
292 * Samba 3.6 and earlier granted execute access even
293 * if the ACL did not contain execute rights.
294 * Samba 4.0 is more correct and checks it.
295 * The compatibilty mode allows one to skip this check
296 * to smoothen upgrades.
298 if (lp_acl_allow_execute_always(SNUM(fsp->conn))) {
299 do_not_check_mask |= FILE_EXECUTE;
302 status = smbd_check_access_rights_fname(fsp->conn,
303 fsp->fsp_name,
304 use_privs,
305 access_mask,
306 do_not_check_mask);
307 if (!NT_STATUS_EQUAL(status, NT_STATUS_MORE_PROCESSING_REQUIRED)) {
308 return status;
311 status = SMB_VFS_FGET_NT_ACL(metadata_fsp(fsp),
312 (SECINFO_OWNER |
313 SECINFO_GROUP |
314 SECINFO_DACL),
315 talloc_tos(),
316 &sd);
317 if (!NT_STATUS_IS_OK(status)) {
318 DBG_DEBUG("Could not get acl on %s: %s\n",
319 fsp_str_dbg(fsp),
320 nt_errstr(status));
321 return status;
324 return smbd_check_access_rights_sd(fsp->conn,
325 dirfsp,
326 fsp->fsp_name,
328 use_privs,
329 access_mask,
330 do_not_check_mask);
334 * Given an fsp that represents a parent directory,
335 * check if the requested access can be granted.
337 NTSTATUS check_parent_access_fsp(struct files_struct *fsp,
338 uint32_t access_mask)
340 NTSTATUS status;
341 struct security_descriptor *parent_sd = NULL;
342 uint32_t access_granted = 0;
343 struct share_mode_lock *lck = NULL;
344 uint32_t name_hash;
345 bool delete_on_close_set;
346 TALLOC_CTX *frame = talloc_stackframe();
348 if (get_current_uid(fsp->conn) == (uid_t)0) {
349 /* I'm sorry sir, I didn't know you were root... */
350 DBG_DEBUG("root override on %s. Granting 0x%x\n",
351 fsp_str_dbg(fsp),
352 (unsigned int)access_mask);
353 status = NT_STATUS_OK;
354 goto out;
357 status = SMB_VFS_FGET_NT_ACL(fsp,
358 SECINFO_DACL,
359 frame,
360 &parent_sd);
362 if (!NT_STATUS_IS_OK(status)) {
363 DBG_INFO("SMB_VFS_FGET_NT_ACL failed for "
364 "%s with error %s\n",
365 fsp_str_dbg(fsp),
366 nt_errstr(status));
367 goto out;
371 * If we can access the path to this file, by
372 * default we have FILE_READ_ATTRIBUTES from the
373 * containing directory. See the section:
374 * "Algorithm to Check Access to an Existing File"
375 * in MS-FSA.pdf.
377 * se_file_access_check() also takes care of
378 * owner WRITE_DAC and READ_CONTROL.
380 status = se_file_access_check(parent_sd,
381 get_current_nttok(fsp->conn),
382 false,
383 (access_mask & ~FILE_READ_ATTRIBUTES),
384 &access_granted);
385 if(!NT_STATUS_IS_OK(status)) {
386 DBG_INFO("access check "
387 "on directory %s for mask 0x%x returned (0x%x) %s\n",
388 fsp_str_dbg(fsp),
389 access_mask,
390 access_granted,
391 nt_errstr(status));
392 goto out;
395 if (!(access_mask & (SEC_DIR_ADD_FILE | SEC_DIR_ADD_SUBDIR))) {
396 status = NT_STATUS_OK;
397 goto out;
399 if (!lp_check_parent_directory_delete_on_close(SNUM(fsp->conn))) {
400 status = NT_STATUS_OK;
401 goto out;
404 /* Check if the directory has delete-on-close set */
405 status = file_name_hash(fsp->conn,
406 fsp->fsp_name->base_name,
407 &name_hash);
408 if (!NT_STATUS_IS_OK(status)) {
409 goto out;
413 * Don't take a lock here. We just need a snapshot
414 * of the current state of delete on close and this is
415 * called in a codepath where we may already have a lock
416 * (and we explicitly can't hold 2 locks at the same time
417 * as that may deadlock).
419 lck = fetch_share_mode_unlocked(frame, fsp->file_id);
420 if (lck == NULL) {
421 status = NT_STATUS_OK;
422 goto out;
425 delete_on_close_set = is_delete_on_close_set(lck, name_hash);
426 if (delete_on_close_set) {
427 status = NT_STATUS_DELETE_PENDING;
428 goto out;
431 status = NT_STATUS_OK;
433 out:
434 TALLOC_FREE(frame);
435 return status;
438 /****************************************************************************
439 Ensure when opening a base file for a stream open that we have permissions
440 to do so given the access mask on the base file.
441 ****************************************************************************/
443 static NTSTATUS check_base_file_access(struct files_struct *fsp,
444 uint32_t access_mask)
446 NTSTATUS status;
448 status = smbd_calculate_access_mask_fsp(fsp->conn->cwd_fsp,
449 fsp,
450 false,
451 access_mask,
452 &access_mask);
453 if (!NT_STATUS_IS_OK(status)) {
454 DEBUG(10, ("smbd_calculate_access_mask "
455 "on file %s returned %s\n",
456 fsp_str_dbg(fsp),
457 nt_errstr(status)));
458 return status;
461 if (access_mask & (FILE_WRITE_DATA|FILE_APPEND_DATA)) {
462 uint32_t dosattrs;
463 if (!CAN_WRITE(fsp->conn)) {
464 return NT_STATUS_ACCESS_DENIED;
466 dosattrs = fdos_mode(fsp);
467 if (IS_DOS_READONLY(dosattrs)) {
468 return NT_STATUS_ACCESS_DENIED;
472 return smbd_check_access_rights_fsp(fsp->conn->cwd_fsp,
473 fsp,
474 false,
475 access_mask);
479 * Take two absolute paths, figure out if "subdir" is a proper
480 * subdirectory of "parent". Return the component relative to the
481 * "parent" without the potential "/". Take care of "parent"
482 * possibly ending in "/".
484 static bool subdir_of(
485 const char *parent,
486 size_t parent_len,
487 const char *subdir,
488 const char **_relative)
491 const char *relative = NULL;
492 bool matched;
494 SMB_ASSERT(parent[0] == '/');
495 SMB_ASSERT(subdir[0] == '/');
497 if (parent_len == 1) {
499 * Everything is below "/"
501 *_relative = subdir+1;
502 return true;
505 if (parent[parent_len-1] == '/') {
506 parent_len -= 1;
509 matched = (strncmp(subdir, parent, parent_len) == 0);
510 if (!matched) {
511 return false;
514 relative = &subdir[parent_len];
516 if (relative[0] == '\0') {
517 *_relative = relative; /* nothing left */
518 return true;
521 if (relative[0] == '/') {
522 /* End of parent must match a '/' in subdir. */
523 *_relative = relative+1;
524 return true;
527 return false;
530 static NTSTATUS chdir_below_conn(
531 TALLOC_CTX *mem_ctx,
532 connection_struct *conn,
533 const char *connectpath,
534 size_t connectpath_len,
535 struct smb_filename *dir_fname,
536 struct smb_filename **_oldwd_fname)
538 struct smb_filename *oldwd_fname = NULL;
539 struct smb_filename *smb_fname_dot = NULL;
540 struct smb_filename *real_fname = NULL;
541 const char *relative = NULL;
542 NTSTATUS status;
543 int ret;
544 bool ok;
546 if (!ISDOT(dir_fname->base_name)) {
548 oldwd_fname = vfs_GetWd(talloc_tos(), conn);
549 if (oldwd_fname == NULL) {
550 status = map_nt_error_from_unix(errno);
551 goto out;
554 /* Pin parent directory in place. */
555 ret = vfs_ChDir(conn, dir_fname);
556 if (ret == -1) {
557 status = map_nt_error_from_unix(errno);
558 DBG_DEBUG("chdir to %s failed: %s\n",
559 dir_fname->base_name,
560 strerror(errno));
561 goto out;
565 smb_fname_dot = synthetic_smb_fname(
566 talloc_tos(),
567 ".",
568 NULL,
569 NULL,
570 dir_fname->twrp,
571 dir_fname->flags);
572 if (smb_fname_dot == NULL) {
573 status = NT_STATUS_NO_MEMORY;
574 goto out;
577 real_fname = SMB_VFS_REALPATH(conn, talloc_tos(), smb_fname_dot);
578 if (real_fname == NULL) {
579 status = map_nt_error_from_unix(errno);
580 DBG_DEBUG("realpath in %s failed: %s\n",
581 dir_fname->base_name,
582 strerror(errno));
583 goto out;
585 TALLOC_FREE(smb_fname_dot);
587 ok = subdir_of(connectpath,
588 connectpath_len,
589 real_fname->base_name,
590 &relative);
591 if (ok) {
592 TALLOC_FREE(real_fname);
593 *_oldwd_fname = oldwd_fname;
594 return NT_STATUS_OK;
597 DBG_NOTICE("Bad access attempt: %s is a symlink "
598 "outside the share path\n"
599 "conn_rootdir =%s\n"
600 "resolved_name=%s\n",
601 dir_fname->base_name,
602 connectpath,
603 real_fname->base_name);
604 TALLOC_FREE(real_fname);
606 status = NT_STATUS_OBJECT_NAME_NOT_FOUND;
608 out:
609 if (oldwd_fname != NULL) {
610 ret = vfs_ChDir(conn, oldwd_fname);
611 SMB_ASSERT(ret == 0);
612 TALLOC_FREE(oldwd_fname);
615 return status;
619 * Get the symlink target of dirfsp/symlink_name, making sure the
620 * target is below connection_path.
623 static NTSTATUS symlink_target_below_conn(
624 TALLOC_CTX *mem_ctx,
625 const char *connection_path,
626 size_t connection_path_len,
627 struct files_struct *fsp,
628 struct files_struct *dirfsp,
629 struct smb_filename *symlink_name,
630 char **_target)
632 char *target = NULL;
633 char *absolute = NULL;
634 const char *relative = NULL;
635 NTSTATUS status;
636 bool ok;
638 if (fsp_get_pathref_fd(fsp) != -1) {
640 * fsp is an O_PATH open, Linux does a "freadlink"
641 * with an empty name argument to readlinkat
643 struct smb_filename null_fname = {
644 .base_name = discard_const_p(char, ""),
646 status = readlink_talloc(
647 talloc_tos(), fsp, &null_fname, &target);
648 } else {
649 status = readlink_talloc(
650 talloc_tos(), dirfsp, symlink_name, &target);
653 if (!NT_STATUS_IS_OK(status)) {
654 DBG_DEBUG("readlink_talloc failed: %s\n", nt_errstr(status));
655 return status;
658 if (target[0] != '/') {
659 char *tmp = talloc_asprintf(
660 talloc_tos(),
661 "%s/%s/%s",
662 connection_path,
663 dirfsp->fsp_name->base_name,
664 target);
666 TALLOC_FREE(target);
668 if (tmp == NULL) {
669 return NT_STATUS_NO_MEMORY;
671 target = tmp;
674 DBG_DEBUG("redirecting to %s\n", target);
676 absolute = canonicalize_absolute_path(talloc_tos(), target);
677 TALLOC_FREE(target);
679 if (absolute == NULL) {
680 return NT_STATUS_NO_MEMORY;
684 * We're doing the "below connection_path" here because it's
685 * cheap. It might be that we get a symlink out of the share,
686 * pointing to yet another symlink getting us back into the
687 * share. If we need that, we would have to remove the check
688 * here.
690 ok = subdir_of(
691 connection_path,
692 connection_path_len,
693 absolute,
694 &relative);
695 if (!ok) {
696 DBG_NOTICE("Bad access attempt: %s is a symlink "
697 "outside the share path\n"
698 "conn_rootdir =%s\n"
699 "resolved_name=%s\n",
700 symlink_name->base_name,
701 connection_path,
702 absolute);
703 TALLOC_FREE(absolute);
704 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
707 if (relative[0] == '\0') {
709 * special case symlink to share root: "." is our
710 * share root filename
712 absolute[0] = '.';
713 absolute[1] = '\0';
714 } else {
715 memmove(absolute, relative, strlen(relative)+1);
718 *_target = absolute;
719 return NT_STATUS_OK;
722 /****************************************************************************
723 Non-widelink open.
724 ****************************************************************************/
726 static NTSTATUS non_widelink_open(const struct files_struct *dirfsp,
727 files_struct *fsp,
728 struct smb_filename *smb_fname,
729 const struct vfs_open_how *_how,
730 unsigned int link_depth)
732 struct connection_struct *conn = fsp->conn;
733 const char *connpath = SMB_VFS_CONNECTPATH(conn, dirfsp, smb_fname);
734 size_t connpath_len;
735 NTSTATUS status = NT_STATUS_OK;
736 int fd = -1;
737 char *orig_smb_fname_base = smb_fname->base_name;
738 struct smb_filename *orig_fsp_name = fsp->fsp_name;
739 struct smb_filename *smb_fname_rel = NULL;
740 struct smb_filename *oldwd_fname = NULL;
741 struct smb_filename *parent_dir_fname = NULL;
742 struct vfs_open_how how = *_how;
743 char *target = NULL;
744 int ret;
746 SMB_ASSERT(!fsp_is_alternate_stream(fsp));
748 if (connpath == NULL) {
750 * This can happen with shadow_copy2 if the snapshot
751 * path is not found
753 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
755 connpath_len = strlen(connpath);
757 again:
758 if (smb_fname->base_name[0] == '/') {
759 int cmp = strcmp(connpath, smb_fname->base_name);
760 if (cmp == 0) {
761 smb_fname->base_name = talloc_strdup(smb_fname, "");
762 if (smb_fname->base_name == NULL) {
763 status = NT_STATUS_NO_MEMORY;
764 goto out;
769 if (dirfsp == conn->cwd_fsp) {
771 status = SMB_VFS_PARENT_PATHNAME(fsp->conn,
772 talloc_tos(),
773 smb_fname,
774 &parent_dir_fname,
775 &smb_fname_rel);
776 if (!NT_STATUS_IS_OK(status)) {
777 goto out;
780 status = chdir_below_conn(
781 talloc_tos(),
782 conn,
783 connpath,
784 connpath_len,
785 parent_dir_fname,
786 &oldwd_fname);
787 if (!NT_STATUS_IS_OK(status)) {
788 goto out;
791 /* Setup fsp->fsp_name to be relative to cwd */
792 fsp->fsp_name = smb_fname_rel;
793 } else {
795 * fsp->fsp_name is unchanged as it is already correctly
796 * relative to conn->cwd.
798 smb_fname_rel = smb_fname;
803 * Assert nobody can step in with a symlink on the
804 * path, there is no path anymore and we'll use
805 * O_NOFOLLOW to open.
807 char *slash = strchr_m(smb_fname_rel->base_name, '/');
808 SMB_ASSERT(slash == NULL);
811 how.flags |= O_NOFOLLOW;
813 fd = SMB_VFS_OPENAT(conn,
814 dirfsp,
815 smb_fname_rel,
816 fsp,
817 &how);
818 fsp_set_fd(fsp, fd); /* This preserves errno */
820 if (fd == -1) {
821 status = map_nt_error_from_unix(errno);
823 if (errno == ENOENT) {
824 goto out;
828 * ENOENT makes it worthless retrying with a
829 * stat, we know for sure the file does not
830 * exist. For everything else we want to know
831 * what's there.
833 ret = SMB_VFS_FSTATAT(
834 fsp->conn,
835 dirfsp,
836 smb_fname_rel,
837 &fsp->fsp_name->st,
838 AT_SYMLINK_NOFOLLOW);
839 } else {
840 ret = SMB_VFS_FSTAT(fsp, &fsp->fsp_name->st);
843 if (ret == -1) {
844 status = map_nt_error_from_unix(errno);
845 DBG_DEBUG("fstat[at](%s) failed: %s\n",
846 smb_fname_str_dbg(smb_fname),
847 strerror(errno));
848 goto out;
851 fsp->fsp_flags.is_directory = S_ISDIR(fsp->fsp_name->st.st_ex_mode);
852 orig_fsp_name->st = fsp->fsp_name->st;
854 if (!S_ISLNK(fsp->fsp_name->st.st_ex_mode)) {
855 goto out;
859 * Found a symlink to follow in user space
862 if (fsp->fsp_name->flags & SMB_FILENAME_POSIX_PATH) {
863 /* Never follow symlinks on posix open. */
864 status = NT_STATUS_STOPPED_ON_SYMLINK;
865 goto out;
867 if (!lp_follow_symlinks(SNUM(conn))) {
868 /* Explicitly no symlinks. */
869 status = NT_STATUS_STOPPED_ON_SYMLINK;
870 goto out;
873 link_depth += 1;
874 if (link_depth >= 40) {
875 status = NT_STATUS_STOPPED_ON_SYMLINK;
876 goto out;
879 fsp->fsp_name = orig_fsp_name;
881 status = symlink_target_below_conn(
882 talloc_tos(),
883 connpath,
884 connpath_len,
885 fsp,
886 discard_const_p(files_struct, dirfsp),
887 smb_fname_rel,
888 &target);
890 if (!NT_STATUS_IS_OK(status)) {
891 DBG_DEBUG("symlink_target_below_conn() failed: %s\n",
892 nt_errstr(status));
893 goto out;
897 * Close what openat(O_PATH) potentially left behind
899 fd_close(fsp);
901 if (smb_fname->base_name != orig_smb_fname_base) {
902 TALLOC_FREE(smb_fname->base_name);
904 smb_fname->base_name = target;
906 if (oldwd_fname != NULL) {
907 ret = vfs_ChDir(conn, oldwd_fname);
908 if (ret == -1) {
909 smb_panic("unable to get back to old directory\n");
911 TALLOC_FREE(oldwd_fname);
915 * And do it all again... As smb_fname is not relative to the passed in
916 * dirfsp anymore, we pass conn->cwd_fsp as dirfsp to
917 * non_widelink_open() to trigger the chdir(parentdir) logic.
919 dirfsp = conn->cwd_fsp;
921 goto again;
923 out:
924 fsp->fsp_name = orig_fsp_name;
925 smb_fname->base_name = orig_smb_fname_base;
927 TALLOC_FREE(parent_dir_fname);
929 if (!NT_STATUS_IS_OK(status)) {
930 fd_close(fsp);
933 if (oldwd_fname != NULL) {
934 ret = vfs_ChDir(conn, oldwd_fname);
935 if (ret == -1) {
936 smb_panic("unable to get back to old directory\n");
938 TALLOC_FREE(oldwd_fname);
940 return status;
943 /****************************************************************************
944 fd support routines - attempt to do a dos_open.
945 ****************************************************************************/
947 NTSTATUS fd_openat(const struct files_struct *dirfsp,
948 struct smb_filename *smb_fname,
949 files_struct *fsp,
950 const struct vfs_open_how *_how)
952 struct vfs_open_how how = *_how;
953 struct connection_struct *conn = fsp->conn;
954 NTSTATUS status = NT_STATUS_OK;
955 bool fsp_is_stream = fsp_is_alternate_stream(fsp);
956 bool smb_fname_is_stream = is_named_stream(smb_fname);
958 SMB_ASSERT(fsp_is_stream == smb_fname_is_stream);
961 * Never follow symlinks on a POSIX client. The
962 * client should be doing this.
965 if ((fsp->posix_flags & FSP_POSIX_FLAGS_OPEN) || !lp_follow_symlinks(SNUM(conn))) {
966 how.flags |= O_NOFOLLOW;
969 if (fsp_is_stream) {
970 int fd;
972 fd = SMB_VFS_OPENAT(
973 conn,
974 NULL, /* stream open is relative to fsp->base_fsp */
975 smb_fname,
976 fsp,
977 &how);
978 if (fd == -1) {
979 status = map_nt_error_from_unix(errno);
981 fsp_set_fd(fsp, fd);
983 if (fd != -1) {
984 status = vfs_stat_fsp(fsp);
985 if (!NT_STATUS_IS_OK(status)) {
986 DBG_DEBUG("vfs_stat_fsp failed: %s\n",
987 nt_errstr(status));
988 fd_close(fsp);
992 return status;
996 * Only follow symlinks within a share
997 * definition.
999 status = non_widelink_open(dirfsp, fsp, smb_fname, &how, 0);
1000 if (!NT_STATUS_IS_OK(status)) {
1001 if (NT_STATUS_EQUAL(status, NT_STATUS_TOO_MANY_OPENED_FILES)) {
1002 static time_t last_warned = 0L;
1004 if (time((time_t *) NULL) > last_warned) {
1005 DEBUG(0,("Too many open files, unable "
1006 "to open more! smbd's max "
1007 "open files = %d\n",
1008 lp_max_open_files()));
1009 last_warned = time((time_t *) NULL);
1013 DBG_DEBUG("name %s, flags = 0%o mode = 0%o, fd = %d. %s\n",
1014 smb_fname_str_dbg(smb_fname),
1015 how.flags,
1016 (int)how.mode,
1017 fsp_get_pathref_fd(fsp),
1018 nt_errstr(status));
1019 return status;
1022 DBG_DEBUG("name %s, flags = 0%o mode = 0%o, fd = %d\n",
1023 smb_fname_str_dbg(smb_fname),
1024 how.flags,
1025 (int)how.mode,
1026 fsp_get_pathref_fd(fsp));
1028 return status;
1031 /****************************************************************************
1032 Close the file associated with a fsp.
1033 ****************************************************************************/
1035 NTSTATUS fd_close(files_struct *fsp)
1037 NTSTATUS status;
1038 int ret;
1040 if (fsp == fsp->conn->cwd_fsp) {
1041 return NT_STATUS_OK;
1044 if (fsp->fsp_flags.fstat_before_close) {
1045 status = vfs_stat_fsp(fsp);
1046 if (!NT_STATUS_IS_OK(status)) {
1047 return status;
1051 if (fsp->dptr) {
1052 dptr_CloseDir(fsp);
1054 if (fsp_get_pathref_fd(fsp) == -1) {
1056 * Either a directory where the dptr_CloseDir() already closed
1057 * the fd or a stat open.
1059 return NT_STATUS_OK;
1061 if (fh_get_refcount(fsp->fh) > 1) {
1062 return NT_STATUS_OK; /* Shared handle. Only close last reference. */
1065 ret = SMB_VFS_CLOSE(fsp);
1066 fsp_set_fd(fsp, -1);
1067 if (ret == -1) {
1068 return map_nt_error_from_unix(errno);
1070 return NT_STATUS_OK;
1073 /****************************************************************************
1074 Change the ownership of a file to that of the parent directory.
1075 Do this by fd if possible.
1076 ****************************************************************************/
1078 static void change_file_owner_to_parent_fsp(struct files_struct *parent_fsp,
1079 struct files_struct *fsp)
1081 int ret;
1083 if (parent_fsp->fsp_name->st.st_ex_uid == fsp->fsp_name->st.st_ex_uid) {
1084 /* Already this uid - no need to change. */
1085 DBG_DEBUG("file %s is already owned by uid %u\n",
1086 fsp_str_dbg(fsp),
1087 (unsigned int)fsp->fsp_name->st.st_ex_uid);
1088 return;
1091 become_root();
1092 ret = SMB_VFS_FCHOWN(fsp,
1093 parent_fsp->fsp_name->st.st_ex_uid,
1094 (gid_t)-1);
1095 unbecome_root();
1096 if (ret == -1) {
1097 DBG_ERR("failed to fchown "
1098 "file %s to parent directory uid %u. Error "
1099 "was %s\n",
1100 fsp_str_dbg(fsp),
1101 (unsigned int)parent_fsp->fsp_name->st.st_ex_uid,
1102 strerror(errno));
1103 } else {
1104 DBG_DEBUG("changed new file %s to "
1105 "parent directory uid %u.\n",
1106 fsp_str_dbg(fsp),
1107 (unsigned int)parent_fsp->fsp_name->st.st_ex_uid);
1108 /* Ensure the uid entry is updated. */
1109 fsp->fsp_name->st.st_ex_uid =
1110 parent_fsp->fsp_name->st.st_ex_uid;
1114 static NTSTATUS change_dir_owner_to_parent_fsp(struct files_struct *parent_fsp,
1115 struct files_struct *fsp)
1117 NTSTATUS status;
1118 int ret;
1120 if (parent_fsp->fsp_name->st.st_ex_uid == fsp->fsp_name->st.st_ex_uid) {
1121 /* Already this uid - no need to change. */
1122 DBG_DEBUG("directory %s is already owned by uid %u\n",
1123 fsp_str_dbg(fsp),
1124 (unsigned int)fsp->fsp_name->st.st_ex_uid);
1125 return NT_STATUS_OK;
1128 become_root();
1129 ret = SMB_VFS_FCHOWN(fsp,
1130 parent_fsp->fsp_name->st.st_ex_uid,
1131 (gid_t)-1);
1132 unbecome_root();
1133 if (ret == -1) {
1134 status = map_nt_error_from_unix(errno);
1135 DBG_ERR("failed to chown "
1136 "directory %s to parent directory uid %u. "
1137 "Error was %s\n",
1138 fsp_str_dbg(fsp),
1139 (unsigned int)parent_fsp->fsp_name->st.st_ex_uid,
1140 nt_errstr(status));
1141 return status;
1144 DBG_DEBUG("changed ownership of new "
1145 "directory %s to parent directory uid %u.\n",
1146 fsp_str_dbg(fsp),
1147 (unsigned int)parent_fsp->fsp_name->st.st_ex_uid);
1149 /* Ensure the uid entry is updated. */
1150 fsp->fsp_name->st.st_ex_uid = parent_fsp->fsp_name->st.st_ex_uid;
1152 return NT_STATUS_OK;
1155 /****************************************************************************
1156 Open a file - returning a guaranteed ATOMIC indication of if the
1157 file was created or not.
1158 ****************************************************************************/
1160 static NTSTATUS fd_open_atomic(struct files_struct *dirfsp,
1161 struct smb_filename *smb_fname,
1162 files_struct *fsp,
1163 int flags,
1164 mode_t mode,
1165 bool *file_created)
1167 struct vfs_open_how how = { .flags = flags, .mode = mode, };
1168 NTSTATUS status = NT_STATUS_UNSUCCESSFUL;
1169 NTSTATUS retry_status;
1170 bool file_existed = VALID_STAT(smb_fname->st);
1172 if (!(how.flags & O_CREAT)) {
1174 * We're not creating the file, just pass through.
1176 status = fd_openat(dirfsp, smb_fname, fsp, &how);
1177 *file_created = false;
1178 return status;
1181 if (how.flags & O_EXCL) {
1183 * Fail if already exists, just pass through.
1185 status = fd_openat(dirfsp, smb_fname, fsp, &how);
1188 * Here we've opened with O_CREAT|O_EXCL. If that went
1189 * NT_STATUS_OK, we *know* we created this file.
1191 *file_created = NT_STATUS_IS_OK(status);
1193 return status;
1197 * Now it gets tricky. We have O_CREAT, but not O_EXCL.
1198 * To know absolutely if we created the file or not,
1199 * we can never call O_CREAT without O_EXCL. So if
1200 * we think the file existed, try without O_CREAT|O_EXCL.
1201 * If we think the file didn't exist, try with
1202 * O_CREAT|O_EXCL.
1204 * The big problem here is dangling symlinks. Opening
1205 * without O_NOFOLLOW means both bad symlink
1206 * and missing path return -1, ENOENT from open(). As POSIX
1207 * is pathname based it's not possible to tell
1208 * the difference between these two cases in a
1209 * non-racy way, so change to try only two attempts before
1210 * giving up.
1212 * We don't have this problem for the O_NOFOLLOW
1213 * case as it just returns NT_STATUS_OBJECT_PATH_NOT_FOUND
1214 * mapped from the ELOOP POSIX error.
1217 if (file_existed) {
1218 how.flags = flags & ~(O_CREAT);
1219 retry_status = NT_STATUS_OBJECT_NAME_NOT_FOUND;
1220 } else {
1221 how.flags = flags | O_EXCL;
1222 retry_status = NT_STATUS_OBJECT_NAME_COLLISION;
1225 status = fd_openat(dirfsp, smb_fname, fsp, &how);
1226 if (NT_STATUS_IS_OK(status)) {
1227 *file_created = !file_existed;
1228 return NT_STATUS_OK;
1230 if (NT_STATUS_EQUAL(status, retry_status)) {
1232 file_existed = !file_existed;
1234 DBG_DEBUG("File %s %s. Retry.\n",
1235 fsp_str_dbg(fsp),
1236 file_existed ? "existed" : "did not exist");
1238 if (file_existed) {
1239 how.flags = flags & ~(O_CREAT);
1240 } else {
1241 how.flags = flags | O_EXCL;
1244 status = fd_openat(dirfsp, smb_fname, fsp, &how);
1247 *file_created = (NT_STATUS_IS_OK(status) && !file_existed);
1248 return status;
1251 static NTSTATUS reopen_from_procfd(struct files_struct *fsp,
1252 int flags,
1253 mode_t mode)
1255 struct vfs_open_how how = { .flags = flags, .mode = mode };
1256 struct smb_filename proc_fname;
1257 const char *p = NULL;
1258 char buf[PATH_MAX];
1259 int old_fd;
1260 int new_fd;
1261 NTSTATUS status;
1263 if (!fsp->fsp_flags.have_proc_fds) {
1264 return NT_STATUS_MORE_PROCESSING_REQUIRED;
1267 old_fd = fsp_get_pathref_fd(fsp);
1268 if (old_fd == -1) {
1269 return NT_STATUS_MORE_PROCESSING_REQUIRED;
1272 if (!fsp->fsp_flags.is_pathref) {
1273 DBG_ERR("[%s] is not a pathref\n",
1274 fsp_str_dbg(fsp));
1275 #ifdef DEVELOPER
1276 smb_panic("Not a pathref");
1277 #endif
1278 return NT_STATUS_INVALID_HANDLE;
1281 p = sys_proc_fd_path(old_fd, buf, sizeof(buf));
1282 if (p == NULL) {
1283 return NT_STATUS_NO_MEMORY;
1286 proc_fname = (struct smb_filename) {
1287 .base_name = discard_const_p(char, p),
1290 fsp->fsp_flags.is_pathref = false;
1292 new_fd = SMB_VFS_OPENAT(fsp->conn,
1293 fsp->conn->cwd_fsp,
1294 &proc_fname,
1295 fsp,
1296 &how);
1297 if (new_fd == -1) {
1298 status = map_nt_error_from_unix(errno);
1299 fd_close(fsp);
1300 return status;
1303 status = fd_close(fsp);
1304 if (!NT_STATUS_IS_OK(status)) {
1305 return status;
1308 fsp_set_fd(fsp, new_fd);
1309 return NT_STATUS_OK;
1312 static NTSTATUS reopen_from_fsp(struct files_struct *dirfsp,
1313 struct smb_filename *smb_fname,
1314 struct files_struct *fsp,
1315 int flags,
1316 mode_t mode,
1317 bool *p_file_created)
1319 bool __unused_file_created = false;
1320 NTSTATUS status;
1322 if (p_file_created == NULL) {
1323 p_file_created = &__unused_file_created;
1327 * TODO: should we move this to the VFS layer?
1328 * SMB_VFS_REOPEN_FSP()?
1331 status = reopen_from_procfd(fsp,
1332 flags,
1333 mode);
1334 if (!NT_STATUS_EQUAL(status, NT_STATUS_MORE_PROCESSING_REQUIRED)) {
1335 return status;
1339 * Close the existing pathref fd and set the fsp flag
1340 * is_pathref to false so we get a "normal" fd this time.
1342 status = fd_close(fsp);
1343 if (!NT_STATUS_IS_OK(status)) {
1344 return status;
1347 fsp->fsp_flags.is_pathref = false;
1349 status = fd_open_atomic(
1350 dirfsp,
1351 smb_fname,
1352 fsp,
1353 flags,
1354 mode,
1355 p_file_created);
1356 return status;
1359 /****************************************************************************
1360 Open a file.
1361 ****************************************************************************/
1363 static NTSTATUS open_file(struct smb_request *req,
1364 struct files_struct *dirfsp,
1365 struct smb_filename *smb_fname_atname,
1366 files_struct *fsp,
1367 int flags,
1368 mode_t unx_mode,
1369 uint32_t access_mask, /* client requested access mask. */
1370 uint32_t open_access_mask, /* what we're actually using in the open. */
1371 uint32_t private_flags,
1372 bool *p_file_created)
1374 connection_struct *conn = fsp->conn;
1375 struct smb_filename *smb_fname = fsp->fsp_name;
1376 NTSTATUS status = NT_STATUS_OK;
1377 int accmode = (flags & O_ACCMODE);
1378 int local_flags = flags;
1379 bool file_existed = VALID_STAT(fsp->fsp_name->st);
1380 uint32_t need_fd_mask =
1381 FILE_READ_DATA |
1382 FILE_WRITE_DATA |
1383 FILE_APPEND_DATA |
1384 FILE_EXECUTE |
1385 SEC_FLAG_SYSTEM_SECURITY;
1386 bool creating = !file_existed && (flags & O_CREAT);
1387 bool truncating = (flags & O_TRUNC);
1388 bool open_fd = false;
1389 bool posix_open = (fsp->posix_flags & FSP_POSIX_FLAGS_OPEN);
1392 * Catch early an attempt to open an existing
1393 * directory as a file.
1395 if (file_existed && S_ISDIR(fsp->fsp_name->st.st_ex_mode)) {
1396 return NT_STATUS_FILE_IS_A_DIRECTORY;
1399 /* Check permissions */
1402 * This code was changed after seeing a client open request
1403 * containing the open mode of (DENY_WRITE/read-only) with
1404 * the 'create if not exist' bit set. The previous code
1405 * would fail to open the file read only on a read-only share
1406 * as it was checking the flags parameter directly against O_RDONLY,
1407 * this was failing as the flags parameter was set to O_RDONLY|O_CREAT.
1408 * JRA.
1411 if (!CAN_WRITE(conn)) {
1412 /* It's a read-only share - fail if we wanted to write. */
1413 if(accmode != O_RDONLY || (flags & O_TRUNC) || (flags & O_APPEND)) {
1414 DEBUG(3,("Permission denied opening %s\n",
1415 smb_fname_str_dbg(smb_fname)));
1416 return NT_STATUS_ACCESS_DENIED;
1418 if (flags & O_CREAT) {
1419 /* We don't want to write - but we must make sure that
1420 O_CREAT doesn't create the file if we have write
1421 access into the directory.
1423 flags &= ~(O_CREAT|O_EXCL);
1424 local_flags &= ~(O_CREAT|O_EXCL);
1429 * This little piece of insanity is inspired by the
1430 * fact that an NT client can open a file for O_RDONLY,
1431 * but set the create disposition to FILE_EXISTS_TRUNCATE.
1432 * If the client *can* write to the file, then it expects to
1433 * truncate the file, even though it is opening for readonly.
1434 * Quicken uses this stupid trick in backup file creation...
1435 * Thanks *greatly* to "David W. Chapman Jr." <dwcjr@inethouston.net>
1436 * for helping track this one down. It didn't bite us in 2.0.x
1437 * as we always opened files read-write in that release. JRA.
1440 if ((accmode == O_RDONLY) && ((flags & O_TRUNC) == O_TRUNC)) {
1441 DEBUG(10,("open_file: truncate requested on read-only open "
1442 "for file %s\n", smb_fname_str_dbg(smb_fname)));
1443 local_flags = (flags & ~O_ACCMODE)|O_RDWR;
1446 if ((open_access_mask & need_fd_mask) || creating || truncating) {
1447 open_fd = true;
1450 if (open_fd) {
1451 const char *wild;
1452 int ret;
1454 #if defined(O_NONBLOCK) && defined(S_ISFIFO)
1456 * We would block on opening a FIFO with no one else on the
1457 * other end. Do what we used to do and add O_NONBLOCK to the
1458 * open flags. JRA.
1461 if (file_existed && S_ISFIFO(smb_fname->st.st_ex_mode)) {
1462 local_flags &= ~O_TRUNC; /* Can't truncate a FIFO. */
1463 local_flags |= O_NONBLOCK;
1464 truncating = false;
1466 #endif
1468 /* Don't create files with Microsoft wildcard characters. */
1469 if (fsp_is_alternate_stream(fsp)) {
1471 * wildcard characters are allowed in stream names
1472 * only test the basefilename
1474 wild = fsp->base_fsp->fsp_name->base_name;
1475 } else {
1476 wild = smb_fname->base_name;
1478 if ((local_flags & O_CREAT) && !file_existed &&
1479 !(fsp->posix_flags & FSP_POSIX_FLAGS_PATHNAMES) &&
1480 ms_has_wild(wild)) {
1481 return NT_STATUS_OBJECT_NAME_INVALID;
1484 /* Can we access this file ? */
1485 if (!fsp_is_alternate_stream(fsp)) {
1486 /* Only do this check on non-stream open. */
1487 if (file_existed) {
1488 status = smbd_check_access_rights_fsp(
1489 dirfsp,
1490 fsp,
1491 false,
1492 access_mask);
1494 if (!NT_STATUS_IS_OK(status)) {
1495 DBG_DEBUG("smbd_check_access_rights_fsp"
1496 " on file %s returned %s\n",
1497 fsp_str_dbg(fsp),
1498 nt_errstr(status));
1501 if (!NT_STATUS_IS_OK(status) &&
1502 !NT_STATUS_EQUAL(status,
1503 NT_STATUS_OBJECT_NAME_NOT_FOUND))
1505 return status;
1508 if (NT_STATUS_EQUAL(status,
1509 NT_STATUS_OBJECT_NAME_NOT_FOUND))
1511 DEBUG(10, ("open_file: "
1512 "file %s vanished since we "
1513 "checked for existence.\n",
1514 smb_fname_str_dbg(smb_fname)));
1515 file_existed = false;
1516 SET_STAT_INVALID(fsp->fsp_name->st);
1520 if (!file_existed) {
1521 if (!(local_flags & O_CREAT)) {
1522 /* File didn't exist and no O_CREAT. */
1523 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
1526 status = check_parent_access_fsp(
1527 dirfsp,
1528 SEC_DIR_ADD_FILE);
1529 if (!NT_STATUS_IS_OK(status)) {
1530 DBG_DEBUG("check_parent_access_fsp on "
1531 "directory %s for file %s "
1532 "returned %s\n",
1533 smb_fname_str_dbg(
1534 dirfsp->fsp_name),
1535 smb_fname_str_dbg(smb_fname),
1536 nt_errstr(status));
1537 return status;
1543 * Actually do the open - if O_TRUNC is needed handle it
1544 * below under the share mode lock.
1546 status = reopen_from_fsp(dirfsp,
1547 smb_fname_atname,
1548 fsp,
1549 local_flags & ~O_TRUNC,
1550 unx_mode,
1551 p_file_created);
1552 if (NT_STATUS_EQUAL(status, NT_STATUS_STOPPED_ON_SYMLINK)) {
1554 * POSIX client that hit a symlink. We don't want to
1555 * return NT_STATUS_STOPPED_ON_SYMLINK to avoid handling
1556 * this special error code in all callers, so we map
1557 * this to NT_STATUS_OBJECT_NAME_NOT_FOUND to match
1558 * openat_pathref_fsp().
1560 status = NT_STATUS_OBJECT_NAME_NOT_FOUND;
1562 if (!NT_STATUS_IS_OK(status)) {
1563 DEBUG(3,("Error opening file %s (%s) (local_flags=%d) "
1564 "(flags=%d)\n", smb_fname_str_dbg(smb_fname),
1565 nt_errstr(status),local_flags,flags));
1566 return status;
1569 if (local_flags & O_NONBLOCK) {
1571 * GPFS can return ETIMEDOUT for pread on
1572 * nonblocking file descriptors when files
1573 * migrated to tape need to be recalled. I
1574 * could imagine this happens elsewhere
1575 * too. With blocking file descriptors this
1576 * does not happen.
1578 ret = vfs_set_blocking(fsp, true);
1579 if (ret == -1) {
1580 status = map_nt_error_from_unix(errno);
1581 DBG_WARNING("Could not set fd to blocking: "
1582 "%s\n", strerror(errno));
1583 fd_close(fsp);
1584 return status;
1588 if (*p_file_created) {
1589 /* We created this file. */
1591 bool need_re_stat = false;
1592 /* Do all inheritance work after we've
1593 done a successful fstat call and filled
1594 in the stat struct in fsp->fsp_name. */
1596 /* Inherit the ACL if required */
1597 if (lp_inherit_permissions(SNUM(conn))) {
1598 inherit_access_posix_acl(conn,
1599 dirfsp,
1600 smb_fname,
1601 unx_mode);
1602 need_re_stat = true;
1605 /* Change the owner if required. */
1606 if (lp_inherit_owner(SNUM(conn)) != INHERIT_OWNER_NO) {
1607 change_file_owner_to_parent_fsp(dirfsp, fsp);
1608 need_re_stat = true;
1611 if (need_re_stat) {
1612 status = vfs_stat_fsp(fsp);
1614 * If we have an fd, this stat should succeed.
1616 if (!NT_STATUS_IS_OK(status)) {
1617 DBG_ERR("Error doing fstat on open "
1618 "file %s (%s)\n",
1619 smb_fname_str_dbg(smb_fname),
1620 nt_errstr(status));
1621 fd_close(fsp);
1622 return status;
1626 notify_fname(conn, NOTIFY_ACTION_ADDED,
1627 FILE_NOTIFY_CHANGE_FILE_NAME,
1628 smb_fname->base_name);
1630 } else {
1631 if (!file_existed) {
1632 /* File must exist for a stat open. */
1633 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
1636 if (S_ISLNK(smb_fname->st.st_ex_mode) &&
1637 !posix_open)
1640 * Don't allow stat opens on symlinks directly unless
1641 * it's a POSIX open. Match the return code from
1642 * openat_pathref_fsp().
1644 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
1647 if (!fsp->fsp_flags.is_pathref) {
1649 * There is only one legit case where end up here:
1650 * openat_pathref_fsp() failed to open a symlink, so the
1651 * fsp was created by fsp_new() which doesn't set
1652 * is_pathref. Other then that, we should always have a
1653 * pathref fsp at this point. The subsequent checks
1654 * assert this.
1656 if (!(smb_fname->flags & SMB_FILENAME_POSIX_PATH)) {
1657 DBG_ERR("[%s] is not a POSIX pathname\n",
1658 smb_fname_str_dbg(smb_fname));
1659 return NT_STATUS_INTERNAL_ERROR;
1661 if (!S_ISLNK(smb_fname->st.st_ex_mode)) {
1662 DBG_ERR("[%s] is not a symlink\n",
1663 smb_fname_str_dbg(smb_fname));
1664 return NT_STATUS_INTERNAL_ERROR;
1666 if (fsp_get_pathref_fd(fsp) != -1) {
1667 DBG_ERR("fd for [%s] is not -1: fd [%d]\n",
1668 smb_fname_str_dbg(smb_fname),
1669 fsp_get_pathref_fd(fsp));
1670 return NT_STATUS_INTERNAL_ERROR;
1675 * Access to streams is checked by checking the basefile and
1676 * that has alreay been checked by check_base_file_access()
1677 * in create_file_unixpath().
1679 if (!fsp_is_alternate_stream(fsp)) {
1680 status = smbd_check_access_rights_fsp(dirfsp,
1681 fsp,
1682 false,
1683 access_mask);
1685 if (NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND) &&
1686 posix_open &&
1687 S_ISLNK(smb_fname->st.st_ex_mode)) {
1688 /* This is a POSIX stat open for delete
1689 * or rename on a symlink that points
1690 * nowhere. Allow. */
1691 DEBUG(10,("open_file: allowing POSIX "
1692 "open on bad symlink %s\n",
1693 smb_fname_str_dbg(smb_fname)));
1694 status = NT_STATUS_OK;
1697 if (!NT_STATUS_IS_OK(status)) {
1698 DBG_DEBUG("smbd_check_access_rights_fsp on file "
1699 "%s returned %s\n",
1700 fsp_str_dbg(fsp),
1701 nt_errstr(status));
1702 return status;
1707 fsp->file_id = vfs_file_id_from_sbuf(conn, &smb_fname->st);
1708 fsp->vuid = req ? req->vuid : UID_FIELD_INVALID;
1709 fsp->file_pid = req ? req->smbpid : 0;
1710 fsp->fsp_flags.can_lock = true;
1711 fsp->fsp_flags.can_read = ((access_mask & FILE_READ_DATA) != 0);
1712 fsp->fsp_flags.can_write =
1713 CAN_WRITE(conn) &&
1714 ((access_mask & (FILE_WRITE_DATA | FILE_APPEND_DATA)) != 0);
1715 fsp->print_file = NULL;
1716 fsp->fsp_flags.modified = false;
1717 fsp->sent_oplock_break = NO_BREAK_SENT;
1718 fsp->fsp_flags.is_directory = false;
1719 if (conn->aio_write_behind_list &&
1720 is_in_path(smb_fname->base_name, conn->aio_write_behind_list,
1721 posix_open ? true: conn->case_sensitive)) {
1722 fsp->fsp_flags.aio_write_behind = true;
1725 DEBUG(2,("%s opened file %s read=%s write=%s (numopen=%d)\n",
1726 conn->session_info->unix_info->unix_name,
1727 smb_fname_str_dbg(smb_fname),
1728 BOOLSTR(fsp->fsp_flags.can_read),
1729 BOOLSTR(fsp->fsp_flags.can_write),
1730 conn->num_files_open));
1732 return NT_STATUS_OK;
1735 static bool mask_conflict(
1736 uint32_t new_access,
1737 uint32_t existing_access,
1738 uint32_t access_mask,
1739 uint32_t new_sharemode,
1740 uint32_t existing_sharemode,
1741 uint32_t sharemode_mask)
1743 bool want_access = (new_access & access_mask);
1744 bool allow_existing = (existing_sharemode & sharemode_mask);
1745 bool have_access = (existing_access & access_mask);
1746 bool allow_new = (new_sharemode & sharemode_mask);
1748 if (want_access && !allow_existing) {
1749 DBG_DEBUG("Access request 0x%"PRIx32"/0x%"PRIx32" conflicts "
1750 "with existing sharemode 0x%"PRIx32"/0x%"PRIx32"\n",
1751 new_access,
1752 access_mask,
1753 existing_sharemode,
1754 sharemode_mask);
1755 return true;
1757 if (have_access && !allow_new) {
1758 DBG_DEBUG("Sharemode request 0x%"PRIx32"/0x%"PRIx32" conflicts "
1759 "with existing access 0x%"PRIx32"/0x%"PRIx32"\n",
1760 new_sharemode,
1761 sharemode_mask,
1762 existing_access,
1763 access_mask);
1764 return true;
1766 return false;
1769 /****************************************************************************
1770 Check if we can open a file with a share mode.
1771 Returns True if conflict, False if not.
1772 ****************************************************************************/
1774 static const uint32_t conflicting_access =
1775 FILE_WRITE_DATA|
1776 FILE_APPEND_DATA|
1777 FILE_READ_DATA|
1778 FILE_EXECUTE|
1779 DELETE_ACCESS;
1781 static bool share_conflict(uint32_t e_access_mask,
1782 uint32_t e_share_access,
1783 uint32_t access_mask,
1784 uint32_t share_access)
1786 bool conflict;
1788 DBG_DEBUG("existing access_mask = 0x%"PRIx32", "
1789 "existing share access = 0x%"PRIx32", "
1790 "access_mask = 0x%"PRIx32", "
1791 "share_access = 0x%"PRIx32"\n",
1792 e_access_mask,
1793 e_share_access,
1794 access_mask,
1795 share_access);
1797 if ((e_access_mask & conflicting_access) == 0) {
1798 DBG_DEBUG("No conflict due to "
1799 "existing access_mask = 0x%"PRIx32"\n",
1800 e_access_mask);
1801 return false;
1803 if ((access_mask & conflicting_access) == 0) {
1804 DBG_DEBUG("No conflict due to access_mask = 0x%"PRIx32"\n",
1805 access_mask);
1806 return false;
1809 conflict = mask_conflict(
1810 access_mask, e_access_mask, FILE_WRITE_DATA | FILE_APPEND_DATA,
1811 share_access, e_share_access, FILE_SHARE_WRITE);
1812 conflict |= mask_conflict(
1813 access_mask, e_access_mask, FILE_READ_DATA | FILE_EXECUTE,
1814 share_access, e_share_access, FILE_SHARE_READ);
1815 conflict |= mask_conflict(
1816 access_mask, e_access_mask, DELETE_ACCESS,
1817 share_access, e_share_access, FILE_SHARE_DELETE);
1819 DBG_DEBUG("conflict=%s\n", conflict ? "true" : "false");
1820 return conflict;
1823 #if defined(DEVELOPER)
1825 struct validate_my_share_entries_state {
1826 struct smbd_server_connection *sconn;
1827 struct file_id fid;
1828 struct server_id self;
1831 static bool validate_my_share_entries_fn(
1832 struct share_mode_entry *e,
1833 bool *modified,
1834 void *private_data)
1836 struct validate_my_share_entries_state *state = private_data;
1837 files_struct *fsp;
1839 if (!server_id_equal(&state->self, &e->pid)) {
1840 return false;
1843 if (e->op_mid == 0) {
1844 /* INTERNAL_OPEN_ONLY */
1845 return false;
1848 fsp = file_find_dif(state->sconn, state->fid, e->share_file_id);
1849 if (!fsp) {
1850 DBG_ERR("PANIC : %s\n",
1851 share_mode_str(talloc_tos(), 0, &state->fid, e));
1852 smb_panic("validate_my_share_entries: Cannot match a "
1853 "share entry with an open file\n");
1856 if (((uint16_t)fsp->oplock_type) != e->op_type) {
1857 goto panic;
1860 return false;
1862 panic:
1864 char *str;
1865 DBG_ERR("validate_my_share_entries: PANIC : %s\n",
1866 share_mode_str(talloc_tos(), 0, &state->fid, e));
1867 str = talloc_asprintf(talloc_tos(),
1868 "validate_my_share_entries: "
1869 "file %s, oplock_type = 0x%x, op_type = 0x%x\n",
1870 fsp->fsp_name->base_name,
1871 (unsigned int)fsp->oplock_type,
1872 (unsigned int)e->op_type);
1873 smb_panic(str);
1876 return false;
1878 #endif
1881 * Allowed access mask for stat opens relevant to oplocks
1883 bool is_oplock_stat_open(uint32_t access_mask)
1885 const uint32_t stat_open_bits =
1886 (SYNCHRONIZE_ACCESS|
1887 FILE_READ_ATTRIBUTES|
1888 FILE_WRITE_ATTRIBUTES);
1890 return (((access_mask & stat_open_bits) != 0) &&
1891 ((access_mask & ~stat_open_bits) == 0));
1895 * Allowed access mask for stat opens relevant to leases
1897 bool is_lease_stat_open(uint32_t access_mask)
1899 const uint32_t stat_open_bits =
1900 (SYNCHRONIZE_ACCESS|
1901 FILE_READ_ATTRIBUTES|
1902 FILE_WRITE_ATTRIBUTES|
1903 READ_CONTROL_ACCESS);
1905 return (((access_mask & stat_open_bits) != 0) &&
1906 ((access_mask & ~stat_open_bits) == 0));
1909 struct has_delete_on_close_state {
1910 bool ret;
1913 static bool has_delete_on_close_fn(
1914 struct share_mode_entry *e,
1915 bool *modified,
1916 void *private_data)
1918 struct has_delete_on_close_state *state = private_data;
1919 state->ret = !share_entry_stale_pid(e);
1920 return state->ret;
1923 static bool has_delete_on_close(struct share_mode_lock *lck,
1924 uint32_t name_hash)
1926 struct has_delete_on_close_state state = { .ret = false };
1927 bool ok;
1929 if (!is_delete_on_close_set(lck, name_hash)) {
1930 return false;
1933 ok= share_mode_forall_entries(lck, has_delete_on_close_fn, &state);
1934 if (!ok) {
1935 DBG_DEBUG("share_mode_forall_entries failed\n");
1936 return false;
1938 return state.ret;
1941 static void share_mode_flags_restrict(
1942 struct share_mode_lock *lck,
1943 uint32_t access_mask,
1944 uint32_t share_mode,
1945 uint32_t lease_type)
1947 uint32_t existing_access_mask, existing_share_mode;
1948 uint32_t existing_lease_type;
1950 share_mode_flags_get(
1951 lck,
1952 &existing_access_mask,
1953 &existing_share_mode,
1954 &existing_lease_type);
1956 existing_access_mask |= access_mask;
1957 if (access_mask & conflicting_access) {
1958 existing_share_mode &= share_mode;
1960 existing_lease_type |= lease_type;
1962 share_mode_flags_set(
1963 lck,
1964 existing_access_mask,
1965 existing_share_mode,
1966 existing_lease_type,
1967 NULL);
1970 /****************************************************************************
1971 Deal with share modes
1972 Invariant: Share mode must be locked on entry and exit.
1973 Returns -1 on error, or number of share modes on success (may be zero).
1974 ****************************************************************************/
1976 struct open_mode_check_state {
1977 struct file_id fid;
1978 uint32_t access_mask;
1979 uint32_t share_access;
1980 uint32_t lease_type;
1983 static bool open_mode_check_fn(
1984 struct share_mode_entry *e,
1985 bool *modified,
1986 void *private_data)
1988 struct open_mode_check_state *state = private_data;
1989 bool disconnected, stale;
1990 uint32_t access_mask, share_access, lease_type;
1992 disconnected = server_id_is_disconnected(&e->pid);
1993 if (disconnected) {
1994 return false;
1997 access_mask = state->access_mask | e->access_mask;
1998 share_access = state->share_access;
1999 if (e->access_mask & conflicting_access) {
2000 share_access &= e->share_access;
2002 lease_type = state->lease_type | get_lease_type(e, state->fid);
2004 if ((access_mask == state->access_mask) &&
2005 (share_access == state->share_access) &&
2006 (lease_type == state->lease_type)) {
2007 return false;
2010 stale = share_entry_stale_pid(e);
2011 if (stale) {
2012 return false;
2015 state->access_mask = access_mask;
2016 state->share_access = share_access;
2017 state->lease_type = lease_type;
2019 return false;
2022 static NTSTATUS open_mode_check(connection_struct *conn,
2023 struct file_id fid,
2024 struct share_mode_lock *lck,
2025 uint32_t access_mask,
2026 uint32_t share_access)
2028 struct open_mode_check_state state;
2029 bool ok, conflict;
2030 bool modified = false;
2032 if (is_oplock_stat_open(access_mask)) {
2033 /* Stat open that doesn't trigger oplock breaks or share mode
2034 * checks... ! JRA. */
2035 return NT_STATUS_OK;
2039 * Check if the share modes will give us access.
2042 #if defined(DEVELOPER)
2044 struct validate_my_share_entries_state validate_state = {
2045 .sconn = conn->sconn,
2046 .fid = fid,
2047 .self = messaging_server_id(conn->sconn->msg_ctx),
2049 ok = share_mode_forall_entries(
2050 lck, validate_my_share_entries_fn, &validate_state);
2051 SMB_ASSERT(ok);
2053 #endif
2055 share_mode_flags_get(
2056 lck, &state.access_mask, &state.share_access, NULL);
2058 conflict = share_conflict(
2059 state.access_mask,
2060 state.share_access,
2061 access_mask,
2062 share_access);
2063 if (!conflict) {
2064 DBG_DEBUG("No conflict due to share_mode_flags access\n");
2065 return NT_STATUS_OK;
2068 state = (struct open_mode_check_state) {
2069 .fid = fid,
2070 .share_access = (FILE_SHARE_READ|
2071 FILE_SHARE_WRITE|
2072 FILE_SHARE_DELETE),
2076 * Walk the share mode array to recalculate d->flags
2079 ok = share_mode_forall_entries(lck, open_mode_check_fn, &state);
2080 if (!ok) {
2081 DBG_DEBUG("share_mode_forall_entries failed\n");
2082 return NT_STATUS_INTERNAL_ERROR;
2085 share_mode_flags_set(
2086 lck,
2087 state.access_mask,
2088 state.share_access,
2089 state.lease_type,
2090 &modified);
2091 if (!modified) {
2093 * We only end up here if we had a sharing violation
2094 * from d->flags and have recalculated it.
2096 return NT_STATUS_SHARING_VIOLATION;
2099 conflict = share_conflict(
2100 state.access_mask,
2101 state.share_access,
2102 access_mask,
2103 share_access);
2104 if (!conflict) {
2105 DBG_DEBUG("No conflict due to share_mode_flags access\n");
2106 return NT_STATUS_OK;
2109 return NT_STATUS_SHARING_VIOLATION;
2113 * Send a break message to the oplock holder and delay the open for
2114 * our client.
2117 NTSTATUS send_break_message(struct messaging_context *msg_ctx,
2118 const struct file_id *id,
2119 const struct share_mode_entry *exclusive,
2120 uint16_t break_to)
2122 struct oplock_break_message msg = {
2123 .id = *id,
2124 .share_file_id = exclusive->share_file_id,
2125 .break_to = break_to,
2127 enum ndr_err_code ndr_err;
2128 DATA_BLOB blob;
2129 NTSTATUS status;
2131 if (DEBUGLVL(10)) {
2132 struct server_id_buf buf;
2133 DBG_DEBUG("Sending break message to %s\n",
2134 server_id_str_buf(exclusive->pid, &buf));
2135 NDR_PRINT_DEBUG(oplock_break_message, &msg);
2138 ndr_err = ndr_push_struct_blob(
2139 &blob,
2140 talloc_tos(),
2141 &msg,
2142 (ndr_push_flags_fn_t)ndr_push_oplock_break_message);
2143 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
2144 DBG_WARNING("ndr_push_oplock_break_message failed: %s\n",
2145 ndr_errstr(ndr_err));
2146 return ndr_map_error2ntstatus(ndr_err);
2149 status = messaging_send(
2150 msg_ctx, exclusive->pid, MSG_SMB_BREAK_REQUEST, &blob);
2151 TALLOC_FREE(blob.data);
2152 if (!NT_STATUS_IS_OK(status)) {
2153 DEBUG(3, ("Could not send oplock break message: %s\n",
2154 nt_errstr(status)));
2157 return status;
2160 struct validate_oplock_types_state {
2161 bool valid;
2162 bool batch;
2163 bool ex_or_batch;
2164 bool level2;
2165 bool no_oplock;
2166 uint32_t num_non_stat_opens;
2169 static bool validate_oplock_types_fn(
2170 struct share_mode_entry *e,
2171 bool *modified,
2172 void *private_data)
2174 struct validate_oplock_types_state *state = private_data;
2176 if (e->op_mid == 0) {
2177 /* INTERNAL_OPEN_ONLY */
2178 return false;
2181 if (e->op_type == NO_OPLOCK && is_oplock_stat_open(e->access_mask)) {
2183 * We ignore stat opens in the table - they always
2184 * have NO_OPLOCK and never get or cause breaks. JRA.
2186 return false;
2189 state->num_non_stat_opens += 1;
2191 if (BATCH_OPLOCK_TYPE(e->op_type)) {
2192 /* batch - can only be one. */
2193 if (share_entry_stale_pid(e)) {
2194 DBG_DEBUG("Found stale batch oplock\n");
2195 return false;
2197 if (state->ex_or_batch ||
2198 state->batch ||
2199 state->level2 ||
2200 state->no_oplock) {
2201 DBG_ERR("Bad batch oplock entry\n");
2202 state->valid = false;
2203 return true;
2205 state->batch = true;
2208 if (EXCLUSIVE_OPLOCK_TYPE(e->op_type)) {
2209 if (share_entry_stale_pid(e)) {
2210 DBG_DEBUG("Found stale duplicate oplock\n");
2211 return false;
2213 /* Exclusive or batch - can only be one. */
2214 if (state->ex_or_batch ||
2215 state->level2 ||
2216 state->no_oplock) {
2217 DBG_ERR("Bad exclusive or batch oplock entry\n");
2218 state->valid = false;
2219 return true;
2221 state->ex_or_batch = true;
2224 if (LEVEL_II_OPLOCK_TYPE(e->op_type)) {
2225 if (state->batch || state->ex_or_batch) {
2226 if (share_entry_stale_pid(e)) {
2227 DBG_DEBUG("Found stale LevelII oplock\n");
2228 return false;
2230 DBG_DEBUG("Bad levelII oplock entry\n");
2231 state->valid = false;
2232 return true;
2234 state->level2 = true;
2237 if (e->op_type == NO_OPLOCK) {
2238 if (state->batch || state->ex_or_batch) {
2239 if (share_entry_stale_pid(e)) {
2240 DBG_DEBUG("Found stale NO_OPLOCK entry\n");
2241 return false;
2243 DBG_ERR("Bad no oplock entry\n");
2244 state->valid = false;
2245 return true;
2247 state->no_oplock = true;
2250 return false;
2254 * Do internal consistency checks on the share mode for a file.
2257 static bool validate_oplock_types(struct share_mode_lock *lck)
2259 struct validate_oplock_types_state state = { .valid = true };
2260 static bool skip_validation;
2261 bool validate;
2262 bool ok;
2264 if (skip_validation) {
2265 return true;
2268 validate = lp_parm_bool(-1, "smbd", "validate_oplock_types", false);
2269 if (!validate) {
2270 DBG_DEBUG("smbd:validate_oplock_types not set to yes\n");
2271 skip_validation = true;
2272 return true;
2275 ok = share_mode_forall_entries(lck, validate_oplock_types_fn, &state);
2276 if (!ok) {
2277 DBG_DEBUG("share_mode_forall_entries failed\n");
2278 return false;
2280 if (!state.valid) {
2281 DBG_DEBUG("Got invalid oplock configuration\n");
2282 return false;
2285 if ((state.batch || state.ex_or_batch) &&
2286 (state.num_non_stat_opens != 1)) {
2287 DBG_WARNING("got batch (%d) or ex (%d) non-exclusively "
2288 "(%"PRIu32")\n",
2289 (int)state.batch,
2290 (int)state.ex_or_batch,
2291 state.num_non_stat_opens);
2292 return false;
2295 return true;
2298 static bool is_same_lease(const files_struct *fsp,
2299 const struct share_mode_entry *e,
2300 const struct smb2_lease *lease)
2302 if (e->op_type != LEASE_OPLOCK) {
2303 return false;
2305 if (lease == NULL) {
2306 return false;
2309 return smb2_lease_equal(fsp_client_guid(fsp),
2310 &lease->lease_key,
2311 &e->client_guid,
2312 &e->lease_key);
2315 static bool file_has_brlocks(files_struct *fsp)
2317 struct byte_range_lock *br_lck;
2319 br_lck = brl_get_locks_readonly(fsp);
2320 if (!br_lck)
2321 return false;
2323 return (brl_num_locks(br_lck) > 0);
2326 struct fsp_lease *find_fsp_lease(struct files_struct *new_fsp,
2327 const struct smb2_lease_key *key,
2328 uint32_t current_state,
2329 uint16_t lease_version,
2330 uint16_t lease_epoch)
2332 struct files_struct *fsp;
2335 * TODO: Measure how expensive this loop is with thousands of open
2336 * handles...
2339 for (fsp = file_find_di_first(new_fsp->conn->sconn, new_fsp->file_id, true);
2340 fsp != NULL;
2341 fsp = file_find_di_next(fsp, true)) {
2343 if (fsp == new_fsp) {
2344 continue;
2346 if (fsp->oplock_type != LEASE_OPLOCK) {
2347 continue;
2349 if (smb2_lease_key_equal(&fsp->lease->lease.lease_key, key)) {
2350 fsp->lease->ref_count += 1;
2351 return fsp->lease;
2355 /* Not found - must be leased in another smbd. */
2356 new_fsp->lease = talloc_zero(new_fsp->conn->sconn, struct fsp_lease);
2357 if (new_fsp->lease == NULL) {
2358 return NULL;
2360 new_fsp->lease->ref_count = 1;
2361 new_fsp->lease->sconn = new_fsp->conn->sconn;
2362 new_fsp->lease->lease.lease_key = *key;
2363 new_fsp->lease->lease.lease_state = current_state;
2365 * We internally treat all leases as V2 and update
2366 * the epoch, but when sending breaks it matters if
2367 * the requesting lease was v1 or v2.
2369 new_fsp->lease->lease.lease_version = lease_version;
2370 new_fsp->lease->lease.lease_epoch = lease_epoch;
2371 return new_fsp->lease;
2374 static NTSTATUS try_lease_upgrade(struct files_struct *fsp,
2375 struct share_mode_lock *lck,
2376 const struct GUID *client_guid,
2377 const struct smb2_lease *lease,
2378 uint32_t granted)
2380 bool do_upgrade;
2381 uint32_t current_state, breaking_to_requested, breaking_to_required;
2382 bool breaking;
2383 uint16_t lease_version, epoch;
2384 uint32_t existing, requested;
2385 NTSTATUS status;
2387 status = leases_db_get(
2388 client_guid,
2389 &lease->lease_key,
2390 &fsp->file_id,
2391 &current_state,
2392 &breaking,
2393 &breaking_to_requested,
2394 &breaking_to_required,
2395 &lease_version,
2396 &epoch);
2397 if (!NT_STATUS_IS_OK(status)) {
2398 return status;
2401 fsp->lease = find_fsp_lease(
2402 fsp,
2403 &lease->lease_key,
2404 current_state,
2405 lease_version,
2406 epoch);
2407 if (fsp->lease == NULL) {
2408 DEBUG(1, ("Did not find existing lease for file %s\n",
2409 fsp_str_dbg(fsp)));
2410 return NT_STATUS_NO_MEMORY;
2414 * Upgrade only if the requested lease is a strict upgrade.
2416 existing = current_state;
2417 requested = lease->lease_state;
2420 * Tricky: This test makes sure that "requested" is a
2421 * strict bitwise superset of "existing".
2423 do_upgrade = ((existing & requested) == existing);
2426 * Upgrade only if there's a change.
2428 do_upgrade &= (granted != existing);
2431 * Upgrade only if other leases don't prevent what was asked
2432 * for.
2434 do_upgrade &= (granted == requested);
2437 * only upgrade if we are not in breaking state
2439 do_upgrade &= !breaking;
2441 DEBUG(10, ("existing=%"PRIu32", requested=%"PRIu32", "
2442 "granted=%"PRIu32", do_upgrade=%d\n",
2443 existing, requested, granted, (int)do_upgrade));
2445 if (do_upgrade) {
2446 NTSTATUS set_status;
2448 current_state = granted;
2449 epoch += 1;
2451 set_status = leases_db_set(
2452 client_guid,
2453 &lease->lease_key,
2454 current_state,
2455 breaking,
2456 breaking_to_requested,
2457 breaking_to_required,
2458 lease_version,
2459 epoch);
2461 if (!NT_STATUS_IS_OK(set_status)) {
2462 DBG_DEBUG("leases_db_set failed: %s\n",
2463 nt_errstr(set_status));
2464 return set_status;
2468 fsp_lease_update(fsp);
2470 return NT_STATUS_OK;
2473 static NTSTATUS grant_new_fsp_lease(struct files_struct *fsp,
2474 struct share_mode_lock *lck,
2475 const struct GUID *client_guid,
2476 const struct smb2_lease *lease,
2477 uint32_t granted)
2479 NTSTATUS status;
2481 fsp->lease = talloc_zero(fsp->conn->sconn, struct fsp_lease);
2482 if (fsp->lease == NULL) {
2483 return NT_STATUS_INSUFFICIENT_RESOURCES;
2485 fsp->lease->ref_count = 1;
2486 fsp->lease->sconn = fsp->conn->sconn;
2487 fsp->lease->lease.lease_version = lease->lease_version;
2488 fsp->lease->lease.lease_key = lease->lease_key;
2489 fsp->lease->lease.lease_state = granted;
2490 fsp->lease->lease.lease_epoch = lease->lease_epoch + 1;
2492 status = leases_db_add(client_guid,
2493 &lease->lease_key,
2494 &fsp->file_id,
2495 fsp->lease->lease.lease_state,
2496 fsp->lease->lease.lease_version,
2497 fsp->lease->lease.lease_epoch,
2498 fsp->conn->connectpath,
2499 fsp->fsp_name->base_name,
2500 fsp->fsp_name->stream_name);
2501 if (!NT_STATUS_IS_OK(status)) {
2502 DEBUG(10, ("%s: leases_db_add failed: %s\n", __func__,
2503 nt_errstr(status)));
2504 TALLOC_FREE(fsp->lease);
2505 return NT_STATUS_INSUFFICIENT_RESOURCES;
2509 * We used to set lck->data->modified=true here without
2510 * actually modifying lck->data, triggering a needless
2511 * writeback of lck->data.
2513 * Apart from that writeback, setting modified=true has the
2514 * effect of triggering all waiters for this file to
2515 * retry. This only makes sense if any blocking condition
2516 * (i.e. waiting for a lease to be downgraded or removed) is
2517 * gone. This routine here only adds a lease, so it will never
2518 * free up resources that blocked waiters can now claim. So
2519 * that second effect also does not matter in this
2520 * routine. Thus setting lck->data->modified=true does not
2521 * need to be done here.
2524 return NT_STATUS_OK;
2527 static NTSTATUS grant_fsp_lease(struct files_struct *fsp,
2528 struct share_mode_lock *lck,
2529 const struct smb2_lease *lease,
2530 uint32_t granted)
2532 const struct GUID *client_guid = fsp_client_guid(fsp);
2533 NTSTATUS status;
2535 status = try_lease_upgrade(fsp, lck, client_guid, lease, granted);
2537 if (NT_STATUS_EQUAL(status, NT_STATUS_NOT_FOUND)) {
2538 status = grant_new_fsp_lease(
2539 fsp, lck, client_guid, lease, granted);
2542 return status;
2545 static int map_lease_type_to_oplock(uint32_t lease_type)
2547 int result = NO_OPLOCK;
2549 switch (lease_type) {
2550 case SMB2_LEASE_READ|SMB2_LEASE_WRITE|SMB2_LEASE_HANDLE:
2551 result = BATCH_OPLOCK|EXCLUSIVE_OPLOCK;
2552 break;
2553 case SMB2_LEASE_READ|SMB2_LEASE_WRITE:
2554 result = EXCLUSIVE_OPLOCK;
2555 break;
2556 case SMB2_LEASE_READ|SMB2_LEASE_HANDLE:
2557 case SMB2_LEASE_READ:
2558 result = LEVEL_II_OPLOCK;
2559 break;
2562 return result;
2565 struct delay_for_oplock_state {
2566 struct files_struct *fsp;
2567 const struct smb2_lease *lease;
2568 bool will_overwrite;
2569 uint32_t delay_mask;
2570 bool first_open_attempt;
2571 bool got_handle_lease;
2572 bool got_oplock;
2573 bool have_other_lease;
2574 bool delay;
2577 static bool delay_for_oplock_fn(
2578 struct share_mode_entry *e,
2579 bool *modified,
2580 void *private_data)
2582 struct delay_for_oplock_state *state = private_data;
2583 struct files_struct *fsp = state->fsp;
2584 const struct smb2_lease *lease = state->lease;
2585 bool e_is_lease = (e->op_type == LEASE_OPLOCK);
2586 uint32_t e_lease_type = SMB2_LEASE_NONE;
2587 uint32_t break_to;
2588 bool lease_is_breaking = false;
2590 if (e_is_lease) {
2591 NTSTATUS status;
2593 if (lease != NULL) {
2594 bool our_lease = is_same_lease(fsp, e, lease);
2595 if (our_lease) {
2596 DBG_DEBUG("Ignoring our own lease\n");
2597 return false;
2601 status = leases_db_get(
2602 &e->client_guid,
2603 &e->lease_key,
2604 &fsp->file_id,
2605 &e_lease_type, /* current_state */
2606 &lease_is_breaking,
2607 NULL, /* breaking_to_requested */
2608 NULL, /* breaking_to_required */
2609 NULL, /* lease_version */
2610 NULL); /* epoch */
2613 * leases_db_get() can return NT_STATUS_NOT_FOUND
2614 * if the share_mode_entry e is stale and the
2615 * lease record was already removed. In this case return
2616 * false so the traverse continues.
2619 if (NT_STATUS_EQUAL(status, NT_STATUS_NOT_FOUND) &&
2620 share_entry_stale_pid(e))
2622 struct GUID_txt_buf guid_strbuf;
2623 struct file_id_buf file_id_strbuf;
2624 DBG_DEBUG("leases_db_get for client_guid [%s] "
2625 "lease_key [%"PRIu64"/%"PRIu64"] "
2626 "file_id [%s] failed for stale "
2627 "share_mode_entry\n",
2628 GUID_buf_string(&e->client_guid, &guid_strbuf),
2629 e->lease_key.data[0],
2630 e->lease_key.data[1],
2631 file_id_str_buf(fsp->file_id, &file_id_strbuf));
2632 return false;
2634 if (!NT_STATUS_IS_OK(status)) {
2635 struct GUID_txt_buf guid_strbuf;
2636 struct file_id_buf file_id_strbuf;
2637 DBG_ERR("leases_db_get for client_guid [%s] "
2638 "lease_key [%"PRIu64"/%"PRIu64"] "
2639 "file_id [%s] failed: %s\n",
2640 GUID_buf_string(&e->client_guid, &guid_strbuf),
2641 e->lease_key.data[0],
2642 e->lease_key.data[1],
2643 file_id_str_buf(fsp->file_id, &file_id_strbuf),
2644 nt_errstr(status));
2645 smb_panic("leases_db_get() failed");
2647 } else {
2648 e_lease_type = get_lease_type(e, fsp->file_id);
2651 if (!state->got_handle_lease &&
2652 ((e_lease_type & SMB2_LEASE_HANDLE) != 0) &&
2653 !share_entry_stale_pid(e)) {
2654 state->got_handle_lease = true;
2657 if (!state->got_oplock &&
2658 (e->op_type != LEASE_OPLOCK) &&
2659 !share_entry_stale_pid(e)) {
2660 state->got_oplock = true;
2663 if (!state->have_other_lease &&
2664 !is_same_lease(fsp, e, lease) &&
2665 !share_entry_stale_pid(e)) {
2666 state->have_other_lease = true;
2669 if (e_is_lease && is_lease_stat_open(fsp->access_mask)) {
2670 return false;
2673 break_to = e_lease_type & ~state->delay_mask;
2675 if (state->will_overwrite) {
2676 break_to &= ~(SMB2_LEASE_HANDLE|SMB2_LEASE_READ);
2679 DBG_DEBUG("e_lease_type %u, will_overwrite: %u\n",
2680 (unsigned)e_lease_type,
2681 (unsigned)state->will_overwrite);
2683 if ((e_lease_type & ~break_to) == 0) {
2684 if (lease_is_breaking) {
2685 state->delay = true;
2687 return false;
2690 if (share_entry_stale_pid(e)) {
2691 return false;
2694 if (state->will_overwrite) {
2696 * If we break anyway break to NONE directly.
2697 * Otherwise vfs_set_filelen() will trigger the
2698 * break.
2700 break_to &= ~(SMB2_LEASE_READ|SMB2_LEASE_WRITE);
2703 if (!e_is_lease) {
2705 * Oplocks only support breaking to R or NONE.
2707 break_to &= ~(SMB2_LEASE_HANDLE|SMB2_LEASE_WRITE);
2710 DBG_DEBUG("breaking from %d to %d\n",
2711 (int)e_lease_type,
2712 (int)break_to);
2713 send_break_message(
2714 fsp->conn->sconn->msg_ctx, &fsp->file_id, e, break_to);
2715 if (e_lease_type & state->delay_mask) {
2716 state->delay = true;
2718 if (lease_is_breaking && !state->first_open_attempt) {
2719 state->delay = true;
2722 return false;
2725 static NTSTATUS delay_for_oplock(files_struct *fsp,
2726 int oplock_request,
2727 const struct smb2_lease *lease,
2728 struct share_mode_lock *lck,
2729 bool have_sharing_violation,
2730 uint32_t create_disposition,
2731 bool first_open_attempt,
2732 int *poplock_type,
2733 uint32_t *pgranted)
2735 struct delay_for_oplock_state state = {
2736 .fsp = fsp,
2737 .lease = lease,
2738 .first_open_attempt = first_open_attempt,
2740 uint32_t requested;
2741 uint32_t granted;
2742 int oplock_type;
2743 bool ok;
2745 *poplock_type = NO_OPLOCK;
2746 *pgranted = 0;
2748 if (fsp->fsp_flags.is_directory) {
2750 * No directory leases yet
2752 SMB_ASSERT(oplock_request == NO_OPLOCK);
2753 if (have_sharing_violation) {
2754 return NT_STATUS_SHARING_VIOLATION;
2756 return NT_STATUS_OK;
2759 if (oplock_request == LEASE_OPLOCK) {
2760 if (lease == NULL) {
2762 * The SMB2 layer should have checked this
2764 return NT_STATUS_INTERNAL_ERROR;
2767 requested = lease->lease_state;
2768 } else {
2769 requested = map_oplock_to_lease_type(
2770 oplock_request & ~SAMBA_PRIVATE_OPLOCK_MASK);
2773 if (is_oplock_stat_open(fsp->access_mask)) {
2774 goto grant;
2777 state.delay_mask = have_sharing_violation ?
2778 SMB2_LEASE_HANDLE : SMB2_LEASE_WRITE;
2780 switch (create_disposition) {
2781 case FILE_SUPERSEDE:
2782 case FILE_OVERWRITE:
2783 case FILE_OVERWRITE_IF:
2784 state.will_overwrite = true;
2785 break;
2786 default:
2787 state.will_overwrite = false;
2788 break;
2791 ok = share_mode_forall_entries(lck, delay_for_oplock_fn, &state);
2792 if (!ok) {
2793 return NT_STATUS_INTERNAL_ERROR;
2796 if (state.delay) {
2797 return NT_STATUS_RETRY;
2800 grant:
2801 if (have_sharing_violation) {
2802 return NT_STATUS_SHARING_VIOLATION;
2805 granted = requested;
2807 if (oplock_request == LEASE_OPLOCK) {
2808 if (lp_kernel_oplocks(SNUM(fsp->conn))) {
2809 DEBUG(10, ("No lease granted because kernel oplocks are enabled\n"));
2810 granted = SMB2_LEASE_NONE;
2812 if ((granted & (SMB2_LEASE_READ|SMB2_LEASE_WRITE)) == 0) {
2813 DEBUG(10, ("No read or write lease requested\n"));
2814 granted = SMB2_LEASE_NONE;
2816 if (granted == SMB2_LEASE_WRITE) {
2817 DEBUG(10, ("pure write lease requested\n"));
2818 granted = SMB2_LEASE_NONE;
2820 if (granted == (SMB2_LEASE_WRITE|SMB2_LEASE_HANDLE)) {
2821 DEBUG(10, ("write and handle lease requested\n"));
2822 granted = SMB2_LEASE_NONE;
2826 if (lp_locking(fsp->conn->params) && file_has_brlocks(fsp)) {
2827 DBG_DEBUG("file %s has byte range locks\n",
2828 fsp_str_dbg(fsp));
2829 granted &= ~SMB2_LEASE_READ;
2832 if (state.have_other_lease) {
2834 * Can grant only one writer
2836 granted &= ~SMB2_LEASE_WRITE;
2839 if ((granted & SMB2_LEASE_READ) && !(granted & SMB2_LEASE_WRITE)) {
2840 bool allow_level2 =
2841 (global_client_caps & CAP_LEVEL_II_OPLOCKS) &&
2842 lp_level2_oplocks(SNUM(fsp->conn));
2844 if (!allow_level2) {
2845 granted = SMB2_LEASE_NONE;
2849 if (oplock_request == LEASE_OPLOCK) {
2850 if (state.got_oplock) {
2851 granted &= ~SMB2_LEASE_HANDLE;
2854 oplock_type = LEASE_OPLOCK;
2855 } else {
2856 if (state.got_handle_lease) {
2857 granted = SMB2_LEASE_NONE;
2861 * Reflect possible downgrades from:
2862 * - map_lease_type_to_oplock() => "RH" to just LEVEL_II
2864 oplock_type = map_lease_type_to_oplock(granted);
2865 granted = map_oplock_to_lease_type(oplock_type);
2868 if (granted & SMB2_LEASE_READ) {
2869 uint32_t acc, sh, ls;
2870 share_mode_flags_get(lck, &acc, &sh, &ls);
2871 ls |= SMB2_LEASE_READ;
2872 share_mode_flags_set(lck, acc, sh, ls, NULL);
2875 DBG_DEBUG("oplock type 0x%x granted (%s%s%s)(0x%x), on file %s, "
2876 "requested 0x%x (%s%s%s)(0x%x)\n",
2877 fsp->oplock_type,
2878 granted & SMB2_LEASE_READ ? "R":"",
2879 granted & SMB2_LEASE_WRITE ? "W":"",
2880 granted & SMB2_LEASE_HANDLE ? "H":"",
2881 granted,
2882 fsp_str_dbg(fsp),
2883 oplock_request,
2884 requested & SMB2_LEASE_READ ? "R":"",
2885 requested & SMB2_LEASE_WRITE ? "W":"",
2886 requested & SMB2_LEASE_HANDLE ? "H":"",
2887 requested);
2889 *poplock_type = oplock_type;
2890 *pgranted = granted;
2891 return NT_STATUS_OK;
2894 static NTSTATUS handle_share_mode_lease(
2895 files_struct *fsp,
2896 struct share_mode_lock *lck,
2897 uint32_t create_disposition,
2898 uint32_t access_mask,
2899 uint32_t share_access,
2900 int oplock_request,
2901 const struct smb2_lease *lease,
2902 bool first_open_attempt,
2903 int *poplock_type,
2904 uint32_t *pgranted)
2906 bool sharing_violation = false;
2907 NTSTATUS status;
2909 *poplock_type = NO_OPLOCK;
2910 *pgranted = 0;
2912 status = open_mode_check(
2913 fsp->conn, fsp->file_id, lck, access_mask, share_access);
2914 if (NT_STATUS_EQUAL(status, NT_STATUS_SHARING_VIOLATION)) {
2915 sharing_violation = true;
2916 status = NT_STATUS_OK; /* handled later */
2919 if (!NT_STATUS_IS_OK(status)) {
2920 return status;
2923 if (oplock_request == INTERNAL_OPEN_ONLY) {
2924 if (sharing_violation) {
2925 DBG_DEBUG("Sharing violation for internal open\n");
2926 return NT_STATUS_SHARING_VIOLATION;
2930 * Internal opens never do oplocks or leases. We don't
2931 * need to go through delay_for_oplock().
2933 return NT_STATUS_OK;
2936 status = delay_for_oplock(
2937 fsp,
2938 oplock_request,
2939 lease,
2940 lck,
2941 sharing_violation,
2942 create_disposition,
2943 first_open_attempt,
2944 poplock_type,
2945 pgranted);
2946 if (!NT_STATUS_IS_OK(status)) {
2947 return status;
2950 return NT_STATUS_OK;
2953 static bool request_timed_out(struct smb_request *req, struct timeval timeout)
2955 struct timeval now, end_time;
2956 GetTimeOfDay(&now);
2957 end_time = timeval_sum(&req->request_time, &timeout);
2958 return (timeval_compare(&end_time, &now) < 0);
2961 struct defer_open_state {
2962 struct smbXsrv_connection *xconn;
2963 uint64_t mid;
2966 static void defer_open_done(struct tevent_req *req);
2969 * Defer an open and watch a locking.tdb record
2971 * This defers an open that gets rescheduled once the locking.tdb record watch
2972 * is triggered by a change to the record.
2974 * It is used to defer opens that triggered an oplock break and for the SMB1
2975 * sharing violation delay.
2977 static void defer_open(struct share_mode_lock *lck,
2978 struct timeval timeout,
2979 struct smb_request *req,
2980 struct file_id id)
2982 struct deferred_open_record *open_rec = NULL;
2983 struct timeval abs_timeout;
2984 struct defer_open_state *watch_state;
2985 struct tevent_req *watch_req;
2986 struct timeval_buf tvbuf1, tvbuf2;
2987 struct file_id_buf fbuf;
2988 bool ok;
2990 abs_timeout = timeval_sum(&req->request_time, &timeout);
2992 DBG_DEBUG("request time [%s] timeout [%s] mid [%" PRIu64 "] "
2993 "file_id [%s]\n",
2994 timeval_str_buf(&req->request_time, false, true, &tvbuf1),
2995 timeval_str_buf(&abs_timeout, false, true, &tvbuf2),
2996 req->mid,
2997 file_id_str_buf(id, &fbuf));
2999 open_rec = talloc_zero(NULL, struct deferred_open_record);
3000 if (open_rec == NULL) {
3001 TALLOC_FREE(lck);
3002 exit_server("talloc failed");
3005 watch_state = talloc(open_rec, struct defer_open_state);
3006 if (watch_state == NULL) {
3007 exit_server("talloc failed");
3009 watch_state->xconn = req->xconn;
3010 watch_state->mid = req->mid;
3012 DBG_DEBUG("defering mid %" PRIu64 "\n", req->mid);
3014 watch_req = share_mode_watch_send(
3015 watch_state,
3016 req->sconn->ev_ctx,
3017 lck,
3018 (struct server_id){0});
3019 if (watch_req == NULL) {
3020 exit_server("Could not watch share mode record");
3022 tevent_req_set_callback(watch_req, defer_open_done, watch_state);
3024 ok = tevent_req_set_endtime(watch_req, req->sconn->ev_ctx, abs_timeout);
3025 if (!ok) {
3026 exit_server("tevent_req_set_endtime failed");
3029 ok = push_deferred_open_message_smb(req, timeout, id, open_rec);
3030 if (!ok) {
3031 TALLOC_FREE(lck);
3032 exit_server("push_deferred_open_message_smb failed");
3036 static void defer_open_done(struct tevent_req *req)
3038 struct defer_open_state *state = tevent_req_callback_data(
3039 req, struct defer_open_state);
3040 NTSTATUS status;
3041 bool ret;
3043 status = share_mode_watch_recv(req, NULL, NULL);
3044 TALLOC_FREE(req);
3045 if (!NT_STATUS_IS_OK(status)) {
3046 DEBUG(5, ("dbwrap_watched_watch_recv returned %s\n",
3047 nt_errstr(status)));
3049 * Even if it failed, retry anyway. TODO: We need a way to
3050 * tell a re-scheduled open about that error.
3054 DEBUG(10, ("scheduling mid %llu\n", (unsigned long long)state->mid));
3056 ret = schedule_deferred_open_message_smb(state->xconn, state->mid);
3057 SMB_ASSERT(ret);
3058 TALLOC_FREE(state);
3062 * Actually attempt the kernel oplock polling open.
3065 static void poll_open_fn(struct tevent_context *ev,
3066 struct tevent_timer *te,
3067 struct timeval current_time,
3068 void *private_data)
3070 struct deferred_open_record *open_rec = talloc_get_type_abort(
3071 private_data, struct deferred_open_record);
3072 bool ok;
3074 TALLOC_FREE(open_rec->watch_req);
3076 ok = schedule_deferred_open_message_smb(
3077 open_rec->xconn, open_rec->mid);
3078 if (!ok) {
3079 exit_server("schedule_deferred_open_message_smb failed");
3081 DBG_DEBUG("timer fired. Retrying open !\n");
3084 static void poll_open_done(struct tevent_req *subreq);
3086 struct poll_open_setup_watcher_state {
3087 TALLOC_CTX *mem_ctx;
3088 struct tevent_context *ev_ctx;
3089 struct tevent_req *watch_req;
3092 static void poll_open_setup_watcher_fn(struct share_mode_lock *lck,
3093 void *private_data)
3095 struct poll_open_setup_watcher_state *state =
3096 (struct poll_open_setup_watcher_state *)private_data;
3098 if (!validate_oplock_types(lck)) {
3099 smb_panic("validate_oplock_types failed");
3102 state->watch_req = share_mode_watch_send(
3103 state->mem_ctx,
3104 state->ev_ctx,
3105 lck,
3106 (struct server_id) {0});
3107 if (state->watch_req == NULL) {
3108 DBG_WARNING("share_mode_watch_send failed\n");
3109 return;
3114 * Reschedule an open for 1 second from now, if not timed out.
3116 static bool setup_poll_open(
3117 struct smb_request *req,
3118 const struct file_id *id,
3119 struct timeval max_timeout,
3120 struct timeval interval)
3122 static struct file_id zero_id = {};
3123 bool ok;
3124 struct deferred_open_record *open_rec = NULL;
3125 struct timeval endtime, next_interval;
3126 struct file_id_buf ftmp;
3128 if (request_timed_out(req, max_timeout)) {
3129 return false;
3132 open_rec = talloc_zero(NULL, struct deferred_open_record);
3133 if (open_rec == NULL) {
3134 DBG_WARNING("talloc failed\n");
3135 return false;
3137 open_rec->xconn = req->xconn;
3138 open_rec->mid = req->mid;
3141 * Make sure open_rec->te does not come later than the
3142 * request's maximum endtime.
3145 endtime = timeval_sum(&req->request_time, &max_timeout);
3146 next_interval = timeval_current_ofs(interval.tv_sec, interval.tv_usec);
3147 next_interval = timeval_min(&endtime, &next_interval);
3149 open_rec->te = tevent_add_timer(
3150 req->sconn->ev_ctx,
3151 open_rec,
3152 next_interval,
3153 poll_open_fn,
3154 open_rec);
3155 if (open_rec->te == NULL) {
3156 DBG_WARNING("tevent_add_timer failed\n");
3157 TALLOC_FREE(open_rec);
3158 return false;
3161 if (id != NULL) {
3162 struct poll_open_setup_watcher_state wstate = {
3163 .mem_ctx = open_rec,
3164 .ev_ctx = req->sconn->ev_ctx,
3166 NTSTATUS status;
3168 status = share_mode_do_locked_vfs_denied(*id,
3169 poll_open_setup_watcher_fn,
3170 &wstate);
3171 if (NT_STATUS_IS_OK(status)) {
3172 if (wstate.watch_req == NULL) {
3173 DBG_WARNING("share_mode_watch_send failed\n");
3174 TALLOC_FREE(open_rec);
3175 return false;
3177 open_rec->watch_req = wstate.watch_req;
3178 tevent_req_set_callback(open_rec->watch_req,
3179 poll_open_done,
3180 open_rec);
3181 } else if (!NT_STATUS_EQUAL(status, NT_STATUS_NOT_FOUND)) {
3182 DBG_WARNING("share_mode_do_locked_vfs_denied failed - %s\n",
3183 nt_errstr(status));
3184 TALLOC_FREE(open_rec);
3185 return false;
3187 } else {
3188 id = &zero_id;
3191 ok = push_deferred_open_message_smb(req, max_timeout, *id, open_rec);
3192 if (!ok) {
3193 DBG_WARNING("push_deferred_open_message_smb failed\n");
3194 TALLOC_FREE(open_rec);
3195 return false;
3198 DBG_DEBUG("poll request time [%s] mid [%" PRIu64 "] file_id [%s]\n",
3199 timeval_string(talloc_tos(), &req->request_time, false),
3200 req->mid,
3201 file_id_str_buf(*id, &ftmp));
3203 return true;
3206 static void poll_open_done(struct tevent_req *subreq)
3208 struct deferred_open_record *open_rec = tevent_req_callback_data(
3209 subreq, struct deferred_open_record);
3210 NTSTATUS status;
3211 bool ok;
3213 status = share_mode_watch_recv(subreq, NULL, NULL);
3214 TALLOC_FREE(subreq);
3215 open_rec->watch_req = NULL;
3216 TALLOC_FREE(open_rec->te);
3218 DBG_DEBUG("dbwrap_watched_watch_recv returned %s\n",
3219 nt_errstr(status));
3221 ok = schedule_deferred_open_message_smb(
3222 open_rec->xconn, open_rec->mid);
3223 if (!ok) {
3224 exit_server("schedule_deferred_open_message_smb failed");
3228 bool defer_smb1_sharing_violation(struct smb_request *req)
3230 bool ok;
3231 int timeout_usecs;
3233 if (!lp_defer_sharing_violations()) {
3234 return false;
3238 * Try every 200msec up to (by default) one second. To be
3239 * precise, according to behaviour note <247> in [MS-CIFS],
3240 * the server tries 5 times. But up to one second should be
3241 * close enough.
3244 timeout_usecs = lp_parm_int(
3245 SNUM(req->conn),
3246 "smbd",
3247 "sharedelay",
3248 SHARING_VIOLATION_USEC_WAIT);
3250 ok = setup_poll_open(
3251 req,
3252 NULL,
3253 (struct timeval) { .tv_usec = timeout_usecs },
3254 (struct timeval) { .tv_usec = 200000 });
3255 return ok;
3258 /****************************************************************************
3259 On overwrite open ensure that the attributes match.
3260 ****************************************************************************/
3262 static bool open_match_attributes(connection_struct *conn,
3263 uint32_t old_dos_attr,
3264 uint32_t new_dos_attr,
3265 mode_t new_unx_mode,
3266 mode_t *returned_unx_mode)
3268 uint32_t noarch_old_dos_attr, noarch_new_dos_attr;
3270 noarch_old_dos_attr = (old_dos_attr & ~FILE_ATTRIBUTE_ARCHIVE);
3271 noarch_new_dos_attr = (new_dos_attr & ~FILE_ATTRIBUTE_ARCHIVE);
3273 if((noarch_old_dos_attr == 0 && noarch_new_dos_attr != 0) ||
3274 (noarch_old_dos_attr != 0 && ((noarch_old_dos_attr & noarch_new_dos_attr) == noarch_old_dos_attr))) {
3275 *returned_unx_mode = new_unx_mode;
3276 } else {
3277 *returned_unx_mode = (mode_t)0;
3280 DEBUG(10,("open_match_attributes: old_dos_attr = 0x%x, "
3281 "new_dos_attr = 0x%x "
3282 "returned_unx_mode = 0%o\n",
3283 (unsigned int)old_dos_attr,
3284 (unsigned int)new_dos_attr,
3285 (unsigned int)*returned_unx_mode ));
3287 /* If we're mapping SYSTEM and HIDDEN ensure they match. */
3288 if (lp_map_system(SNUM(conn)) || lp_store_dos_attributes(SNUM(conn))) {
3289 if ((old_dos_attr & FILE_ATTRIBUTE_SYSTEM) &&
3290 !(new_dos_attr & FILE_ATTRIBUTE_SYSTEM)) {
3291 return False;
3294 if (lp_map_hidden(SNUM(conn)) || lp_store_dos_attributes(SNUM(conn))) {
3295 if ((old_dos_attr & FILE_ATTRIBUTE_HIDDEN) &&
3296 !(new_dos_attr & FILE_ATTRIBUTE_HIDDEN)) {
3297 return False;
3300 return True;
3303 static void schedule_defer_open(struct share_mode_lock *lck,
3304 struct file_id id,
3305 struct smb_request *req)
3307 /* This is a relative time, added to the absolute
3308 request_time value to get the absolute timeout time.
3309 Note that if this is the second or greater time we enter
3310 this codepath for this particular request mid then
3311 request_time is left as the absolute time of the *first*
3312 time this request mid was processed. This is what allows
3313 the request to eventually time out. */
3315 struct timeval timeout;
3317 /* Normally the smbd we asked should respond within
3318 * OPLOCK_BREAK_TIMEOUT seconds regardless of whether
3319 * the client did, give twice the timeout as a safety
3320 * measure here in case the other smbd is stuck
3321 * somewhere else. */
3323 timeout = timeval_set(OPLOCK_BREAK_TIMEOUT*2, 0);
3325 if (request_timed_out(req, timeout)) {
3326 return;
3329 defer_open(lck, timeout, req, id);
3332 /****************************************************************************
3333 Reschedule an open call that went asynchronous.
3334 ****************************************************************************/
3336 static void schedule_async_open_timer(struct tevent_context *ev,
3337 struct tevent_timer *te,
3338 struct timeval current_time,
3339 void *private_data)
3341 exit_server("async open timeout");
3344 static void schedule_async_open(struct smb_request *req)
3346 struct deferred_open_record *open_rec = NULL;
3347 struct timeval timeout = timeval_set(20, 0);
3348 bool ok;
3350 if (request_timed_out(req, timeout)) {
3351 return;
3354 open_rec = talloc_zero(NULL, struct deferred_open_record);
3355 if (open_rec == NULL) {
3356 exit_server("deferred_open_record_create failed");
3358 open_rec->async_open = true;
3360 ok = push_deferred_open_message_smb(
3361 req, timeout, (struct file_id){0}, open_rec);
3362 if (!ok) {
3363 exit_server("push_deferred_open_message_smb failed");
3366 open_rec->te = tevent_add_timer(req->sconn->ev_ctx,
3367 req,
3368 timeval_current_ofs(20, 0),
3369 schedule_async_open_timer,
3370 open_rec);
3371 if (open_rec->te == NULL) {
3372 exit_server("tevent_add_timer failed");
3376 /****************************************************************************
3377 Work out what access_mask to use from what the client sent us.
3378 ****************************************************************************/
3380 static NTSTATUS smbd_calculate_maximum_allowed_access_fsp(
3381 struct files_struct *dirfsp,
3382 struct files_struct *fsp,
3383 bool use_privs,
3384 uint32_t *p_access_mask)
3386 struct security_descriptor *sd = NULL;
3387 uint32_t access_granted = 0;
3388 uint32_t dosattrs;
3389 NTSTATUS status;
3391 /* Cope with symlinks */
3392 if (fsp == NULL || fsp_get_pathref_fd(fsp) == -1) {
3393 *p_access_mask = FILE_GENERIC_ALL;
3394 return NT_STATUS_OK;
3397 /* Cope with fake/printer fsp's. */
3398 if (fsp->fake_file_handle != NULL || fsp->print_file != NULL) {
3399 *p_access_mask = FILE_GENERIC_ALL;
3400 return NT_STATUS_OK;
3403 if (!use_privs && (get_current_uid(fsp->conn) == (uid_t)0)) {
3404 *p_access_mask |= FILE_GENERIC_ALL;
3405 return NT_STATUS_OK;
3408 status = SMB_VFS_FGET_NT_ACL(metadata_fsp(fsp),
3409 (SECINFO_OWNER |
3410 SECINFO_GROUP |
3411 SECINFO_DACL),
3412 talloc_tos(),
3413 &sd);
3415 if (NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
3417 * File did not exist
3419 *p_access_mask = FILE_GENERIC_ALL;
3420 return NT_STATUS_OK;
3422 if (!NT_STATUS_IS_OK(status)) {
3423 DBG_ERR("Could not get acl on file %s: %s\n",
3424 fsp_str_dbg(fsp),
3425 nt_errstr(status));
3426 return status;
3430 * If we can access the path to this file, by
3431 * default we have FILE_READ_ATTRIBUTES from the
3432 * containing directory. See the section:
3433 * "Algorithm to Check Access to an Existing File"
3434 * in MS-FSA.pdf.
3436 * se_file_access_check()
3437 * also takes care of owner WRITE_DAC and READ_CONTROL.
3439 status = se_file_access_check(sd,
3440 get_current_nttok(fsp->conn),
3441 use_privs,
3442 (*p_access_mask & ~FILE_READ_ATTRIBUTES),
3443 &access_granted);
3445 TALLOC_FREE(sd);
3447 if (!NT_STATUS_IS_OK(status)) {
3448 DBG_ERR("Status %s on file %s: "
3449 "when calculating maximum access\n",
3450 nt_errstr(status),
3451 fsp_str_dbg(fsp));
3452 return status;
3455 *p_access_mask = (access_granted | FILE_READ_ATTRIBUTES);
3457 if (!(access_granted & DELETE_ACCESS)) {
3458 if (can_delete_file_in_directory(fsp->conn,
3459 dirfsp,
3460 fsp->fsp_name)) {
3461 *p_access_mask |= DELETE_ACCESS;
3465 dosattrs = fdos_mode(fsp);
3466 if (IS_DOS_READONLY(dosattrs) || !CAN_WRITE(fsp->conn)) {
3467 *p_access_mask &= ~(FILE_GENERIC_WRITE | DELETE_ACCESS);
3470 return NT_STATUS_OK;
3473 NTSTATUS smbd_calculate_access_mask_fsp(struct files_struct *dirfsp,
3474 struct files_struct *fsp,
3475 bool use_privs,
3476 uint32_t access_mask,
3477 uint32_t *access_mask_out)
3479 NTSTATUS status;
3480 uint32_t orig_access_mask = access_mask;
3481 uint32_t rejected_share_access;
3483 if (access_mask & SEC_MASK_INVALID) {
3484 DBG_DEBUG("access_mask [%8x] contains invalid bits\n",
3485 access_mask);
3486 return NT_STATUS_ACCESS_DENIED;
3490 * Convert GENERIC bits to specific bits.
3493 se_map_generic(&access_mask, &file_generic_mapping);
3495 /* Calculate MAXIMUM_ALLOWED_ACCESS if requested. */
3496 if (access_mask & MAXIMUM_ALLOWED_ACCESS) {
3498 status = smbd_calculate_maximum_allowed_access_fsp(
3499 dirfsp,
3500 fsp,
3501 use_privs,
3502 &access_mask);
3504 if (!NT_STATUS_IS_OK(status)) {
3505 return status;
3508 access_mask &= fsp->conn->share_access;
3511 rejected_share_access = access_mask & ~(fsp->conn->share_access);
3513 if (rejected_share_access) {
3514 DBG_ERR("Access denied on file %s: "
3515 "rejected by share access mask[0x%08X] "
3516 "orig[0x%08X] mapped[0x%08X] reject[0x%08X]\n",
3517 fsp_str_dbg(fsp),
3518 fsp->conn->share_access,
3519 orig_access_mask, access_mask,
3520 rejected_share_access);
3521 return NT_STATUS_ACCESS_DENIED;
3524 *access_mask_out = access_mask;
3525 return NT_STATUS_OK;
3528 /****************************************************************************
3529 Remove the deferred open entry under lock.
3530 ****************************************************************************/
3532 /****************************************************************************
3533 Return true if this is a state pointer to an asynchronous create.
3534 ****************************************************************************/
3536 bool is_deferred_open_async(const struct deferred_open_record *rec)
3538 return rec->async_open;
3541 static bool clear_ads(uint32_t create_disposition)
3543 bool ret = false;
3545 switch (create_disposition) {
3546 case FILE_SUPERSEDE:
3547 case FILE_OVERWRITE_IF:
3548 case FILE_OVERWRITE:
3549 ret = true;
3550 break;
3551 default:
3552 break;
3554 return ret;
3557 static int disposition_to_open_flags(uint32_t create_disposition)
3559 int ret = 0;
3562 * Currently we're using FILE_SUPERSEDE as the same as
3563 * FILE_OVERWRITE_IF but they really are
3564 * different. FILE_SUPERSEDE deletes an existing file
3565 * (requiring delete access) then recreates it.
3568 switch (create_disposition) {
3569 case FILE_SUPERSEDE:
3570 case FILE_OVERWRITE_IF:
3572 * If file exists replace/overwrite. If file doesn't
3573 * exist create.
3575 ret = O_CREAT|O_TRUNC;
3576 break;
3578 case FILE_OPEN:
3580 * If file exists open. If file doesn't exist error.
3582 ret = 0;
3583 break;
3585 case FILE_OVERWRITE:
3587 * If file exists overwrite. If file doesn't exist
3588 * error.
3590 ret = O_TRUNC;
3591 break;
3593 case FILE_CREATE:
3595 * If file exists error. If file doesn't exist create.
3597 ret = O_CREAT|O_EXCL;
3598 break;
3600 case FILE_OPEN_IF:
3602 * If file exists open. If file doesn't exist create.
3604 ret = O_CREAT;
3605 break;
3607 return ret;
3610 static int calculate_open_access_flags(uint32_t access_mask,
3611 uint32_t private_flags)
3613 bool need_write, need_read;
3616 * Note that we ignore the append flag as append does not
3617 * mean the same thing under DOS and Unix.
3620 need_write = (access_mask & (FILE_WRITE_DATA | FILE_APPEND_DATA));
3621 if (!need_write) {
3622 return O_RDONLY;
3625 /* DENY_DOS opens are always underlying read-write on the
3626 file handle, no matter what the requested access mask
3627 says. */
3629 need_read =
3630 ((private_flags & NTCREATEX_FLAG_DENY_DOS) ||
3631 access_mask & (FILE_READ_ATTRIBUTES|FILE_READ_DATA|
3632 FILE_READ_EA|FILE_EXECUTE));
3634 if (!need_read) {
3635 return O_WRONLY;
3637 return O_RDWR;
3640 /****************************************************************************
3641 Open a file with a share mode. Passed in an already created files_struct *.
3642 ****************************************************************************/
3644 static NTSTATUS open_file_ntcreate(connection_struct *conn,
3645 struct smb_request *req,
3646 uint32_t access_mask, /* access bits (FILE_READ_DATA etc.) */
3647 uint32_t share_access, /* share constants (FILE_SHARE_READ etc) */
3648 uint32_t create_disposition, /* FILE_OPEN_IF etc. */
3649 uint32_t create_options, /* options such as delete on close. */
3650 uint32_t new_dos_attributes, /* attributes used for new file. */
3651 int oplock_request, /* internal Samba oplock codes. */
3652 const struct smb2_lease *lease,
3653 /* Information (FILE_EXISTS etc.) */
3654 uint32_t private_flags, /* Samba specific flags. */
3655 struct smb_filename *parent_dir_fname, /* parent. */
3656 struct smb_filename *smb_fname_atname, /* atname relative to parent. */
3657 int *pinfo,
3658 files_struct *fsp)
3660 struct smb_filename *smb_fname = fsp->fsp_name;
3661 int flags=0;
3662 int flags2=0;
3663 bool file_existed = VALID_STAT(smb_fname->st);
3664 bool def_acl = False;
3665 bool posix_open = False;
3666 bool new_file_created = False;
3667 bool first_open_attempt = true;
3668 NTSTATUS fsp_open = NT_STATUS_ACCESS_DENIED;
3669 mode_t new_unx_mode = (mode_t)0;
3670 mode_t unx_mode = (mode_t)0;
3671 int info;
3672 uint32_t existing_dos_attributes = 0;
3673 struct share_mode_lock *lck = NULL;
3674 uint32_t open_access_mask = access_mask;
3675 const struct smb2_lease_key *lease_key = NULL;
3676 int oplock_type = NO_OPLOCK;
3677 uint32_t granted_lease = 0;
3678 NTSTATUS status;
3679 SMB_STRUCT_STAT saved_stat = smb_fname->st;
3680 struct timespec old_write_time;
3681 bool setup_poll = false;
3682 bool ok;
3684 if (conn->printer) {
3686 * Printers are handled completely differently.
3687 * Most of the passed parameters are ignored.
3690 if (pinfo) {
3691 *pinfo = FILE_WAS_CREATED;
3694 DEBUG(10, ("open_file_ntcreate: printer open fname=%s\n",
3695 smb_fname_str_dbg(smb_fname)));
3697 if (!req) {
3698 DEBUG(0,("open_file_ntcreate: printer open without "
3699 "an SMB request!\n"));
3700 return NT_STATUS_INTERNAL_ERROR;
3703 return print_spool_open(fsp, smb_fname->base_name,
3704 req->vuid);
3707 if (new_dos_attributes & FILE_FLAG_POSIX_SEMANTICS) {
3708 posix_open = True;
3709 unx_mode = (mode_t)(new_dos_attributes & ~FILE_FLAG_POSIX_SEMANTICS);
3710 new_dos_attributes = 0;
3711 } else {
3712 /* Windows allows a new file to be created and
3713 silently removes a FILE_ATTRIBUTE_DIRECTORY
3714 sent by the client. Do the same. */
3716 new_dos_attributes &= ~FILE_ATTRIBUTE_DIRECTORY;
3718 /* We add FILE_ATTRIBUTE_ARCHIVE to this as this mode is only used if the file is
3719 * created new. */
3720 unx_mode = unix_mode(
3721 conn,
3722 new_dos_attributes | FILE_ATTRIBUTE_ARCHIVE,
3723 smb_fname,
3724 parent_dir_fname->fsp);
3727 DEBUG(10, ("open_file_ntcreate: fname=%s, dos_attrs=0x%x "
3728 "access_mask=0x%x share_access=0x%x "
3729 "create_disposition = 0x%x create_options=0x%x "
3730 "unix mode=0%o oplock_request=%d private_flags = 0x%x\n",
3731 smb_fname_str_dbg(smb_fname), new_dos_attributes,
3732 access_mask, share_access, create_disposition,
3733 create_options, (unsigned int)unx_mode, oplock_request,
3734 (unsigned int)private_flags));
3736 if (req == NULL) {
3737 /* Ensure req == NULL means INTERNAL_OPEN_ONLY */
3738 SMB_ASSERT(oplock_request == INTERNAL_OPEN_ONLY);
3739 } else {
3740 /* And req != NULL means no INTERNAL_OPEN_ONLY */
3741 SMB_ASSERT(((oplock_request & INTERNAL_OPEN_ONLY) == 0));
3745 * Only non-internal opens can be deferred at all
3748 if (req) {
3749 struct deferred_open_record *open_rec;
3750 if (get_deferred_open_message_state(req, NULL, &open_rec)) {
3752 /* If it was an async create retry, the file
3753 didn't exist. */
3755 if (is_deferred_open_async(open_rec)) {
3756 SET_STAT_INVALID(smb_fname->st);
3757 file_existed = false;
3760 /* Ensure we don't reprocess this message. */
3761 remove_deferred_open_message_smb(req->xconn, req->mid);
3763 first_open_attempt = false;
3767 if (!posix_open) {
3768 new_dos_attributes &= SAMBA_ATTRIBUTES_MASK;
3769 if (file_existed) {
3771 * Only use stored DOS attributes for checks
3772 * against requested attributes (below via
3773 * open_match_attributes()), cf bug #11992
3774 * for details. -slow
3776 uint32_t attr = 0;
3778 status = vfs_fget_dos_attributes(smb_fname->fsp, &attr);
3779 if (NT_STATUS_IS_OK(status)) {
3780 existing_dos_attributes = attr;
3785 /* ignore any oplock requests if oplocks are disabled */
3786 if (!lp_oplocks(SNUM(conn)) ||
3787 IS_VETO_OPLOCK_PATH(conn, smb_fname->base_name)) {
3788 /* Mask off everything except the private Samba bits. */
3789 oplock_request &= SAMBA_PRIVATE_OPLOCK_MASK;
3792 /* this is for OS/2 long file names - say we don't support them */
3793 if (req != NULL && !req->posix_pathnames &&
3794 strstr(smb_fname->base_name,".+,;=[].")) {
3795 /* OS/2 Workplace shell fix may be main code stream in a later
3796 * release. */
3797 DEBUG(5,("open_file_ntcreate: OS/2 long filenames are not "
3798 "supported.\n"));
3799 if (use_nt_status()) {
3800 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3802 return NT_STATUS_DOS(ERRDOS, ERRcannotopen);
3805 switch( create_disposition ) {
3806 case FILE_OPEN:
3807 /* If file exists open. If file doesn't exist error. */
3808 if (!file_existed) {
3809 DEBUG(5,("open_file_ntcreate: FILE_OPEN "
3810 "requested for file %s and file "
3811 "doesn't exist.\n",
3812 smb_fname_str_dbg(smb_fname)));
3813 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3815 break;
3817 case FILE_OVERWRITE:
3818 /* If file exists overwrite. If file doesn't exist
3819 * error. */
3820 if (!file_existed) {
3821 DEBUG(5,("open_file_ntcreate: FILE_OVERWRITE "
3822 "requested for file %s and file "
3823 "doesn't exist.\n",
3824 smb_fname_str_dbg(smb_fname) ));
3825 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3827 break;
3829 case FILE_CREATE:
3830 /* If file exists error. If file doesn't exist
3831 * create. */
3832 if (file_existed) {
3833 DEBUG(5,("open_file_ntcreate: FILE_CREATE "
3834 "requested for file %s and file "
3835 "already exists.\n",
3836 smb_fname_str_dbg(smb_fname)));
3837 if (S_ISDIR(smb_fname->st.st_ex_mode)) {
3838 return NT_STATUS_FILE_IS_A_DIRECTORY;
3840 return NT_STATUS_OBJECT_NAME_COLLISION;
3842 break;
3844 case FILE_SUPERSEDE:
3845 case FILE_OVERWRITE_IF:
3846 case FILE_OPEN_IF:
3847 break;
3848 default:
3849 return NT_STATUS_INVALID_PARAMETER;
3852 flags2 = disposition_to_open_flags(create_disposition);
3854 /* We only care about matching attributes on file exists and
3855 * overwrite. */
3857 if (!posix_open && file_existed &&
3858 ((create_disposition == FILE_OVERWRITE) ||
3859 (create_disposition == FILE_OVERWRITE_IF))) {
3860 if (!open_match_attributes(conn, existing_dos_attributes,
3861 new_dos_attributes,
3862 unx_mode, &new_unx_mode)) {
3863 DEBUG(5,("open_file_ntcreate: attributes mismatch "
3864 "for file %s (%x %x) (0%o, 0%o)\n",
3865 smb_fname_str_dbg(smb_fname),
3866 existing_dos_attributes,
3867 new_dos_attributes,
3868 (unsigned int)smb_fname->st.st_ex_mode,
3869 (unsigned int)unx_mode ));
3870 return NT_STATUS_ACCESS_DENIED;
3874 status = smbd_calculate_access_mask_fsp(parent_dir_fname->fsp,
3875 smb_fname->fsp,
3876 false,
3877 access_mask,
3878 &access_mask);
3879 if (!NT_STATUS_IS_OK(status)) {
3880 DBG_DEBUG("smbd_calculate_access_mask_fsp "
3881 "on file %s returned %s\n",
3882 smb_fname_str_dbg(smb_fname),
3883 nt_errstr(status));
3884 return status;
3887 open_access_mask = access_mask;
3889 if (flags2 & O_TRUNC) {
3890 open_access_mask |= FILE_WRITE_DATA; /* This will cause oplock breaks. */
3893 if (file_existed) {
3895 * stat opens on existing files don't get oplocks.
3896 * They can get leases.
3898 * Note that we check for stat open on the *open_access_mask*,
3899 * i.e. the access mask we actually used to do the open,
3900 * not the one the client asked for (which is in
3901 * fsp->access_mask). This is due to the fact that
3902 * FILE_OVERWRITE and FILE_OVERWRITE_IF add in O_TRUNC,
3903 * which adds FILE_WRITE_DATA to open_access_mask.
3905 if (is_oplock_stat_open(open_access_mask) && lease == NULL) {
3906 oplock_request = NO_OPLOCK;
3910 DEBUG(10, ("open_file_ntcreate: fname=%s, after mapping "
3911 "access_mask=0x%x\n", smb_fname_str_dbg(smb_fname),
3912 access_mask));
3915 * Note that we ignore the append flag as append does not
3916 * mean the same thing under DOS and Unix.
3919 flags = calculate_open_access_flags(access_mask, private_flags);
3922 * Currently we only look at FILE_WRITE_THROUGH for create options.
3925 #if defined(O_SYNC)
3926 if ((create_options & FILE_WRITE_THROUGH) && lp_strict_sync(SNUM(conn))) {
3927 flags2 |= O_SYNC;
3929 #endif /* O_SYNC */
3931 if (posix_open && (access_mask & FILE_APPEND_DATA)) {
3932 flags2 |= O_APPEND;
3935 if (!posix_open && !CAN_WRITE(conn)) {
3937 * We should really return a permission denied error if either
3938 * O_CREAT or O_TRUNC are set, but for compatibility with
3939 * older versions of Samba we just AND them out.
3941 flags2 &= ~(O_CREAT|O_TRUNC);
3945 * With kernel oplocks the open breaking an oplock
3946 * blocks until the oplock holder has given up the
3947 * oplock or closed the file. We prevent this by always
3948 * trying to open the file with O_NONBLOCK (see "man
3949 * fcntl" on Linux).
3951 * If a process that doesn't use the smbd open files
3952 * database or communication methods holds a kernel
3953 * oplock we must periodically poll for available open
3954 * using O_NONBLOCK.
3956 flags2 |= O_NONBLOCK;
3959 * Ensure we can't write on a read-only share or file.
3962 if (flags != O_RDONLY && file_existed &&
3963 (!CAN_WRITE(conn) || IS_DOS_READONLY(existing_dos_attributes))) {
3964 DEBUG(5,("open_file_ntcreate: write access requested for "
3965 "file %s on read only %s\n",
3966 smb_fname_str_dbg(smb_fname),
3967 !CAN_WRITE(conn) ? "share" : "file" ));
3968 return NT_STATUS_ACCESS_DENIED;
3971 if (VALID_STAT(smb_fname->st)) {
3973 * Only try and create a file id before open
3974 * for an existing file. For a file being created
3975 * this won't do anything useful until the file
3976 * exists and has a valid stat struct.
3978 fsp->file_id = vfs_file_id_from_sbuf(conn, &smb_fname->st);
3980 fh_set_private_options(fsp->fh, private_flags);
3981 fsp->access_mask = open_access_mask; /* We change this to the
3982 * requested access_mask after
3983 * the open is done. */
3984 if (posix_open) {
3985 fsp->posix_flags |= FSP_POSIX_FLAGS_ALL;
3988 if ((create_options & FILE_DELETE_ON_CLOSE) &&
3989 (flags2 & O_CREAT) &&
3990 !file_existed) {
3991 /* Delete on close semantics for new files. */
3992 status = can_set_delete_on_close(fsp,
3993 new_dos_attributes);
3994 if (!NT_STATUS_IS_OK(status)) {
3995 fd_close(fsp);
3996 return status;
4001 * Ensure we pay attention to default ACLs on directories if required.
4004 if ((flags2 & O_CREAT) && lp_inherit_acls(SNUM(conn)) &&
4005 (def_acl = directory_has_default_acl_fsp(parent_dir_fname->fsp)))
4007 unx_mode = (0777 & lp_create_mask(SNUM(conn)));
4010 DEBUG(4,("calling open_file with flags=0x%X flags2=0x%X mode=0%o, "
4011 "access_mask = 0x%x, open_access_mask = 0x%x\n",
4012 (unsigned int)flags, (unsigned int)flags2,
4013 (unsigned int)unx_mode, (unsigned int)access_mask,
4014 (unsigned int)open_access_mask));
4016 fsp_open = open_file(req,
4017 parent_dir_fname->fsp,
4018 smb_fname_atname,
4019 fsp,
4020 flags|flags2,
4021 unx_mode,
4022 access_mask,
4023 open_access_mask,
4024 private_flags,
4025 &new_file_created);
4026 if (NT_STATUS_EQUAL(fsp_open, NT_STATUS_NETWORK_BUSY)) {
4027 if (file_existed && S_ISFIFO(fsp->fsp_name->st.st_ex_mode)) {
4028 DEBUG(10, ("FIFO busy\n"));
4029 return NT_STATUS_NETWORK_BUSY;
4031 if (req == NULL) {
4032 DEBUG(10, ("Internal open busy\n"));
4033 return NT_STATUS_NETWORK_BUSY;
4036 * This handles the kernel oplock case:
4038 * the file has an active kernel oplock and the open() returned
4039 * EWOULDBLOCK/EAGAIN which maps to NETWORK_BUSY.
4041 * "Samba locking.tdb oplocks" are handled below after acquiring
4042 * the sharemode lock with get_share_mode_lock().
4044 setup_poll = true;
4047 if (NT_STATUS_EQUAL(fsp_open, NT_STATUS_RETRY)) {
4049 * EINTR from the open(2) syscall. Just setup a retry
4050 * in a bit. We can't use the sys_write() tight retry
4051 * loop here, as we might have to actually deal with
4052 * lease-break signals to avoid a deadlock.
4054 setup_poll = true;
4057 if (setup_poll) {
4059 * Retry once a second. If there's a share_mode_lock
4060 * around, also wait for it in case it was smbd
4061 * holding that kernel oplock that can quickly tell us
4062 * the oplock got removed.
4065 setup_poll_open(
4066 req,
4067 &fsp->file_id,
4068 timeval_set(OPLOCK_BREAK_TIMEOUT*2, 0),
4069 timeval_set(1, 0));
4071 return NT_STATUS_SHARING_VIOLATION;
4074 if (!NT_STATUS_IS_OK(fsp_open)) {
4075 bool wait_for_aio = NT_STATUS_EQUAL(
4076 fsp_open, NT_STATUS_MORE_PROCESSING_REQUIRED);
4077 if (wait_for_aio) {
4078 schedule_async_open(req);
4080 return fsp_open;
4083 if (new_file_created) {
4085 * As we atomically create using O_CREAT|O_EXCL,
4086 * then if new_file_created is true, then
4087 * file_existed *MUST* have been false (even
4088 * if the file was previously detected as being
4089 * there).
4091 file_existed = false;
4094 if (file_existed && !check_same_dev_ino(&saved_stat, &smb_fname->st)) {
4096 * The file did exist, but some other (local or NFS)
4097 * process either renamed/unlinked and re-created the
4098 * file with different dev/ino after we walked the path,
4099 * but before we did the open. We could retry the
4100 * open but it's a rare enough case it's easier to
4101 * just fail the open to prevent creating any problems
4102 * in the open file db having the wrong dev/ino key.
4104 fd_close(fsp);
4105 DBG_WARNING("file %s - dev/ino mismatch. "
4106 "Old (dev=%ju, ino=%ju). "
4107 "New (dev=%ju, ino=%ju). Failing open "
4108 "with NT_STATUS_ACCESS_DENIED.\n",
4109 smb_fname_str_dbg(smb_fname),
4110 (uintmax_t)saved_stat.st_ex_dev,
4111 (uintmax_t)saved_stat.st_ex_ino,
4112 (uintmax_t)smb_fname->st.st_ex_dev,
4113 (uintmax_t)smb_fname->st.st_ex_ino);
4114 return NT_STATUS_ACCESS_DENIED;
4117 old_write_time = smb_fname->st.st_ex_mtime;
4120 * Deal with the race condition where two smbd's detect the
4121 * file doesn't exist and do the create at the same time. One
4122 * of them will win and set a share mode, the other (ie. this
4123 * one) should check if the requested share mode for this
4124 * create is allowed.
4128 * Now the file exists and fsp is successfully opened,
4129 * fsp->dev and fsp->inode are valid and should replace the
4130 * dev=0,inode=0 from a non existent file. Spotted by
4131 * Nadav Danieli <nadavd@exanet.com>. JRA.
4134 lck = get_share_mode_lock(talloc_tos(), fsp->file_id,
4135 conn->connectpath,
4136 smb_fname, &old_write_time);
4138 if (lck == NULL) {
4139 DEBUG(0, ("open_file_ntcreate: Could not get share "
4140 "mode lock for %s\n",
4141 smb_fname_str_dbg(smb_fname)));
4142 fd_close(fsp);
4143 return NT_STATUS_SHARING_VIOLATION;
4146 /* Get the types we need to examine. */
4147 if (!validate_oplock_types(lck)) {
4148 smb_panic("validate_oplock_types failed");
4151 if (has_delete_on_close(lck, fsp->name_hash)) {
4152 TALLOC_FREE(lck);
4153 fd_close(fsp);
4154 return NT_STATUS_DELETE_PENDING;
4157 status = handle_share_mode_lease(
4158 fsp,
4159 lck,
4160 create_disposition,
4161 access_mask,
4162 share_access,
4163 oplock_request,
4164 lease,
4165 first_open_attempt,
4166 &oplock_type,
4167 &granted_lease);
4169 if (NT_STATUS_EQUAL(status, NT_STATUS_RETRY)) {
4170 schedule_defer_open(lck, fsp->file_id, req);
4171 TALLOC_FREE(lck);
4172 fd_close(fsp);
4173 return NT_STATUS_SHARING_VIOLATION;
4176 if (!NT_STATUS_IS_OK(status)) {
4177 TALLOC_FREE(lck);
4178 fd_close(fsp);
4179 return status;
4182 if (oplock_type == LEASE_OPLOCK) {
4183 lease_key = &lease->lease_key;
4186 share_mode_flags_restrict(lck, access_mask, share_access, 0);
4188 ok = set_share_mode(
4189 lck,
4190 fsp,
4191 get_current_uid(fsp->conn),
4192 req ? req->mid : 0,
4193 oplock_type,
4194 lease_key,
4195 share_access,
4196 access_mask);
4197 if (!ok) {
4198 TALLOC_FREE(lck);
4199 fd_close(fsp);
4200 return NT_STATUS_NO_MEMORY;
4203 if (oplock_type == LEASE_OPLOCK) {
4204 status = grant_fsp_lease(fsp, lck, lease, granted_lease);
4205 if (!NT_STATUS_IS_OK(status)) {
4206 del_share_mode(lck, fsp);
4207 TALLOC_FREE(lck);
4208 fd_close(fsp);
4209 return status;
4212 DBG_DEBUG("lease_state=%d\n", fsp->lease->lease.lease_state);
4215 fsp->oplock_type = oplock_type;
4217 if (fsp->oplock_type != NO_OPLOCK && fsp->oplock_type != LEASE_OPLOCK) {
4219 * Now ask for kernel oplocks
4220 * and cleanup on failure.
4222 status = set_file_oplock(fsp);
4223 if (!NT_STATUS_IS_OK(status)) {
4225 * Could not get the kernel oplock
4227 remove_share_oplock(lck, fsp);
4228 fsp->oplock_type = oplock_type = NO_OPLOCK;
4232 /* Should we atomically (to the client at least) truncate ? */
4233 if ((!new_file_created) &&
4234 (flags2 & O_TRUNC) &&
4235 (S_ISREG(fsp->fsp_name->st.st_ex_mode))) {
4236 int ret;
4238 ret = SMB_VFS_FTRUNCATE(fsp, 0);
4239 if (ret != 0) {
4240 status = map_nt_error_from_unix(errno);
4241 del_share_mode(lck, fsp);
4242 TALLOC_FREE(lck);
4243 fd_close(fsp);
4244 return status;
4246 notify_fname(fsp->conn, NOTIFY_ACTION_MODIFIED,
4247 FILE_NOTIFY_CHANGE_SIZE
4248 | FILE_NOTIFY_CHANGE_ATTRIBUTES,
4249 fsp->fsp_name->base_name);
4253 * We have the share entry *locked*.....
4256 /* Delete streams if create_disposition requires it */
4257 if (!new_file_created &&
4258 clear_ads(create_disposition) &&
4259 !fsp_is_alternate_stream(fsp)) {
4260 status = delete_all_streams(conn, smb_fname);
4261 if (!NT_STATUS_IS_OK(status)) {
4262 del_share_mode(lck, fsp);
4263 TALLOC_FREE(lck);
4264 fd_close(fsp);
4265 return status;
4269 if (!fsp->fsp_flags.is_pathref &&
4270 fsp_get_io_fd(fsp) != -1 &&
4271 lp_kernel_share_modes(SNUM(conn)))
4273 int ret;
4275 * Beware: streams implementing VFS modules may
4276 * implement streams in a way that fsp will have the
4277 * basefile open in the fsp fd, so lacking a distinct
4278 * fd for the stream the file-system sharemode will
4279 * apply on the basefile which is wrong. The actual
4280 * check is deferred to the VFS module implementing
4281 * the file-system sharemode call.
4283 ret = SMB_VFS_FILESYSTEM_SHAREMODE(fsp,
4284 share_access,
4285 access_mask);
4286 if (ret == -1){
4287 del_share_mode(lck, fsp);
4288 TALLOC_FREE(lck);
4289 fd_close(fsp);
4291 return NT_STATUS_SHARING_VIOLATION;
4294 fsp->fsp_flags.kernel_share_modes_taken = true;
4298 * At this point onwards, we can guarantee that the share entry
4299 * is locked, whether we created the file or not, and that the
4300 * deny mode is compatible with all current opens.
4304 * According to Samba4, SEC_FILE_READ_ATTRIBUTE is always granted,
4305 * but we don't have to store this - just ignore it on access check.
4307 if (conn->sconn->using_smb2) {
4309 * SMB2 doesn't return it (according to Microsoft tests).
4310 * Test Case: TestSuite_ScenarioNo009GrantedAccessTestS0
4311 * File created with access = 0x7 (Read, Write, Delete)
4312 * Query Info on file returns 0x87 (Read, Write, Delete, Read Attributes)
4314 fsp->access_mask = access_mask;
4315 } else {
4316 /* But SMB1 does. */
4317 fsp->access_mask = access_mask | FILE_READ_ATTRIBUTES;
4320 if (new_file_created) {
4321 info = FILE_WAS_CREATED;
4322 } else {
4323 if (flags2 & O_TRUNC) {
4324 info = FILE_WAS_OVERWRITTEN;
4325 } else {
4326 info = FILE_WAS_OPENED;
4330 if (pinfo) {
4331 *pinfo = info;
4334 /* Handle strange delete on close create semantics. */
4335 if (create_options & FILE_DELETE_ON_CLOSE) {
4336 if (!new_file_created) {
4337 status = can_set_delete_on_close(fsp,
4338 existing_dos_attributes);
4340 if (!NT_STATUS_IS_OK(status)) {
4341 /* Remember to delete the mode we just added. */
4342 del_share_mode(lck, fsp);
4343 TALLOC_FREE(lck);
4344 fd_close(fsp);
4345 return status;
4348 /* Note that here we set the *initial* delete on close flag,
4349 not the regular one. The magic gets handled in close. */
4350 fsp->fsp_flags.initial_delete_on_close = true;
4353 if (info != FILE_WAS_OPENED) {
4354 /* Overwritten files should be initially set as archive */
4355 if ((info == FILE_WAS_OVERWRITTEN && lp_map_archive(SNUM(conn))) ||
4356 lp_store_dos_attributes(SNUM(conn))) {
4357 (void)fdos_mode(fsp);
4358 if (!posix_open) {
4359 if (file_set_dosmode(conn, smb_fname,
4360 new_dos_attributes | FILE_ATTRIBUTE_ARCHIVE,
4361 parent_dir_fname, true) == 0) {
4362 unx_mode = smb_fname->st.st_ex_mode;
4368 /* Determine sparse flag. */
4369 if (posix_open) {
4370 /* POSIX opens are sparse by default. */
4371 fsp->fsp_flags.is_sparse = true;
4372 } else {
4373 fsp->fsp_flags.is_sparse =
4374 (existing_dos_attributes & FILE_ATTRIBUTE_SPARSE);
4378 * Take care of inherited ACLs on created files - if default ACL not
4379 * selected.
4382 if (!posix_open && new_file_created && !def_acl) {
4383 if (unx_mode != smb_fname->st.st_ex_mode) {
4384 int ret = SMB_VFS_FCHMOD(fsp, unx_mode);
4385 if (ret == -1) {
4386 DBG_INFO("failed to reset "
4387 "attributes of file %s to 0%o\n",
4388 smb_fname_str_dbg(smb_fname),
4389 (unsigned int)unx_mode);
4393 } else if (new_unx_mode) {
4395 * We only get here in the case of:
4397 * a). Not a POSIX open.
4398 * b). File already existed.
4399 * c). File was overwritten.
4400 * d). Requested DOS attributes didn't match
4401 * the DOS attributes on the existing file.
4403 * In that case new_unx_mode has been set
4404 * equal to the calculated mode (including
4405 * possible inheritance of the mode from the
4406 * containing directory).
4408 * Note this mode was calculated with the
4409 * DOS attribute FILE_ATTRIBUTE_ARCHIVE added,
4410 * so the mode change here is suitable for
4411 * an overwritten file.
4414 if (new_unx_mode != smb_fname->st.st_ex_mode) {
4415 int ret = SMB_VFS_FCHMOD(fsp, new_unx_mode);
4416 if (ret == -1) {
4417 DBG_INFO("failed to reset "
4418 "attributes of file %s to 0%o\n",
4419 smb_fname_str_dbg(smb_fname),
4420 (unsigned int)new_unx_mode);
4427 * Deal with other opens having a modified write time.
4429 struct timespec write_time = get_share_mode_write_time(lck);
4431 if (!is_omit_timespec(&write_time)) {
4432 update_stat_ex_mtime(&fsp->fsp_name->st, write_time);
4436 TALLOC_FREE(lck);
4438 return NT_STATUS_OK;
4441 static NTSTATUS mkdir_internal(connection_struct *conn,
4442 struct smb_filename *parent_dir_fname, /* parent. */
4443 struct smb_filename *smb_fname_atname, /* atname relative to parent. */
4444 struct smb_filename *smb_dname, /* full pathname from root of share. */
4445 uint32_t file_attributes,
4446 struct files_struct *fsp)
4448 const struct loadparm_substitution *lp_sub =
4449 loadparm_s3_global_substitution();
4450 mode_t mode;
4451 NTSTATUS status;
4452 bool posix_open = false;
4453 bool need_re_stat = false;
4454 uint32_t access_mask = SEC_DIR_ADD_SUBDIR;
4455 struct vfs_open_how how = { .flags = O_RDONLY|O_DIRECTORY, };
4456 int ret;
4458 if (!CAN_WRITE(conn) || (access_mask & ~(conn->share_access))) {
4459 DEBUG(5,("mkdir_internal: failing share access "
4460 "%s\n", lp_servicename(talloc_tos(), lp_sub, SNUM(conn))));
4461 return NT_STATUS_ACCESS_DENIED;
4464 if (file_attributes & FILE_FLAG_POSIX_SEMANTICS) {
4465 posix_open = true;
4466 mode = (mode_t)(file_attributes & ~FILE_FLAG_POSIX_SEMANTICS);
4467 } else {
4468 mode = unix_mode(conn,
4469 FILE_ATTRIBUTE_DIRECTORY,
4470 smb_dname,
4471 parent_dir_fname->fsp);
4474 status = check_parent_access_fsp(parent_dir_fname->fsp, access_mask);
4475 if(!NT_STATUS_IS_OK(status)) {
4476 DBG_INFO("check_parent_access_fsp "
4477 "on directory %s for path %s returned %s\n",
4478 smb_fname_str_dbg(parent_dir_fname),
4479 smb_dname->base_name,
4480 nt_errstr(status));
4481 return status;
4484 if (lp_inherit_acls(SNUM(conn))) {
4485 if (directory_has_default_acl_fsp(parent_dir_fname->fsp)) {
4486 mode = (0777 & lp_directory_mask(SNUM(conn)));
4490 ret = SMB_VFS_MKDIRAT(conn,
4491 parent_dir_fname->fsp,
4492 smb_fname_atname,
4493 mode);
4494 if (ret != 0) {
4495 return map_nt_error_from_unix(errno);
4499 * Make this a pathref fsp for now. open_directory() will reopen as a
4500 * full fsp.
4502 fsp->fsp_flags.is_pathref = true;
4504 status = fd_openat(parent_dir_fname->fsp, smb_fname_atname, fsp, &how);
4505 if (!NT_STATUS_IS_OK(status)) {
4506 return status;
4509 /* Ensure we're checking for a symlink here.... */
4510 /* We don't want to get caught by a symlink racer. */
4512 status = vfs_stat_fsp(fsp);
4513 if (!NT_STATUS_IS_OK(status)) {
4514 DEBUG(2, ("Could not stat directory '%s' just created: %s\n",
4515 smb_fname_str_dbg(smb_dname), nt_errstr(status)));
4516 return status;
4519 if (!S_ISDIR(smb_dname->st.st_ex_mode)) {
4520 DEBUG(0, ("Directory '%s' just created is not a directory !\n",
4521 smb_fname_str_dbg(smb_dname)));
4522 return NT_STATUS_NOT_A_DIRECTORY;
4525 if (lp_store_dos_attributes(SNUM(conn)) && !posix_open) {
4526 file_set_dosmode(conn,
4527 smb_dname,
4528 file_attributes | FILE_ATTRIBUTE_DIRECTORY,
4529 parent_dir_fname,
4530 true);
4533 if (lp_inherit_permissions(SNUM(conn))) {
4534 inherit_access_posix_acl(conn, parent_dir_fname->fsp,
4535 smb_dname, mode);
4536 need_re_stat = true;
4539 if (!posix_open) {
4541 * Check if high bits should have been set,
4542 * then (if bits are missing): add them.
4543 * Consider bits automagically set by UNIX, i.e. SGID bit from parent
4544 * dir.
4546 if ((mode & ~(S_IRWXU|S_IRWXG|S_IRWXO)) &&
4547 (mode & ~smb_dname->st.st_ex_mode)) {
4548 SMB_VFS_FCHMOD(fsp,
4549 (smb_dname->st.st_ex_mode |
4550 (mode & ~smb_dname->st.st_ex_mode)));
4551 need_re_stat = true;
4555 /* Change the owner if required. */
4556 if (lp_inherit_owner(SNUM(conn)) != INHERIT_OWNER_NO) {
4557 change_dir_owner_to_parent_fsp(parent_dir_fname->fsp,
4558 fsp);
4559 need_re_stat = true;
4562 if (need_re_stat) {
4563 status = vfs_stat_fsp(fsp);
4564 if (!NT_STATUS_IS_OK(status)) {
4565 DEBUG(2, ("Could not stat directory '%s' just created: %s\n",
4566 smb_fname_str_dbg(smb_dname), nt_errstr(status)));
4567 return status;
4571 notify_fname(conn, NOTIFY_ACTION_ADDED, FILE_NOTIFY_CHANGE_DIR_NAME,
4572 smb_dname->base_name);
4574 return NT_STATUS_OK;
4577 /****************************************************************************
4578 Open a directory from an NT SMB call.
4579 ****************************************************************************/
4581 static NTSTATUS open_directory(connection_struct *conn,
4582 struct smb_request *req,
4583 uint32_t access_mask,
4584 uint32_t share_access,
4585 uint32_t create_disposition,
4586 uint32_t create_options,
4587 uint32_t file_attributes,
4588 struct smb_filename *parent_dir_fname,
4589 struct smb_filename *smb_fname_atname,
4590 int *pinfo,
4591 struct files_struct *fsp)
4593 struct smb_filename *smb_dname = fsp->fsp_name;
4594 bool dir_existed = VALID_STAT(smb_dname->st);
4595 struct share_mode_lock *lck = NULL;
4596 int oplock_type = NO_OPLOCK;
4597 uint32_t granted_lease = 0;
4598 NTSTATUS status;
4599 struct timespec mtimespec;
4600 int info = 0;
4601 bool ok;
4602 uint32_t need_fd_access;
4604 if (is_ntfs_stream_smb_fname(smb_dname)) {
4605 DEBUG(2, ("open_directory: %s is a stream name!\n",
4606 smb_fname_str_dbg(smb_dname)));
4607 return NT_STATUS_NOT_A_DIRECTORY;
4610 if (!(file_attributes & FILE_FLAG_POSIX_SEMANTICS)) {
4611 /* Ensure we have a directory attribute. */
4612 file_attributes |= FILE_ATTRIBUTE_DIRECTORY;
4615 DBG_INFO("opening directory %s, access_mask = 0x%"PRIx32", "
4616 "share_access = 0x%"PRIx32" create_options = 0x%"PRIx32", "
4617 "create_disposition = 0x%"PRIx32", "
4618 "file_attributes = 0x%"PRIx32"\n",
4619 smb_fname_str_dbg(smb_dname),
4620 access_mask,
4621 share_access,
4622 create_options,
4623 create_disposition,
4624 file_attributes);
4626 status = smbd_calculate_access_mask_fsp(parent_dir_fname->fsp,
4627 smb_dname->fsp,
4628 false,
4629 access_mask,
4630 &access_mask);
4631 if (!NT_STATUS_IS_OK(status)) {
4632 DBG_DEBUG("smbd_calculate_access_mask_fsp "
4633 "on file %s returned %s\n",
4634 smb_fname_str_dbg(smb_dname),
4635 nt_errstr(status));
4636 return status;
4639 if ((access_mask & SEC_FLAG_SYSTEM_SECURITY) &&
4640 !security_token_has_privilege(get_current_nttok(conn),
4641 SEC_PRIV_SECURITY)) {
4642 DEBUG(10, ("open_directory: open on %s "
4643 "failed - SEC_FLAG_SYSTEM_SECURITY denied.\n",
4644 smb_fname_str_dbg(smb_dname)));
4645 return NT_STATUS_PRIVILEGE_NOT_HELD;
4648 switch( create_disposition ) {
4649 case FILE_OPEN:
4651 if (!dir_existed) {
4652 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
4655 info = FILE_WAS_OPENED;
4656 break;
4658 case FILE_CREATE:
4660 /* If directory exists error. If directory doesn't
4661 * exist create. */
4663 if (dir_existed) {
4664 status = NT_STATUS_OBJECT_NAME_COLLISION;
4665 DEBUG(2, ("open_directory: unable to create "
4666 "%s. Error was %s\n",
4667 smb_fname_str_dbg(smb_dname),
4668 nt_errstr(status)));
4669 return status;
4672 status = mkdir_internal(conn,
4673 parent_dir_fname,
4674 smb_fname_atname,
4675 smb_dname,
4676 file_attributes,
4677 fsp);
4679 if (!NT_STATUS_IS_OK(status)) {
4680 DEBUG(2, ("open_directory: unable to create "
4681 "%s. Error was %s\n",
4682 smb_fname_str_dbg(smb_dname),
4683 nt_errstr(status)));
4684 return status;
4687 info = FILE_WAS_CREATED;
4688 break;
4690 case FILE_OPEN_IF:
4692 * If directory exists open. If directory doesn't
4693 * exist create.
4696 if (dir_existed) {
4697 status = NT_STATUS_OK;
4698 info = FILE_WAS_OPENED;
4699 } else {
4700 status = mkdir_internal(conn,
4701 parent_dir_fname,
4702 smb_fname_atname,
4703 smb_dname,
4704 file_attributes,
4705 fsp);
4707 if (NT_STATUS_IS_OK(status)) {
4708 info = FILE_WAS_CREATED;
4709 } else {
4710 /* Cope with create race. */
4711 if (!NT_STATUS_EQUAL(status,
4712 NT_STATUS_OBJECT_NAME_COLLISION)) {
4713 DEBUG(2, ("open_directory: unable to create "
4714 "%s. Error was %s\n",
4715 smb_fname_str_dbg(smb_dname),
4716 nt_errstr(status)));
4717 return status;
4721 * If mkdir_internal() returned
4722 * NT_STATUS_OBJECT_NAME_COLLISION
4723 * we still must lstat the path.
4726 if (SMB_VFS_LSTAT(conn, smb_dname)
4727 == -1) {
4728 DEBUG(2, ("Could not stat "
4729 "directory '%s' just "
4730 "opened: %s\n",
4731 smb_fname_str_dbg(
4732 smb_dname),
4733 strerror(errno)));
4734 return map_nt_error_from_unix(
4735 errno);
4738 info = FILE_WAS_OPENED;
4742 break;
4744 case FILE_SUPERSEDE:
4745 case FILE_OVERWRITE:
4746 case FILE_OVERWRITE_IF:
4747 default:
4748 DEBUG(5,("open_directory: invalid create_disposition "
4749 "0x%x for directory %s\n",
4750 (unsigned int)create_disposition,
4751 smb_fname_str_dbg(smb_dname)));
4752 return NT_STATUS_INVALID_PARAMETER;
4755 if(!S_ISDIR(smb_dname->st.st_ex_mode)) {
4756 DEBUG(5,("open_directory: %s is not a directory !\n",
4757 smb_fname_str_dbg(smb_dname)));
4758 return NT_STATUS_NOT_A_DIRECTORY;
4762 * Setup the files_struct for it.
4765 fsp->file_id = vfs_file_id_from_sbuf(conn, &smb_dname->st);
4766 fsp->vuid = req ? req->vuid : UID_FIELD_INVALID;
4767 fsp->file_pid = req ? req->smbpid : 0;
4768 fsp->fsp_flags.can_lock = false;
4769 fsp->fsp_flags.can_read = false;
4770 fsp->fsp_flags.can_write = false;
4772 fh_set_private_options(fsp->fh, 0);
4774 * According to Samba4, SEC_FILE_READ_ATTRIBUTE is always granted,
4776 fsp->access_mask = access_mask | FILE_READ_ATTRIBUTES;
4777 fsp->print_file = NULL;
4778 fsp->fsp_flags.modified = false;
4779 fsp->oplock_type = NO_OPLOCK;
4780 fsp->sent_oplock_break = NO_BREAK_SENT;
4781 fsp->fsp_flags.is_directory = true;
4782 if (file_attributes & FILE_FLAG_POSIX_SEMANTICS) {
4783 fsp->posix_flags |= FSP_POSIX_FLAGS_ALL;
4786 /* Don't store old timestamps for directory
4787 handles in the internal database. We don't
4788 update them in there if new objects
4789 are created in the directory. Currently
4790 we only update timestamps on file writes.
4791 See bug #9870.
4793 mtimespec = make_omit_timespec();
4796 * Obviously for FILE_LIST_DIRECTORY we need to reopen to get an fd
4797 * usable for reading a directory. SMB2_FLUSH may be called on
4798 * directories opened with FILE_ADD_FILE and FILE_ADD_SUBDIRECTORY so
4799 * for those we need to reopen as well.
4801 need_fd_access =
4802 FILE_LIST_DIRECTORY |
4803 FILE_ADD_FILE |
4804 FILE_ADD_SUBDIRECTORY;
4806 if (access_mask & need_fd_access) {
4807 status = reopen_from_fsp(
4808 fsp->conn->cwd_fsp,
4809 fsp->fsp_name,
4810 fsp,
4811 O_RDONLY | O_DIRECTORY,
4813 NULL);
4814 if (!NT_STATUS_IS_OK(status)) {
4815 DBG_INFO("Could not open fd for [%s]: %s\n",
4816 smb_fname_str_dbg(smb_dname),
4817 nt_errstr(status));
4818 return status;
4822 status = vfs_stat_fsp(fsp);
4823 if (!NT_STATUS_IS_OK(status)) {
4824 fd_close(fsp);
4825 return status;
4828 if(!S_ISDIR(fsp->fsp_name->st.st_ex_mode)) {
4829 DEBUG(5,("open_directory: %s is not a directory !\n",
4830 smb_fname_str_dbg(smb_dname)));
4831 fd_close(fsp);
4832 return NT_STATUS_NOT_A_DIRECTORY;
4835 /* Ensure there was no race condition. We need to check
4836 * dev/inode but not permissions, as these can change
4837 * legitimately */
4838 if (!check_same_dev_ino(&smb_dname->st, &fsp->fsp_name->st)) {
4839 DEBUG(5,("open_directory: stat struct differs for "
4840 "directory %s.\n",
4841 smb_fname_str_dbg(smb_dname)));
4842 fd_close(fsp);
4843 return NT_STATUS_ACCESS_DENIED;
4846 if (info == FILE_WAS_OPENED) {
4847 status = smbd_check_access_rights_fsp(parent_dir_fname->fsp,
4848 fsp,
4849 false,
4850 access_mask);
4851 if (!NT_STATUS_IS_OK(status)) {
4852 DBG_DEBUG("smbd_check_access_rights_fsp on "
4853 "file %s failed with %s\n",
4854 fsp_str_dbg(fsp),
4855 nt_errstr(status));
4856 fd_close(fsp);
4857 return status;
4861 lck = get_share_mode_lock(talloc_tos(), fsp->file_id,
4862 conn->connectpath, smb_dname,
4863 &mtimespec);
4865 if (lck == NULL) {
4866 DEBUG(0, ("open_directory: Could not get share mode lock for "
4867 "%s\n", smb_fname_str_dbg(smb_dname)));
4868 fd_close(fsp);
4869 return NT_STATUS_SHARING_VIOLATION;
4872 if (has_delete_on_close(lck, fsp->name_hash)) {
4873 TALLOC_FREE(lck);
4874 fd_close(fsp);
4875 return NT_STATUS_DELETE_PENDING;
4878 status = handle_share_mode_lease(
4879 fsp,
4880 lck,
4881 create_disposition,
4882 access_mask,
4883 share_access,
4884 NO_OPLOCK,
4885 NULL, /* lease */
4886 true, /* first_open_attempt */
4887 &oplock_type,
4888 &granted_lease);
4889 if (!NT_STATUS_IS_OK(status)) {
4890 TALLOC_FREE(lck);
4891 fd_close(fsp);
4892 return status;
4895 share_mode_flags_restrict(lck, access_mask, share_access, 0);
4897 ok = set_share_mode(
4898 lck,
4899 fsp,
4900 get_current_uid(conn),
4901 req ? req->mid : 0,
4902 oplock_type,
4903 NULL,
4904 share_access,
4905 fsp->access_mask);
4906 if (!ok) {
4907 TALLOC_FREE(lck);
4908 fd_close(fsp);
4909 return NT_STATUS_NO_MEMORY;
4912 /* For directories the delete on close bit at open time seems
4913 always to be honored on close... See test 19 in Samba4 BASE-DELETE. */
4914 if (create_options & FILE_DELETE_ON_CLOSE) {
4915 status = can_set_delete_on_close(fsp, 0);
4916 if (!NT_STATUS_IS_OK(status) && !NT_STATUS_EQUAL(status, NT_STATUS_DIRECTORY_NOT_EMPTY)) {
4917 del_share_mode(lck, fsp);
4918 TALLOC_FREE(lck);
4919 fd_close(fsp);
4920 return status;
4923 if (NT_STATUS_IS_OK(status)) {
4924 /* Note that here we set the *initial* delete on close flag,
4925 not the regular one. The magic gets handled in close. */
4926 fsp->fsp_flags.initial_delete_on_close = true;
4932 * Deal with other opens having a modified write time. Is this
4933 * possible for directories?
4935 struct timespec write_time = get_share_mode_write_time(lck);
4937 if (!is_omit_timespec(&write_time)) {
4938 update_stat_ex_mtime(&fsp->fsp_name->st, write_time);
4942 TALLOC_FREE(lck);
4944 if (pinfo) {
4945 *pinfo = info;
4948 return NT_STATUS_OK;
4951 NTSTATUS create_directory(connection_struct *conn,
4952 struct smb_request *req,
4953 struct files_struct *dirfsp,
4954 struct smb_filename *smb_dname)
4956 NTSTATUS status;
4957 files_struct *fsp;
4959 status = SMB_VFS_CREATE_FILE(
4960 conn, /* conn */
4961 req, /* req */
4962 dirfsp, /* dirfsp */
4963 smb_dname, /* fname */
4964 FILE_READ_ATTRIBUTES, /* access_mask */
4965 FILE_SHARE_NONE, /* share_access */
4966 FILE_CREATE, /* create_disposition*/
4967 FILE_DIRECTORY_FILE, /* create_options */
4968 FILE_ATTRIBUTE_DIRECTORY, /* file_attributes */
4969 0, /* oplock_request */
4970 NULL, /* lease */
4971 0, /* allocation_size */
4972 0, /* private_flags */
4973 NULL, /* sd */
4974 NULL, /* ea_list */
4975 &fsp, /* result */
4976 NULL, /* pinfo */
4977 NULL, NULL); /* create context */
4979 if (NT_STATUS_IS_OK(status)) {
4980 close_file_free(req, &fsp, NORMAL_CLOSE);
4983 return status;
4986 /****************************************************************************
4987 Receive notification that one of our open files has been renamed by another
4988 smbd process.
4989 ****************************************************************************/
4991 void msg_file_was_renamed(struct messaging_context *msg_ctx,
4992 void *private_data,
4993 uint32_t msg_type,
4994 struct server_id src,
4995 DATA_BLOB *data)
4997 struct file_rename_message *msg = NULL;
4998 enum ndr_err_code ndr_err;
4999 files_struct *fsp;
5000 struct smb_filename *smb_fname = NULL;
5001 struct smbd_server_connection *sconn =
5002 talloc_get_type_abort(private_data,
5003 struct smbd_server_connection);
5005 msg = talloc(talloc_tos(), struct file_rename_message);
5006 if (msg == NULL) {
5007 DBG_WARNING("talloc failed\n");
5008 return;
5011 ndr_err = ndr_pull_struct_blob_all(
5012 data,
5013 msg,
5014 msg,
5015 (ndr_pull_flags_fn_t)ndr_pull_file_rename_message);
5016 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
5017 DBG_DEBUG("ndr_pull_oplock_break_message failed: %s\n",
5018 ndr_errstr(ndr_err));
5019 goto out;
5021 if (DEBUGLEVEL >= 10) {
5022 struct server_id_buf buf;
5023 DBG_DEBUG("Got rename message from %s\n",
5024 server_id_str_buf(src, &buf));
5025 NDR_PRINT_DEBUG(file_rename_message, msg);
5028 /* stream_name must always be NULL if there is no stream. */
5029 if ((msg->stream_name != NULL) && (msg->stream_name[0] == '\0')) {
5030 msg->stream_name = NULL;
5033 smb_fname = synthetic_smb_fname(msg,
5034 msg->base_name,
5035 msg->stream_name,
5036 NULL,
5039 if (smb_fname == NULL) {
5040 DBG_DEBUG("synthetic_smb_fname failed\n");
5041 goto out;
5044 fsp = file_find_dif(sconn, msg->id, msg->share_file_id);
5045 if (fsp == NULL) {
5046 DBG_DEBUG("fsp not found\n");
5047 goto out;
5050 if (strcmp(fsp->conn->connectpath, msg->servicepath) == 0) {
5051 SMB_STRUCT_STAT fsp_orig_sbuf;
5052 NTSTATUS status;
5053 DBG_DEBUG("renaming file %s from %s -> %s\n",
5054 fsp_fnum_dbg(fsp),
5055 fsp_str_dbg(fsp),
5056 smb_fname_str_dbg(smb_fname));
5059 * The incoming smb_fname here has an
5060 * invalid stat struct from synthetic_smb_fname()
5061 * above.
5062 * Preserve the existing stat from the
5063 * open fsp after fsp_set_smb_fname()
5064 * overwrites with the invalid stat.
5066 * (We could just copy this into
5067 * smb_fname->st, but keep this code
5068 * identical to the fix in rename_open_files()
5069 * for clarity.
5071 * We will do an fstat before returning
5072 * any of this metadata to the client anyway.
5074 fsp_orig_sbuf = fsp->fsp_name->st;
5075 status = fsp_set_smb_fname(fsp, smb_fname);
5076 if (!NT_STATUS_IS_OK(status)) {
5077 DBG_DEBUG("fsp_set_smb_fname failed: %s\n",
5078 nt_errstr(status));
5080 fsp->fsp_name->st = fsp_orig_sbuf;
5081 } else {
5082 /* TODO. JRA. */
5084 * Now we have the complete path we can work out if
5085 * this is actually within this share and adjust
5086 * newname accordingly.
5088 DBG_DEBUG("share mismatch (sharepath %s not sharepath %s) "
5089 "%s from %s -> %s\n",
5090 fsp->conn->connectpath,
5091 msg->servicepath,
5092 fsp_fnum_dbg(fsp),
5093 fsp_str_dbg(fsp),
5094 smb_fname_str_dbg(smb_fname));
5096 out:
5097 TALLOC_FREE(msg);
5101 * If a main file is opened for delete, all streams need to be checked for
5102 * !FILE_SHARE_DELETE. Do this by opening with DELETE_ACCESS.
5103 * If that works, delete them all by setting the delete on close and close.
5106 static NTSTATUS open_streams_for_delete(connection_struct *conn,
5107 const struct smb_filename *smb_fname)
5109 struct stream_struct *stream_info = NULL;
5110 files_struct **streams = NULL;
5111 int j;
5112 unsigned int i, num_streams = 0;
5113 TALLOC_CTX *frame = talloc_stackframe();
5114 const struct smb_filename *pathref = NULL;
5115 NTSTATUS status;
5117 if (smb_fname->fsp == NULL) {
5118 struct smb_filename *tmp = NULL;
5119 status = synthetic_pathref(frame,
5120 conn->cwd_fsp,
5121 smb_fname->base_name,
5122 NULL,
5123 NULL,
5124 smb_fname->twrp,
5125 smb_fname->flags,
5126 &tmp);
5127 if (!NT_STATUS_IS_OK(status)) {
5128 if (NT_STATUS_EQUAL(status, NT_STATUS_NOT_IMPLEMENTED)
5129 || NT_STATUS_EQUAL(status,
5130 NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
5131 DBG_DEBUG("no streams around\n");
5132 TALLOC_FREE(frame);
5133 return NT_STATUS_OK;
5135 DBG_DEBUG("synthetic_pathref failed: %s\n",
5136 nt_errstr(status));
5137 goto fail;
5139 pathref = tmp;
5140 } else {
5141 pathref = smb_fname;
5143 status = vfs_fstreaminfo(pathref->fsp, talloc_tos(),
5144 &num_streams, &stream_info);
5146 if (NT_STATUS_EQUAL(status, NT_STATUS_NOT_IMPLEMENTED)
5147 || NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
5148 DEBUG(10, ("no streams around\n"));
5149 TALLOC_FREE(frame);
5150 return NT_STATUS_OK;
5153 if (!NT_STATUS_IS_OK(status)) {
5154 DEBUG(10, ("vfs_fstreaminfo failed: %s\n",
5155 nt_errstr(status)));
5156 goto fail;
5159 DEBUG(10, ("open_streams_for_delete found %d streams\n",
5160 num_streams));
5162 if (num_streams == 0) {
5163 TALLOC_FREE(frame);
5164 return NT_STATUS_OK;
5167 streams = talloc_array(talloc_tos(), files_struct *, num_streams);
5168 if (streams == NULL) {
5169 DEBUG(0, ("talloc failed\n"));
5170 status = NT_STATUS_NO_MEMORY;
5171 goto fail;
5174 for (i=0; i<num_streams; i++) {
5175 struct smb_filename *smb_fname_cp;
5177 if (strequal(stream_info[i].name, "::$DATA")) {
5178 streams[i] = NULL;
5179 continue;
5182 smb_fname_cp = synthetic_smb_fname(talloc_tos(),
5183 smb_fname->base_name,
5184 stream_info[i].name,
5185 NULL,
5186 smb_fname->twrp,
5187 (smb_fname->flags &
5188 ~SMB_FILENAME_POSIX_PATH));
5189 if (smb_fname_cp == NULL) {
5190 status = NT_STATUS_NO_MEMORY;
5191 goto fail;
5194 status = openat_pathref_fsp(conn->cwd_fsp, smb_fname_cp);
5195 if (!NT_STATUS_IS_OK(status)) {
5196 DBG_DEBUG("Unable to open stream [%s]: %s\n",
5197 smb_fname_str_dbg(smb_fname_cp),
5198 nt_errstr(status));
5199 TALLOC_FREE(smb_fname_cp);
5200 break;
5203 status = SMB_VFS_CREATE_FILE(
5204 conn, /* conn */
5205 NULL, /* req */
5206 NULL, /* dirfsp */
5207 smb_fname_cp, /* fname */
5208 DELETE_ACCESS, /* access_mask */
5209 (FILE_SHARE_READ | /* share_access */
5210 FILE_SHARE_WRITE | FILE_SHARE_DELETE),
5211 FILE_OPEN, /* create_disposition*/
5212 0, /* create_options */
5213 FILE_ATTRIBUTE_NORMAL, /* file_attributes */
5214 0, /* oplock_request */
5215 NULL, /* lease */
5216 0, /* allocation_size */
5217 0, /* private_flags */
5218 NULL, /* sd */
5219 NULL, /* ea_list */
5220 &streams[i], /* result */
5221 NULL, /* pinfo */
5222 NULL, NULL); /* create context */
5224 if (!NT_STATUS_IS_OK(status)) {
5225 DEBUG(10, ("Could not open stream %s: %s\n",
5226 smb_fname_str_dbg(smb_fname_cp),
5227 nt_errstr(status)));
5229 TALLOC_FREE(smb_fname_cp);
5230 break;
5232 TALLOC_FREE(smb_fname_cp);
5236 * don't touch the variable "status" beyond this point :-)
5239 for (j = i-1 ; j >= 0; j--) {
5240 if (streams[j] == NULL) {
5241 continue;
5244 DEBUG(10, ("Closing stream # %d, %s\n", j,
5245 fsp_str_dbg(streams[j])));
5246 close_file_free(NULL, &streams[j], NORMAL_CLOSE);
5249 fail:
5250 TALLOC_FREE(frame);
5251 return status;
5254 /*********************************************************************
5255 Create a default ACL by inheriting from the parent. If no inheritance
5256 from the parent available, don't set anything. This will leave the actual
5257 permissions the new file or directory already got from the filesystem
5258 as the NT ACL when read.
5259 *********************************************************************/
5261 static NTSTATUS inherit_new_acl(files_struct *dirfsp, files_struct *fsp)
5263 TALLOC_CTX *frame = talloc_stackframe();
5264 struct security_descriptor *parent_desc = NULL;
5265 NTSTATUS status = NT_STATUS_OK;
5266 struct security_descriptor *psd = NULL;
5267 const struct dom_sid *owner_sid = NULL;
5268 const struct dom_sid *group_sid = NULL;
5269 uint32_t security_info_sent = (SECINFO_OWNER | SECINFO_GROUP | SECINFO_DACL);
5270 struct security_token *token = fsp->conn->session_info->security_token;
5271 bool inherit_owner =
5272 (lp_inherit_owner(SNUM(fsp->conn)) == INHERIT_OWNER_WINDOWS_AND_UNIX);
5273 bool inheritable_components = false;
5274 bool try_builtin_administrators = false;
5275 const struct dom_sid *BA_U_sid = NULL;
5276 const struct dom_sid *BA_G_sid = NULL;
5277 bool try_system = false;
5278 const struct dom_sid *SY_U_sid = NULL;
5279 const struct dom_sid *SY_G_sid = NULL;
5280 size_t size = 0;
5281 bool ok;
5283 status = SMB_VFS_FGET_NT_ACL(dirfsp,
5284 (SECINFO_OWNER | SECINFO_GROUP | SECINFO_DACL),
5285 frame,
5286 &parent_desc);
5287 if (!NT_STATUS_IS_OK(status)) {
5288 TALLOC_FREE(frame);
5289 return status;
5292 inheritable_components = sd_has_inheritable_components(parent_desc,
5293 fsp->fsp_flags.is_directory);
5295 if (!inheritable_components && !inherit_owner) {
5296 TALLOC_FREE(frame);
5297 /* Nothing to inherit and not setting owner. */
5298 return NT_STATUS_OK;
5301 /* Create an inherited descriptor from the parent. */
5303 if (DEBUGLEVEL >= 10) {
5304 DEBUG(10,("inherit_new_acl: parent acl for %s is:\n",
5305 fsp_str_dbg(fsp) ));
5306 NDR_PRINT_DEBUG(security_descriptor, parent_desc);
5309 /* Inherit from parent descriptor if "inherit owner" set. */
5310 if (inherit_owner) {
5311 owner_sid = parent_desc->owner_sid;
5312 group_sid = parent_desc->group_sid;
5315 if (owner_sid == NULL) {
5316 if (security_token_has_builtin_administrators(token)) {
5317 try_builtin_administrators = true;
5318 } else if (security_token_is_system(token)) {
5319 try_builtin_administrators = true;
5320 try_system = true;
5324 if (group_sid == NULL &&
5325 token->num_sids == PRIMARY_GROUP_SID_INDEX)
5327 if (security_token_is_system(token)) {
5328 try_builtin_administrators = true;
5329 try_system = true;
5333 if (try_builtin_administrators) {
5334 struct unixid ids = { .id = 0 };
5336 ok = sids_to_unixids(&global_sid_Builtin_Administrators, 1, &ids);
5337 if (ok) {
5338 switch (ids.type) {
5339 case ID_TYPE_BOTH:
5340 BA_U_sid = &global_sid_Builtin_Administrators;
5341 BA_G_sid = &global_sid_Builtin_Administrators;
5342 break;
5343 case ID_TYPE_UID:
5344 BA_U_sid = &global_sid_Builtin_Administrators;
5345 break;
5346 case ID_TYPE_GID:
5347 BA_G_sid = &global_sid_Builtin_Administrators;
5348 break;
5349 default:
5350 break;
5355 if (try_system) {
5356 struct unixid ids = { .id = 0 };
5358 ok = sids_to_unixids(&global_sid_System, 1, &ids);
5359 if (ok) {
5360 switch (ids.type) {
5361 case ID_TYPE_BOTH:
5362 SY_U_sid = &global_sid_System;
5363 SY_G_sid = &global_sid_System;
5364 break;
5365 case ID_TYPE_UID:
5366 SY_U_sid = &global_sid_System;
5367 break;
5368 case ID_TYPE_GID:
5369 SY_G_sid = &global_sid_System;
5370 break;
5371 default:
5372 break;
5377 if (owner_sid == NULL) {
5378 owner_sid = BA_U_sid;
5381 if (owner_sid == NULL) {
5382 owner_sid = SY_U_sid;
5385 if (group_sid == NULL) {
5386 group_sid = SY_G_sid;
5389 if (try_system && group_sid == NULL) {
5390 group_sid = BA_G_sid;
5393 if (owner_sid == NULL) {
5394 owner_sid = &token->sids[PRIMARY_USER_SID_INDEX];
5396 if (group_sid == NULL) {
5397 if (token->num_sids == PRIMARY_GROUP_SID_INDEX) {
5398 group_sid = &token->sids[PRIMARY_USER_SID_INDEX];
5399 } else {
5400 group_sid = &token->sids[PRIMARY_GROUP_SID_INDEX];
5404 status = se_create_child_secdesc(frame,
5405 &psd,
5406 &size,
5407 parent_desc,
5408 owner_sid,
5409 group_sid,
5410 fsp->fsp_flags.is_directory);
5411 if (!NT_STATUS_IS_OK(status)) {
5412 TALLOC_FREE(frame);
5413 return status;
5416 /* If inheritable_components == false,
5417 se_create_child_secdesc()
5418 creates a security descriptor with a NULL dacl
5419 entry, but with SEC_DESC_DACL_PRESENT. We need
5420 to remove that flag. */
5422 if (!inheritable_components) {
5423 security_info_sent &= ~SECINFO_DACL;
5424 psd->type &= ~SEC_DESC_DACL_PRESENT;
5427 if (DEBUGLEVEL >= 10) {
5428 DEBUG(10,("inherit_new_acl: child acl for %s is:\n",
5429 fsp_str_dbg(fsp) ));
5430 NDR_PRINT_DEBUG(security_descriptor, psd);
5433 if (inherit_owner) {
5434 /* We need to be root to force this. */
5435 become_root();
5437 status = SMB_VFS_FSET_NT_ACL(metadata_fsp(fsp),
5438 security_info_sent,
5439 psd);
5440 if (inherit_owner) {
5441 unbecome_root();
5443 TALLOC_FREE(frame);
5444 return status;
5448 * If we already have a lease, it must match the new file id. [MS-SMB2]
5449 * 3.3.5.9.8 speaks about INVALID_PARAMETER if an already used lease key is
5450 * used for a different file name.
5453 struct lease_match_state {
5454 /* Input parameters. */
5455 TALLOC_CTX *mem_ctx;
5456 const char *servicepath;
5457 const struct smb_filename *fname;
5458 bool file_existed;
5459 struct file_id id;
5460 /* Return parameters. */
5461 uint32_t num_file_ids;
5462 struct file_id *ids;
5463 NTSTATUS match_status;
5466 /*************************************************************
5467 File doesn't exist but this lease key+guid is already in use.
5469 This is only allowable in the dynamic share case where the
5470 service path must be different.
5472 There is a small race condition here in the multi-connection
5473 case where a client sends two create calls on different connections,
5474 where the file doesn't exist and one smbd creates the leases_db
5475 entry first, but this will get fixed by the multichannel cleanup
5476 when all identical client_guids get handled by a single smbd.
5477 **************************************************************/
5479 static void lease_match_parser_new_file(
5480 uint32_t num_files,
5481 const struct leases_db_file *files,
5482 struct lease_match_state *state)
5484 uint32_t i;
5486 for (i = 0; i < num_files; i++) {
5487 const struct leases_db_file *f = &files[i];
5488 if (strequal(state->servicepath, f->servicepath)) {
5489 state->match_status = NT_STATUS_INVALID_PARAMETER;
5490 return;
5494 /* Dynamic share case. Break leases on all other files. */
5495 state->match_status = leases_db_copy_file_ids(state->mem_ctx,
5496 num_files,
5497 files,
5498 &state->ids);
5499 if (!NT_STATUS_IS_OK(state->match_status)) {
5500 return;
5503 state->num_file_ids = num_files;
5504 state->match_status = NT_STATUS_OPLOCK_NOT_GRANTED;
5505 return;
5508 static void lease_match_parser(
5509 uint32_t num_files,
5510 const struct leases_db_file *files,
5511 void *private_data)
5513 struct lease_match_state *state =
5514 (struct lease_match_state *)private_data;
5515 uint32_t i;
5517 if (!state->file_existed) {
5519 * Deal with name mismatch or
5520 * possible dynamic share case separately
5521 * to make code clearer.
5523 lease_match_parser_new_file(num_files,
5524 files,
5525 state);
5526 return;
5529 /* File existed. */
5530 state->match_status = NT_STATUS_OK;
5532 for (i = 0; i < num_files; i++) {
5533 const struct leases_db_file *f = &files[i];
5535 /* Everything should be the same. */
5536 if (!file_id_equal(&state->id, &f->id)) {
5538 * The client asked for a lease on a
5539 * file that doesn't match the file_id
5540 * in the database.
5542 * Maybe this is a dynamic share, i.e.
5543 * a share where the servicepath is
5544 * different for different users (e.g.
5545 * the [HOMES] share.
5547 * If the servicepath is different, but the requested
5548 * file name + stream name is the same then this is
5549 * a dynamic share, the client is using the same share
5550 * name and doesn't know that the underlying servicepath
5551 * is different. It was expecting a lease on the
5552 * same file. Return NT_STATUS_OPLOCK_NOT_GRANTED
5553 * to break leases
5555 * Otherwise the client has messed up, or is
5556 * testing our error codes, so return
5557 * NT_STATUS_INVALID_PARAMETER.
5559 if (!strequal(f->servicepath, state->servicepath) &&
5560 strequal(f->base_name, state->fname->base_name) &&
5561 strequal(f->stream_name, state->fname->stream_name))
5564 * Name is the same but servicepath is
5565 * different, dynamic share. Break leases.
5567 state->match_status =
5568 NT_STATUS_OPLOCK_NOT_GRANTED;
5569 } else {
5570 state->match_status =
5571 NT_STATUS_INVALID_PARAMETER;
5573 break;
5575 if (!strequal(f->servicepath, state->servicepath)) {
5576 state->match_status = NT_STATUS_INVALID_PARAMETER;
5577 break;
5579 if (!strequal(f->base_name, state->fname->base_name)) {
5580 state->match_status = NT_STATUS_INVALID_PARAMETER;
5581 break;
5583 if (!strequal(f->stream_name, state->fname->stream_name)) {
5584 state->match_status = NT_STATUS_INVALID_PARAMETER;
5585 break;
5589 if (NT_STATUS_IS_OK(state->match_status)) {
5591 * Common case - just opening another handle on a
5592 * file on a non-dynamic share.
5594 return;
5597 if (NT_STATUS_EQUAL(state->match_status, NT_STATUS_INVALID_PARAMETER)) {
5598 /* Mismatched path. Error back to client. */
5599 return;
5603 * File id mismatch. Dynamic share case NT_STATUS_OPLOCK_NOT_GRANTED.
5604 * Don't allow leases.
5607 state->match_status = leases_db_copy_file_ids(state->mem_ctx,
5608 num_files,
5609 files,
5610 &state->ids);
5611 if (!NT_STATUS_IS_OK(state->match_status)) {
5612 return;
5615 state->num_file_ids = num_files;
5616 state->match_status = NT_STATUS_OPLOCK_NOT_GRANTED;
5617 return;
5620 struct lease_match_break_state {
5621 struct messaging_context *msg_ctx;
5622 const struct smb2_lease_key *lease_key;
5623 struct file_id id;
5625 bool found_lease;
5626 uint16_t version;
5627 uint16_t epoch;
5630 static bool lease_match_break_fn(
5631 struct share_mode_entry *e,
5632 void *private_data)
5634 struct lease_match_break_state *state = private_data;
5635 bool stale, equal;
5636 uint32_t e_lease_type = SMB2_LEASE_NONE;
5637 NTSTATUS status;
5639 stale = share_entry_stale_pid(e);
5640 if (stale) {
5641 return false;
5644 equal = smb2_lease_key_equal(&e->lease_key, state->lease_key);
5645 if (!equal) {
5646 return false;
5649 status = leases_db_get(
5650 &e->client_guid,
5651 &e->lease_key,
5652 &state->id,
5653 &e_lease_type, /* current_state */
5654 NULL, /* breaking */
5655 NULL, /* breaking_to_requested */
5656 NULL, /* breaking_to_required */
5657 &state->version, /* lease_version */
5658 &state->epoch); /* epoch */
5659 if (NT_STATUS_IS_OK(status)) {
5660 state->found_lease = true;
5661 } else {
5662 DBG_WARNING("Could not find version/epoch: %s\n",
5663 nt_errstr(status));
5664 return false;
5667 if (e_lease_type == SMB2_LEASE_NONE) {
5668 return false;
5670 send_break_message(state->msg_ctx, &state->id, e, SMB2_LEASE_NONE);
5673 * Windows 7 and 8 lease clients are broken in that they will
5674 * not respond to lease break requests whilst waiting for an
5675 * outstanding open request on that lease handle on the same
5676 * TCP connection, due to holding an internal inode lock.
5678 * This means we can't reschedule ourselves here, but must
5679 * return from the create.
5681 * Work around:
5683 * Send the breaks and then return SMB2_LEASE_NONE in the
5684 * lease handle to cause them to acknowledge the lease
5685 * break. Consultation with Microsoft engineering confirmed
5686 * this approach is safe.
5689 return false;
5692 static void lease_match_fid_fn(struct share_mode_lock *lck,
5693 void *private_data)
5695 bool ok;
5697 ok = share_mode_forall_leases(lck, lease_match_break_fn, private_data);
5698 if (!ok) {
5699 DBG_DEBUG("share_mode_forall_leases failed\n");
5703 static NTSTATUS lease_match(connection_struct *conn,
5704 struct smb_request *req,
5705 const struct smb2_lease_key *lease_key,
5706 const char *servicepath,
5707 const struct smb_filename *fname,
5708 uint16_t *p_version,
5709 uint16_t *p_epoch)
5711 struct smbd_server_connection *sconn = req->sconn;
5712 TALLOC_CTX *tos = talloc_tos();
5713 struct lease_match_state state = {
5714 .mem_ctx = tos,
5715 .servicepath = servicepath,
5716 .fname = fname,
5717 .match_status = NT_STATUS_OK
5719 uint32_t i;
5720 NTSTATUS status;
5722 state.file_existed = VALID_STAT(fname->st);
5723 if (state.file_existed) {
5724 state.id = vfs_file_id_from_sbuf(conn, &fname->st);
5727 status = leases_db_parse(&sconn->client->global->client_guid,
5728 lease_key, lease_match_parser, &state);
5729 if (!NT_STATUS_IS_OK(status)) {
5731 * Not found or error means okay: We can make the lease pass
5733 return NT_STATUS_OK;
5735 if (!NT_STATUS_EQUAL(state.match_status, NT_STATUS_OPLOCK_NOT_GRANTED)) {
5737 * Anything but NT_STATUS_OPLOCK_NOT_GRANTED, let the caller
5738 * deal with it.
5740 return state.match_status;
5743 /* We have to break all existing leases. */
5744 for (i = 0; i < state.num_file_ids; i++) {
5745 struct lease_match_break_state break_state = {
5746 .msg_ctx = conn->sconn->msg_ctx,
5747 .lease_key = lease_key,
5750 if (file_id_equal(&state.ids[i], &state.id)) {
5751 /* Don't need to break our own file. */
5752 continue;
5755 break_state.id = state.ids[i];
5757 status = share_mode_do_locked_vfs_denied(break_state.id,
5758 lease_match_fid_fn,
5759 &break_state);
5760 if (!NT_STATUS_IS_OK(status)) {
5761 /* Race condition - file already closed. */
5762 continue;
5765 if (break_state.found_lease) {
5766 *p_version = break_state.version;
5767 *p_epoch = break_state.epoch;
5771 * Ensure we don't grant anything more so we
5772 * never upgrade.
5774 return NT_STATUS_OPLOCK_NOT_GRANTED;
5778 * Wrapper around open_file_ntcreate and open_directory
5781 static NTSTATUS create_file_unixpath(connection_struct *conn,
5782 struct smb_request *req,
5783 struct files_struct *dirfsp,
5784 struct smb_filename *smb_fname,
5785 uint32_t access_mask,
5786 uint32_t share_access,
5787 uint32_t create_disposition,
5788 uint32_t create_options,
5789 uint32_t file_attributes,
5790 uint32_t oplock_request,
5791 const struct smb2_lease *lease,
5792 uint64_t allocation_size,
5793 uint32_t private_flags,
5794 struct security_descriptor *sd,
5795 struct ea_list *ea_list,
5797 files_struct **result,
5798 int *pinfo)
5800 struct smb2_lease none_lease;
5801 int info = FILE_WAS_OPENED;
5802 files_struct *base_fsp = NULL;
5803 files_struct *fsp = NULL;
5804 bool free_fsp_on_error = false;
5805 NTSTATUS status;
5806 int ret;
5807 struct smb_filename *parent_dir_fname = NULL;
5808 struct smb_filename *smb_fname_atname = NULL;
5810 DBG_DEBUG("access_mask = 0x%"PRIx32" "
5811 "file_attributes = 0x%"PRIx32" "
5812 "share_access = 0x%"PRIx32" "
5813 "create_disposition = 0x%"PRIx32" "
5814 "create_options = 0x%"PRIx32" "
5815 "oplock_request = 0x%"PRIx32" "
5816 "private_flags = 0x%"PRIx32" "
5817 "ea_list = %p, "
5818 "sd = %p, "
5819 "fname = %s\n",
5820 access_mask,
5821 file_attributes,
5822 share_access,
5823 create_disposition,
5824 create_options,
5825 oplock_request,
5826 private_flags,
5827 ea_list,
5829 smb_fname_str_dbg(smb_fname));
5831 if (create_options & FILE_OPEN_BY_FILE_ID) {
5832 status = NT_STATUS_NOT_SUPPORTED;
5833 goto fail;
5836 if (create_options & NTCREATEX_OPTIONS_INVALID_PARAM_MASK) {
5837 status = NT_STATUS_INVALID_PARAMETER;
5838 goto fail;
5841 if (req == NULL) {
5842 oplock_request |= INTERNAL_OPEN_ONLY;
5845 if (lease != NULL) {
5846 uint16_t epoch = lease->lease_epoch;
5847 uint16_t version = lease->lease_version;
5849 if (req == NULL) {
5850 DBG_WARNING("Got lease on internal open\n");
5851 status = NT_STATUS_INTERNAL_ERROR;
5852 goto fail;
5855 status = lease_match(conn,
5856 req,
5857 &lease->lease_key,
5858 conn->connectpath,
5859 smb_fname,
5860 &version,
5861 &epoch);
5862 if (NT_STATUS_EQUAL(status, NT_STATUS_OPLOCK_NOT_GRANTED)) {
5863 /* Dynamic share file. No leases and update epoch... */
5864 none_lease = *lease;
5865 none_lease.lease_state = SMB2_LEASE_NONE;
5866 none_lease.lease_epoch = epoch;
5867 none_lease.lease_version = version;
5868 lease = &none_lease;
5869 } else if (!NT_STATUS_IS_OK(status)) {
5870 goto fail;
5874 if ((conn->fs_capabilities & FILE_NAMED_STREAMS)
5875 && (access_mask & DELETE_ACCESS)
5876 && !is_named_stream(smb_fname)) {
5878 * We can't open a file with DELETE access if any of the
5879 * streams is open without FILE_SHARE_DELETE
5881 status = open_streams_for_delete(conn, smb_fname);
5883 if (!NT_STATUS_IS_OK(status)) {
5884 goto fail;
5888 if (access_mask & SEC_FLAG_SYSTEM_SECURITY) {
5889 bool ok;
5891 ok = security_token_has_privilege(get_current_nttok(conn),
5892 SEC_PRIV_SECURITY);
5893 if (!ok) {
5894 DBG_DEBUG("open on %s failed - "
5895 "SEC_FLAG_SYSTEM_SECURITY denied.\n",
5896 smb_fname_str_dbg(smb_fname));
5897 status = NT_STATUS_PRIVILEGE_NOT_HELD;
5898 goto fail;
5901 if (conn->sconn->using_smb2 &&
5902 (access_mask == SEC_FLAG_SYSTEM_SECURITY))
5905 * No other bits set. Windows SMB2 refuses this.
5906 * See smbtorture3 SMB2-SACL test.
5908 * Note this is an SMB2-only behavior,
5909 * smbtorture3 SMB1-SYSTEM-SECURITY already tests
5910 * that SMB1 allows this.
5912 status = NT_STATUS_ACCESS_DENIED;
5913 goto fail;
5918 * Files or directories can't be opened DELETE_ON_CLOSE without
5919 * delete access.
5920 * BUG: https://bugzilla.samba.org/show_bug.cgi?id=13358
5922 if (create_options & FILE_DELETE_ON_CLOSE) {
5923 if ((access_mask & DELETE_ACCESS) == 0) {
5924 status = NT_STATUS_INVALID_PARAMETER;
5925 goto fail;
5929 if ((conn->fs_capabilities & FILE_NAMED_STREAMS)
5930 && is_named_stream(smb_fname))
5932 uint32_t base_create_disposition;
5933 struct smb_filename *smb_fname_base = NULL;
5934 uint32_t base_privflags;
5936 if (create_options & FILE_DIRECTORY_FILE) {
5937 DBG_DEBUG("Can't open a stream as directory\n");
5938 status = NT_STATUS_NOT_A_DIRECTORY;
5939 goto fail;
5942 switch (create_disposition) {
5943 case FILE_OPEN:
5944 base_create_disposition = FILE_OPEN;
5945 break;
5946 default:
5947 base_create_disposition = FILE_OPEN_IF;
5948 break;
5951 smb_fname_base = cp_smb_filename_nostream(
5952 talloc_tos(), smb_fname);
5954 if (smb_fname_base == NULL) {
5955 status = NT_STATUS_NO_MEMORY;
5956 goto fail;
5960 * We may be creating the basefile as part of creating the
5961 * stream, so it's legal if the basefile doesn't exist at this
5962 * point, the create_file_unixpath() below will create it. But
5963 * if the basefile exists we want a handle so we can fstat() it.
5966 ret = vfs_stat(conn, smb_fname_base);
5967 if (ret == -1 && errno != ENOENT) {
5968 status = map_nt_error_from_unix(errno);
5969 TALLOC_FREE(smb_fname_base);
5970 goto fail;
5972 if (ret == 0) {
5973 status = openat_pathref_fsp(conn->cwd_fsp,
5974 smb_fname_base);
5975 if (!NT_STATUS_IS_OK(status)) {
5976 DBG_ERR("open_smb_fname_fsp [%s] failed: %s\n",
5977 smb_fname_str_dbg(smb_fname_base),
5978 nt_errstr(status));
5979 TALLOC_FREE(smb_fname_base);
5980 goto fail;
5984 * https://bugzilla.samba.org/show_bug.cgi?id=10229
5985 * We need to check if the requested access mask
5986 * could be used to open the underlying file (if
5987 * it existed), as we're passing in zero for the
5988 * access mask to the base filename.
5990 status = check_base_file_access(smb_fname_base->fsp,
5991 access_mask);
5993 if (!NT_STATUS_IS_OK(status)) {
5994 DEBUG(10, ("Permission check "
5995 "for base %s failed: "
5996 "%s\n", smb_fname->base_name,
5997 nt_errstr(status)));
5998 TALLOC_FREE(smb_fname_base);
5999 goto fail;
6003 base_privflags = NTCREATEX_FLAG_STREAM_BASEOPEN;
6005 /* Open the base file. */
6006 status = create_file_unixpath(conn,
6007 NULL,
6008 dirfsp,
6009 smb_fname_base,
6011 FILE_SHARE_READ
6012 | FILE_SHARE_WRITE
6013 | FILE_SHARE_DELETE,
6014 base_create_disposition,
6018 NULL,
6020 base_privflags,
6021 NULL,
6022 NULL,
6023 &base_fsp,
6024 NULL);
6025 TALLOC_FREE(smb_fname_base);
6027 if (!NT_STATUS_IS_OK(status)) {
6028 DEBUG(10, ("create_file_unixpath for base %s failed: "
6029 "%s\n", smb_fname->base_name,
6030 nt_errstr(status)));
6031 goto fail;
6035 if (smb_fname->fsp != NULL) {
6037 fsp = smb_fname->fsp;
6040 * We're about to use smb_fname->fsp for the fresh open.
6042 * Every fsp passed in via smb_fname->fsp already
6043 * holds a fsp->fsp_name. If it is already this
6044 * fsp->fsp_name that we got passed in as our input
6045 * argument smb_fname, these two are assumed to have
6046 * the same lifetime: Every fsp hangs of "conn", and
6047 * fsp->fsp_name is its talloc child.
6050 if (smb_fname != smb_fname->fsp->fsp_name) {
6052 * "smb_fname" is temporary in this case, but
6053 * the destructor of smb_fname would also tear
6054 * down the fsp we're about to use. Unlink
6055 * them from each other.
6057 smb_fname_fsp_unlink(smb_fname);
6060 * "fsp" is ours now
6062 free_fsp_on_error = true;
6065 status = fsp_bind_smb(fsp, req);
6066 if (!NT_STATUS_IS_OK(status)) {
6067 goto fail;
6070 if (fsp_is_alternate_stream(fsp)) {
6071 struct files_struct *tmp_base_fsp = fsp->base_fsp;
6073 fsp_set_base_fsp(fsp, NULL);
6075 fd_close(tmp_base_fsp);
6076 file_free(NULL, tmp_base_fsp);
6078 } else {
6080 * No fsp passed in that we can use, create one
6082 status = file_new(req, conn, &fsp);
6083 if(!NT_STATUS_IS_OK(status)) {
6084 goto fail;
6086 free_fsp_on_error = true;
6088 status = fsp_set_smb_fname(fsp, smb_fname);
6089 if (!NT_STATUS_IS_OK(status)) {
6090 goto fail;
6094 SMB_ASSERT(fsp->fsp_name->fsp != NULL);
6095 SMB_ASSERT(fsp->fsp_name->fsp == fsp);
6097 if (base_fsp) {
6099 * We're opening the stream element of a
6100 * base_fsp we already opened. Set up the
6101 * base_fsp pointer.
6103 fsp_set_base_fsp(fsp, base_fsp);
6106 if (dirfsp != NULL) {
6107 status = SMB_VFS_PARENT_PATHNAME(
6108 conn,
6109 talloc_tos(),
6110 smb_fname,
6111 &parent_dir_fname,
6112 &smb_fname_atname);
6113 if (!NT_STATUS_IS_OK(status)) {
6114 goto fail;
6116 } else {
6118 * Get a pathref on the parent. We can re-use this for
6119 * multiple calls to check parent ACLs etc. to avoid
6120 * pathname calls.
6122 status = parent_pathref(talloc_tos(),
6123 conn->cwd_fsp,
6124 smb_fname,
6125 &parent_dir_fname,
6126 &smb_fname_atname);
6127 if (!NT_STATUS_IS_OK(status)) {
6128 goto fail;
6131 dirfsp = parent_dir_fname->fsp;
6132 status = fsp_set_smb_fname(dirfsp, parent_dir_fname);
6133 if (!NT_STATUS_IS_OK(status)) {
6134 goto fail;
6139 * If it's a request for a directory open, deal with it separately.
6142 if (create_options & FILE_DIRECTORY_FILE) {
6144 if (create_options & FILE_NON_DIRECTORY_FILE) {
6145 status = NT_STATUS_INVALID_PARAMETER;
6146 goto fail;
6149 /* Can't open a temp directory. IFS kit test. */
6150 if (!(file_attributes & FILE_FLAG_POSIX_SEMANTICS) &&
6151 (file_attributes & FILE_ATTRIBUTE_TEMPORARY)) {
6152 status = NT_STATUS_INVALID_PARAMETER;
6153 goto fail;
6157 * We will get a create directory here if the Win32
6158 * app specified a security descriptor in the
6159 * CreateDirectory() call.
6162 oplock_request = 0;
6163 status = open_directory(conn,
6164 req,
6165 access_mask,
6166 share_access,
6167 create_disposition,
6168 create_options,
6169 file_attributes,
6170 dirfsp->fsp_name,
6171 smb_fname_atname,
6172 &info,
6173 fsp);
6174 } else {
6177 * Ordinary file case.
6180 if (allocation_size) {
6181 fsp->initial_allocation_size = smb_roundup(fsp->conn,
6182 allocation_size);
6185 status = open_file_ntcreate(conn,
6186 req,
6187 access_mask,
6188 share_access,
6189 create_disposition,
6190 create_options,
6191 file_attributes,
6192 oplock_request,
6193 lease,
6194 private_flags,
6195 dirfsp->fsp_name,
6196 smb_fname_atname,
6197 &info,
6198 fsp);
6199 if (NT_STATUS_EQUAL(status, NT_STATUS_FILE_IS_A_DIRECTORY)) {
6201 /* A stream open never opens a directory */
6203 if (base_fsp) {
6204 status = NT_STATUS_FILE_IS_A_DIRECTORY;
6205 goto fail;
6209 * Fail the open if it was explicitly a non-directory
6210 * file.
6213 if (create_options & FILE_NON_DIRECTORY_FILE) {
6214 status = NT_STATUS_FILE_IS_A_DIRECTORY;
6215 goto fail;
6218 oplock_request = 0;
6219 status = open_directory(conn,
6220 req,
6221 access_mask,
6222 share_access,
6223 create_disposition,
6224 create_options,
6225 file_attributes,
6226 dirfsp->fsp_name,
6227 smb_fname_atname,
6228 &info,
6229 fsp);
6233 if (!NT_STATUS_IS_OK(status)) {
6234 goto fail;
6237 fsp->fsp_flags.is_fsa = true;
6239 if ((ea_list != NULL) &&
6240 ((info == FILE_WAS_CREATED) || (info == FILE_WAS_OVERWRITTEN))) {
6241 status = set_ea(conn, fsp, ea_list);
6242 if (!NT_STATUS_IS_OK(status)) {
6243 goto fail;
6247 if (!fsp->fsp_flags.is_directory &&
6248 S_ISDIR(fsp->fsp_name->st.st_ex_mode))
6250 status = NT_STATUS_ACCESS_DENIED;
6251 goto fail;
6254 /* Save the requested allocation size. */
6255 if ((info == FILE_WAS_CREATED) || (info == FILE_WAS_OVERWRITTEN)) {
6256 if ((allocation_size > (uint64_t)fsp->fsp_name->st.st_ex_size)
6257 && !(fsp->fsp_flags.is_directory))
6259 fsp->initial_allocation_size = smb_roundup(
6260 fsp->conn, allocation_size);
6261 if (vfs_allocate_file_space(
6262 fsp, fsp->initial_allocation_size) == -1) {
6263 status = NT_STATUS_DISK_FULL;
6264 goto fail;
6266 } else {
6267 fsp->initial_allocation_size = smb_roundup(
6268 fsp->conn, (uint64_t)fsp->fsp_name->st.st_ex_size);
6270 } else {
6271 fsp->initial_allocation_size = 0;
6274 if ((info == FILE_WAS_CREATED) &&
6275 lp_nt_acl_support(SNUM(conn)) &&
6276 !fsp_is_alternate_stream(fsp)) {
6277 if (sd != NULL) {
6279 * According to the MS documentation, the only time the security
6280 * descriptor is applied to the opened file is iff we *created* the
6281 * file; an existing file stays the same.
6283 * Also, it seems (from observation) that you can open the file with
6284 * any access mask but you can still write the sd. We need to override
6285 * the granted access before we call set_sd
6286 * Patch for bug #2242 from Tom Lackemann <cessnatomny@yahoo.com>.
6289 uint32_t sec_info_sent;
6290 uint32_t saved_access_mask = fsp->access_mask;
6292 sec_info_sent = get_sec_info(sd);
6294 fsp->access_mask = FILE_GENERIC_ALL;
6296 if (sec_info_sent & (SECINFO_OWNER|
6297 SECINFO_GROUP|
6298 SECINFO_DACL|
6299 SECINFO_SACL)) {
6300 status = set_sd(fsp, sd, sec_info_sent);
6303 fsp->access_mask = saved_access_mask;
6305 if (!NT_STATUS_IS_OK(status)) {
6306 goto fail;
6308 } else if (lp_inherit_acls(SNUM(conn))) {
6309 /* Inherit from parent. Errors here are not fatal. */
6310 status = inherit_new_acl(dirfsp, fsp);
6311 if (!NT_STATUS_IS_OK(status)) {
6312 DEBUG(10,("inherit_new_acl: failed for %s with %s\n",
6313 fsp_str_dbg(fsp),
6314 nt_errstr(status) ));
6319 if ((conn->fs_capabilities & FILE_FILE_COMPRESSION)
6320 && (create_options & FILE_NO_COMPRESSION)
6321 && (info == FILE_WAS_CREATED)) {
6322 status = SMB_VFS_SET_COMPRESSION(conn, fsp, fsp,
6323 COMPRESSION_FORMAT_NONE);
6324 if (!NT_STATUS_IS_OK(status)) {
6325 DEBUG(1, ("failed to disable compression: %s\n",
6326 nt_errstr(status)));
6330 DEBUG(10, ("create_file_unixpath: info=%d\n", info));
6332 *result = fsp;
6333 if (pinfo != NULL) {
6334 *pinfo = info;
6337 smb_fname->st = fsp->fsp_name->st;
6339 TALLOC_FREE(parent_dir_fname);
6341 return NT_STATUS_OK;
6343 fail:
6344 DEBUG(10, ("create_file_unixpath: %s\n", nt_errstr(status)));
6346 if (fsp != NULL) {
6348 * The close_file below will close
6349 * fsp->base_fsp.
6351 base_fsp = NULL;
6352 close_file_smb(req, fsp, ERROR_CLOSE);
6353 if (free_fsp_on_error) {
6354 file_free(req, fsp);
6355 fsp = NULL;
6358 if (base_fsp != NULL) {
6359 close_file_free(req, &base_fsp, ERROR_CLOSE);
6362 TALLOC_FREE(parent_dir_fname);
6364 return status;
6367 NTSTATUS create_file_default(connection_struct *conn,
6368 struct smb_request *req,
6369 struct files_struct *dirfsp,
6370 struct smb_filename *smb_fname,
6371 uint32_t access_mask,
6372 uint32_t share_access,
6373 uint32_t create_disposition,
6374 uint32_t create_options,
6375 uint32_t file_attributes,
6376 uint32_t oplock_request,
6377 const struct smb2_lease *lease,
6378 uint64_t allocation_size,
6379 uint32_t private_flags,
6380 struct security_descriptor *sd,
6381 struct ea_list *ea_list,
6382 files_struct **result,
6383 int *pinfo,
6384 const struct smb2_create_blobs *in_context_blobs,
6385 struct smb2_create_blobs *out_context_blobs)
6387 int info = FILE_WAS_OPENED;
6388 files_struct *fsp = NULL;
6389 NTSTATUS status;
6390 bool stream_name = false;
6391 struct smb2_create_blob *posx = NULL;
6393 DBG_DEBUG("create_file: access_mask = 0x%x "
6394 "file_attributes = 0x%x, share_access = 0x%x, "
6395 "create_disposition = 0x%x create_options = 0x%x "
6396 "oplock_request = 0x%x "
6397 "private_flags = 0x%x "
6398 "ea_list = %p, sd = %p, "
6399 "fname = %s\n",
6400 (unsigned int)access_mask,
6401 (unsigned int)file_attributes,
6402 (unsigned int)share_access,
6403 (unsigned int)create_disposition,
6404 (unsigned int)create_options,
6405 (unsigned int)oplock_request,
6406 (unsigned int)private_flags,
6407 ea_list,
6409 smb_fname_str_dbg(smb_fname));
6411 if (req != NULL) {
6413 * Remember the absolute time of the original request
6414 * with this mid. We'll use it later to see if this
6415 * has timed out.
6417 get_deferred_open_message_state(req, &req->request_time, NULL);
6421 * Check to see if this is a mac fork of some kind.
6424 stream_name = is_ntfs_stream_smb_fname(smb_fname);
6425 if (stream_name) {
6426 enum FAKE_FILE_TYPE fake_file_type;
6428 fake_file_type = is_fake_file(smb_fname);
6430 if (req != NULL && fake_file_type != FAKE_FILE_TYPE_NONE) {
6433 * Here we go! support for changing the disk quotas
6434 * --metze
6436 * We need to fake up to open this MAGIC QUOTA file
6437 * and return a valid FID.
6439 * w2k close this file directly after openening xp
6440 * also tries a QUERY_FILE_INFO on the file and then
6441 * close it
6443 status = open_fake_file(req, conn, req->vuid,
6444 fake_file_type, smb_fname,
6445 access_mask, &fsp);
6446 if (!NT_STATUS_IS_OK(status)) {
6447 goto fail;
6450 ZERO_STRUCT(smb_fname->st);
6451 goto done;
6454 if (!(conn->fs_capabilities & FILE_NAMED_STREAMS)) {
6455 status = NT_STATUS_OBJECT_NAME_INVALID;
6456 goto fail;
6460 if (is_ntfs_default_stream_smb_fname(smb_fname)) {
6461 int ret;
6462 /* We have to handle this error here. */
6463 if (create_options & FILE_DIRECTORY_FILE) {
6464 status = NT_STATUS_NOT_A_DIRECTORY;
6465 goto fail;
6467 ret = vfs_stat(conn, smb_fname);
6468 if (ret == 0 && VALID_STAT_OF_DIR(smb_fname->st)) {
6469 status = NT_STATUS_FILE_IS_A_DIRECTORY;
6470 goto fail;
6474 posx = smb2_create_blob_find(
6475 in_context_blobs, SMB2_CREATE_TAG_POSIX);
6476 if (posx != NULL) {
6477 uint32_t wire_mode_bits = 0;
6478 mode_t mode_bits = 0;
6479 SMB_STRUCT_STAT sbuf = { 0 };
6480 enum perm_type ptype =
6481 (create_options & FILE_DIRECTORY_FILE) ?
6482 PERM_NEW_DIR : PERM_NEW_FILE;
6484 if (posx->data.length != 4) {
6485 status = NT_STATUS_INVALID_PARAMETER;
6486 goto fail;
6489 wire_mode_bits = IVAL(posx->data.data, 0);
6490 status = unix_perms_from_wire(
6491 conn, &sbuf, wire_mode_bits, ptype, &mode_bits);
6492 if (!NT_STATUS_IS_OK(status)) {
6493 goto fail;
6496 * Remove type info from mode, leaving only the
6497 * permissions and setuid/gid bits.
6499 mode_bits &= ~S_IFMT;
6501 file_attributes = (FILE_FLAG_POSIX_SEMANTICS | mode_bits);
6504 status = create_file_unixpath(conn,
6505 req,
6506 dirfsp,
6507 smb_fname,
6508 access_mask,
6509 share_access,
6510 create_disposition,
6511 create_options,
6512 file_attributes,
6513 oplock_request,
6514 lease,
6515 allocation_size,
6516 private_flags,
6518 ea_list,
6519 &fsp,
6520 &info);
6521 if (!NT_STATUS_IS_OK(status)) {
6522 goto fail;
6525 done:
6526 DEBUG(10, ("create_file: info=%d\n", info));
6528 *result = fsp;
6529 if (pinfo != NULL) {
6530 *pinfo = info;
6532 return NT_STATUS_OK;
6534 fail:
6535 DEBUG(10, ("create_file: %s\n", nt_errstr(status)));
6537 if (fsp != NULL) {
6538 close_file_free(req, &fsp, ERROR_CLOSE);
6540 return status;