smbd: set fsp->fsp_flags.can_write to false for access to previous-versions
[Samba.git] / source3 / smbd / open.c
blob8b08c9ad5dcc8e3f0d7ed7876bc72aafffaa532b
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 compatibility 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);
478 static NTSTATUS chdir_below_conn(
479 TALLOC_CTX *mem_ctx,
480 connection_struct *conn,
481 const char *connectpath,
482 size_t connectpath_len,
483 struct smb_filename *dir_fname,
484 struct smb_filename **_oldwd_fname)
486 struct smb_filename *oldwd_fname = NULL;
487 struct smb_filename *smb_fname_dot = NULL;
488 struct smb_filename *real_fname = NULL;
489 const char *relative = NULL;
490 NTSTATUS status;
491 int ret;
492 bool ok;
494 if (!ISDOT(dir_fname->base_name)) {
496 oldwd_fname = vfs_GetWd(talloc_tos(), conn);
497 if (oldwd_fname == NULL) {
498 status = map_nt_error_from_unix(errno);
499 goto out;
502 /* Pin parent directory in place. */
503 ret = vfs_ChDir(conn, dir_fname);
504 if (ret == -1) {
505 status = map_nt_error_from_unix(errno);
506 DBG_DEBUG("chdir to %s failed: %s\n",
507 dir_fname->base_name,
508 strerror(errno));
509 goto out;
513 smb_fname_dot = synthetic_smb_fname(
514 talloc_tos(),
515 ".",
516 NULL,
517 NULL,
518 dir_fname->twrp,
519 dir_fname->flags);
520 if (smb_fname_dot == NULL) {
521 status = NT_STATUS_NO_MEMORY;
522 goto out;
525 real_fname = SMB_VFS_REALPATH(conn, talloc_tos(), smb_fname_dot);
526 if (real_fname == NULL) {
527 status = map_nt_error_from_unix(errno);
528 DBG_DEBUG("realpath in %s failed: %s\n",
529 dir_fname->base_name,
530 strerror(errno));
531 goto out;
533 TALLOC_FREE(smb_fname_dot);
535 ok = subdir_of(connectpath,
536 connectpath_len,
537 real_fname->base_name,
538 &relative);
539 if (ok) {
540 TALLOC_FREE(real_fname);
541 *_oldwd_fname = oldwd_fname;
542 return NT_STATUS_OK;
545 DBG_NOTICE("Bad access attempt: %s is a symlink "
546 "outside the share path\n"
547 "conn_rootdir =%s\n"
548 "resolved_name=%s\n",
549 dir_fname->base_name,
550 connectpath,
551 real_fname->base_name);
552 TALLOC_FREE(real_fname);
554 status = NT_STATUS_OBJECT_NAME_NOT_FOUND;
556 out:
557 if (oldwd_fname != NULL) {
558 ret = vfs_ChDir(conn, oldwd_fname);
559 SMB_ASSERT(ret == 0);
560 TALLOC_FREE(oldwd_fname);
563 return status;
567 * Get the symlink target of dirfsp/symlink_name, making sure the
568 * target is below connection_path.
571 static NTSTATUS symlink_target_below_conn(
572 TALLOC_CTX *mem_ctx,
573 const char *connection_path,
574 size_t connection_path_len,
575 struct files_struct *fsp,
576 struct files_struct *dirfsp,
577 struct smb_filename *symlink_name,
578 char **_target)
580 char *target = NULL;
581 char *absolute = NULL;
582 const char *relative = NULL;
583 NTSTATUS status;
584 bool ok;
586 if (fsp_get_pathref_fd(fsp) != -1) {
588 * fsp is an O_PATH open, Linux does a "freadlink"
589 * with an empty name argument to readlinkat
591 status = readlink_talloc(talloc_tos(), fsp, NULL, &target);
592 } else {
593 status = readlink_talloc(
594 talloc_tos(), dirfsp, symlink_name, &target);
597 if (!NT_STATUS_IS_OK(status)) {
598 DBG_DEBUG("readlink_talloc failed: %s\n", nt_errstr(status));
599 return status;
602 if (target[0] != '/') {
603 char *tmp = talloc_asprintf(
604 talloc_tos(),
605 "%s/%s/%s",
606 connection_path,
607 dirfsp->fsp_name->base_name,
608 target);
610 TALLOC_FREE(target);
612 if (tmp == NULL) {
613 return NT_STATUS_NO_MEMORY;
615 target = tmp;
618 DBG_DEBUG("redirecting to %s\n", target);
620 absolute = canonicalize_absolute_path(talloc_tos(), target);
621 TALLOC_FREE(target);
623 if (absolute == NULL) {
624 return NT_STATUS_NO_MEMORY;
628 * We're doing the "below connection_path" here because it's
629 * cheap. It might be that we get a symlink out of the share,
630 * pointing to yet another symlink getting us back into the
631 * share. If we need that, we would have to remove the check
632 * here.
634 ok = subdir_of(
635 connection_path,
636 connection_path_len,
637 absolute,
638 &relative);
639 if (!ok) {
640 DBG_NOTICE("Bad access attempt: %s is a symlink "
641 "outside the share path\n"
642 "conn_rootdir =%s\n"
643 "resolved_name=%s\n",
644 symlink_name->base_name,
645 connection_path,
646 absolute);
647 TALLOC_FREE(absolute);
648 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
651 if (relative[0] == '\0') {
653 * special case symlink to share root: "." is our
654 * share root filename
656 absolute[0] = '.';
657 absolute[1] = '\0';
658 } else {
659 memmove(absolute, relative, strlen(relative)+1);
662 *_target = absolute;
663 return NT_STATUS_OK;
666 /****************************************************************************
667 Non-widelink open.
668 ****************************************************************************/
670 static NTSTATUS non_widelink_open(const struct files_struct *dirfsp,
671 files_struct *fsp,
672 struct smb_filename *smb_fname,
673 const struct vfs_open_how *_how)
675 struct connection_struct *conn = fsp->conn;
676 const char *connpath = SMB_VFS_CONNECTPATH(conn, dirfsp, smb_fname);
677 size_t connpath_len;
678 NTSTATUS status = NT_STATUS_OK;
679 int fd = -1;
680 char *orig_smb_fname_base = smb_fname->base_name;
681 struct smb_filename *orig_fsp_name = fsp->fsp_name;
682 struct smb_filename *smb_fname_rel = NULL;
683 struct smb_filename *oldwd_fname = NULL;
684 struct smb_filename *parent_dir_fname = NULL;
685 struct vfs_open_how how = *_how;
686 char *target = NULL;
687 size_t link_depth = 0;
688 int ret;
690 SMB_ASSERT(!fsp_is_alternate_stream(fsp));
692 if (connpath == NULL) {
694 * This can happen with shadow_copy2 if the snapshot
695 * path is not found
697 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
699 connpath_len = strlen(connpath);
701 again:
702 if (smb_fname->base_name[0] == '/') {
703 int cmp = strcmp(connpath, smb_fname->base_name);
704 if (cmp == 0) {
705 smb_fname->base_name = talloc_strdup(smb_fname, "");
706 if (smb_fname->base_name == NULL) {
707 status = NT_STATUS_NO_MEMORY;
708 goto out;
713 if (dirfsp == conn->cwd_fsp) {
715 status = SMB_VFS_PARENT_PATHNAME(fsp->conn,
716 talloc_tos(),
717 smb_fname,
718 &parent_dir_fname,
719 &smb_fname_rel);
720 if (!NT_STATUS_IS_OK(status)) {
721 goto out;
724 status = chdir_below_conn(
725 talloc_tos(),
726 conn,
727 connpath,
728 connpath_len,
729 parent_dir_fname,
730 &oldwd_fname);
731 if (!NT_STATUS_IS_OK(status)) {
732 goto out;
735 /* Setup fsp->fsp_name to be relative to cwd */
736 fsp->fsp_name = smb_fname_rel;
737 } else {
739 * fsp->fsp_name is unchanged as it is already correctly
740 * relative to conn->cwd.
742 smb_fname_rel = smb_fname;
747 * Assert nobody can step in with a symlink on the
748 * path, there is no path anymore and we'll use
749 * O_NOFOLLOW to open.
751 char *slash = strchr_m(smb_fname_rel->base_name, '/');
752 SMB_ASSERT(slash == NULL);
755 how.flags |= O_NOFOLLOW;
757 fd = SMB_VFS_OPENAT(conn,
758 dirfsp,
759 smb_fname_rel,
760 fsp,
761 &how);
762 fsp_set_fd(fsp, fd); /* This preserves errno */
764 if (fd == -1) {
765 status = map_nt_error_from_unix(errno);
767 if (errno == ENOENT) {
768 goto out;
772 * ENOENT makes it worthless retrying with a
773 * stat, we know for sure the file does not
774 * exist. For everything else we want to know
775 * what's there.
777 ret = SMB_VFS_FSTATAT(
778 fsp->conn,
779 dirfsp,
780 smb_fname_rel,
781 &fsp->fsp_name->st,
782 AT_SYMLINK_NOFOLLOW);
784 if (ret == -1) {
786 * Keep the original error. Otherwise we would
787 * mask for example EROFS for open(O_CREAT),
788 * turning it into ENOENT.
790 goto out;
792 } else {
793 ret = SMB_VFS_FSTAT(fsp, &fsp->fsp_name->st);
796 if (ret == -1) {
797 status = map_nt_error_from_unix(errno);
798 DBG_DEBUG("fstat[at](%s) failed: %s\n",
799 smb_fname_str_dbg(smb_fname),
800 strerror(errno));
801 goto out;
804 fsp->fsp_flags.is_directory = S_ISDIR(fsp->fsp_name->st.st_ex_mode);
805 orig_fsp_name->st = fsp->fsp_name->st;
807 if (!S_ISLNK(fsp->fsp_name->st.st_ex_mode)) {
808 goto out;
812 * Found a symlink to follow in user space
815 if (fsp->fsp_name->flags & SMB_FILENAME_POSIX_PATH) {
816 /* Never follow symlinks on posix open. */
817 status = NT_STATUS_STOPPED_ON_SYMLINK;
818 goto out;
820 if (!lp_follow_symlinks(SNUM(conn))) {
821 /* Explicitly no symlinks. */
822 status = NT_STATUS_STOPPED_ON_SYMLINK;
823 goto out;
826 link_depth += 1;
827 if (link_depth >= 40) {
828 status = NT_STATUS_STOPPED_ON_SYMLINK;
829 goto out;
832 fsp->fsp_name = orig_fsp_name;
834 status = symlink_target_below_conn(
835 talloc_tos(),
836 connpath,
837 connpath_len,
838 fsp,
839 discard_const_p(files_struct, dirfsp),
840 smb_fname_rel,
841 &target);
843 if (!NT_STATUS_IS_OK(status)) {
844 DBG_DEBUG("symlink_target_below_conn() failed: %s\n",
845 nt_errstr(status));
846 goto out;
850 * Close what openat(O_PATH) potentially left behind
852 fd_close(fsp);
854 if (smb_fname->base_name != orig_smb_fname_base) {
855 TALLOC_FREE(smb_fname->base_name);
857 smb_fname->base_name = target;
859 if (oldwd_fname != NULL) {
860 ret = vfs_ChDir(conn, oldwd_fname);
861 if (ret == -1) {
862 smb_panic("unable to get back to old directory\n");
864 TALLOC_FREE(oldwd_fname);
868 * And do it all again... As smb_fname is not relative to the passed in
869 * dirfsp anymore, we pass conn->cwd_fsp as dirfsp to
870 * non_widelink_open() to trigger the chdir(parentdir) logic.
872 dirfsp = conn->cwd_fsp;
874 goto again;
876 out:
877 fsp->fsp_name = orig_fsp_name;
878 smb_fname->base_name = orig_smb_fname_base;
880 TALLOC_FREE(parent_dir_fname);
882 if (!NT_STATUS_IS_OK(status)) {
883 fd_close(fsp);
886 if (oldwd_fname != NULL) {
887 ret = vfs_ChDir(conn, oldwd_fname);
888 if (ret == -1) {
889 smb_panic("unable to get back to old directory\n");
891 TALLOC_FREE(oldwd_fname);
893 return status;
896 /****************************************************************************
897 fd support routines - attempt to do a dos_open.
898 ****************************************************************************/
900 NTSTATUS fd_openat(const struct files_struct *dirfsp,
901 struct smb_filename *smb_fname,
902 files_struct *fsp,
903 const struct vfs_open_how *_how)
905 struct vfs_open_how how = *_how;
906 struct connection_struct *conn = fsp->conn;
907 NTSTATUS status = NT_STATUS_OK;
908 bool fsp_is_stream = fsp_is_alternate_stream(fsp);
909 bool smb_fname_is_stream = is_named_stream(smb_fname);
911 SMB_ASSERT(fsp_is_stream == smb_fname_is_stream);
914 * Never follow symlinks on a POSIX client. The
915 * client should be doing this.
918 if ((fsp->posix_flags & FSP_POSIX_FLAGS_OPEN) || !lp_follow_symlinks(SNUM(conn))) {
919 how.flags |= O_NOFOLLOW;
922 if (fsp_is_stream) {
923 int fd;
925 fd = SMB_VFS_OPENAT(
926 conn,
927 NULL, /* stream open is relative to fsp->base_fsp */
928 smb_fname,
929 fsp,
930 &how);
931 if (fd == -1) {
932 status = map_nt_error_from_unix(errno);
934 fsp_set_fd(fsp, fd);
936 if (fd != -1) {
937 status = vfs_stat_fsp(fsp);
938 if (!NT_STATUS_IS_OK(status)) {
939 DBG_DEBUG("vfs_stat_fsp failed: %s\n",
940 nt_errstr(status));
941 fd_close(fsp);
945 return status;
949 * Only follow symlinks within a share
950 * definition.
952 status = non_widelink_open(dirfsp, fsp, smb_fname, &how);
953 if (!NT_STATUS_IS_OK(status)) {
954 if (NT_STATUS_EQUAL(status, NT_STATUS_TOO_MANY_OPENED_FILES)) {
955 static time_t last_warned = 0L;
957 if (time((time_t *) NULL) > last_warned) {
958 DEBUG(0,("Too many open files, unable "
959 "to open more! smbd's max "
960 "open files = %d\n",
961 lp_max_open_files()));
962 last_warned = time((time_t *) NULL);
966 DBG_DEBUG("name %s, flags = 0%o mode = 0%o, fd = %d. %s\n",
967 smb_fname_str_dbg(smb_fname),
968 how.flags,
969 (int)how.mode,
970 fsp_get_pathref_fd(fsp),
971 nt_errstr(status));
972 return status;
975 DBG_DEBUG("name %s, flags = 0%o mode = 0%o, fd = %d\n",
976 smb_fname_str_dbg(smb_fname),
977 how.flags,
978 (int)how.mode,
979 fsp_get_pathref_fd(fsp));
981 return status;
984 /****************************************************************************
985 Close the file associated with a fsp.
986 ****************************************************************************/
988 NTSTATUS fd_close(files_struct *fsp)
990 NTSTATUS status;
991 int ret;
993 if (fsp == fsp->conn->cwd_fsp) {
994 return NT_STATUS_OK;
997 if (fsp->fsp_flags.fstat_before_close) {
998 status = vfs_stat_fsp(fsp);
999 if (!NT_STATUS_IS_OK(status)) {
1001 * If this is a stream and delete-on-close was set, the
1002 * backing object (an xattr from streams_xattr) might
1003 * already be deleted so fstat() fails with
1004 * NT_STATUS_NOT_FOUND. So if fsp refers to a stream we
1005 * ignore the error and only bail for normal files where
1006 * an fstat() should still work. NB. We cannot use
1007 * fsp_is_alternate_stream(fsp) for this as the base_fsp
1008 * has already been closed at this point and so the value
1009 * fsp_is_alternate_stream() checks for is already NULL.
1011 if (fsp->fsp_name->stream_name == NULL) {
1012 return status;
1017 if (fsp->dptr) {
1018 dptr_CloseDir(fsp);
1020 if (fsp_get_pathref_fd(fsp) == -1) {
1022 * Either a directory where the dptr_CloseDir() already closed
1023 * the fd or a stat open.
1025 return NT_STATUS_OK;
1027 if (fh_get_refcount(fsp->fh) > 1) {
1028 return NT_STATUS_OK; /* Shared handle. Only close last reference. */
1031 ret = SMB_VFS_CLOSE(fsp);
1032 fsp_set_fd(fsp, -1);
1033 if (ret == -1) {
1034 return map_nt_error_from_unix(errno);
1036 return NT_STATUS_OK;
1039 /****************************************************************************
1040 Change the ownership of a file to that of the parent directory.
1041 Do this by fd if possible.
1042 ****************************************************************************/
1044 static void change_file_owner_to_parent_fsp(struct files_struct *parent_fsp,
1045 struct files_struct *fsp)
1047 int ret;
1049 if (parent_fsp->fsp_name->st.st_ex_uid == fsp->fsp_name->st.st_ex_uid) {
1050 /* Already this uid - no need to change. */
1051 DBG_DEBUG("file %s is already owned by uid %u\n",
1052 fsp_str_dbg(fsp),
1053 (unsigned int)fsp->fsp_name->st.st_ex_uid);
1054 return;
1057 become_root();
1058 ret = SMB_VFS_FCHOWN(fsp,
1059 parent_fsp->fsp_name->st.st_ex_uid,
1060 (gid_t)-1);
1061 unbecome_root();
1062 if (ret == -1) {
1063 DBG_ERR("failed to fchown "
1064 "file %s to parent directory uid %u. Error "
1065 "was %s\n",
1066 fsp_str_dbg(fsp),
1067 (unsigned int)parent_fsp->fsp_name->st.st_ex_uid,
1068 strerror(errno));
1069 } else {
1070 DBG_DEBUG("changed new file %s to "
1071 "parent directory uid %u.\n",
1072 fsp_str_dbg(fsp),
1073 (unsigned int)parent_fsp->fsp_name->st.st_ex_uid);
1074 /* Ensure the uid entry is updated. */
1075 fsp->fsp_name->st.st_ex_uid =
1076 parent_fsp->fsp_name->st.st_ex_uid;
1080 static NTSTATUS change_dir_owner_to_parent_fsp(struct files_struct *parent_fsp,
1081 struct files_struct *fsp)
1083 NTSTATUS status;
1084 int ret;
1086 if (parent_fsp->fsp_name->st.st_ex_uid == fsp->fsp_name->st.st_ex_uid) {
1087 /* Already this uid - no need to change. */
1088 DBG_DEBUG("directory %s is already owned by uid %u\n",
1089 fsp_str_dbg(fsp),
1090 (unsigned int)fsp->fsp_name->st.st_ex_uid);
1091 return NT_STATUS_OK;
1094 become_root();
1095 ret = SMB_VFS_FCHOWN(fsp,
1096 parent_fsp->fsp_name->st.st_ex_uid,
1097 (gid_t)-1);
1098 unbecome_root();
1099 if (ret == -1) {
1100 status = map_nt_error_from_unix(errno);
1101 DBG_ERR("failed to chown "
1102 "directory %s to parent directory uid %u. "
1103 "Error was %s\n",
1104 fsp_str_dbg(fsp),
1105 (unsigned int)parent_fsp->fsp_name->st.st_ex_uid,
1106 nt_errstr(status));
1107 return status;
1110 DBG_DEBUG("changed ownership of new "
1111 "directory %s to parent directory uid %u.\n",
1112 fsp_str_dbg(fsp),
1113 (unsigned int)parent_fsp->fsp_name->st.st_ex_uid);
1115 /* Ensure the uid entry is updated. */
1116 fsp->fsp_name->st.st_ex_uid = parent_fsp->fsp_name->st.st_ex_uid;
1118 return NT_STATUS_OK;
1121 /****************************************************************************
1122 Open a file - returning a guaranteed ATOMIC indication of if the
1123 file was created or not.
1124 ****************************************************************************/
1126 static NTSTATUS fd_open_atomic(struct files_struct *dirfsp,
1127 struct smb_filename *smb_fname,
1128 files_struct *fsp,
1129 int flags,
1130 mode_t mode,
1131 bool *file_created)
1133 struct vfs_open_how how = { .flags = flags, .mode = mode, };
1134 NTSTATUS status = NT_STATUS_UNSUCCESSFUL;
1135 NTSTATUS retry_status;
1136 bool file_existed = VALID_STAT(smb_fname->st);
1138 if (!(how.flags & O_CREAT)) {
1140 * We're not creating the file, just pass through.
1142 status = fd_openat(dirfsp, smb_fname, fsp, &how);
1143 *file_created = false;
1144 return status;
1147 if (how.flags & O_EXCL) {
1149 * Fail if already exists, just pass through.
1151 status = fd_openat(dirfsp, smb_fname, fsp, &how);
1154 * Here we've opened with O_CREAT|O_EXCL. If that went
1155 * NT_STATUS_OK, we *know* we created this file.
1157 *file_created = NT_STATUS_IS_OK(status);
1159 return status;
1163 * Now it gets tricky. We have O_CREAT, but not O_EXCL.
1164 * To know absolutely if we created the file or not,
1165 * we can never call O_CREAT without O_EXCL. So if
1166 * we think the file existed, try without O_CREAT|O_EXCL.
1167 * If we think the file didn't exist, try with
1168 * O_CREAT|O_EXCL.
1170 * The big problem here is dangling symlinks. Opening
1171 * without O_NOFOLLOW means both bad symlink
1172 * and missing path return -1, ENOENT from open(). As POSIX
1173 * is pathname based it's not possible to tell
1174 * the difference between these two cases in a
1175 * non-racy way, so change to try only two attempts before
1176 * giving up.
1178 * We don't have this problem for the O_NOFOLLOW
1179 * case as it just returns NT_STATUS_OBJECT_PATH_NOT_FOUND
1180 * mapped from the ELOOP POSIX error.
1183 if (file_existed) {
1184 how.flags = flags & ~(O_CREAT);
1185 retry_status = NT_STATUS_OBJECT_NAME_NOT_FOUND;
1186 } else {
1187 how.flags = flags | O_EXCL;
1188 retry_status = NT_STATUS_OBJECT_NAME_COLLISION;
1191 status = fd_openat(dirfsp, smb_fname, fsp, &how);
1192 if (NT_STATUS_IS_OK(status)) {
1193 *file_created = !file_existed;
1194 return NT_STATUS_OK;
1196 if (NT_STATUS_EQUAL(status, retry_status)) {
1198 file_existed = !file_existed;
1200 DBG_DEBUG("File %s %s. Retry.\n",
1201 fsp_str_dbg(fsp),
1202 file_existed ? "existed" : "did not exist");
1204 if (file_existed) {
1205 how.flags = flags & ~(O_CREAT);
1206 } else {
1207 how.flags = flags | O_EXCL;
1210 status = fd_openat(dirfsp, smb_fname, fsp, &how);
1213 *file_created = (NT_STATUS_IS_OK(status) && !file_existed);
1214 return status;
1217 static NTSTATUS reopen_from_procfd(struct files_struct *fsp,
1218 int flags,
1219 mode_t mode)
1221 struct vfs_open_how how = { .flags = flags, .mode = mode };
1222 struct smb_filename proc_fname;
1223 const char *p = NULL;
1224 char buf[PATH_MAX];
1225 int old_fd;
1226 int new_fd;
1227 NTSTATUS status;
1229 if (!fsp->fsp_flags.have_proc_fds) {
1230 return NT_STATUS_MORE_PROCESSING_REQUIRED;
1233 old_fd = fsp_get_pathref_fd(fsp);
1234 if (old_fd == -1) {
1235 return NT_STATUS_MORE_PROCESSING_REQUIRED;
1238 if (!fsp->fsp_flags.is_pathref) {
1239 DBG_ERR("[%s] is not a pathref\n",
1240 fsp_str_dbg(fsp));
1241 #ifdef DEVELOPER
1242 smb_panic("Not a pathref");
1243 #endif
1244 return NT_STATUS_INVALID_HANDLE;
1247 p = sys_proc_fd_path(old_fd, buf, sizeof(buf));
1248 if (p == NULL) {
1249 return NT_STATUS_NO_MEMORY;
1252 proc_fname = (struct smb_filename) {
1253 .base_name = discard_const_p(char, p),
1256 fsp->fsp_flags.is_pathref = false;
1258 new_fd = SMB_VFS_OPENAT(fsp->conn,
1259 fsp->conn->cwd_fsp,
1260 &proc_fname,
1261 fsp,
1262 &how);
1263 if (new_fd == -1) {
1264 status = map_nt_error_from_unix(errno);
1265 fd_close(fsp);
1266 return status;
1269 status = fd_close(fsp);
1270 if (!NT_STATUS_IS_OK(status)) {
1271 return status;
1274 fsp_set_fd(fsp, new_fd);
1275 return NT_STATUS_OK;
1278 static NTSTATUS reopen_from_fsp(struct files_struct *dirfsp,
1279 struct smb_filename *smb_fname,
1280 struct files_struct *fsp,
1281 int flags,
1282 mode_t mode,
1283 bool *p_file_created)
1285 bool __unused_file_created = false;
1286 NTSTATUS status;
1288 if (p_file_created == NULL) {
1289 p_file_created = &__unused_file_created;
1293 * TODO: should we move this to the VFS layer?
1294 * SMB_VFS_REOPEN_FSP()?
1297 status = reopen_from_procfd(fsp,
1298 flags,
1299 mode);
1300 if (!NT_STATUS_EQUAL(status, NT_STATUS_MORE_PROCESSING_REQUIRED)) {
1301 return status;
1305 * Close the existing pathref fd and set the fsp flag
1306 * is_pathref to false so we get a "normal" fd this time.
1308 status = fd_close(fsp);
1309 if (!NT_STATUS_IS_OK(status)) {
1310 return status;
1313 fsp->fsp_flags.is_pathref = false;
1315 status = fd_open_atomic(
1316 dirfsp,
1317 smb_fname,
1318 fsp,
1319 flags,
1320 mode,
1321 p_file_created);
1322 return status;
1325 /****************************************************************************
1326 Open a file.
1327 ****************************************************************************/
1329 static NTSTATUS open_file(struct smb_request *req,
1330 struct files_struct *dirfsp,
1331 struct smb_filename *smb_fname_atname,
1332 files_struct *fsp,
1333 int flags,
1334 mode_t unx_mode,
1335 uint32_t access_mask, /* client requested access mask. */
1336 uint32_t open_access_mask, /* what we're actually using in the open. */
1337 uint32_t private_flags,
1338 bool *p_file_created)
1340 connection_struct *conn = fsp->conn;
1341 struct smb_filename *smb_fname = fsp->fsp_name;
1342 NTSTATUS status = NT_STATUS_OK;
1343 int accmode = (flags & O_ACCMODE);
1344 int local_flags = flags;
1345 bool file_existed = VALID_STAT(fsp->fsp_name->st);
1346 const uint32_t need_fd_mask =
1347 FILE_READ_DATA |
1348 FILE_WRITE_DATA |
1349 FILE_APPEND_DATA |
1350 FILE_EXECUTE |
1351 SEC_FLAG_SYSTEM_SECURITY;
1352 bool creating = !file_existed && (flags & O_CREAT);
1353 bool truncating = (flags & O_TRUNC);
1354 bool open_fd = false;
1355 bool posix_open = (fsp->posix_flags & FSP_POSIX_FLAGS_OPEN);
1358 * Catch early an attempt to open an existing
1359 * directory as a file.
1361 if (file_existed && S_ISDIR(fsp->fsp_name->st.st_ex_mode)) {
1362 return NT_STATUS_FILE_IS_A_DIRECTORY;
1365 /* Check permissions */
1368 * This code was changed after seeing a client open request
1369 * containing the open mode of (DENY_WRITE/read-only) with
1370 * the 'create if not exist' bit set. The previous code
1371 * would fail to open the file read only on a read-only share
1372 * as it was checking the flags parameter directly against O_RDONLY,
1373 * this was failing as the flags parameter was set to O_RDONLY|O_CREAT.
1374 * JRA.
1377 if (!CAN_WRITE(conn)) {
1378 /* It's a read-only share - fail if we wanted to write. */
1379 if(accmode != O_RDONLY || (flags & O_TRUNC) || (flags & O_APPEND)) {
1380 DEBUG(3,("Permission denied opening %s\n",
1381 smb_fname_str_dbg(smb_fname)));
1382 return NT_STATUS_ACCESS_DENIED;
1384 if (flags & O_CREAT) {
1385 /* We don't want to write - but we must make sure that
1386 O_CREAT doesn't create the file if we have write
1387 access into the directory.
1389 flags &= ~(O_CREAT|O_EXCL);
1390 local_flags &= ~(O_CREAT|O_EXCL);
1395 * This little piece of insanity is inspired by the
1396 * fact that an NT client can open a file for O_RDONLY,
1397 * but set the create disposition to FILE_EXISTS_TRUNCATE.
1398 * If the client *can* write to the file, then it expects to
1399 * truncate the file, even though it is opening for readonly.
1400 * Quicken uses this stupid trick in backup file creation...
1401 * Thanks *greatly* to "David W. Chapman Jr." <dwcjr@inethouston.net>
1402 * for helping track this one down. It didn't bite us in 2.0.x
1403 * as we always opened files read-write in that release. JRA.
1406 if ((accmode == O_RDONLY) && ((flags & O_TRUNC) == O_TRUNC)) {
1407 DEBUG(10,("open_file: truncate requested on read-only open "
1408 "for file %s\n", smb_fname_str_dbg(smb_fname)));
1409 local_flags = (flags & ~O_ACCMODE)|O_RDWR;
1412 if ((open_access_mask & need_fd_mask) || creating || truncating) {
1413 open_fd = true;
1416 if (open_fd) {
1417 const char *wild;
1418 int ret;
1420 #if defined(O_NONBLOCK) && defined(S_ISFIFO)
1422 * We would block on opening a FIFO with no one else on the
1423 * other end. Do what we used to do and add O_NONBLOCK to the
1424 * open flags. JRA.
1427 if (file_existed && S_ISFIFO(smb_fname->st.st_ex_mode)) {
1428 local_flags &= ~O_TRUNC; /* Can't truncate a FIFO. */
1429 local_flags |= O_NONBLOCK;
1430 truncating = false;
1432 #endif
1434 /* Don't create files with Microsoft wildcard characters. */
1435 if (fsp_is_alternate_stream(fsp)) {
1437 * wildcard characters are allowed in stream names
1438 * only test the basefilename
1440 wild = fsp->base_fsp->fsp_name->base_name;
1441 } else {
1442 wild = smb_fname->base_name;
1444 if ((local_flags & O_CREAT) && !file_existed &&
1445 !(fsp->posix_flags & FSP_POSIX_FLAGS_PATHNAMES) &&
1446 ms_has_wild(wild)) {
1447 return NT_STATUS_OBJECT_NAME_INVALID;
1450 /* Can we access this file ? */
1451 if (!fsp_is_alternate_stream(fsp)) {
1452 /* Only do this check on non-stream open. */
1453 if (file_existed) {
1454 status = smbd_check_access_rights_fsp(
1455 dirfsp,
1456 fsp,
1457 false,
1458 open_access_mask);
1460 if (!NT_STATUS_IS_OK(status)) {
1461 DBG_DEBUG("smbd_check_access_rights_fsp"
1462 " on file %s returned %s\n",
1463 fsp_str_dbg(fsp),
1464 nt_errstr(status));
1467 if (!NT_STATUS_IS_OK(status) &&
1468 !NT_STATUS_EQUAL(status,
1469 NT_STATUS_OBJECT_NAME_NOT_FOUND))
1471 return status;
1474 if (NT_STATUS_EQUAL(status,
1475 NT_STATUS_OBJECT_NAME_NOT_FOUND))
1477 DEBUG(10, ("open_file: "
1478 "file %s vanished since we "
1479 "checked for existence.\n",
1480 smb_fname_str_dbg(smb_fname)));
1481 file_existed = false;
1482 SET_STAT_INVALID(fsp->fsp_name->st);
1486 if (!file_existed) {
1487 if (!(local_flags & O_CREAT)) {
1488 /* File didn't exist and no O_CREAT. */
1489 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
1492 status = check_parent_access_fsp(
1493 dirfsp,
1494 SEC_DIR_ADD_FILE);
1495 if (!NT_STATUS_IS_OK(status)) {
1496 DBG_DEBUG("check_parent_access_fsp on "
1497 "directory %s for file %s "
1498 "returned %s\n",
1499 smb_fname_str_dbg(
1500 dirfsp->fsp_name),
1501 smb_fname_str_dbg(smb_fname),
1502 nt_errstr(status));
1503 return status;
1509 * Actually do the open - if O_TRUNC is needed handle it
1510 * below under the share mode lock.
1512 status = reopen_from_fsp(dirfsp,
1513 smb_fname_atname,
1514 fsp,
1515 local_flags & ~O_TRUNC,
1516 unx_mode,
1517 p_file_created);
1518 if (NT_STATUS_EQUAL(status, NT_STATUS_STOPPED_ON_SYMLINK)) {
1520 * Non-O_PATH reopen that hit a race
1521 * condition: Someone has put a symlink where
1522 * we used to have a file. Can't happen with
1523 * O_PATH and reopening from /proc/self/fd/ or
1524 * equivalent.
1526 status = NT_STATUS_OBJECT_NAME_NOT_FOUND;
1528 if (!NT_STATUS_IS_OK(status)) {
1529 DEBUG(3,("Error opening file %s (%s) (local_flags=%d) "
1530 "(flags=%d)\n", smb_fname_str_dbg(smb_fname),
1531 nt_errstr(status),local_flags,flags));
1532 return status;
1535 if (local_flags & O_NONBLOCK) {
1537 * GPFS can return ETIMEDOUT for pread on
1538 * nonblocking file descriptors when files
1539 * migrated to tape need to be recalled. I
1540 * could imagine this happens elsewhere
1541 * too. With blocking file descriptors this
1542 * does not happen.
1544 ret = vfs_set_blocking(fsp, true);
1545 if (ret == -1) {
1546 status = map_nt_error_from_unix(errno);
1547 DBG_WARNING("Could not set fd to blocking: "
1548 "%s\n", strerror(errno));
1549 fd_close(fsp);
1550 return status;
1554 if (*p_file_created) {
1555 /* We created this file. */
1557 bool need_re_stat = false;
1558 /* Do all inheritance work after we've
1559 done a successful fstat call and filled
1560 in the stat struct in fsp->fsp_name. */
1562 /* Inherit the ACL if required */
1563 if (lp_inherit_permissions(SNUM(conn))) {
1564 inherit_access_posix_acl(conn,
1565 dirfsp,
1566 smb_fname,
1567 unx_mode);
1568 need_re_stat = true;
1571 /* Change the owner if required. */
1572 if (lp_inherit_owner(SNUM(conn)) != INHERIT_OWNER_NO) {
1573 change_file_owner_to_parent_fsp(dirfsp, fsp);
1574 need_re_stat = true;
1577 if (need_re_stat) {
1578 status = vfs_stat_fsp(fsp);
1580 * If we have an fd, this stat should succeed.
1582 if (!NT_STATUS_IS_OK(status)) {
1583 DBG_ERR("Error doing fstat on open "
1584 "file %s (%s)\n",
1585 smb_fname_str_dbg(smb_fname),
1586 nt_errstr(status));
1587 fd_close(fsp);
1588 return status;
1592 notify_fname(conn, NOTIFY_ACTION_ADDED,
1593 FILE_NOTIFY_CHANGE_FILE_NAME,
1594 smb_fname->base_name);
1596 } else {
1597 if (!file_existed) {
1598 /* File must exist for a stat open. */
1599 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
1602 if (S_ISLNK(smb_fname->st.st_ex_mode) &&
1603 !posix_open)
1606 * Don't allow stat opens on symlinks directly unless
1607 * it's a POSIX open. Match the return code from
1608 * openat_pathref_fsp().
1610 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
1613 if (!fsp->fsp_flags.is_pathref) {
1615 * There is only one legit case where end up here:
1616 * openat_pathref_fsp() failed to open a symlink, so the
1617 * fsp was created by fsp_new() which doesn't set
1618 * is_pathref. Other then that, we should always have a
1619 * pathref fsp at this point. The subsequent checks
1620 * assert this.
1622 if (!(smb_fname->flags & SMB_FILENAME_POSIX_PATH)) {
1623 DBG_ERR("[%s] is not a POSIX pathname\n",
1624 smb_fname_str_dbg(smb_fname));
1625 return NT_STATUS_INTERNAL_ERROR;
1627 if (!S_ISLNK(smb_fname->st.st_ex_mode)) {
1628 DBG_ERR("[%s] is not a symlink\n",
1629 smb_fname_str_dbg(smb_fname));
1630 return NT_STATUS_INTERNAL_ERROR;
1632 if (fsp_get_pathref_fd(fsp) != -1) {
1633 DBG_ERR("fd for [%s] is not -1: fd [%d]\n",
1634 smb_fname_str_dbg(smb_fname),
1635 fsp_get_pathref_fd(fsp));
1636 return NT_STATUS_INTERNAL_ERROR;
1641 * Access to streams is checked by checking the basefile and
1642 * that has already been checked by check_base_file_access()
1643 * in create_file_unixpath().
1645 if (!fsp_is_alternate_stream(fsp)) {
1646 status = smbd_check_access_rights_fsp(dirfsp,
1647 fsp,
1648 false,
1649 open_access_mask);
1651 if (NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND) &&
1652 posix_open &&
1653 S_ISLNK(smb_fname->st.st_ex_mode)) {
1654 /* This is a POSIX stat open for delete
1655 * or rename on a symlink that points
1656 * nowhere. Allow. */
1657 DEBUG(10,("open_file: allowing POSIX "
1658 "open on bad symlink %s\n",
1659 smb_fname_str_dbg(smb_fname)));
1660 status = NT_STATUS_OK;
1663 if (!NT_STATUS_IS_OK(status)) {
1664 DBG_DEBUG("smbd_check_access_rights_fsp on file "
1665 "%s returned %s\n",
1666 fsp_str_dbg(fsp),
1667 nt_errstr(status));
1668 return status;
1673 fsp->file_id = vfs_file_id_from_sbuf(conn, &smb_fname->st);
1674 fsp->vuid = req ? req->vuid : UID_FIELD_INVALID;
1675 fsp->file_pid = req ? req->smbpid : 0;
1676 fsp->fsp_flags.can_lock = true;
1677 fsp->fsp_flags.can_read = ((access_mask & FILE_READ_DATA) != 0);
1678 fsp->fsp_flags.can_write =
1679 CAN_WRITE(conn) &&
1680 ((access_mask & (FILE_WRITE_DATA | FILE_APPEND_DATA)) != 0);
1681 if (fsp->fsp_name->twrp != 0) {
1682 fsp->fsp_flags.can_write = false;
1684 fsp->print_file = NULL;
1685 fsp->fsp_flags.modified = false;
1686 fsp->sent_oplock_break = NO_BREAK_SENT;
1687 fsp->fsp_flags.is_directory = false;
1688 if (conn->aio_write_behind_list &&
1689 is_in_path(smb_fname->base_name, conn->aio_write_behind_list,
1690 posix_open ? true: conn->case_sensitive)) {
1691 fsp->fsp_flags.aio_write_behind = true;
1694 DEBUG(2,("%s opened file %s read=%s write=%s (numopen=%d)\n",
1695 conn->session_info->unix_info->unix_name,
1696 smb_fname_str_dbg(smb_fname),
1697 BOOLSTR(fsp->fsp_flags.can_read),
1698 BOOLSTR(fsp->fsp_flags.can_write),
1699 conn->num_files_open));
1701 return NT_STATUS_OK;
1704 static bool mask_conflict(
1705 uint32_t new_access,
1706 uint32_t existing_access,
1707 uint32_t access_mask,
1708 uint32_t new_sharemode,
1709 uint32_t existing_sharemode,
1710 uint32_t sharemode_mask)
1712 bool want_access = (new_access & access_mask);
1713 bool allow_existing = (existing_sharemode & sharemode_mask);
1714 bool have_access = (existing_access & access_mask);
1715 bool allow_new = (new_sharemode & sharemode_mask);
1717 if (want_access && !allow_existing) {
1718 DBG_DEBUG("Access request 0x%"PRIx32"/0x%"PRIx32" conflicts "
1719 "with existing sharemode 0x%"PRIx32"/0x%"PRIx32"\n",
1720 new_access,
1721 access_mask,
1722 existing_sharemode,
1723 sharemode_mask);
1724 return true;
1726 if (have_access && !allow_new) {
1727 DBG_DEBUG("Sharemode request 0x%"PRIx32"/0x%"PRIx32" conflicts "
1728 "with existing access 0x%"PRIx32"/0x%"PRIx32"\n",
1729 new_sharemode,
1730 sharemode_mask,
1731 existing_access,
1732 access_mask);
1733 return true;
1735 return false;
1738 /****************************************************************************
1739 Check if we can open a file with a share mode.
1740 Returns True if conflict, False if not.
1741 ****************************************************************************/
1743 static const uint32_t conflicting_access =
1744 FILE_WRITE_DATA|
1745 FILE_APPEND_DATA|
1746 FILE_READ_DATA|
1747 FILE_EXECUTE|
1748 DELETE_ACCESS;
1750 static bool share_conflict(uint32_t e_access_mask,
1751 uint32_t e_share_access,
1752 uint32_t access_mask,
1753 uint32_t share_access)
1755 bool conflict;
1757 DBG_DEBUG("existing access_mask = 0x%"PRIx32", "
1758 "existing share access = 0x%"PRIx32", "
1759 "access_mask = 0x%"PRIx32", "
1760 "share_access = 0x%"PRIx32"\n",
1761 e_access_mask,
1762 e_share_access,
1763 access_mask,
1764 share_access);
1766 if ((e_access_mask & conflicting_access) == 0) {
1767 DBG_DEBUG("No conflict due to "
1768 "existing access_mask = 0x%"PRIx32"\n",
1769 e_access_mask);
1770 return false;
1772 if ((access_mask & conflicting_access) == 0) {
1773 DBG_DEBUG("No conflict due to access_mask = 0x%"PRIx32"\n",
1774 access_mask);
1775 return false;
1778 conflict = mask_conflict(
1779 access_mask, e_access_mask, FILE_WRITE_DATA | FILE_APPEND_DATA,
1780 share_access, e_share_access, FILE_SHARE_WRITE);
1781 conflict |= mask_conflict(
1782 access_mask, e_access_mask, FILE_READ_DATA | FILE_EXECUTE,
1783 share_access, e_share_access, FILE_SHARE_READ);
1784 conflict |= mask_conflict(
1785 access_mask, e_access_mask, DELETE_ACCESS,
1786 share_access, e_share_access, FILE_SHARE_DELETE);
1788 DBG_DEBUG("conflict=%s\n", conflict ? "true" : "false");
1789 return conflict;
1792 #if defined(DEVELOPER)
1794 struct validate_my_share_entries_state {
1795 struct smbd_server_connection *sconn;
1796 struct file_id fid;
1797 struct server_id self;
1800 static bool validate_my_share_entries_fn(
1801 struct share_mode_entry *e,
1802 bool *modified,
1803 void *private_data)
1805 struct validate_my_share_entries_state *state = private_data;
1806 files_struct *fsp;
1808 if (!server_id_equal(&state->self, &e->pid)) {
1809 return false;
1812 if (e->op_mid == 0) {
1813 /* INTERNAL_OPEN_ONLY */
1814 return false;
1817 fsp = file_find_dif(state->sconn, state->fid, e->share_file_id);
1818 if (!fsp) {
1819 DBG_ERR("PANIC : %s\n",
1820 share_mode_str(talloc_tos(), 0, &state->fid, e));
1821 smb_panic("validate_my_share_entries: Cannot match a "
1822 "share entry with an open file\n");
1825 if (((uint16_t)fsp->oplock_type) != e->op_type) {
1826 goto panic;
1829 return false;
1831 panic:
1833 char *str;
1834 DBG_ERR("validate_my_share_entries: PANIC : %s\n",
1835 share_mode_str(talloc_tos(), 0, &state->fid, e));
1836 str = talloc_asprintf(talloc_tos(),
1837 "validate_my_share_entries: "
1838 "file %s, oplock_type = 0x%x, op_type = 0x%x\n",
1839 fsp->fsp_name->base_name,
1840 (unsigned int)fsp->oplock_type,
1841 (unsigned int)e->op_type);
1842 smb_panic(str);
1845 return false;
1847 #endif
1850 * Allowed access mask for stat opens relevant to oplocks
1852 bool is_oplock_stat_open(uint32_t access_mask)
1854 const uint32_t stat_open_bits =
1855 (SYNCHRONIZE_ACCESS|
1856 FILE_READ_ATTRIBUTES|
1857 FILE_WRITE_ATTRIBUTES);
1859 return (((access_mask & stat_open_bits) != 0) &&
1860 ((access_mask & ~stat_open_bits) == 0));
1864 * Allowed access mask for stat opens relevant to leases
1866 bool is_lease_stat_open(uint32_t access_mask)
1868 const uint32_t stat_open_bits =
1869 (SYNCHRONIZE_ACCESS|
1870 FILE_READ_ATTRIBUTES|
1871 FILE_WRITE_ATTRIBUTES|
1872 READ_CONTROL_ACCESS);
1874 return (((access_mask & stat_open_bits) != 0) &&
1875 ((access_mask & ~stat_open_bits) == 0));
1878 struct has_delete_on_close_state {
1879 bool ret;
1882 static bool has_delete_on_close_fn(
1883 struct share_mode_entry *e,
1884 bool *modified,
1885 void *private_data)
1887 struct has_delete_on_close_state *state = private_data;
1888 state->ret = !share_entry_stale_pid(e);
1889 return state->ret;
1892 static bool has_delete_on_close(struct share_mode_lock *lck,
1893 uint32_t name_hash)
1895 struct has_delete_on_close_state state = { .ret = false };
1896 bool ok;
1898 if (!is_delete_on_close_set(lck, name_hash)) {
1899 return false;
1902 ok= share_mode_forall_entries(lck, has_delete_on_close_fn, &state);
1903 if (!ok) {
1904 DBG_DEBUG("share_mode_forall_entries failed\n");
1905 return false;
1907 return state.ret;
1910 static void share_mode_flags_restrict(
1911 struct share_mode_lock *lck,
1912 uint32_t access_mask,
1913 uint32_t share_mode,
1914 uint32_t lease_type)
1916 uint32_t existing_access_mask, existing_share_mode;
1917 uint32_t existing_lease_type;
1919 share_mode_flags_get(
1920 lck,
1921 &existing_access_mask,
1922 &existing_share_mode,
1923 &existing_lease_type);
1925 existing_access_mask |= access_mask;
1926 if (access_mask & conflicting_access) {
1927 existing_share_mode &= share_mode;
1929 existing_lease_type |= lease_type;
1931 share_mode_flags_set(
1932 lck,
1933 existing_access_mask,
1934 existing_share_mode,
1935 existing_lease_type,
1936 NULL);
1939 /****************************************************************************
1940 Deal with share modes
1941 Invariant: Share mode must be locked on entry and exit.
1942 Returns -1 on error, or number of share modes on success (may be zero).
1943 ****************************************************************************/
1945 struct open_mode_check_state {
1946 struct file_id fid;
1947 uint32_t access_mask;
1948 uint32_t share_access;
1949 uint32_t lease_type;
1952 static bool open_mode_check_fn(
1953 struct share_mode_entry *e,
1954 bool *modified,
1955 void *private_data)
1957 struct open_mode_check_state *state = private_data;
1958 bool disconnected, stale;
1959 uint32_t access_mask, share_access, lease_type;
1961 disconnected = server_id_is_disconnected(&e->pid);
1962 if (disconnected) {
1963 return false;
1966 access_mask = state->access_mask | e->access_mask;
1967 share_access = state->share_access;
1968 if (e->access_mask & conflicting_access) {
1969 share_access &= e->share_access;
1971 lease_type = state->lease_type | get_lease_type(e, state->fid);
1973 if ((access_mask == state->access_mask) &&
1974 (share_access == state->share_access) &&
1975 (lease_type == state->lease_type)) {
1976 return false;
1979 stale = share_entry_stale_pid(e);
1980 if (stale) {
1981 return false;
1984 state->access_mask = access_mask;
1985 state->share_access = share_access;
1986 state->lease_type = lease_type;
1988 return false;
1991 static NTSTATUS open_mode_check(connection_struct *conn,
1992 struct file_id fid,
1993 struct share_mode_lock *lck,
1994 uint32_t access_mask,
1995 uint32_t share_access)
1997 struct open_mode_check_state state;
1998 bool ok, conflict;
1999 bool modified = false;
2001 if (is_oplock_stat_open(access_mask)) {
2002 /* Stat open that doesn't trigger oplock breaks or share mode
2003 * checks... ! JRA. */
2004 return NT_STATUS_OK;
2008 * Check if the share modes will give us access.
2011 #if defined(DEVELOPER)
2013 struct validate_my_share_entries_state validate_state = {
2014 .sconn = conn->sconn,
2015 .fid = fid,
2016 .self = messaging_server_id(conn->sconn->msg_ctx),
2018 ok = share_mode_forall_entries(
2019 lck, validate_my_share_entries_fn, &validate_state);
2020 SMB_ASSERT(ok);
2022 #endif
2024 share_mode_flags_get(
2025 lck, &state.access_mask, &state.share_access, NULL);
2027 conflict = share_conflict(
2028 state.access_mask,
2029 state.share_access,
2030 access_mask,
2031 share_access);
2032 if (!conflict) {
2033 DBG_DEBUG("No conflict due to share_mode_flags access\n");
2034 return NT_STATUS_OK;
2037 state = (struct open_mode_check_state) {
2038 .fid = fid,
2039 .share_access = (FILE_SHARE_READ|
2040 FILE_SHARE_WRITE|
2041 FILE_SHARE_DELETE),
2045 * Walk the share mode array to recalculate d->flags
2048 ok = share_mode_forall_entries(lck, open_mode_check_fn, &state);
2049 if (!ok) {
2050 DBG_DEBUG("share_mode_forall_entries failed\n");
2051 return NT_STATUS_INTERNAL_ERROR;
2054 share_mode_flags_set(
2055 lck,
2056 state.access_mask,
2057 state.share_access,
2058 state.lease_type,
2059 &modified);
2060 if (!modified) {
2062 * We only end up here if we had a sharing violation
2063 * from d->flags and have recalculated it.
2065 return NT_STATUS_SHARING_VIOLATION;
2068 conflict = share_conflict(
2069 state.access_mask,
2070 state.share_access,
2071 access_mask,
2072 share_access);
2073 if (!conflict) {
2074 DBG_DEBUG("No conflict due to share_mode_flags access\n");
2075 return NT_STATUS_OK;
2078 return NT_STATUS_SHARING_VIOLATION;
2082 * Send a break message to the oplock holder and delay the open for
2083 * our client.
2086 NTSTATUS send_break_message(struct messaging_context *msg_ctx,
2087 const struct file_id *id,
2088 const struct share_mode_entry *exclusive,
2089 uint16_t break_to)
2091 struct oplock_break_message msg = {
2092 .id = *id,
2093 .share_file_id = exclusive->share_file_id,
2094 .break_to = break_to,
2096 enum ndr_err_code ndr_err;
2097 DATA_BLOB blob;
2098 NTSTATUS status;
2100 if (DEBUGLVL(10)) {
2101 struct server_id_buf buf;
2102 DBG_DEBUG("Sending break message to %s\n",
2103 server_id_str_buf(exclusive->pid, &buf));
2104 NDR_PRINT_DEBUG(oplock_break_message, &msg);
2107 ndr_err = ndr_push_struct_blob(
2108 &blob,
2109 talloc_tos(),
2110 &msg,
2111 (ndr_push_flags_fn_t)ndr_push_oplock_break_message);
2112 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
2113 DBG_WARNING("ndr_push_oplock_break_message failed: %s\n",
2114 ndr_errstr(ndr_err));
2115 return ndr_map_error2ntstatus(ndr_err);
2118 status = messaging_send(
2119 msg_ctx, exclusive->pid, MSG_SMB_BREAK_REQUEST, &blob);
2120 TALLOC_FREE(blob.data);
2121 if (!NT_STATUS_IS_OK(status)) {
2122 DEBUG(3, ("Could not send oplock break message: %s\n",
2123 nt_errstr(status)));
2126 return status;
2129 struct validate_oplock_types_state {
2130 bool valid;
2131 bool batch;
2132 bool ex_or_batch;
2133 bool level2;
2134 bool no_oplock;
2135 uint32_t num_non_stat_opens;
2138 static bool validate_oplock_types_fn(
2139 struct share_mode_entry *e,
2140 bool *modified,
2141 void *private_data)
2143 struct validate_oplock_types_state *state = private_data;
2145 if (e->op_mid == 0) {
2146 /* INTERNAL_OPEN_ONLY */
2147 return false;
2150 if (e->op_type == NO_OPLOCK && is_oplock_stat_open(e->access_mask)) {
2152 * We ignore stat opens in the table - they always
2153 * have NO_OPLOCK and never get or cause breaks. JRA.
2155 return false;
2158 state->num_non_stat_opens += 1;
2160 if (BATCH_OPLOCK_TYPE(e->op_type)) {
2161 /* batch - can only be one. */
2162 if (share_entry_stale_pid(e)) {
2163 DBG_DEBUG("Found stale batch oplock\n");
2164 return false;
2166 if (state->ex_or_batch ||
2167 state->batch ||
2168 state->level2 ||
2169 state->no_oplock) {
2170 DBG_ERR("Bad batch oplock entry\n");
2171 state->valid = false;
2172 return true;
2174 state->batch = true;
2177 if (EXCLUSIVE_OPLOCK_TYPE(e->op_type)) {
2178 if (share_entry_stale_pid(e)) {
2179 DBG_DEBUG("Found stale duplicate oplock\n");
2180 return false;
2182 /* Exclusive or batch - can only be one. */
2183 if (state->ex_or_batch ||
2184 state->level2 ||
2185 state->no_oplock) {
2186 DBG_ERR("Bad exclusive or batch oplock entry\n");
2187 state->valid = false;
2188 return true;
2190 state->ex_or_batch = true;
2193 if (LEVEL_II_OPLOCK_TYPE(e->op_type)) {
2194 if (state->batch || state->ex_or_batch) {
2195 if (share_entry_stale_pid(e)) {
2196 DBG_DEBUG("Found stale LevelII oplock\n");
2197 return false;
2199 DBG_DEBUG("Bad levelII oplock entry\n");
2200 state->valid = false;
2201 return true;
2203 state->level2 = true;
2206 if (e->op_type == NO_OPLOCK) {
2207 if (state->batch || state->ex_or_batch) {
2208 if (share_entry_stale_pid(e)) {
2209 DBG_DEBUG("Found stale NO_OPLOCK entry\n");
2210 return false;
2212 DBG_ERR("Bad no oplock entry\n");
2213 state->valid = false;
2214 return true;
2216 state->no_oplock = true;
2219 return false;
2223 * Do internal consistency checks on the share mode for a file.
2226 static bool validate_oplock_types(struct share_mode_lock *lck)
2228 struct validate_oplock_types_state state = { .valid = true };
2229 static bool skip_validation;
2230 bool validate;
2231 bool ok;
2233 if (skip_validation) {
2234 return true;
2237 validate = lp_parm_bool(-1, "smbd", "validate_oplock_types", false);
2238 if (!validate) {
2239 DBG_DEBUG("smbd:validate_oplock_types not set to yes\n");
2240 skip_validation = true;
2241 return true;
2244 ok = share_mode_forall_entries(lck, validate_oplock_types_fn, &state);
2245 if (!ok) {
2246 DBG_DEBUG("share_mode_forall_entries failed\n");
2247 return false;
2249 if (!state.valid) {
2250 DBG_DEBUG("Got invalid oplock configuration\n");
2251 return false;
2254 if ((state.batch || state.ex_or_batch) &&
2255 (state.num_non_stat_opens != 1)) {
2256 DBG_WARNING("got batch (%d) or ex (%d) non-exclusively "
2257 "(%"PRIu32")\n",
2258 (int)state.batch,
2259 (int)state.ex_or_batch,
2260 state.num_non_stat_opens);
2261 return false;
2264 return true;
2267 static bool is_same_lease(const files_struct *fsp,
2268 const struct share_mode_entry *e,
2269 const struct smb2_lease *lease)
2271 if (e->op_type != LEASE_OPLOCK) {
2272 return false;
2274 if (lease == NULL) {
2275 return false;
2278 return smb2_lease_equal(fsp_client_guid(fsp),
2279 &lease->lease_key,
2280 &e->client_guid,
2281 &e->lease_key);
2284 static bool file_has_brlocks(files_struct *fsp)
2286 struct byte_range_lock *br_lck;
2288 br_lck = brl_get_locks_readonly(fsp);
2289 if (!br_lck)
2290 return false;
2292 return (brl_num_locks(br_lck) > 0);
2295 struct fsp_lease *find_fsp_lease(struct files_struct *new_fsp,
2296 const struct smb2_lease_key *key,
2297 uint32_t current_state,
2298 uint16_t lease_version,
2299 uint16_t lease_epoch)
2301 struct files_struct *fsp;
2304 * TODO: Measure how expensive this loop is with thousands of open
2305 * handles...
2308 for (fsp = file_find_di_first(new_fsp->conn->sconn, new_fsp->file_id, true);
2309 fsp != NULL;
2310 fsp = file_find_di_next(fsp, true)) {
2312 if (fsp == new_fsp) {
2313 continue;
2315 if (fsp->oplock_type != LEASE_OPLOCK) {
2316 continue;
2318 if (smb2_lease_key_equal(&fsp->lease->lease.lease_key, key)) {
2319 fsp->lease->ref_count += 1;
2320 return fsp->lease;
2324 /* Not found - must be leased in another smbd. */
2325 new_fsp->lease = talloc_zero(new_fsp->conn->sconn, struct fsp_lease);
2326 if (new_fsp->lease == NULL) {
2327 return NULL;
2329 new_fsp->lease->ref_count = 1;
2330 new_fsp->lease->sconn = new_fsp->conn->sconn;
2331 new_fsp->lease->lease.lease_key = *key;
2332 new_fsp->lease->lease.lease_state = current_state;
2334 * We internally treat all leases as V2 and update
2335 * the epoch, but when sending breaks it matters if
2336 * the requesting lease was v1 or v2.
2338 new_fsp->lease->lease.lease_version = lease_version;
2339 new_fsp->lease->lease.lease_epoch = lease_epoch;
2340 return new_fsp->lease;
2343 static NTSTATUS try_lease_upgrade(struct files_struct *fsp,
2344 struct share_mode_lock *lck,
2345 const struct GUID *client_guid,
2346 const struct smb2_lease *lease,
2347 uint32_t granted)
2349 bool do_upgrade;
2350 uint32_t current_state, breaking_to_requested, breaking_to_required;
2351 bool breaking;
2352 uint16_t lease_version, epoch;
2353 uint32_t existing, requested;
2354 NTSTATUS status;
2356 status = leases_db_get(
2357 client_guid,
2358 &lease->lease_key,
2359 &fsp->file_id,
2360 &current_state,
2361 &breaking,
2362 &breaking_to_requested,
2363 &breaking_to_required,
2364 &lease_version,
2365 &epoch);
2366 if (!NT_STATUS_IS_OK(status)) {
2367 return status;
2370 fsp->lease = find_fsp_lease(
2371 fsp,
2372 &lease->lease_key,
2373 current_state,
2374 lease_version,
2375 epoch);
2376 if (fsp->lease == NULL) {
2377 DEBUG(1, ("Did not find existing lease for file %s\n",
2378 fsp_str_dbg(fsp)));
2379 return NT_STATUS_NO_MEMORY;
2383 * Upgrade only if the requested lease is a strict upgrade.
2385 existing = current_state;
2386 requested = lease->lease_state;
2389 * Tricky: This test makes sure that "requested" is a
2390 * strict bitwise superset of "existing".
2392 do_upgrade = ((existing & requested) == existing);
2395 * Upgrade only if there's a change.
2397 do_upgrade &= (granted != existing);
2400 * Upgrade only if other leases don't prevent what was asked
2401 * for.
2403 do_upgrade &= (granted == requested);
2406 * only upgrade if we are not in breaking state
2408 do_upgrade &= !breaking;
2410 DEBUG(10, ("existing=%"PRIu32", requested=%"PRIu32", "
2411 "granted=%"PRIu32", do_upgrade=%d\n",
2412 existing, requested, granted, (int)do_upgrade));
2414 if (do_upgrade) {
2415 NTSTATUS set_status;
2417 current_state = granted;
2418 epoch += 1;
2420 set_status = leases_db_set(
2421 client_guid,
2422 &lease->lease_key,
2423 current_state,
2424 breaking,
2425 breaking_to_requested,
2426 breaking_to_required,
2427 lease_version,
2428 epoch);
2430 if (!NT_STATUS_IS_OK(set_status)) {
2431 DBG_DEBUG("leases_db_set failed: %s\n",
2432 nt_errstr(set_status));
2433 return set_status;
2437 fsp_lease_update(fsp);
2439 return NT_STATUS_OK;
2442 static NTSTATUS grant_new_fsp_lease(struct files_struct *fsp,
2443 struct share_mode_lock *lck,
2444 const struct GUID *client_guid,
2445 const struct smb2_lease *lease,
2446 uint32_t granted)
2448 NTSTATUS status;
2450 fsp->lease = talloc_zero(fsp->conn->sconn, struct fsp_lease);
2451 if (fsp->lease == NULL) {
2452 return NT_STATUS_INSUFFICIENT_RESOURCES;
2454 fsp->lease->ref_count = 1;
2455 fsp->lease->sconn = fsp->conn->sconn;
2456 fsp->lease->lease.lease_version = lease->lease_version;
2457 fsp->lease->lease.lease_key = lease->lease_key;
2458 fsp->lease->lease.lease_state = granted;
2459 fsp->lease->lease.lease_epoch = lease->lease_epoch + 1;
2461 status = leases_db_add(client_guid,
2462 &lease->lease_key,
2463 &fsp->file_id,
2464 fsp->lease->lease.lease_state,
2465 fsp->lease->lease.lease_version,
2466 fsp->lease->lease.lease_epoch,
2467 fsp->conn->connectpath,
2468 fsp->fsp_name->base_name,
2469 fsp->fsp_name->stream_name);
2470 if (!NT_STATUS_IS_OK(status)) {
2471 DEBUG(10, ("%s: leases_db_add failed: %s\n", __func__,
2472 nt_errstr(status)));
2473 TALLOC_FREE(fsp->lease);
2474 return NT_STATUS_INSUFFICIENT_RESOURCES;
2478 * We used to set lck->data->modified=true here without
2479 * actually modifying lck->data, triggering a needless
2480 * writeback of lck->data.
2482 * Apart from that writeback, setting modified=true has the
2483 * effect of triggering all waiters for this file to
2484 * retry. This only makes sense if any blocking condition
2485 * (i.e. waiting for a lease to be downgraded or removed) is
2486 * gone. This routine here only adds a lease, so it will never
2487 * free up resources that blocked waiters can now claim. So
2488 * that second effect also does not matter in this
2489 * routine. Thus setting lck->data->modified=true does not
2490 * need to be done here.
2493 return NT_STATUS_OK;
2496 static NTSTATUS grant_fsp_lease(struct files_struct *fsp,
2497 struct share_mode_lock *lck,
2498 const struct smb2_lease *lease,
2499 uint32_t granted)
2501 const struct GUID *client_guid = fsp_client_guid(fsp);
2502 NTSTATUS status;
2504 status = try_lease_upgrade(fsp, lck, client_guid, lease, granted);
2506 if (NT_STATUS_EQUAL(status, NT_STATUS_NOT_FOUND)) {
2507 status = grant_new_fsp_lease(
2508 fsp, lck, client_guid, lease, granted);
2511 return status;
2514 static int map_lease_type_to_oplock(uint32_t lease_type)
2516 int result = NO_OPLOCK;
2518 switch (lease_type) {
2519 case SMB2_LEASE_READ|SMB2_LEASE_WRITE|SMB2_LEASE_HANDLE:
2520 result = BATCH_OPLOCK|EXCLUSIVE_OPLOCK;
2521 break;
2522 case SMB2_LEASE_READ|SMB2_LEASE_WRITE:
2523 result = EXCLUSIVE_OPLOCK;
2524 break;
2525 case SMB2_LEASE_READ|SMB2_LEASE_HANDLE:
2526 case SMB2_LEASE_READ:
2527 result = LEVEL_II_OPLOCK;
2528 break;
2531 return result;
2534 struct delay_for_oplock_state {
2535 struct files_struct *fsp;
2536 const struct smb2_lease *lease;
2537 bool will_overwrite;
2538 uint32_t delay_mask;
2539 bool first_open_attempt;
2540 bool got_handle_lease;
2541 bool got_oplock;
2542 bool have_other_lease;
2543 uint32_t total_lease_types;
2544 bool delay;
2547 static bool delay_for_oplock_fn(
2548 struct share_mode_entry *e,
2549 bool *modified,
2550 void *private_data)
2552 struct delay_for_oplock_state *state = private_data;
2553 struct files_struct *fsp = state->fsp;
2554 const struct smb2_lease *lease = state->lease;
2555 bool e_is_lease = (e->op_type == LEASE_OPLOCK);
2556 uint32_t e_lease_type = SMB2_LEASE_NONE;
2557 uint32_t break_to;
2558 bool lease_is_breaking = false;
2560 if (e_is_lease) {
2561 NTSTATUS status;
2563 if (lease != NULL) {
2564 bool our_lease = is_same_lease(fsp, e, lease);
2565 if (our_lease) {
2566 DBG_DEBUG("Ignoring our own lease\n");
2567 return false;
2571 status = leases_db_get(
2572 &e->client_guid,
2573 &e->lease_key,
2574 &fsp->file_id,
2575 &e_lease_type, /* current_state */
2576 &lease_is_breaking,
2577 NULL, /* breaking_to_requested */
2578 NULL, /* breaking_to_required */
2579 NULL, /* lease_version */
2580 NULL); /* epoch */
2583 * leases_db_get() can return NT_STATUS_NOT_FOUND
2584 * if the share_mode_entry e is stale and the
2585 * lease record was already removed. In this case return
2586 * false so the traverse continues.
2589 if (NT_STATUS_EQUAL(status, NT_STATUS_NOT_FOUND) &&
2590 share_entry_stale_pid(e))
2592 struct GUID_txt_buf guid_strbuf;
2593 struct file_id_buf file_id_strbuf;
2594 DBG_DEBUG("leases_db_get for client_guid [%s] "
2595 "lease_key [%"PRIu64"/%"PRIu64"] "
2596 "file_id [%s] failed for stale "
2597 "share_mode_entry\n",
2598 GUID_buf_string(&e->client_guid, &guid_strbuf),
2599 e->lease_key.data[0],
2600 e->lease_key.data[1],
2601 file_id_str_buf(fsp->file_id, &file_id_strbuf));
2602 return false;
2604 if (!NT_STATUS_IS_OK(status)) {
2605 struct GUID_txt_buf guid_strbuf;
2606 struct file_id_buf file_id_strbuf;
2607 DBG_ERR("leases_db_get for client_guid [%s] "
2608 "lease_key [%"PRIu64"/%"PRIu64"] "
2609 "file_id [%s] failed: %s\n",
2610 GUID_buf_string(&e->client_guid, &guid_strbuf),
2611 e->lease_key.data[0],
2612 e->lease_key.data[1],
2613 file_id_str_buf(fsp->file_id, &file_id_strbuf),
2614 nt_errstr(status));
2615 smb_panic("leases_db_get() failed");
2617 } else {
2618 e_lease_type = get_lease_type(e, fsp->file_id);
2621 if (((e_lease_type & ~state->total_lease_types) != 0) &&
2622 !share_entry_stale_pid(e))
2624 state->total_lease_types |= e_lease_type;
2627 if (!state->got_handle_lease &&
2628 ((e_lease_type & SMB2_LEASE_HANDLE) != 0) &&
2629 !share_entry_stale_pid(e)) {
2630 state->got_handle_lease = true;
2633 if (!state->got_oplock &&
2634 (e->op_type != LEASE_OPLOCK) &&
2635 !share_entry_stale_pid(e)) {
2636 state->got_oplock = true;
2639 if (!state->have_other_lease &&
2640 !is_same_lease(fsp, e, lease) &&
2641 !share_entry_stale_pid(e)) {
2642 state->have_other_lease = true;
2645 if (e_is_lease && is_lease_stat_open(fsp->access_mask)) {
2646 return false;
2649 break_to = e_lease_type & ~state->delay_mask;
2651 if (state->will_overwrite) {
2652 break_to &= ~(SMB2_LEASE_HANDLE|SMB2_LEASE_READ);
2655 DBG_DEBUG("e_lease_type %u, will_overwrite: %u\n",
2656 (unsigned)e_lease_type,
2657 (unsigned)state->will_overwrite);
2659 if ((e_lease_type & ~break_to) == 0) {
2660 if (lease_is_breaking) {
2661 state->delay = true;
2663 return false;
2666 if (share_entry_stale_pid(e)) {
2667 return false;
2670 if (state->will_overwrite) {
2672 * If we break anyway break to NONE directly.
2673 * Otherwise vfs_set_filelen() will trigger the
2674 * break.
2676 break_to &= ~(SMB2_LEASE_READ|SMB2_LEASE_WRITE);
2679 if (!e_is_lease) {
2681 * Oplocks only support breaking to R or NONE.
2683 break_to &= ~(SMB2_LEASE_HANDLE|SMB2_LEASE_WRITE);
2686 DBG_DEBUG("breaking from %d to %d\n",
2687 (int)e_lease_type,
2688 (int)break_to);
2689 send_break_message(
2690 fsp->conn->sconn->msg_ctx, &fsp->file_id, e, break_to);
2691 if (e_lease_type & state->delay_mask) {
2692 state->delay = true;
2694 if (lease_is_breaking && !state->first_open_attempt) {
2695 state->delay = true;
2698 return false;
2701 static NTSTATUS delay_for_oplock(files_struct *fsp,
2702 int oplock_request,
2703 const struct smb2_lease *lease,
2704 struct share_mode_lock *lck,
2705 bool have_sharing_violation,
2706 uint32_t create_disposition,
2707 bool first_open_attempt,
2708 int *poplock_type,
2709 uint32_t *pgranted)
2711 struct delay_for_oplock_state state = {
2712 .fsp = fsp,
2713 .lease = lease,
2714 .first_open_attempt = first_open_attempt,
2716 uint32_t requested;
2717 uint32_t granted;
2718 int oplock_type;
2719 bool ok;
2721 *poplock_type = NO_OPLOCK;
2722 *pgranted = 0;
2724 if (fsp->fsp_flags.is_directory) {
2726 * No directory leases yet
2728 SMB_ASSERT(oplock_request == NO_OPLOCK);
2729 if (have_sharing_violation) {
2730 return NT_STATUS_SHARING_VIOLATION;
2732 return NT_STATUS_OK;
2735 if (oplock_request == LEASE_OPLOCK) {
2736 if (lease == NULL) {
2738 * The SMB2 layer should have checked this
2740 return NT_STATUS_INTERNAL_ERROR;
2743 requested = lease->lease_state;
2744 } else {
2745 requested = map_oplock_to_lease_type(
2746 oplock_request & ~SAMBA_PRIVATE_OPLOCK_MASK);
2749 share_mode_flags_get(lck, NULL, NULL, &state.total_lease_types);
2751 if (is_oplock_stat_open(fsp->access_mask)) {
2752 goto grant;
2755 state.delay_mask = have_sharing_violation ?
2756 SMB2_LEASE_HANDLE : SMB2_LEASE_WRITE;
2758 switch (create_disposition) {
2759 case FILE_SUPERSEDE:
2760 case FILE_OVERWRITE:
2761 case FILE_OVERWRITE_IF:
2762 state.will_overwrite = true;
2763 break;
2764 default:
2765 state.will_overwrite = false;
2766 break;
2769 state.total_lease_types = SMB2_LEASE_NONE;
2770 ok = share_mode_forall_entries(lck, delay_for_oplock_fn, &state);
2771 if (!ok) {
2772 return NT_STATUS_INTERNAL_ERROR;
2775 if (state.delay) {
2776 return NT_STATUS_RETRY;
2779 grant:
2780 if (have_sharing_violation) {
2781 return NT_STATUS_SHARING_VIOLATION;
2784 granted = requested;
2786 if (oplock_request == LEASE_OPLOCK) {
2787 if (lp_kernel_oplocks(SNUM(fsp->conn))) {
2788 DEBUG(10, ("No lease granted because kernel oplocks are enabled\n"));
2789 granted = SMB2_LEASE_NONE;
2791 if ((granted & (SMB2_LEASE_READ|SMB2_LEASE_WRITE)) == 0) {
2792 DEBUG(10, ("No read or write lease requested\n"));
2793 granted = SMB2_LEASE_NONE;
2795 if (granted == SMB2_LEASE_WRITE) {
2796 DEBUG(10, ("pure write lease requested\n"));
2797 granted = SMB2_LEASE_NONE;
2799 if (granted == (SMB2_LEASE_WRITE|SMB2_LEASE_HANDLE)) {
2800 DEBUG(10, ("write and handle lease requested\n"));
2801 granted = SMB2_LEASE_NONE;
2805 if (lp_locking(fsp->conn->params) && file_has_brlocks(fsp)) {
2806 DBG_DEBUG("file %s has byte range locks\n",
2807 fsp_str_dbg(fsp));
2808 granted &= ~SMB2_LEASE_READ;
2811 if (state.have_other_lease) {
2813 * Can grant only one writer
2815 granted &= ~SMB2_LEASE_WRITE;
2818 if ((granted & SMB2_LEASE_READ) && !(granted & SMB2_LEASE_WRITE)) {
2819 bool allow_level2 =
2820 (global_client_caps & CAP_LEVEL_II_OPLOCKS) &&
2821 lp_level2_oplocks(SNUM(fsp->conn));
2823 if (!allow_level2) {
2824 granted = SMB2_LEASE_NONE;
2828 if (oplock_request == LEASE_OPLOCK) {
2829 if (state.got_oplock) {
2830 granted &= ~SMB2_LEASE_HANDLE;
2833 oplock_type = LEASE_OPLOCK;
2834 } else {
2835 if (state.got_handle_lease) {
2836 granted = SMB2_LEASE_NONE;
2840 * Reflect possible downgrades from:
2841 * - map_lease_type_to_oplock() => "RH" to just LEVEL_II
2843 oplock_type = map_lease_type_to_oplock(granted);
2844 granted = map_oplock_to_lease_type(oplock_type);
2847 state.total_lease_types |= granted;
2850 uint32_t acc, sh, ls;
2851 share_mode_flags_get(lck, &acc, &sh, &ls);
2852 ls = state.total_lease_types;
2853 share_mode_flags_set(lck, acc, sh, ls, NULL);
2856 DBG_DEBUG("oplock type 0x%x granted (%s%s%s)(0x%x), on file %s, "
2857 "requested 0x%x (%s%s%s)(0x%x) => total (%s%s%s)(0x%x)\n",
2858 fsp->oplock_type,
2859 granted & SMB2_LEASE_READ ? "R":"",
2860 granted & SMB2_LEASE_WRITE ? "W":"",
2861 granted & SMB2_LEASE_HANDLE ? "H":"",
2862 granted,
2863 fsp_str_dbg(fsp),
2864 oplock_request,
2865 requested & SMB2_LEASE_READ ? "R":"",
2866 requested & SMB2_LEASE_WRITE ? "W":"",
2867 requested & SMB2_LEASE_HANDLE ? "H":"",
2868 requested,
2869 state.total_lease_types & SMB2_LEASE_READ ? "R":"",
2870 state.total_lease_types & SMB2_LEASE_WRITE ? "W":"",
2871 state.total_lease_types & SMB2_LEASE_HANDLE ? "H":"",
2872 state.total_lease_types);
2874 *poplock_type = oplock_type;
2875 *pgranted = granted;
2876 return NT_STATUS_OK;
2879 static NTSTATUS handle_share_mode_lease(
2880 files_struct *fsp,
2881 struct share_mode_lock *lck,
2882 uint32_t create_disposition,
2883 uint32_t access_mask,
2884 uint32_t share_access,
2885 int oplock_request,
2886 const struct smb2_lease *lease,
2887 bool first_open_attempt,
2888 int *poplock_type,
2889 uint32_t *pgranted)
2891 bool sharing_violation = false;
2892 NTSTATUS status;
2894 *poplock_type = NO_OPLOCK;
2895 *pgranted = 0;
2897 status = open_mode_check(
2898 fsp->conn, fsp->file_id, lck, access_mask, share_access);
2899 if (NT_STATUS_EQUAL(status, NT_STATUS_SHARING_VIOLATION)) {
2900 sharing_violation = true;
2901 status = NT_STATUS_OK; /* handled later */
2904 if (!NT_STATUS_IS_OK(status)) {
2905 return status;
2908 if (oplock_request == INTERNAL_OPEN_ONLY) {
2909 if (sharing_violation) {
2910 DBG_DEBUG("Sharing violation for internal open\n");
2911 return NT_STATUS_SHARING_VIOLATION;
2915 * Internal opens never do oplocks or leases. We don't
2916 * need to go through delay_for_oplock().
2918 return NT_STATUS_OK;
2921 status = delay_for_oplock(
2922 fsp,
2923 oplock_request,
2924 lease,
2925 lck,
2926 sharing_violation,
2927 create_disposition,
2928 first_open_attempt,
2929 poplock_type,
2930 pgranted);
2931 if (!NT_STATUS_IS_OK(status)) {
2932 return status;
2935 return NT_STATUS_OK;
2938 static bool request_timed_out(struct smb_request *req, struct timeval timeout)
2940 struct timeval now, end_time;
2941 GetTimeOfDay(&now);
2942 end_time = timeval_sum(&req->request_time, &timeout);
2943 return (timeval_compare(&end_time, &now) < 0);
2946 struct defer_open_state {
2947 struct smbXsrv_connection *xconn;
2948 uint64_t mid;
2951 static void defer_open_done(struct tevent_req *req);
2954 * Defer an open and watch a locking.tdb record
2956 * This defers an open that gets rescheduled once the locking.tdb record watch
2957 * is triggered by a change to the record.
2959 * It is used to defer opens that triggered an oplock break and for the SMB1
2960 * sharing violation delay.
2962 static void defer_open(struct share_mode_lock *lck,
2963 struct timeval timeout,
2964 struct smb_request *req,
2965 struct file_id id)
2967 struct deferred_open_record *open_rec = NULL;
2968 struct timeval abs_timeout;
2969 struct defer_open_state *watch_state;
2970 struct tevent_req *watch_req;
2971 struct timeval_buf tvbuf1, tvbuf2;
2972 struct file_id_buf fbuf;
2973 bool ok;
2975 abs_timeout = timeval_sum(&req->request_time, &timeout);
2977 DBG_DEBUG("request time [%s] timeout [%s] mid [%" PRIu64 "] "
2978 "file_id [%s]\n",
2979 timeval_str_buf(&req->request_time, false, true, &tvbuf1),
2980 timeval_str_buf(&abs_timeout, false, true, &tvbuf2),
2981 req->mid,
2982 file_id_str_buf(id, &fbuf));
2984 open_rec = talloc_zero(NULL, struct deferred_open_record);
2985 if (open_rec == NULL) {
2986 TALLOC_FREE(lck);
2987 exit_server("talloc failed");
2990 watch_state = talloc(open_rec, struct defer_open_state);
2991 if (watch_state == NULL) {
2992 exit_server("talloc failed");
2994 watch_state->xconn = req->xconn;
2995 watch_state->mid = req->mid;
2997 DBG_DEBUG("deferring mid %" PRIu64 "\n", req->mid);
2999 watch_req = share_mode_watch_send(
3000 watch_state,
3001 req->sconn->ev_ctx,
3002 lck,
3003 (struct server_id){0});
3004 if (watch_req == NULL) {
3005 exit_server("Could not watch share mode record");
3007 tevent_req_set_callback(watch_req, defer_open_done, watch_state);
3009 ok = tevent_req_set_endtime(watch_req, req->sconn->ev_ctx, abs_timeout);
3010 if (!ok) {
3011 exit_server("tevent_req_set_endtime failed");
3014 ok = push_deferred_open_message_smb(req, timeout, id, open_rec);
3015 if (!ok) {
3016 TALLOC_FREE(lck);
3017 exit_server("push_deferred_open_message_smb failed");
3021 static void defer_open_done(struct tevent_req *req)
3023 struct defer_open_state *state = tevent_req_callback_data(
3024 req, struct defer_open_state);
3025 NTSTATUS status;
3026 bool ret;
3028 status = share_mode_watch_recv(req, NULL, NULL);
3029 TALLOC_FREE(req);
3030 if (!NT_STATUS_IS_OK(status)) {
3031 DEBUG(5, ("dbwrap_watched_watch_recv returned %s\n",
3032 nt_errstr(status)));
3034 * Even if it failed, retry anyway. TODO: We need a way to
3035 * tell a re-scheduled open about that error.
3039 DEBUG(10, ("scheduling mid %llu\n", (unsigned long long)state->mid));
3041 ret = schedule_deferred_open_message_smb(state->xconn, state->mid);
3042 SMB_ASSERT(ret);
3043 TALLOC_FREE(state);
3047 * Actually attempt the kernel oplock polling open.
3050 static void poll_open_fn(struct tevent_context *ev,
3051 struct tevent_timer *te,
3052 struct timeval current_time,
3053 void *private_data)
3055 struct deferred_open_record *open_rec = talloc_get_type_abort(
3056 private_data, struct deferred_open_record);
3057 bool ok;
3059 TALLOC_FREE(open_rec->watch_req);
3061 ok = schedule_deferred_open_message_smb(
3062 open_rec->xconn, open_rec->mid);
3063 if (!ok) {
3064 exit_server("schedule_deferred_open_message_smb failed");
3066 DBG_DEBUG("timer fired. Retrying open !\n");
3069 static void poll_open_done(struct tevent_req *subreq);
3071 struct poll_open_setup_watcher_state {
3072 TALLOC_CTX *mem_ctx;
3073 struct tevent_context *ev_ctx;
3074 struct tevent_req *watch_req;
3077 static void poll_open_setup_watcher_fn(struct share_mode_lock *lck,
3078 void *private_data)
3080 struct poll_open_setup_watcher_state *state =
3081 (struct poll_open_setup_watcher_state *)private_data;
3083 if (!validate_oplock_types(lck)) {
3084 smb_panic("validate_oplock_types failed");
3087 state->watch_req = share_mode_watch_send(
3088 state->mem_ctx,
3089 state->ev_ctx,
3090 lck,
3091 (struct server_id) {0});
3092 if (state->watch_req == NULL) {
3093 DBG_WARNING("share_mode_watch_send failed\n");
3094 return;
3099 * Reschedule an open for 1 second from now, if not timed out.
3101 static bool setup_poll_open(
3102 struct smb_request *req,
3103 const struct file_id *id,
3104 struct timeval max_timeout,
3105 struct timeval interval)
3107 static struct file_id zero_id = {};
3108 bool ok;
3109 struct deferred_open_record *open_rec = NULL;
3110 struct timeval endtime, next_interval;
3111 struct file_id_buf ftmp;
3113 if (request_timed_out(req, max_timeout)) {
3114 return false;
3117 open_rec = talloc_zero(NULL, struct deferred_open_record);
3118 if (open_rec == NULL) {
3119 DBG_WARNING("talloc failed\n");
3120 return false;
3122 open_rec->xconn = req->xconn;
3123 open_rec->mid = req->mid;
3126 * Make sure open_rec->te does not come later than the
3127 * request's maximum endtime.
3130 endtime = timeval_sum(&req->request_time, &max_timeout);
3131 next_interval = timeval_current_ofs(interval.tv_sec, interval.tv_usec);
3132 next_interval = timeval_min(&endtime, &next_interval);
3134 open_rec->te = tevent_add_timer(
3135 req->sconn->ev_ctx,
3136 open_rec,
3137 next_interval,
3138 poll_open_fn,
3139 open_rec);
3140 if (open_rec->te == NULL) {
3141 DBG_WARNING("tevent_add_timer failed\n");
3142 TALLOC_FREE(open_rec);
3143 return false;
3146 if (id != NULL) {
3147 struct poll_open_setup_watcher_state wstate = {
3148 .mem_ctx = open_rec,
3149 .ev_ctx = req->sconn->ev_ctx,
3151 NTSTATUS status;
3153 status = share_mode_do_locked_vfs_denied(*id,
3154 poll_open_setup_watcher_fn,
3155 &wstate);
3156 if (NT_STATUS_IS_OK(status)) {
3157 if (wstate.watch_req == NULL) {
3158 DBG_WARNING("share_mode_watch_send failed\n");
3159 TALLOC_FREE(open_rec);
3160 return false;
3162 open_rec->watch_req = wstate.watch_req;
3163 tevent_req_set_callback(open_rec->watch_req,
3164 poll_open_done,
3165 open_rec);
3166 } else if (!NT_STATUS_EQUAL(status, NT_STATUS_NOT_FOUND)) {
3167 DBG_WARNING("share_mode_do_locked_vfs_denied failed - %s\n",
3168 nt_errstr(status));
3169 TALLOC_FREE(open_rec);
3170 return false;
3172 } else {
3173 id = &zero_id;
3176 ok = push_deferred_open_message_smb(req, max_timeout, *id, open_rec);
3177 if (!ok) {
3178 DBG_WARNING("push_deferred_open_message_smb failed\n");
3179 TALLOC_FREE(open_rec);
3180 return false;
3183 DBG_DEBUG("poll request time [%s] mid [%" PRIu64 "] file_id [%s]\n",
3184 timeval_string(talloc_tos(), &req->request_time, false),
3185 req->mid,
3186 file_id_str_buf(*id, &ftmp));
3188 return true;
3191 static void poll_open_done(struct tevent_req *subreq)
3193 struct deferred_open_record *open_rec = tevent_req_callback_data(
3194 subreq, struct deferred_open_record);
3195 NTSTATUS status;
3196 bool ok;
3198 status = share_mode_watch_recv(subreq, NULL, NULL);
3199 TALLOC_FREE(subreq);
3200 open_rec->watch_req = NULL;
3201 TALLOC_FREE(open_rec->te);
3203 DBG_DEBUG("dbwrap_watched_watch_recv returned %s\n",
3204 nt_errstr(status));
3206 ok = schedule_deferred_open_message_smb(
3207 open_rec->xconn, open_rec->mid);
3208 if (!ok) {
3209 exit_server("schedule_deferred_open_message_smb failed");
3213 bool defer_smb1_sharing_violation(struct smb_request *req)
3215 bool ok;
3216 int timeout_usecs;
3218 if (!lp_defer_sharing_violations()) {
3219 return false;
3223 * Try every 200msec up to (by default) one second. To be
3224 * precise, according to behaviour note <247> in [MS-CIFS],
3225 * the server tries 5 times. But up to one second should be
3226 * close enough.
3229 timeout_usecs = lp_parm_int(
3230 SNUM(req->conn),
3231 "smbd",
3232 "sharedelay",
3233 SHARING_VIOLATION_USEC_WAIT);
3235 ok = setup_poll_open(
3236 req,
3237 NULL,
3238 (struct timeval) { .tv_usec = timeout_usecs },
3239 (struct timeval) { .tv_usec = 200000 });
3240 return ok;
3243 /****************************************************************************
3244 On overwrite open ensure that the attributes match.
3245 ****************************************************************************/
3247 static bool open_match_attributes(connection_struct *conn,
3248 uint32_t old_dos_attr,
3249 uint32_t new_dos_attr,
3250 mode_t new_unx_mode,
3251 mode_t *returned_unx_mode)
3253 uint32_t noarch_old_dos_attr, noarch_new_dos_attr;
3255 noarch_old_dos_attr = (old_dos_attr & ~FILE_ATTRIBUTE_ARCHIVE);
3256 noarch_new_dos_attr = (new_dos_attr & ~FILE_ATTRIBUTE_ARCHIVE);
3258 if((noarch_old_dos_attr == 0 && noarch_new_dos_attr != 0) ||
3259 (noarch_old_dos_attr != 0 && ((noarch_old_dos_attr & noarch_new_dos_attr) == noarch_old_dos_attr))) {
3260 *returned_unx_mode = new_unx_mode;
3261 } else {
3262 *returned_unx_mode = (mode_t)0;
3265 DEBUG(10,("open_match_attributes: old_dos_attr = 0x%x, "
3266 "new_dos_attr = 0x%x "
3267 "returned_unx_mode = 0%o\n",
3268 (unsigned int)old_dos_attr,
3269 (unsigned int)new_dos_attr,
3270 (unsigned int)*returned_unx_mode ));
3272 /* If we're mapping SYSTEM and HIDDEN ensure they match. */
3273 if (lp_map_system(SNUM(conn)) || lp_store_dos_attributes(SNUM(conn))) {
3274 if ((old_dos_attr & FILE_ATTRIBUTE_SYSTEM) &&
3275 !(new_dos_attr & FILE_ATTRIBUTE_SYSTEM)) {
3276 return False;
3279 if (lp_map_hidden(SNUM(conn)) || lp_store_dos_attributes(SNUM(conn))) {
3280 if ((old_dos_attr & FILE_ATTRIBUTE_HIDDEN) &&
3281 !(new_dos_attr & FILE_ATTRIBUTE_HIDDEN)) {
3282 return False;
3285 return True;
3288 static void schedule_defer_open(struct share_mode_lock *lck,
3289 struct file_id id,
3290 struct smb_request *req)
3292 /* This is a relative time, added to the absolute
3293 request_time value to get the absolute timeout time.
3294 Note that if this is the second or greater time we enter
3295 this codepath for this particular request mid then
3296 request_time is left as the absolute time of the *first*
3297 time this request mid was processed. This is what allows
3298 the request to eventually time out. */
3300 struct timeval timeout;
3302 /* Normally the smbd we asked should respond within
3303 * OPLOCK_BREAK_TIMEOUT seconds regardless of whether
3304 * the client did, give twice the timeout as a safety
3305 * measure here in case the other smbd is stuck
3306 * somewhere else. */
3308 timeout = timeval_set(OPLOCK_BREAK_TIMEOUT*2, 0);
3310 if (request_timed_out(req, timeout)) {
3311 return;
3314 defer_open(lck, timeout, req, id);
3317 /****************************************************************************
3318 Reschedule an open call that went asynchronous.
3319 ****************************************************************************/
3321 static void schedule_async_open_timer(struct tevent_context *ev,
3322 struct tevent_timer *te,
3323 struct timeval current_time,
3324 void *private_data)
3326 exit_server("async open timeout");
3329 static void schedule_async_open(struct smb_request *req)
3331 struct deferred_open_record *open_rec = NULL;
3332 struct timeval timeout = timeval_set(20, 0);
3333 bool ok;
3335 if (request_timed_out(req, timeout)) {
3336 return;
3339 open_rec = talloc_zero(NULL, struct deferred_open_record);
3340 if (open_rec == NULL) {
3341 exit_server("deferred_open_record_create failed");
3343 open_rec->async_open = true;
3345 ok = push_deferred_open_message_smb(
3346 req, timeout, (struct file_id){0}, open_rec);
3347 if (!ok) {
3348 exit_server("push_deferred_open_message_smb failed");
3351 open_rec->te = tevent_add_timer(req->sconn->ev_ctx,
3352 req,
3353 timeval_current_ofs(20, 0),
3354 schedule_async_open_timer,
3355 open_rec);
3356 if (open_rec->te == NULL) {
3357 exit_server("tevent_add_timer failed");
3361 static NTSTATUS check_and_store_share_mode(
3362 struct files_struct *fsp,
3363 struct smb_request *req,
3364 struct share_mode_lock *lck,
3365 uint32_t create_disposition,
3366 uint32_t access_mask,
3367 uint32_t share_access,
3368 int oplock_request,
3369 const struct smb2_lease *lease,
3370 bool first_open_attempt)
3372 NTSTATUS status;
3373 int oplock_type = NO_OPLOCK;
3374 uint32_t granted_lease = 0;
3375 const struct smb2_lease_key *lease_key = NULL;
3376 bool delete_on_close;
3377 bool ok;
3379 /* Get the types we need to examine. */
3380 if (!validate_oplock_types(lck)) {
3381 smb_panic("validate_oplock_types failed");
3384 delete_on_close = has_delete_on_close(lck, fsp->name_hash);
3385 if (delete_on_close) {
3386 return NT_STATUS_DELETE_PENDING;
3389 status = handle_share_mode_lease(fsp,
3390 lck,
3391 create_disposition,
3392 access_mask,
3393 share_access,
3394 oplock_request,
3395 lease,
3396 first_open_attempt,
3397 &oplock_type,
3398 &granted_lease);
3399 if (NT_STATUS_EQUAL(status, NT_STATUS_RETRY)) {
3400 schedule_defer_open(lck, fsp->file_id, req);
3401 return NT_STATUS_SHARING_VIOLATION;
3403 if (!NT_STATUS_IS_OK(status)) {
3404 return status;
3407 if (oplock_type == LEASE_OPLOCK) {
3408 lease_key = &lease->lease_key;
3411 share_mode_flags_restrict(lck, access_mask, share_access, 0);
3413 ok = set_share_mode(lck,
3414 fsp,
3415 get_current_uid(fsp->conn),
3416 req ? req->mid : 0,
3417 oplock_type,
3418 lease_key,
3419 share_access,
3420 access_mask);
3421 if (!ok) {
3422 return NT_STATUS_NO_MEMORY;
3425 if (oplock_type == LEASE_OPLOCK) {
3426 status = grant_fsp_lease(fsp, lck, lease, granted_lease);
3427 if (!NT_STATUS_IS_OK(status)) {
3428 del_share_mode(lck, fsp);
3429 return status;
3432 DBG_DEBUG("lease_state=%d\n", fsp->lease->lease.lease_state);
3435 fsp->oplock_type = oplock_type;
3437 return NT_STATUS_OK;
3440 /****************************************************************************
3441 Work out what access_mask to use from what the client sent us.
3442 ****************************************************************************/
3444 static NTSTATUS smbd_calculate_maximum_allowed_access_fsp(
3445 struct files_struct *dirfsp,
3446 struct files_struct *fsp,
3447 bool use_privs,
3448 uint32_t *p_access_mask)
3450 struct security_descriptor *sd = NULL;
3451 uint32_t access_granted = 0;
3452 uint32_t dosattrs;
3453 NTSTATUS status;
3455 /* Cope with symlinks */
3456 if (fsp == NULL || fsp_get_pathref_fd(fsp) == -1) {
3457 *p_access_mask = FILE_GENERIC_ALL;
3458 return NT_STATUS_OK;
3461 /* Cope with fake/printer fsp's. */
3462 if (fsp->fake_file_handle != NULL || fsp->print_file != NULL) {
3463 *p_access_mask = FILE_GENERIC_ALL;
3464 return NT_STATUS_OK;
3467 if (!use_privs && (get_current_uid(fsp->conn) == (uid_t)0)) {
3468 *p_access_mask |= FILE_GENERIC_ALL;
3469 return NT_STATUS_OK;
3472 status = SMB_VFS_FGET_NT_ACL(metadata_fsp(fsp),
3473 (SECINFO_OWNER |
3474 SECINFO_GROUP |
3475 SECINFO_DACL),
3476 talloc_tos(),
3477 &sd);
3479 if (NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
3481 * File did not exist
3483 *p_access_mask = FILE_GENERIC_ALL;
3484 return NT_STATUS_OK;
3486 if (!NT_STATUS_IS_OK(status)) {
3487 DBG_ERR("Could not get acl on file %s: %s\n",
3488 fsp_str_dbg(fsp),
3489 nt_errstr(status));
3490 return status;
3494 * If we can access the path to this file, by
3495 * default we have FILE_READ_ATTRIBUTES from the
3496 * containing directory. See the section:
3497 * "Algorithm to Check Access to an Existing File"
3498 * in MS-FSA.pdf.
3500 * se_file_access_check()
3501 * also takes care of owner WRITE_DAC and READ_CONTROL.
3503 status = se_file_access_check(sd,
3504 get_current_nttok(fsp->conn),
3505 use_privs,
3506 (*p_access_mask & ~FILE_READ_ATTRIBUTES),
3507 &access_granted);
3509 TALLOC_FREE(sd);
3511 if (!NT_STATUS_IS_OK(status)) {
3512 DBG_ERR("Status %s on file %s: "
3513 "when calculating maximum access\n",
3514 nt_errstr(status),
3515 fsp_str_dbg(fsp));
3516 return status;
3519 *p_access_mask = (access_granted | FILE_READ_ATTRIBUTES);
3521 if (!(access_granted & DELETE_ACCESS)) {
3522 if (can_delete_file_in_directory(fsp->conn,
3523 dirfsp,
3524 fsp->fsp_name)) {
3525 *p_access_mask |= DELETE_ACCESS;
3529 dosattrs = fdos_mode(fsp);
3530 if (IS_DOS_READONLY(dosattrs) || !CAN_WRITE(fsp->conn)) {
3531 *p_access_mask &= ~(FILE_GENERIC_WRITE | DELETE_ACCESS);
3534 return NT_STATUS_OK;
3537 NTSTATUS smbd_calculate_access_mask_fsp(struct files_struct *dirfsp,
3538 struct files_struct *fsp,
3539 bool use_privs,
3540 uint32_t access_mask,
3541 uint32_t *access_mask_out)
3543 NTSTATUS status;
3544 uint32_t orig_access_mask = access_mask;
3545 uint32_t rejected_share_access;
3547 if (access_mask & SEC_MASK_INVALID) {
3548 DBG_DEBUG("access_mask [%8x] contains invalid bits\n",
3549 access_mask);
3550 return NT_STATUS_ACCESS_DENIED;
3554 * Convert GENERIC bits to specific bits.
3557 se_map_generic(&access_mask, &file_generic_mapping);
3559 /* Calculate MAXIMUM_ALLOWED_ACCESS if requested. */
3560 if (access_mask & MAXIMUM_ALLOWED_ACCESS) {
3562 status = smbd_calculate_maximum_allowed_access_fsp(
3563 dirfsp,
3564 fsp,
3565 use_privs,
3566 &access_mask);
3568 if (!NT_STATUS_IS_OK(status)) {
3569 return status;
3572 access_mask &= fsp->conn->share_access;
3575 rejected_share_access = access_mask & ~(fsp->conn->share_access);
3577 if (rejected_share_access) {
3578 DBG_INFO("Access denied on file %s: "
3579 "rejected by share access mask[0x%08X] "
3580 "orig[0x%08X] mapped[0x%08X] reject[0x%08X]\n",
3581 fsp_str_dbg(fsp),
3582 fsp->conn->share_access,
3583 orig_access_mask, access_mask,
3584 rejected_share_access);
3585 return NT_STATUS_ACCESS_DENIED;
3588 *access_mask_out = access_mask;
3589 return NT_STATUS_OK;
3592 /****************************************************************************
3593 Remove the deferred open entry under lock.
3594 ****************************************************************************/
3596 /****************************************************************************
3597 Return true if this is a state pointer to an asynchronous create.
3598 ****************************************************************************/
3600 bool is_deferred_open_async(const struct deferred_open_record *rec)
3602 return rec->async_open;
3605 static bool clear_ads(uint32_t create_disposition)
3607 bool ret = false;
3609 switch (create_disposition) {
3610 case FILE_SUPERSEDE:
3611 case FILE_OVERWRITE_IF:
3612 case FILE_OVERWRITE:
3613 ret = true;
3614 break;
3615 default:
3616 break;
3618 return ret;
3621 static int disposition_to_open_flags(uint32_t create_disposition)
3623 int ret = 0;
3626 * Currently we're using FILE_SUPERSEDE as the same as
3627 * FILE_OVERWRITE_IF but they really are
3628 * different. FILE_SUPERSEDE deletes an existing file
3629 * (requiring delete access) then recreates it.
3632 switch (create_disposition) {
3633 case FILE_SUPERSEDE:
3634 case FILE_OVERWRITE_IF:
3636 * If file exists replace/overwrite. If file doesn't
3637 * exist create.
3639 ret = O_CREAT|O_TRUNC;
3640 break;
3642 case FILE_OPEN:
3644 * If file exists open. If file doesn't exist error.
3646 ret = 0;
3647 break;
3649 case FILE_OVERWRITE:
3651 * If file exists overwrite. If file doesn't exist
3652 * error.
3654 ret = O_TRUNC;
3655 break;
3657 case FILE_CREATE:
3659 * If file exists error. If file doesn't exist create.
3661 ret = O_CREAT|O_EXCL;
3662 break;
3664 case FILE_OPEN_IF:
3666 * If file exists open. If file doesn't exist create.
3668 ret = O_CREAT;
3669 break;
3671 return ret;
3674 static int calculate_open_access_flags(uint32_t access_mask,
3675 uint32_t private_flags)
3677 bool need_write, need_read;
3680 * Note that we ignore the append flag as append does not
3681 * mean the same thing under DOS and Unix.
3684 need_write = (access_mask & (FILE_WRITE_DATA | FILE_APPEND_DATA));
3685 if (!need_write) {
3686 return O_RDONLY;
3689 /* DENY_DOS opens are always underlying read-write on the
3690 file handle, no matter what the requested access mask
3691 says. */
3693 need_read =
3694 ((private_flags & NTCREATEX_FLAG_DENY_DOS) ||
3695 access_mask & (FILE_READ_ATTRIBUTES|FILE_READ_DATA|
3696 FILE_READ_EA|FILE_EXECUTE));
3698 if (!need_read) {
3699 return O_WRONLY;
3701 return O_RDWR;
3704 struct open_ntcreate_lock_state {
3705 struct share_mode_entry_prepare_state prepare_state;
3706 struct files_struct *fsp;
3707 const char *object_type;
3708 struct smb_request *req;
3709 uint32_t create_disposition;
3710 uint32_t access_mask;
3711 uint32_t share_access;
3712 int oplock_request;
3713 const struct smb2_lease *lease;
3714 bool first_open_attempt;
3715 bool keep_locked;
3716 NTSTATUS status;
3717 struct timespec write_time;
3718 share_mode_entry_prepare_unlock_fn_t cleanup_fn;
3721 static void open_ntcreate_lock_add_entry(struct share_mode_lock *lck,
3722 bool *keep_locked,
3723 void *private_data)
3725 struct open_ntcreate_lock_state *state =
3726 (struct open_ntcreate_lock_state *)private_data;
3729 * By default drop the g_lock again if we leave the
3730 * tdb chainlock.
3732 *keep_locked = false;
3734 state->status = check_and_store_share_mode(state->fsp,
3735 state->req,
3736 lck,
3737 state->create_disposition,
3738 state->access_mask,
3739 state->share_access,
3740 state->oplock_request,
3741 state->lease,
3742 state->first_open_attempt);
3743 if (!NT_STATUS_IS_OK(state->status)) {
3744 return;
3747 state->write_time = get_share_mode_write_time(lck);
3750 * keep the g_lock while existing the tdb chainlock,
3751 * we we're asked to, which mean we'll keep
3752 * the share_mode_lock during object creation,
3753 * or setting delete on close.
3755 *keep_locked = state->keep_locked;
3758 static void open_ntcreate_lock_cleanup_oplock(struct share_mode_lock *lck,
3759 void *private_data)
3761 struct open_ntcreate_lock_state *state =
3762 (struct open_ntcreate_lock_state *)private_data;
3763 bool ok;
3765 ok = remove_share_oplock(lck, state->fsp);
3766 if (!ok) {
3767 DBG_ERR("Could not remove oplock for %s %s\n",
3768 state->object_type, fsp_str_dbg(state->fsp));
3772 static void open_ntcreate_lock_cleanup_entry(struct share_mode_lock *lck,
3773 void *private_data)
3775 struct open_ntcreate_lock_state *state =
3776 (struct open_ntcreate_lock_state *)private_data;
3777 bool ok;
3779 ok = del_share_mode(lck, state->fsp);
3780 if (!ok) {
3781 DBG_ERR("Could not delete share entry for %s %s\n",
3782 state->object_type, fsp_str_dbg(state->fsp));
3786 /****************************************************************************
3787 Open a file with a share mode. Passed in an already created files_struct *.
3788 ****************************************************************************/
3790 static NTSTATUS open_file_ntcreate(connection_struct *conn,
3791 struct smb_request *req,
3792 uint32_t access_mask, /* access bits (FILE_READ_DATA etc.) */
3793 uint32_t share_access, /* share constants (FILE_SHARE_READ etc) */
3794 uint32_t create_disposition, /* FILE_OPEN_IF etc. */
3795 uint32_t create_options, /* options such as delete on close. */
3796 uint32_t new_dos_attributes, /* attributes used for new file. */
3797 int oplock_request, /* internal Samba oplock codes. */
3798 const struct smb2_lease *lease,
3799 /* Information (FILE_EXISTS etc.) */
3800 uint32_t private_flags, /* Samba specific flags. */
3801 struct smb_filename *parent_dir_fname, /* parent. */
3802 struct smb_filename *smb_fname_atname, /* atname relative to parent. */
3803 int *pinfo,
3804 files_struct *fsp)
3806 struct smb_filename *smb_fname = fsp->fsp_name;
3807 int flags=0;
3808 int flags2=0;
3809 bool file_existed = VALID_STAT(smb_fname->st);
3810 bool def_acl = False;
3811 bool posix_open = False;
3812 bool new_file_created = False;
3813 bool first_open_attempt = true;
3814 NTSTATUS fsp_open = NT_STATUS_ACCESS_DENIED;
3815 mode_t new_unx_mode = (mode_t)0;
3816 mode_t unx_mode = (mode_t)0;
3817 int info;
3818 uint32_t existing_dos_attributes = 0;
3819 struct open_ntcreate_lock_state lck_state = {};
3820 bool keep_locked = false;
3821 uint32_t open_access_mask = access_mask;
3822 NTSTATUS status;
3823 SMB_STRUCT_STAT saved_stat = smb_fname->st;
3824 struct timespec old_write_time;
3825 bool setup_poll = false;
3826 NTSTATUS ulstatus;
3828 if (conn->printer) {
3830 * Printers are handled completely differently.
3831 * Most of the passed parameters are ignored.
3834 if (pinfo) {
3835 *pinfo = FILE_WAS_CREATED;
3838 DEBUG(10, ("open_file_ntcreate: printer open fname=%s\n",
3839 smb_fname_str_dbg(smb_fname)));
3841 if (!req) {
3842 DEBUG(0,("open_file_ntcreate: printer open without "
3843 "an SMB request!\n"));
3844 return NT_STATUS_INTERNAL_ERROR;
3847 return print_spool_open(fsp, smb_fname->base_name,
3848 req->vuid);
3851 if (new_dos_attributes & FILE_FLAG_POSIX_SEMANTICS) {
3852 posix_open = True;
3853 unx_mode = (mode_t)(new_dos_attributes & ~FILE_FLAG_POSIX_SEMANTICS);
3854 new_dos_attributes = 0;
3855 } else {
3856 /* Windows allows a new file to be created and
3857 silently removes a FILE_ATTRIBUTE_DIRECTORY
3858 sent by the client. Do the same. */
3860 new_dos_attributes &= ~FILE_ATTRIBUTE_DIRECTORY;
3862 /* We add FILE_ATTRIBUTE_ARCHIVE to this as this mode is only used if the file is
3863 * created new. */
3864 unx_mode = unix_mode(
3865 conn,
3866 new_dos_attributes | FILE_ATTRIBUTE_ARCHIVE,
3867 smb_fname,
3868 parent_dir_fname->fsp);
3871 DEBUG(10, ("open_file_ntcreate: fname=%s, dos_attrs=0x%x "
3872 "access_mask=0x%x share_access=0x%x "
3873 "create_disposition = 0x%x create_options=0x%x "
3874 "unix mode=0%o oplock_request=%d private_flags = 0x%x\n",
3875 smb_fname_str_dbg(smb_fname), new_dos_attributes,
3876 access_mask, share_access, create_disposition,
3877 create_options, (unsigned int)unx_mode, oplock_request,
3878 (unsigned int)private_flags));
3880 if (req == NULL) {
3881 /* Ensure req == NULL means INTERNAL_OPEN_ONLY */
3882 SMB_ASSERT(oplock_request == INTERNAL_OPEN_ONLY);
3883 } else {
3884 /* And req != NULL means no INTERNAL_OPEN_ONLY */
3885 SMB_ASSERT(((oplock_request & INTERNAL_OPEN_ONLY) == 0));
3889 * Only non-internal opens can be deferred at all
3892 if (req) {
3893 struct deferred_open_record *open_rec;
3894 if (get_deferred_open_message_state(req, NULL, &open_rec)) {
3896 /* If it was an async create retry, the file
3897 didn't exist. */
3899 if (is_deferred_open_async(open_rec)) {
3900 SET_STAT_INVALID(smb_fname->st);
3901 file_existed = false;
3904 /* Ensure we don't reprocess this message. */
3905 remove_deferred_open_message_smb(req->xconn, req->mid);
3907 first_open_attempt = false;
3911 if (!posix_open) {
3912 new_dos_attributes &= SAMBA_ATTRIBUTES_MASK;
3913 if (file_existed) {
3915 * Only use stored DOS attributes for checks
3916 * against requested attributes (below via
3917 * open_match_attributes()), cf bug #11992
3918 * for details. -slow
3920 uint32_t attr = 0;
3922 status = vfs_fget_dos_attributes(smb_fname->fsp, &attr);
3923 if (NT_STATUS_IS_OK(status)) {
3924 existing_dos_attributes = attr;
3929 /* ignore any oplock requests if oplocks are disabled */
3930 if (!lp_oplocks(SNUM(conn)) ||
3931 IS_VETO_OPLOCK_PATH(conn, smb_fname->base_name)) {
3932 /* Mask off everything except the private Samba bits. */
3933 oplock_request &= SAMBA_PRIVATE_OPLOCK_MASK;
3936 /* this is for OS/2 long file names - say we don't support them */
3937 if (req != NULL && !req->posix_pathnames &&
3938 strstr(smb_fname->base_name,".+,;=[].")) {
3939 /* OS/2 Workplace shell fix may be main code stream in a later
3940 * release. */
3941 DEBUG(5,("open_file_ntcreate: OS/2 long filenames are not "
3942 "supported.\n"));
3943 if (use_nt_status()) {
3944 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3946 return NT_STATUS_DOS(ERRDOS, ERRcannotopen);
3949 switch( create_disposition ) {
3950 case FILE_OPEN:
3951 /* If file exists open. If file doesn't exist error. */
3952 if (!file_existed) {
3953 DEBUG(5,("open_file_ntcreate: FILE_OPEN "
3954 "requested for file %s and file "
3955 "doesn't exist.\n",
3956 smb_fname_str_dbg(smb_fname)));
3957 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3959 break;
3961 case FILE_OVERWRITE:
3962 /* If file exists overwrite. If file doesn't exist
3963 * error. */
3964 if (!file_existed) {
3965 DEBUG(5,("open_file_ntcreate: FILE_OVERWRITE "
3966 "requested for file %s and file "
3967 "doesn't exist.\n",
3968 smb_fname_str_dbg(smb_fname) ));
3969 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3971 break;
3973 case FILE_CREATE:
3974 /* If file exists error. If file doesn't exist
3975 * create. */
3976 if (file_existed) {
3977 DEBUG(5,("open_file_ntcreate: FILE_CREATE "
3978 "requested for file %s and file "
3979 "already exists.\n",
3980 smb_fname_str_dbg(smb_fname)));
3981 if (S_ISDIR(smb_fname->st.st_ex_mode)) {
3982 return NT_STATUS_FILE_IS_A_DIRECTORY;
3984 return NT_STATUS_OBJECT_NAME_COLLISION;
3986 break;
3988 case FILE_SUPERSEDE:
3989 case FILE_OVERWRITE_IF:
3990 case FILE_OPEN_IF:
3991 break;
3992 default:
3993 return NT_STATUS_INVALID_PARAMETER;
3996 flags2 = disposition_to_open_flags(create_disposition);
3998 /* We only care about matching attributes on file exists and
3999 * overwrite. */
4001 if (!posix_open && file_existed &&
4002 ((create_disposition == FILE_OVERWRITE) ||
4003 (create_disposition == FILE_OVERWRITE_IF))) {
4004 if (!open_match_attributes(conn, existing_dos_attributes,
4005 new_dos_attributes,
4006 unx_mode, &new_unx_mode)) {
4007 DEBUG(5,("open_file_ntcreate: attributes mismatch "
4008 "for file %s (%x %x) (0%o, 0%o)\n",
4009 smb_fname_str_dbg(smb_fname),
4010 existing_dos_attributes,
4011 new_dos_attributes,
4012 (unsigned int)smb_fname->st.st_ex_mode,
4013 (unsigned int)unx_mode ));
4014 return NT_STATUS_ACCESS_DENIED;
4018 status = smbd_calculate_access_mask_fsp(parent_dir_fname->fsp,
4019 smb_fname->fsp,
4020 false,
4021 access_mask,
4022 &access_mask);
4023 if (!NT_STATUS_IS_OK(status)) {
4024 DBG_DEBUG("smbd_calculate_access_mask_fsp "
4025 "on file %s returned %s\n",
4026 smb_fname_str_dbg(smb_fname),
4027 nt_errstr(status));
4028 return status;
4031 open_access_mask = access_mask;
4033 if (flags2 & O_TRUNC) {
4034 open_access_mask |= FILE_WRITE_DATA; /* This will cause oplock breaks. */
4037 if (file_existed) {
4039 * stat opens on existing files don't get oplocks.
4040 * They can get leases.
4042 * Note that we check for stat open on the *open_access_mask*,
4043 * i.e. the access mask we actually used to do the open,
4044 * not the one the client asked for (which is in
4045 * fsp->access_mask). This is due to the fact that
4046 * FILE_OVERWRITE and FILE_OVERWRITE_IF add in O_TRUNC,
4047 * which adds FILE_WRITE_DATA to open_access_mask.
4049 if (is_oplock_stat_open(open_access_mask) && lease == NULL) {
4050 oplock_request = NO_OPLOCK;
4054 DEBUG(10, ("open_file_ntcreate: fname=%s, after mapping "
4055 "access_mask=0x%x\n", smb_fname_str_dbg(smb_fname),
4056 access_mask));
4059 * Note that we ignore the append flag as append does not
4060 * mean the same thing under DOS and Unix.
4063 flags = calculate_open_access_flags(access_mask, private_flags);
4066 * Currently we only look at FILE_WRITE_THROUGH for create options.
4069 #if defined(O_SYNC)
4070 if ((create_options & FILE_WRITE_THROUGH) && lp_strict_sync(SNUM(conn))) {
4071 flags2 |= O_SYNC;
4073 #endif /* O_SYNC */
4075 if (posix_open && (access_mask & FILE_APPEND_DATA)) {
4076 flags2 |= O_APPEND;
4079 if (!posix_open && !CAN_WRITE(conn)) {
4081 * We should really return a permission denied error if either
4082 * O_CREAT or O_TRUNC are set, but for compatibility with
4083 * older versions of Samba we just AND them out.
4085 flags2 &= ~(O_CREAT|O_TRUNC);
4089 * With kernel oplocks the open breaking an oplock
4090 * blocks until the oplock holder has given up the
4091 * oplock or closed the file. We prevent this by always
4092 * trying to open the file with O_NONBLOCK (see "man
4093 * fcntl" on Linux).
4095 * If a process that doesn't use the smbd open files
4096 * database or communication methods holds a kernel
4097 * oplock we must periodically poll for available open
4098 * using O_NONBLOCK.
4100 flags2 |= O_NONBLOCK;
4103 * Ensure we can't write on a read-only share or file.
4106 if (flags != O_RDONLY && file_existed &&
4107 (!CAN_WRITE(conn) || IS_DOS_READONLY(existing_dos_attributes))) {
4108 DEBUG(5,("open_file_ntcreate: write access requested for "
4109 "file %s on read only %s\n",
4110 smb_fname_str_dbg(smb_fname),
4111 !CAN_WRITE(conn) ? "share" : "file" ));
4112 return NT_STATUS_ACCESS_DENIED;
4115 if (VALID_STAT(smb_fname->st)) {
4117 * Only try and create a file id before open
4118 * for an existing file. For a file being created
4119 * this won't do anything useful until the file
4120 * exists and has a valid stat struct.
4122 fsp->file_id = vfs_file_id_from_sbuf(conn, &smb_fname->st);
4124 fh_set_private_options(fsp->fh, private_flags);
4125 fsp->access_mask = open_access_mask; /* We change this to the
4126 * requested access_mask after
4127 * the open is done. */
4128 if (posix_open) {
4129 fsp->posix_flags |= FSP_POSIX_FLAGS_ALL;
4132 if ((create_options & FILE_DELETE_ON_CLOSE) &&
4133 (flags2 & O_CREAT) &&
4134 !file_existed) {
4135 /* Delete on close semantics for new files. */
4136 status = can_set_delete_on_close(fsp,
4137 new_dos_attributes);
4138 if (!NT_STATUS_IS_OK(status)) {
4139 fd_close(fsp);
4140 return status;
4145 * Ensure we pay attention to default ACLs on directories if required.
4148 if ((flags2 & O_CREAT) && lp_inherit_acls(SNUM(conn)) &&
4149 (def_acl = directory_has_default_acl_fsp(parent_dir_fname->fsp)))
4151 unx_mode = (0777 & lp_create_mask(SNUM(conn)));
4154 DEBUG(4,("calling open_file with flags=0x%X flags2=0x%X mode=0%o, "
4155 "access_mask = 0x%x, open_access_mask = 0x%x\n",
4156 (unsigned int)flags, (unsigned int)flags2,
4157 (unsigned int)unx_mode, (unsigned int)access_mask,
4158 (unsigned int)open_access_mask));
4160 fsp_open = open_file(req,
4161 parent_dir_fname->fsp,
4162 smb_fname_atname,
4163 fsp,
4164 flags|flags2,
4165 unx_mode,
4166 access_mask,
4167 open_access_mask,
4168 private_flags,
4169 &new_file_created);
4170 if (NT_STATUS_EQUAL(fsp_open, NT_STATUS_NETWORK_BUSY)) {
4171 if (file_existed && S_ISFIFO(fsp->fsp_name->st.st_ex_mode)) {
4172 DEBUG(10, ("FIFO busy\n"));
4173 return NT_STATUS_NETWORK_BUSY;
4175 if (req == NULL) {
4176 DEBUG(10, ("Internal open busy\n"));
4177 return NT_STATUS_NETWORK_BUSY;
4180 * This handles the kernel oplock case:
4182 * the file has an active kernel oplock and the open() returned
4183 * EWOULDBLOCK/EAGAIN which maps to NETWORK_BUSY.
4185 * "Samba locking.tdb oplocks" are handled below after acquiring
4186 * the sharemode lock with get_share_mode_lock().
4188 setup_poll = true;
4191 if (NT_STATUS_EQUAL(fsp_open, NT_STATUS_RETRY)) {
4193 * EINTR from the open(2) syscall. Just setup a retry
4194 * in a bit. We can't use the sys_write() tight retry
4195 * loop here, as we might have to actually deal with
4196 * lease-break signals to avoid a deadlock.
4198 setup_poll = true;
4201 if (setup_poll) {
4203 * Retry once a second. If there's a share_mode_lock
4204 * around, also wait for it in case it was smbd
4205 * holding that kernel oplock that can quickly tell us
4206 * the oplock got removed.
4209 setup_poll_open(
4210 req,
4211 &fsp->file_id,
4212 timeval_set(OPLOCK_BREAK_TIMEOUT*2, 0),
4213 timeval_set(1, 0));
4215 return NT_STATUS_SHARING_VIOLATION;
4218 if (!NT_STATUS_IS_OK(fsp_open)) {
4219 bool wait_for_aio = NT_STATUS_EQUAL(
4220 fsp_open, NT_STATUS_MORE_PROCESSING_REQUIRED);
4221 if (wait_for_aio) {
4222 schedule_async_open(req);
4224 return fsp_open;
4227 if (new_file_created) {
4229 * As we atomically create using O_CREAT|O_EXCL,
4230 * then if new_file_created is true, then
4231 * file_existed *MUST* have been false (even
4232 * if the file was previously detected as being
4233 * there).
4235 file_existed = false;
4238 if (file_existed && !check_same_dev_ino(&saved_stat, &smb_fname->st)) {
4240 * The file did exist, but some other (local or NFS)
4241 * process either renamed/unlinked and re-created the
4242 * file with different dev/ino after we walked the path,
4243 * but before we did the open. We could retry the
4244 * open but it's a rare enough case it's easier to
4245 * just fail the open to prevent creating any problems
4246 * in the open file db having the wrong dev/ino key.
4248 fd_close(fsp);
4249 DBG_WARNING("file %s - dev/ino mismatch. "
4250 "Old (dev=%ju, ino=%ju). "
4251 "New (dev=%ju, ino=%ju). Failing open "
4252 "with NT_STATUS_ACCESS_DENIED.\n",
4253 smb_fname_str_dbg(smb_fname),
4254 (uintmax_t)saved_stat.st_ex_dev,
4255 (uintmax_t)saved_stat.st_ex_ino,
4256 (uintmax_t)smb_fname->st.st_ex_dev,
4257 (uintmax_t)smb_fname->st.st_ex_ino);
4258 return NT_STATUS_ACCESS_DENIED;
4261 old_write_time = smb_fname->st.st_ex_mtime;
4264 * Deal with the race condition where two smbd's detect the
4265 * file doesn't exist and do the create at the same time. One
4266 * of them will win and set a share mode, the other (ie. this
4267 * one) should check if the requested share mode for this
4268 * create is allowed.
4272 * Now the file exists and fsp is successfully opened,
4273 * fsp->dev and fsp->inode are valid and should replace the
4274 * dev=0,inode=0 from a non existent file. Spotted by
4275 * Nadav Danieli <nadavd@exanet.com>. JRA.
4278 if (new_file_created) {
4279 info = FILE_WAS_CREATED;
4280 } else {
4281 if (flags2 & O_TRUNC) {
4282 info = FILE_WAS_OVERWRITTEN;
4283 } else {
4284 info = FILE_WAS_OPENED;
4289 * If we created a new file, overwrite an existing one
4290 * or going to delete it later, we should keep
4291 * the share_mode_lock (g_lock) until we call
4292 * share_mode_entry_prepare_unlock()
4294 if (info != FILE_WAS_OPENED) {
4295 keep_locked = true;
4296 } else if (create_options & FILE_DELETE_ON_CLOSE) {
4297 keep_locked = true;
4300 lck_state = (struct open_ntcreate_lock_state) {
4301 .fsp = fsp,
4302 .object_type = "file",
4303 .req = req,
4304 .create_disposition = create_disposition,
4305 .access_mask = access_mask,
4306 .share_access = share_access,
4307 .oplock_request = oplock_request,
4308 .lease = lease,
4309 .first_open_attempt = first_open_attempt,
4310 .keep_locked = keep_locked,
4313 status = share_mode_entry_prepare_lock_add(&lck_state.prepare_state,
4314 fsp->file_id,
4315 conn->connectpath,
4316 smb_fname,
4317 &old_write_time,
4318 open_ntcreate_lock_add_entry,
4319 &lck_state);
4320 if (!NT_STATUS_IS_OK(status)) {
4321 DBG_ERR("share_mode_entry_prepare_lock_add() failed for %s - %s\n",
4322 smb_fname_str_dbg(smb_fname), nt_errstr(status));
4323 fd_close(fsp);
4324 return status;
4327 status = lck_state.status;
4328 if (!NT_STATUS_IS_OK(status)) {
4329 fd_close(fsp);
4330 return status;
4334 * From here we need to use 'goto unlock;' instead of return !!!
4337 if (fsp->oplock_type != NO_OPLOCK && fsp->oplock_type != LEASE_OPLOCK) {
4339 * Now ask for kernel oplocks
4340 * and cleanup on failure.
4342 status = set_file_oplock(fsp);
4343 if (!NT_STATUS_IS_OK(status)) {
4345 * Could not get the kernel oplock
4347 lck_state.cleanup_fn =
4348 open_ntcreate_lock_cleanup_oplock;
4349 fsp->oplock_type = NO_OPLOCK;
4353 /* Should we atomically (to the client at least) truncate ? */
4354 if ((!new_file_created) &&
4355 (flags2 & O_TRUNC) &&
4356 (S_ISREG(fsp->fsp_name->st.st_ex_mode))) {
4357 int ret;
4359 ret = SMB_VFS_FTRUNCATE(fsp, 0);
4360 if (ret != 0) {
4361 status = map_nt_error_from_unix(errno);
4362 lck_state.cleanup_fn =
4363 open_ntcreate_lock_cleanup_entry;
4364 goto unlock;
4366 notify_fname(fsp->conn, NOTIFY_ACTION_MODIFIED,
4367 FILE_NOTIFY_CHANGE_SIZE
4368 | FILE_NOTIFY_CHANGE_ATTRIBUTES,
4369 fsp->fsp_name->base_name);
4373 * We have the share entry *locked*.....
4376 /* Delete streams if create_disposition requires it */
4377 if (!new_file_created &&
4378 clear_ads(create_disposition) &&
4379 !fsp_is_alternate_stream(fsp)) {
4380 status = delete_all_streams(conn, smb_fname);
4381 if (!NT_STATUS_IS_OK(status)) {
4382 lck_state.cleanup_fn =
4383 open_ntcreate_lock_cleanup_entry;
4384 goto unlock;
4388 if (!fsp->fsp_flags.is_pathref &&
4389 fsp_get_io_fd(fsp) != -1 &&
4390 lp_kernel_share_modes(SNUM(conn)))
4392 int ret;
4394 * Beware: streams implementing VFS modules may
4395 * implement streams in a way that fsp will have the
4396 * basefile open in the fsp fd, so lacking a distinct
4397 * fd for the stream the file-system sharemode will
4398 * apply on the basefile which is wrong. The actual
4399 * check is deferred to the VFS module implementing
4400 * the file-system sharemode call.
4402 ret = SMB_VFS_FILESYSTEM_SHAREMODE(fsp,
4403 share_access,
4404 access_mask);
4405 if (ret == -1){
4406 status = NT_STATUS_SHARING_VIOLATION;
4407 lck_state.cleanup_fn =
4408 open_ntcreate_lock_cleanup_entry;
4409 goto unlock;
4412 fsp->fsp_flags.kernel_share_modes_taken = true;
4416 * At this point onwards, we can guarantee that the share entry
4417 * is locked, whether we created the file or not, and that the
4418 * deny mode is compatible with all current opens.
4422 * According to Samba4, SEC_FILE_READ_ATTRIBUTE is always granted,
4423 * but we don't have to store this - just ignore it on access check.
4425 if (conn->sconn->using_smb2) {
4427 * SMB2 doesn't return it (according to Microsoft tests).
4428 * Test Case: TestSuite_ScenarioNo009GrantedAccessTestS0
4429 * File created with access = 0x7 (Read, Write, Delete)
4430 * Query Info on file returns 0x87 (Read, Write, Delete, Read Attributes)
4432 fsp->access_mask = access_mask;
4433 } else {
4434 /* But SMB1 does. */
4435 fsp->access_mask = access_mask | FILE_READ_ATTRIBUTES;
4438 if (pinfo) {
4439 *pinfo = info;
4442 /* Handle strange delete on close create semantics. */
4443 if (create_options & FILE_DELETE_ON_CLOSE) {
4444 if (!new_file_created) {
4445 status = can_set_delete_on_close(fsp,
4446 existing_dos_attributes);
4448 if (!NT_STATUS_IS_OK(status)) {
4449 /* Remember to delete the mode we just added. */
4450 lck_state.cleanup_fn =
4451 open_ntcreate_lock_cleanup_entry;
4452 goto unlock;
4455 /* Note that here we set the *initial* delete on close flag,
4456 not the regular one. The magic gets handled in close. */
4457 fsp->fsp_flags.initial_delete_on_close = true;
4460 if (info != FILE_WAS_OPENED) {
4461 /* Overwritten files should be initially set as archive */
4462 if ((info == FILE_WAS_OVERWRITTEN && lp_map_archive(SNUM(conn))) ||
4463 lp_store_dos_attributes(SNUM(conn))) {
4464 (void)fdos_mode(fsp);
4465 if (!posix_open) {
4466 if (file_set_dosmode(conn, smb_fname,
4467 new_dos_attributes | FILE_ATTRIBUTE_ARCHIVE,
4468 parent_dir_fname, true) == 0) {
4469 unx_mode = smb_fname->st.st_ex_mode;
4475 /* Determine sparse flag. */
4476 if (posix_open) {
4477 /* POSIX opens are sparse by default. */
4478 fsp->fsp_flags.is_sparse = true;
4479 } else {
4480 fsp->fsp_flags.is_sparse =
4481 (existing_dos_attributes & FILE_ATTRIBUTE_SPARSE);
4485 * Take care of inherited ACLs on created files - if default ACL not
4486 * selected.
4489 if (!posix_open && new_file_created && !def_acl) {
4490 if (unx_mode != smb_fname->st.st_ex_mode) {
4491 int ret = SMB_VFS_FCHMOD(fsp, unx_mode);
4492 if (ret == -1) {
4493 DBG_INFO("failed to reset "
4494 "attributes of file %s to 0%o\n",
4495 smb_fname_str_dbg(smb_fname),
4496 (unsigned int)unx_mode);
4500 } else if (new_unx_mode) {
4502 * We only get here in the case of:
4504 * a). Not a POSIX open.
4505 * b). File already existed.
4506 * c). File was overwritten.
4507 * d). Requested DOS attributes didn't match
4508 * the DOS attributes on the existing file.
4510 * In that case new_unx_mode has been set
4511 * equal to the calculated mode (including
4512 * possible inheritance of the mode from the
4513 * containing directory).
4515 * Note this mode was calculated with the
4516 * DOS attribute FILE_ATTRIBUTE_ARCHIVE added,
4517 * so the mode change here is suitable for
4518 * an overwritten file.
4521 if (new_unx_mode != smb_fname->st.st_ex_mode) {
4522 int ret = SMB_VFS_FCHMOD(fsp, new_unx_mode);
4523 if (ret == -1) {
4524 DBG_INFO("failed to reset "
4525 "attributes of file %s to 0%o\n",
4526 smb_fname_str_dbg(smb_fname),
4527 (unsigned int)new_unx_mode);
4533 * Deal with other opens having a modified write time.
4535 if (fsp_getinfo_ask_sharemode(fsp) &&
4536 !is_omit_timespec(&lck_state.write_time))
4538 update_stat_ex_mtime(&fsp->fsp_name->st, lck_state.write_time);
4541 status = NT_STATUS_OK;
4543 unlock:
4544 ulstatus = share_mode_entry_prepare_unlock(&lck_state.prepare_state,
4545 lck_state.cleanup_fn,
4546 &lck_state);
4547 if (!NT_STATUS_IS_OK(ulstatus)) {
4548 DBG_ERR("share_mode_entry_prepare_unlock() failed for %s - %s\n",
4549 smb_fname_str_dbg(smb_fname), nt_errstr(ulstatus));
4550 smb_panic("share_mode_entry_prepare_unlock() failed!");
4553 if (!NT_STATUS_IS_OK(status)) {
4554 fd_close(fsp);
4555 return status;
4558 return NT_STATUS_OK;
4561 static NTSTATUS mkdir_internal(connection_struct *conn,
4562 struct smb_filename *parent_dir_fname, /* parent. */
4563 struct smb_filename *smb_fname_atname, /* atname relative to parent. */
4564 struct smb_filename *smb_dname, /* full pathname from root of share. */
4565 uint32_t file_attributes,
4566 struct files_struct *fsp)
4568 const struct loadparm_substitution *lp_sub =
4569 loadparm_s3_global_substitution();
4570 mode_t mode;
4571 NTSTATUS status;
4572 bool posix_open = false;
4573 bool need_re_stat = false;
4574 uint32_t access_mask = SEC_DIR_ADD_SUBDIR;
4575 struct vfs_open_how how = { .flags = O_RDONLY|O_DIRECTORY, };
4576 int ret;
4578 if (!CAN_WRITE(conn) || (access_mask & ~(conn->share_access))) {
4579 DEBUG(5,("mkdir_internal: failing share access "
4580 "%s\n", lp_servicename(talloc_tos(), lp_sub, SNUM(conn))));
4581 return NT_STATUS_ACCESS_DENIED;
4584 if (file_attributes & FILE_FLAG_POSIX_SEMANTICS) {
4585 posix_open = true;
4586 mode = (mode_t)(file_attributes & ~FILE_FLAG_POSIX_SEMANTICS);
4587 } else {
4588 mode = unix_mode(conn,
4589 FILE_ATTRIBUTE_DIRECTORY,
4590 smb_dname,
4591 parent_dir_fname->fsp);
4594 status = check_parent_access_fsp(parent_dir_fname->fsp, access_mask);
4595 if(!NT_STATUS_IS_OK(status)) {
4596 DBG_INFO("check_parent_access_fsp "
4597 "on directory %s for path %s returned %s\n",
4598 smb_fname_str_dbg(parent_dir_fname),
4599 smb_dname->base_name,
4600 nt_errstr(status));
4601 return status;
4604 if (lp_inherit_acls(SNUM(conn))) {
4605 if (directory_has_default_acl_fsp(parent_dir_fname->fsp)) {
4606 mode = (0777 & lp_directory_mask(SNUM(conn)));
4610 ret = SMB_VFS_MKDIRAT(conn,
4611 parent_dir_fname->fsp,
4612 smb_fname_atname,
4613 mode);
4614 if (ret != 0) {
4615 return map_nt_error_from_unix(errno);
4619 * Make this a pathref fsp for now. open_directory() will reopen as a
4620 * full fsp.
4622 fsp->fsp_flags.is_pathref = true;
4624 status = fd_openat(parent_dir_fname->fsp, smb_fname_atname, fsp, &how);
4625 if (!NT_STATUS_IS_OK(status)) {
4626 return status;
4629 /* Ensure we're checking for a symlink here.... */
4630 /* We don't want to get caught by a symlink racer. */
4632 status = vfs_stat_fsp(fsp);
4633 if (!NT_STATUS_IS_OK(status)) {
4634 DEBUG(2, ("Could not stat directory '%s' just created: %s\n",
4635 smb_fname_str_dbg(smb_dname), nt_errstr(status)));
4636 return status;
4639 if (!S_ISDIR(smb_dname->st.st_ex_mode)) {
4640 DEBUG(0, ("Directory '%s' just created is not a directory !\n",
4641 smb_fname_str_dbg(smb_dname)));
4642 return NT_STATUS_NOT_A_DIRECTORY;
4645 if (lp_store_dos_attributes(SNUM(conn)) && !posix_open) {
4646 file_set_dosmode(conn,
4647 smb_dname,
4648 file_attributes | FILE_ATTRIBUTE_DIRECTORY,
4649 parent_dir_fname,
4650 true);
4653 if (lp_inherit_permissions(SNUM(conn))) {
4654 inherit_access_posix_acl(conn, parent_dir_fname->fsp,
4655 smb_dname, mode);
4656 need_re_stat = true;
4659 if (!posix_open) {
4661 * Check if high bits should have been set,
4662 * then (if bits are missing): add them.
4663 * Consider bits automagically set by UNIX, i.e. SGID bit from parent
4664 * dir.
4666 if ((mode & ~(S_IRWXU|S_IRWXG|S_IRWXO)) &&
4667 (mode & ~smb_dname->st.st_ex_mode)) {
4668 SMB_VFS_FCHMOD(fsp,
4669 (smb_dname->st.st_ex_mode |
4670 (mode & ~smb_dname->st.st_ex_mode)));
4671 need_re_stat = true;
4675 /* Change the owner if required. */
4676 if (lp_inherit_owner(SNUM(conn)) != INHERIT_OWNER_NO) {
4677 change_dir_owner_to_parent_fsp(parent_dir_fname->fsp,
4678 fsp);
4679 need_re_stat = true;
4682 if (need_re_stat) {
4683 status = vfs_stat_fsp(fsp);
4684 if (!NT_STATUS_IS_OK(status)) {
4685 DEBUG(2, ("Could not stat directory '%s' just created: %s\n",
4686 smb_fname_str_dbg(smb_dname), nt_errstr(status)));
4687 return status;
4691 notify_fname(conn, NOTIFY_ACTION_ADDED, FILE_NOTIFY_CHANGE_DIR_NAME,
4692 smb_dname->base_name);
4694 return NT_STATUS_OK;
4697 /****************************************************************************
4698 Open a directory from an NT SMB call.
4699 ****************************************************************************/
4701 static NTSTATUS open_directory(connection_struct *conn,
4702 struct smb_request *req,
4703 uint32_t access_mask,
4704 uint32_t share_access,
4705 uint32_t create_disposition,
4706 uint32_t create_options,
4707 uint32_t file_attributes,
4708 struct smb_filename *parent_dir_fname,
4709 struct smb_filename *smb_fname_atname,
4710 int *pinfo,
4711 struct files_struct *fsp)
4713 struct smb_filename *smb_dname = fsp->fsp_name;
4714 bool dir_existed = VALID_STAT(smb_dname->st);
4715 struct open_ntcreate_lock_state lck_state = {};
4716 bool keep_locked = false;
4717 NTSTATUS status;
4718 struct timespec mtimespec;
4719 int info = 0;
4720 uint32_t need_fd_access;
4721 NTSTATUS ulstatus;
4723 if (is_ntfs_stream_smb_fname(smb_dname)) {
4724 DEBUG(2, ("open_directory: %s is a stream name!\n",
4725 smb_fname_str_dbg(smb_dname)));
4726 return NT_STATUS_NOT_A_DIRECTORY;
4729 if (!(file_attributes & FILE_FLAG_POSIX_SEMANTICS)) {
4730 /* Ensure we have a directory attribute. */
4731 file_attributes |= FILE_ATTRIBUTE_DIRECTORY;
4734 DBG_INFO("opening directory %s, access_mask = 0x%"PRIx32", "
4735 "share_access = 0x%"PRIx32" create_options = 0x%"PRIx32", "
4736 "create_disposition = 0x%"PRIx32", "
4737 "file_attributes = 0x%"PRIx32"\n",
4738 smb_fname_str_dbg(smb_dname),
4739 access_mask,
4740 share_access,
4741 create_options,
4742 create_disposition,
4743 file_attributes);
4745 status = smbd_calculate_access_mask_fsp(parent_dir_fname->fsp,
4746 smb_dname->fsp,
4747 false,
4748 access_mask,
4749 &access_mask);
4750 if (!NT_STATUS_IS_OK(status)) {
4751 DBG_DEBUG("smbd_calculate_access_mask_fsp "
4752 "on file %s returned %s\n",
4753 smb_fname_str_dbg(smb_dname),
4754 nt_errstr(status));
4755 return status;
4758 if ((access_mask & SEC_FLAG_SYSTEM_SECURITY) &&
4759 !security_token_has_privilege(get_current_nttok(conn),
4760 SEC_PRIV_SECURITY)) {
4761 DEBUG(10, ("open_directory: open on %s "
4762 "failed - SEC_FLAG_SYSTEM_SECURITY denied.\n",
4763 smb_fname_str_dbg(smb_dname)));
4764 return NT_STATUS_PRIVILEGE_NOT_HELD;
4767 switch( create_disposition ) {
4768 case FILE_OPEN:
4770 if (!dir_existed) {
4771 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
4774 info = FILE_WAS_OPENED;
4775 break;
4777 case FILE_CREATE:
4779 /* If directory exists error. If directory doesn't
4780 * exist create. */
4782 if (dir_existed) {
4783 status = NT_STATUS_OBJECT_NAME_COLLISION;
4784 DEBUG(2, ("open_directory: unable to create "
4785 "%s. Error was %s\n",
4786 smb_fname_str_dbg(smb_dname),
4787 nt_errstr(status)));
4788 return status;
4791 status = mkdir_internal(conn,
4792 parent_dir_fname,
4793 smb_fname_atname,
4794 smb_dname,
4795 file_attributes,
4796 fsp);
4798 if (!NT_STATUS_IS_OK(status)) {
4799 DEBUG(2, ("open_directory: unable to create "
4800 "%s. Error was %s\n",
4801 smb_fname_str_dbg(smb_dname),
4802 nt_errstr(status)));
4803 return status;
4806 info = FILE_WAS_CREATED;
4807 break;
4809 case FILE_OPEN_IF:
4811 * If directory exists open. If directory doesn't
4812 * exist create.
4815 if (dir_existed) {
4816 status = NT_STATUS_OK;
4817 info = FILE_WAS_OPENED;
4818 } else {
4819 status = mkdir_internal(conn,
4820 parent_dir_fname,
4821 smb_fname_atname,
4822 smb_dname,
4823 file_attributes,
4824 fsp);
4826 if (NT_STATUS_IS_OK(status)) {
4827 info = FILE_WAS_CREATED;
4828 } else {
4829 /* Cope with create race. */
4830 if (!NT_STATUS_EQUAL(status,
4831 NT_STATUS_OBJECT_NAME_COLLISION)) {
4832 DEBUG(2, ("open_directory: unable to create "
4833 "%s. Error was %s\n",
4834 smb_fname_str_dbg(smb_dname),
4835 nt_errstr(status)));
4836 return status;
4840 * If mkdir_internal() returned
4841 * NT_STATUS_OBJECT_NAME_COLLISION
4842 * we still must lstat the path.
4845 if (SMB_VFS_LSTAT(conn, smb_dname)
4846 == -1) {
4847 DEBUG(2, ("Could not stat "
4848 "directory '%s' just "
4849 "opened: %s\n",
4850 smb_fname_str_dbg(
4851 smb_dname),
4852 strerror(errno)));
4853 return map_nt_error_from_unix(
4854 errno);
4857 info = FILE_WAS_OPENED;
4861 break;
4863 case FILE_SUPERSEDE:
4864 case FILE_OVERWRITE:
4865 case FILE_OVERWRITE_IF:
4866 default:
4867 DEBUG(5,("open_directory: invalid create_disposition "
4868 "0x%x for directory %s\n",
4869 (unsigned int)create_disposition,
4870 smb_fname_str_dbg(smb_dname)));
4871 return NT_STATUS_INVALID_PARAMETER;
4874 if(!S_ISDIR(smb_dname->st.st_ex_mode)) {
4875 DEBUG(5,("open_directory: %s is not a directory !\n",
4876 smb_fname_str_dbg(smb_dname)));
4877 return NT_STATUS_NOT_A_DIRECTORY;
4881 * Setup the files_struct for it.
4884 fsp->file_id = vfs_file_id_from_sbuf(conn, &smb_dname->st);
4885 fsp->vuid = req ? req->vuid : UID_FIELD_INVALID;
4886 fsp->file_pid = req ? req->smbpid : 0;
4887 fsp->fsp_flags.can_lock = false;
4888 fsp->fsp_flags.can_read = false;
4889 fsp->fsp_flags.can_write = false;
4891 fh_set_private_options(fsp->fh, 0);
4893 * According to Samba4, SEC_FILE_READ_ATTRIBUTE is always granted,
4895 fsp->access_mask = access_mask | FILE_READ_ATTRIBUTES;
4896 fsp->print_file = NULL;
4897 fsp->fsp_flags.modified = false;
4898 fsp->oplock_type = NO_OPLOCK;
4899 fsp->sent_oplock_break = NO_BREAK_SENT;
4900 fsp->fsp_flags.is_directory = true;
4901 if (file_attributes & FILE_FLAG_POSIX_SEMANTICS) {
4902 fsp->posix_flags |= FSP_POSIX_FLAGS_ALL;
4905 /* Don't store old timestamps for directory
4906 handles in the internal database. We don't
4907 update them in there if new objects
4908 are created in the directory. Currently
4909 we only update timestamps on file writes.
4910 See bug #9870.
4912 mtimespec = make_omit_timespec();
4915 * Obviously for FILE_LIST_DIRECTORY we need to reopen to get an fd
4916 * usable for reading a directory. SMB2_FLUSH may be called on
4917 * directories opened with FILE_ADD_FILE and FILE_ADD_SUBDIRECTORY so
4918 * for those we need to reopen as well.
4920 need_fd_access =
4921 FILE_LIST_DIRECTORY |
4922 FILE_ADD_FILE |
4923 FILE_ADD_SUBDIRECTORY;
4925 if (access_mask & need_fd_access) {
4926 status = reopen_from_fsp(
4927 fsp->conn->cwd_fsp,
4928 fsp->fsp_name,
4929 fsp,
4930 O_RDONLY | O_DIRECTORY,
4932 NULL);
4933 if (!NT_STATUS_IS_OK(status)) {
4934 DBG_INFO("Could not open fd for [%s]: %s\n",
4935 smb_fname_str_dbg(smb_dname),
4936 nt_errstr(status));
4937 return status;
4941 status = vfs_stat_fsp(fsp);
4942 if (!NT_STATUS_IS_OK(status)) {
4943 fd_close(fsp);
4944 return status;
4947 if(!S_ISDIR(fsp->fsp_name->st.st_ex_mode)) {
4948 DEBUG(5,("open_directory: %s is not a directory !\n",
4949 smb_fname_str_dbg(smb_dname)));
4950 fd_close(fsp);
4951 return NT_STATUS_NOT_A_DIRECTORY;
4954 /* Ensure there was no race condition. We need to check
4955 * dev/inode but not permissions, as these can change
4956 * legitimately */
4957 if (!check_same_dev_ino(&smb_dname->st, &fsp->fsp_name->st)) {
4958 DEBUG(5,("open_directory: stat struct differs for "
4959 "directory %s.\n",
4960 smb_fname_str_dbg(smb_dname)));
4961 fd_close(fsp);
4962 return NT_STATUS_ACCESS_DENIED;
4965 if (info == FILE_WAS_OPENED) {
4966 status = smbd_check_access_rights_fsp(parent_dir_fname->fsp,
4967 fsp,
4968 false,
4969 access_mask);
4970 if (!NT_STATUS_IS_OK(status)) {
4971 DBG_DEBUG("smbd_check_access_rights_fsp on "
4972 "file %s failed with %s\n",
4973 fsp_str_dbg(fsp),
4974 nt_errstr(status));
4975 fd_close(fsp);
4976 return status;
4981 * If we created a new directory or going to delete it later,
4982 * we should keep * the share_mode_lock (g_lock) until we call
4983 * share_mode_entry_prepare_unlock()
4985 if (info != FILE_WAS_OPENED) {
4986 keep_locked = true;
4987 } else if (create_options & FILE_DELETE_ON_CLOSE) {
4988 keep_locked = true;
4991 lck_state = (struct open_ntcreate_lock_state) {
4992 .fsp = fsp,
4993 .object_type = "directory",
4994 .req = req,
4995 .create_disposition = create_disposition,
4996 .access_mask = access_mask,
4997 .share_access = share_access,
4998 .oplock_request = NO_OPLOCK,
4999 .lease = NULL,
5000 .first_open_attempt = true,
5001 .keep_locked = keep_locked,
5004 status = share_mode_entry_prepare_lock_add(&lck_state.prepare_state,
5005 fsp->file_id,
5006 conn->connectpath,
5007 smb_dname,
5008 &mtimespec,
5009 open_ntcreate_lock_add_entry,
5010 &lck_state);
5011 if (!NT_STATUS_IS_OK(status)) {
5012 DBG_ERR("share_mode_entry_prepare_lock_add() failed for %s - %s\n",
5013 smb_fname_str_dbg(smb_dname), nt_errstr(status));
5014 fd_close(fsp);
5015 return status;
5018 status = lck_state.status;
5019 if (!NT_STATUS_IS_OK(status)) {
5020 fd_close(fsp);
5021 return status;
5025 * From here we need to use 'goto unlock;' instead of return !!!
5028 /* For directories the delete on close bit at open time seems
5029 always to be honored on close... See test 19 in Samba4 BASE-DELETE. */
5030 if (create_options & FILE_DELETE_ON_CLOSE) {
5031 status = can_set_delete_on_close(fsp, 0);
5032 if (!NT_STATUS_IS_OK(status) && !NT_STATUS_EQUAL(status, NT_STATUS_DIRECTORY_NOT_EMPTY)) {
5033 lck_state.cleanup_fn =
5034 open_ntcreate_lock_cleanup_entry;
5035 goto unlock;
5038 if (NT_STATUS_IS_OK(status)) {
5039 /* Note that here we set the *initial* delete on close flag,
5040 not the regular one. The magic gets handled in close. */
5041 fsp->fsp_flags.initial_delete_on_close = true;
5046 * Deal with other opens having a modified write time.
5048 if (!is_omit_timespec(&lck_state.write_time)) {
5049 update_stat_ex_mtime(&fsp->fsp_name->st, lck_state.write_time);
5052 if (pinfo) {
5053 *pinfo = info;
5056 status = NT_STATUS_OK;
5058 unlock:
5059 ulstatus = share_mode_entry_prepare_unlock(&lck_state.prepare_state,
5060 lck_state.cleanup_fn,
5061 &lck_state);
5062 if (!NT_STATUS_IS_OK(ulstatus)) {
5063 DBG_ERR("share_mode_entry_prepare_unlock() failed for %s - %s\n",
5064 smb_fname_str_dbg(smb_dname), nt_errstr(ulstatus));
5065 smb_panic("share_mode_entry_prepare_unlock() failed!");
5068 if (!NT_STATUS_IS_OK(status)) {
5069 fd_close(fsp);
5070 return status;
5073 return NT_STATUS_OK;
5076 NTSTATUS create_directory(connection_struct *conn,
5077 struct smb_request *req,
5078 struct files_struct *dirfsp,
5079 struct smb_filename *smb_dname)
5081 NTSTATUS status;
5082 files_struct *fsp;
5084 status = SMB_VFS_CREATE_FILE(
5085 conn, /* conn */
5086 req, /* req */
5087 dirfsp, /* dirfsp */
5088 smb_dname, /* fname */
5089 FILE_READ_ATTRIBUTES, /* access_mask */
5090 FILE_SHARE_NONE, /* share_access */
5091 FILE_CREATE, /* create_disposition*/
5092 FILE_DIRECTORY_FILE, /* create_options */
5093 FILE_ATTRIBUTE_DIRECTORY, /* file_attributes */
5094 0, /* oplock_request */
5095 NULL, /* lease */
5096 0, /* allocation_size */
5097 0, /* private_flags */
5098 NULL, /* sd */
5099 NULL, /* ea_list */
5100 &fsp, /* result */
5101 NULL, /* pinfo */
5102 NULL, NULL); /* create context */
5104 if (NT_STATUS_IS_OK(status)) {
5105 close_file_free(req, &fsp, NORMAL_CLOSE);
5108 return status;
5111 /****************************************************************************
5112 Receive notification that one of our open files has been renamed by another
5113 smbd process.
5114 ****************************************************************************/
5116 void msg_file_was_renamed(struct messaging_context *msg_ctx,
5117 void *private_data,
5118 uint32_t msg_type,
5119 struct server_id src,
5120 DATA_BLOB *data)
5122 struct file_rename_message *msg = NULL;
5123 enum ndr_err_code ndr_err;
5124 files_struct *fsp;
5125 struct smb_filename *smb_fname = NULL;
5126 struct smbd_server_connection *sconn =
5127 talloc_get_type_abort(private_data,
5128 struct smbd_server_connection);
5130 msg = talloc(talloc_tos(), struct file_rename_message);
5131 if (msg == NULL) {
5132 DBG_WARNING("talloc failed\n");
5133 return;
5136 ndr_err = ndr_pull_struct_blob_all(
5137 data,
5138 msg,
5139 msg,
5140 (ndr_pull_flags_fn_t)ndr_pull_file_rename_message);
5141 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
5142 DBG_DEBUG("ndr_pull_oplock_break_message failed: %s\n",
5143 ndr_errstr(ndr_err));
5144 goto out;
5146 if (DEBUGLEVEL >= 10) {
5147 struct server_id_buf buf;
5148 DBG_DEBUG("Got rename message from %s\n",
5149 server_id_str_buf(src, &buf));
5150 NDR_PRINT_DEBUG(file_rename_message, msg);
5153 /* stream_name must always be NULL if there is no stream. */
5154 if ((msg->stream_name != NULL) && (msg->stream_name[0] == '\0')) {
5155 msg->stream_name = NULL;
5158 smb_fname = synthetic_smb_fname(msg,
5159 msg->base_name,
5160 msg->stream_name,
5161 NULL,
5164 if (smb_fname == NULL) {
5165 DBG_DEBUG("synthetic_smb_fname failed\n");
5166 goto out;
5169 fsp = file_find_dif(sconn, msg->id, msg->share_file_id);
5170 if (fsp == NULL) {
5171 DBG_DEBUG("fsp not found\n");
5172 goto out;
5175 if (strcmp(fsp->conn->connectpath, msg->servicepath) == 0) {
5176 SMB_STRUCT_STAT fsp_orig_sbuf;
5177 NTSTATUS status;
5178 DBG_DEBUG("renaming file %s from %s -> %s\n",
5179 fsp_fnum_dbg(fsp),
5180 fsp_str_dbg(fsp),
5181 smb_fname_str_dbg(smb_fname));
5184 * The incoming smb_fname here has an
5185 * invalid stat struct from synthetic_smb_fname()
5186 * above.
5187 * Preserve the existing stat from the
5188 * open fsp after fsp_set_smb_fname()
5189 * overwrites with the invalid stat.
5191 * (We could just copy this into
5192 * smb_fname->st, but keep this code
5193 * identical to the fix in rename_open_files()
5194 * for clarity.
5196 * We will do an fstat before returning
5197 * any of this metadata to the client anyway.
5199 fsp_orig_sbuf = fsp->fsp_name->st;
5200 status = fsp_set_smb_fname(fsp, smb_fname);
5201 if (!NT_STATUS_IS_OK(status)) {
5202 DBG_DEBUG("fsp_set_smb_fname failed: %s\n",
5203 nt_errstr(status));
5205 fsp->fsp_name->st = fsp_orig_sbuf;
5206 } else {
5207 /* TODO. JRA. */
5209 * Now we have the complete path we can work out if
5210 * this is actually within this share and adjust
5211 * newname accordingly.
5213 DBG_DEBUG("share mismatch (sharepath %s not sharepath %s) "
5214 "%s from %s -> %s\n",
5215 fsp->conn->connectpath,
5216 msg->servicepath,
5217 fsp_fnum_dbg(fsp),
5218 fsp_str_dbg(fsp),
5219 smb_fname_str_dbg(smb_fname));
5221 out:
5222 TALLOC_FREE(msg);
5226 * If a main file is opened for delete, all streams need to be checked for
5227 * !FILE_SHARE_DELETE. Do this by opening with DELETE_ACCESS.
5228 * If that works, delete them all by setting the delete on close and close.
5231 static NTSTATUS open_streams_for_delete(connection_struct *conn,
5232 const struct smb_filename *smb_fname)
5234 struct stream_struct *stream_info = NULL;
5235 files_struct **streams = NULL;
5236 int j;
5237 unsigned int i, num_streams = 0;
5238 TALLOC_CTX *frame = talloc_stackframe();
5239 const struct smb_filename *pathref = NULL;
5240 NTSTATUS status;
5242 if (smb_fname->fsp == NULL) {
5243 struct smb_filename *tmp = NULL;
5244 status = synthetic_pathref(frame,
5245 conn->cwd_fsp,
5246 smb_fname->base_name,
5247 NULL,
5248 NULL,
5249 smb_fname->twrp,
5250 smb_fname->flags,
5251 &tmp);
5252 if (!NT_STATUS_IS_OK(status)) {
5253 if (NT_STATUS_EQUAL(status, NT_STATUS_NOT_IMPLEMENTED)
5254 || NT_STATUS_EQUAL(status,
5255 NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
5256 DBG_DEBUG("no streams around\n");
5257 TALLOC_FREE(frame);
5258 return NT_STATUS_OK;
5260 DBG_DEBUG("synthetic_pathref failed: %s\n",
5261 nt_errstr(status));
5262 goto fail;
5264 pathref = tmp;
5265 } else {
5266 pathref = smb_fname;
5268 status = vfs_fstreaminfo(pathref->fsp, talloc_tos(),
5269 &num_streams, &stream_info);
5271 if (NT_STATUS_EQUAL(status, NT_STATUS_NOT_IMPLEMENTED)
5272 || NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
5273 DEBUG(10, ("no streams around\n"));
5274 TALLOC_FREE(frame);
5275 return NT_STATUS_OK;
5278 if (!NT_STATUS_IS_OK(status)) {
5279 DEBUG(10, ("vfs_fstreaminfo failed: %s\n",
5280 nt_errstr(status)));
5281 goto fail;
5284 DEBUG(10, ("open_streams_for_delete found %d streams\n",
5285 num_streams));
5287 if (num_streams == 0) {
5288 TALLOC_FREE(frame);
5289 return NT_STATUS_OK;
5292 streams = talloc_array(talloc_tos(), files_struct *, num_streams);
5293 if (streams == NULL) {
5294 DEBUG(0, ("talloc failed\n"));
5295 status = NT_STATUS_NO_MEMORY;
5296 goto fail;
5299 for (i=0; i<num_streams; i++) {
5300 struct smb_filename *smb_fname_cp;
5302 if (strequal(stream_info[i].name, "::$DATA")) {
5303 streams[i] = NULL;
5304 continue;
5307 smb_fname_cp = synthetic_smb_fname(talloc_tos(),
5308 smb_fname->base_name,
5309 stream_info[i].name,
5310 NULL,
5311 smb_fname->twrp,
5312 (smb_fname->flags &
5313 ~SMB_FILENAME_POSIX_PATH));
5314 if (smb_fname_cp == NULL) {
5315 status = NT_STATUS_NO_MEMORY;
5316 goto fail;
5319 status = openat_pathref_fsp(conn->cwd_fsp, smb_fname_cp);
5320 if (!NT_STATUS_IS_OK(status)) {
5321 DBG_DEBUG("Unable to open stream [%s]: %s\n",
5322 smb_fname_str_dbg(smb_fname_cp),
5323 nt_errstr(status));
5324 TALLOC_FREE(smb_fname_cp);
5325 break;
5328 status = SMB_VFS_CREATE_FILE(
5329 conn, /* conn */
5330 NULL, /* req */
5331 NULL, /* dirfsp */
5332 smb_fname_cp, /* fname */
5333 DELETE_ACCESS, /* access_mask */
5334 (FILE_SHARE_READ | /* share_access */
5335 FILE_SHARE_WRITE | FILE_SHARE_DELETE),
5336 FILE_OPEN, /* create_disposition*/
5337 0, /* create_options */
5338 FILE_ATTRIBUTE_NORMAL, /* file_attributes */
5339 0, /* oplock_request */
5340 NULL, /* lease */
5341 0, /* allocation_size */
5342 0, /* private_flags */
5343 NULL, /* sd */
5344 NULL, /* ea_list */
5345 &streams[i], /* result */
5346 NULL, /* pinfo */
5347 NULL, NULL); /* create context */
5349 if (!NT_STATUS_IS_OK(status)) {
5350 DEBUG(10, ("Could not open stream %s: %s\n",
5351 smb_fname_str_dbg(smb_fname_cp),
5352 nt_errstr(status)));
5354 TALLOC_FREE(smb_fname_cp);
5355 break;
5357 TALLOC_FREE(smb_fname_cp);
5361 * don't touch the variable "status" beyond this point :-)
5364 for (j = i-1 ; j >= 0; j--) {
5365 if (streams[j] == NULL) {
5366 continue;
5369 DEBUG(10, ("Closing stream # %d, %s\n", j,
5370 fsp_str_dbg(streams[j])));
5371 close_file_free(NULL, &streams[j], NORMAL_CLOSE);
5374 fail:
5375 TALLOC_FREE(frame);
5376 return status;
5379 /*********************************************************************
5380 Create a default ACL by inheriting from the parent. If no inheritance
5381 from the parent available, don't set anything. This will leave the actual
5382 permissions the new file or directory already got from the filesystem
5383 as the NT ACL when read.
5384 *********************************************************************/
5386 static NTSTATUS inherit_new_acl(files_struct *dirfsp, files_struct *fsp)
5388 TALLOC_CTX *frame = talloc_stackframe();
5389 struct security_descriptor *parent_desc = NULL;
5390 NTSTATUS status = NT_STATUS_OK;
5391 struct security_descriptor *psd = NULL;
5392 const struct dom_sid *owner_sid = NULL;
5393 const struct dom_sid *group_sid = NULL;
5394 uint32_t security_info_sent = (SECINFO_OWNER | SECINFO_GROUP | SECINFO_DACL);
5395 struct security_token *token = fsp->conn->session_info->security_token;
5396 bool inherit_owner =
5397 (lp_inherit_owner(SNUM(fsp->conn)) == INHERIT_OWNER_WINDOWS_AND_UNIX);
5398 bool inheritable_components = false;
5399 bool try_builtin_administrators = false;
5400 const struct dom_sid *BA_U_sid = NULL;
5401 const struct dom_sid *BA_G_sid = NULL;
5402 bool try_system = false;
5403 const struct dom_sid *SY_U_sid = NULL;
5404 const struct dom_sid *SY_G_sid = NULL;
5405 size_t size = 0;
5406 bool ok;
5408 status = SMB_VFS_FGET_NT_ACL(dirfsp,
5409 (SECINFO_OWNER | SECINFO_GROUP | SECINFO_DACL),
5410 frame,
5411 &parent_desc);
5412 if (!NT_STATUS_IS_OK(status)) {
5413 TALLOC_FREE(frame);
5414 return status;
5417 inheritable_components = sd_has_inheritable_components(parent_desc,
5418 fsp->fsp_flags.is_directory);
5420 if (!inheritable_components && !inherit_owner) {
5421 TALLOC_FREE(frame);
5422 /* Nothing to inherit and not setting owner. */
5423 return NT_STATUS_OK;
5426 /* Create an inherited descriptor from the parent. */
5428 if (DEBUGLEVEL >= 10) {
5429 DEBUG(10,("inherit_new_acl: parent acl for %s is:\n",
5430 fsp_str_dbg(fsp) ));
5431 NDR_PRINT_DEBUG(security_descriptor, parent_desc);
5434 /* Inherit from parent descriptor if "inherit owner" set. */
5435 if (inherit_owner) {
5436 owner_sid = parent_desc->owner_sid;
5437 group_sid = parent_desc->group_sid;
5440 if (owner_sid == NULL) {
5441 if (security_token_has_builtin_administrators(token)) {
5442 try_builtin_administrators = true;
5443 } else if (security_token_is_system(token)) {
5444 try_builtin_administrators = true;
5445 try_system = true;
5449 if (group_sid == NULL &&
5450 token->num_sids == PRIMARY_GROUP_SID_INDEX)
5452 if (security_token_is_system(token)) {
5453 try_builtin_administrators = true;
5454 try_system = true;
5458 if (try_builtin_administrators) {
5459 struct unixid ids = { .id = 0 };
5461 ok = sids_to_unixids(&global_sid_Builtin_Administrators, 1, &ids);
5462 if (ok) {
5463 switch (ids.type) {
5464 case ID_TYPE_BOTH:
5465 BA_U_sid = &global_sid_Builtin_Administrators;
5466 BA_G_sid = &global_sid_Builtin_Administrators;
5467 break;
5468 case ID_TYPE_UID:
5469 BA_U_sid = &global_sid_Builtin_Administrators;
5470 break;
5471 case ID_TYPE_GID:
5472 BA_G_sid = &global_sid_Builtin_Administrators;
5473 break;
5474 default:
5475 break;
5480 if (try_system) {
5481 struct unixid ids = { .id = 0 };
5483 ok = sids_to_unixids(&global_sid_System, 1, &ids);
5484 if (ok) {
5485 switch (ids.type) {
5486 case ID_TYPE_BOTH:
5487 SY_U_sid = &global_sid_System;
5488 SY_G_sid = &global_sid_System;
5489 break;
5490 case ID_TYPE_UID:
5491 SY_U_sid = &global_sid_System;
5492 break;
5493 case ID_TYPE_GID:
5494 SY_G_sid = &global_sid_System;
5495 break;
5496 default:
5497 break;
5502 if (owner_sid == NULL) {
5503 owner_sid = BA_U_sid;
5506 if (owner_sid == NULL) {
5507 owner_sid = SY_U_sid;
5510 if (group_sid == NULL) {
5511 group_sid = SY_G_sid;
5514 if (try_system && group_sid == NULL) {
5515 group_sid = BA_G_sid;
5518 if (owner_sid == NULL) {
5519 owner_sid = &token->sids[PRIMARY_USER_SID_INDEX];
5521 if (group_sid == NULL) {
5522 if (token->num_sids == PRIMARY_GROUP_SID_INDEX) {
5523 group_sid = &token->sids[PRIMARY_USER_SID_INDEX];
5524 } else {
5525 group_sid = &token->sids[PRIMARY_GROUP_SID_INDEX];
5529 status = se_create_child_secdesc(frame,
5530 &psd,
5531 &size,
5532 parent_desc,
5533 owner_sid,
5534 group_sid,
5535 fsp->fsp_flags.is_directory);
5536 if (!NT_STATUS_IS_OK(status)) {
5537 TALLOC_FREE(frame);
5538 return status;
5541 /* If inheritable_components == false,
5542 se_create_child_secdesc()
5543 creates a security descriptor with a NULL dacl
5544 entry, but with SEC_DESC_DACL_PRESENT. We need
5545 to remove that flag. */
5547 if (!inheritable_components) {
5548 security_info_sent &= ~SECINFO_DACL;
5549 psd->type &= ~SEC_DESC_DACL_PRESENT;
5552 if (DEBUGLEVEL >= 10) {
5553 DEBUG(10,("inherit_new_acl: child acl for %s is:\n",
5554 fsp_str_dbg(fsp) ));
5555 NDR_PRINT_DEBUG(security_descriptor, psd);
5558 if (inherit_owner) {
5559 /* We need to be root to force this. */
5560 become_root();
5562 status = SMB_VFS_FSET_NT_ACL(metadata_fsp(fsp),
5563 security_info_sent,
5564 psd);
5565 if (inherit_owner) {
5566 unbecome_root();
5568 TALLOC_FREE(frame);
5569 return status;
5573 * If we already have a lease, it must match the new file id. [MS-SMB2]
5574 * 3.3.5.9.8 speaks about INVALID_PARAMETER if an already used lease key is
5575 * used for a different file name.
5578 struct lease_match_state {
5579 /* Input parameters. */
5580 TALLOC_CTX *mem_ctx;
5581 const char *servicepath;
5582 const struct smb_filename *fname;
5583 bool file_existed;
5584 struct file_id id;
5585 /* Return parameters. */
5586 uint32_t num_file_ids;
5587 struct file_id *ids;
5588 NTSTATUS match_status;
5591 /*************************************************************
5592 File doesn't exist but this lease key+guid is already in use.
5594 This is only allowable in the dynamic share case where the
5595 service path must be different.
5597 There is a small race condition here in the multi-connection
5598 case where a client sends two create calls on different connections,
5599 where the file doesn't exist and one smbd creates the leases_db
5600 entry first, but this will get fixed by the multichannel cleanup
5601 when all identical client_guids get handled by a single smbd.
5602 **************************************************************/
5604 static void lease_match_parser_new_file(
5605 uint32_t num_files,
5606 const struct leases_db_file *files,
5607 struct lease_match_state *state)
5609 uint32_t i;
5611 for (i = 0; i < num_files; i++) {
5612 const struct leases_db_file *f = &files[i];
5613 if (strequal(state->servicepath, f->servicepath)) {
5614 state->match_status = NT_STATUS_INVALID_PARAMETER;
5615 return;
5619 /* Dynamic share case. Break leases on all other files. */
5620 state->match_status = leases_db_copy_file_ids(state->mem_ctx,
5621 num_files,
5622 files,
5623 &state->ids);
5624 if (!NT_STATUS_IS_OK(state->match_status)) {
5625 return;
5628 state->num_file_ids = num_files;
5629 state->match_status = NT_STATUS_OPLOCK_NOT_GRANTED;
5630 return;
5633 static void lease_match_parser(
5634 uint32_t num_files,
5635 const struct leases_db_file *files,
5636 void *private_data)
5638 struct lease_match_state *state =
5639 (struct lease_match_state *)private_data;
5640 uint32_t i;
5642 if (!state->file_existed) {
5644 * Deal with name mismatch or
5645 * possible dynamic share case separately
5646 * to make code clearer.
5648 lease_match_parser_new_file(num_files,
5649 files,
5650 state);
5651 return;
5654 /* File existed. */
5655 state->match_status = NT_STATUS_OK;
5657 for (i = 0; i < num_files; i++) {
5658 const struct leases_db_file *f = &files[i];
5660 /* Everything should be the same. */
5661 if (!file_id_equal(&state->id, &f->id)) {
5663 * The client asked for a lease on a
5664 * file that doesn't match the file_id
5665 * in the database.
5667 * Maybe this is a dynamic share, i.e.
5668 * a share where the servicepath is
5669 * different for different users (e.g.
5670 * the [HOMES] share.
5672 * If the servicepath is different, but the requested
5673 * file name + stream name is the same then this is
5674 * a dynamic share, the client is using the same share
5675 * name and doesn't know that the underlying servicepath
5676 * is different. It was expecting a lease on the
5677 * same file. Return NT_STATUS_OPLOCK_NOT_GRANTED
5678 * to break leases
5680 * Otherwise the client has messed up, or is
5681 * testing our error codes, so return
5682 * NT_STATUS_INVALID_PARAMETER.
5684 if (!strequal(f->servicepath, state->servicepath) &&
5685 strequal(f->base_name, state->fname->base_name) &&
5686 strequal(f->stream_name, state->fname->stream_name))
5689 * Name is the same but servicepath is
5690 * different, dynamic share. Break leases.
5692 state->match_status =
5693 NT_STATUS_OPLOCK_NOT_GRANTED;
5694 } else {
5695 state->match_status =
5696 NT_STATUS_INVALID_PARAMETER;
5698 break;
5700 if (!strequal(f->servicepath, state->servicepath)) {
5701 state->match_status = NT_STATUS_INVALID_PARAMETER;
5702 break;
5704 if (!strequal(f->base_name, state->fname->base_name)) {
5705 state->match_status = NT_STATUS_INVALID_PARAMETER;
5706 break;
5708 if (!strequal(f->stream_name, state->fname->stream_name)) {
5709 state->match_status = NT_STATUS_INVALID_PARAMETER;
5710 break;
5714 if (NT_STATUS_IS_OK(state->match_status)) {
5716 * Common case - just opening another handle on a
5717 * file on a non-dynamic share.
5719 return;
5722 if (NT_STATUS_EQUAL(state->match_status, NT_STATUS_INVALID_PARAMETER)) {
5723 /* Mismatched path. Error back to client. */
5724 return;
5728 * File id mismatch. Dynamic share case NT_STATUS_OPLOCK_NOT_GRANTED.
5729 * Don't allow leases.
5732 state->match_status = leases_db_copy_file_ids(state->mem_ctx,
5733 num_files,
5734 files,
5735 &state->ids);
5736 if (!NT_STATUS_IS_OK(state->match_status)) {
5737 return;
5740 state->num_file_ids = num_files;
5741 state->match_status = NT_STATUS_OPLOCK_NOT_GRANTED;
5742 return;
5745 struct lease_match_break_state {
5746 struct messaging_context *msg_ctx;
5747 const struct smb2_lease_key *lease_key;
5748 struct file_id id;
5750 bool found_lease;
5751 uint16_t version;
5752 uint16_t epoch;
5755 static bool lease_match_break_fn(
5756 struct share_mode_entry *e,
5757 void *private_data)
5759 struct lease_match_break_state *state = private_data;
5760 bool stale, equal;
5761 uint32_t e_lease_type = SMB2_LEASE_NONE;
5762 NTSTATUS status;
5764 stale = share_entry_stale_pid(e);
5765 if (stale) {
5766 return false;
5769 equal = smb2_lease_key_equal(&e->lease_key, state->lease_key);
5770 if (!equal) {
5771 return false;
5774 status = leases_db_get(
5775 &e->client_guid,
5776 &e->lease_key,
5777 &state->id,
5778 &e_lease_type, /* current_state */
5779 NULL, /* breaking */
5780 NULL, /* breaking_to_requested */
5781 NULL, /* breaking_to_required */
5782 &state->version, /* lease_version */
5783 &state->epoch); /* epoch */
5784 if (NT_STATUS_IS_OK(status)) {
5785 state->found_lease = true;
5786 } else {
5787 DBG_WARNING("Could not find version/epoch: %s\n",
5788 nt_errstr(status));
5789 return false;
5792 if (e_lease_type == SMB2_LEASE_NONE) {
5793 return false;
5795 send_break_message(state->msg_ctx, &state->id, e, SMB2_LEASE_NONE);
5798 * Windows 7 and 8 lease clients are broken in that they will
5799 * not respond to lease break requests whilst waiting for an
5800 * outstanding open request on that lease handle on the same
5801 * TCP connection, due to holding an internal inode lock.
5803 * This means we can't reschedule ourselves here, but must
5804 * return from the create.
5806 * Work around:
5808 * Send the breaks and then return SMB2_LEASE_NONE in the
5809 * lease handle to cause them to acknowledge the lease
5810 * break. Consultation with Microsoft engineering confirmed
5811 * this approach is safe.
5814 return false;
5817 static void lease_match_fid_fn(struct share_mode_lock *lck,
5818 void *private_data)
5820 bool ok;
5822 ok = share_mode_forall_leases(lck, lease_match_break_fn, private_data);
5823 if (!ok) {
5824 DBG_DEBUG("share_mode_forall_leases failed\n");
5828 static NTSTATUS lease_match(connection_struct *conn,
5829 struct smb_request *req,
5830 const struct smb2_lease_key *lease_key,
5831 const char *servicepath,
5832 const struct smb_filename *fname,
5833 uint16_t *p_version,
5834 uint16_t *p_epoch)
5836 struct smbd_server_connection *sconn = req->sconn;
5837 TALLOC_CTX *tos = talloc_tos();
5838 struct lease_match_state state = {
5839 .mem_ctx = tos,
5840 .servicepath = servicepath,
5841 .fname = fname,
5842 .match_status = NT_STATUS_OK
5844 uint32_t i;
5845 NTSTATUS status;
5847 state.file_existed = VALID_STAT(fname->st);
5848 if (state.file_existed) {
5849 state.id = vfs_file_id_from_sbuf(conn, &fname->st);
5852 status = leases_db_parse(&sconn->client->global->client_guid,
5853 lease_key, lease_match_parser, &state);
5854 if (!NT_STATUS_IS_OK(status)) {
5856 * Not found or error means okay: We can make the lease pass
5858 return NT_STATUS_OK;
5860 if (!NT_STATUS_EQUAL(state.match_status, NT_STATUS_OPLOCK_NOT_GRANTED)) {
5862 * Anything but NT_STATUS_OPLOCK_NOT_GRANTED, let the caller
5863 * deal with it.
5865 return state.match_status;
5868 /* We have to break all existing leases. */
5869 for (i = 0; i < state.num_file_ids; i++) {
5870 struct lease_match_break_state break_state = {
5871 .msg_ctx = conn->sconn->msg_ctx,
5872 .lease_key = lease_key,
5875 if (file_id_equal(&state.ids[i], &state.id)) {
5876 /* Don't need to break our own file. */
5877 continue;
5880 break_state.id = state.ids[i];
5882 status = share_mode_do_locked_vfs_denied(break_state.id,
5883 lease_match_fid_fn,
5884 &break_state);
5885 if (!NT_STATUS_IS_OK(status)) {
5886 /* Race condition - file already closed. */
5887 continue;
5890 if (break_state.found_lease) {
5891 *p_version = break_state.version;
5892 *p_epoch = break_state.epoch;
5896 * Ensure we don't grant anything more so we
5897 * never upgrade.
5899 return NT_STATUS_OPLOCK_NOT_GRANTED;
5903 * Wrapper around open_file_ntcreate and open_directory
5906 static NTSTATUS create_file_unixpath(connection_struct *conn,
5907 struct smb_request *req,
5908 struct files_struct *dirfsp,
5909 struct smb_filename *smb_fname,
5910 uint32_t access_mask,
5911 uint32_t share_access,
5912 uint32_t create_disposition,
5913 uint32_t create_options,
5914 uint32_t file_attributes,
5915 uint32_t oplock_request,
5916 const struct smb2_lease *lease,
5917 uint64_t allocation_size,
5918 uint32_t private_flags,
5919 struct security_descriptor *sd,
5920 struct ea_list *ea_list,
5922 files_struct **result,
5923 int *pinfo)
5925 struct smb2_lease none_lease;
5926 int info = FILE_WAS_OPENED;
5927 files_struct *base_fsp = NULL;
5928 files_struct *fsp = NULL;
5929 bool free_fsp_on_error = false;
5930 NTSTATUS status;
5931 int ret;
5932 struct smb_filename *parent_dir_fname = NULL;
5933 struct smb_filename *smb_fname_atname = NULL;
5935 DBG_DEBUG("access_mask = 0x%"PRIx32" "
5936 "file_attributes = 0x%"PRIx32" "
5937 "share_access = 0x%"PRIx32" "
5938 "create_disposition = 0x%"PRIx32" "
5939 "create_options = 0x%"PRIx32" "
5940 "oplock_request = 0x%"PRIx32" "
5941 "private_flags = 0x%"PRIx32" "
5942 "ea_list = %p, "
5943 "sd = %p, "
5944 "fname = %s\n",
5945 access_mask,
5946 file_attributes,
5947 share_access,
5948 create_disposition,
5949 create_options,
5950 oplock_request,
5951 private_flags,
5952 ea_list,
5954 smb_fname_str_dbg(smb_fname));
5956 if (create_options & FILE_OPEN_BY_FILE_ID) {
5957 status = NT_STATUS_NOT_SUPPORTED;
5958 goto fail;
5961 if (create_options & NTCREATEX_OPTIONS_INVALID_PARAM_MASK) {
5962 status = NT_STATUS_INVALID_PARAMETER;
5963 goto fail;
5966 if (req == NULL) {
5967 oplock_request |= INTERNAL_OPEN_ONLY;
5970 if (lease != NULL) {
5971 uint16_t epoch = lease->lease_epoch;
5972 uint16_t version = lease->lease_version;
5974 if (req == NULL) {
5975 DBG_WARNING("Got lease on internal open\n");
5976 status = NT_STATUS_INTERNAL_ERROR;
5977 goto fail;
5980 status = lease_match(conn,
5981 req,
5982 &lease->lease_key,
5983 conn->connectpath,
5984 smb_fname,
5985 &version,
5986 &epoch);
5987 if (NT_STATUS_EQUAL(status, NT_STATUS_OPLOCK_NOT_GRANTED)) {
5988 /* Dynamic share file. No leases and update epoch... */
5989 none_lease = *lease;
5990 none_lease.lease_state = SMB2_LEASE_NONE;
5991 none_lease.lease_epoch = epoch;
5992 none_lease.lease_version = version;
5993 lease = &none_lease;
5994 } else if (!NT_STATUS_IS_OK(status)) {
5995 goto fail;
5999 if ((conn->fs_capabilities & FILE_NAMED_STREAMS)
6000 && (access_mask & DELETE_ACCESS)
6001 && !is_named_stream(smb_fname)) {
6003 * We can't open a file with DELETE access if any of the
6004 * streams is open without FILE_SHARE_DELETE
6006 status = open_streams_for_delete(conn, smb_fname);
6008 if (!NT_STATUS_IS_OK(status)) {
6009 goto fail;
6013 if (access_mask & SEC_FLAG_SYSTEM_SECURITY) {
6014 bool ok;
6016 ok = security_token_has_privilege(get_current_nttok(conn),
6017 SEC_PRIV_SECURITY);
6018 if (!ok) {
6019 DBG_DEBUG("open on %s failed - "
6020 "SEC_FLAG_SYSTEM_SECURITY denied.\n",
6021 smb_fname_str_dbg(smb_fname));
6022 status = NT_STATUS_PRIVILEGE_NOT_HELD;
6023 goto fail;
6026 if (conn->sconn->using_smb2 &&
6027 (access_mask == SEC_FLAG_SYSTEM_SECURITY))
6030 * No other bits set. Windows SMB2 refuses this.
6031 * See smbtorture3 SMB2-SACL test.
6033 * Note this is an SMB2-only behavior,
6034 * smbtorture3 SMB1-SYSTEM-SECURITY already tests
6035 * that SMB1 allows this.
6037 status = NT_STATUS_ACCESS_DENIED;
6038 goto fail;
6043 * Files or directories can't be opened DELETE_ON_CLOSE without
6044 * delete access.
6045 * BUG: https://bugzilla.samba.org/show_bug.cgi?id=13358
6047 if (create_options & FILE_DELETE_ON_CLOSE) {
6048 if ((access_mask & DELETE_ACCESS) == 0) {
6049 status = NT_STATUS_INVALID_PARAMETER;
6050 goto fail;
6054 if ((conn->fs_capabilities & FILE_NAMED_STREAMS)
6055 && is_named_stream(smb_fname))
6057 uint32_t base_create_disposition;
6058 struct smb_filename *smb_fname_base = NULL;
6059 uint32_t base_privflags;
6061 if (create_options & FILE_DIRECTORY_FILE) {
6062 DBG_DEBUG("Can't open a stream as directory\n");
6063 status = NT_STATUS_NOT_A_DIRECTORY;
6064 goto fail;
6067 switch (create_disposition) {
6068 case FILE_OPEN:
6069 base_create_disposition = FILE_OPEN;
6070 break;
6071 default:
6072 base_create_disposition = FILE_OPEN_IF;
6073 break;
6076 smb_fname_base = cp_smb_filename_nostream(
6077 talloc_tos(), smb_fname);
6079 if (smb_fname_base == NULL) {
6080 status = NT_STATUS_NO_MEMORY;
6081 goto fail;
6085 * We may be creating the basefile as part of creating the
6086 * stream, so it's legal if the basefile doesn't exist at this
6087 * point, the create_file_unixpath() below will create it. But
6088 * if the basefile exists we want a handle so we can fstat() it.
6091 ret = vfs_stat(conn, smb_fname_base);
6092 if (ret == -1 && errno != ENOENT) {
6093 status = map_nt_error_from_unix(errno);
6094 TALLOC_FREE(smb_fname_base);
6095 goto fail;
6097 if (ret == 0) {
6098 status = openat_pathref_fsp(conn->cwd_fsp,
6099 smb_fname_base);
6100 if (!NT_STATUS_IS_OK(status)) {
6101 DBG_ERR("open_smb_fname_fsp [%s] failed: %s\n",
6102 smb_fname_str_dbg(smb_fname_base),
6103 nt_errstr(status));
6104 TALLOC_FREE(smb_fname_base);
6105 goto fail;
6109 * https://bugzilla.samba.org/show_bug.cgi?id=10229
6110 * We need to check if the requested access mask
6111 * could be used to open the underlying file (if
6112 * it existed), as we're passing in zero for the
6113 * access mask to the base filename.
6115 status = check_base_file_access(smb_fname_base->fsp,
6116 access_mask);
6118 if (!NT_STATUS_IS_OK(status)) {
6119 DEBUG(10, ("Permission check "
6120 "for base %s failed: "
6121 "%s\n", smb_fname->base_name,
6122 nt_errstr(status)));
6123 TALLOC_FREE(smb_fname_base);
6124 goto fail;
6128 base_privflags = NTCREATEX_FLAG_STREAM_BASEOPEN;
6130 /* Open the base file. */
6131 status = create_file_unixpath(conn,
6132 NULL,
6133 dirfsp,
6134 smb_fname_base,
6136 FILE_SHARE_READ
6137 | FILE_SHARE_WRITE
6138 | FILE_SHARE_DELETE,
6139 base_create_disposition,
6143 NULL,
6145 base_privflags,
6146 NULL,
6147 NULL,
6148 &base_fsp,
6149 NULL);
6150 TALLOC_FREE(smb_fname_base);
6152 if (!NT_STATUS_IS_OK(status)) {
6153 DEBUG(10, ("create_file_unixpath for base %s failed: "
6154 "%s\n", smb_fname->base_name,
6155 nt_errstr(status)));
6156 goto fail;
6160 if (smb_fname->fsp != NULL) {
6162 fsp = smb_fname->fsp;
6165 * We're about to use smb_fname->fsp for the fresh open.
6167 * Every fsp passed in via smb_fname->fsp already
6168 * holds a fsp->fsp_name. If it is already this
6169 * fsp->fsp_name that we got passed in as our input
6170 * argument smb_fname, these two are assumed to have
6171 * the same lifetime: Every fsp hangs of "conn", and
6172 * fsp->fsp_name is its talloc child.
6175 if (smb_fname != smb_fname->fsp->fsp_name) {
6177 * "smb_fname" is temporary in this case, but
6178 * the destructor of smb_fname would also tear
6179 * down the fsp we're about to use. Unlink
6180 * them from each other.
6182 smb_fname_fsp_unlink(smb_fname);
6185 * "fsp" is ours now
6187 free_fsp_on_error = true;
6190 status = fsp_bind_smb(fsp, req);
6191 if (!NT_STATUS_IS_OK(status)) {
6192 goto fail;
6195 if (fsp_is_alternate_stream(fsp)) {
6196 struct files_struct *tmp_base_fsp = fsp->base_fsp;
6198 fsp_set_base_fsp(fsp, NULL);
6200 fd_close(tmp_base_fsp);
6201 file_free(NULL, tmp_base_fsp);
6203 } else {
6205 * No fsp passed in that we can use, create one
6207 status = file_new(req, conn, &fsp);
6208 if(!NT_STATUS_IS_OK(status)) {
6209 goto fail;
6211 free_fsp_on_error = true;
6213 status = fsp_set_smb_fname(fsp, smb_fname);
6214 if (!NT_STATUS_IS_OK(status)) {
6215 goto fail;
6219 SMB_ASSERT(fsp->fsp_name->fsp != NULL);
6220 SMB_ASSERT(fsp->fsp_name->fsp == fsp);
6222 if (base_fsp) {
6224 * We're opening the stream element of a
6225 * base_fsp we already opened. Set up the
6226 * base_fsp pointer.
6228 fsp_set_base_fsp(fsp, base_fsp);
6231 if (dirfsp != NULL) {
6232 status = SMB_VFS_PARENT_PATHNAME(
6233 conn,
6234 talloc_tos(),
6235 smb_fname,
6236 &parent_dir_fname,
6237 &smb_fname_atname);
6238 if (!NT_STATUS_IS_OK(status)) {
6239 goto fail;
6241 } else {
6243 * Get a pathref on the parent. We can re-use this for
6244 * multiple calls to check parent ACLs etc. to avoid
6245 * pathname calls.
6247 status = parent_pathref(talloc_tos(),
6248 conn->cwd_fsp,
6249 smb_fname,
6250 &parent_dir_fname,
6251 &smb_fname_atname);
6252 if (!NT_STATUS_IS_OK(status)) {
6253 goto fail;
6256 dirfsp = parent_dir_fname->fsp;
6257 status = fsp_set_smb_fname(dirfsp, parent_dir_fname);
6258 if (!NT_STATUS_IS_OK(status)) {
6259 goto fail;
6264 * If it's a request for a directory open, deal with it separately.
6267 if (create_options & FILE_DIRECTORY_FILE) {
6269 if (create_options & FILE_NON_DIRECTORY_FILE) {
6270 status = NT_STATUS_INVALID_PARAMETER;
6271 goto fail;
6274 /* Can't open a temp directory. IFS kit test. */
6275 if (!(file_attributes & FILE_FLAG_POSIX_SEMANTICS) &&
6276 (file_attributes & FILE_ATTRIBUTE_TEMPORARY)) {
6277 status = NT_STATUS_INVALID_PARAMETER;
6278 goto fail;
6282 * We will get a create directory here if the Win32
6283 * app specified a security descriptor in the
6284 * CreateDirectory() call.
6287 oplock_request = 0;
6288 status = open_directory(conn,
6289 req,
6290 access_mask,
6291 share_access,
6292 create_disposition,
6293 create_options,
6294 file_attributes,
6295 dirfsp->fsp_name,
6296 smb_fname_atname,
6297 &info,
6298 fsp);
6299 } else {
6302 * Ordinary file case.
6305 if (allocation_size) {
6306 fsp->initial_allocation_size = smb_roundup(fsp->conn,
6307 allocation_size);
6310 status = open_file_ntcreate(conn,
6311 req,
6312 access_mask,
6313 share_access,
6314 create_disposition,
6315 create_options,
6316 file_attributes,
6317 oplock_request,
6318 lease,
6319 private_flags,
6320 dirfsp->fsp_name,
6321 smb_fname_atname,
6322 &info,
6323 fsp);
6324 if (NT_STATUS_EQUAL(status, NT_STATUS_FILE_IS_A_DIRECTORY)) {
6326 /* A stream open never opens a directory */
6328 if (base_fsp) {
6329 status = NT_STATUS_FILE_IS_A_DIRECTORY;
6330 goto fail;
6334 * Fail the open if it was explicitly a non-directory
6335 * file.
6338 if (create_options & FILE_NON_DIRECTORY_FILE) {
6339 status = NT_STATUS_FILE_IS_A_DIRECTORY;
6340 goto fail;
6343 oplock_request = 0;
6344 status = open_directory(conn,
6345 req,
6346 access_mask,
6347 share_access,
6348 create_disposition,
6349 create_options,
6350 file_attributes,
6351 dirfsp->fsp_name,
6352 smb_fname_atname,
6353 &info,
6354 fsp);
6358 if (!NT_STATUS_IS_OK(status)) {
6359 goto fail;
6362 fsp->fsp_flags.is_fsa = true;
6364 if ((ea_list != NULL) &&
6365 ((info == FILE_WAS_CREATED) || (info == FILE_WAS_OVERWRITTEN))) {
6366 status = set_ea(conn, fsp, ea_list);
6367 if (!NT_STATUS_IS_OK(status)) {
6368 goto fail;
6372 if (!fsp->fsp_flags.is_directory &&
6373 S_ISDIR(fsp->fsp_name->st.st_ex_mode))
6375 status = NT_STATUS_ACCESS_DENIED;
6376 goto fail;
6379 /* Save the requested allocation size. */
6380 if ((info == FILE_WAS_CREATED) || (info == FILE_WAS_OVERWRITTEN)) {
6381 if ((allocation_size > (uint64_t)fsp->fsp_name->st.st_ex_size)
6382 && !(fsp->fsp_flags.is_directory))
6384 fsp->initial_allocation_size = smb_roundup(
6385 fsp->conn, allocation_size);
6386 if (vfs_allocate_file_space(
6387 fsp, fsp->initial_allocation_size) == -1) {
6388 status = NT_STATUS_DISK_FULL;
6389 goto fail;
6391 } else {
6392 fsp->initial_allocation_size = smb_roundup(
6393 fsp->conn, (uint64_t)fsp->fsp_name->st.st_ex_size);
6395 } else {
6396 fsp->initial_allocation_size = 0;
6399 if ((info == FILE_WAS_CREATED) &&
6400 lp_nt_acl_support(SNUM(conn)) &&
6401 !fsp_is_alternate_stream(fsp)) {
6402 if (sd != NULL) {
6404 * According to the MS documentation, the only time the security
6405 * descriptor is applied to the opened file is iff we *created* the
6406 * file; an existing file stays the same.
6408 * Also, it seems (from observation) that you can open the file with
6409 * any access mask but you can still write the sd. We need to override
6410 * the granted access before we call set_sd
6411 * Patch for bug #2242 from Tom Lackemann <cessnatomny@yahoo.com>.
6414 uint32_t sec_info_sent;
6415 uint32_t saved_access_mask = fsp->access_mask;
6417 sec_info_sent = get_sec_info(sd);
6419 fsp->access_mask = FILE_GENERIC_ALL;
6421 if (sec_info_sent & (SECINFO_OWNER|
6422 SECINFO_GROUP|
6423 SECINFO_DACL|
6424 SECINFO_SACL)) {
6425 status = set_sd(fsp, sd, sec_info_sent);
6428 fsp->access_mask = saved_access_mask;
6430 if (!NT_STATUS_IS_OK(status)) {
6431 goto fail;
6433 } else if (lp_inherit_acls(SNUM(conn))) {
6434 /* Inherit from parent. Errors here are not fatal. */
6435 status = inherit_new_acl(dirfsp, fsp);
6436 if (!NT_STATUS_IS_OK(status)) {
6437 DEBUG(10,("inherit_new_acl: failed for %s with %s\n",
6438 fsp_str_dbg(fsp),
6439 nt_errstr(status) ));
6444 if ((conn->fs_capabilities & FILE_FILE_COMPRESSION)
6445 && (create_options & FILE_NO_COMPRESSION)
6446 && (info == FILE_WAS_CREATED)) {
6447 status = SMB_VFS_SET_COMPRESSION(conn, fsp, fsp,
6448 COMPRESSION_FORMAT_NONE);
6449 if (!NT_STATUS_IS_OK(status)) {
6450 DEBUG(1, ("failed to disable compression: %s\n",
6451 nt_errstr(status)));
6455 DEBUG(10, ("create_file_unixpath: info=%d\n", info));
6457 *result = fsp;
6458 if (pinfo != NULL) {
6459 *pinfo = info;
6462 smb_fname->st = fsp->fsp_name->st;
6464 TALLOC_FREE(parent_dir_fname);
6466 return NT_STATUS_OK;
6468 fail:
6469 DEBUG(10, ("create_file_unixpath: %s\n", nt_errstr(status)));
6471 if (fsp != NULL) {
6473 * The close_file below will close
6474 * fsp->base_fsp.
6476 base_fsp = NULL;
6477 close_file_smb(req, fsp, ERROR_CLOSE);
6478 if (free_fsp_on_error) {
6479 file_free(req, fsp);
6480 fsp = NULL;
6483 if (base_fsp != NULL) {
6484 close_file_free(req, &base_fsp, ERROR_CLOSE);
6487 TALLOC_FREE(parent_dir_fname);
6489 return status;
6492 NTSTATUS create_file_default(connection_struct *conn,
6493 struct smb_request *req,
6494 struct files_struct *dirfsp,
6495 struct smb_filename *smb_fname,
6496 uint32_t access_mask,
6497 uint32_t share_access,
6498 uint32_t create_disposition,
6499 uint32_t create_options,
6500 uint32_t file_attributes,
6501 uint32_t oplock_request,
6502 const struct smb2_lease *lease,
6503 uint64_t allocation_size,
6504 uint32_t private_flags,
6505 struct security_descriptor *sd,
6506 struct ea_list *ea_list,
6507 files_struct **result,
6508 int *pinfo,
6509 const struct smb2_create_blobs *in_context_blobs,
6510 struct smb2_create_blobs *out_context_blobs)
6512 int info = FILE_WAS_OPENED;
6513 files_struct *fsp = NULL;
6514 NTSTATUS status;
6515 bool stream_name = false;
6516 struct smb2_create_blob *posx = NULL;
6518 DBG_DEBUG("create_file: access_mask = 0x%x "
6519 "file_attributes = 0x%x, share_access = 0x%x, "
6520 "create_disposition = 0x%x create_options = 0x%x "
6521 "oplock_request = 0x%x "
6522 "private_flags = 0x%x "
6523 "ea_list = %p, sd = %p, "
6524 "fname = %s\n",
6525 (unsigned int)access_mask,
6526 (unsigned int)file_attributes,
6527 (unsigned int)share_access,
6528 (unsigned int)create_disposition,
6529 (unsigned int)create_options,
6530 (unsigned int)oplock_request,
6531 (unsigned int)private_flags,
6532 ea_list,
6534 smb_fname_str_dbg(smb_fname));
6536 if (req != NULL) {
6538 * Remember the absolute time of the original request
6539 * with this mid. We'll use it later to see if this
6540 * has timed out.
6542 get_deferred_open_message_state(req, &req->request_time, NULL);
6546 * Check to see if this is a mac fork of some kind.
6549 stream_name = is_ntfs_stream_smb_fname(smb_fname);
6550 if (stream_name) {
6551 enum FAKE_FILE_TYPE fake_file_type;
6553 fake_file_type = is_fake_file(smb_fname);
6555 if (req != NULL && fake_file_type != FAKE_FILE_TYPE_NONE) {
6558 * Here we go! support for changing the disk quotas
6559 * --metze
6561 * We need to fake up to open this MAGIC QUOTA file
6562 * and return a valid FID.
6564 * w2k close this file directly after opening xp
6565 * also tries a QUERY_FILE_INFO on the file and then
6566 * close it
6568 status = open_fake_file(req, conn, req->vuid,
6569 fake_file_type, smb_fname,
6570 access_mask, &fsp);
6571 if (!NT_STATUS_IS_OK(status)) {
6572 goto fail;
6575 ZERO_STRUCT(smb_fname->st);
6576 goto done;
6579 if (!(conn->fs_capabilities & FILE_NAMED_STREAMS)) {
6580 status = NT_STATUS_OBJECT_NAME_INVALID;
6581 goto fail;
6585 if (is_ntfs_default_stream_smb_fname(smb_fname)) {
6586 int ret;
6587 /* We have to handle this error here. */
6588 if (create_options & FILE_DIRECTORY_FILE) {
6589 status = NT_STATUS_NOT_A_DIRECTORY;
6590 goto fail;
6592 ret = vfs_stat(conn, smb_fname);
6593 if (ret == 0 && VALID_STAT_OF_DIR(smb_fname->st)) {
6594 status = NT_STATUS_FILE_IS_A_DIRECTORY;
6595 goto fail;
6599 posx = smb2_create_blob_find(
6600 in_context_blobs, SMB2_CREATE_TAG_POSIX);
6601 if (posx != NULL) {
6602 uint32_t wire_mode_bits = 0;
6603 mode_t mode_bits = 0;
6604 SMB_STRUCT_STAT sbuf = { 0 };
6605 enum perm_type ptype =
6606 (create_options & FILE_DIRECTORY_FILE) ?
6607 PERM_NEW_DIR : PERM_NEW_FILE;
6609 if (posx->data.length != 4) {
6610 status = NT_STATUS_INVALID_PARAMETER;
6611 goto fail;
6614 wire_mode_bits = IVAL(posx->data.data, 0);
6615 status = unix_perms_from_wire(
6616 conn, &sbuf, wire_mode_bits, ptype, &mode_bits);
6617 if (!NT_STATUS_IS_OK(status)) {
6618 goto fail;
6621 * Remove type info from mode, leaving only the
6622 * permissions and setuid/gid bits.
6624 mode_bits &= ~S_IFMT;
6626 file_attributes = (FILE_FLAG_POSIX_SEMANTICS | mode_bits);
6629 status = create_file_unixpath(conn,
6630 req,
6631 dirfsp,
6632 smb_fname,
6633 access_mask,
6634 share_access,
6635 create_disposition,
6636 create_options,
6637 file_attributes,
6638 oplock_request,
6639 lease,
6640 allocation_size,
6641 private_flags,
6643 ea_list,
6644 &fsp,
6645 &info);
6646 if (!NT_STATUS_IS_OK(status)) {
6647 goto fail;
6650 done:
6651 DEBUG(10, ("create_file: info=%d\n", info));
6653 *result = fsp;
6654 if (pinfo != NULL) {
6655 *pinfo = info;
6657 return NT_STATUS_OK;
6659 fail:
6660 DEBUG(10, ("create_file: %s\n", nt_errstr(status)));
6662 if (fsp != NULL) {
6663 close_file_free(req, &fsp, ERROR_CLOSE);
6665 return status;