winbind_nss_freebsd: fix const discard warning
[Samba.git] / source3 / smbd / open.c
blob8c52f4bba56b0af8262409063fca55bfaab45b74
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 "smbd/smbd.h"
28 #include "smbd/globals.h"
29 #include "fake_file.h"
30 #include "../libcli/security/security.h"
31 #include "../librpc/gen_ndr/ndr_security.h"
32 #include "../librpc/gen_ndr/open_files.h"
33 #include "../librpc/gen_ndr/idmap.h"
34 #include "../librpc/gen_ndr/ioctl.h"
35 #include "passdb/lookup_sid.h"
36 #include "auth.h"
37 #include "serverid.h"
38 #include "messages.h"
39 #include "source3/lib/dbwrap/dbwrap_watch.h"
40 #include "locking/leases_db.h"
41 #include "librpc/gen_ndr/ndr_leases_db.h"
43 extern const struct generic_mapping file_generic_mapping;
45 struct deferred_open_record {
46 bool delayed_for_oplocks;
47 bool async_open;
48 struct file_id id;
51 * Timer for async opens, needed because they don't use a watch on
52 * a locking.tdb record. This is currently only used for real async
53 * opens and just terminates smbd if the async open times out.
55 struct tevent_timer *te;
58 /****************************************************************************
59 If the requester wanted DELETE_ACCESS and was rejected because
60 the file ACL didn't include DELETE_ACCESS, see if the parent ACL
61 overrides this.
62 ****************************************************************************/
64 static bool parent_override_delete(connection_struct *conn,
65 const struct smb_filename *smb_fname,
66 uint32_t access_mask,
67 uint32_t rejected_mask)
69 if ((access_mask & DELETE_ACCESS) &&
70 (rejected_mask & DELETE_ACCESS) &&
71 can_delete_file_in_directory(conn, smb_fname)) {
72 return true;
74 return false;
77 /****************************************************************************
78 Check if we have open rights.
79 ****************************************************************************/
81 NTSTATUS smbd_check_access_rights(struct connection_struct *conn,
82 const struct smb_filename *smb_fname,
83 bool use_privs,
84 uint32_t access_mask)
86 /* Check if we have rights to open. */
87 NTSTATUS status;
88 struct security_descriptor *sd = NULL;
89 uint32_t rejected_share_access;
90 uint32_t rejected_mask = access_mask;
91 uint32_t do_not_check_mask = 0;
93 rejected_share_access = access_mask & ~(conn->share_access);
95 if (rejected_share_access) {
96 DEBUG(10, ("smbd_check_access_rights: rejected share access 0x%x "
97 "on %s (0x%x)\n",
98 (unsigned int)access_mask,
99 smb_fname_str_dbg(smb_fname),
100 (unsigned int)rejected_share_access ));
101 return NT_STATUS_ACCESS_DENIED;
104 if (!use_privs && get_current_uid(conn) == (uid_t)0) {
105 /* I'm sorry sir, I didn't know you were root... */
106 DEBUG(10,("smbd_check_access_rights: root override "
107 "on %s. Granting 0x%x\n",
108 smb_fname_str_dbg(smb_fname),
109 (unsigned int)access_mask ));
110 return NT_STATUS_OK;
113 if ((access_mask & DELETE_ACCESS) && !lp_acl_check_permissions(SNUM(conn))) {
114 DEBUG(10,("smbd_check_access_rights: not checking ACL "
115 "on DELETE_ACCESS on file %s. Granting 0x%x\n",
116 smb_fname_str_dbg(smb_fname),
117 (unsigned int)access_mask ));
118 return NT_STATUS_OK;
121 if (access_mask == DELETE_ACCESS &&
122 VALID_STAT(smb_fname->st) &&
123 S_ISLNK(smb_fname->st.st_ex_mode)) {
124 /* We can always delete a symlink. */
125 DEBUG(10,("smbd_check_access_rights: not checking ACL "
126 "on DELETE_ACCESS on symlink %s.\n",
127 smb_fname_str_dbg(smb_fname) ));
128 return NT_STATUS_OK;
131 status = SMB_VFS_GET_NT_ACL(conn, smb_fname,
132 (SECINFO_OWNER |
133 SECINFO_GROUP |
134 SECINFO_DACL), talloc_tos(), &sd);
136 if (!NT_STATUS_IS_OK(status)) {
137 DEBUG(10, ("smbd_check_access_rights: Could not get acl "
138 "on %s: %s\n",
139 smb_fname_str_dbg(smb_fname),
140 nt_errstr(status)));
142 if (NT_STATUS_EQUAL(status, NT_STATUS_ACCESS_DENIED)) {
143 goto access_denied;
146 return status;
150 * If we can access the path to this file, by
151 * default we have FILE_READ_ATTRIBUTES from the
152 * containing directory. See the section:
153 * "Algorithm to Check Access to an Existing File"
154 * in MS-FSA.pdf.
156 * se_file_access_check() also takes care of
157 * owner WRITE_DAC and READ_CONTROL.
159 do_not_check_mask = FILE_READ_ATTRIBUTES;
162 * Samba 3.6 and earlier granted execute access even
163 * if the ACL did not contain execute rights.
164 * Samba 4.0 is more correct and checks it.
165 * The compatibilty mode allows one to skip this check
166 * to smoothen upgrades.
168 if (lp_acl_allow_execute_always(SNUM(conn))) {
169 do_not_check_mask |= FILE_EXECUTE;
172 status = se_file_access_check(sd,
173 get_current_nttok(conn),
174 use_privs,
175 (access_mask & ~do_not_check_mask),
176 &rejected_mask);
178 DEBUG(10,("smbd_check_access_rights: file %s requesting "
179 "0x%x returning 0x%x (%s)\n",
180 smb_fname_str_dbg(smb_fname),
181 (unsigned int)access_mask,
182 (unsigned int)rejected_mask,
183 nt_errstr(status) ));
185 if (!NT_STATUS_IS_OK(status)) {
186 if (DEBUGLEVEL >= 10) {
187 DEBUG(10,("smbd_check_access_rights: acl for %s is:\n",
188 smb_fname_str_dbg(smb_fname) ));
189 NDR_PRINT_DEBUG(security_descriptor, sd);
193 TALLOC_FREE(sd);
195 if (NT_STATUS_IS_OK(status) ||
196 !NT_STATUS_EQUAL(status, NT_STATUS_ACCESS_DENIED)) {
197 return status;
200 /* Here we know status == NT_STATUS_ACCESS_DENIED. */
202 access_denied:
204 if ((access_mask & FILE_WRITE_ATTRIBUTES) &&
205 (rejected_mask & FILE_WRITE_ATTRIBUTES) &&
206 !lp_store_dos_attributes(SNUM(conn)) &&
207 (lp_map_readonly(SNUM(conn)) ||
208 lp_map_archive(SNUM(conn)) ||
209 lp_map_hidden(SNUM(conn)) ||
210 lp_map_system(SNUM(conn)))) {
211 rejected_mask &= ~FILE_WRITE_ATTRIBUTES;
213 DEBUG(10,("smbd_check_access_rights: "
214 "overrode "
215 "FILE_WRITE_ATTRIBUTES "
216 "on file %s\n",
217 smb_fname_str_dbg(smb_fname)));
220 if (parent_override_delete(conn,
221 smb_fname,
222 access_mask,
223 rejected_mask)) {
224 /* Were we trying to do an open
225 * for delete and didn't get DELETE
226 * access (only) ? Check if the
227 * directory allows DELETE_CHILD.
228 * See here:
229 * http://blogs.msdn.com/oldnewthing/archive/2004/06/04/148426.aspx
230 * for details. */
232 rejected_mask &= ~DELETE_ACCESS;
234 DEBUG(10,("smbd_check_access_rights: "
235 "overrode "
236 "DELETE_ACCESS on "
237 "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 check_parent_access(struct connection_struct *conn,
248 struct smb_filename *smb_fname,
249 uint32_t access_mask)
251 NTSTATUS status;
252 char *parent_dir = NULL;
253 struct security_descriptor *parent_sd = NULL;
254 uint32_t access_granted = 0;
255 struct smb_filename *parent_smb_fname = NULL;
257 if (!parent_dirname(talloc_tos(),
258 smb_fname->base_name,
259 &parent_dir,
260 NULL)) {
261 return NT_STATUS_NO_MEMORY;
264 parent_smb_fname = synthetic_smb_fname(talloc_tos(),
265 parent_dir,
266 NULL,
267 NULL,
268 smb_fname->flags);
269 if (parent_smb_fname == NULL) {
270 return NT_STATUS_NO_MEMORY;
273 if (get_current_uid(conn) == (uid_t)0) {
274 /* I'm sorry sir, I didn't know you were root... */
275 DEBUG(10,("check_parent_access: root override "
276 "on %s. Granting 0x%x\n",
277 smb_fname_str_dbg(smb_fname),
278 (unsigned int)access_mask ));
279 return NT_STATUS_OK;
282 status = SMB_VFS_GET_NT_ACL(conn,
283 parent_smb_fname,
284 SECINFO_DACL,
285 talloc_tos(),
286 &parent_sd);
288 if (!NT_STATUS_IS_OK(status)) {
289 DEBUG(5,("check_parent_access: SMB_VFS_GET_NT_ACL failed for "
290 "%s with error %s\n",
291 parent_dir,
292 nt_errstr(status)));
293 return status;
297 * If we can access the path to this file, by
298 * default we have FILE_READ_ATTRIBUTES from the
299 * containing directory. See the section:
300 * "Algorithm to Check Access to an Existing File"
301 * in MS-FSA.pdf.
303 * se_file_access_check() also takes care of
304 * owner WRITE_DAC and READ_CONTROL.
306 status = se_file_access_check(parent_sd,
307 get_current_nttok(conn),
308 false,
309 (access_mask & ~FILE_READ_ATTRIBUTES),
310 &access_granted);
311 if(!NT_STATUS_IS_OK(status)) {
312 DEBUG(5,("check_parent_access: access check "
313 "on directory %s for "
314 "path %s for mask 0x%x returned (0x%x) %s\n",
315 parent_dir,
316 smb_fname->base_name,
317 access_mask,
318 access_granted,
319 nt_errstr(status) ));
320 return status;
323 return NT_STATUS_OK;
326 /****************************************************************************
327 Ensure when opening a base file for a stream open that we have permissions
328 to do so given the access mask on the base file.
329 ****************************************************************************/
331 static NTSTATUS check_base_file_access(struct connection_struct *conn,
332 struct smb_filename *smb_fname,
333 uint32_t access_mask)
335 NTSTATUS status;
337 status = smbd_calculate_access_mask(conn, smb_fname,
338 false,
339 access_mask,
340 &access_mask);
341 if (!NT_STATUS_IS_OK(status)) {
342 DEBUG(10, ("smbd_calculate_access_mask "
343 "on file %s returned %s\n",
344 smb_fname_str_dbg(smb_fname),
345 nt_errstr(status)));
346 return status;
349 if (access_mask & (FILE_WRITE_DATA|FILE_APPEND_DATA)) {
350 uint32_t dosattrs;
351 if (!CAN_WRITE(conn)) {
352 return NT_STATUS_ACCESS_DENIED;
354 dosattrs = dos_mode(conn, smb_fname);
355 if (IS_DOS_READONLY(dosattrs)) {
356 return NT_STATUS_ACCESS_DENIED;
360 return smbd_check_access_rights(conn,
361 smb_fname,
362 false,
363 access_mask);
366 /****************************************************************************
367 Handle differing symlink errno's
368 ****************************************************************************/
370 static int link_errno_convert(int err)
372 #if defined(ENOTSUP) && defined(OSF1)
373 /* handle special Tru64 errno */
374 if (err == ENOTSUP) {
375 err = ELOOP;
377 #endif /* ENOTSUP */
378 #ifdef EFTYPE
379 /* fix broken NetBSD errno */
380 if (err == EFTYPE) {
381 err = ELOOP;
383 #endif /* EFTYPE */
384 /* fix broken FreeBSD errno */
385 if (err == EMLINK) {
386 err = ELOOP;
388 return err;
391 static int non_widelink_open(struct connection_struct *conn,
392 const struct smb_filename *conn_rootdir_fname,
393 files_struct *fsp,
394 struct smb_filename *smb_fname,
395 int flags,
396 mode_t mode,
397 unsigned int link_depth);
399 /****************************************************************************
400 Follow a symlink in userspace.
401 ****************************************************************************/
403 static int process_symlink_open(struct connection_struct *conn,
404 const struct smb_filename *conn_rootdir_fname,
405 files_struct *fsp,
406 struct smb_filename *smb_fname,
407 int flags,
408 mode_t mode,
409 unsigned int link_depth)
411 int fd = -1;
412 char *link_target = NULL;
413 struct smb_filename target_fname = {0};
414 int link_len = -1;
415 struct smb_filename *oldwd_fname = NULL;
416 size_t rootdir_len = 0;
417 struct smb_filename *resolved_fname = NULL;
418 char *resolved_name = NULL;
419 bool matched = false;
420 int saved_errno = 0;
423 * Ensure we don't get stuck in a symlink loop.
425 link_depth++;
426 if (link_depth >= 20) {
427 errno = ELOOP;
428 goto out;
431 /* Allocate space for the link target. */
432 link_target = talloc_array(talloc_tos(), char, PATH_MAX);
433 if (link_target == NULL) {
434 errno = ENOMEM;
435 goto out;
438 /* Read the link target. */
439 link_len = SMB_VFS_READLINK(conn,
440 smb_fname,
441 link_target,
442 PATH_MAX - 1);
443 if (link_len == -1) {
444 goto out;
447 /* Ensure it's at least null terminated. */
448 link_target[link_len] = '\0';
449 target_fname = (struct smb_filename){ .base_name = link_target };
451 /* Convert to an absolute path. */
452 resolved_fname = SMB_VFS_REALPATH(conn, talloc_tos(), &target_fname);
453 if (resolved_fname == NULL) {
454 goto out;
456 resolved_name = resolved_fname->base_name;
459 * We know conn_rootdir starts with '/' and
460 * does not end in '/'. FIXME ! Should we
461 * smb_assert this ?
463 rootdir_len = strlen(conn_rootdir_fname->base_name);
465 matched = (strncmp(conn_rootdir_fname->base_name,
466 resolved_name,
467 rootdir_len) == 0);
468 if (!matched) {
469 errno = EACCES;
470 goto out;
474 * Turn into a path relative to the share root.
476 if (resolved_name[rootdir_len] == '\0') {
477 /* Link to the root of the share. */
478 TALLOC_FREE(smb_fname->base_name);
479 smb_fname->base_name = talloc_strdup(smb_fname, ".");
480 } else if (resolved_name[rootdir_len] == '/') {
481 TALLOC_FREE(smb_fname->base_name);
482 smb_fname->base_name = talloc_strdup(smb_fname,
483 &resolved_name[rootdir_len+1]);
484 } else {
485 errno = EACCES;
486 goto out;
489 if (smb_fname->base_name == NULL) {
490 errno = ENOMEM;
491 goto out;
494 oldwd_fname = vfs_GetWd(talloc_tos(), conn);
495 if (oldwd_fname == NULL) {
496 goto out;
499 /* Ensure we operate from the root of the share. */
500 if (vfs_ChDir(conn, conn_rootdir_fname) == -1) {
501 goto out;
504 /* And do it all again.. */
505 fd = non_widelink_open(conn,
506 conn_rootdir_fname,
507 fsp,
508 smb_fname,
509 flags,
510 mode,
511 link_depth);
512 if (fd == -1) {
513 saved_errno = errno;
516 out:
518 TALLOC_FREE(resolved_fname);
519 TALLOC_FREE(link_target);
520 if (oldwd_fname != NULL) {
521 int ret = vfs_ChDir(conn, oldwd_fname);
522 if (ret == -1) {
523 smb_panic("unable to get back to old directory\n");
525 TALLOC_FREE(oldwd_fname);
527 if (saved_errno != 0) {
528 errno = saved_errno;
530 return fd;
533 /****************************************************************************
534 Non-widelink open.
535 ****************************************************************************/
537 static int non_widelink_open(struct connection_struct *conn,
538 const struct smb_filename *conn_rootdir_fname,
539 files_struct *fsp,
540 struct smb_filename *smb_fname,
541 int flags,
542 mode_t mode,
543 unsigned int link_depth)
545 NTSTATUS status;
546 int fd = -1;
547 struct smb_filename *smb_fname_rel = NULL;
548 int saved_errno = 0;
549 struct smb_filename *oldwd_fname = NULL;
550 char *parent_dir = NULL;
551 struct smb_filename parent_dir_fname = {0};
552 const char *final_component = NULL;
553 bool is_directory = false;
554 bool ok;
556 #ifdef O_DIRECTORY
557 if (flags & O_DIRECTORY) {
558 is_directory = true;
560 #endif
562 if (is_directory) {
563 parent_dir = talloc_strdup(talloc_tos(), smb_fname->base_name);
564 if (parent_dir == NULL) {
565 saved_errno = errno;
566 goto out;
569 final_component = ".";
570 } else {
571 ok = parent_dirname(talloc_tos(),
572 smb_fname->base_name,
573 &parent_dir,
574 &final_component);
575 if (!ok) {
576 saved_errno = errno;
577 goto out;
581 parent_dir_fname = (struct smb_filename) { .base_name = parent_dir };
583 oldwd_fname = vfs_GetWd(talloc_tos(), conn);
584 if (oldwd_fname == NULL) {
585 goto out;
588 /* Pin parent directory in place. */
589 if (vfs_ChDir(conn, &parent_dir_fname) == -1) {
590 goto out;
593 smb_fname_rel = synthetic_smb_fname(talloc_tos(),
594 final_component,
595 smb_fname->stream_name,
596 &smb_fname->st,
597 smb_fname->flags);
598 if (smb_fname_rel == NULL) {
599 saved_errno = ENOMEM;
600 goto out;
603 /* Ensure the relative path is below the share. */
604 status = check_reduced_name(conn, &parent_dir_fname, smb_fname_rel);
605 if (!NT_STATUS_IS_OK(status)) {
606 saved_errno = map_errno_from_nt_status(status);
607 goto out;
610 flags |= O_NOFOLLOW;
613 struct smb_filename *tmp_name = fsp->fsp_name;
614 fsp->fsp_name = smb_fname_rel;
615 fd = SMB_VFS_OPEN(conn, smb_fname_rel, fsp, flags, mode);
616 fsp->fsp_name = tmp_name;
619 if (fd == -1) {
620 saved_errno = link_errno_convert(errno);
622 * Trying to open a symlink to a directory with O_NOFOLLOW and
623 * O_DIRECTORY can return either of ELOOP and ENOTDIR. So
624 * ENOTDIR really means: might be a symlink, but we're not sure.
625 * In this case, we just assume there's a symlink. If we were
626 * wrong, process_symlink_open() will return EINVAL. We check
627 * this below, and fall back to returning the initial
628 * saved_errno.
630 * BUG: https://bugzilla.samba.org/show_bug.cgi?id=12860
632 if (saved_errno == ELOOP || saved_errno == ENOTDIR) {
633 if (fsp->posix_flags & FSP_POSIX_FLAGS_OPEN) {
634 /* Never follow symlinks on posix open. */
635 goto out;
637 if (!lp_follow_symlinks(SNUM(conn))) {
638 /* Explicitly no symlinks. */
639 goto out;
642 * We may have a symlink. Follow in userspace
643 * to ensure it's under the share definition.
645 fd = process_symlink_open(conn,
646 conn_rootdir_fname,
647 fsp,
648 smb_fname_rel,
649 flags,
650 mode,
651 link_depth);
652 if (fd == -1) {
653 if (saved_errno == ENOTDIR &&
654 errno == EINVAL) {
656 * O_DIRECTORY on neither a directory,
657 * nor a symlink. Just return
658 * saved_errno from initial open()
660 goto out;
662 saved_errno =
663 link_errno_convert(errno);
668 out:
670 TALLOC_FREE(parent_dir);
671 TALLOC_FREE(smb_fname_rel);
673 if (oldwd_fname != NULL) {
674 int ret = vfs_ChDir(conn, oldwd_fname);
675 if (ret == -1) {
676 smb_panic("unable to get back to old directory\n");
678 TALLOC_FREE(oldwd_fname);
680 if (saved_errno != 0) {
681 errno = saved_errno;
683 return fd;
686 /****************************************************************************
687 fd support routines - attempt to do a dos_open.
688 ****************************************************************************/
690 NTSTATUS fd_open(struct connection_struct *conn,
691 files_struct *fsp,
692 int flags,
693 mode_t mode)
695 struct smb_filename *smb_fname = fsp->fsp_name;
696 NTSTATUS status = NT_STATUS_OK;
699 * Never follow symlinks on a POSIX client. The
700 * client should be doing this.
703 if ((fsp->posix_flags & FSP_POSIX_FLAGS_OPEN) || !lp_follow_symlinks(SNUM(conn))) {
704 flags |= O_NOFOLLOW;
707 /* Ensure path is below share definition. */
708 if (!lp_widelinks(SNUM(conn))) {
709 struct smb_filename *conn_rootdir_fname = NULL;
710 const char *conn_rootdir = SMB_VFS_CONNECTPATH(conn,
711 smb_fname);
712 int saved_errno = 0;
714 if (conn_rootdir == NULL) {
715 return NT_STATUS_NO_MEMORY;
717 conn_rootdir_fname = synthetic_smb_fname(talloc_tos(),
718 conn_rootdir,
719 NULL,
720 NULL,
722 if (conn_rootdir_fname == NULL) {
723 return NT_STATUS_NO_MEMORY;
727 * Only follow symlinks within a share
728 * definition.
730 fsp->fh->fd = non_widelink_open(conn,
731 conn_rootdir_fname,
732 fsp,
733 smb_fname,
734 flags,
735 mode,
737 if (fsp->fh->fd == -1) {
738 saved_errno = errno;
740 TALLOC_FREE(conn_rootdir_fname);
741 if (saved_errno != 0) {
742 errno = saved_errno;
744 } else {
745 fsp->fh->fd = SMB_VFS_OPEN(conn, smb_fname, fsp, flags, mode);
748 if (fsp->fh->fd == -1) {
749 int posix_errno = link_errno_convert(errno);
750 status = map_nt_error_from_unix(posix_errno);
751 if (errno == EMFILE) {
752 static time_t last_warned = 0L;
754 if (time((time_t *) NULL) > last_warned) {
755 DEBUG(0,("Too many open files, unable "
756 "to open more! smbd's max "
757 "open files = %d\n",
758 lp_max_open_files()));
759 last_warned = time((time_t *) NULL);
765 DEBUG(10,("fd_open: name %s, flags = 0%o mode = 0%o, fd = %d. %s\n",
766 smb_fname_str_dbg(smb_fname), flags, (int)mode, fsp->fh->fd,
767 (fsp->fh->fd == -1) ? strerror(errno) : "" ));
769 return status;
772 /****************************************************************************
773 Close the file associated with a fsp.
774 ****************************************************************************/
776 NTSTATUS fd_close(files_struct *fsp)
778 int ret;
780 if (fsp->dptr) {
781 dptr_CloseDir(fsp);
783 if (fsp->fh->fd == -1) {
784 return NT_STATUS_OK; /* What we used to call a stat open. */
786 if (fsp->fh->ref_count > 1) {
787 return NT_STATUS_OK; /* Shared handle. Only close last reference. */
790 ret = SMB_VFS_CLOSE(fsp);
791 fsp->fh->fd = -1;
792 if (ret == -1) {
793 return map_nt_error_from_unix(errno);
795 return NT_STATUS_OK;
798 /****************************************************************************
799 Change the ownership of a file to that of the parent directory.
800 Do this by fd if possible.
801 ****************************************************************************/
803 void change_file_owner_to_parent(connection_struct *conn,
804 const char *inherit_from_dir,
805 files_struct *fsp)
807 struct smb_filename *smb_fname_parent;
808 int ret;
810 smb_fname_parent = synthetic_smb_fname(talloc_tos(),
811 inherit_from_dir,
812 NULL,
813 NULL,
815 if (smb_fname_parent == NULL) {
816 return;
819 ret = SMB_VFS_STAT(conn, smb_fname_parent);
820 if (ret == -1) {
821 DEBUG(0,("change_file_owner_to_parent: failed to stat parent "
822 "directory %s. Error was %s\n",
823 smb_fname_str_dbg(smb_fname_parent),
824 strerror(errno)));
825 TALLOC_FREE(smb_fname_parent);
826 return;
829 if (smb_fname_parent->st.st_ex_uid == fsp->fsp_name->st.st_ex_uid) {
830 /* Already this uid - no need to change. */
831 DEBUG(10,("change_file_owner_to_parent: file %s "
832 "is already owned by uid %d\n",
833 fsp_str_dbg(fsp),
834 (int)fsp->fsp_name->st.st_ex_uid ));
835 TALLOC_FREE(smb_fname_parent);
836 return;
839 become_root();
840 ret = SMB_VFS_FCHOWN(fsp, smb_fname_parent->st.st_ex_uid, (gid_t)-1);
841 unbecome_root();
842 if (ret == -1) {
843 DEBUG(0,("change_file_owner_to_parent: failed to fchown "
844 "file %s to parent directory uid %u. Error "
845 "was %s\n", fsp_str_dbg(fsp),
846 (unsigned int)smb_fname_parent->st.st_ex_uid,
847 strerror(errno) ));
848 } else {
849 DEBUG(10,("change_file_owner_to_parent: changed new file %s to "
850 "parent directory uid %u.\n", fsp_str_dbg(fsp),
851 (unsigned int)smb_fname_parent->st.st_ex_uid));
852 /* Ensure the uid entry is updated. */
853 fsp->fsp_name->st.st_ex_uid = smb_fname_parent->st.st_ex_uid;
856 TALLOC_FREE(smb_fname_parent);
859 static NTSTATUS change_dir_owner_to_parent(connection_struct *conn,
860 const char *inherit_from_dir,
861 struct smb_filename *smb_dname,
862 SMB_STRUCT_STAT *psbuf)
864 struct smb_filename *smb_fname_parent;
865 struct smb_filename *smb_fname_cwd = NULL;
866 struct smb_filename *saved_dir_fname = NULL;
867 TALLOC_CTX *ctx = talloc_tos();
868 NTSTATUS status = NT_STATUS_OK;
869 int ret;
871 smb_fname_parent = synthetic_smb_fname(ctx,
872 inherit_from_dir,
873 NULL,
874 NULL,
876 if (smb_fname_parent == NULL) {
877 return NT_STATUS_NO_MEMORY;
880 ret = SMB_VFS_STAT(conn, smb_fname_parent);
881 if (ret == -1) {
882 status = map_nt_error_from_unix(errno);
883 DEBUG(0,("change_dir_owner_to_parent: failed to stat parent "
884 "directory %s. Error was %s\n",
885 smb_fname_str_dbg(smb_fname_parent),
886 strerror(errno)));
887 goto out;
890 /* We've already done an lstat into psbuf, and we know it's a
891 directory. If we can cd into the directory and the dev/ino
892 are the same then we can safely chown without races as
893 we're locking the directory in place by being in it. This
894 should work on any UNIX (thanks tridge :-). JRA.
897 saved_dir_fname = vfs_GetWd(ctx,conn);
898 if (!saved_dir_fname) {
899 status = map_nt_error_from_unix(errno);
900 DEBUG(0,("change_dir_owner_to_parent: failed to get "
901 "current working directory. Error was %s\n",
902 strerror(errno)));
903 goto out;
906 /* Chdir into the new path. */
907 if (vfs_ChDir(conn, smb_dname) == -1) {
908 status = map_nt_error_from_unix(errno);
909 DEBUG(0,("change_dir_owner_to_parent: failed to change "
910 "current working directory to %s. Error "
911 "was %s\n", smb_dname->base_name, strerror(errno) ));
912 goto chdir;
915 smb_fname_cwd = synthetic_smb_fname(ctx, ".", NULL, NULL, 0);
916 if (smb_fname_cwd == NULL) {
917 status = NT_STATUS_NO_MEMORY;
918 goto chdir;
921 ret = SMB_VFS_STAT(conn, smb_fname_cwd);
922 if (ret == -1) {
923 status = map_nt_error_from_unix(errno);
924 DEBUG(0,("change_dir_owner_to_parent: failed to stat "
925 "directory '.' (%s) Error was %s\n",
926 smb_dname->base_name, strerror(errno)));
927 goto chdir;
930 /* Ensure we're pointing at the same place. */
931 if (smb_fname_cwd->st.st_ex_dev != psbuf->st_ex_dev ||
932 smb_fname_cwd->st.st_ex_ino != psbuf->st_ex_ino) {
933 DEBUG(0,("change_dir_owner_to_parent: "
934 "device/inode on directory %s changed. "
935 "Refusing to chown !\n",
936 smb_dname->base_name ));
937 status = NT_STATUS_ACCESS_DENIED;
938 goto chdir;
941 if (smb_fname_parent->st.st_ex_uid == smb_fname_cwd->st.st_ex_uid) {
942 /* Already this uid - no need to change. */
943 DEBUG(10,("change_dir_owner_to_parent: directory %s "
944 "is already owned by uid %d\n",
945 smb_dname->base_name,
946 (int)smb_fname_cwd->st.st_ex_uid ));
947 status = NT_STATUS_OK;
948 goto chdir;
951 become_root();
952 ret = SMB_VFS_LCHOWN(conn,
953 smb_fname_cwd,
954 smb_fname_parent->st.st_ex_uid,
955 (gid_t)-1);
956 unbecome_root();
957 if (ret == -1) {
958 status = map_nt_error_from_unix(errno);
959 DEBUG(10,("change_dir_owner_to_parent: failed to chown "
960 "directory %s to parent directory uid %u. "
961 "Error was %s\n",
962 smb_dname->base_name,
963 (unsigned int)smb_fname_parent->st.st_ex_uid,
964 strerror(errno) ));
965 } else {
966 DEBUG(10,("change_dir_owner_to_parent: changed ownership of new "
967 "directory %s to parent directory uid %u.\n",
968 smb_dname->base_name,
969 (unsigned int)smb_fname_parent->st.st_ex_uid ));
970 /* Ensure the uid entry is updated. */
971 psbuf->st_ex_uid = smb_fname_parent->st.st_ex_uid;
974 chdir:
975 vfs_ChDir(conn, saved_dir_fname);
976 out:
977 TALLOC_FREE(saved_dir_fname);
978 TALLOC_FREE(smb_fname_parent);
979 TALLOC_FREE(smb_fname_cwd);
980 return status;
983 /****************************************************************************
984 Open a file - returning a guaranteed ATOMIC indication of if the
985 file was created or not.
986 ****************************************************************************/
988 static NTSTATUS fd_open_atomic(struct connection_struct *conn,
989 files_struct *fsp,
990 int flags,
991 mode_t mode,
992 bool *file_created)
994 NTSTATUS status = NT_STATUS_UNSUCCESSFUL;
995 NTSTATUS retry_status;
996 bool file_existed = VALID_STAT(fsp->fsp_name->st);
997 int curr_flags;
999 *file_created = false;
1001 if (!(flags & O_CREAT)) {
1003 * We're not creating the file, just pass through.
1005 return fd_open(conn, fsp, flags, mode);
1008 if (flags & O_EXCL) {
1010 * Fail if already exists, just pass through.
1012 status = fd_open(conn, fsp, flags, mode);
1015 * Here we've opened with O_CREAT|O_EXCL. If that went
1016 * NT_STATUS_OK, we *know* we created this file.
1018 *file_created = NT_STATUS_IS_OK(status);
1020 return status;
1024 * Now it gets tricky. We have O_CREAT, but not O_EXCL.
1025 * To know absolutely if we created the file or not,
1026 * we can never call O_CREAT without O_EXCL. So if
1027 * we think the file existed, try without O_CREAT|O_EXCL.
1028 * If we think the file didn't exist, try with
1029 * O_CREAT|O_EXCL.
1031 * The big problem here is dangling symlinks. Opening
1032 * without O_NOFOLLOW means both bad symlink
1033 * and missing path return -1, ENOENT from open(). As POSIX
1034 * is pathname based it's not possible to tell
1035 * the difference between these two cases in a
1036 * non-racy way, so change to try only two attempts before
1037 * giving up.
1039 * We don't have this problem for the O_NOFOLLOW
1040 * case as it just returns NT_STATUS_OBJECT_PATH_NOT_FOUND
1041 * mapped from the ELOOP POSIX error.
1044 curr_flags = flags;
1046 if (file_existed) {
1047 curr_flags &= ~(O_CREAT);
1048 retry_status = NT_STATUS_OBJECT_NAME_NOT_FOUND;
1049 } else {
1050 curr_flags |= O_EXCL;
1051 retry_status = NT_STATUS_OBJECT_NAME_COLLISION;
1054 status = fd_open(conn, fsp, curr_flags, mode);
1055 if (NT_STATUS_IS_OK(status)) {
1056 if (!file_existed) {
1057 *file_created = true;
1059 return NT_STATUS_OK;
1061 if (!NT_STATUS_EQUAL(status, retry_status)) {
1062 return status;
1065 curr_flags = flags;
1068 * Keep file_existed up to date for clarity.
1070 if (NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
1071 file_existed = false;
1072 curr_flags |= O_EXCL;
1073 DBG_DEBUG("file %s did not exist. Retry.\n",
1074 smb_fname_str_dbg(fsp->fsp_name));
1075 } else {
1076 file_existed = true;
1077 curr_flags &= ~(O_CREAT);
1078 DBG_DEBUG("file %s existed. Retry.\n",
1079 smb_fname_str_dbg(fsp->fsp_name));
1082 status = fd_open(conn, fsp, curr_flags, mode);
1084 if (NT_STATUS_IS_OK(status) && (!file_existed)) {
1085 *file_created = true;
1088 return status;
1091 /****************************************************************************
1092 Open a file.
1093 ****************************************************************************/
1095 static NTSTATUS open_file(files_struct *fsp,
1096 connection_struct *conn,
1097 struct smb_request *req,
1098 const char *parent_dir,
1099 int flags,
1100 mode_t unx_mode,
1101 uint32_t access_mask, /* client requested access mask. */
1102 uint32_t open_access_mask, /* what we're actually using in the open. */
1103 bool *p_file_created)
1105 struct smb_filename *smb_fname = fsp->fsp_name;
1106 NTSTATUS status = NT_STATUS_OK;
1107 int accmode = (flags & O_ACCMODE);
1108 int local_flags = flags;
1109 bool file_existed = VALID_STAT(fsp->fsp_name->st);
1111 fsp->fh->fd = -1;
1112 errno = EPERM;
1114 /* Check permissions */
1117 * This code was changed after seeing a client open request
1118 * containing the open mode of (DENY_WRITE/read-only) with
1119 * the 'create if not exist' bit set. The previous code
1120 * would fail to open the file read only on a read-only share
1121 * as it was checking the flags parameter directly against O_RDONLY,
1122 * this was failing as the flags parameter was set to O_RDONLY|O_CREAT.
1123 * JRA.
1126 if (!CAN_WRITE(conn)) {
1127 /* It's a read-only share - fail if we wanted to write. */
1128 if(accmode != O_RDONLY || (flags & O_TRUNC) || (flags & O_APPEND)) {
1129 DEBUG(3,("Permission denied opening %s\n",
1130 smb_fname_str_dbg(smb_fname)));
1131 return NT_STATUS_ACCESS_DENIED;
1133 if (flags & O_CREAT) {
1134 /* We don't want to write - but we must make sure that
1135 O_CREAT doesn't create the file if we have write
1136 access into the directory.
1138 flags &= ~(O_CREAT|O_EXCL);
1139 local_flags &= ~(O_CREAT|O_EXCL);
1144 * This little piece of insanity is inspired by the
1145 * fact that an NT client can open a file for O_RDONLY,
1146 * but set the create disposition to FILE_EXISTS_TRUNCATE.
1147 * If the client *can* write to the file, then it expects to
1148 * truncate the file, even though it is opening for readonly.
1149 * Quicken uses this stupid trick in backup file creation...
1150 * Thanks *greatly* to "David W. Chapman Jr." <dwcjr@inethouston.net>
1151 * for helping track this one down. It didn't bite us in 2.0.x
1152 * as we always opened files read-write in that release. JRA.
1155 if ((accmode == O_RDONLY) && ((flags & O_TRUNC) == O_TRUNC)) {
1156 DEBUG(10,("open_file: truncate requested on read-only open "
1157 "for file %s\n", smb_fname_str_dbg(smb_fname)));
1158 local_flags = (flags & ~O_ACCMODE)|O_RDWR;
1161 if ((open_access_mask & (FILE_READ_DATA|FILE_WRITE_DATA|FILE_APPEND_DATA|FILE_EXECUTE)) ||
1162 (!file_existed && (local_flags & O_CREAT)) ||
1163 ((local_flags & O_TRUNC) == O_TRUNC) ) {
1164 const char *wild;
1165 int ret;
1167 #if defined(O_NONBLOCK) && defined(S_ISFIFO)
1169 * We would block on opening a FIFO with no one else on the
1170 * other end. Do what we used to do and add O_NONBLOCK to the
1171 * open flags. JRA.
1174 if (file_existed && S_ISFIFO(smb_fname->st.st_ex_mode)) {
1175 local_flags &= ~O_TRUNC; /* Can't truncate a FIFO. */
1176 local_flags |= O_NONBLOCK;
1178 #endif
1180 /* Don't create files with Microsoft wildcard characters. */
1181 if (fsp->base_fsp) {
1183 * wildcard characters are allowed in stream names
1184 * only test the basefilename
1186 wild = fsp->base_fsp->fsp_name->base_name;
1187 } else {
1188 wild = smb_fname->base_name;
1190 if ((local_flags & O_CREAT) && !file_existed &&
1191 !(fsp->posix_flags & FSP_POSIX_FLAGS_PATHNAMES) &&
1192 ms_has_wild(wild)) {
1193 return NT_STATUS_OBJECT_NAME_INVALID;
1196 /* Can we access this file ? */
1197 if (!fsp->base_fsp) {
1198 /* Only do this check on non-stream open. */
1199 if (file_existed) {
1200 status = smbd_check_access_rights(conn,
1201 smb_fname,
1202 false,
1203 access_mask);
1205 if (!NT_STATUS_IS_OK(status)) {
1206 DEBUG(10, ("open_file: "
1207 "smbd_check_access_rights "
1208 "on file %s returned %s\n",
1209 smb_fname_str_dbg(smb_fname),
1210 nt_errstr(status)));
1213 if (!NT_STATUS_IS_OK(status) &&
1214 !NT_STATUS_EQUAL(status,
1215 NT_STATUS_OBJECT_NAME_NOT_FOUND))
1217 return status;
1220 if (NT_STATUS_EQUAL(status,
1221 NT_STATUS_OBJECT_NAME_NOT_FOUND))
1223 DEBUG(10, ("open_file: "
1224 "file %s vanished since we "
1225 "checked for existence.\n",
1226 smb_fname_str_dbg(smb_fname)));
1227 file_existed = false;
1228 SET_STAT_INVALID(fsp->fsp_name->st);
1232 if (!file_existed) {
1233 if (!(local_flags & O_CREAT)) {
1234 /* File didn't exist and no O_CREAT. */
1235 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
1238 status = check_parent_access(conn,
1239 smb_fname,
1240 SEC_DIR_ADD_FILE);
1241 if (!NT_STATUS_IS_OK(status)) {
1242 DEBUG(10, ("open_file: "
1243 "check_parent_access on "
1244 "file %s returned %s\n",
1245 smb_fname_str_dbg(smb_fname),
1246 nt_errstr(status) ));
1247 return status;
1253 * Actually do the open - if O_TRUNC is needed handle it
1254 * below under the share mode lock.
1256 status = fd_open_atomic(conn, fsp, local_flags & ~O_TRUNC,
1257 unx_mode, p_file_created);
1258 if (!NT_STATUS_IS_OK(status)) {
1259 DEBUG(3,("Error opening file %s (%s) (local_flags=%d) "
1260 "(flags=%d)\n", smb_fname_str_dbg(smb_fname),
1261 nt_errstr(status),local_flags,flags));
1262 return status;
1265 if (local_flags & O_NONBLOCK) {
1267 * GPFS can return ETIMEDOUT for pread on
1268 * nonblocking file descriptors when files
1269 * migrated to tape need to be recalled. I
1270 * could imagine this happens elsehwere
1271 * too. With blocking file descriptors this
1272 * does not happen.
1274 ret = set_blocking(fsp->fh->fd, true);
1275 if (ret == -1) {
1276 status = map_nt_error_from_unix(errno);
1277 DBG_WARNING("Could not set fd to blocking: "
1278 "%s\n", strerror(errno));
1279 fd_close(fsp);
1280 return status;
1284 ret = SMB_VFS_FSTAT(fsp, &smb_fname->st);
1285 if (ret == -1) {
1286 /* If we have an fd, this stat should succeed. */
1287 DEBUG(0,("Error doing fstat on open file %s "
1288 "(%s)\n",
1289 smb_fname_str_dbg(smb_fname),
1290 strerror(errno) ));
1291 status = map_nt_error_from_unix(errno);
1292 fd_close(fsp);
1293 return status;
1296 if (*p_file_created) {
1297 /* We created this file. */
1299 bool need_re_stat = false;
1300 /* Do all inheritance work after we've
1301 done a successful fstat call and filled
1302 in the stat struct in fsp->fsp_name. */
1304 /* Inherit the ACL if required */
1305 if (lp_inherit_permissions(SNUM(conn))) {
1306 inherit_access_posix_acl(conn, parent_dir,
1307 smb_fname,
1308 unx_mode);
1309 need_re_stat = true;
1312 /* Change the owner if required. */
1313 if (lp_inherit_owner(SNUM(conn)) != INHERIT_OWNER_NO) {
1314 change_file_owner_to_parent(conn, parent_dir,
1315 fsp);
1316 need_re_stat = true;
1319 if (need_re_stat) {
1320 ret = SMB_VFS_FSTAT(fsp, &smb_fname->st);
1321 /* If we have an fd, this stat should succeed. */
1322 if (ret == -1) {
1323 DEBUG(0,("Error doing fstat on open file %s "
1324 "(%s)\n",
1325 smb_fname_str_dbg(smb_fname),
1326 strerror(errno) ));
1330 notify_fname(conn, NOTIFY_ACTION_ADDED,
1331 FILE_NOTIFY_CHANGE_FILE_NAME,
1332 smb_fname->base_name);
1334 } else {
1335 fsp->fh->fd = -1; /* What we used to call a stat open. */
1336 if (!file_existed) {
1337 /* File must exist for a stat open. */
1338 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
1341 status = smbd_check_access_rights(conn,
1342 smb_fname,
1343 false,
1344 access_mask);
1346 if (NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND) &&
1347 (fsp->posix_flags & FSP_POSIX_FLAGS_OPEN) &&
1348 S_ISLNK(smb_fname->st.st_ex_mode)) {
1349 /* This is a POSIX stat open for delete
1350 * or rename on a symlink that points
1351 * nowhere. Allow. */
1352 DEBUG(10,("open_file: allowing POSIX "
1353 "open on bad symlink %s\n",
1354 smb_fname_str_dbg(smb_fname)));
1355 status = NT_STATUS_OK;
1358 if (!NT_STATUS_IS_OK(status)) {
1359 DEBUG(10,("open_file: "
1360 "smbd_check_access_rights on file "
1361 "%s returned %s\n",
1362 smb_fname_str_dbg(smb_fname),
1363 nt_errstr(status) ));
1364 return status;
1369 * POSIX allows read-only opens of directories. We don't
1370 * want to do this (we use a different code path for this)
1371 * so catch a directory open and return an EISDIR. JRA.
1374 if(S_ISDIR(smb_fname->st.st_ex_mode)) {
1375 fd_close(fsp);
1376 errno = EISDIR;
1377 return NT_STATUS_FILE_IS_A_DIRECTORY;
1380 fsp->file_id = vfs_file_id_from_sbuf(conn, &smb_fname->st);
1381 fsp->vuid = req ? req->vuid : UID_FIELD_INVALID;
1382 fsp->file_pid = req ? req->smbpid : 0;
1383 fsp->can_lock = True;
1384 fsp->can_read = ((access_mask & FILE_READ_DATA) != 0);
1385 fsp->can_write =
1386 CAN_WRITE(conn) &&
1387 ((access_mask & (FILE_WRITE_DATA | FILE_APPEND_DATA)) != 0);
1388 fsp->print_file = NULL;
1389 fsp->modified = False;
1390 fsp->sent_oplock_break = NO_BREAK_SENT;
1391 fsp->is_directory = False;
1392 if (conn->aio_write_behind_list &&
1393 is_in_path(smb_fname->base_name, conn->aio_write_behind_list,
1394 conn->case_sensitive)) {
1395 fsp->aio_write_behind = True;
1398 fsp->wcp = NULL; /* Write cache pointer. */
1400 DEBUG(2,("%s opened file %s read=%s write=%s (numopen=%d)\n",
1401 conn->session_info->unix_info->unix_name,
1402 smb_fname_str_dbg(smb_fname),
1403 BOOLSTR(fsp->can_read), BOOLSTR(fsp->can_write),
1404 conn->num_files_open));
1406 errno = 0;
1407 return NT_STATUS_OK;
1410 /****************************************************************************
1411 Check if we can open a file with a share mode.
1412 Returns True if conflict, False if not.
1413 ****************************************************************************/
1415 static bool share_conflict(struct share_mode_entry *entry,
1416 uint32_t access_mask,
1417 uint32_t share_access)
1419 DEBUG(10,("share_conflict: entry->access_mask = 0x%x, "
1420 "entry->share_access = 0x%x, "
1421 "entry->private_options = 0x%x\n",
1422 (unsigned int)entry->access_mask,
1423 (unsigned int)entry->share_access,
1424 (unsigned int)entry->private_options));
1426 if (server_id_is_disconnected(&entry->pid)) {
1428 * note: cleanup should have been done by
1429 * delay_for_batch_oplocks()
1431 return false;
1434 DEBUG(10,("share_conflict: access_mask = 0x%x, share_access = 0x%x\n",
1435 (unsigned int)access_mask, (unsigned int)share_access));
1437 if ((entry->access_mask & (FILE_WRITE_DATA|
1438 FILE_APPEND_DATA|
1439 FILE_READ_DATA|
1440 FILE_EXECUTE|
1441 DELETE_ACCESS)) == 0) {
1442 DEBUG(10,("share_conflict: No conflict due to "
1443 "entry->access_mask = 0x%x\n",
1444 (unsigned int)entry->access_mask ));
1445 return False;
1448 if ((access_mask & (FILE_WRITE_DATA|
1449 FILE_APPEND_DATA|
1450 FILE_READ_DATA|
1451 FILE_EXECUTE|
1452 DELETE_ACCESS)) == 0) {
1453 DEBUG(10,("share_conflict: No conflict due to "
1454 "access_mask = 0x%x\n",
1455 (unsigned int)access_mask ));
1456 return False;
1459 #if 1 /* JRA TEST - Superdebug. */
1460 #define CHECK_MASK(num, am, right, sa, share) \
1461 DEBUG(10,("share_conflict: [%d] am (0x%x) & right (0x%x) = 0x%x\n", \
1462 (unsigned int)(num), (unsigned int)(am), \
1463 (unsigned int)(right), (unsigned int)(am)&(right) )); \
1464 DEBUG(10,("share_conflict: [%d] sa (0x%x) & share (0x%x) = 0x%x\n", \
1465 (unsigned int)(num), (unsigned int)(sa), \
1466 (unsigned int)(share), (unsigned int)(sa)&(share) )); \
1467 if (((am) & (right)) && !((sa) & (share))) { \
1468 DEBUG(10,("share_conflict: check %d conflict am = 0x%x, right = 0x%x, \
1469 sa = 0x%x, share = 0x%x\n", (num), (unsigned int)(am), (unsigned int)(right), (unsigned int)(sa), \
1470 (unsigned int)(share) )); \
1471 return True; \
1473 #else
1474 #define CHECK_MASK(num, am, right, sa, share) \
1475 if (((am) & (right)) && !((sa) & (share))) { \
1476 DEBUG(10,("share_conflict: check %d conflict am = 0x%x, right = 0x%x, \
1477 sa = 0x%x, share = 0x%x\n", (num), (unsigned int)(am), (unsigned int)(right), (unsigned int)(sa), \
1478 (unsigned int)(share) )); \
1479 return True; \
1481 #endif
1483 CHECK_MASK(1, entry->access_mask, FILE_WRITE_DATA | FILE_APPEND_DATA,
1484 share_access, FILE_SHARE_WRITE);
1485 CHECK_MASK(2, access_mask, FILE_WRITE_DATA | FILE_APPEND_DATA,
1486 entry->share_access, FILE_SHARE_WRITE);
1488 CHECK_MASK(3, entry->access_mask, FILE_READ_DATA | FILE_EXECUTE,
1489 share_access, FILE_SHARE_READ);
1490 CHECK_MASK(4, access_mask, FILE_READ_DATA | FILE_EXECUTE,
1491 entry->share_access, FILE_SHARE_READ);
1493 CHECK_MASK(5, entry->access_mask, DELETE_ACCESS,
1494 share_access, FILE_SHARE_DELETE);
1495 CHECK_MASK(6, access_mask, DELETE_ACCESS,
1496 entry->share_access, FILE_SHARE_DELETE);
1498 DEBUG(10,("share_conflict: No conflict.\n"));
1499 return False;
1502 #if defined(DEVELOPER)
1503 static void validate_my_share_entries(struct smbd_server_connection *sconn,
1504 int num,
1505 struct share_mode_entry *share_entry)
1507 struct server_id self = messaging_server_id(sconn->msg_ctx);
1508 files_struct *fsp;
1510 if (!serverid_equal(&self, &share_entry->pid)) {
1511 return;
1514 if (share_entry->op_mid == 0) {
1515 /* INTERNAL_OPEN_ONLY */
1516 return;
1519 if (!is_valid_share_mode_entry(share_entry)) {
1520 return;
1523 fsp = file_find_dif(sconn, share_entry->id,
1524 share_entry->share_file_id);
1525 if (!fsp) {
1526 DEBUG(0,("validate_my_share_entries: PANIC : %s\n",
1527 share_mode_str(talloc_tos(), num, share_entry) ));
1528 smb_panic("validate_my_share_entries: Cannot match a "
1529 "share entry with an open file\n");
1532 if (((uint16_t)fsp->oplock_type) != share_entry->op_type) {
1533 goto panic;
1536 return;
1538 panic:
1540 char *str;
1541 DEBUG(0,("validate_my_share_entries: PANIC : %s\n",
1542 share_mode_str(talloc_tos(), num, share_entry) ));
1543 str = talloc_asprintf(talloc_tos(),
1544 "validate_my_share_entries: "
1545 "file %s, oplock_type = 0x%x, op_type = 0x%x\n",
1546 fsp->fsp_name->base_name,
1547 (unsigned int)fsp->oplock_type,
1548 (unsigned int)share_entry->op_type );
1549 smb_panic(str);
1552 #endif
1554 bool is_stat_open(uint32_t access_mask)
1556 const uint32_t stat_open_bits =
1557 (SYNCHRONIZE_ACCESS|
1558 FILE_READ_ATTRIBUTES|
1559 FILE_WRITE_ATTRIBUTES);
1561 return (((access_mask & stat_open_bits) != 0) &&
1562 ((access_mask & ~stat_open_bits) == 0));
1565 static bool has_delete_on_close(struct share_mode_lock *lck,
1566 uint32_t name_hash)
1568 struct share_mode_data *d = lck->data;
1569 uint32_t i;
1571 if (d->num_share_modes == 0) {
1572 return false;
1574 if (!is_delete_on_close_set(lck, name_hash)) {
1575 return false;
1577 for (i=0; i<d->num_share_modes; i++) {
1578 if (!share_mode_stale_pid(d, i)) {
1579 return true;
1582 return false;
1585 /****************************************************************************
1586 Deal with share modes
1587 Invariant: Share mode must be locked on entry and exit.
1588 Returns -1 on error, or number of share modes on success (may be zero).
1589 ****************************************************************************/
1591 static NTSTATUS open_mode_check(connection_struct *conn,
1592 struct share_mode_lock *lck,
1593 uint32_t access_mask,
1594 uint32_t share_access)
1596 uint32_t i;
1598 if(lck->data->num_share_modes == 0) {
1599 return NT_STATUS_OK;
1602 if (is_stat_open(access_mask)) {
1603 /* Stat open that doesn't trigger oplock breaks or share mode
1604 * checks... ! JRA. */
1605 return NT_STATUS_OK;
1609 * Check if the share modes will give us access.
1612 #if defined(DEVELOPER)
1613 for(i = 0; i < lck->data->num_share_modes; i++) {
1614 validate_my_share_entries(conn->sconn, i,
1615 &lck->data->share_modes[i]);
1617 #endif
1619 /* Now we check the share modes, after any oplock breaks. */
1620 for(i = 0; i < lck->data->num_share_modes; i++) {
1622 if (!is_valid_share_mode_entry(&lck->data->share_modes[i])) {
1623 continue;
1626 /* someone else has a share lock on it, check to see if we can
1627 * too */
1628 if (share_conflict(&lck->data->share_modes[i],
1629 access_mask, share_access)) {
1631 if (share_mode_stale_pid(lck->data, i)) {
1632 continue;
1635 return NT_STATUS_SHARING_VIOLATION;
1639 return NT_STATUS_OK;
1643 * Send a break message to the oplock holder and delay the open for
1644 * our client.
1647 NTSTATUS send_break_message(struct messaging_context *msg_ctx,
1648 const struct share_mode_entry *exclusive,
1649 uint16_t break_to)
1651 NTSTATUS status;
1652 char msg[MSG_SMB_SHARE_MODE_ENTRY_SIZE];
1653 struct server_id_buf tmp;
1655 DEBUG(10, ("Sending break request to PID %s\n",
1656 server_id_str_buf(exclusive->pid, &tmp)));
1658 /* Create the message. */
1659 share_mode_entry_to_message(msg, exclusive);
1661 /* Overload entry->op_type */
1663 * This is a cut from uint32_t to uint16_t, but so far only the lower 3
1664 * bits (LEASE_WRITE/HANDLE/READ are used anyway.
1666 SSVAL(msg,OP_BREAK_MSG_OP_TYPE_OFFSET, break_to);
1668 status = messaging_send_buf(msg_ctx, exclusive->pid,
1669 MSG_SMB_BREAK_REQUEST,
1670 (uint8_t *)msg, sizeof(msg));
1671 if (!NT_STATUS_IS_OK(status)) {
1672 DEBUG(3, ("Could not send oplock break message: %s\n",
1673 nt_errstr(status)));
1676 return status;
1680 * Do internal consistency checks on the share mode for a file.
1683 static bool validate_oplock_types(struct share_mode_lock *lck)
1685 struct share_mode_data *d = lck->data;
1686 bool batch = false;
1687 bool ex_or_batch = false;
1688 bool level2 = false;
1689 bool no_oplock = false;
1690 uint32_t num_non_stat_opens = 0;
1691 uint32_t i;
1693 for (i=0; i<d->num_share_modes; i++) {
1694 struct share_mode_entry *e = &d->share_modes[i];
1696 if (!is_valid_share_mode_entry(e)) {
1697 continue;
1700 if (e->op_mid == 0) {
1701 /* INTERNAL_OPEN_ONLY */
1702 continue;
1705 if (e->op_type == NO_OPLOCK && is_stat_open(e->access_mask)) {
1706 /* We ignore stat opens in the table - they
1707 always have NO_OPLOCK and never get or
1708 cause breaks. JRA. */
1709 continue;
1712 num_non_stat_opens += 1;
1714 if (BATCH_OPLOCK_TYPE(e->op_type)) {
1715 /* batch - can only be one. */
1716 if (share_mode_stale_pid(d, i)) {
1717 DEBUG(10, ("Found stale batch oplock\n"));
1718 continue;
1720 if (ex_or_batch || batch || level2 || no_oplock) {
1721 DEBUG(0, ("Bad batch oplock entry %u.",
1722 (unsigned)i));
1723 return false;
1725 batch = true;
1728 if (EXCLUSIVE_OPLOCK_TYPE(e->op_type)) {
1729 if (share_mode_stale_pid(d, i)) {
1730 DEBUG(10, ("Found stale duplicate oplock\n"));
1731 continue;
1733 /* Exclusive or batch - can only be one. */
1734 if (ex_or_batch || level2 || no_oplock) {
1735 DEBUG(0, ("Bad exclusive or batch oplock "
1736 "entry %u.", (unsigned)i));
1737 return false;
1739 ex_or_batch = true;
1742 if (LEVEL_II_OPLOCK_TYPE(e->op_type)) {
1743 if (batch || ex_or_batch) {
1744 if (share_mode_stale_pid(d, i)) {
1745 DEBUG(10, ("Found stale LevelII "
1746 "oplock\n"));
1747 continue;
1749 DEBUG(0, ("Bad levelII oplock entry %u.",
1750 (unsigned)i));
1751 return false;
1753 level2 = true;
1756 if (e->op_type == NO_OPLOCK) {
1757 if (batch || ex_or_batch) {
1758 if (share_mode_stale_pid(d, i)) {
1759 DEBUG(10, ("Found stale NO_OPLOCK "
1760 "entry\n"));
1761 continue;
1763 DEBUG(0, ("Bad no oplock entry %u.",
1764 (unsigned)i));
1765 return false;
1767 no_oplock = true;
1771 remove_stale_share_mode_entries(d);
1773 if ((batch || ex_or_batch) && (num_non_stat_opens != 1)) {
1774 DEBUG(1, ("got batch (%d) or ex (%d) non-exclusively (%d)\n",
1775 (int)batch, (int)ex_or_batch,
1776 (int)d->num_share_modes));
1777 return false;
1780 return true;
1783 static bool delay_for_oplock(files_struct *fsp,
1784 int oplock_request,
1785 const struct smb2_lease *lease,
1786 struct share_mode_lock *lck,
1787 bool have_sharing_violation,
1788 uint32_t create_disposition,
1789 bool first_open_attempt)
1791 struct share_mode_data *d = lck->data;
1792 uint32_t i;
1793 bool delay = false;
1794 bool will_overwrite;
1796 if ((oplock_request & INTERNAL_OPEN_ONLY) ||
1797 is_stat_open(fsp->access_mask)) {
1798 return false;
1801 switch (create_disposition) {
1802 case FILE_SUPERSEDE:
1803 case FILE_OVERWRITE:
1804 case FILE_OVERWRITE_IF:
1805 will_overwrite = true;
1806 break;
1807 default:
1808 will_overwrite = false;
1809 break;
1812 for (i=0; i<d->num_share_modes; i++) {
1813 struct share_mode_entry *e = &d->share_modes[i];
1814 struct share_mode_lease *l = NULL;
1815 uint32_t e_lease_type = get_lease_type(d, e);
1816 uint32_t break_to;
1817 uint32_t delay_mask = 0;
1819 if (e->op_type == LEASE_OPLOCK) {
1820 l = &d->leases[e->lease_idx];
1823 if (have_sharing_violation) {
1824 delay_mask = SMB2_LEASE_HANDLE;
1825 } else {
1826 delay_mask = SMB2_LEASE_WRITE;
1829 break_to = e_lease_type & ~delay_mask;
1831 if (will_overwrite) {
1833 * we'll decide about SMB2_LEASE_READ later.
1835 * Maybe the break will be deferred
1837 break_to &= ~SMB2_LEASE_HANDLE;
1840 DEBUG(10, ("entry %u: e_lease_type %u, will_overwrite: %u\n",
1841 (unsigned)i, (unsigned)e_lease_type,
1842 (unsigned)will_overwrite));
1844 if (lease != NULL && l != NULL) {
1845 bool ign;
1847 ign = smb2_lease_equal(fsp_client_guid(fsp),
1848 &lease->lease_key,
1849 &l->client_guid,
1850 &l->lease_key);
1851 if (ign) {
1852 continue;
1856 if ((e_lease_type & ~break_to) == 0) {
1857 if (l != NULL && l->breaking) {
1858 delay = true;
1860 continue;
1863 if (share_mode_stale_pid(d, i)) {
1864 continue;
1867 if (will_overwrite) {
1869 * If we break anyway break to NONE directly.
1870 * Otherwise vfs_set_filelen() will trigger the
1871 * break.
1873 break_to &= ~(SMB2_LEASE_READ|SMB2_LEASE_WRITE);
1876 if (e->op_type != LEASE_OPLOCK) {
1878 * Oplocks only support breaking to R or NONE.
1880 break_to &= ~(SMB2_LEASE_HANDLE|SMB2_LEASE_WRITE);
1883 DEBUG(10, ("breaking from %d to %d\n",
1884 (int)e_lease_type, (int)break_to));
1885 send_break_message(fsp->conn->sconn->msg_ctx, e,
1886 break_to);
1887 if (e_lease_type & delay_mask) {
1888 delay = true;
1890 if (l != NULL && l->breaking && !first_open_attempt) {
1891 delay = true;
1893 continue;
1896 return delay;
1899 static bool file_has_brlocks(files_struct *fsp)
1901 struct byte_range_lock *br_lck;
1903 br_lck = brl_get_locks_readonly(fsp);
1904 if (!br_lck)
1905 return false;
1907 return (brl_num_locks(br_lck) > 0);
1910 int find_share_mode_lease(struct share_mode_data *d,
1911 const struct GUID *client_guid,
1912 const struct smb2_lease_key *key)
1914 uint32_t i;
1916 for (i=0; i<d->num_leases; i++) {
1917 struct share_mode_lease *l = &d->leases[i];
1919 if (smb2_lease_equal(client_guid,
1920 key,
1921 &l->client_guid,
1922 &l->lease_key)) {
1923 return i;
1927 return -1;
1930 struct fsp_lease *find_fsp_lease(struct files_struct *new_fsp,
1931 const struct smb2_lease_key *key,
1932 const struct share_mode_lease *l)
1934 struct files_struct *fsp;
1937 * TODO: Measure how expensive this loop is with thousands of open
1938 * handles...
1941 for (fsp = file_find_di_first(new_fsp->conn->sconn, new_fsp->file_id);
1942 fsp != NULL;
1943 fsp = file_find_di_next(fsp)) {
1945 if (fsp == new_fsp) {
1946 continue;
1948 if (fsp->oplock_type != LEASE_OPLOCK) {
1949 continue;
1951 if (smb2_lease_key_equal(&fsp->lease->lease.lease_key, key)) {
1952 fsp->lease->ref_count += 1;
1953 return fsp->lease;
1957 /* Not found - must be leased in another smbd. */
1958 new_fsp->lease = talloc_zero(new_fsp->conn->sconn, struct fsp_lease);
1959 if (new_fsp->lease == NULL) {
1960 return NULL;
1962 new_fsp->lease->ref_count = 1;
1963 new_fsp->lease->sconn = new_fsp->conn->sconn;
1964 new_fsp->lease->lease.lease_key = *key;
1965 new_fsp->lease->lease.lease_state = l->current_state;
1967 * We internally treat all leases as V2 and update
1968 * the epoch, but when sending breaks it matters if
1969 * the requesting lease was v1 or v2.
1971 new_fsp->lease->lease.lease_version = l->lease_version;
1972 new_fsp->lease->lease.lease_epoch = l->epoch;
1973 return new_fsp->lease;
1976 static NTSTATUS grant_fsp_lease(struct files_struct *fsp,
1977 struct share_mode_lock *lck,
1978 const struct smb2_lease *lease,
1979 uint32_t *p_lease_idx,
1980 uint32_t granted)
1982 struct share_mode_data *d = lck->data;
1983 const struct GUID *client_guid = fsp_client_guid(fsp);
1984 struct share_mode_lease *tmp;
1985 NTSTATUS status;
1986 int idx;
1988 idx = find_share_mode_lease(d, client_guid, &lease->lease_key);
1990 if (idx != -1) {
1991 struct share_mode_lease *l = &d->leases[idx];
1992 bool do_upgrade;
1993 uint32_t existing, requested;
1995 fsp->lease = find_fsp_lease(fsp, &lease->lease_key, l);
1996 if (fsp->lease == NULL) {
1997 DEBUG(1, ("Did not find existing lease for file %s\n",
1998 fsp_str_dbg(fsp)));
1999 return NT_STATUS_NO_MEMORY;
2002 *p_lease_idx = idx;
2005 * Upgrade only if the requested lease is a strict upgrade.
2007 existing = l->current_state;
2008 requested = lease->lease_state;
2011 * Tricky: This test makes sure that "requested" is a
2012 * strict bitwise superset of "existing".
2014 do_upgrade = ((existing & requested) == existing);
2017 * Upgrade only if there's a change.
2019 do_upgrade &= (granted != existing);
2022 * Upgrade only if other leases don't prevent what was asked
2023 * for.
2025 do_upgrade &= (granted == requested);
2028 * only upgrade if we are not in breaking state
2030 do_upgrade &= !l->breaking;
2032 DEBUG(10, ("existing=%"PRIu32", requested=%"PRIu32", "
2033 "granted=%"PRIu32", do_upgrade=%d\n",
2034 existing, requested, granted, (int)do_upgrade));
2036 if (do_upgrade) {
2037 l->current_state = granted;
2038 l->epoch += 1;
2041 /* Ensure we're in sync with current lease state. */
2042 fsp_lease_update(lck, fsp_client_guid(fsp), fsp->lease);
2043 return NT_STATUS_OK;
2047 * Create new lease
2050 tmp = talloc_realloc(d, d->leases, struct share_mode_lease,
2051 d->num_leases+1);
2052 if (tmp == NULL) {
2054 * See [MS-SMB2]
2056 return NT_STATUS_INSUFFICIENT_RESOURCES;
2058 d->leases = tmp;
2060 fsp->lease = talloc_zero(fsp->conn->sconn, struct fsp_lease);
2061 if (fsp->lease == NULL) {
2062 return NT_STATUS_INSUFFICIENT_RESOURCES;
2064 fsp->lease->ref_count = 1;
2065 fsp->lease->sconn = fsp->conn->sconn;
2066 fsp->lease->lease.lease_version = lease->lease_version;
2067 fsp->lease->lease.lease_key = lease->lease_key;
2068 fsp->lease->lease.lease_state = granted;
2069 fsp->lease->lease.lease_epoch = lease->lease_epoch + 1;
2071 *p_lease_idx = d->num_leases;
2073 d->leases[d->num_leases] = (struct share_mode_lease) {
2074 .client_guid = *client_guid,
2075 .lease_key = fsp->lease->lease.lease_key,
2076 .current_state = fsp->lease->lease.lease_state,
2077 .lease_version = fsp->lease->lease.lease_version,
2078 .epoch = fsp->lease->lease.lease_epoch,
2081 status = leases_db_add(client_guid,
2082 &lease->lease_key,
2083 &fsp->file_id,
2084 fsp->conn->connectpath,
2085 fsp->fsp_name->base_name,
2086 fsp->fsp_name->stream_name);
2087 if (!NT_STATUS_IS_OK(status)) {
2088 DEBUG(10, ("%s: leases_db_add failed: %s\n", __func__,
2089 nt_errstr(status)));
2090 TALLOC_FREE(fsp->lease);
2091 return NT_STATUS_INSUFFICIENT_RESOURCES;
2094 d->num_leases += 1;
2095 d->modified = true;
2097 return NT_STATUS_OK;
2100 static bool is_same_lease(const files_struct *fsp,
2101 const struct share_mode_data *d,
2102 const struct share_mode_entry *e,
2103 const struct smb2_lease *lease)
2105 if (e->op_type != LEASE_OPLOCK) {
2106 return false;
2108 if (lease == NULL) {
2109 return false;
2112 return smb2_lease_equal(fsp_client_guid(fsp),
2113 &lease->lease_key,
2114 &d->leases[e->lease_idx].client_guid,
2115 &d->leases[e->lease_idx].lease_key);
2118 static NTSTATUS grant_fsp_oplock_type(struct smb_request *req,
2119 struct files_struct *fsp,
2120 struct share_mode_lock *lck,
2121 int oplock_request,
2122 struct smb2_lease *lease)
2124 struct share_mode_data *d = lck->data;
2125 bool got_handle_lease = false;
2126 bool got_oplock = false;
2127 uint32_t i;
2128 uint32_t granted;
2129 uint32_t lease_idx = UINT32_MAX;
2130 bool ok;
2131 NTSTATUS status;
2133 if (oplock_request & INTERNAL_OPEN_ONLY) {
2134 /* No oplocks on internal open. */
2135 oplock_request = NO_OPLOCK;
2136 DEBUG(10,("grant_fsp_oplock_type: oplock type 0x%x on file %s\n",
2137 fsp->oplock_type, fsp_str_dbg(fsp)));
2140 if (oplock_request == LEASE_OPLOCK) {
2141 if (lease == NULL) {
2143 * The SMB2 layer should have checked this
2145 return NT_STATUS_INTERNAL_ERROR;
2148 granted = lease->lease_state;
2150 if (lp_kernel_oplocks(SNUM(fsp->conn))) {
2151 DEBUG(10, ("No lease granted because kernel oplocks are enabled\n"));
2152 granted = SMB2_LEASE_NONE;
2154 if ((granted & (SMB2_LEASE_READ|SMB2_LEASE_WRITE)) == 0) {
2155 DEBUG(10, ("No read or write lease requested\n"));
2156 granted = SMB2_LEASE_NONE;
2158 if (granted == SMB2_LEASE_WRITE) {
2159 DEBUG(10, ("pure write lease requested\n"));
2160 granted = SMB2_LEASE_NONE;
2162 if (granted == (SMB2_LEASE_WRITE|SMB2_LEASE_HANDLE)) {
2163 DEBUG(10, ("write and handle lease requested\n"));
2164 granted = SMB2_LEASE_NONE;
2166 } else {
2167 granted = map_oplock_to_lease_type(
2168 oplock_request & ~SAMBA_PRIVATE_OPLOCK_MASK);
2171 if (lp_locking(fsp->conn->params) && file_has_brlocks(fsp)) {
2172 DEBUG(10,("grant_fsp_oplock_type: file %s has byte range locks\n",
2173 fsp_str_dbg(fsp)));
2174 granted &= ~SMB2_LEASE_READ;
2177 for (i=0; i<d->num_share_modes; i++) {
2178 struct share_mode_entry *e = &d->share_modes[i];
2179 uint32_t e_lease_type;
2181 e_lease_type = get_lease_type(d, e);
2183 if ((granted & SMB2_LEASE_WRITE) &&
2184 !is_same_lease(fsp, d, e, lease) &&
2185 !share_mode_stale_pid(d, i)) {
2187 * Can grant only one writer
2189 granted &= ~SMB2_LEASE_WRITE;
2192 if ((e_lease_type & SMB2_LEASE_HANDLE) && !got_handle_lease &&
2193 !share_mode_stale_pid(d, i)) {
2194 got_handle_lease = true;
2197 if ((e->op_type != LEASE_OPLOCK) && !got_oplock &&
2198 !share_mode_stale_pid(d, i)) {
2199 got_oplock = true;
2203 if ((granted & SMB2_LEASE_READ) && !(granted & SMB2_LEASE_WRITE)) {
2204 bool allow_level2 =
2205 (global_client_caps & CAP_LEVEL_II_OPLOCKS) &&
2206 lp_level2_oplocks(SNUM(fsp->conn));
2208 if (!allow_level2) {
2209 granted = SMB2_LEASE_NONE;
2213 if (oplock_request == LEASE_OPLOCK) {
2214 if (got_oplock) {
2215 granted &= ~SMB2_LEASE_HANDLE;
2218 fsp->oplock_type = LEASE_OPLOCK;
2220 status = grant_fsp_lease(fsp, lck, lease, &lease_idx,
2221 granted);
2222 if (!NT_STATUS_IS_OK(status)) {
2223 return status;
2226 *lease = fsp->lease->lease;
2227 DEBUG(10, ("lease_state=%d\n", lease->lease_state));
2228 } else {
2229 if (got_handle_lease) {
2230 granted = SMB2_LEASE_NONE;
2233 switch (granted) {
2234 case SMB2_LEASE_READ|SMB2_LEASE_WRITE|SMB2_LEASE_HANDLE:
2235 fsp->oplock_type = BATCH_OPLOCK|EXCLUSIVE_OPLOCK;
2236 break;
2237 case SMB2_LEASE_READ|SMB2_LEASE_WRITE:
2238 fsp->oplock_type = EXCLUSIVE_OPLOCK;
2239 break;
2240 case SMB2_LEASE_READ|SMB2_LEASE_HANDLE:
2241 case SMB2_LEASE_READ:
2242 fsp->oplock_type = LEVEL_II_OPLOCK;
2243 break;
2244 default:
2245 fsp->oplock_type = NO_OPLOCK;
2246 break;
2249 status = set_file_oplock(fsp);
2250 if (!NT_STATUS_IS_OK(status)) {
2252 * Could not get the kernel oplock
2254 fsp->oplock_type = NO_OPLOCK;
2258 ok = set_share_mode(lck, fsp, get_current_uid(fsp->conn),
2259 req ? req->mid : 0,
2260 fsp->oplock_type,
2261 lease_idx);
2262 if (!ok) {
2263 return NT_STATUS_NO_MEMORY;
2266 ok = update_num_read_oplocks(fsp, lck);
2267 if (!ok) {
2268 del_share_mode(lck, fsp);
2269 return NT_STATUS_INTERNAL_ERROR;
2272 DEBUG(10,("grant_fsp_oplock_type: oplock type 0x%x on file %s\n",
2273 fsp->oplock_type, fsp_str_dbg(fsp)));
2275 return NT_STATUS_OK;
2278 static bool request_timed_out(struct timeval request_time,
2279 struct timeval timeout)
2281 struct timeval now, end_time;
2282 GetTimeOfDay(&now);
2283 end_time = timeval_sum(&request_time, &timeout);
2284 return (timeval_compare(&end_time, &now) < 0);
2287 static struct deferred_open_record *deferred_open_record_create(
2288 bool delayed_for_oplocks,
2289 bool async_open,
2290 struct file_id id)
2292 struct deferred_open_record *record = NULL;
2294 record = talloc(NULL, struct deferred_open_record);
2295 if (record == NULL) {
2296 return NULL;
2299 *record = (struct deferred_open_record) {
2300 .delayed_for_oplocks = delayed_for_oplocks,
2301 .async_open = async_open,
2302 .id = id,
2305 return record;
2308 struct defer_open_state {
2309 struct smbXsrv_connection *xconn;
2310 uint64_t mid;
2313 static void defer_open_done(struct tevent_req *req);
2316 * Defer an open and watch a locking.tdb record
2318 * This defers an open that gets rescheduled once the locking.tdb record watch
2319 * is triggered by a change to the record.
2321 * It is used to defer opens that triggered an oplock break and for the SMB1
2322 * sharing violation delay.
2324 static void defer_open(struct share_mode_lock *lck,
2325 struct timeval request_time,
2326 struct timeval timeout,
2327 struct smb_request *req,
2328 bool delayed_for_oplocks,
2329 struct file_id id)
2331 struct deferred_open_record *open_rec = NULL;
2332 struct timeval abs_timeout;
2333 struct defer_open_state *watch_state;
2334 struct tevent_req *watch_req;
2335 bool ok;
2337 abs_timeout = timeval_sum(&request_time, &timeout);
2339 DBG_DEBUG("request time [%s] timeout [%s] mid [%" PRIu64 "] "
2340 "delayed_for_oplocks [%s] file_id [%s]\n",
2341 timeval_string(talloc_tos(), &request_time, false),
2342 timeval_string(talloc_tos(), &abs_timeout, false),
2343 req->mid,
2344 delayed_for_oplocks ? "yes" : "no",
2345 file_id_string_tos(&id));
2347 open_rec = deferred_open_record_create(delayed_for_oplocks,
2348 false,
2349 id);
2350 if (open_rec == NULL) {
2351 TALLOC_FREE(lck);
2352 exit_server("talloc failed");
2355 watch_state = talloc(open_rec, struct defer_open_state);
2356 if (watch_state == NULL) {
2357 exit_server("talloc failed");
2359 watch_state->xconn = req->xconn;
2360 watch_state->mid = req->mid;
2362 DBG_DEBUG("defering mid %" PRIu64 "\n", req->mid);
2364 watch_req = dbwrap_watched_watch_send(watch_state,
2365 req->sconn->ev_ctx,
2366 lck->data->record,
2367 (struct server_id){0});
2368 if (watch_req == NULL) {
2369 exit_server("Could not watch share mode record");
2371 tevent_req_set_callback(watch_req, defer_open_done, watch_state);
2373 ok = tevent_req_set_endtime(watch_req, req->sconn->ev_ctx, abs_timeout);
2374 if (!ok) {
2375 exit_server("tevent_req_set_endtime failed");
2378 ok = push_deferred_open_message_smb(req, request_time, timeout,
2379 open_rec->id, open_rec);
2380 if (!ok) {
2381 TALLOC_FREE(lck);
2382 exit_server("push_deferred_open_message_smb failed");
2386 static void defer_open_done(struct tevent_req *req)
2388 struct defer_open_state *state = tevent_req_callback_data(
2389 req, struct defer_open_state);
2390 NTSTATUS status;
2391 bool ret;
2393 status = dbwrap_watched_watch_recv(req, talloc_tos(), NULL, NULL,
2394 NULL);
2395 TALLOC_FREE(req);
2396 if (!NT_STATUS_IS_OK(status)) {
2397 DEBUG(5, ("dbwrap_watched_watch_recv returned %s\n",
2398 nt_errstr(status)));
2400 * Even if it failed, retry anyway. TODO: We need a way to
2401 * tell a re-scheduled open about that error.
2405 DEBUG(10, ("scheduling mid %llu\n", (unsigned long long)state->mid));
2407 ret = schedule_deferred_open_message_smb(state->xconn, state->mid);
2408 SMB_ASSERT(ret);
2409 TALLOC_FREE(state);
2413 * Actually attempt the kernel oplock polling open.
2416 static void kernel_oplock_poll_open_timer(struct tevent_context *ev,
2417 struct tevent_timer *te,
2418 struct timeval current_time,
2419 void *private_data)
2421 bool ok;
2422 struct smb_request *req = (struct smb_request *)private_data;
2424 ok = schedule_deferred_open_message_smb(req->xconn, req->mid);
2425 if (!ok) {
2426 exit_server("schedule_deferred_open_message_smb failed");
2428 DBG_DEBUG("kernel_oplock_poll_open_timer fired. Retying open !\n");
2432 * Reschedule an open for 1 second from now, if not timed out.
2434 static void setup_kernel_oplock_poll_open(struct timeval request_time,
2435 struct smb_request *req,
2436 struct file_id id)
2439 bool ok;
2440 struct deferred_open_record *open_rec = NULL;
2441 /* Maximum wait time. */
2442 struct timeval timeout = timeval_set(OPLOCK_BREAK_TIMEOUT*2, 0);
2444 if (request_timed_out(request_time, timeout)) {
2445 return;
2448 open_rec = deferred_open_record_create(false, false, id);
2449 if (open_rec == NULL) {
2450 exit_server("talloc failed");
2453 ok = push_deferred_open_message_smb(req,
2454 request_time,
2455 timeout,
2457 open_rec);
2458 if (!ok) {
2459 exit_server("push_deferred_open_message_smb failed");
2463 * As this timer event is owned by req, it will
2464 * disappear if req it talloc_freed.
2466 open_rec->te = tevent_add_timer(req->sconn->ev_ctx,
2467 req,
2468 timeval_current_ofs(1, 0),
2469 kernel_oplock_poll_open_timer,
2470 req);
2471 if (open_rec->te == NULL) {
2472 exit_server("tevent_add_timer failed");
2475 DBG_DEBUG("poll request time [%s] mid [%" PRIu64 "] file_id [%s]\n",
2476 timeval_string(talloc_tos(), &request_time, false),
2477 req->mid,
2478 file_id_string_tos(&id));
2481 /****************************************************************************
2482 On overwrite open ensure that the attributes match.
2483 ****************************************************************************/
2485 static bool open_match_attributes(connection_struct *conn,
2486 uint32_t old_dos_attr,
2487 uint32_t new_dos_attr,
2488 mode_t existing_unx_mode,
2489 mode_t new_unx_mode,
2490 mode_t *returned_unx_mode)
2492 uint32_t noarch_old_dos_attr, noarch_new_dos_attr;
2494 noarch_old_dos_attr = (old_dos_attr & ~FILE_ATTRIBUTE_ARCHIVE);
2495 noarch_new_dos_attr = (new_dos_attr & ~FILE_ATTRIBUTE_ARCHIVE);
2497 if((noarch_old_dos_attr == 0 && noarch_new_dos_attr != 0) ||
2498 (noarch_old_dos_attr != 0 && ((noarch_old_dos_attr & noarch_new_dos_attr) == noarch_old_dos_attr))) {
2499 *returned_unx_mode = new_unx_mode;
2500 } else {
2501 *returned_unx_mode = (mode_t)0;
2504 DEBUG(10,("open_match_attributes: old_dos_attr = 0x%x, "
2505 "existing_unx_mode = 0%o, new_dos_attr = 0x%x "
2506 "returned_unx_mode = 0%o\n",
2507 (unsigned int)old_dos_attr,
2508 (unsigned int)existing_unx_mode,
2509 (unsigned int)new_dos_attr,
2510 (unsigned int)*returned_unx_mode ));
2512 /* If we're mapping SYSTEM and HIDDEN ensure they match. */
2513 if (lp_map_system(SNUM(conn)) || lp_store_dos_attributes(SNUM(conn))) {
2514 if ((old_dos_attr & FILE_ATTRIBUTE_SYSTEM) &&
2515 !(new_dos_attr & FILE_ATTRIBUTE_SYSTEM)) {
2516 return False;
2519 if (lp_map_hidden(SNUM(conn)) || lp_store_dos_attributes(SNUM(conn))) {
2520 if ((old_dos_attr & FILE_ATTRIBUTE_HIDDEN) &&
2521 !(new_dos_attr & FILE_ATTRIBUTE_HIDDEN)) {
2522 return False;
2525 return True;
2528 /****************************************************************************
2529 Special FCB or DOS processing in the case of a sharing violation.
2530 Try and find a duplicated file handle.
2531 ****************************************************************************/
2533 static NTSTATUS fcb_or_dos_open(struct smb_request *req,
2534 connection_struct *conn,
2535 files_struct *fsp_to_dup_into,
2536 const struct smb_filename *smb_fname,
2537 struct file_id id,
2538 uint16_t file_pid,
2539 uint64_t vuid,
2540 uint32_t access_mask,
2541 uint32_t share_access,
2542 uint32_t create_options)
2544 files_struct *fsp;
2546 DEBUG(5,("fcb_or_dos_open: attempting old open semantics for "
2547 "file %s.\n", smb_fname_str_dbg(smb_fname)));
2549 for(fsp = file_find_di_first(conn->sconn, id); fsp;
2550 fsp = file_find_di_next(fsp)) {
2552 DEBUG(10,("fcb_or_dos_open: checking file %s, fd = %d, "
2553 "vuid = %llu, file_pid = %u, private_options = 0x%x "
2554 "access_mask = 0x%x\n", fsp_str_dbg(fsp),
2555 fsp->fh->fd, (unsigned long long)fsp->vuid,
2556 (unsigned int)fsp->file_pid,
2557 (unsigned int)fsp->fh->private_options,
2558 (unsigned int)fsp->access_mask ));
2560 if (fsp != fsp_to_dup_into &&
2561 fsp->fh->fd != -1 &&
2562 fsp->vuid == vuid &&
2563 fsp->file_pid == file_pid &&
2564 (fsp->fh->private_options & (NTCREATEX_OPTIONS_PRIVATE_DENY_DOS |
2565 NTCREATEX_OPTIONS_PRIVATE_DENY_FCB)) &&
2566 (fsp->access_mask & FILE_WRITE_DATA) &&
2567 strequal(fsp->fsp_name->base_name, smb_fname->base_name) &&
2568 strequal(fsp->fsp_name->stream_name,
2569 smb_fname->stream_name)) {
2570 DEBUG(10,("fcb_or_dos_open: file match\n"));
2571 break;
2575 if (!fsp) {
2576 return NT_STATUS_NOT_FOUND;
2579 /* quite an insane set of semantics ... */
2580 if (is_executable(smb_fname->base_name) &&
2581 (fsp->fh->private_options & NTCREATEX_OPTIONS_PRIVATE_DENY_DOS)) {
2582 DEBUG(10,("fcb_or_dos_open: file fail due to is_executable.\n"));
2583 return NT_STATUS_INVALID_PARAMETER;
2586 /* We need to duplicate this fsp. */
2587 return dup_file_fsp(req, fsp, access_mask, share_access,
2588 create_options, fsp_to_dup_into);
2591 static void schedule_defer_open(struct share_mode_lock *lck,
2592 struct file_id id,
2593 struct timeval request_time,
2594 struct smb_request *req)
2596 /* This is a relative time, added to the absolute
2597 request_time value to get the absolute timeout time.
2598 Note that if this is the second or greater time we enter
2599 this codepath for this particular request mid then
2600 request_time is left as the absolute time of the *first*
2601 time this request mid was processed. This is what allows
2602 the request to eventually time out. */
2604 struct timeval timeout;
2606 /* Normally the smbd we asked should respond within
2607 * OPLOCK_BREAK_TIMEOUT seconds regardless of whether
2608 * the client did, give twice the timeout as a safety
2609 * measure here in case the other smbd is stuck
2610 * somewhere else. */
2612 timeout = timeval_set(OPLOCK_BREAK_TIMEOUT*2, 0);
2614 if (request_timed_out(request_time, timeout)) {
2615 return;
2618 defer_open(lck, request_time, timeout, req, true, id);
2621 /****************************************************************************
2622 Reschedule an open call that went asynchronous.
2623 ****************************************************************************/
2625 static void schedule_async_open_timer(struct tevent_context *ev,
2626 struct tevent_timer *te,
2627 struct timeval current_time,
2628 void *private_data)
2630 exit_server("async open timeout");
2633 static void schedule_async_open(struct timeval request_time,
2634 struct smb_request *req)
2636 struct deferred_open_record *open_rec = NULL;
2637 struct timeval timeout = timeval_set(20, 0);
2638 bool ok;
2640 if (request_timed_out(request_time, timeout)) {
2641 return;
2644 open_rec = deferred_open_record_create(false, true, (struct file_id){0});
2645 if (open_rec == NULL) {
2646 exit_server("deferred_open_record_create failed");
2649 ok = push_deferred_open_message_smb(req, request_time, timeout,
2650 (struct file_id){0}, open_rec);
2651 if (!ok) {
2652 exit_server("push_deferred_open_message_smb failed");
2655 open_rec->te = tevent_add_timer(req->sconn->ev_ctx,
2656 req,
2657 timeval_current_ofs(20, 0),
2658 schedule_async_open_timer,
2659 open_rec);
2660 if (open_rec->te == NULL) {
2661 exit_server("tevent_add_timer failed");
2665 /****************************************************************************
2666 Work out what access_mask to use from what the client sent us.
2667 ****************************************************************************/
2669 static NTSTATUS smbd_calculate_maximum_allowed_access(
2670 connection_struct *conn,
2671 const struct smb_filename *smb_fname,
2672 bool use_privs,
2673 uint32_t *p_access_mask)
2675 struct security_descriptor *sd;
2676 uint32_t access_granted;
2677 NTSTATUS status;
2679 if (!use_privs && (get_current_uid(conn) == (uid_t)0)) {
2680 *p_access_mask |= FILE_GENERIC_ALL;
2681 return NT_STATUS_OK;
2684 status = SMB_VFS_GET_NT_ACL(conn, smb_fname,
2685 (SECINFO_OWNER |
2686 SECINFO_GROUP |
2687 SECINFO_DACL),
2688 talloc_tos(), &sd);
2690 if (NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
2692 * File did not exist
2694 *p_access_mask = FILE_GENERIC_ALL;
2695 return NT_STATUS_OK;
2697 if (!NT_STATUS_IS_OK(status)) {
2698 DEBUG(10,("Could not get acl on file %s: %s\n",
2699 smb_fname_str_dbg(smb_fname),
2700 nt_errstr(status)));
2701 return NT_STATUS_ACCESS_DENIED;
2705 * If we can access the path to this file, by
2706 * default we have FILE_READ_ATTRIBUTES from the
2707 * containing directory. See the section:
2708 * "Algorithm to Check Access to an Existing File"
2709 * in MS-FSA.pdf.
2711 * se_file_access_check()
2712 * also takes care of owner WRITE_DAC and READ_CONTROL.
2714 status = se_file_access_check(sd,
2715 get_current_nttok(conn),
2716 use_privs,
2717 (*p_access_mask & ~FILE_READ_ATTRIBUTES),
2718 &access_granted);
2720 TALLOC_FREE(sd);
2722 if (!NT_STATUS_IS_OK(status)) {
2723 DEBUG(10, ("Access denied on file %s: "
2724 "when calculating maximum access\n",
2725 smb_fname_str_dbg(smb_fname)));
2726 return NT_STATUS_ACCESS_DENIED;
2728 *p_access_mask = (access_granted | FILE_READ_ATTRIBUTES);
2730 if (!(access_granted & DELETE_ACCESS)) {
2731 if (can_delete_file_in_directory(conn, smb_fname)) {
2732 *p_access_mask |= DELETE_ACCESS;
2736 return NT_STATUS_OK;
2739 NTSTATUS smbd_calculate_access_mask(connection_struct *conn,
2740 const struct smb_filename *smb_fname,
2741 bool use_privs,
2742 uint32_t access_mask,
2743 uint32_t *access_mask_out)
2745 NTSTATUS status;
2746 uint32_t orig_access_mask = access_mask;
2747 uint32_t rejected_share_access;
2749 if (access_mask & SEC_MASK_INVALID) {
2750 DBG_DEBUG("access_mask [%8x] contains invalid bits\n",
2751 access_mask);
2752 return NT_STATUS_ACCESS_DENIED;
2756 * Convert GENERIC bits to specific bits.
2759 se_map_generic(&access_mask, &file_generic_mapping);
2761 /* Calculate MAXIMUM_ALLOWED_ACCESS if requested. */
2762 if (access_mask & MAXIMUM_ALLOWED_ACCESS) {
2764 status = smbd_calculate_maximum_allowed_access(
2765 conn, smb_fname, use_privs, &access_mask);
2767 if (!NT_STATUS_IS_OK(status)) {
2768 return status;
2771 access_mask &= conn->share_access;
2774 rejected_share_access = access_mask & ~(conn->share_access);
2776 if (rejected_share_access) {
2777 DEBUG(10, ("smbd_calculate_access_mask: Access denied on "
2778 "file %s: rejected by share access mask[0x%08X] "
2779 "orig[0x%08X] mapped[0x%08X] reject[0x%08X]\n",
2780 smb_fname_str_dbg(smb_fname),
2781 conn->share_access,
2782 orig_access_mask, access_mask,
2783 rejected_share_access));
2784 return NT_STATUS_ACCESS_DENIED;
2787 *access_mask_out = access_mask;
2788 return NT_STATUS_OK;
2791 /****************************************************************************
2792 Remove the deferred open entry under lock.
2793 ****************************************************************************/
2795 /****************************************************************************
2796 Return true if this is a state pointer to an asynchronous create.
2797 ****************************************************************************/
2799 bool is_deferred_open_async(const struct deferred_open_record *rec)
2801 return rec->async_open;
2804 static bool clear_ads(uint32_t create_disposition)
2806 bool ret = false;
2808 switch (create_disposition) {
2809 case FILE_SUPERSEDE:
2810 case FILE_OVERWRITE_IF:
2811 case FILE_OVERWRITE:
2812 ret = true;
2813 break;
2814 default:
2815 break;
2817 return ret;
2820 static int disposition_to_open_flags(uint32_t create_disposition)
2822 int ret = 0;
2825 * Currently we're using FILE_SUPERSEDE as the same as
2826 * FILE_OVERWRITE_IF but they really are
2827 * different. FILE_SUPERSEDE deletes an existing file
2828 * (requiring delete access) then recreates it.
2831 switch (create_disposition) {
2832 case FILE_SUPERSEDE:
2833 case FILE_OVERWRITE_IF:
2835 * If file exists replace/overwrite. If file doesn't
2836 * exist create.
2838 ret = O_CREAT|O_TRUNC;
2839 break;
2841 case FILE_OPEN:
2843 * If file exists open. If file doesn't exist error.
2845 ret = 0;
2846 break;
2848 case FILE_OVERWRITE:
2850 * If file exists overwrite. If file doesn't exist
2851 * error.
2853 ret = O_TRUNC;
2854 break;
2856 case FILE_CREATE:
2858 * If file exists error. If file doesn't exist create.
2860 ret = O_CREAT|O_EXCL;
2861 break;
2863 case FILE_OPEN_IF:
2865 * If file exists open. If file doesn't exist create.
2867 ret = O_CREAT;
2868 break;
2870 return ret;
2873 static int calculate_open_access_flags(uint32_t access_mask,
2874 uint32_t private_flags)
2876 bool need_write, need_read;
2879 * Note that we ignore the append flag as append does not
2880 * mean the same thing under DOS and Unix.
2883 need_write = (access_mask & (FILE_WRITE_DATA | FILE_APPEND_DATA));
2884 if (!need_write) {
2885 return O_RDONLY;
2888 /* DENY_DOS opens are always underlying read-write on the
2889 file handle, no matter what the requested access mask
2890 says. */
2892 need_read =
2893 ((private_flags & NTCREATEX_OPTIONS_PRIVATE_DENY_DOS) ||
2894 access_mask & (FILE_READ_ATTRIBUTES|FILE_READ_DATA|
2895 FILE_READ_EA|FILE_EXECUTE));
2897 if (!need_read) {
2898 return O_WRONLY;
2900 return O_RDWR;
2903 /****************************************************************************
2904 Open a file with a share mode. Passed in an already created files_struct *.
2905 ****************************************************************************/
2907 static NTSTATUS open_file_ntcreate(connection_struct *conn,
2908 struct smb_request *req,
2909 uint32_t access_mask, /* access bits (FILE_READ_DATA etc.) */
2910 uint32_t share_access, /* share constants (FILE_SHARE_READ etc) */
2911 uint32_t create_disposition, /* FILE_OPEN_IF etc. */
2912 uint32_t create_options, /* options such as delete on close. */
2913 uint32_t new_dos_attributes, /* attributes used for new file. */
2914 int oplock_request, /* internal Samba oplock codes. */
2915 struct smb2_lease *lease,
2916 /* Information (FILE_EXISTS etc.) */
2917 uint32_t private_flags, /* Samba specific flags. */
2918 int *pinfo,
2919 files_struct *fsp)
2921 struct smb_filename *smb_fname = fsp->fsp_name;
2922 int flags=0;
2923 int flags2=0;
2924 bool file_existed = VALID_STAT(smb_fname->st);
2925 bool def_acl = False;
2926 bool posix_open = False;
2927 bool new_file_created = False;
2928 bool first_open_attempt = true;
2929 NTSTATUS fsp_open = NT_STATUS_ACCESS_DENIED;
2930 mode_t new_unx_mode = (mode_t)0;
2931 mode_t unx_mode = (mode_t)0;
2932 int info;
2933 uint32_t existing_dos_attributes = 0;
2934 struct timeval request_time = timeval_zero();
2935 struct share_mode_lock *lck = NULL;
2936 uint32_t open_access_mask = access_mask;
2937 NTSTATUS status;
2938 char *parent_dir;
2939 SMB_STRUCT_STAT saved_stat = smb_fname->st;
2940 struct timespec old_write_time;
2941 struct file_id id;
2943 if (conn->printer) {
2945 * Printers are handled completely differently.
2946 * Most of the passed parameters are ignored.
2949 if (pinfo) {
2950 *pinfo = FILE_WAS_CREATED;
2953 DEBUG(10, ("open_file_ntcreate: printer open fname=%s\n",
2954 smb_fname_str_dbg(smb_fname)));
2956 if (!req) {
2957 DEBUG(0,("open_file_ntcreate: printer open without "
2958 "an SMB request!\n"));
2959 return NT_STATUS_INTERNAL_ERROR;
2962 return print_spool_open(fsp, smb_fname->base_name,
2963 req->vuid);
2966 if (!parent_dirname(talloc_tos(), smb_fname->base_name, &parent_dir,
2967 NULL)) {
2968 return NT_STATUS_NO_MEMORY;
2971 if (new_dos_attributes & FILE_FLAG_POSIX_SEMANTICS) {
2972 posix_open = True;
2973 unx_mode = (mode_t)(new_dos_attributes & ~FILE_FLAG_POSIX_SEMANTICS);
2974 new_dos_attributes = 0;
2975 } else {
2976 /* Windows allows a new file to be created and
2977 silently removes a FILE_ATTRIBUTE_DIRECTORY
2978 sent by the client. Do the same. */
2980 new_dos_attributes &= ~FILE_ATTRIBUTE_DIRECTORY;
2982 /* We add FILE_ATTRIBUTE_ARCHIVE to this as this mode is only used if the file is
2983 * created new. */
2984 unx_mode = unix_mode(conn, new_dos_attributes | FILE_ATTRIBUTE_ARCHIVE,
2985 smb_fname, parent_dir);
2988 DEBUG(10, ("open_file_ntcreate: fname=%s, dos_attrs=0x%x "
2989 "access_mask=0x%x share_access=0x%x "
2990 "create_disposition = 0x%x create_options=0x%x "
2991 "unix mode=0%o oplock_request=%d private_flags = 0x%x\n",
2992 smb_fname_str_dbg(smb_fname), new_dos_attributes,
2993 access_mask, share_access, create_disposition,
2994 create_options, (unsigned int)unx_mode, oplock_request,
2995 (unsigned int)private_flags));
2997 if (req == NULL) {
2998 /* Ensure req == NULL means INTERNAL_OPEN_ONLY */
2999 SMB_ASSERT(((oplock_request & INTERNAL_OPEN_ONLY) != 0));
3000 } else {
3001 /* And req != NULL means no INTERNAL_OPEN_ONLY */
3002 SMB_ASSERT(((oplock_request & INTERNAL_OPEN_ONLY) == 0));
3006 * Only non-internal opens can be deferred at all
3009 if (req) {
3010 struct deferred_open_record *open_rec;
3011 if (get_deferred_open_message_state(req,
3012 &request_time,
3013 &open_rec)) {
3014 /* Remember the absolute time of the original
3015 request with this mid. We'll use it later to
3016 see if this has timed out. */
3018 /* If it was an async create retry, the file
3019 didn't exist. */
3021 if (is_deferred_open_async(open_rec)) {
3022 SET_STAT_INVALID(smb_fname->st);
3023 file_existed = false;
3026 /* Ensure we don't reprocess this message. */
3027 remove_deferred_open_message_smb(req->xconn, req->mid);
3029 first_open_attempt = false;
3033 if (!posix_open) {
3034 new_dos_attributes &= SAMBA_ATTRIBUTES_MASK;
3035 if (file_existed) {
3037 * Only use strored DOS attributes for checks
3038 * against requested attributes (below via
3039 * open_match_attributes()), cf bug #11992
3040 * for details. -slow
3042 uint32_t attr = 0;
3044 status = SMB_VFS_GET_DOS_ATTRIBUTES(conn, smb_fname, &attr);
3045 if (NT_STATUS_IS_OK(status)) {
3046 existing_dos_attributes = attr;
3051 /* ignore any oplock requests if oplocks are disabled */
3052 if (!lp_oplocks(SNUM(conn)) ||
3053 IS_VETO_OPLOCK_PATH(conn, smb_fname->base_name)) {
3054 /* Mask off everything except the private Samba bits. */
3055 oplock_request &= SAMBA_PRIVATE_OPLOCK_MASK;
3058 /* this is for OS/2 long file names - say we don't support them */
3059 if (req != NULL && !req->posix_pathnames &&
3060 strstr(smb_fname->base_name,".+,;=[].")) {
3061 /* OS/2 Workplace shell fix may be main code stream in a later
3062 * release. */
3063 DEBUG(5,("open_file_ntcreate: OS/2 long filenames are not "
3064 "supported.\n"));
3065 if (use_nt_status()) {
3066 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3068 return NT_STATUS_DOS(ERRDOS, ERRcannotopen);
3071 switch( create_disposition ) {
3072 case FILE_OPEN:
3073 /* If file exists open. If file doesn't exist error. */
3074 if (!file_existed) {
3075 DEBUG(5,("open_file_ntcreate: FILE_OPEN "
3076 "requested for file %s and file "
3077 "doesn't exist.\n",
3078 smb_fname_str_dbg(smb_fname)));
3079 errno = ENOENT;
3080 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3082 break;
3084 case FILE_OVERWRITE:
3085 /* If file exists overwrite. If file doesn't exist
3086 * error. */
3087 if (!file_existed) {
3088 DEBUG(5,("open_file_ntcreate: FILE_OVERWRITE "
3089 "requested for file %s and file "
3090 "doesn't exist.\n",
3091 smb_fname_str_dbg(smb_fname) ));
3092 errno = ENOENT;
3093 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3095 break;
3097 case FILE_CREATE:
3098 /* If file exists error. If file doesn't exist
3099 * create. */
3100 if (file_existed) {
3101 DEBUG(5,("open_file_ntcreate: FILE_CREATE "
3102 "requested for file %s and file "
3103 "already exists.\n",
3104 smb_fname_str_dbg(smb_fname)));
3105 if (S_ISDIR(smb_fname->st.st_ex_mode)) {
3106 errno = EISDIR;
3107 } else {
3108 errno = EEXIST;
3110 return map_nt_error_from_unix(errno);
3112 break;
3114 case FILE_SUPERSEDE:
3115 case FILE_OVERWRITE_IF:
3116 case FILE_OPEN_IF:
3117 break;
3118 default:
3119 return NT_STATUS_INVALID_PARAMETER;
3122 flags2 = disposition_to_open_flags(create_disposition);
3124 /* We only care about matching attributes on file exists and
3125 * overwrite. */
3127 if (!posix_open && file_existed &&
3128 ((create_disposition == FILE_OVERWRITE) ||
3129 (create_disposition == FILE_OVERWRITE_IF))) {
3130 if (!open_match_attributes(conn, existing_dos_attributes,
3131 new_dos_attributes,
3132 smb_fname->st.st_ex_mode,
3133 unx_mode, &new_unx_mode)) {
3134 DEBUG(5,("open_file_ntcreate: attributes missmatch "
3135 "for file %s (%x %x) (0%o, 0%o)\n",
3136 smb_fname_str_dbg(smb_fname),
3137 existing_dos_attributes,
3138 new_dos_attributes,
3139 (unsigned int)smb_fname->st.st_ex_mode,
3140 (unsigned int)unx_mode ));
3141 errno = EACCES;
3142 return NT_STATUS_ACCESS_DENIED;
3146 status = smbd_calculate_access_mask(conn, smb_fname,
3147 false,
3148 access_mask,
3149 &access_mask);
3150 if (!NT_STATUS_IS_OK(status)) {
3151 DEBUG(10, ("open_file_ntcreate: smbd_calculate_access_mask "
3152 "on file %s returned %s\n",
3153 smb_fname_str_dbg(smb_fname), nt_errstr(status)));
3154 return status;
3157 open_access_mask = access_mask;
3159 if (flags2 & O_TRUNC) {
3160 open_access_mask |= FILE_WRITE_DATA; /* This will cause oplock breaks. */
3163 DEBUG(10, ("open_file_ntcreate: fname=%s, after mapping "
3164 "access_mask=0x%x\n", smb_fname_str_dbg(smb_fname),
3165 access_mask));
3168 * Note that we ignore the append flag as append does not
3169 * mean the same thing under DOS and Unix.
3172 flags = calculate_open_access_flags(access_mask, private_flags);
3175 * Currently we only look at FILE_WRITE_THROUGH for create options.
3178 #if defined(O_SYNC)
3179 if ((create_options & FILE_WRITE_THROUGH) && lp_strict_sync(SNUM(conn))) {
3180 flags2 |= O_SYNC;
3182 #endif /* O_SYNC */
3184 if (posix_open && (access_mask & FILE_APPEND_DATA)) {
3185 flags2 |= O_APPEND;
3188 if (!posix_open && !CAN_WRITE(conn)) {
3190 * We should really return a permission denied error if either
3191 * O_CREAT or O_TRUNC are set, but for compatibility with
3192 * older versions of Samba we just AND them out.
3194 flags2 &= ~(O_CREAT|O_TRUNC);
3197 if (lp_kernel_oplocks(SNUM(conn))) {
3199 * With kernel oplocks the open breaking an oplock
3200 * blocks until the oplock holder has given up the
3201 * oplock or closed the file. We prevent this by always
3202 * trying to open the file with O_NONBLOCK (see "man
3203 * fcntl" on Linux).
3205 * If a process that doesn't use the smbd open files
3206 * database or communication methods holds a kernel
3207 * oplock we must periodically poll for available open
3208 * using O_NONBLOCK.
3210 flags2 |= O_NONBLOCK;
3214 * Ensure we can't write on a read-only share or file.
3217 if (flags != O_RDONLY && file_existed &&
3218 (!CAN_WRITE(conn) || IS_DOS_READONLY(existing_dos_attributes))) {
3219 DEBUG(5,("open_file_ntcreate: write access requested for "
3220 "file %s on read only %s\n",
3221 smb_fname_str_dbg(smb_fname),
3222 !CAN_WRITE(conn) ? "share" : "file" ));
3223 errno = EACCES;
3224 return NT_STATUS_ACCESS_DENIED;
3227 fsp->file_id = vfs_file_id_from_sbuf(conn, &smb_fname->st);
3228 fsp->share_access = share_access;
3229 fsp->fh->private_options = private_flags;
3230 fsp->access_mask = open_access_mask; /* We change this to the
3231 * requested access_mask after
3232 * the open is done. */
3233 if (posix_open) {
3234 fsp->posix_flags |= FSP_POSIX_FLAGS_ALL;
3237 if (timeval_is_zero(&request_time)) {
3238 request_time = fsp->open_time;
3242 * Ensure we pay attention to default ACLs on directories if required.
3245 if ((flags2 & O_CREAT) && lp_inherit_acls(SNUM(conn)) &&
3246 (def_acl = directory_has_default_acl(conn, parent_dir))) {
3247 unx_mode = (0777 & lp_create_mask(SNUM(conn)));
3250 DEBUG(4,("calling open_file with flags=0x%X flags2=0x%X mode=0%o, "
3251 "access_mask = 0x%x, open_access_mask = 0x%x\n",
3252 (unsigned int)flags, (unsigned int)flags2,
3253 (unsigned int)unx_mode, (unsigned int)access_mask,
3254 (unsigned int)open_access_mask));
3256 fsp_open = open_file(fsp, conn, req, parent_dir,
3257 flags|flags2, unx_mode, access_mask,
3258 open_access_mask, &new_file_created);
3260 if (NT_STATUS_EQUAL(fsp_open, NT_STATUS_NETWORK_BUSY)) {
3261 bool delay;
3264 * This handles the kernel oplock case:
3266 * the file has an active kernel oplock and the open() returned
3267 * EWOULDBLOCK/EAGAIN which maps to NETWORK_BUSY.
3269 * "Samba locking.tdb oplocks" are handled below after acquiring
3270 * the sharemode lock with get_share_mode_lock().
3272 if (file_existed && S_ISFIFO(fsp->fsp_name->st.st_ex_mode)) {
3273 DEBUG(10, ("FIFO busy\n"));
3274 return NT_STATUS_NETWORK_BUSY;
3276 if (req == NULL) {
3277 DEBUG(10, ("Internal open busy\n"));
3278 return NT_STATUS_NETWORK_BUSY;
3282 * From here on we assume this is an oplock break triggered
3285 lck = get_existing_share_mode_lock(talloc_tos(), fsp->file_id);
3286 if (lck == NULL) {
3288 * No oplock from Samba around. Set up a poll every 1
3289 * second to retry a non-blocking open until the time
3290 * expires.
3292 setup_kernel_oplock_poll_open(request_time,
3293 req,
3294 fsp->file_id);
3295 DBG_DEBUG("No Samba oplock around after EWOULDBLOCK. "
3296 "Retrying with poll\n");
3297 return NT_STATUS_SHARING_VIOLATION;
3300 if (!validate_oplock_types(lck)) {
3301 smb_panic("validate_oplock_types failed");
3304 delay = delay_for_oplock(fsp, 0, lease, lck, false,
3305 create_disposition,
3306 first_open_attempt);
3307 if (delay) {
3308 schedule_defer_open(lck, fsp->file_id, request_time,
3309 req);
3310 TALLOC_FREE(lck);
3311 DEBUG(10, ("Sent oplock break request to kernel "
3312 "oplock holder\n"));
3313 return NT_STATUS_SHARING_VIOLATION;
3317 * No oplock from Samba around. Set up a poll every 1
3318 * second to retry a non-blocking open until the time
3319 * expires.
3321 setup_kernel_oplock_poll_open(request_time, req, fsp->file_id);
3323 TALLOC_FREE(lck);
3324 DBG_DEBUG("No Samba oplock around after EWOULDBLOCK. "
3325 "Retrying with poll\n");
3326 return NT_STATUS_SHARING_VIOLATION;
3329 if (!NT_STATUS_IS_OK(fsp_open)) {
3330 if (NT_STATUS_EQUAL(fsp_open, NT_STATUS_RETRY)) {
3331 schedule_async_open(request_time, req);
3333 return fsp_open;
3336 if (new_file_created) {
3338 * As we atomically create using O_CREAT|O_EXCL,
3339 * then if new_file_created is true, then
3340 * file_existed *MUST* have been false (even
3341 * if the file was previously detected as being
3342 * there).
3344 file_existed = false;
3347 if (file_existed && !check_same_dev_ino(&saved_stat, &smb_fname->st)) {
3349 * The file did exist, but some other (local or NFS)
3350 * process either renamed/unlinked and re-created the
3351 * file with different dev/ino after we walked the path,
3352 * but before we did the open. We could retry the
3353 * open but it's a rare enough case it's easier to
3354 * just fail the open to prevent creating any problems
3355 * in the open file db having the wrong dev/ino key.
3357 fd_close(fsp);
3358 DEBUG(1,("open_file_ntcreate: file %s - dev/ino mismatch. "
3359 "Old (dev=0x%llu, ino =0x%llu). "
3360 "New (dev=0x%llu, ino=0x%llu). Failing open "
3361 " with NT_STATUS_ACCESS_DENIED.\n",
3362 smb_fname_str_dbg(smb_fname),
3363 (unsigned long long)saved_stat.st_ex_dev,
3364 (unsigned long long)saved_stat.st_ex_ino,
3365 (unsigned long long)smb_fname->st.st_ex_dev,
3366 (unsigned long long)smb_fname->st.st_ex_ino));
3367 return NT_STATUS_ACCESS_DENIED;
3370 old_write_time = smb_fname->st.st_ex_mtime;
3373 * Deal with the race condition where two smbd's detect the
3374 * file doesn't exist and do the create at the same time. One
3375 * of them will win and set a share mode, the other (ie. this
3376 * one) should check if the requested share mode for this
3377 * create is allowed.
3381 * Now the file exists and fsp is successfully opened,
3382 * fsp->dev and fsp->inode are valid and should replace the
3383 * dev=0,inode=0 from a non existent file. Spotted by
3384 * Nadav Danieli <nadavd@exanet.com>. JRA.
3387 id = fsp->file_id;
3389 lck = get_share_mode_lock(talloc_tos(), id,
3390 conn->connectpath,
3391 smb_fname, &old_write_time);
3393 if (lck == NULL) {
3394 DEBUG(0, ("open_file_ntcreate: Could not get share "
3395 "mode lock for %s\n",
3396 smb_fname_str_dbg(smb_fname)));
3397 fd_close(fsp);
3398 return NT_STATUS_SHARING_VIOLATION;
3401 /* Get the types we need to examine. */
3402 if (!validate_oplock_types(lck)) {
3403 smb_panic("validate_oplock_types failed");
3406 if (has_delete_on_close(lck, fsp->name_hash)) {
3407 TALLOC_FREE(lck);
3408 fd_close(fsp);
3409 return NT_STATUS_DELETE_PENDING;
3412 status = open_mode_check(conn, lck,
3413 access_mask, share_access);
3415 if (NT_STATUS_EQUAL(status, NT_STATUS_SHARING_VIOLATION) ||
3416 (lck->data->num_share_modes > 0)) {
3418 * This comes from ancient times out of open_mode_check. I
3419 * have no clue whether this is still necessary. I can't think
3420 * of a case where this would actually matter further down in
3421 * this function. I leave it here for further investigation
3422 * :-)
3424 file_existed = true;
3427 if (req != NULL) {
3429 * Handle oplocks, deferring the request if delay_for_oplock()
3430 * triggered a break message and we have to wait for the break
3431 * response.
3433 bool delay;
3434 bool sharing_violation = NT_STATUS_EQUAL(
3435 status, NT_STATUS_SHARING_VIOLATION);
3437 delay = delay_for_oplock(fsp, oplock_request, lease, lck,
3438 sharing_violation,
3439 create_disposition,
3440 first_open_attempt);
3441 if (delay) {
3442 schedule_defer_open(lck, fsp->file_id,
3443 request_time, req);
3444 TALLOC_FREE(lck);
3445 fd_close(fsp);
3446 return NT_STATUS_SHARING_VIOLATION;
3450 if (!NT_STATUS_IS_OK(status)) {
3451 uint32_t can_access_mask;
3452 bool can_access = True;
3454 SMB_ASSERT(NT_STATUS_EQUAL(status, NT_STATUS_SHARING_VIOLATION));
3456 /* Check if this can be done with the deny_dos and fcb
3457 * calls. */
3458 if (private_flags &
3459 (NTCREATEX_OPTIONS_PRIVATE_DENY_DOS|
3460 NTCREATEX_OPTIONS_PRIVATE_DENY_FCB)) {
3461 if (req == NULL) {
3462 DEBUG(0, ("DOS open without an SMB "
3463 "request!\n"));
3464 TALLOC_FREE(lck);
3465 fd_close(fsp);
3466 return NT_STATUS_INTERNAL_ERROR;
3469 /* Use the client requested access mask here,
3470 * not the one we open with. */
3471 status = fcb_or_dos_open(req,
3472 conn,
3473 fsp,
3474 smb_fname,
3476 req->smbpid,
3477 req->vuid,
3478 access_mask,
3479 share_access,
3480 create_options);
3482 if (NT_STATUS_IS_OK(status)) {
3483 TALLOC_FREE(lck);
3484 if (pinfo) {
3485 *pinfo = FILE_WAS_OPENED;
3487 return NT_STATUS_OK;
3492 * This next line is a subtlety we need for
3493 * MS-Access. If a file open will fail due to share
3494 * permissions and also for security (access) reasons,
3495 * we need to return the access failed error, not the
3496 * share error. We can't open the file due to kernel
3497 * oplock deadlock (it's possible we failed above on
3498 * the open_mode_check()) so use a userspace check.
3501 if (flags & O_RDWR) {
3502 can_access_mask = FILE_READ_DATA|FILE_WRITE_DATA;
3503 } else if (flags & O_WRONLY) {
3504 can_access_mask = FILE_WRITE_DATA;
3505 } else {
3506 can_access_mask = FILE_READ_DATA;
3509 if (((can_access_mask & FILE_WRITE_DATA) &&
3510 !CAN_WRITE(conn)) ||
3511 !NT_STATUS_IS_OK(smbd_check_access_rights(conn,
3512 smb_fname,
3513 false,
3514 can_access_mask))) {
3515 can_access = False;
3519 * If we're returning a share violation, ensure we
3520 * cope with the braindead 1 second delay (SMB1 only).
3523 if (!(oplock_request & INTERNAL_OPEN_ONLY) &&
3524 !conn->sconn->using_smb2 &&
3525 lp_defer_sharing_violations()) {
3526 struct timeval timeout;
3527 int timeout_usecs;
3529 /* this is a hack to speed up torture tests
3530 in 'make test' */
3531 timeout_usecs = lp_parm_int(SNUM(conn),
3532 "smbd","sharedelay",
3533 SHARING_VIOLATION_USEC_WAIT);
3535 /* This is a relative time, added to the absolute
3536 request_time value to get the absolute timeout time.
3537 Note that if this is the second or greater time we enter
3538 this codepath for this particular request mid then
3539 request_time is left as the absolute time of the *first*
3540 time this request mid was processed. This is what allows
3541 the request to eventually time out. */
3543 timeout = timeval_set(0, timeout_usecs);
3545 if (!request_timed_out(request_time, timeout)) {
3546 defer_open(lck, request_time, timeout, req,
3547 false, id);
3551 TALLOC_FREE(lck);
3552 fd_close(fsp);
3553 if (can_access) {
3555 * We have detected a sharing violation here
3556 * so return the correct error code
3558 status = NT_STATUS_SHARING_VIOLATION;
3559 } else {
3560 status = NT_STATUS_ACCESS_DENIED;
3562 return status;
3565 /* Should we atomically (to the client at least) truncate ? */
3566 if ((!new_file_created) &&
3567 (flags2 & O_TRUNC) &&
3568 (!S_ISFIFO(fsp->fsp_name->st.st_ex_mode))) {
3569 int ret;
3571 ret = vfs_set_filelen(fsp, 0);
3572 if (ret != 0) {
3573 status = map_nt_error_from_unix(errno);
3574 TALLOC_FREE(lck);
3575 fd_close(fsp);
3576 return status;
3581 * We have the share entry *locked*.....
3584 /* Delete streams if create_disposition requires it */
3585 if (!new_file_created && clear_ads(create_disposition) &&
3586 !is_ntfs_stream_smb_fname(smb_fname)) {
3587 status = delete_all_streams(conn, smb_fname);
3588 if (!NT_STATUS_IS_OK(status)) {
3589 TALLOC_FREE(lck);
3590 fd_close(fsp);
3591 return status;
3595 /* note that we ignore failure for the following. It is
3596 basically a hack for NFS, and NFS will never set one of
3597 these only read them. Nobody but Samba can ever set a deny
3598 mode and we have already checked our more authoritative
3599 locking database for permission to set this deny mode. If
3600 the kernel refuses the operations then the kernel is wrong.
3601 note that GPFS supports it as well - jmcd */
3603 if (fsp->fh->fd != -1 && lp_kernel_share_modes(SNUM(conn))) {
3604 int ret_flock;
3606 * Beware: streams implementing VFS modules may
3607 * implement streams in a way that fsp will have the
3608 * basefile open in the fsp fd, so lacking a distinct
3609 * fd for the stream kernel_flock will apply on the
3610 * basefile which is wrong. The actual check is
3611 * deffered to the VFS module implementing the
3612 * kernel_flock call.
3614 ret_flock = SMB_VFS_KERNEL_FLOCK(fsp, share_access, access_mask);
3615 if(ret_flock == -1 ){
3617 TALLOC_FREE(lck);
3618 fd_close(fsp);
3620 return NT_STATUS_SHARING_VIOLATION;
3623 fsp->kernel_share_modes_taken = true;
3627 * At this point onwards, we can guarantee that the share entry
3628 * is locked, whether we created the file or not, and that the
3629 * deny mode is compatible with all current opens.
3633 * According to Samba4, SEC_FILE_READ_ATTRIBUTE is always granted,
3634 * but we don't have to store this - just ignore it on access check.
3636 if (conn->sconn->using_smb2) {
3638 * SMB2 doesn't return it (according to Microsoft tests).
3639 * Test Case: TestSuite_ScenarioNo009GrantedAccessTestS0
3640 * File created with access = 0x7 (Read, Write, Delete)
3641 * Query Info on file returns 0x87 (Read, Write, Delete, Read Attributes)
3643 fsp->access_mask = access_mask;
3644 } else {
3645 /* But SMB1 does. */
3646 fsp->access_mask = access_mask | FILE_READ_ATTRIBUTES;
3649 if (file_existed) {
3651 * stat opens on existing files don't get oplocks.
3652 * They can get leases.
3654 * Note that we check for stat open on the *open_access_mask*,
3655 * i.e. the access mask we actually used to do the open,
3656 * not the one the client asked for (which is in
3657 * fsp->access_mask). This is due to the fact that
3658 * FILE_OVERWRITE and FILE_OVERWRITE_IF add in O_TRUNC,
3659 * which adds FILE_WRITE_DATA to open_access_mask.
3661 if (is_stat_open(open_access_mask) && lease == NULL) {
3662 oplock_request = NO_OPLOCK;
3666 if (new_file_created) {
3667 info = FILE_WAS_CREATED;
3668 } else {
3669 if (flags2 & O_TRUNC) {
3670 info = FILE_WAS_OVERWRITTEN;
3671 } else {
3672 info = FILE_WAS_OPENED;
3676 if (pinfo) {
3677 *pinfo = info;
3681 * Setup the oplock info in both the shared memory and
3682 * file structs.
3684 status = grant_fsp_oplock_type(req, fsp, lck, oplock_request, lease);
3685 if (!NT_STATUS_IS_OK(status)) {
3686 TALLOC_FREE(lck);
3687 fd_close(fsp);
3688 return status;
3691 /* Handle strange delete on close create semantics. */
3692 if (create_options & FILE_DELETE_ON_CLOSE) {
3694 status = can_set_delete_on_close(fsp, new_dos_attributes);
3696 if (!NT_STATUS_IS_OK(status)) {
3697 /* Remember to delete the mode we just added. */
3698 del_share_mode(lck, fsp);
3699 TALLOC_FREE(lck);
3700 fd_close(fsp);
3701 return status;
3703 /* Note that here we set the *inital* delete on close flag,
3704 not the regular one. The magic gets handled in close. */
3705 fsp->initial_delete_on_close = True;
3708 if (info != FILE_WAS_OPENED) {
3709 /* Overwritten files should be initially set as archive */
3710 if ((info == FILE_WAS_OVERWRITTEN && lp_map_archive(SNUM(conn))) ||
3711 lp_store_dos_attributes(SNUM(conn))) {
3712 if (!posix_open) {
3713 if (file_set_dosmode(conn, smb_fname,
3714 new_dos_attributes | FILE_ATTRIBUTE_ARCHIVE,
3715 parent_dir, true) == 0) {
3716 unx_mode = smb_fname->st.st_ex_mode;
3722 /* Determine sparse flag. */
3723 if (posix_open) {
3724 /* POSIX opens are sparse by default. */
3725 fsp->is_sparse = true;
3726 } else {
3727 fsp->is_sparse = (file_existed &&
3728 (existing_dos_attributes & FILE_ATTRIBUTE_SPARSE));
3732 * Take care of inherited ACLs on created files - if default ACL not
3733 * selected.
3736 if (!posix_open && new_file_created && !def_acl) {
3738 int saved_errno = errno; /* We might get ENOSYS in the next
3739 * call.. */
3741 if (SMB_VFS_FCHMOD_ACL(fsp, unx_mode) == -1 &&
3742 errno == ENOSYS) {
3743 errno = saved_errno; /* Ignore ENOSYS */
3746 } else if (new_unx_mode) {
3748 int ret = -1;
3750 /* Attributes need changing. File already existed. */
3753 int saved_errno = errno; /* We might get ENOSYS in the
3754 * next call.. */
3755 ret = SMB_VFS_FCHMOD_ACL(fsp, new_unx_mode);
3757 if (ret == -1 && errno == ENOSYS) {
3758 errno = saved_errno; /* Ignore ENOSYS */
3759 } else {
3760 DEBUG(5, ("open_file_ntcreate: reset "
3761 "attributes of file %s to 0%o\n",
3762 smb_fname_str_dbg(smb_fname),
3763 (unsigned int)new_unx_mode));
3764 ret = 0; /* Don't do the fchmod below. */
3768 if ((ret == -1) &&
3769 (SMB_VFS_FCHMOD(fsp, new_unx_mode) == -1))
3770 DEBUG(5, ("open_file_ntcreate: failed to reset "
3771 "attributes of file %s to 0%o\n",
3772 smb_fname_str_dbg(smb_fname),
3773 (unsigned int)new_unx_mode));
3778 * Deal with other opens having a modified write time.
3780 struct timespec write_time = get_share_mode_write_time(lck);
3782 if (!null_timespec(write_time)) {
3783 update_stat_ex_mtime(&fsp->fsp_name->st, write_time);
3787 TALLOC_FREE(lck);
3789 return NT_STATUS_OK;
3792 static NTSTATUS mkdir_internal(connection_struct *conn,
3793 struct smb_filename *smb_dname,
3794 uint32_t file_attributes)
3796 mode_t mode;
3797 char *parent_dir = NULL;
3798 NTSTATUS status;
3799 bool posix_open = false;
3800 bool need_re_stat = false;
3801 uint32_t access_mask = SEC_DIR_ADD_SUBDIR;
3803 if (!CAN_WRITE(conn) || (access_mask & ~(conn->share_access))) {
3804 DEBUG(5,("mkdir_internal: failing share access "
3805 "%s\n", lp_servicename(talloc_tos(), SNUM(conn))));
3806 return NT_STATUS_ACCESS_DENIED;
3809 if (!parent_dirname(talloc_tos(), smb_dname->base_name, &parent_dir,
3810 NULL)) {
3811 return NT_STATUS_NO_MEMORY;
3814 if (file_attributes & FILE_FLAG_POSIX_SEMANTICS) {
3815 posix_open = true;
3816 mode = (mode_t)(file_attributes & ~FILE_FLAG_POSIX_SEMANTICS);
3817 } else {
3818 mode = unix_mode(conn, FILE_ATTRIBUTE_DIRECTORY, smb_dname, parent_dir);
3821 status = check_parent_access(conn,
3822 smb_dname,
3823 access_mask);
3824 if(!NT_STATUS_IS_OK(status)) {
3825 DEBUG(5,("mkdir_internal: check_parent_access "
3826 "on directory %s for path %s returned %s\n",
3827 parent_dir,
3828 smb_dname->base_name,
3829 nt_errstr(status) ));
3830 return status;
3833 if (SMB_VFS_MKDIR(conn, smb_dname, mode) != 0) {
3834 return map_nt_error_from_unix(errno);
3837 /* Ensure we're checking for a symlink here.... */
3838 /* We don't want to get caught by a symlink racer. */
3840 if (SMB_VFS_LSTAT(conn, smb_dname) == -1) {
3841 DEBUG(2, ("Could not stat directory '%s' just created: %s\n",
3842 smb_fname_str_dbg(smb_dname), strerror(errno)));
3843 return map_nt_error_from_unix(errno);
3846 if (!S_ISDIR(smb_dname->st.st_ex_mode)) {
3847 DEBUG(0, ("Directory '%s' just created is not a directory !\n",
3848 smb_fname_str_dbg(smb_dname)));
3849 return NT_STATUS_NOT_A_DIRECTORY;
3852 if (lp_store_dos_attributes(SNUM(conn))) {
3853 if (!posix_open) {
3854 file_set_dosmode(conn, smb_dname,
3855 file_attributes | FILE_ATTRIBUTE_DIRECTORY,
3856 parent_dir, true);
3860 if (lp_inherit_permissions(SNUM(conn))) {
3861 inherit_access_posix_acl(conn, parent_dir,
3862 smb_dname, mode);
3863 need_re_stat = true;
3866 if (!posix_open) {
3868 * Check if high bits should have been set,
3869 * then (if bits are missing): add them.
3870 * Consider bits automagically set by UNIX, i.e. SGID bit from parent
3871 * dir.
3873 if ((mode & ~(S_IRWXU|S_IRWXG|S_IRWXO)) &&
3874 (mode & ~smb_dname->st.st_ex_mode)) {
3875 SMB_VFS_CHMOD(conn, smb_dname,
3876 (smb_dname->st.st_ex_mode |
3877 (mode & ~smb_dname->st.st_ex_mode)));
3878 need_re_stat = true;
3882 /* Change the owner if required. */
3883 if (lp_inherit_owner(SNUM(conn)) != INHERIT_OWNER_NO) {
3884 change_dir_owner_to_parent(conn, parent_dir,
3885 smb_dname,
3886 &smb_dname->st);
3887 need_re_stat = true;
3890 if (need_re_stat) {
3891 if (SMB_VFS_LSTAT(conn, smb_dname) == -1) {
3892 DEBUG(2, ("Could not stat directory '%s' just created: %s\n",
3893 smb_fname_str_dbg(smb_dname), strerror(errno)));
3894 return map_nt_error_from_unix(errno);
3898 notify_fname(conn, NOTIFY_ACTION_ADDED, FILE_NOTIFY_CHANGE_DIR_NAME,
3899 smb_dname->base_name);
3901 return NT_STATUS_OK;
3904 /****************************************************************************
3905 Open a directory from an NT SMB call.
3906 ****************************************************************************/
3908 static NTSTATUS open_directory(connection_struct *conn,
3909 struct smb_request *req,
3910 struct smb_filename *smb_dname,
3911 uint32_t access_mask,
3912 uint32_t share_access,
3913 uint32_t create_disposition,
3914 uint32_t create_options,
3915 uint32_t file_attributes,
3916 int *pinfo,
3917 files_struct **result)
3919 files_struct *fsp = NULL;
3920 bool dir_existed = VALID_STAT(smb_dname->st) ? True : False;
3921 struct share_mode_lock *lck = NULL;
3922 NTSTATUS status;
3923 struct timespec mtimespec;
3924 int info = 0;
3925 bool ok;
3927 if (is_ntfs_stream_smb_fname(smb_dname)) {
3928 DEBUG(2, ("open_directory: %s is a stream name!\n",
3929 smb_fname_str_dbg(smb_dname)));
3930 return NT_STATUS_NOT_A_DIRECTORY;
3933 if (!(file_attributes & FILE_FLAG_POSIX_SEMANTICS)) {
3934 /* Ensure we have a directory attribute. */
3935 file_attributes |= FILE_ATTRIBUTE_DIRECTORY;
3938 DEBUG(5,("open_directory: opening directory %s, access_mask = 0x%x, "
3939 "share_access = 0x%x create_options = 0x%x, "
3940 "create_disposition = 0x%x, file_attributes = 0x%x\n",
3941 smb_fname_str_dbg(smb_dname),
3942 (unsigned int)access_mask,
3943 (unsigned int)share_access,
3944 (unsigned int)create_options,
3945 (unsigned int)create_disposition,
3946 (unsigned int)file_attributes));
3948 status = smbd_calculate_access_mask(conn, smb_dname, false,
3949 access_mask, &access_mask);
3950 if (!NT_STATUS_IS_OK(status)) {
3951 DEBUG(10, ("open_directory: smbd_calculate_access_mask "
3952 "on file %s returned %s\n",
3953 smb_fname_str_dbg(smb_dname),
3954 nt_errstr(status)));
3955 return status;
3958 if ((access_mask & SEC_FLAG_SYSTEM_SECURITY) &&
3959 !security_token_has_privilege(get_current_nttok(conn),
3960 SEC_PRIV_SECURITY)) {
3961 DEBUG(10, ("open_directory: open on %s "
3962 "failed - SEC_FLAG_SYSTEM_SECURITY denied.\n",
3963 smb_fname_str_dbg(smb_dname)));
3964 return NT_STATUS_PRIVILEGE_NOT_HELD;
3967 switch( create_disposition ) {
3968 case FILE_OPEN:
3970 if (!dir_existed) {
3971 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3974 info = FILE_WAS_OPENED;
3975 break;
3977 case FILE_CREATE:
3979 /* If directory exists error. If directory doesn't
3980 * exist create. */
3982 if (dir_existed) {
3983 status = NT_STATUS_OBJECT_NAME_COLLISION;
3984 DEBUG(2, ("open_directory: unable to create "
3985 "%s. Error was %s\n",
3986 smb_fname_str_dbg(smb_dname),
3987 nt_errstr(status)));
3988 return status;
3991 status = mkdir_internal(conn, smb_dname,
3992 file_attributes);
3994 if (!NT_STATUS_IS_OK(status)) {
3995 DEBUG(2, ("open_directory: unable to create "
3996 "%s. Error was %s\n",
3997 smb_fname_str_dbg(smb_dname),
3998 nt_errstr(status)));
3999 return status;
4002 info = FILE_WAS_CREATED;
4003 break;
4005 case FILE_OPEN_IF:
4007 * If directory exists open. If directory doesn't
4008 * exist create.
4011 if (dir_existed) {
4012 status = NT_STATUS_OK;
4013 info = FILE_WAS_OPENED;
4014 } else {
4015 status = mkdir_internal(conn, smb_dname,
4016 file_attributes);
4018 if (NT_STATUS_IS_OK(status)) {
4019 info = FILE_WAS_CREATED;
4020 } else {
4021 /* Cope with create race. */
4022 if (!NT_STATUS_EQUAL(status,
4023 NT_STATUS_OBJECT_NAME_COLLISION)) {
4024 DEBUG(2, ("open_directory: unable to create "
4025 "%s. Error was %s\n",
4026 smb_fname_str_dbg(smb_dname),
4027 nt_errstr(status)));
4028 return status;
4032 * If mkdir_internal() returned
4033 * NT_STATUS_OBJECT_NAME_COLLISION
4034 * we still must lstat the path.
4037 if (SMB_VFS_LSTAT(conn, smb_dname)
4038 == -1) {
4039 DEBUG(2, ("Could not stat "
4040 "directory '%s' just "
4041 "opened: %s\n",
4042 smb_fname_str_dbg(
4043 smb_dname),
4044 strerror(errno)));
4045 return map_nt_error_from_unix(
4046 errno);
4049 info = FILE_WAS_OPENED;
4053 break;
4055 case FILE_SUPERSEDE:
4056 case FILE_OVERWRITE:
4057 case FILE_OVERWRITE_IF:
4058 default:
4059 DEBUG(5,("open_directory: invalid create_disposition "
4060 "0x%x for directory %s\n",
4061 (unsigned int)create_disposition,
4062 smb_fname_str_dbg(smb_dname)));
4063 return NT_STATUS_INVALID_PARAMETER;
4066 if(!S_ISDIR(smb_dname->st.st_ex_mode)) {
4067 DEBUG(5,("open_directory: %s is not a directory !\n",
4068 smb_fname_str_dbg(smb_dname)));
4069 return NT_STATUS_NOT_A_DIRECTORY;
4072 if (info == FILE_WAS_OPENED) {
4073 status = smbd_check_access_rights(conn,
4074 smb_dname,
4075 false,
4076 access_mask);
4077 if (!NT_STATUS_IS_OK(status)) {
4078 DEBUG(10, ("open_directory: smbd_check_access_rights on "
4079 "file %s failed with %s\n",
4080 smb_fname_str_dbg(smb_dname),
4081 nt_errstr(status)));
4082 return status;
4086 status = file_new(req, conn, &fsp);
4087 if(!NT_STATUS_IS_OK(status)) {
4088 return status;
4092 * Setup the files_struct for it.
4095 fsp->file_id = vfs_file_id_from_sbuf(conn, &smb_dname->st);
4096 fsp->vuid = req ? req->vuid : UID_FIELD_INVALID;
4097 fsp->file_pid = req ? req->smbpid : 0;
4098 fsp->can_lock = False;
4099 fsp->can_read = False;
4100 fsp->can_write = False;
4102 fsp->share_access = share_access;
4103 fsp->fh->private_options = 0;
4105 * According to Samba4, SEC_FILE_READ_ATTRIBUTE is always granted,
4107 fsp->access_mask = access_mask | FILE_READ_ATTRIBUTES;
4108 fsp->print_file = NULL;
4109 fsp->modified = False;
4110 fsp->oplock_type = NO_OPLOCK;
4111 fsp->sent_oplock_break = NO_BREAK_SENT;
4112 fsp->is_directory = True;
4113 if (file_attributes & FILE_FLAG_POSIX_SEMANTICS) {
4114 fsp->posix_flags |= FSP_POSIX_FLAGS_ALL;
4116 status = fsp_set_smb_fname(fsp, smb_dname);
4117 if (!NT_STATUS_IS_OK(status)) {
4118 file_free(req, fsp);
4119 return status;
4122 /* Don't store old timestamps for directory
4123 handles in the internal database. We don't
4124 update them in there if new objects
4125 are creaded in the directory. Currently
4126 we only update timestamps on file writes.
4127 See bug #9870.
4129 ZERO_STRUCT(mtimespec);
4131 if (access_mask & (FILE_LIST_DIRECTORY|
4132 FILE_ADD_FILE|
4133 FILE_ADD_SUBDIRECTORY|
4134 FILE_TRAVERSE|
4135 DELETE_ACCESS|
4136 FILE_DELETE_CHILD)) {
4137 #ifdef O_DIRECTORY
4138 status = fd_open(conn, fsp, O_RDONLY|O_DIRECTORY, 0);
4139 #else
4140 /* POSIX allows us to open a directory with O_RDONLY. */
4141 status = fd_open(conn, fsp, O_RDONLY, 0);
4142 #endif
4143 if (!NT_STATUS_IS_OK(status)) {
4144 DEBUG(5, ("open_directory: Could not open fd for "
4145 "%s (%s)\n",
4146 smb_fname_str_dbg(smb_dname),
4147 nt_errstr(status)));
4148 file_free(req, fsp);
4149 return status;
4151 } else {
4152 fsp->fh->fd = -1;
4153 DEBUG(10, ("Not opening Directory %s\n",
4154 smb_fname_str_dbg(smb_dname)));
4157 status = vfs_stat_fsp(fsp);
4158 if (!NT_STATUS_IS_OK(status)) {
4159 fd_close(fsp);
4160 file_free(req, fsp);
4161 return status;
4164 if(!S_ISDIR(fsp->fsp_name->st.st_ex_mode)) {
4165 DEBUG(5,("open_directory: %s is not a directory !\n",
4166 smb_fname_str_dbg(smb_dname)));
4167 fd_close(fsp);
4168 file_free(req, fsp);
4169 return NT_STATUS_NOT_A_DIRECTORY;
4172 /* Ensure there was no race condition. We need to check
4173 * dev/inode but not permissions, as these can change
4174 * legitimately */
4175 if (!check_same_dev_ino(&smb_dname->st, &fsp->fsp_name->st)) {
4176 DEBUG(5,("open_directory: stat struct differs for "
4177 "directory %s.\n",
4178 smb_fname_str_dbg(smb_dname)));
4179 fd_close(fsp);
4180 file_free(req, fsp);
4181 return NT_STATUS_ACCESS_DENIED;
4184 lck = get_share_mode_lock(talloc_tos(), fsp->file_id,
4185 conn->connectpath, smb_dname,
4186 &mtimespec);
4188 if (lck == NULL) {
4189 DEBUG(0, ("open_directory: Could not get share mode lock for "
4190 "%s\n", smb_fname_str_dbg(smb_dname)));
4191 fd_close(fsp);
4192 file_free(req, fsp);
4193 return NT_STATUS_SHARING_VIOLATION;
4196 if (has_delete_on_close(lck, fsp->name_hash)) {
4197 TALLOC_FREE(lck);
4198 fd_close(fsp);
4199 file_free(req, fsp);
4200 return NT_STATUS_DELETE_PENDING;
4203 status = open_mode_check(conn, lck,
4204 access_mask, share_access);
4206 if (!NT_STATUS_IS_OK(status)) {
4207 TALLOC_FREE(lck);
4208 fd_close(fsp);
4209 file_free(req, fsp);
4210 return status;
4213 ok = set_share_mode(lck, fsp, get_current_uid(conn),
4214 req ? req->mid : 0, NO_OPLOCK,
4215 UINT32_MAX);
4216 if (!ok) {
4217 TALLOC_FREE(lck);
4218 fd_close(fsp);
4219 file_free(req, fsp);
4220 return NT_STATUS_NO_MEMORY;
4223 /* For directories the delete on close bit at open time seems
4224 always to be honored on close... See test 19 in Samba4 BASE-DELETE. */
4225 if (create_options & FILE_DELETE_ON_CLOSE) {
4226 status = can_set_delete_on_close(fsp, 0);
4227 if (!NT_STATUS_IS_OK(status) && !NT_STATUS_EQUAL(status, NT_STATUS_DIRECTORY_NOT_EMPTY)) {
4228 del_share_mode(lck, fsp);
4229 TALLOC_FREE(lck);
4230 fd_close(fsp);
4231 file_free(req, fsp);
4232 return status;
4235 if (NT_STATUS_IS_OK(status)) {
4236 /* Note that here we set the *inital* delete on close flag,
4237 not the regular one. The magic gets handled in close. */
4238 fsp->initial_delete_on_close = True;
4244 * Deal with other opens having a modified write time. Is this
4245 * possible for directories?
4247 struct timespec write_time = get_share_mode_write_time(lck);
4249 if (!null_timespec(write_time)) {
4250 update_stat_ex_mtime(&fsp->fsp_name->st, write_time);
4254 TALLOC_FREE(lck);
4256 if (pinfo) {
4257 *pinfo = info;
4260 *result = fsp;
4261 return NT_STATUS_OK;
4264 NTSTATUS create_directory(connection_struct *conn, struct smb_request *req,
4265 struct smb_filename *smb_dname)
4267 NTSTATUS status;
4268 files_struct *fsp;
4270 status = SMB_VFS_CREATE_FILE(
4271 conn, /* conn */
4272 req, /* req */
4273 0, /* root_dir_fid */
4274 smb_dname, /* fname */
4275 FILE_READ_ATTRIBUTES, /* access_mask */
4276 FILE_SHARE_NONE, /* share_access */
4277 FILE_CREATE, /* create_disposition*/
4278 FILE_DIRECTORY_FILE, /* create_options */
4279 FILE_ATTRIBUTE_DIRECTORY, /* file_attributes */
4280 0, /* oplock_request */
4281 NULL, /* lease */
4282 0, /* allocation_size */
4283 0, /* private_flags */
4284 NULL, /* sd */
4285 NULL, /* ea_list */
4286 &fsp, /* result */
4287 NULL, /* pinfo */
4288 NULL, NULL); /* create context */
4290 if (NT_STATUS_IS_OK(status)) {
4291 close_file(req, fsp, NORMAL_CLOSE);
4294 return status;
4297 /****************************************************************************
4298 Receive notification that one of our open files has been renamed by another
4299 smbd process.
4300 ****************************************************************************/
4302 void msg_file_was_renamed(struct messaging_context *msg,
4303 void *private_data,
4304 uint32_t msg_type,
4305 struct server_id server_id,
4306 DATA_BLOB *data)
4308 files_struct *fsp;
4309 char *frm = (char *)data->data;
4310 struct file_id id;
4311 const char *sharepath;
4312 const char *base_name;
4313 const char *stream_name;
4314 struct smb_filename *smb_fname = NULL;
4315 size_t sp_len, bn_len;
4316 NTSTATUS status;
4317 struct smbd_server_connection *sconn =
4318 talloc_get_type_abort(private_data,
4319 struct smbd_server_connection);
4321 if (data->data == NULL
4322 || data->length < MSG_FILE_RENAMED_MIN_SIZE + 2) {
4323 DEBUG(0, ("msg_file_was_renamed: Got invalid msg len %d\n",
4324 (int)data->length));
4325 return;
4328 /* Unpack the message. */
4329 pull_file_id_24(frm, &id);
4330 sharepath = &frm[24];
4331 sp_len = strlen(sharepath);
4332 base_name = sharepath + sp_len + 1;
4333 bn_len = strlen(base_name);
4334 stream_name = sharepath + sp_len + 1 + bn_len + 1;
4336 /* stream_name must always be NULL if there is no stream. */
4337 if (stream_name[0] == '\0') {
4338 stream_name = NULL;
4341 smb_fname = synthetic_smb_fname(talloc_tos(),
4342 base_name,
4343 stream_name,
4344 NULL,
4346 if (smb_fname == NULL) {
4347 return;
4350 DEBUG(10,("msg_file_was_renamed: Got rename message for sharepath %s, new name %s, "
4351 "file_id %s\n",
4352 sharepath, smb_fname_str_dbg(smb_fname),
4353 file_id_string_tos(&id)));
4355 for(fsp = file_find_di_first(sconn, id); fsp;
4356 fsp = file_find_di_next(fsp)) {
4357 if (memcmp(fsp->conn->connectpath, sharepath, sp_len) == 0) {
4359 DEBUG(10,("msg_file_was_renamed: renaming file %s from %s -> %s\n",
4360 fsp_fnum_dbg(fsp), fsp_str_dbg(fsp),
4361 smb_fname_str_dbg(smb_fname)));
4362 status = fsp_set_smb_fname(fsp, smb_fname);
4363 if (!NT_STATUS_IS_OK(status)) {
4364 goto out;
4366 } else {
4367 /* TODO. JRA. */
4368 /* Now we have the complete path we can work out if this is
4369 actually within this share and adjust newname accordingly. */
4370 DEBUG(10,("msg_file_was_renamed: share mismatch (sharepath %s "
4371 "not sharepath %s) "
4372 "%s from %s -> %s\n",
4373 fsp->conn->connectpath,
4374 sharepath,
4375 fsp_fnum_dbg(fsp),
4376 fsp_str_dbg(fsp),
4377 smb_fname_str_dbg(smb_fname)));
4380 out:
4381 TALLOC_FREE(smb_fname);
4382 return;
4386 * If a main file is opened for delete, all streams need to be checked for
4387 * !FILE_SHARE_DELETE. Do this by opening with DELETE_ACCESS.
4388 * If that works, delete them all by setting the delete on close and close.
4391 static NTSTATUS open_streams_for_delete(connection_struct *conn,
4392 const struct smb_filename *smb_fname)
4394 struct stream_struct *stream_info = NULL;
4395 files_struct **streams = NULL;
4396 int i;
4397 unsigned int num_streams = 0;
4398 TALLOC_CTX *frame = talloc_stackframe();
4399 NTSTATUS status;
4401 status = vfs_streaminfo(conn, NULL, smb_fname, talloc_tos(),
4402 &num_streams, &stream_info);
4404 if (NT_STATUS_EQUAL(status, NT_STATUS_NOT_IMPLEMENTED)
4405 || NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
4406 DEBUG(10, ("no streams around\n"));
4407 TALLOC_FREE(frame);
4408 return NT_STATUS_OK;
4411 if (!NT_STATUS_IS_OK(status)) {
4412 DEBUG(10, ("vfs_streaminfo failed: %s\n",
4413 nt_errstr(status)));
4414 goto fail;
4417 DEBUG(10, ("open_streams_for_delete found %d streams\n",
4418 num_streams));
4420 if (num_streams == 0) {
4421 TALLOC_FREE(frame);
4422 return NT_STATUS_OK;
4425 streams = talloc_array(talloc_tos(), files_struct *, num_streams);
4426 if (streams == NULL) {
4427 DEBUG(0, ("talloc failed\n"));
4428 status = NT_STATUS_NO_MEMORY;
4429 goto fail;
4432 for (i=0; i<num_streams; i++) {
4433 struct smb_filename *smb_fname_cp;
4435 if (strequal(stream_info[i].name, "::$DATA")) {
4436 streams[i] = NULL;
4437 continue;
4440 smb_fname_cp = synthetic_smb_fname(talloc_tos(),
4441 smb_fname->base_name,
4442 stream_info[i].name,
4443 NULL,
4444 (smb_fname->flags &
4445 ~SMB_FILENAME_POSIX_PATH));
4446 if (smb_fname_cp == NULL) {
4447 status = NT_STATUS_NO_MEMORY;
4448 goto fail;
4451 if (SMB_VFS_STAT(conn, smb_fname_cp) == -1) {
4452 DEBUG(10, ("Unable to stat stream: %s\n",
4453 smb_fname_str_dbg(smb_fname_cp)));
4456 status = SMB_VFS_CREATE_FILE(
4457 conn, /* conn */
4458 NULL, /* req */
4459 0, /* root_dir_fid */
4460 smb_fname_cp, /* fname */
4461 DELETE_ACCESS, /* access_mask */
4462 (FILE_SHARE_READ | /* share_access */
4463 FILE_SHARE_WRITE | FILE_SHARE_DELETE),
4464 FILE_OPEN, /* create_disposition*/
4465 0, /* create_options */
4466 FILE_ATTRIBUTE_NORMAL, /* file_attributes */
4467 0, /* oplock_request */
4468 NULL, /* lease */
4469 0, /* allocation_size */
4470 NTCREATEX_OPTIONS_PRIVATE_STREAM_DELETE, /* private_flags */
4471 NULL, /* sd */
4472 NULL, /* ea_list */
4473 &streams[i], /* result */
4474 NULL, /* pinfo */
4475 NULL, NULL); /* create context */
4477 if (!NT_STATUS_IS_OK(status)) {
4478 DEBUG(10, ("Could not open stream %s: %s\n",
4479 smb_fname_str_dbg(smb_fname_cp),
4480 nt_errstr(status)));
4482 TALLOC_FREE(smb_fname_cp);
4483 break;
4485 TALLOC_FREE(smb_fname_cp);
4489 * don't touch the variable "status" beyond this point :-)
4492 for (i -= 1 ; i >= 0; i--) {
4493 if (streams[i] == NULL) {
4494 continue;
4497 DEBUG(10, ("Closing stream # %d, %s\n", i,
4498 fsp_str_dbg(streams[i])));
4499 close_file(NULL, streams[i], NORMAL_CLOSE);
4502 fail:
4503 TALLOC_FREE(frame);
4504 return status;
4507 /*********************************************************************
4508 Create a default ACL by inheriting from the parent. If no inheritance
4509 from the parent available, don't set anything. This will leave the actual
4510 permissions the new file or directory already got from the filesystem
4511 as the NT ACL when read.
4512 *********************************************************************/
4514 static NTSTATUS inherit_new_acl(files_struct *fsp)
4516 TALLOC_CTX *frame = talloc_stackframe();
4517 char *parent_name = NULL;
4518 struct security_descriptor *parent_desc = NULL;
4519 NTSTATUS status = NT_STATUS_OK;
4520 struct security_descriptor *psd = NULL;
4521 const struct dom_sid *owner_sid = NULL;
4522 const struct dom_sid *group_sid = NULL;
4523 uint32_t security_info_sent = (SECINFO_OWNER | SECINFO_GROUP | SECINFO_DACL);
4524 struct security_token *token = fsp->conn->session_info->security_token;
4525 bool inherit_owner =
4526 (lp_inherit_owner(SNUM(fsp->conn)) == INHERIT_OWNER_WINDOWS_AND_UNIX);
4527 bool inheritable_components = false;
4528 bool try_builtin_administrators = false;
4529 const struct dom_sid *BA_U_sid = NULL;
4530 const struct dom_sid *BA_G_sid = NULL;
4531 bool try_system = false;
4532 const struct dom_sid *SY_U_sid = NULL;
4533 const struct dom_sid *SY_G_sid = NULL;
4534 size_t size = 0;
4535 struct smb_filename *parent_smb_fname = NULL;
4537 if (!parent_dirname(frame, fsp->fsp_name->base_name, &parent_name, NULL)) {
4538 TALLOC_FREE(frame);
4539 return NT_STATUS_NO_MEMORY;
4541 parent_smb_fname = synthetic_smb_fname(talloc_tos(),
4542 parent_name,
4543 NULL,
4544 NULL,
4545 fsp->fsp_name->flags);
4547 if (parent_smb_fname == NULL) {
4548 TALLOC_FREE(frame);
4549 return NT_STATUS_NO_MEMORY;
4552 status = SMB_VFS_GET_NT_ACL(fsp->conn,
4553 parent_smb_fname,
4554 (SECINFO_OWNER | SECINFO_GROUP | SECINFO_DACL),
4555 frame,
4556 &parent_desc);
4557 if (!NT_STATUS_IS_OK(status)) {
4558 TALLOC_FREE(frame);
4559 return status;
4562 inheritable_components = sd_has_inheritable_components(parent_desc,
4563 fsp->is_directory);
4565 if (!inheritable_components && !inherit_owner) {
4566 TALLOC_FREE(frame);
4567 /* Nothing to inherit and not setting owner. */
4568 return NT_STATUS_OK;
4571 /* Create an inherited descriptor from the parent. */
4573 if (DEBUGLEVEL >= 10) {
4574 DEBUG(10,("inherit_new_acl: parent acl for %s is:\n",
4575 fsp_str_dbg(fsp) ));
4576 NDR_PRINT_DEBUG(security_descriptor, parent_desc);
4579 /* Inherit from parent descriptor if "inherit owner" set. */
4580 if (inherit_owner) {
4581 owner_sid = parent_desc->owner_sid;
4582 group_sid = parent_desc->group_sid;
4585 if (owner_sid == NULL) {
4586 if (security_token_has_builtin_administrators(token)) {
4587 try_builtin_administrators = true;
4588 } else if (security_token_is_system(token)) {
4589 try_builtin_administrators = true;
4590 try_system = true;
4594 if (group_sid == NULL &&
4595 token->num_sids == PRIMARY_GROUP_SID_INDEX)
4597 if (security_token_is_system(token)) {
4598 try_builtin_administrators = true;
4599 try_system = true;
4603 if (try_builtin_administrators) {
4604 struct unixid ids;
4605 bool ok;
4607 ZERO_STRUCT(ids);
4608 ok = sids_to_unixids(&global_sid_Builtin_Administrators, 1, &ids);
4609 if (ok) {
4610 switch (ids.type) {
4611 case ID_TYPE_BOTH:
4612 BA_U_sid = &global_sid_Builtin_Administrators;
4613 BA_G_sid = &global_sid_Builtin_Administrators;
4614 break;
4615 case ID_TYPE_UID:
4616 BA_U_sid = &global_sid_Builtin_Administrators;
4617 break;
4618 case ID_TYPE_GID:
4619 BA_G_sid = &global_sid_Builtin_Administrators;
4620 break;
4621 default:
4622 break;
4627 if (try_system) {
4628 struct unixid ids;
4629 bool ok;
4631 ZERO_STRUCT(ids);
4632 ok = sids_to_unixids(&global_sid_System, 1, &ids);
4633 if (ok) {
4634 switch (ids.type) {
4635 case ID_TYPE_BOTH:
4636 SY_U_sid = &global_sid_System;
4637 SY_G_sid = &global_sid_System;
4638 break;
4639 case ID_TYPE_UID:
4640 SY_U_sid = &global_sid_System;
4641 break;
4642 case ID_TYPE_GID:
4643 SY_G_sid = &global_sid_System;
4644 break;
4645 default:
4646 break;
4651 if (owner_sid == NULL) {
4652 owner_sid = BA_U_sid;
4655 if (owner_sid == NULL) {
4656 owner_sid = SY_U_sid;
4659 if (group_sid == NULL) {
4660 group_sid = SY_G_sid;
4663 if (try_system && group_sid == NULL) {
4664 group_sid = BA_G_sid;
4667 if (owner_sid == NULL) {
4668 owner_sid = &token->sids[PRIMARY_USER_SID_INDEX];
4670 if (group_sid == NULL) {
4671 if (token->num_sids == PRIMARY_GROUP_SID_INDEX) {
4672 group_sid = &token->sids[PRIMARY_USER_SID_INDEX];
4673 } else {
4674 group_sid = &token->sids[PRIMARY_GROUP_SID_INDEX];
4678 status = se_create_child_secdesc(frame,
4679 &psd,
4680 &size,
4681 parent_desc,
4682 owner_sid,
4683 group_sid,
4684 fsp->is_directory);
4685 if (!NT_STATUS_IS_OK(status)) {
4686 TALLOC_FREE(frame);
4687 return status;
4690 /* If inheritable_components == false,
4691 se_create_child_secdesc()
4692 creates a security desriptor with a NULL dacl
4693 entry, but with SEC_DESC_DACL_PRESENT. We need
4694 to remove that flag. */
4696 if (!inheritable_components) {
4697 security_info_sent &= ~SECINFO_DACL;
4698 psd->type &= ~SEC_DESC_DACL_PRESENT;
4701 if (DEBUGLEVEL >= 10) {
4702 DEBUG(10,("inherit_new_acl: child acl for %s is:\n",
4703 fsp_str_dbg(fsp) ));
4704 NDR_PRINT_DEBUG(security_descriptor, psd);
4707 if (inherit_owner) {
4708 /* We need to be root to force this. */
4709 become_root();
4711 status = SMB_VFS_FSET_NT_ACL(fsp,
4712 security_info_sent,
4713 psd);
4714 if (inherit_owner) {
4715 unbecome_root();
4717 TALLOC_FREE(frame);
4718 return status;
4722 * If we already have a lease, it must match the new file id. [MS-SMB2]
4723 * 3.3.5.9.8 speaks about INVALID_PARAMETER if an already used lease key is
4724 * used for a different file name.
4727 struct lease_match_state {
4728 /* Input parameters. */
4729 TALLOC_CTX *mem_ctx;
4730 const char *servicepath;
4731 const struct smb_filename *fname;
4732 bool file_existed;
4733 struct file_id id;
4734 /* Return parameters. */
4735 uint32_t num_file_ids;
4736 struct file_id *ids;
4737 NTSTATUS match_status;
4740 /*************************************************************
4741 File doesn't exist but this lease key+guid is already in use.
4743 This is only allowable in the dynamic share case where the
4744 service path must be different.
4746 There is a small race condition here in the multi-connection
4747 case where a client sends two create calls on different connections,
4748 where the file doesn't exist and one smbd creates the leases_db
4749 entry first, but this will get fixed by the multichannel cleanup
4750 when all identical client_guids get handled by a single smbd.
4751 **************************************************************/
4753 static void lease_match_parser_new_file(
4754 uint32_t num_files,
4755 const struct leases_db_file *files,
4756 struct lease_match_state *state)
4758 uint32_t i;
4760 for (i = 0; i < num_files; i++) {
4761 const struct leases_db_file *f = &files[i];
4762 if (strequal(state->servicepath, f->servicepath)) {
4763 state->match_status = NT_STATUS_INVALID_PARAMETER;
4764 return;
4768 /* Dynamic share case. Break leases on all other files. */
4769 state->match_status = leases_db_copy_file_ids(state->mem_ctx,
4770 num_files,
4771 files,
4772 &state->ids);
4773 if (!NT_STATUS_IS_OK(state->match_status)) {
4774 return;
4777 state->num_file_ids = num_files;
4778 state->match_status = NT_STATUS_OPLOCK_NOT_GRANTED;
4779 return;
4782 static void lease_match_parser(
4783 uint32_t num_files,
4784 const struct leases_db_file *files,
4785 void *private_data)
4787 struct lease_match_state *state =
4788 (struct lease_match_state *)private_data;
4789 uint32_t i;
4791 if (!state->file_existed) {
4793 * Deal with name mismatch or
4794 * possible dynamic share case separately
4795 * to make code clearer.
4797 lease_match_parser_new_file(num_files,
4798 files,
4799 state);
4800 return;
4803 /* File existed. */
4804 state->match_status = NT_STATUS_OK;
4806 for (i = 0; i < num_files; i++) {
4807 const struct leases_db_file *f = &files[i];
4809 /* Everything should be the same. */
4810 if (!file_id_equal(&state->id, &f->id)) {
4811 /* This should catch all dynamic share cases. */
4812 state->match_status = NT_STATUS_OPLOCK_NOT_GRANTED;
4813 break;
4815 if (!strequal(f->servicepath, state->servicepath)) {
4816 state->match_status = NT_STATUS_INVALID_PARAMETER;
4817 break;
4819 if (!strequal(f->base_name, state->fname->base_name)) {
4820 state->match_status = NT_STATUS_INVALID_PARAMETER;
4821 break;
4823 if (!strequal(f->stream_name, state->fname->stream_name)) {
4824 state->match_status = NT_STATUS_INVALID_PARAMETER;
4825 break;
4829 if (NT_STATUS_IS_OK(state->match_status)) {
4831 * Common case - just opening another handle on a
4832 * file on a non-dynamic share.
4834 return;
4837 if (NT_STATUS_EQUAL(state->match_status, NT_STATUS_INVALID_PARAMETER)) {
4838 /* Mismatched path. Error back to client. */
4839 return;
4843 * File id mismatch. Dynamic share case NT_STATUS_OPLOCK_NOT_GRANTED.
4844 * Don't allow leases.
4847 state->match_status = leases_db_copy_file_ids(state->mem_ctx,
4848 num_files,
4849 files,
4850 &state->ids);
4851 if (!NT_STATUS_IS_OK(state->match_status)) {
4852 return;
4855 state->num_file_ids = num_files;
4856 state->match_status = NT_STATUS_OPLOCK_NOT_GRANTED;
4857 return;
4860 static NTSTATUS lease_match(connection_struct *conn,
4861 struct smb_request *req,
4862 struct smb2_lease_key *lease_key,
4863 const char *servicepath,
4864 const struct smb_filename *fname,
4865 uint16_t *p_version,
4866 uint16_t *p_epoch)
4868 struct smbd_server_connection *sconn = req->sconn;
4869 TALLOC_CTX *tos = talloc_tos();
4870 struct lease_match_state state = {
4871 .mem_ctx = tos,
4872 .servicepath = servicepath,
4873 .fname = fname,
4874 .match_status = NT_STATUS_OK
4876 uint32_t i;
4877 NTSTATUS status;
4879 state.file_existed = VALID_STAT(fname->st);
4880 if (state.file_existed) {
4881 state.id = vfs_file_id_from_sbuf(conn, &fname->st);
4882 } else {
4883 memset(&state.id, '\0', sizeof(state.id));
4886 status = leases_db_parse(&sconn->client->connections->smb2.client.guid,
4887 lease_key, lease_match_parser, &state);
4888 if (!NT_STATUS_IS_OK(status)) {
4890 * Not found or error means okay: We can make the lease pass
4892 return NT_STATUS_OK;
4894 if (!NT_STATUS_EQUAL(state.match_status, NT_STATUS_OPLOCK_NOT_GRANTED)) {
4896 * Anything but NT_STATUS_OPLOCK_NOT_GRANTED, let the caller
4897 * deal with it.
4899 return state.match_status;
4902 /* We have to break all existing leases. */
4903 for (i = 0; i < state.num_file_ids; i++) {
4904 struct share_mode_lock *lck;
4905 struct share_mode_data *d;
4906 uint32_t j;
4908 if (file_id_equal(&state.ids[i], &state.id)) {
4909 /* Don't need to break our own file. */
4910 continue;
4913 lck = get_existing_share_mode_lock(talloc_tos(), state.ids[i]);
4914 if (lck == NULL) {
4915 /* Race condition - file already closed. */
4916 continue;
4918 d = lck->data;
4919 for (j=0; j<d->num_share_modes; j++) {
4920 struct share_mode_entry *e = &d->share_modes[j];
4921 uint32_t e_lease_type = get_lease_type(d, e);
4922 struct share_mode_lease *l = NULL;
4924 if (share_mode_stale_pid(d, j)) {
4925 continue;
4928 if (e->op_type == LEASE_OPLOCK) {
4929 l = &lck->data->leases[e->lease_idx];
4930 if (!smb2_lease_key_equal(&l->lease_key,
4931 lease_key)) {
4932 continue;
4934 *p_epoch = l->epoch;
4935 *p_version = l->lease_version;
4938 if (e_lease_type == SMB2_LEASE_NONE) {
4939 continue;
4942 send_break_message(conn->sconn->msg_ctx, e,
4943 SMB2_LEASE_NONE);
4946 * Windows 7 and 8 lease clients
4947 * are broken in that they will not
4948 * respond to lease break requests
4949 * whilst waiting for an outstanding
4950 * open request on that lease handle
4951 * on the same TCP connection, due
4952 * to holding an internal inode lock.
4954 * This means we can't reschedule
4955 * ourselves here, but must return
4956 * from the create.
4958 * Work around:
4960 * Send the breaks and then return
4961 * SMB2_LEASE_NONE in the lease handle
4962 * to cause them to acknowledge the
4963 * lease break. Consulatation with
4964 * Microsoft engineering confirmed
4965 * this approach is safe.
4969 TALLOC_FREE(lck);
4972 * Ensure we don't grant anything more so we
4973 * never upgrade.
4975 return NT_STATUS_OPLOCK_NOT_GRANTED;
4979 * Wrapper around open_file_ntcreate and open_directory
4982 static NTSTATUS create_file_unixpath(connection_struct *conn,
4983 struct smb_request *req,
4984 struct smb_filename *smb_fname,
4985 uint32_t access_mask,
4986 uint32_t share_access,
4987 uint32_t create_disposition,
4988 uint32_t create_options,
4989 uint32_t file_attributes,
4990 uint32_t oplock_request,
4991 struct smb2_lease *lease,
4992 uint64_t allocation_size,
4993 uint32_t private_flags,
4994 struct security_descriptor *sd,
4995 struct ea_list *ea_list,
4997 files_struct **result,
4998 int *pinfo)
5000 int info = FILE_WAS_OPENED;
5001 files_struct *base_fsp = NULL;
5002 files_struct *fsp = NULL;
5003 NTSTATUS status;
5005 DEBUG(10,("create_file_unixpath: access_mask = 0x%x "
5006 "file_attributes = 0x%x, share_access = 0x%x, "
5007 "create_disposition = 0x%x create_options = 0x%x "
5008 "oplock_request = 0x%x private_flags = 0x%x "
5009 "ea_list = 0x%p, sd = 0x%p, "
5010 "fname = %s\n",
5011 (unsigned int)access_mask,
5012 (unsigned int)file_attributes,
5013 (unsigned int)share_access,
5014 (unsigned int)create_disposition,
5015 (unsigned int)create_options,
5016 (unsigned int)oplock_request,
5017 (unsigned int)private_flags,
5018 ea_list, sd, smb_fname_str_dbg(smb_fname)));
5020 if (create_options & FILE_OPEN_BY_FILE_ID) {
5021 status = NT_STATUS_NOT_SUPPORTED;
5022 goto fail;
5025 if (create_options & NTCREATEX_OPTIONS_INVALID_PARAM_MASK) {
5026 status = NT_STATUS_INVALID_PARAMETER;
5027 goto fail;
5030 if (req == NULL) {
5031 oplock_request |= INTERNAL_OPEN_ONLY;
5034 if (lease != NULL) {
5035 uint16_t epoch = lease->lease_epoch;
5036 uint16_t version = lease->lease_version;
5037 status = lease_match(conn,
5038 req,
5039 &lease->lease_key,
5040 conn->connectpath,
5041 smb_fname,
5042 &version,
5043 &epoch);
5044 if (NT_STATUS_EQUAL(status, NT_STATUS_OPLOCK_NOT_GRANTED)) {
5045 /* Dynamic share file. No leases and update epoch... */
5046 lease->lease_state = SMB2_LEASE_NONE;
5047 lease->lease_epoch = epoch;
5048 lease->lease_version = version;
5049 } else if (!NT_STATUS_IS_OK(status)) {
5050 goto fail;
5054 if ((conn->fs_capabilities & FILE_NAMED_STREAMS)
5055 && (access_mask & DELETE_ACCESS)
5056 && !is_ntfs_stream_smb_fname(smb_fname)) {
5058 * We can't open a file with DELETE access if any of the
5059 * streams is open without FILE_SHARE_DELETE
5061 status = open_streams_for_delete(conn, smb_fname);
5063 if (!NT_STATUS_IS_OK(status)) {
5064 goto fail;
5068 if ((access_mask & SEC_FLAG_SYSTEM_SECURITY) &&
5069 !security_token_has_privilege(get_current_nttok(conn),
5070 SEC_PRIV_SECURITY)) {
5071 DEBUG(10, ("create_file_unixpath: open on %s "
5072 "failed - SEC_FLAG_SYSTEM_SECURITY denied.\n",
5073 smb_fname_str_dbg(smb_fname)));
5074 status = NT_STATUS_PRIVILEGE_NOT_HELD;
5075 goto fail;
5078 if ((conn->fs_capabilities & FILE_NAMED_STREAMS)
5079 && is_ntfs_stream_smb_fname(smb_fname)
5080 && (!(private_flags & NTCREATEX_OPTIONS_PRIVATE_STREAM_DELETE))) {
5081 uint32_t base_create_disposition;
5082 struct smb_filename *smb_fname_base = NULL;
5084 if (create_options & FILE_DIRECTORY_FILE) {
5085 status = NT_STATUS_NOT_A_DIRECTORY;
5086 goto fail;
5089 switch (create_disposition) {
5090 case FILE_OPEN:
5091 base_create_disposition = FILE_OPEN;
5092 break;
5093 default:
5094 base_create_disposition = FILE_OPEN_IF;
5095 break;
5098 /* Create an smb_filename with stream_name == NULL. */
5099 smb_fname_base = synthetic_smb_fname(talloc_tos(),
5100 smb_fname->base_name,
5101 NULL,
5102 NULL,
5103 smb_fname->flags);
5104 if (smb_fname_base == NULL) {
5105 status = NT_STATUS_NO_MEMORY;
5106 goto fail;
5109 if (SMB_VFS_STAT(conn, smb_fname_base) == -1) {
5110 DEBUG(10, ("Unable to stat stream: %s\n",
5111 smb_fname_str_dbg(smb_fname_base)));
5112 } else {
5114 * https://bugzilla.samba.org/show_bug.cgi?id=10229
5115 * We need to check if the requested access mask
5116 * could be used to open the underlying file (if
5117 * it existed), as we're passing in zero for the
5118 * access mask to the base filename.
5120 status = check_base_file_access(conn,
5121 smb_fname_base,
5122 access_mask);
5124 if (!NT_STATUS_IS_OK(status)) {
5125 DEBUG(10, ("Permission check "
5126 "for base %s failed: "
5127 "%s\n", smb_fname->base_name,
5128 nt_errstr(status)));
5129 goto fail;
5133 /* Open the base file. */
5134 status = create_file_unixpath(conn, NULL, smb_fname_base, 0,
5135 FILE_SHARE_READ
5136 | FILE_SHARE_WRITE
5137 | FILE_SHARE_DELETE,
5138 base_create_disposition,
5139 0, 0, 0, NULL, 0, 0, NULL, NULL,
5140 &base_fsp, NULL);
5141 TALLOC_FREE(smb_fname_base);
5143 if (!NT_STATUS_IS_OK(status)) {
5144 DEBUG(10, ("create_file_unixpath for base %s failed: "
5145 "%s\n", smb_fname->base_name,
5146 nt_errstr(status)));
5147 goto fail;
5149 /* we don't need the low level fd */
5150 fd_close(base_fsp);
5154 * If it's a request for a directory open, deal with it separately.
5157 if (create_options & FILE_DIRECTORY_FILE) {
5159 if (create_options & FILE_NON_DIRECTORY_FILE) {
5160 status = NT_STATUS_INVALID_PARAMETER;
5161 goto fail;
5164 /* Can't open a temp directory. IFS kit test. */
5165 if (!(file_attributes & FILE_FLAG_POSIX_SEMANTICS) &&
5166 (file_attributes & FILE_ATTRIBUTE_TEMPORARY)) {
5167 status = NT_STATUS_INVALID_PARAMETER;
5168 goto fail;
5172 * We will get a create directory here if the Win32
5173 * app specified a security descriptor in the
5174 * CreateDirectory() call.
5177 oplock_request = 0;
5178 status = open_directory(
5179 conn, req, smb_fname, access_mask, share_access,
5180 create_disposition, create_options, file_attributes,
5181 &info, &fsp);
5182 } else {
5185 * Ordinary file case.
5188 status = file_new(req, conn, &fsp);
5189 if(!NT_STATUS_IS_OK(status)) {
5190 goto fail;
5193 status = fsp_set_smb_fname(fsp, smb_fname);
5194 if (!NT_STATUS_IS_OK(status)) {
5195 goto fail;
5198 if (base_fsp) {
5200 * We're opening the stream element of a
5201 * base_fsp we already opened. Set up the
5202 * base_fsp pointer.
5204 fsp->base_fsp = base_fsp;
5207 if (allocation_size) {
5208 fsp->initial_allocation_size = smb_roundup(fsp->conn,
5209 allocation_size);
5212 status = open_file_ntcreate(conn,
5213 req,
5214 access_mask,
5215 share_access,
5216 create_disposition,
5217 create_options,
5218 file_attributes,
5219 oplock_request,
5220 lease,
5221 private_flags,
5222 &info,
5223 fsp);
5225 if(!NT_STATUS_IS_OK(status)) {
5226 file_free(req, fsp);
5227 fsp = NULL;
5230 if (NT_STATUS_EQUAL(status, NT_STATUS_FILE_IS_A_DIRECTORY)) {
5232 /* A stream open never opens a directory */
5234 if (base_fsp) {
5235 status = NT_STATUS_FILE_IS_A_DIRECTORY;
5236 goto fail;
5240 * Fail the open if it was explicitly a non-directory
5241 * file.
5244 if (create_options & FILE_NON_DIRECTORY_FILE) {
5245 status = NT_STATUS_FILE_IS_A_DIRECTORY;
5246 goto fail;
5249 oplock_request = 0;
5250 status = open_directory(
5251 conn, req, smb_fname, access_mask,
5252 share_access, create_disposition,
5253 create_options, file_attributes,
5254 &info, &fsp);
5258 if (!NT_STATUS_IS_OK(status)) {
5259 goto fail;
5262 fsp->base_fsp = base_fsp;
5264 if ((ea_list != NULL) &&
5265 ((info == FILE_WAS_CREATED) || (info == FILE_WAS_OVERWRITTEN))) {
5266 status = set_ea(conn, fsp, fsp->fsp_name, ea_list);
5267 if (!NT_STATUS_IS_OK(status)) {
5268 goto fail;
5272 if (!fsp->is_directory && S_ISDIR(fsp->fsp_name->st.st_ex_mode)) {
5273 status = NT_STATUS_ACCESS_DENIED;
5274 goto fail;
5277 /* Save the requested allocation size. */
5278 if ((info == FILE_WAS_CREATED) || (info == FILE_WAS_OVERWRITTEN)) {
5279 if ((allocation_size > fsp->fsp_name->st.st_ex_size)
5280 && !(fsp->is_directory))
5282 fsp->initial_allocation_size = smb_roundup(
5283 fsp->conn, allocation_size);
5284 if (vfs_allocate_file_space(
5285 fsp, fsp->initial_allocation_size) == -1) {
5286 status = NT_STATUS_DISK_FULL;
5287 goto fail;
5289 } else {
5290 fsp->initial_allocation_size = smb_roundup(
5291 fsp->conn, (uint64_t)fsp->fsp_name->st.st_ex_size);
5293 } else {
5294 fsp->initial_allocation_size = 0;
5297 if ((info == FILE_WAS_CREATED) && lp_nt_acl_support(SNUM(conn)) &&
5298 fsp->base_fsp == NULL) {
5299 if (sd != NULL) {
5301 * According to the MS documentation, the only time the security
5302 * descriptor is applied to the opened file is iff we *created* the
5303 * file; an existing file stays the same.
5305 * Also, it seems (from observation) that you can open the file with
5306 * any access mask but you can still write the sd. We need to override
5307 * the granted access before we call set_sd
5308 * Patch for bug #2242 from Tom Lackemann <cessnatomny@yahoo.com>.
5311 uint32_t sec_info_sent;
5312 uint32_t saved_access_mask = fsp->access_mask;
5314 sec_info_sent = get_sec_info(sd);
5316 fsp->access_mask = FILE_GENERIC_ALL;
5318 if (sec_info_sent & (SECINFO_OWNER|
5319 SECINFO_GROUP|
5320 SECINFO_DACL|
5321 SECINFO_SACL)) {
5322 status = set_sd(fsp, sd, sec_info_sent);
5325 fsp->access_mask = saved_access_mask;
5327 if (!NT_STATUS_IS_OK(status)) {
5328 goto fail;
5330 } else if (lp_inherit_acls(SNUM(conn))) {
5331 /* Inherit from parent. Errors here are not fatal. */
5332 status = inherit_new_acl(fsp);
5333 if (!NT_STATUS_IS_OK(status)) {
5334 DEBUG(10,("inherit_new_acl: failed for %s with %s\n",
5335 fsp_str_dbg(fsp),
5336 nt_errstr(status) ));
5341 if ((conn->fs_capabilities & FILE_FILE_COMPRESSION)
5342 && (create_options & FILE_NO_COMPRESSION)
5343 && (info == FILE_WAS_CREATED)) {
5344 status = SMB_VFS_SET_COMPRESSION(conn, fsp, fsp,
5345 COMPRESSION_FORMAT_NONE);
5346 if (!NT_STATUS_IS_OK(status)) {
5347 DEBUG(1, ("failed to disable compression: %s\n",
5348 nt_errstr(status)));
5352 DEBUG(10, ("create_file_unixpath: info=%d\n", info));
5354 *result = fsp;
5355 if (pinfo != NULL) {
5356 *pinfo = info;
5359 smb_fname->st = fsp->fsp_name->st;
5361 return NT_STATUS_OK;
5363 fail:
5364 DEBUG(10, ("create_file_unixpath: %s\n", nt_errstr(status)));
5366 if (fsp != NULL) {
5367 if (base_fsp && fsp->base_fsp == base_fsp) {
5369 * The close_file below will close
5370 * fsp->base_fsp.
5372 base_fsp = NULL;
5374 close_file(req, fsp, ERROR_CLOSE);
5375 fsp = NULL;
5377 if (base_fsp != NULL) {
5378 close_file(req, base_fsp, ERROR_CLOSE);
5379 base_fsp = NULL;
5381 return status;
5385 * Calculate the full path name given a relative fid.
5387 NTSTATUS get_relative_fid_filename(connection_struct *conn,
5388 struct smb_request *req,
5389 uint16_t root_dir_fid,
5390 const struct smb_filename *smb_fname,
5391 struct smb_filename **smb_fname_out)
5393 files_struct *dir_fsp;
5394 char *parent_fname = NULL;
5395 char *new_base_name = NULL;
5396 uint32_t ucf_flags = ucf_flags_from_smb_request(req);
5397 NTSTATUS status;
5399 if (root_dir_fid == 0 || !smb_fname) {
5400 status = NT_STATUS_INTERNAL_ERROR;
5401 goto out;
5404 dir_fsp = file_fsp(req, root_dir_fid);
5406 if (dir_fsp == NULL) {
5407 status = NT_STATUS_INVALID_HANDLE;
5408 goto out;
5411 if (is_ntfs_stream_smb_fname(dir_fsp->fsp_name)) {
5412 status = NT_STATUS_INVALID_HANDLE;
5413 goto out;
5416 if (!dir_fsp->is_directory) {
5419 * Check to see if this is a mac fork of some kind.
5422 if ((conn->fs_capabilities & FILE_NAMED_STREAMS) &&
5423 is_ntfs_stream_smb_fname(smb_fname)) {
5424 status = NT_STATUS_OBJECT_PATH_NOT_FOUND;
5425 goto out;
5429 we need to handle the case when we get a
5430 relative open relative to a file and the
5431 pathname is blank - this is a reopen!
5432 (hint from demyn plantenberg)
5435 status = NT_STATUS_INVALID_HANDLE;
5436 goto out;
5439 if (ISDOT(dir_fsp->fsp_name->base_name)) {
5441 * We're at the toplevel dir, the final file name
5442 * must not contain ./, as this is filtered out
5443 * normally by srvstr_get_path and unix_convert
5444 * explicitly rejects paths containing ./.
5446 parent_fname = talloc_strdup(talloc_tos(), "");
5447 if (parent_fname == NULL) {
5448 status = NT_STATUS_NO_MEMORY;
5449 goto out;
5451 } else {
5452 size_t dir_name_len = strlen(dir_fsp->fsp_name->base_name);
5455 * Copy in the base directory name.
5458 parent_fname = talloc_array(talloc_tos(), char,
5459 dir_name_len+2);
5460 if (parent_fname == NULL) {
5461 status = NT_STATUS_NO_MEMORY;
5462 goto out;
5464 memcpy(parent_fname, dir_fsp->fsp_name->base_name,
5465 dir_name_len+1);
5468 * Ensure it ends in a '/'.
5469 * We used TALLOC_SIZE +2 to add space for the '/'.
5472 if(dir_name_len
5473 && (parent_fname[dir_name_len-1] != '\\')
5474 && (parent_fname[dir_name_len-1] != '/')) {
5475 parent_fname[dir_name_len] = '/';
5476 parent_fname[dir_name_len+1] = '\0';
5480 new_base_name = talloc_asprintf(talloc_tos(), "%s%s", parent_fname,
5481 smb_fname->base_name);
5482 if (new_base_name == NULL) {
5483 status = NT_STATUS_NO_MEMORY;
5484 goto out;
5487 status = filename_convert(req,
5488 conn,
5489 new_base_name,
5490 ucf_flags,
5491 NULL,
5492 smb_fname_out);
5493 if (!NT_STATUS_IS_OK(status)) {
5494 goto out;
5497 out:
5498 TALLOC_FREE(parent_fname);
5499 TALLOC_FREE(new_base_name);
5500 return status;
5503 NTSTATUS create_file_default(connection_struct *conn,
5504 struct smb_request *req,
5505 uint16_t root_dir_fid,
5506 struct smb_filename *smb_fname,
5507 uint32_t access_mask,
5508 uint32_t share_access,
5509 uint32_t create_disposition,
5510 uint32_t create_options,
5511 uint32_t file_attributes,
5512 uint32_t oplock_request,
5513 struct smb2_lease *lease,
5514 uint64_t allocation_size,
5515 uint32_t private_flags,
5516 struct security_descriptor *sd,
5517 struct ea_list *ea_list,
5518 files_struct **result,
5519 int *pinfo,
5520 const struct smb2_create_blobs *in_context_blobs,
5521 struct smb2_create_blobs *out_context_blobs)
5523 int info = FILE_WAS_OPENED;
5524 files_struct *fsp = NULL;
5525 NTSTATUS status;
5526 bool stream_name = false;
5528 DEBUG(10,("create_file: access_mask = 0x%x "
5529 "file_attributes = 0x%x, share_access = 0x%x, "
5530 "create_disposition = 0x%x create_options = 0x%x "
5531 "oplock_request = 0x%x "
5532 "private_flags = 0x%x "
5533 "root_dir_fid = 0x%x, ea_list = 0x%p, sd = 0x%p, "
5534 "fname = %s\n",
5535 (unsigned int)access_mask,
5536 (unsigned int)file_attributes,
5537 (unsigned int)share_access,
5538 (unsigned int)create_disposition,
5539 (unsigned int)create_options,
5540 (unsigned int)oplock_request,
5541 (unsigned int)private_flags,
5542 (unsigned int)root_dir_fid,
5543 ea_list, sd, smb_fname_str_dbg(smb_fname)));
5546 * Calculate the filename from the root_dir_if if necessary.
5549 if (root_dir_fid != 0) {
5550 struct smb_filename *smb_fname_out = NULL;
5551 status = get_relative_fid_filename(conn, req, root_dir_fid,
5552 smb_fname, &smb_fname_out);
5553 if (!NT_STATUS_IS_OK(status)) {
5554 goto fail;
5556 smb_fname = smb_fname_out;
5560 * Check to see if this is a mac fork of some kind.
5563 stream_name = is_ntfs_stream_smb_fname(smb_fname);
5564 if (stream_name) {
5565 enum FAKE_FILE_TYPE fake_file_type;
5567 fake_file_type = is_fake_file(smb_fname);
5569 if (fake_file_type != FAKE_FILE_TYPE_NONE) {
5572 * Here we go! support for changing the disk quotas
5573 * --metze
5575 * We need to fake up to open this MAGIC QUOTA file
5576 * and return a valid FID.
5578 * w2k close this file directly after openening xp
5579 * also tries a QUERY_FILE_INFO on the file and then
5580 * close it
5582 status = open_fake_file(req, conn, req->vuid,
5583 fake_file_type, smb_fname,
5584 access_mask, &fsp);
5585 if (!NT_STATUS_IS_OK(status)) {
5586 goto fail;
5589 ZERO_STRUCT(smb_fname->st);
5590 goto done;
5593 if (!(conn->fs_capabilities & FILE_NAMED_STREAMS)) {
5594 status = NT_STATUS_OBJECT_NAME_NOT_FOUND;
5595 goto fail;
5599 if (is_ntfs_default_stream_smb_fname(smb_fname)) {
5600 int ret;
5601 smb_fname->stream_name = NULL;
5602 /* We have to handle this error here. */
5603 if (create_options & FILE_DIRECTORY_FILE) {
5604 status = NT_STATUS_NOT_A_DIRECTORY;
5605 goto fail;
5607 if (req != NULL && req->posix_pathnames) {
5608 ret = SMB_VFS_LSTAT(conn, smb_fname);
5609 } else {
5610 ret = SMB_VFS_STAT(conn, smb_fname);
5613 if (ret == 0 && VALID_STAT_OF_DIR(smb_fname->st)) {
5614 status = NT_STATUS_FILE_IS_A_DIRECTORY;
5615 goto fail;
5619 status = create_file_unixpath(
5620 conn, req, smb_fname, access_mask, share_access,
5621 create_disposition, create_options, file_attributes,
5622 oplock_request, lease, allocation_size, private_flags,
5623 sd, ea_list,
5624 &fsp, &info);
5626 if (!NT_STATUS_IS_OK(status)) {
5627 goto fail;
5630 done:
5631 DEBUG(10, ("create_file: info=%d\n", info));
5633 *result = fsp;
5634 if (pinfo != NULL) {
5635 *pinfo = info;
5637 return NT_STATUS_OK;
5639 fail:
5640 DEBUG(10, ("create_file: %s\n", nt_errstr(status)));
5642 if (fsp != NULL) {
5643 close_file(req, fsp, ERROR_CLOSE);
5644 fsp = NULL;
5646 return status;