winbindd: remove unused single_domains array
[Samba.git] / source3 / smbd / open.c
blob50f8a5ea216620d6b6cb838b6791f22c5c09fc76
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 char *conn_rootdir,
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 char *conn_rootdir,
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 int link_len = -1;
414 char *oldwd = NULL;
415 size_t rootdir_len = 0;
416 char *resolved_name = NULL;
417 bool matched = false;
418 int saved_errno = 0;
421 * Ensure we don't get stuck in a symlink loop.
423 link_depth++;
424 if (link_depth >= 20) {
425 errno = ELOOP;
426 goto out;
429 /* Allocate space for the link target. */
430 link_target = talloc_array(talloc_tos(), char, PATH_MAX);
431 if (link_target == NULL) {
432 errno = ENOMEM;
433 goto out;
436 /* Read the link target. */
437 link_len = SMB_VFS_READLINK(conn,
438 smb_fname->base_name,
439 link_target,
440 PATH_MAX - 1);
441 if (link_len == -1) {
442 goto out;
445 /* Ensure it's at least null terminated. */
446 link_target[link_len] = '\0';
448 /* Convert to an absolute path. */
449 resolved_name = SMB_VFS_REALPATH(conn, link_target);
450 if (resolved_name == NULL) {
451 goto out;
455 * We know conn_rootdir starts with '/' and
456 * does not end in '/'. FIXME ! Should we
457 * smb_assert this ?
459 rootdir_len = strlen(conn_rootdir);
461 matched = (strncmp(conn_rootdir, resolved_name, rootdir_len) == 0);
462 if (!matched) {
463 errno = EACCES;
464 goto out;
468 * Turn into a path relative to the share root.
470 if (resolved_name[rootdir_len] == '\0') {
471 /* Link to the root of the share. */
472 smb_fname->base_name = talloc_strdup(talloc_tos(), ".");
473 if (smb_fname->base_name == NULL) {
474 errno = ENOMEM;
475 goto out;
477 } else if (resolved_name[rootdir_len] == '/') {
478 smb_fname->base_name = &resolved_name[rootdir_len+1];
479 } else {
480 errno = EACCES;
481 goto out;
484 oldwd = vfs_GetWd(talloc_tos(), conn);
485 if (oldwd == NULL) {
486 goto out;
489 /* Ensure we operate from the root of the share. */
490 if (vfs_ChDir(conn, conn_rootdir) == -1) {
491 goto out;
494 /* And do it all again.. */
495 fd = non_widelink_open(conn,
496 conn_rootdir,
497 fsp,
498 smb_fname,
499 flags,
500 mode,
501 link_depth);
502 if (fd == -1) {
503 saved_errno = errno;
506 out:
508 SAFE_FREE(resolved_name);
509 TALLOC_FREE(link_target);
510 if (oldwd != NULL) {
511 int ret = vfs_ChDir(conn, oldwd);
512 if (ret == -1) {
513 smb_panic("unable to get back to old directory\n");
515 TALLOC_FREE(oldwd);
517 if (saved_errno != 0) {
518 errno = saved_errno;
520 return fd;
523 /****************************************************************************
524 Non-widelink open.
525 ****************************************************************************/
527 static int non_widelink_open(struct connection_struct *conn,
528 const char *conn_rootdir,
529 files_struct *fsp,
530 struct smb_filename *smb_fname,
531 int flags,
532 mode_t mode,
533 unsigned int link_depth)
535 NTSTATUS status;
536 int fd = -1;
537 struct smb_filename *smb_fname_rel = NULL;
538 int saved_errno = 0;
539 char *oldwd = NULL;
540 char *parent_dir = NULL;
541 const char *final_component = NULL;
543 if (!parent_dirname(talloc_tos(),
544 smb_fname->base_name,
545 &parent_dir,
546 &final_component)) {
547 goto out;
550 oldwd = vfs_GetWd(talloc_tos(), conn);
551 if (oldwd == NULL) {
552 goto out;
555 /* Pin parent directory in place. */
556 if (vfs_ChDir(conn, parent_dir) == -1) {
557 goto out;
560 /* Ensure the relative path is below the share. */
561 status = check_reduced_name(conn, parent_dir, final_component);
562 if (!NT_STATUS_IS_OK(status)) {
563 saved_errno = map_errno_from_nt_status(status);
564 goto out;
567 smb_fname_rel = synthetic_smb_fname(talloc_tos(),
568 final_component,
569 smb_fname->stream_name,
570 &smb_fname->st,
571 smb_fname->flags);
573 flags |= O_NOFOLLOW;
576 struct smb_filename *tmp_name = fsp->fsp_name;
577 fsp->fsp_name = smb_fname_rel;
578 fd = SMB_VFS_OPEN(conn, smb_fname_rel, fsp, flags, mode);
579 fsp->fsp_name = tmp_name;
582 if (fd == -1) {
583 saved_errno = link_errno_convert(errno);
584 if (saved_errno == ELOOP) {
585 if (fsp->posix_flags & FSP_POSIX_FLAGS_OPEN) {
586 /* Never follow symlinks on posix open. */
587 goto out;
589 if (!lp_follow_symlinks(SNUM(conn))) {
590 /* Explicitly no symlinks. */
591 goto out;
594 * We have a symlink. Follow in userspace
595 * to ensure it's under the share definition.
597 fd = process_symlink_open(conn,
598 conn_rootdir,
599 fsp,
600 smb_fname_rel,
601 flags,
602 mode,
603 link_depth);
604 if (fd == -1) {
605 saved_errno =
606 link_errno_convert(errno);
611 out:
613 TALLOC_FREE(parent_dir);
614 TALLOC_FREE(smb_fname_rel);
616 if (oldwd != NULL) {
617 int ret = vfs_ChDir(conn, oldwd);
618 if (ret == -1) {
619 smb_panic("unable to get back to old directory\n");
621 TALLOC_FREE(oldwd);
623 if (saved_errno != 0) {
624 errno = saved_errno;
626 return fd;
629 /****************************************************************************
630 fd support routines - attempt to do a dos_open.
631 ****************************************************************************/
633 NTSTATUS fd_open(struct connection_struct *conn,
634 files_struct *fsp,
635 int flags,
636 mode_t mode)
638 struct smb_filename *smb_fname = fsp->fsp_name;
639 NTSTATUS status = NT_STATUS_OK;
642 * Never follow symlinks on a POSIX client. The
643 * client should be doing this.
646 if ((fsp->posix_flags & FSP_POSIX_FLAGS_OPEN) || !lp_follow_symlinks(SNUM(conn))) {
647 flags |= O_NOFOLLOW;
650 /* Ensure path is below share definition. */
651 if (!lp_widelinks(SNUM(conn))) {
652 const char *conn_rootdir = SMB_VFS_CONNECTPATH(conn,
653 smb_fname->base_name);
654 if (conn_rootdir == NULL) {
655 return NT_STATUS_NO_MEMORY;
658 * Only follow symlinks within a share
659 * definition.
661 fsp->fh->fd = non_widelink_open(conn,
662 conn_rootdir,
663 fsp,
664 smb_fname,
665 flags,
666 mode,
668 } else {
669 fsp->fh->fd = SMB_VFS_OPEN(conn, smb_fname, fsp, flags, mode);
672 if (fsp->fh->fd == -1) {
673 int posix_errno = link_errno_convert(errno);
674 status = map_nt_error_from_unix(posix_errno);
675 if (errno == EMFILE) {
676 static time_t last_warned = 0L;
678 if (time((time_t *) NULL) > last_warned) {
679 DEBUG(0,("Too many open files, unable "
680 "to open more! smbd's max "
681 "open files = %d\n",
682 lp_max_open_files()));
683 last_warned = time((time_t *) NULL);
689 DEBUG(10,("fd_open: name %s, flags = 0%o mode = 0%o, fd = %d. %s\n",
690 smb_fname_str_dbg(smb_fname), flags, (int)mode, fsp->fh->fd,
691 (fsp->fh->fd == -1) ? strerror(errno) : "" ));
693 return status;
696 /****************************************************************************
697 Close the file associated with a fsp.
698 ****************************************************************************/
700 NTSTATUS fd_close(files_struct *fsp)
702 int ret;
704 if (fsp->dptr) {
705 dptr_CloseDir(fsp);
707 if (fsp->fh->fd == -1) {
708 return NT_STATUS_OK; /* What we used to call a stat open. */
710 if (fsp->fh->ref_count > 1) {
711 return NT_STATUS_OK; /* Shared handle. Only close last reference. */
714 ret = SMB_VFS_CLOSE(fsp);
715 fsp->fh->fd = -1;
716 if (ret == -1) {
717 return map_nt_error_from_unix(errno);
719 return NT_STATUS_OK;
722 /****************************************************************************
723 Change the ownership of a file to that of the parent directory.
724 Do this by fd if possible.
725 ****************************************************************************/
727 void change_file_owner_to_parent(connection_struct *conn,
728 const char *inherit_from_dir,
729 files_struct *fsp)
731 struct smb_filename *smb_fname_parent;
732 int ret;
734 smb_fname_parent = synthetic_smb_fname(talloc_tos(),
735 inherit_from_dir,
736 NULL,
737 NULL,
739 if (smb_fname_parent == NULL) {
740 return;
743 ret = SMB_VFS_STAT(conn, smb_fname_parent);
744 if (ret == -1) {
745 DEBUG(0,("change_file_owner_to_parent: failed to stat parent "
746 "directory %s. Error was %s\n",
747 smb_fname_str_dbg(smb_fname_parent),
748 strerror(errno)));
749 TALLOC_FREE(smb_fname_parent);
750 return;
753 if (smb_fname_parent->st.st_ex_uid == fsp->fsp_name->st.st_ex_uid) {
754 /* Already this uid - no need to change. */
755 DEBUG(10,("change_file_owner_to_parent: file %s "
756 "is already owned by uid %d\n",
757 fsp_str_dbg(fsp),
758 (int)fsp->fsp_name->st.st_ex_uid ));
759 TALLOC_FREE(smb_fname_parent);
760 return;
763 become_root();
764 ret = SMB_VFS_FCHOWN(fsp, smb_fname_parent->st.st_ex_uid, (gid_t)-1);
765 unbecome_root();
766 if (ret == -1) {
767 DEBUG(0,("change_file_owner_to_parent: failed to fchown "
768 "file %s to parent directory uid %u. Error "
769 "was %s\n", fsp_str_dbg(fsp),
770 (unsigned int)smb_fname_parent->st.st_ex_uid,
771 strerror(errno) ));
772 } else {
773 DEBUG(10,("change_file_owner_to_parent: changed new file %s to "
774 "parent directory uid %u.\n", fsp_str_dbg(fsp),
775 (unsigned int)smb_fname_parent->st.st_ex_uid));
776 /* Ensure the uid entry is updated. */
777 fsp->fsp_name->st.st_ex_uid = smb_fname_parent->st.st_ex_uid;
780 TALLOC_FREE(smb_fname_parent);
783 NTSTATUS change_dir_owner_to_parent(connection_struct *conn,
784 const char *inherit_from_dir,
785 const char *fname,
786 SMB_STRUCT_STAT *psbuf)
788 struct smb_filename *smb_fname_parent;
789 struct smb_filename *smb_fname_cwd = NULL;
790 char *saved_dir = NULL;
791 TALLOC_CTX *ctx = talloc_tos();
792 NTSTATUS status = NT_STATUS_OK;
793 int ret;
795 smb_fname_parent = synthetic_smb_fname(ctx,
796 inherit_from_dir,
797 NULL,
798 NULL,
800 if (smb_fname_parent == NULL) {
801 return NT_STATUS_NO_MEMORY;
804 ret = SMB_VFS_STAT(conn, smb_fname_parent);
805 if (ret == -1) {
806 status = map_nt_error_from_unix(errno);
807 DEBUG(0,("change_dir_owner_to_parent: failed to stat parent "
808 "directory %s. Error was %s\n",
809 smb_fname_str_dbg(smb_fname_parent),
810 strerror(errno)));
811 goto out;
814 /* We've already done an lstat into psbuf, and we know it's a
815 directory. If we can cd into the directory and the dev/ino
816 are the same then we can safely chown without races as
817 we're locking the directory in place by being in it. This
818 should work on any UNIX (thanks tridge :-). JRA.
821 saved_dir = vfs_GetWd(ctx,conn);
822 if (!saved_dir) {
823 status = map_nt_error_from_unix(errno);
824 DEBUG(0,("change_dir_owner_to_parent: failed to get "
825 "current working directory. Error was %s\n",
826 strerror(errno)));
827 goto out;
830 /* Chdir into the new path. */
831 if (vfs_ChDir(conn, fname) == -1) {
832 status = map_nt_error_from_unix(errno);
833 DEBUG(0,("change_dir_owner_to_parent: failed to change "
834 "current working directory to %s. Error "
835 "was %s\n", fname, strerror(errno) ));
836 goto chdir;
839 smb_fname_cwd = synthetic_smb_fname(ctx, ".", NULL, NULL, 0);
840 if (smb_fname_cwd == NULL) {
841 status = NT_STATUS_NO_MEMORY;
842 goto chdir;
845 ret = SMB_VFS_STAT(conn, smb_fname_cwd);
846 if (ret == -1) {
847 status = map_nt_error_from_unix(errno);
848 DEBUG(0,("change_dir_owner_to_parent: failed to stat "
849 "directory '.' (%s) Error was %s\n",
850 fname, strerror(errno)));
851 goto chdir;
854 /* Ensure we're pointing at the same place. */
855 if (smb_fname_cwd->st.st_ex_dev != psbuf->st_ex_dev ||
856 smb_fname_cwd->st.st_ex_ino != psbuf->st_ex_ino) {
857 DEBUG(0,("change_dir_owner_to_parent: "
858 "device/inode on directory %s changed. "
859 "Refusing to chown !\n", fname ));
860 status = NT_STATUS_ACCESS_DENIED;
861 goto chdir;
864 if (smb_fname_parent->st.st_ex_uid == smb_fname_cwd->st.st_ex_uid) {
865 /* Already this uid - no need to change. */
866 DEBUG(10,("change_dir_owner_to_parent: directory %s "
867 "is already owned by uid %d\n",
868 fname,
869 (int)smb_fname_cwd->st.st_ex_uid ));
870 status = NT_STATUS_OK;
871 goto chdir;
874 become_root();
875 ret = SMB_VFS_LCHOWN(conn,
876 smb_fname_cwd,
877 smb_fname_parent->st.st_ex_uid,
878 (gid_t)-1);
879 unbecome_root();
880 if (ret == -1) {
881 status = map_nt_error_from_unix(errno);
882 DEBUG(10,("change_dir_owner_to_parent: failed to chown "
883 "directory %s to parent directory uid %u. "
884 "Error was %s\n", fname,
885 (unsigned int)smb_fname_parent->st.st_ex_uid,
886 strerror(errno) ));
887 } else {
888 DEBUG(10,("change_dir_owner_to_parent: changed ownership of new "
889 "directory %s to parent directory uid %u.\n",
890 fname, (unsigned int)smb_fname_parent->st.st_ex_uid ));
891 /* Ensure the uid entry is updated. */
892 psbuf->st_ex_uid = smb_fname_parent->st.st_ex_uid;
895 chdir:
896 vfs_ChDir(conn,saved_dir);
897 out:
898 TALLOC_FREE(smb_fname_parent);
899 TALLOC_FREE(smb_fname_cwd);
900 return status;
903 /****************************************************************************
904 Open a file - returning a guaranteed ATOMIC indication of if the
905 file was created or not.
906 ****************************************************************************/
908 static NTSTATUS fd_open_atomic(struct connection_struct *conn,
909 files_struct *fsp,
910 int flags,
911 mode_t mode,
912 bool *file_created)
914 NTSTATUS status = NT_STATUS_UNSUCCESSFUL;
915 NTSTATUS retry_status;
916 bool file_existed = VALID_STAT(fsp->fsp_name->st);
917 int curr_flags;
919 *file_created = false;
921 if (!(flags & O_CREAT)) {
923 * We're not creating the file, just pass through.
925 return fd_open(conn, fsp, flags, mode);
928 if (flags & O_EXCL) {
930 * Fail if already exists, just pass through.
932 status = fd_open(conn, fsp, flags, mode);
935 * Here we've opened with O_CREAT|O_EXCL. If that went
936 * NT_STATUS_OK, we *know* we created this file.
938 *file_created = NT_STATUS_IS_OK(status);
940 return status;
944 * Now it gets tricky. We have O_CREAT, but not O_EXCL.
945 * To know absolutely if we created the file or not,
946 * we can never call O_CREAT without O_EXCL. So if
947 * we think the file existed, try without O_CREAT|O_EXCL.
948 * If we think the file didn't exist, try with
949 * O_CREAT|O_EXCL.
951 * The big problem here is dangling symlinks. Opening
952 * without O_NOFOLLOW means both bad symlink
953 * and missing path return -1, ENOENT from open(). As POSIX
954 * is pathname based it's not possible to tell
955 * the difference between these two cases in a
956 * non-racy way, so change to try only two attempts before
957 * giving up.
959 * We don't have this problem for the O_NOFOLLOW
960 * case as it just returns NT_STATUS_OBJECT_PATH_NOT_FOUND
961 * mapped from the ELOOP POSIX error.
964 curr_flags = flags;
966 if (file_existed) {
967 curr_flags &= ~(O_CREAT);
968 retry_status = NT_STATUS_OBJECT_NAME_NOT_FOUND;
969 } else {
970 curr_flags |= O_EXCL;
971 retry_status = NT_STATUS_OBJECT_NAME_COLLISION;
974 status = fd_open(conn, fsp, curr_flags, mode);
975 if (NT_STATUS_IS_OK(status)) {
976 if (!file_existed) {
977 *file_created = true;
979 return NT_STATUS_OK;
981 if (!NT_STATUS_EQUAL(status, retry_status)) {
982 return status;
985 curr_flags = flags;
988 * Keep file_existed up to date for clarity.
990 if (NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
991 file_existed = false;
992 curr_flags |= O_EXCL;
993 DBG_DEBUG("file %s did not exist. Retry.\n",
994 smb_fname_str_dbg(fsp->fsp_name));
995 } else {
996 file_existed = true;
997 curr_flags &= ~(O_CREAT);
998 DBG_DEBUG("file %s existed. Retry.\n",
999 smb_fname_str_dbg(fsp->fsp_name));
1002 status = fd_open(conn, fsp, curr_flags, mode);
1004 if (NT_STATUS_IS_OK(status) && (!file_existed)) {
1005 *file_created = true;
1008 return status;
1011 /****************************************************************************
1012 Open a file.
1013 ****************************************************************************/
1015 static NTSTATUS open_file(files_struct *fsp,
1016 connection_struct *conn,
1017 struct smb_request *req,
1018 const char *parent_dir,
1019 int flags,
1020 mode_t unx_mode,
1021 uint32_t access_mask, /* client requested access mask. */
1022 uint32_t open_access_mask, /* what we're actually using in the open. */
1023 bool *p_file_created)
1025 struct smb_filename *smb_fname = fsp->fsp_name;
1026 NTSTATUS status = NT_STATUS_OK;
1027 int accmode = (flags & O_ACCMODE);
1028 int local_flags = flags;
1029 bool file_existed = VALID_STAT(fsp->fsp_name->st);
1031 fsp->fh->fd = -1;
1032 errno = EPERM;
1034 /* Check permissions */
1037 * This code was changed after seeing a client open request
1038 * containing the open mode of (DENY_WRITE/read-only) with
1039 * the 'create if not exist' bit set. The previous code
1040 * would fail to open the file read only on a read-only share
1041 * as it was checking the flags parameter directly against O_RDONLY,
1042 * this was failing as the flags parameter was set to O_RDONLY|O_CREAT.
1043 * JRA.
1046 if (!CAN_WRITE(conn)) {
1047 /* It's a read-only share - fail if we wanted to write. */
1048 if(accmode != O_RDONLY || (flags & O_TRUNC) || (flags & O_APPEND)) {
1049 DEBUG(3,("Permission denied opening %s\n",
1050 smb_fname_str_dbg(smb_fname)));
1051 return NT_STATUS_ACCESS_DENIED;
1053 if (flags & O_CREAT) {
1054 /* We don't want to write - but we must make sure that
1055 O_CREAT doesn't create the file if we have write
1056 access into the directory.
1058 flags &= ~(O_CREAT|O_EXCL);
1059 local_flags &= ~(O_CREAT|O_EXCL);
1064 * This little piece of insanity is inspired by the
1065 * fact that an NT client can open a file for O_RDONLY,
1066 * but set the create disposition to FILE_EXISTS_TRUNCATE.
1067 * If the client *can* write to the file, then it expects to
1068 * truncate the file, even though it is opening for readonly.
1069 * Quicken uses this stupid trick in backup file creation...
1070 * Thanks *greatly* to "David W. Chapman Jr." <dwcjr@inethouston.net>
1071 * for helping track this one down. It didn't bite us in 2.0.x
1072 * as we always opened files read-write in that release. JRA.
1075 if ((accmode == O_RDONLY) && ((flags & O_TRUNC) == O_TRUNC)) {
1076 DEBUG(10,("open_file: truncate requested on read-only open "
1077 "for file %s\n", smb_fname_str_dbg(smb_fname)));
1078 local_flags = (flags & ~O_ACCMODE)|O_RDWR;
1081 if ((open_access_mask & (FILE_READ_DATA|FILE_WRITE_DATA|FILE_APPEND_DATA|FILE_EXECUTE)) ||
1082 (!file_existed && (local_flags & O_CREAT)) ||
1083 ((local_flags & O_TRUNC) == O_TRUNC) ) {
1084 const char *wild;
1085 int ret;
1087 #if defined(O_NONBLOCK) && defined(S_ISFIFO)
1089 * We would block on opening a FIFO with no one else on the
1090 * other end. Do what we used to do and add O_NONBLOCK to the
1091 * open flags. JRA.
1094 if (file_existed && S_ISFIFO(smb_fname->st.st_ex_mode)) {
1095 local_flags &= ~O_TRUNC; /* Can't truncate a FIFO. */
1096 local_flags |= O_NONBLOCK;
1098 #endif
1100 /* Don't create files with Microsoft wildcard characters. */
1101 if (fsp->base_fsp) {
1103 * wildcard characters are allowed in stream names
1104 * only test the basefilename
1106 wild = fsp->base_fsp->fsp_name->base_name;
1107 } else {
1108 wild = smb_fname->base_name;
1110 if ((local_flags & O_CREAT) && !file_existed &&
1111 !(fsp->posix_flags & FSP_POSIX_FLAGS_PATHNAMES) &&
1112 ms_has_wild(wild)) {
1113 return NT_STATUS_OBJECT_NAME_INVALID;
1116 /* Can we access this file ? */
1117 if (!fsp->base_fsp) {
1118 /* Only do this check on non-stream open. */
1119 if (file_existed) {
1120 status = smbd_check_access_rights(conn,
1121 smb_fname,
1122 false,
1123 access_mask);
1125 if (!NT_STATUS_IS_OK(status)) {
1126 DEBUG(10, ("open_file: "
1127 "smbd_check_access_rights "
1128 "on file %s returned %s\n",
1129 smb_fname_str_dbg(smb_fname),
1130 nt_errstr(status)));
1133 if (!NT_STATUS_IS_OK(status) &&
1134 !NT_STATUS_EQUAL(status,
1135 NT_STATUS_OBJECT_NAME_NOT_FOUND))
1137 return status;
1140 if (NT_STATUS_EQUAL(status,
1141 NT_STATUS_OBJECT_NAME_NOT_FOUND))
1143 DEBUG(10, ("open_file: "
1144 "file %s vanished since we "
1145 "checked for existence.\n",
1146 smb_fname_str_dbg(smb_fname)));
1147 file_existed = false;
1148 SET_STAT_INVALID(fsp->fsp_name->st);
1152 if (!file_existed) {
1153 if (!(local_flags & O_CREAT)) {
1154 /* File didn't exist and no O_CREAT. */
1155 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
1158 status = check_parent_access(conn,
1159 smb_fname,
1160 SEC_DIR_ADD_FILE);
1161 if (!NT_STATUS_IS_OK(status)) {
1162 DEBUG(10, ("open_file: "
1163 "check_parent_access on "
1164 "file %s returned %s\n",
1165 smb_fname_str_dbg(smb_fname),
1166 nt_errstr(status) ));
1167 return status;
1173 * Actually do the open - if O_TRUNC is needed handle it
1174 * below under the share mode lock.
1176 status = fd_open_atomic(conn, fsp, local_flags & ~O_TRUNC,
1177 unx_mode, p_file_created);
1178 if (!NT_STATUS_IS_OK(status)) {
1179 DEBUG(3,("Error opening file %s (%s) (local_flags=%d) "
1180 "(flags=%d)\n", smb_fname_str_dbg(smb_fname),
1181 nt_errstr(status),local_flags,flags));
1182 return status;
1185 if (local_flags & O_NONBLOCK) {
1187 * GPFS can return ETIMEDOUT for pread on
1188 * nonblocking file descriptors when files
1189 * migrated to tape need to be recalled. I
1190 * could imagine this happens elsehwere
1191 * too. With blocking file descriptors this
1192 * does not happen.
1194 ret = set_blocking(fsp->fh->fd, true);
1195 if (ret == -1) {
1196 status = map_nt_error_from_unix(errno);
1197 DBG_WARNING("Could not set fd to blocking: "
1198 "%s\n", strerror(errno));
1199 fd_close(fsp);
1200 return status;
1204 ret = SMB_VFS_FSTAT(fsp, &smb_fname->st);
1205 if (ret == -1) {
1206 /* If we have an fd, this stat should succeed. */
1207 DEBUG(0,("Error doing fstat on open file %s "
1208 "(%s)\n",
1209 smb_fname_str_dbg(smb_fname),
1210 strerror(errno) ));
1211 status = map_nt_error_from_unix(errno);
1212 fd_close(fsp);
1213 return status;
1216 if (*p_file_created) {
1217 /* We created this file. */
1219 bool need_re_stat = false;
1220 /* Do all inheritance work after we've
1221 done a successful fstat call and filled
1222 in the stat struct in fsp->fsp_name. */
1224 /* Inherit the ACL if required */
1225 if (lp_inherit_permissions(SNUM(conn))) {
1226 inherit_access_posix_acl(conn, parent_dir,
1227 smb_fname->base_name,
1228 unx_mode);
1229 need_re_stat = true;
1232 /* Change the owner if required. */
1233 if (lp_inherit_owner(SNUM(conn)) != INHERIT_OWNER_NO) {
1234 change_file_owner_to_parent(conn, parent_dir,
1235 fsp);
1236 need_re_stat = true;
1239 if (need_re_stat) {
1240 ret = SMB_VFS_FSTAT(fsp, &smb_fname->st);
1241 /* If we have an fd, this stat should succeed. */
1242 if (ret == -1) {
1243 DEBUG(0,("Error doing fstat on open file %s "
1244 "(%s)\n",
1245 smb_fname_str_dbg(smb_fname),
1246 strerror(errno) ));
1250 notify_fname(conn, NOTIFY_ACTION_ADDED,
1251 FILE_NOTIFY_CHANGE_FILE_NAME,
1252 smb_fname->base_name);
1254 } else {
1255 fsp->fh->fd = -1; /* What we used to call a stat open. */
1256 if (!file_existed) {
1257 /* File must exist for a stat open. */
1258 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
1261 status = smbd_check_access_rights(conn,
1262 smb_fname,
1263 false,
1264 access_mask);
1266 if (NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND) &&
1267 (fsp->posix_flags & FSP_POSIX_FLAGS_OPEN) &&
1268 S_ISLNK(smb_fname->st.st_ex_mode)) {
1269 /* This is a POSIX stat open for delete
1270 * or rename on a symlink that points
1271 * nowhere. Allow. */
1272 DEBUG(10,("open_file: allowing POSIX "
1273 "open on bad symlink %s\n",
1274 smb_fname_str_dbg(smb_fname)));
1275 status = NT_STATUS_OK;
1278 if (!NT_STATUS_IS_OK(status)) {
1279 DEBUG(10,("open_file: "
1280 "smbd_check_access_rights on file "
1281 "%s returned %s\n",
1282 smb_fname_str_dbg(smb_fname),
1283 nt_errstr(status) ));
1284 return status;
1289 * POSIX allows read-only opens of directories. We don't
1290 * want to do this (we use a different code path for this)
1291 * so catch a directory open and return an EISDIR. JRA.
1294 if(S_ISDIR(smb_fname->st.st_ex_mode)) {
1295 fd_close(fsp);
1296 errno = EISDIR;
1297 return NT_STATUS_FILE_IS_A_DIRECTORY;
1300 fsp->file_id = vfs_file_id_from_sbuf(conn, &smb_fname->st);
1301 fsp->vuid = req ? req->vuid : UID_FIELD_INVALID;
1302 fsp->file_pid = req ? req->smbpid : 0;
1303 fsp->can_lock = True;
1304 fsp->can_read = ((access_mask & FILE_READ_DATA) != 0);
1305 fsp->can_write =
1306 CAN_WRITE(conn) &&
1307 ((access_mask & (FILE_WRITE_DATA | FILE_APPEND_DATA)) != 0);
1308 fsp->print_file = NULL;
1309 fsp->modified = False;
1310 fsp->sent_oplock_break = NO_BREAK_SENT;
1311 fsp->is_directory = False;
1312 if (conn->aio_write_behind_list &&
1313 is_in_path(smb_fname->base_name, conn->aio_write_behind_list,
1314 conn->case_sensitive)) {
1315 fsp->aio_write_behind = True;
1318 fsp->wcp = NULL; /* Write cache pointer. */
1320 DEBUG(2,("%s opened file %s read=%s write=%s (numopen=%d)\n",
1321 conn->session_info->unix_info->unix_name,
1322 smb_fname_str_dbg(smb_fname),
1323 BOOLSTR(fsp->can_read), BOOLSTR(fsp->can_write),
1324 conn->num_files_open));
1326 errno = 0;
1327 return NT_STATUS_OK;
1330 /****************************************************************************
1331 Check if we can open a file with a share mode.
1332 Returns True if conflict, False if not.
1333 ****************************************************************************/
1335 static bool share_conflict(struct share_mode_entry *entry,
1336 uint32_t access_mask,
1337 uint32_t share_access)
1339 DEBUG(10,("share_conflict: entry->access_mask = 0x%x, "
1340 "entry->share_access = 0x%x, "
1341 "entry->private_options = 0x%x\n",
1342 (unsigned int)entry->access_mask,
1343 (unsigned int)entry->share_access,
1344 (unsigned int)entry->private_options));
1346 if (server_id_is_disconnected(&entry->pid)) {
1348 * note: cleanup should have been done by
1349 * delay_for_batch_oplocks()
1351 return false;
1354 DEBUG(10,("share_conflict: access_mask = 0x%x, share_access = 0x%x\n",
1355 (unsigned int)access_mask, (unsigned int)share_access));
1357 if ((entry->access_mask & (FILE_WRITE_DATA|
1358 FILE_APPEND_DATA|
1359 FILE_READ_DATA|
1360 FILE_EXECUTE|
1361 DELETE_ACCESS)) == 0) {
1362 DEBUG(10,("share_conflict: No conflict due to "
1363 "entry->access_mask = 0x%x\n",
1364 (unsigned int)entry->access_mask ));
1365 return False;
1368 if ((access_mask & (FILE_WRITE_DATA|
1369 FILE_APPEND_DATA|
1370 FILE_READ_DATA|
1371 FILE_EXECUTE|
1372 DELETE_ACCESS)) == 0) {
1373 DEBUG(10,("share_conflict: No conflict due to "
1374 "access_mask = 0x%x\n",
1375 (unsigned int)access_mask ));
1376 return False;
1379 #if 1 /* JRA TEST - Superdebug. */
1380 #define CHECK_MASK(num, am, right, sa, share) \
1381 DEBUG(10,("share_conflict: [%d] am (0x%x) & right (0x%x) = 0x%x\n", \
1382 (unsigned int)(num), (unsigned int)(am), \
1383 (unsigned int)(right), (unsigned int)(am)&(right) )); \
1384 DEBUG(10,("share_conflict: [%d] sa (0x%x) & share (0x%x) = 0x%x\n", \
1385 (unsigned int)(num), (unsigned int)(sa), \
1386 (unsigned int)(share), (unsigned int)(sa)&(share) )); \
1387 if (((am) & (right)) && !((sa) & (share))) { \
1388 DEBUG(10,("share_conflict: check %d conflict am = 0x%x, right = 0x%x, \
1389 sa = 0x%x, share = 0x%x\n", (num), (unsigned int)(am), (unsigned int)(right), (unsigned int)(sa), \
1390 (unsigned int)(share) )); \
1391 return True; \
1393 #else
1394 #define CHECK_MASK(num, am, right, sa, share) \
1395 if (((am) & (right)) && !((sa) & (share))) { \
1396 DEBUG(10,("share_conflict: check %d conflict am = 0x%x, right = 0x%x, \
1397 sa = 0x%x, share = 0x%x\n", (num), (unsigned int)(am), (unsigned int)(right), (unsigned int)(sa), \
1398 (unsigned int)(share) )); \
1399 return True; \
1401 #endif
1403 CHECK_MASK(1, entry->access_mask, FILE_WRITE_DATA | FILE_APPEND_DATA,
1404 share_access, FILE_SHARE_WRITE);
1405 CHECK_MASK(2, access_mask, FILE_WRITE_DATA | FILE_APPEND_DATA,
1406 entry->share_access, FILE_SHARE_WRITE);
1408 CHECK_MASK(3, entry->access_mask, FILE_READ_DATA | FILE_EXECUTE,
1409 share_access, FILE_SHARE_READ);
1410 CHECK_MASK(4, access_mask, FILE_READ_DATA | FILE_EXECUTE,
1411 entry->share_access, FILE_SHARE_READ);
1413 CHECK_MASK(5, entry->access_mask, DELETE_ACCESS,
1414 share_access, FILE_SHARE_DELETE);
1415 CHECK_MASK(6, access_mask, DELETE_ACCESS,
1416 entry->share_access, FILE_SHARE_DELETE);
1418 DEBUG(10,("share_conflict: No conflict.\n"));
1419 return False;
1422 #if defined(DEVELOPER)
1423 static void validate_my_share_entries(struct smbd_server_connection *sconn,
1424 int num,
1425 struct share_mode_entry *share_entry)
1427 struct server_id self = messaging_server_id(sconn->msg_ctx);
1428 files_struct *fsp;
1430 if (!serverid_equal(&self, &share_entry->pid)) {
1431 return;
1434 if (share_entry->op_mid == 0) {
1435 /* INTERNAL_OPEN_ONLY */
1436 return;
1439 if (!is_valid_share_mode_entry(share_entry)) {
1440 return;
1443 fsp = file_find_dif(sconn, share_entry->id,
1444 share_entry->share_file_id);
1445 if (!fsp) {
1446 DEBUG(0,("validate_my_share_entries: PANIC : %s\n",
1447 share_mode_str(talloc_tos(), num, share_entry) ));
1448 smb_panic("validate_my_share_entries: Cannot match a "
1449 "share entry with an open file\n");
1452 if (((uint16_t)fsp->oplock_type) != share_entry->op_type) {
1453 goto panic;
1456 return;
1458 panic:
1460 char *str;
1461 DEBUG(0,("validate_my_share_entries: PANIC : %s\n",
1462 share_mode_str(talloc_tos(), num, share_entry) ));
1463 str = talloc_asprintf(talloc_tos(),
1464 "validate_my_share_entries: "
1465 "file %s, oplock_type = 0x%x, op_type = 0x%x\n",
1466 fsp->fsp_name->base_name,
1467 (unsigned int)fsp->oplock_type,
1468 (unsigned int)share_entry->op_type );
1469 smb_panic(str);
1472 #endif
1474 bool is_stat_open(uint32_t access_mask)
1476 const uint32_t stat_open_bits =
1477 (SYNCHRONIZE_ACCESS|
1478 FILE_READ_ATTRIBUTES|
1479 FILE_WRITE_ATTRIBUTES);
1481 return (((access_mask & stat_open_bits) != 0) &&
1482 ((access_mask & ~stat_open_bits) == 0));
1485 static bool has_delete_on_close(struct share_mode_lock *lck,
1486 uint32_t name_hash)
1488 struct share_mode_data *d = lck->data;
1489 uint32_t i;
1491 if (d->num_share_modes == 0) {
1492 return false;
1494 if (!is_delete_on_close_set(lck, name_hash)) {
1495 return false;
1497 for (i=0; i<d->num_share_modes; i++) {
1498 if (!share_mode_stale_pid(d, i)) {
1499 return true;
1502 return false;
1505 /****************************************************************************
1506 Deal with share modes
1507 Invariant: Share mode must be locked on entry and exit.
1508 Returns -1 on error, or number of share modes on success (may be zero).
1509 ****************************************************************************/
1511 static NTSTATUS open_mode_check(connection_struct *conn,
1512 struct share_mode_lock *lck,
1513 uint32_t access_mask,
1514 uint32_t share_access)
1516 uint32_t i;
1518 if(lck->data->num_share_modes == 0) {
1519 return NT_STATUS_OK;
1522 if (is_stat_open(access_mask)) {
1523 /* Stat open that doesn't trigger oplock breaks or share mode
1524 * checks... ! JRA. */
1525 return NT_STATUS_OK;
1529 * Check if the share modes will give us access.
1532 #if defined(DEVELOPER)
1533 for(i = 0; i < lck->data->num_share_modes; i++) {
1534 validate_my_share_entries(conn->sconn, i,
1535 &lck->data->share_modes[i]);
1537 #endif
1539 /* Now we check the share modes, after any oplock breaks. */
1540 for(i = 0; i < lck->data->num_share_modes; i++) {
1542 if (!is_valid_share_mode_entry(&lck->data->share_modes[i])) {
1543 continue;
1546 /* someone else has a share lock on it, check to see if we can
1547 * too */
1548 if (share_conflict(&lck->data->share_modes[i],
1549 access_mask, share_access)) {
1551 if (share_mode_stale_pid(lck->data, i)) {
1552 continue;
1555 return NT_STATUS_SHARING_VIOLATION;
1559 return NT_STATUS_OK;
1563 * Send a break message to the oplock holder and delay the open for
1564 * our client.
1567 NTSTATUS send_break_message(struct messaging_context *msg_ctx,
1568 const struct share_mode_entry *exclusive,
1569 uint16_t break_to)
1571 NTSTATUS status;
1572 char msg[MSG_SMB_SHARE_MODE_ENTRY_SIZE];
1573 struct server_id_buf tmp;
1575 DEBUG(10, ("Sending break request to PID %s\n",
1576 server_id_str_buf(exclusive->pid, &tmp)));
1578 /* Create the message. */
1579 share_mode_entry_to_message(msg, exclusive);
1581 /* Overload entry->op_type */
1583 * This is a cut from uint32_t to uint16_t, but so far only the lower 3
1584 * bits (LEASE_WRITE/HANDLE/READ are used anyway.
1586 SSVAL(msg,OP_BREAK_MSG_OP_TYPE_OFFSET, break_to);
1588 status = messaging_send_buf(msg_ctx, exclusive->pid,
1589 MSG_SMB_BREAK_REQUEST,
1590 (uint8_t *)msg, sizeof(msg));
1591 if (!NT_STATUS_IS_OK(status)) {
1592 DEBUG(3, ("Could not send oplock break message: %s\n",
1593 nt_errstr(status)));
1596 return status;
1600 * Do internal consistency checks on the share mode for a file.
1603 static bool validate_oplock_types(struct share_mode_lock *lck)
1605 struct share_mode_data *d = lck->data;
1606 bool batch = false;
1607 bool ex_or_batch = false;
1608 bool level2 = false;
1609 bool no_oplock = false;
1610 uint32_t num_non_stat_opens = 0;
1611 uint32_t i;
1613 for (i=0; i<d->num_share_modes; i++) {
1614 struct share_mode_entry *e = &d->share_modes[i];
1616 if (!is_valid_share_mode_entry(e)) {
1617 continue;
1620 if (e->op_mid == 0) {
1621 /* INTERNAL_OPEN_ONLY */
1622 continue;
1625 if (e->op_type == NO_OPLOCK && is_stat_open(e->access_mask)) {
1626 /* We ignore stat opens in the table - they
1627 always have NO_OPLOCK and never get or
1628 cause breaks. JRA. */
1629 continue;
1632 num_non_stat_opens += 1;
1634 if (BATCH_OPLOCK_TYPE(e->op_type)) {
1635 /* batch - can only be one. */
1636 if (share_mode_stale_pid(d, i)) {
1637 DEBUG(10, ("Found stale batch oplock\n"));
1638 continue;
1640 if (ex_or_batch || batch || level2 || no_oplock) {
1641 DEBUG(0, ("Bad batch oplock entry %u.",
1642 (unsigned)i));
1643 return false;
1645 batch = true;
1648 if (EXCLUSIVE_OPLOCK_TYPE(e->op_type)) {
1649 if (share_mode_stale_pid(d, i)) {
1650 DEBUG(10, ("Found stale duplicate oplock\n"));
1651 continue;
1653 /* Exclusive or batch - can only be one. */
1654 if (ex_or_batch || level2 || no_oplock) {
1655 DEBUG(0, ("Bad exclusive or batch oplock "
1656 "entry %u.", (unsigned)i));
1657 return false;
1659 ex_or_batch = true;
1662 if (LEVEL_II_OPLOCK_TYPE(e->op_type)) {
1663 if (batch || ex_or_batch) {
1664 if (share_mode_stale_pid(d, i)) {
1665 DEBUG(10, ("Found stale LevelII "
1666 "oplock\n"));
1667 continue;
1669 DEBUG(0, ("Bad levelII oplock entry %u.",
1670 (unsigned)i));
1671 return false;
1673 level2 = true;
1676 if (e->op_type == NO_OPLOCK) {
1677 if (batch || ex_or_batch) {
1678 if (share_mode_stale_pid(d, i)) {
1679 DEBUG(10, ("Found stale NO_OPLOCK "
1680 "entry\n"));
1681 continue;
1683 DEBUG(0, ("Bad no oplock entry %u.",
1684 (unsigned)i));
1685 return false;
1687 no_oplock = true;
1691 remove_stale_share_mode_entries(d);
1693 if ((batch || ex_or_batch) && (num_non_stat_opens != 1)) {
1694 DEBUG(1, ("got batch (%d) or ex (%d) non-exclusively (%d)\n",
1695 (int)batch, (int)ex_or_batch,
1696 (int)d->num_share_modes));
1697 return false;
1700 return true;
1703 static bool delay_for_oplock(files_struct *fsp,
1704 int oplock_request,
1705 const struct smb2_lease *lease,
1706 struct share_mode_lock *lck,
1707 bool have_sharing_violation,
1708 uint32_t create_disposition,
1709 bool first_open_attempt)
1711 struct share_mode_data *d = lck->data;
1712 uint32_t i;
1713 bool delay = false;
1714 bool will_overwrite;
1716 if ((oplock_request & INTERNAL_OPEN_ONLY) ||
1717 is_stat_open(fsp->access_mask)) {
1718 return false;
1721 switch (create_disposition) {
1722 case FILE_SUPERSEDE:
1723 case FILE_OVERWRITE:
1724 case FILE_OVERWRITE_IF:
1725 will_overwrite = true;
1726 break;
1727 default:
1728 will_overwrite = false;
1729 break;
1732 for (i=0; i<d->num_share_modes; i++) {
1733 struct share_mode_entry *e = &d->share_modes[i];
1734 struct share_mode_lease *l = NULL;
1735 uint32_t e_lease_type = get_lease_type(d, e);
1736 uint32_t break_to;
1737 uint32_t delay_mask = 0;
1739 if (e->op_type == LEASE_OPLOCK) {
1740 l = &d->leases[e->lease_idx];
1743 if (have_sharing_violation) {
1744 delay_mask = SMB2_LEASE_HANDLE;
1745 } else {
1746 delay_mask = SMB2_LEASE_WRITE;
1749 break_to = e_lease_type & ~delay_mask;
1751 if (will_overwrite) {
1753 * we'll decide about SMB2_LEASE_READ later.
1755 * Maybe the break will be deferred
1757 break_to &= ~SMB2_LEASE_HANDLE;
1760 DEBUG(10, ("entry %u: e_lease_type %u, will_overwrite: %u\n",
1761 (unsigned)i, (unsigned)e_lease_type,
1762 (unsigned)will_overwrite));
1764 if (lease != NULL && l != NULL) {
1765 bool ign;
1767 ign = smb2_lease_equal(fsp_client_guid(fsp),
1768 &lease->lease_key,
1769 &l->client_guid,
1770 &l->lease_key);
1771 if (ign) {
1772 continue;
1776 if ((e_lease_type & ~break_to) == 0) {
1777 if (l != NULL && l->breaking) {
1778 delay = true;
1780 continue;
1783 if (share_mode_stale_pid(d, i)) {
1784 continue;
1787 if (will_overwrite) {
1789 * If we break anyway break to NONE directly.
1790 * Otherwise vfs_set_filelen() will trigger the
1791 * break.
1793 break_to &= ~(SMB2_LEASE_READ|SMB2_LEASE_WRITE);
1796 if (e->op_type != LEASE_OPLOCK) {
1798 * Oplocks only support breaking to R or NONE.
1800 break_to &= ~(SMB2_LEASE_HANDLE|SMB2_LEASE_WRITE);
1803 DEBUG(10, ("breaking from %d to %d\n",
1804 (int)e_lease_type, (int)break_to));
1805 send_break_message(fsp->conn->sconn->msg_ctx, e,
1806 break_to);
1807 if (e_lease_type & delay_mask) {
1808 delay = true;
1810 if (l != NULL && l->breaking && !first_open_attempt) {
1811 delay = true;
1813 continue;
1816 return delay;
1820 * Return lease or oplock state from a share mode
1822 static uint32_t get_lease_type_from_share_mode(const struct share_mode_data *d)
1824 uint32_t e_lease_type = 0;
1825 uint32_t i;
1827 for (i=0; i < d->num_share_modes; i++) {
1828 struct share_mode_entry *e = &d->share_modes[i];
1830 e_lease_type |= get_lease_type(d, e);
1833 return e_lease_type;
1836 static bool file_has_brlocks(files_struct *fsp)
1838 struct byte_range_lock *br_lck;
1840 br_lck = brl_get_locks_readonly(fsp);
1841 if (!br_lck)
1842 return false;
1844 return (brl_num_locks(br_lck) > 0);
1847 int find_share_mode_lease(struct share_mode_data *d,
1848 const struct GUID *client_guid,
1849 const struct smb2_lease_key *key)
1851 uint32_t i;
1853 for (i=0; i<d->num_leases; i++) {
1854 struct share_mode_lease *l = &d->leases[i];
1856 if (smb2_lease_equal(client_guid,
1857 key,
1858 &l->client_guid,
1859 &l->lease_key)) {
1860 return i;
1864 return -1;
1867 struct fsp_lease *find_fsp_lease(struct files_struct *new_fsp,
1868 const struct smb2_lease_key *key,
1869 const struct share_mode_lease *l)
1871 struct files_struct *fsp;
1874 * TODO: Measure how expensive this loop is with thousands of open
1875 * handles...
1878 for (fsp = file_find_di_first(new_fsp->conn->sconn, new_fsp->file_id);
1879 fsp != NULL;
1880 fsp = file_find_di_next(fsp)) {
1882 if (fsp == new_fsp) {
1883 continue;
1885 if (fsp->oplock_type != LEASE_OPLOCK) {
1886 continue;
1888 if (smb2_lease_key_equal(&fsp->lease->lease.lease_key, key)) {
1889 fsp->lease->ref_count += 1;
1890 return fsp->lease;
1894 /* Not found - must be leased in another smbd. */
1895 new_fsp->lease = talloc_zero(new_fsp->conn->sconn, struct fsp_lease);
1896 if (new_fsp->lease == NULL) {
1897 return NULL;
1899 new_fsp->lease->ref_count = 1;
1900 new_fsp->lease->sconn = new_fsp->conn->sconn;
1901 new_fsp->lease->lease.lease_key = *key;
1902 new_fsp->lease->lease.lease_state = l->current_state;
1904 * We internally treat all leases as V2 and update
1905 * the epoch, but when sending breaks it matters if
1906 * the requesting lease was v1 or v2.
1908 new_fsp->lease->lease.lease_version = l->lease_version;
1909 new_fsp->lease->lease.lease_epoch = l->epoch;
1910 return new_fsp->lease;
1913 static NTSTATUS grant_fsp_lease(struct files_struct *fsp,
1914 struct share_mode_lock *lck,
1915 const struct smb2_lease *lease,
1916 uint32_t *p_lease_idx,
1917 uint32_t granted)
1919 struct share_mode_data *d = lck->data;
1920 const struct GUID *client_guid = fsp_client_guid(fsp);
1921 struct share_mode_lease *tmp;
1922 NTSTATUS status;
1923 int idx;
1925 idx = find_share_mode_lease(d, client_guid, &lease->lease_key);
1927 if (idx != -1) {
1928 struct share_mode_lease *l = &d->leases[idx];
1929 bool do_upgrade;
1930 uint32_t existing, requested;
1932 fsp->lease = find_fsp_lease(fsp, &lease->lease_key, l);
1933 if (fsp->lease == NULL) {
1934 DEBUG(1, ("Did not find existing lease for file %s\n",
1935 fsp_str_dbg(fsp)));
1936 return NT_STATUS_NO_MEMORY;
1939 *p_lease_idx = idx;
1942 * Upgrade only if the requested lease is a strict upgrade.
1944 existing = l->current_state;
1945 requested = lease->lease_state;
1948 * Tricky: This test makes sure that "requested" is a
1949 * strict bitwise superset of "existing".
1951 do_upgrade = ((existing & requested) == existing);
1954 * Upgrade only if there's a change.
1956 do_upgrade &= (granted != existing);
1959 * Upgrade only if other leases don't prevent what was asked
1960 * for.
1962 do_upgrade &= (granted == requested);
1965 * only upgrade if we are not in breaking state
1967 do_upgrade &= !l->breaking;
1969 DEBUG(10, ("existing=%"PRIu32", requested=%"PRIu32", "
1970 "granted=%"PRIu32", do_upgrade=%d\n",
1971 existing, requested, granted, (int)do_upgrade));
1973 if (do_upgrade) {
1974 l->current_state = granted;
1975 l->epoch += 1;
1978 /* Ensure we're in sync with current lease state. */
1979 fsp_lease_update(lck, fsp_client_guid(fsp), fsp->lease);
1980 return NT_STATUS_OK;
1984 * Create new lease
1987 tmp = talloc_realloc(d, d->leases, struct share_mode_lease,
1988 d->num_leases+1);
1989 if (tmp == NULL) {
1991 * See [MS-SMB2]
1993 return NT_STATUS_INSUFFICIENT_RESOURCES;
1995 d->leases = tmp;
1997 fsp->lease = talloc_zero(fsp->conn->sconn, struct fsp_lease);
1998 if (fsp->lease == NULL) {
1999 return NT_STATUS_INSUFFICIENT_RESOURCES;
2001 fsp->lease->ref_count = 1;
2002 fsp->lease->sconn = fsp->conn->sconn;
2003 fsp->lease->lease.lease_version = lease->lease_version;
2004 fsp->lease->lease.lease_key = lease->lease_key;
2005 fsp->lease->lease.lease_state = granted;
2006 fsp->lease->lease.lease_epoch = lease->lease_epoch + 1;
2008 *p_lease_idx = d->num_leases;
2010 d->leases[d->num_leases] = (struct share_mode_lease) {
2011 .client_guid = *client_guid,
2012 .lease_key = fsp->lease->lease.lease_key,
2013 .current_state = fsp->lease->lease.lease_state,
2014 .lease_version = fsp->lease->lease.lease_version,
2015 .epoch = fsp->lease->lease.lease_epoch,
2018 status = leases_db_add(client_guid,
2019 &lease->lease_key,
2020 &fsp->file_id,
2021 fsp->conn->connectpath,
2022 fsp->fsp_name->base_name,
2023 fsp->fsp_name->stream_name);
2024 if (!NT_STATUS_IS_OK(status)) {
2025 DEBUG(10, ("%s: leases_db_add failed: %s\n", __func__,
2026 nt_errstr(status)));
2027 TALLOC_FREE(fsp->lease);
2028 return NT_STATUS_INSUFFICIENT_RESOURCES;
2031 d->num_leases += 1;
2032 d->modified = true;
2034 return NT_STATUS_OK;
2037 static bool is_same_lease(const files_struct *fsp,
2038 const struct share_mode_data *d,
2039 const struct share_mode_entry *e,
2040 const struct smb2_lease *lease)
2042 if (e->op_type != LEASE_OPLOCK) {
2043 return false;
2045 if (lease == NULL) {
2046 return false;
2049 return smb2_lease_equal(fsp_client_guid(fsp),
2050 &lease->lease_key,
2051 &d->leases[e->lease_idx].client_guid,
2052 &d->leases[e->lease_idx].lease_key);
2055 static NTSTATUS grant_fsp_oplock_type(struct smb_request *req,
2056 struct files_struct *fsp,
2057 struct share_mode_lock *lck,
2058 int oplock_request,
2059 struct smb2_lease *lease)
2061 struct share_mode_data *d = lck->data;
2062 bool got_handle_lease = false;
2063 bool got_oplock = false;
2064 uint32_t i;
2065 uint32_t granted;
2066 uint32_t lease_idx = UINT32_MAX;
2067 bool ok;
2068 NTSTATUS status;
2070 if (oplock_request & INTERNAL_OPEN_ONLY) {
2071 /* No oplocks on internal open. */
2072 oplock_request = NO_OPLOCK;
2073 DEBUG(10,("grant_fsp_oplock_type: oplock type 0x%x on file %s\n",
2074 fsp->oplock_type, fsp_str_dbg(fsp)));
2077 if (oplock_request == LEASE_OPLOCK) {
2078 if (lease == NULL) {
2080 * The SMB2 layer should have checked this
2082 return NT_STATUS_INTERNAL_ERROR;
2085 granted = lease->lease_state;
2087 if (lp_kernel_oplocks(SNUM(fsp->conn))) {
2088 DEBUG(10, ("No lease granted because kernel oplocks are enabled\n"));
2089 granted = SMB2_LEASE_NONE;
2091 if ((granted & (SMB2_LEASE_READ|SMB2_LEASE_WRITE)) == 0) {
2092 DEBUG(10, ("No read or write lease requested\n"));
2093 granted = SMB2_LEASE_NONE;
2095 if (granted == SMB2_LEASE_WRITE) {
2096 DEBUG(10, ("pure write lease requested\n"));
2097 granted = SMB2_LEASE_NONE;
2099 if (granted == (SMB2_LEASE_WRITE|SMB2_LEASE_HANDLE)) {
2100 DEBUG(10, ("write and handle lease requested\n"));
2101 granted = SMB2_LEASE_NONE;
2103 } else {
2104 granted = map_oplock_to_lease_type(
2105 oplock_request & ~SAMBA_PRIVATE_OPLOCK_MASK);
2108 if (lp_locking(fsp->conn->params) && file_has_brlocks(fsp)) {
2109 DEBUG(10,("grant_fsp_oplock_type: file %s has byte range locks\n",
2110 fsp_str_dbg(fsp)));
2111 granted &= ~SMB2_LEASE_READ;
2114 for (i=0; i<d->num_share_modes; i++) {
2115 struct share_mode_entry *e = &d->share_modes[i];
2116 uint32_t e_lease_type;
2118 e_lease_type = get_lease_type(d, e);
2120 if ((granted & SMB2_LEASE_WRITE) &&
2121 !is_same_lease(fsp, d, e, lease) &&
2122 !share_mode_stale_pid(d, i)) {
2124 * Can grant only one writer
2126 granted &= ~SMB2_LEASE_WRITE;
2129 if ((e_lease_type & SMB2_LEASE_HANDLE) && !got_handle_lease &&
2130 !share_mode_stale_pid(d, i)) {
2131 got_handle_lease = true;
2134 if ((e->op_type != LEASE_OPLOCK) && !got_oplock &&
2135 !share_mode_stale_pid(d, i)) {
2136 got_oplock = true;
2140 if ((granted & SMB2_LEASE_READ) && !(granted & SMB2_LEASE_WRITE)) {
2141 bool allow_level2 =
2142 (global_client_caps & CAP_LEVEL_II_OPLOCKS) &&
2143 lp_level2_oplocks(SNUM(fsp->conn));
2145 if (!allow_level2) {
2146 granted = SMB2_LEASE_NONE;
2150 if (oplock_request == LEASE_OPLOCK) {
2151 if (got_oplock) {
2152 granted &= ~SMB2_LEASE_HANDLE;
2155 fsp->oplock_type = LEASE_OPLOCK;
2157 status = grant_fsp_lease(fsp, lck, lease, &lease_idx,
2158 granted);
2159 if (!NT_STATUS_IS_OK(status)) {
2160 return status;
2163 *lease = fsp->lease->lease;
2164 DEBUG(10, ("lease_state=%d\n", lease->lease_state));
2165 } else {
2166 if (got_handle_lease) {
2167 granted = SMB2_LEASE_NONE;
2170 switch (granted) {
2171 case SMB2_LEASE_READ|SMB2_LEASE_WRITE|SMB2_LEASE_HANDLE:
2172 fsp->oplock_type = BATCH_OPLOCK|EXCLUSIVE_OPLOCK;
2173 break;
2174 case SMB2_LEASE_READ|SMB2_LEASE_WRITE:
2175 fsp->oplock_type = EXCLUSIVE_OPLOCK;
2176 break;
2177 case SMB2_LEASE_READ|SMB2_LEASE_HANDLE:
2178 case SMB2_LEASE_READ:
2179 fsp->oplock_type = LEVEL_II_OPLOCK;
2180 break;
2181 default:
2182 fsp->oplock_type = NO_OPLOCK;
2183 break;
2186 status = set_file_oplock(fsp);
2187 if (!NT_STATUS_IS_OK(status)) {
2189 * Could not get the kernel oplock
2191 fsp->oplock_type = NO_OPLOCK;
2195 ok = set_share_mode(lck, fsp, get_current_uid(fsp->conn),
2196 req ? req->mid : 0,
2197 fsp->oplock_type,
2198 lease_idx);
2199 if (!ok) {
2200 return NT_STATUS_NO_MEMORY;
2203 ok = update_num_read_oplocks(fsp, lck);
2204 if (!ok) {
2205 del_share_mode(lck, fsp);
2206 return NT_STATUS_INTERNAL_ERROR;
2209 DEBUG(10,("grant_fsp_oplock_type: oplock type 0x%x on file %s\n",
2210 fsp->oplock_type, fsp_str_dbg(fsp)));
2212 return NT_STATUS_OK;
2215 static bool request_timed_out(struct timeval request_time,
2216 struct timeval timeout)
2218 struct timeval now, end_time;
2219 GetTimeOfDay(&now);
2220 end_time = timeval_sum(&request_time, &timeout);
2221 return (timeval_compare(&end_time, &now) < 0);
2224 static struct deferred_open_record *deferred_open_record_create(
2225 bool delayed_for_oplocks,
2226 bool async_open,
2227 struct file_id id)
2229 struct deferred_open_record *record = NULL;
2231 record = talloc(NULL, struct deferred_open_record);
2232 if (record == NULL) {
2233 return NULL;
2236 *record = (struct deferred_open_record) {
2237 .delayed_for_oplocks = delayed_for_oplocks,
2238 .async_open = async_open,
2239 .id = id,
2242 return record;
2245 struct defer_open_state {
2246 struct smbXsrv_connection *xconn;
2247 uint64_t mid;
2248 struct file_id file_id;
2249 struct timeval request_time;
2250 struct timeval timeout;
2251 bool kernel_oplock;
2252 uint32_t lease_type;
2255 static void defer_open_done(struct tevent_req *req);
2258 * Defer an open and watch a locking.tdb record
2260 * This defers an open that gets rescheduled once the locking.tdb record watch
2261 * is triggered by a change to the record.
2263 * It is used to defer opens that triggered an oplock break and for the SMB1
2264 * sharing violation delay.
2266 static void defer_open(struct share_mode_lock *lck,
2267 struct timeval request_time,
2268 struct timeval timeout,
2269 struct smb_request *req,
2270 bool delayed_for_oplocks,
2271 bool kernel_oplock,
2272 struct file_id id)
2274 struct deferred_open_record *open_rec = NULL;
2275 struct timeval abs_timeout;
2276 struct defer_open_state *watch_state;
2277 struct tevent_req *watch_req;
2278 bool ok;
2280 abs_timeout = timeval_sum(&request_time, &timeout);
2282 DBG_DEBUG("request time [%s] timeout [%s] mid [%" PRIu64 "] "
2283 "delayed_for_oplocks [%s] kernel_oplock [%s] file_id [%s]\n",
2284 timeval_string(talloc_tos(), &request_time, false),
2285 timeval_string(talloc_tos(), &abs_timeout, false),
2286 req->mid,
2287 delayed_for_oplocks ? "yes" : "no",
2288 kernel_oplock ? "yes" : "no",
2289 file_id_string_tos(&id));
2291 open_rec = deferred_open_record_create(delayed_for_oplocks,
2292 false,
2293 id);
2294 if (open_rec == NULL) {
2295 TALLOC_FREE(lck);
2296 exit_server("talloc failed");
2299 watch_state = talloc(open_rec, struct defer_open_state);
2300 if (watch_state == NULL) {
2301 exit_server("talloc failed");
2303 watch_state->xconn = req->xconn;
2304 watch_state->mid = req->mid;
2305 watch_state->file_id = lck->data->id;
2306 watch_state->request_time = request_time;
2307 watch_state->timeout = timeout;
2308 watch_state->kernel_oplock = kernel_oplock;
2309 watch_state->lease_type = get_lease_type_from_share_mode(lck->data);
2311 DBG_DEBUG("defering mid %" PRIu64 "\n", req->mid);
2313 watch_req = dbwrap_watched_watch_send(watch_state,
2314 req->sconn->ev_ctx,
2315 lck->data->record,
2316 (struct server_id){0});
2317 if (watch_req == NULL) {
2318 exit_server("Could not watch share mode record");
2320 tevent_req_set_callback(watch_req, defer_open_done, watch_state);
2322 ok = tevent_req_set_endtime(watch_req, req->sconn->ev_ctx, abs_timeout);
2323 if (!ok) {
2324 exit_server("tevent_req_set_endtime failed");
2327 ok = push_deferred_open_message_smb(req, request_time, timeout,
2328 open_rec->id, open_rec);
2329 if (!ok) {
2330 TALLOC_FREE(lck);
2331 exit_server("push_deferred_open_message_smb failed");
2335 static void defer_open_done(struct tevent_req *req)
2337 struct defer_open_state *state = tevent_req_callback_data(
2338 req, struct defer_open_state);
2339 struct tevent_req *watch_req = NULL;
2340 struct share_mode_lock *lck = NULL;
2341 bool schedule_req = true;
2342 struct timeval timeout;
2343 NTSTATUS status;
2344 bool ok;
2346 status = dbwrap_watched_watch_recv(req, talloc_tos(), NULL, NULL,
2347 NULL);
2348 TALLOC_FREE(req);
2349 if (!NT_STATUS_IS_OK(status)) {
2350 DEBUG(5, ("dbwrap_watched_watch_recv returned %s\n",
2351 nt_errstr(status)));
2353 * Even if it failed, retry anyway. TODO: We need a way to
2354 * tell a re-scheduled open about that error.
2356 if (NT_STATUS_EQUAL(status, NT_STATUS_IO_TIMEOUT) &&
2357 state->kernel_oplock)
2360 * If we reschedule but the kernel oplock is still hold
2361 * we would block in the second open as that will be a
2362 * blocking open attempt.
2364 exit_server("Kernel oplock holder didn't "
2365 "respond to break message");
2369 if (state->kernel_oplock) {
2370 lck = get_existing_share_mode_lock(talloc_tos(), state->file_id);
2371 if (lck != NULL) {
2372 uint32_t lease_type;
2374 lease_type = get_lease_type_from_share_mode(lck->data);
2376 if ((lease_type != 0) &&
2377 (lease_type == state->lease_type))
2379 DBG_DEBUG("Unchanged lease: %" PRIu32 "\n",
2380 lease_type);
2381 schedule_req = false;
2386 if (schedule_req) {
2387 DBG_DEBUG("scheduling mid %" PRIu64 "\n", state->mid);
2389 ok = schedule_deferred_open_message_smb(state->xconn,
2390 state->mid);
2391 if (!ok) {
2392 exit_server("schedule_deferred_open_message_smb failed");
2394 TALLOC_FREE(lck);
2395 TALLOC_FREE(state);
2396 return;
2399 DBG_DEBUG("Keep waiting for oplock release for [%s/%s%s] "
2400 "mid: %" PRIu64 "\n",
2401 lck->data->servicepath,
2402 lck->data->base_name,
2403 lck->data->stream_name ? lck->data->stream_name : "",
2404 state->mid);
2406 watch_req = dbwrap_watched_watch_send(state,
2407 state->xconn->ev_ctx,
2408 lck->data->record,
2409 (struct server_id){0});
2410 if (watch_req == NULL) {
2411 exit_server("Could not watch share mode record");
2413 tevent_req_set_callback(watch_req, defer_open_done, state);
2415 timeout = timeval_sum(&state->request_time, &state->timeout);
2416 ok = tevent_req_set_endtime(watch_req, state->xconn->ev_ctx, timeout);
2417 if (!ok) {
2418 exit_server("tevent_req_set_endtime failed");
2421 TALLOC_FREE(lck);
2425 * Reschedule an open for immediate execution
2427 static void retry_open(struct timeval request_time,
2428 struct smb_request *req,
2429 struct file_id id)
2431 struct deferred_open_record *open_rec = NULL;
2432 bool ok;
2434 DBG_DEBUG("request time [%s] mid [%" PRIu64 "] file_id [%s]\n",
2435 timeval_string(talloc_tos(), &request_time, false),
2436 req->mid,
2437 file_id_string_tos(&id));
2439 open_rec = deferred_open_record_create(false, false, id);
2440 if (open_rec == NULL) {
2441 exit_server("talloc failed");
2444 ok = push_deferred_open_message_smb(req,
2445 request_time,
2446 timeval_set(0, 0),
2448 open_rec);
2449 if (!ok) {
2450 exit_server("push_deferred_open_message_smb failed");
2453 ok = schedule_deferred_open_message_smb(req->xconn, req->mid);
2454 if (!ok) {
2455 exit_server("schedule_deferred_open_message_smb failed");
2459 /****************************************************************************
2460 On overwrite open ensure that the attributes match.
2461 ****************************************************************************/
2463 static bool open_match_attributes(connection_struct *conn,
2464 uint32_t old_dos_attr,
2465 uint32_t new_dos_attr,
2466 mode_t existing_unx_mode,
2467 mode_t new_unx_mode,
2468 mode_t *returned_unx_mode)
2470 uint32_t noarch_old_dos_attr, noarch_new_dos_attr;
2472 noarch_old_dos_attr = (old_dos_attr & ~FILE_ATTRIBUTE_ARCHIVE);
2473 noarch_new_dos_attr = (new_dos_attr & ~FILE_ATTRIBUTE_ARCHIVE);
2475 if((noarch_old_dos_attr == 0 && noarch_new_dos_attr != 0) ||
2476 (noarch_old_dos_attr != 0 && ((noarch_old_dos_attr & noarch_new_dos_attr) == noarch_old_dos_attr))) {
2477 *returned_unx_mode = new_unx_mode;
2478 } else {
2479 *returned_unx_mode = (mode_t)0;
2482 DEBUG(10,("open_match_attributes: old_dos_attr = 0x%x, "
2483 "existing_unx_mode = 0%o, new_dos_attr = 0x%x "
2484 "returned_unx_mode = 0%o\n",
2485 (unsigned int)old_dos_attr,
2486 (unsigned int)existing_unx_mode,
2487 (unsigned int)new_dos_attr,
2488 (unsigned int)*returned_unx_mode ));
2490 /* If we're mapping SYSTEM and HIDDEN ensure they match. */
2491 if (lp_map_system(SNUM(conn)) || lp_store_dos_attributes(SNUM(conn))) {
2492 if ((old_dos_attr & FILE_ATTRIBUTE_SYSTEM) &&
2493 !(new_dos_attr & FILE_ATTRIBUTE_SYSTEM)) {
2494 return False;
2497 if (lp_map_hidden(SNUM(conn)) || lp_store_dos_attributes(SNUM(conn))) {
2498 if ((old_dos_attr & FILE_ATTRIBUTE_HIDDEN) &&
2499 !(new_dos_attr & FILE_ATTRIBUTE_HIDDEN)) {
2500 return False;
2503 return True;
2506 /****************************************************************************
2507 Special FCB or DOS processing in the case of a sharing violation.
2508 Try and find a duplicated file handle.
2509 ****************************************************************************/
2511 static NTSTATUS fcb_or_dos_open(struct smb_request *req,
2512 connection_struct *conn,
2513 files_struct *fsp_to_dup_into,
2514 const struct smb_filename *smb_fname,
2515 struct file_id id,
2516 uint16_t file_pid,
2517 uint64_t vuid,
2518 uint32_t access_mask,
2519 uint32_t share_access,
2520 uint32_t create_options)
2522 files_struct *fsp;
2524 DEBUG(5,("fcb_or_dos_open: attempting old open semantics for "
2525 "file %s.\n", smb_fname_str_dbg(smb_fname)));
2527 for(fsp = file_find_di_first(conn->sconn, id); fsp;
2528 fsp = file_find_di_next(fsp)) {
2530 DEBUG(10,("fcb_or_dos_open: checking file %s, fd = %d, "
2531 "vuid = %llu, file_pid = %u, private_options = 0x%x "
2532 "access_mask = 0x%x\n", fsp_str_dbg(fsp),
2533 fsp->fh->fd, (unsigned long long)fsp->vuid,
2534 (unsigned int)fsp->file_pid,
2535 (unsigned int)fsp->fh->private_options,
2536 (unsigned int)fsp->access_mask ));
2538 if (fsp != fsp_to_dup_into &&
2539 fsp->fh->fd != -1 &&
2540 fsp->vuid == vuid &&
2541 fsp->file_pid == file_pid &&
2542 (fsp->fh->private_options & (NTCREATEX_OPTIONS_PRIVATE_DENY_DOS |
2543 NTCREATEX_OPTIONS_PRIVATE_DENY_FCB)) &&
2544 (fsp->access_mask & FILE_WRITE_DATA) &&
2545 strequal(fsp->fsp_name->base_name, smb_fname->base_name) &&
2546 strequal(fsp->fsp_name->stream_name,
2547 smb_fname->stream_name)) {
2548 DEBUG(10,("fcb_or_dos_open: file match\n"));
2549 break;
2553 if (!fsp) {
2554 return NT_STATUS_NOT_FOUND;
2557 /* quite an insane set of semantics ... */
2558 if (is_executable(smb_fname->base_name) &&
2559 (fsp->fh->private_options & NTCREATEX_OPTIONS_PRIVATE_DENY_DOS)) {
2560 DEBUG(10,("fcb_or_dos_open: file fail due to is_executable.\n"));
2561 return NT_STATUS_INVALID_PARAMETER;
2564 /* We need to duplicate this fsp. */
2565 return dup_file_fsp(req, fsp, access_mask, share_access,
2566 create_options, fsp_to_dup_into);
2569 static void schedule_defer_open(struct share_mode_lock *lck,
2570 struct file_id id,
2571 struct timeval request_time,
2572 struct smb_request *req,
2573 bool kernel_oplock)
2575 /* This is a relative time, added to the absolute
2576 request_time value to get the absolute timeout time.
2577 Note that if this is the second or greater time we enter
2578 this codepath for this particular request mid then
2579 request_time is left as the absolute time of the *first*
2580 time this request mid was processed. This is what allows
2581 the request to eventually time out. */
2583 struct timeval timeout;
2585 /* Normally the smbd we asked should respond within
2586 * OPLOCK_BREAK_TIMEOUT seconds regardless of whether
2587 * the client did, give twice the timeout as a safety
2588 * measure here in case the other smbd is stuck
2589 * somewhere else. */
2591 timeout = timeval_set(OPLOCK_BREAK_TIMEOUT*2, 0);
2593 if (request_timed_out(request_time, timeout)) {
2594 return;
2597 defer_open(lck, request_time, timeout, req, true, kernel_oplock, id);
2600 /****************************************************************************
2601 Reschedule an open call that went asynchronous.
2602 ****************************************************************************/
2604 static void schedule_async_open_timer(struct tevent_context *ev,
2605 struct tevent_timer *te,
2606 struct timeval current_time,
2607 void *private_data)
2609 exit_server("async open timeout");
2612 static void schedule_async_open(struct timeval request_time,
2613 struct smb_request *req)
2615 struct deferred_open_record *open_rec = NULL;
2616 struct timeval timeout = timeval_set(20, 0);
2617 bool ok;
2619 if (request_timed_out(request_time, timeout)) {
2620 return;
2623 open_rec = deferred_open_record_create(false, true, (struct file_id){0});
2624 if (open_rec == NULL) {
2625 exit_server("deferred_open_record_create failed");
2628 ok = push_deferred_open_message_smb(req, request_time, timeout,
2629 (struct file_id){0}, open_rec);
2630 if (!ok) {
2631 exit_server("push_deferred_open_message_smb failed");
2634 open_rec->te = tevent_add_timer(req->sconn->ev_ctx,
2635 req,
2636 timeval_current_ofs(20, 0),
2637 schedule_async_open_timer,
2638 open_rec);
2639 if (open_rec->te == NULL) {
2640 exit_server("tevent_add_timer failed");
2644 /****************************************************************************
2645 Work out what access_mask to use from what the client sent us.
2646 ****************************************************************************/
2648 static NTSTATUS smbd_calculate_maximum_allowed_access(
2649 connection_struct *conn,
2650 const struct smb_filename *smb_fname,
2651 bool use_privs,
2652 uint32_t *p_access_mask)
2654 struct security_descriptor *sd;
2655 uint32_t access_granted;
2656 NTSTATUS status;
2658 if (!use_privs && (get_current_uid(conn) == (uid_t)0)) {
2659 *p_access_mask |= FILE_GENERIC_ALL;
2660 return NT_STATUS_OK;
2663 status = SMB_VFS_GET_NT_ACL(conn, smb_fname,
2664 (SECINFO_OWNER |
2665 SECINFO_GROUP |
2666 SECINFO_DACL),
2667 talloc_tos(), &sd);
2669 if (NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
2671 * File did not exist
2673 *p_access_mask = FILE_GENERIC_ALL;
2674 return NT_STATUS_OK;
2676 if (!NT_STATUS_IS_OK(status)) {
2677 DEBUG(10,("Could not get acl on file %s: %s\n",
2678 smb_fname_str_dbg(smb_fname),
2679 nt_errstr(status)));
2680 return NT_STATUS_ACCESS_DENIED;
2684 * If we can access the path to this file, by
2685 * default we have FILE_READ_ATTRIBUTES from the
2686 * containing directory. See the section:
2687 * "Algorithm to Check Access to an Existing File"
2688 * in MS-FSA.pdf.
2690 * se_file_access_check()
2691 * also takes care of owner WRITE_DAC and READ_CONTROL.
2693 status = se_file_access_check(sd,
2694 get_current_nttok(conn),
2695 use_privs,
2696 (*p_access_mask & ~FILE_READ_ATTRIBUTES),
2697 &access_granted);
2699 TALLOC_FREE(sd);
2701 if (!NT_STATUS_IS_OK(status)) {
2702 DEBUG(10, ("Access denied on file %s: "
2703 "when calculating maximum access\n",
2704 smb_fname_str_dbg(smb_fname)));
2705 return NT_STATUS_ACCESS_DENIED;
2707 *p_access_mask = (access_granted | FILE_READ_ATTRIBUTES);
2709 if (!(access_granted & DELETE_ACCESS)) {
2710 if (can_delete_file_in_directory(conn, smb_fname)) {
2711 *p_access_mask |= DELETE_ACCESS;
2715 return NT_STATUS_OK;
2718 NTSTATUS smbd_calculate_access_mask(connection_struct *conn,
2719 const struct smb_filename *smb_fname,
2720 bool use_privs,
2721 uint32_t access_mask,
2722 uint32_t *access_mask_out)
2724 NTSTATUS status;
2725 uint32_t orig_access_mask = access_mask;
2726 uint32_t rejected_share_access;
2728 if (access_mask & SEC_MASK_INVALID) {
2729 DBG_DEBUG("access_mask [%8x] contains invalid bits\n",
2730 access_mask);
2731 return NT_STATUS_ACCESS_DENIED;
2735 * Convert GENERIC bits to specific bits.
2738 se_map_generic(&access_mask, &file_generic_mapping);
2740 /* Calculate MAXIMUM_ALLOWED_ACCESS if requested. */
2741 if (access_mask & MAXIMUM_ALLOWED_ACCESS) {
2743 status = smbd_calculate_maximum_allowed_access(
2744 conn, smb_fname, use_privs, &access_mask);
2746 if (!NT_STATUS_IS_OK(status)) {
2747 return status;
2750 access_mask &= conn->share_access;
2753 rejected_share_access = access_mask & ~(conn->share_access);
2755 if (rejected_share_access) {
2756 DEBUG(10, ("smbd_calculate_access_mask: Access denied on "
2757 "file %s: rejected by share access mask[0x%08X] "
2758 "orig[0x%08X] mapped[0x%08X] reject[0x%08X]\n",
2759 smb_fname_str_dbg(smb_fname),
2760 conn->share_access,
2761 orig_access_mask, access_mask,
2762 rejected_share_access));
2763 return NT_STATUS_ACCESS_DENIED;
2766 *access_mask_out = access_mask;
2767 return NT_STATUS_OK;
2770 /****************************************************************************
2771 Remove the deferred open entry under lock.
2772 ****************************************************************************/
2774 /****************************************************************************
2775 Return true if this is a state pointer to an asynchronous create.
2776 ****************************************************************************/
2778 bool is_deferred_open_async(const struct deferred_open_record *rec)
2780 return rec->async_open;
2783 static bool clear_ads(uint32_t create_disposition)
2785 bool ret = false;
2787 switch (create_disposition) {
2788 case FILE_SUPERSEDE:
2789 case FILE_OVERWRITE_IF:
2790 case FILE_OVERWRITE:
2791 ret = true;
2792 break;
2793 default:
2794 break;
2796 return ret;
2799 static int disposition_to_open_flags(uint32_t create_disposition)
2801 int ret = 0;
2804 * Currently we're using FILE_SUPERSEDE as the same as
2805 * FILE_OVERWRITE_IF but they really are
2806 * different. FILE_SUPERSEDE deletes an existing file
2807 * (requiring delete access) then recreates it.
2810 switch (create_disposition) {
2811 case FILE_SUPERSEDE:
2812 case FILE_OVERWRITE_IF:
2814 * If file exists replace/overwrite. If file doesn't
2815 * exist create.
2817 ret = O_CREAT|O_TRUNC;
2818 break;
2820 case FILE_OPEN:
2822 * If file exists open. If file doesn't exist error.
2824 ret = 0;
2825 break;
2827 case FILE_OVERWRITE:
2829 * If file exists overwrite. If file doesn't exist
2830 * error.
2832 ret = O_TRUNC;
2833 break;
2835 case FILE_CREATE:
2837 * If file exists error. If file doesn't exist create.
2839 ret = O_CREAT|O_EXCL;
2840 break;
2842 case FILE_OPEN_IF:
2844 * If file exists open. If file doesn't exist create.
2846 ret = O_CREAT;
2847 break;
2849 return ret;
2852 static int calculate_open_access_flags(uint32_t access_mask,
2853 uint32_t private_flags)
2855 bool need_write, need_read;
2858 * Note that we ignore the append flag as append does not
2859 * mean the same thing under DOS and Unix.
2862 need_write = (access_mask & (FILE_WRITE_DATA | FILE_APPEND_DATA));
2863 if (!need_write) {
2864 return O_RDONLY;
2867 /* DENY_DOS opens are always underlying read-write on the
2868 file handle, no matter what the requested access mask
2869 says. */
2871 need_read =
2872 ((private_flags & NTCREATEX_OPTIONS_PRIVATE_DENY_DOS) ||
2873 access_mask & (FILE_READ_ATTRIBUTES|FILE_READ_DATA|
2874 FILE_READ_EA|FILE_EXECUTE));
2876 if (!need_read) {
2877 return O_WRONLY;
2879 return O_RDWR;
2882 /****************************************************************************
2883 Open a file with a share mode. Passed in an already created files_struct *.
2884 ****************************************************************************/
2886 static NTSTATUS open_file_ntcreate(connection_struct *conn,
2887 struct smb_request *req,
2888 uint32_t access_mask, /* access bits (FILE_READ_DATA etc.) */
2889 uint32_t share_access, /* share constants (FILE_SHARE_READ etc) */
2890 uint32_t create_disposition, /* FILE_OPEN_IF etc. */
2891 uint32_t create_options, /* options such as delete on close. */
2892 uint32_t new_dos_attributes, /* attributes used for new file. */
2893 int oplock_request, /* internal Samba oplock codes. */
2894 struct smb2_lease *lease,
2895 /* Information (FILE_EXISTS etc.) */
2896 uint32_t private_flags, /* Samba specific flags. */
2897 int *pinfo,
2898 files_struct *fsp)
2900 struct smb_filename *smb_fname = fsp->fsp_name;
2901 int flags=0;
2902 int flags2=0;
2903 bool file_existed = VALID_STAT(smb_fname->st);
2904 bool def_acl = False;
2905 bool posix_open = False;
2906 bool new_file_created = False;
2907 bool first_open_attempt = true;
2908 NTSTATUS fsp_open = NT_STATUS_ACCESS_DENIED;
2909 mode_t new_unx_mode = (mode_t)0;
2910 mode_t unx_mode = (mode_t)0;
2911 int info;
2912 uint32_t existing_dos_attributes = 0;
2913 struct timeval request_time = timeval_zero();
2914 struct share_mode_lock *lck = NULL;
2915 uint32_t open_access_mask = access_mask;
2916 NTSTATUS status;
2917 char *parent_dir;
2918 SMB_STRUCT_STAT saved_stat = smb_fname->st;
2919 struct timespec old_write_time;
2920 struct file_id id;
2922 if (conn->printer) {
2924 * Printers are handled completely differently.
2925 * Most of the passed parameters are ignored.
2928 if (pinfo) {
2929 *pinfo = FILE_WAS_CREATED;
2932 DEBUG(10, ("open_file_ntcreate: printer open fname=%s\n",
2933 smb_fname_str_dbg(smb_fname)));
2935 if (!req) {
2936 DEBUG(0,("open_file_ntcreate: printer open without "
2937 "an SMB request!\n"));
2938 return NT_STATUS_INTERNAL_ERROR;
2941 return print_spool_open(fsp, smb_fname->base_name,
2942 req->vuid);
2945 if (!parent_dirname(talloc_tos(), smb_fname->base_name, &parent_dir,
2946 NULL)) {
2947 return NT_STATUS_NO_MEMORY;
2950 if (new_dos_attributes & FILE_FLAG_POSIX_SEMANTICS) {
2951 posix_open = True;
2952 unx_mode = (mode_t)(new_dos_attributes & ~FILE_FLAG_POSIX_SEMANTICS);
2953 new_dos_attributes = 0;
2954 } else {
2955 /* Windows allows a new file to be created and
2956 silently removes a FILE_ATTRIBUTE_DIRECTORY
2957 sent by the client. Do the same. */
2959 new_dos_attributes &= ~FILE_ATTRIBUTE_DIRECTORY;
2961 /* We add FILE_ATTRIBUTE_ARCHIVE to this as this mode is only used if the file is
2962 * created new. */
2963 unx_mode = unix_mode(conn, new_dos_attributes | FILE_ATTRIBUTE_ARCHIVE,
2964 smb_fname, parent_dir);
2967 DEBUG(10, ("open_file_ntcreate: fname=%s, dos_attrs=0x%x "
2968 "access_mask=0x%x share_access=0x%x "
2969 "create_disposition = 0x%x create_options=0x%x "
2970 "unix mode=0%o oplock_request=%d private_flags = 0x%x\n",
2971 smb_fname_str_dbg(smb_fname), new_dos_attributes,
2972 access_mask, share_access, create_disposition,
2973 create_options, (unsigned int)unx_mode, oplock_request,
2974 (unsigned int)private_flags));
2976 if (req == NULL) {
2977 /* Ensure req == NULL means INTERNAL_OPEN_ONLY */
2978 SMB_ASSERT(((oplock_request & INTERNAL_OPEN_ONLY) != 0));
2979 } else {
2980 /* And req != NULL means no INTERNAL_OPEN_ONLY */
2981 SMB_ASSERT(((oplock_request & INTERNAL_OPEN_ONLY) == 0));
2985 * Only non-internal opens can be deferred at all
2988 if (req) {
2989 struct deferred_open_record *open_rec;
2990 if (get_deferred_open_message_state(req,
2991 &request_time,
2992 &open_rec)) {
2993 /* Remember the absolute time of the original
2994 request with this mid. We'll use it later to
2995 see if this has timed out. */
2997 /* If it was an async create retry, the file
2998 didn't exist. */
3000 if (is_deferred_open_async(open_rec)) {
3001 SET_STAT_INVALID(smb_fname->st);
3002 file_existed = false;
3005 /* Ensure we don't reprocess this message. */
3006 remove_deferred_open_message_smb(req->xconn, req->mid);
3008 first_open_attempt = false;
3012 if (!posix_open) {
3013 new_dos_attributes &= SAMBA_ATTRIBUTES_MASK;
3014 if (file_existed) {
3016 * Only use strored DOS attributes for checks
3017 * against requested attributes (below via
3018 * open_match_attributes()), cf bug #11992
3019 * for details. -slow
3021 uint32_t attr = 0;
3023 status = SMB_VFS_GET_DOS_ATTRIBUTES(conn, smb_fname, &attr);
3024 if (NT_STATUS_IS_OK(status)) {
3025 existing_dos_attributes = attr;
3030 /* ignore any oplock requests if oplocks are disabled */
3031 if (!lp_oplocks(SNUM(conn)) ||
3032 IS_VETO_OPLOCK_PATH(conn, smb_fname->base_name)) {
3033 /* Mask off everything except the private Samba bits. */
3034 oplock_request &= SAMBA_PRIVATE_OPLOCK_MASK;
3037 /* this is for OS/2 long file names - say we don't support them */
3038 if (req != NULL && !req->posix_pathnames &&
3039 strstr(smb_fname->base_name,".+,;=[].")) {
3040 /* OS/2 Workplace shell fix may be main code stream in a later
3041 * release. */
3042 DEBUG(5,("open_file_ntcreate: OS/2 long filenames are not "
3043 "supported.\n"));
3044 if (use_nt_status()) {
3045 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3047 return NT_STATUS_DOS(ERRDOS, ERRcannotopen);
3050 switch( create_disposition ) {
3051 case FILE_OPEN:
3052 /* If file exists open. If file doesn't exist error. */
3053 if (!file_existed) {
3054 DEBUG(5,("open_file_ntcreate: FILE_OPEN "
3055 "requested for file %s and file "
3056 "doesn't exist.\n",
3057 smb_fname_str_dbg(smb_fname)));
3058 errno = ENOENT;
3059 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3061 break;
3063 case FILE_OVERWRITE:
3064 /* If file exists overwrite. If file doesn't exist
3065 * error. */
3066 if (!file_existed) {
3067 DEBUG(5,("open_file_ntcreate: FILE_OVERWRITE "
3068 "requested for file %s and file "
3069 "doesn't exist.\n",
3070 smb_fname_str_dbg(smb_fname) ));
3071 errno = ENOENT;
3072 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3074 break;
3076 case FILE_CREATE:
3077 /* If file exists error. If file doesn't exist
3078 * create. */
3079 if (file_existed) {
3080 DEBUG(5,("open_file_ntcreate: FILE_CREATE "
3081 "requested for file %s and file "
3082 "already exists.\n",
3083 smb_fname_str_dbg(smb_fname)));
3084 if (S_ISDIR(smb_fname->st.st_ex_mode)) {
3085 errno = EISDIR;
3086 } else {
3087 errno = EEXIST;
3089 return map_nt_error_from_unix(errno);
3091 break;
3093 case FILE_SUPERSEDE:
3094 case FILE_OVERWRITE_IF:
3095 case FILE_OPEN_IF:
3096 break;
3097 default:
3098 return NT_STATUS_INVALID_PARAMETER;
3101 flags2 = disposition_to_open_flags(create_disposition);
3103 /* We only care about matching attributes on file exists and
3104 * overwrite. */
3106 if (!posix_open && file_existed &&
3107 ((create_disposition == FILE_OVERWRITE) ||
3108 (create_disposition == FILE_OVERWRITE_IF))) {
3109 if (!open_match_attributes(conn, existing_dos_attributes,
3110 new_dos_attributes,
3111 smb_fname->st.st_ex_mode,
3112 unx_mode, &new_unx_mode)) {
3113 DEBUG(5,("open_file_ntcreate: attributes missmatch "
3114 "for file %s (%x %x) (0%o, 0%o)\n",
3115 smb_fname_str_dbg(smb_fname),
3116 existing_dos_attributes,
3117 new_dos_attributes,
3118 (unsigned int)smb_fname->st.st_ex_mode,
3119 (unsigned int)unx_mode ));
3120 errno = EACCES;
3121 return NT_STATUS_ACCESS_DENIED;
3125 status = smbd_calculate_access_mask(conn, smb_fname,
3126 false,
3127 access_mask,
3128 &access_mask);
3129 if (!NT_STATUS_IS_OK(status)) {
3130 DEBUG(10, ("open_file_ntcreate: smbd_calculate_access_mask "
3131 "on file %s returned %s\n",
3132 smb_fname_str_dbg(smb_fname), nt_errstr(status)));
3133 return status;
3136 open_access_mask = access_mask;
3138 if (flags2 & O_TRUNC) {
3139 open_access_mask |= FILE_WRITE_DATA; /* This will cause oplock breaks. */
3142 DEBUG(10, ("open_file_ntcreate: fname=%s, after mapping "
3143 "access_mask=0x%x\n", smb_fname_str_dbg(smb_fname),
3144 access_mask));
3147 * Note that we ignore the append flag as append does not
3148 * mean the same thing under DOS and Unix.
3151 flags = calculate_open_access_flags(access_mask, private_flags);
3154 * Currently we only look at FILE_WRITE_THROUGH for create options.
3157 #if defined(O_SYNC)
3158 if ((create_options & FILE_WRITE_THROUGH) && lp_strict_sync(SNUM(conn))) {
3159 flags2 |= O_SYNC;
3161 #endif /* O_SYNC */
3163 if (posix_open && (access_mask & FILE_APPEND_DATA)) {
3164 flags2 |= O_APPEND;
3167 if (!posix_open && !CAN_WRITE(conn)) {
3169 * We should really return a permission denied error if either
3170 * O_CREAT or O_TRUNC are set, but for compatibility with
3171 * older versions of Samba we just AND them out.
3173 flags2 &= ~(O_CREAT|O_TRUNC);
3176 if (first_open_attempt && lp_kernel_oplocks(SNUM(conn))) {
3178 * With kernel oplocks the open breaking an oplock
3179 * blocks until the oplock holder has given up the
3180 * oplock or closed the file. We prevent this by first
3181 * trying to open the file with O_NONBLOCK (see "man
3182 * fcntl" on Linux). For the second try, triggered by
3183 * an oplock break response, we do not need this
3184 * anymore.
3186 * This is true under the assumption that only Samba
3187 * requests kernel oplocks. Once someone else like
3188 * NFSv4 starts to use that API, we will have to
3189 * modify this by communicating with the NFSv4 server.
3191 flags2 |= O_NONBLOCK;
3195 * Ensure we can't write on a read-only share or file.
3198 if (flags != O_RDONLY && file_existed &&
3199 (!CAN_WRITE(conn) || IS_DOS_READONLY(existing_dos_attributes))) {
3200 DEBUG(5,("open_file_ntcreate: write access requested for "
3201 "file %s on read only %s\n",
3202 smb_fname_str_dbg(smb_fname),
3203 !CAN_WRITE(conn) ? "share" : "file" ));
3204 errno = EACCES;
3205 return NT_STATUS_ACCESS_DENIED;
3208 fsp->file_id = vfs_file_id_from_sbuf(conn, &smb_fname->st);
3209 fsp->share_access = share_access;
3210 fsp->fh->private_options = private_flags;
3211 fsp->access_mask = open_access_mask; /* We change this to the
3212 * requested access_mask after
3213 * the open is done. */
3214 if (posix_open) {
3215 fsp->posix_flags |= FSP_POSIX_FLAGS_ALL;
3218 if (timeval_is_zero(&request_time)) {
3219 request_time = fsp->open_time;
3223 * Ensure we pay attention to default ACLs on directories if required.
3226 if ((flags2 & O_CREAT) && lp_inherit_acls(SNUM(conn)) &&
3227 (def_acl = directory_has_default_acl(conn, parent_dir))) {
3228 unx_mode = (0777 & lp_create_mask(SNUM(conn)));
3231 DEBUG(4,("calling open_file with flags=0x%X flags2=0x%X mode=0%o, "
3232 "access_mask = 0x%x, open_access_mask = 0x%x\n",
3233 (unsigned int)flags, (unsigned int)flags2,
3234 (unsigned int)unx_mode, (unsigned int)access_mask,
3235 (unsigned int)open_access_mask));
3237 fsp_open = open_file(fsp, conn, req, parent_dir,
3238 flags|flags2, unx_mode, access_mask,
3239 open_access_mask, &new_file_created);
3241 if (NT_STATUS_EQUAL(fsp_open, NT_STATUS_NETWORK_BUSY)) {
3242 bool delay;
3245 * This handles the kernel oplock case:
3247 * the file has an active kernel oplock and the open() returned
3248 * EWOULDBLOCK/EAGAIN which maps to NETWORK_BUSY.
3250 * "Samba locking.tdb oplocks" are handled below after acquiring
3251 * the sharemode lock with get_share_mode_lock().
3253 if (file_existed && S_ISFIFO(fsp->fsp_name->st.st_ex_mode)) {
3254 DEBUG(10, ("FIFO busy\n"));
3255 return NT_STATUS_NETWORK_BUSY;
3257 if (req == NULL) {
3258 DEBUG(10, ("Internal open busy\n"));
3259 return NT_STATUS_NETWORK_BUSY;
3263 * From here on we assume this is an oplock break triggered
3266 lck = get_existing_share_mode_lock(talloc_tos(), fsp->file_id);
3267 if (lck == NULL) {
3268 retry_open(request_time, req, fsp->file_id);
3269 DEBUG(10, ("No share mode lock found after "
3270 "EWOULDBLOCK, retrying sync\n"));
3271 return NT_STATUS_SHARING_VIOLATION;
3274 if (!validate_oplock_types(lck)) {
3275 smb_panic("validate_oplock_types failed");
3278 delay = delay_for_oplock(fsp, 0, lease, lck, false,
3279 create_disposition,
3280 first_open_attempt);
3281 if (delay) {
3282 schedule_defer_open(lck, fsp->file_id, request_time,
3283 req, true);
3284 TALLOC_FREE(lck);
3285 DEBUG(10, ("Sent oplock break request to kernel "
3286 "oplock holder\n"));
3287 return NT_STATUS_SHARING_VIOLATION;
3291 * No oplock from Samba around. Immediately retry with
3292 * a blocking open.
3294 retry_open(request_time, req, fsp->file_id);
3296 TALLOC_FREE(lck);
3297 DEBUG(10, ("No Samba oplock around after EWOULDBLOCK. "
3298 "Retrying sync\n"));
3299 return NT_STATUS_SHARING_VIOLATION;
3302 if (!NT_STATUS_IS_OK(fsp_open)) {
3303 if (NT_STATUS_EQUAL(fsp_open, NT_STATUS_RETRY)) {
3304 schedule_async_open(request_time, req);
3306 return fsp_open;
3309 if (new_file_created) {
3311 * As we atomically create using O_CREAT|O_EXCL,
3312 * then if new_file_created is true, then
3313 * file_existed *MUST* have been false (even
3314 * if the file was previously detected as being
3315 * there).
3317 file_existed = false;
3320 if (file_existed && !check_same_dev_ino(&saved_stat, &smb_fname->st)) {
3322 * The file did exist, but some other (local or NFS)
3323 * process either renamed/unlinked and re-created the
3324 * file with different dev/ino after we walked the path,
3325 * but before we did the open. We could retry the
3326 * open but it's a rare enough case it's easier to
3327 * just fail the open to prevent creating any problems
3328 * in the open file db having the wrong dev/ino key.
3330 fd_close(fsp);
3331 DEBUG(1,("open_file_ntcreate: file %s - dev/ino mismatch. "
3332 "Old (dev=0x%llu, ino =0x%llu). "
3333 "New (dev=0x%llu, ino=0x%llu). Failing open "
3334 " with NT_STATUS_ACCESS_DENIED.\n",
3335 smb_fname_str_dbg(smb_fname),
3336 (unsigned long long)saved_stat.st_ex_dev,
3337 (unsigned long long)saved_stat.st_ex_ino,
3338 (unsigned long long)smb_fname->st.st_ex_dev,
3339 (unsigned long long)smb_fname->st.st_ex_ino));
3340 return NT_STATUS_ACCESS_DENIED;
3343 old_write_time = smb_fname->st.st_ex_mtime;
3346 * Deal with the race condition where two smbd's detect the
3347 * file doesn't exist and do the create at the same time. One
3348 * of them will win and set a share mode, the other (ie. this
3349 * one) should check if the requested share mode for this
3350 * create is allowed.
3354 * Now the file exists and fsp is successfully opened,
3355 * fsp->dev and fsp->inode are valid and should replace the
3356 * dev=0,inode=0 from a non existent file. Spotted by
3357 * Nadav Danieli <nadavd@exanet.com>. JRA.
3360 id = fsp->file_id;
3362 lck = get_share_mode_lock(talloc_tos(), id,
3363 conn->connectpath,
3364 smb_fname, &old_write_time);
3366 if (lck == NULL) {
3367 DEBUG(0, ("open_file_ntcreate: Could not get share "
3368 "mode lock for %s\n",
3369 smb_fname_str_dbg(smb_fname)));
3370 fd_close(fsp);
3371 return NT_STATUS_SHARING_VIOLATION;
3374 /* Get the types we need to examine. */
3375 if (!validate_oplock_types(lck)) {
3376 smb_panic("validate_oplock_types failed");
3379 if (has_delete_on_close(lck, fsp->name_hash)) {
3380 TALLOC_FREE(lck);
3381 fd_close(fsp);
3382 return NT_STATUS_DELETE_PENDING;
3385 status = open_mode_check(conn, lck,
3386 access_mask, share_access);
3388 if (NT_STATUS_EQUAL(status, NT_STATUS_SHARING_VIOLATION) ||
3389 (lck->data->num_share_modes > 0)) {
3391 * This comes from ancient times out of open_mode_check. I
3392 * have no clue whether this is still necessary. I can't think
3393 * of a case where this would actually matter further down in
3394 * this function. I leave it here for further investigation
3395 * :-)
3397 file_existed = true;
3400 if (req != NULL) {
3402 * Handle oplocks, deferring the request if delay_for_oplock()
3403 * triggered a break message and we have to wait for the break
3404 * response.
3406 bool delay;
3407 bool sharing_violation = NT_STATUS_EQUAL(
3408 status, NT_STATUS_SHARING_VIOLATION);
3410 delay = delay_for_oplock(fsp, oplock_request, lease, lck,
3411 sharing_violation,
3412 create_disposition,
3413 first_open_attempt);
3414 if (delay) {
3415 schedule_defer_open(lck, fsp->file_id,
3416 request_time, req, false);
3417 TALLOC_FREE(lck);
3418 fd_close(fsp);
3419 return NT_STATUS_SHARING_VIOLATION;
3423 if (!NT_STATUS_IS_OK(status)) {
3424 uint32_t can_access_mask;
3425 bool can_access = True;
3427 SMB_ASSERT(NT_STATUS_EQUAL(status, NT_STATUS_SHARING_VIOLATION));
3429 /* Check if this can be done with the deny_dos and fcb
3430 * calls. */
3431 if (private_flags &
3432 (NTCREATEX_OPTIONS_PRIVATE_DENY_DOS|
3433 NTCREATEX_OPTIONS_PRIVATE_DENY_FCB)) {
3434 if (req == NULL) {
3435 DEBUG(0, ("DOS open without an SMB "
3436 "request!\n"));
3437 TALLOC_FREE(lck);
3438 fd_close(fsp);
3439 return NT_STATUS_INTERNAL_ERROR;
3442 /* Use the client requested access mask here,
3443 * not the one we open with. */
3444 status = fcb_or_dos_open(req,
3445 conn,
3446 fsp,
3447 smb_fname,
3449 req->smbpid,
3450 req->vuid,
3451 access_mask,
3452 share_access,
3453 create_options);
3455 if (NT_STATUS_IS_OK(status)) {
3456 TALLOC_FREE(lck);
3457 if (pinfo) {
3458 *pinfo = FILE_WAS_OPENED;
3460 return NT_STATUS_OK;
3465 * This next line is a subtlety we need for
3466 * MS-Access. If a file open will fail due to share
3467 * permissions and also for security (access) reasons,
3468 * we need to return the access failed error, not the
3469 * share error. We can't open the file due to kernel
3470 * oplock deadlock (it's possible we failed above on
3471 * the open_mode_check()) so use a userspace check.
3474 if (flags & O_RDWR) {
3475 can_access_mask = FILE_READ_DATA|FILE_WRITE_DATA;
3476 } else if (flags & O_WRONLY) {
3477 can_access_mask = FILE_WRITE_DATA;
3478 } else {
3479 can_access_mask = FILE_READ_DATA;
3482 if (((can_access_mask & FILE_WRITE_DATA) &&
3483 !CAN_WRITE(conn)) ||
3484 !NT_STATUS_IS_OK(smbd_check_access_rights(conn,
3485 smb_fname,
3486 false,
3487 can_access_mask))) {
3488 can_access = False;
3492 * If we're returning a share violation, ensure we
3493 * cope with the braindead 1 second delay (SMB1 only).
3496 if (!(oplock_request & INTERNAL_OPEN_ONLY) &&
3497 !conn->sconn->using_smb2 &&
3498 lp_defer_sharing_violations()) {
3499 struct timeval timeout;
3500 int timeout_usecs;
3502 /* this is a hack to speed up torture tests
3503 in 'make test' */
3504 timeout_usecs = lp_parm_int(SNUM(conn),
3505 "smbd","sharedelay",
3506 SHARING_VIOLATION_USEC_WAIT);
3508 /* This is a relative time, added to the absolute
3509 request_time value to get the absolute timeout time.
3510 Note that if this is the second or greater time we enter
3511 this codepath for this particular request mid then
3512 request_time is left as the absolute time of the *first*
3513 time this request mid was processed. This is what allows
3514 the request to eventually time out. */
3516 timeout = timeval_set(0, timeout_usecs);
3518 if (!request_timed_out(request_time, timeout)) {
3519 defer_open(lck, request_time, timeout, req,
3520 false, false, id);
3524 TALLOC_FREE(lck);
3525 fd_close(fsp);
3526 if (can_access) {
3528 * We have detected a sharing violation here
3529 * so return the correct error code
3531 status = NT_STATUS_SHARING_VIOLATION;
3532 } else {
3533 status = NT_STATUS_ACCESS_DENIED;
3535 return status;
3538 /* Should we atomically (to the client at least) truncate ? */
3539 if ((!new_file_created) &&
3540 (flags2 & O_TRUNC) &&
3541 (!S_ISFIFO(fsp->fsp_name->st.st_ex_mode))) {
3542 int ret;
3544 ret = vfs_set_filelen(fsp, 0);
3545 if (ret != 0) {
3546 status = map_nt_error_from_unix(errno);
3547 TALLOC_FREE(lck);
3548 fd_close(fsp);
3549 return status;
3554 * We have the share entry *locked*.....
3557 /* Delete streams if create_disposition requires it */
3558 if (!new_file_created && clear_ads(create_disposition) &&
3559 !is_ntfs_stream_smb_fname(smb_fname)) {
3560 status = delete_all_streams(conn, smb_fname);
3561 if (!NT_STATUS_IS_OK(status)) {
3562 TALLOC_FREE(lck);
3563 fd_close(fsp);
3564 return status;
3568 /* note that we ignore failure for the following. It is
3569 basically a hack for NFS, and NFS will never set one of
3570 these only read them. Nobody but Samba can ever set a deny
3571 mode and we have already checked our more authoritative
3572 locking database for permission to set this deny mode. If
3573 the kernel refuses the operations then the kernel is wrong.
3574 note that GPFS supports it as well - jmcd */
3576 if (fsp->fh->fd != -1 && lp_kernel_share_modes(SNUM(conn))) {
3577 int ret_flock;
3579 * Beware: streams implementing VFS modules may
3580 * implement streams in a way that fsp will have the
3581 * basefile open in the fsp fd, so lacking a distinct
3582 * fd for the stream kernel_flock will apply on the
3583 * basefile which is wrong. The actual check is
3584 * deffered to the VFS module implementing the
3585 * kernel_flock call.
3587 ret_flock = SMB_VFS_KERNEL_FLOCK(fsp, share_access, access_mask);
3588 if(ret_flock == -1 ){
3590 TALLOC_FREE(lck);
3591 fd_close(fsp);
3593 return NT_STATUS_SHARING_VIOLATION;
3596 fsp->kernel_share_modes_taken = true;
3600 * At this point onwards, we can guarantee that the share entry
3601 * is locked, whether we created the file or not, and that the
3602 * deny mode is compatible with all current opens.
3606 * According to Samba4, SEC_FILE_READ_ATTRIBUTE is always granted,
3607 * but we don't have to store this - just ignore it on access check.
3609 if (conn->sconn->using_smb2) {
3611 * SMB2 doesn't return it (according to Microsoft tests).
3612 * Test Case: TestSuite_ScenarioNo009GrantedAccessTestS0
3613 * File created with access = 0x7 (Read, Write, Delete)
3614 * Query Info on file returns 0x87 (Read, Write, Delete, Read Attributes)
3616 fsp->access_mask = access_mask;
3617 } else {
3618 /* But SMB1 does. */
3619 fsp->access_mask = access_mask | FILE_READ_ATTRIBUTES;
3622 if (file_existed) {
3624 * stat opens on existing files don't get oplocks.
3625 * They can get leases.
3627 * Note that we check for stat open on the *open_access_mask*,
3628 * i.e. the access mask we actually used to do the open,
3629 * not the one the client asked for (which is in
3630 * fsp->access_mask). This is due to the fact that
3631 * FILE_OVERWRITE and FILE_OVERWRITE_IF add in O_TRUNC,
3632 * which adds FILE_WRITE_DATA to open_access_mask.
3634 if (is_stat_open(open_access_mask) && lease == NULL) {
3635 oplock_request = NO_OPLOCK;
3639 if (new_file_created) {
3640 info = FILE_WAS_CREATED;
3641 } else {
3642 if (flags2 & O_TRUNC) {
3643 info = FILE_WAS_OVERWRITTEN;
3644 } else {
3645 info = FILE_WAS_OPENED;
3649 if (pinfo) {
3650 *pinfo = info;
3654 * Setup the oplock info in both the shared memory and
3655 * file structs.
3657 status = grant_fsp_oplock_type(req, fsp, lck, oplock_request, lease);
3658 if (!NT_STATUS_IS_OK(status)) {
3659 TALLOC_FREE(lck);
3660 fd_close(fsp);
3661 return status;
3664 /* Handle strange delete on close create semantics. */
3665 if (create_options & FILE_DELETE_ON_CLOSE) {
3667 status = can_set_delete_on_close(fsp, new_dos_attributes);
3669 if (!NT_STATUS_IS_OK(status)) {
3670 /* Remember to delete the mode we just added. */
3671 del_share_mode(lck, fsp);
3672 TALLOC_FREE(lck);
3673 fd_close(fsp);
3674 return status;
3676 /* Note that here we set the *inital* delete on close flag,
3677 not the regular one. The magic gets handled in close. */
3678 fsp->initial_delete_on_close = True;
3681 if (info != FILE_WAS_OPENED) {
3682 /* Overwritten files should be initially set as archive */
3683 if ((info == FILE_WAS_OVERWRITTEN && lp_map_archive(SNUM(conn))) ||
3684 lp_store_dos_attributes(SNUM(conn))) {
3685 if (!posix_open) {
3686 if (file_set_dosmode(conn, smb_fname,
3687 new_dos_attributes | FILE_ATTRIBUTE_ARCHIVE,
3688 parent_dir, true) == 0) {
3689 unx_mode = smb_fname->st.st_ex_mode;
3695 /* Determine sparse flag. */
3696 if (posix_open) {
3697 /* POSIX opens are sparse by default. */
3698 fsp->is_sparse = true;
3699 } else {
3700 fsp->is_sparse = (file_existed &&
3701 (existing_dos_attributes & FILE_ATTRIBUTE_SPARSE));
3705 * Take care of inherited ACLs on created files - if default ACL not
3706 * selected.
3709 if (!posix_open && new_file_created && !def_acl) {
3711 int saved_errno = errno; /* We might get ENOSYS in the next
3712 * call.. */
3714 if (SMB_VFS_FCHMOD_ACL(fsp, unx_mode) == -1 &&
3715 errno == ENOSYS) {
3716 errno = saved_errno; /* Ignore ENOSYS */
3719 } else if (new_unx_mode) {
3721 int ret = -1;
3723 /* Attributes need changing. File already existed. */
3726 int saved_errno = errno; /* We might get ENOSYS in the
3727 * next call.. */
3728 ret = SMB_VFS_FCHMOD_ACL(fsp, new_unx_mode);
3730 if (ret == -1 && errno == ENOSYS) {
3731 errno = saved_errno; /* Ignore ENOSYS */
3732 } else {
3733 DEBUG(5, ("open_file_ntcreate: reset "
3734 "attributes of file %s to 0%o\n",
3735 smb_fname_str_dbg(smb_fname),
3736 (unsigned int)new_unx_mode));
3737 ret = 0; /* Don't do the fchmod below. */
3741 if ((ret == -1) &&
3742 (SMB_VFS_FCHMOD(fsp, new_unx_mode) == -1))
3743 DEBUG(5, ("open_file_ntcreate: failed to reset "
3744 "attributes of file %s to 0%o\n",
3745 smb_fname_str_dbg(smb_fname),
3746 (unsigned int)new_unx_mode));
3751 * Deal with other opens having a modified write time.
3753 struct timespec write_time = get_share_mode_write_time(lck);
3755 if (!null_timespec(write_time)) {
3756 update_stat_ex_mtime(&fsp->fsp_name->st, write_time);
3760 TALLOC_FREE(lck);
3762 return NT_STATUS_OK;
3765 static NTSTATUS mkdir_internal(connection_struct *conn,
3766 struct smb_filename *smb_dname,
3767 uint32_t file_attributes)
3769 mode_t mode;
3770 char *parent_dir = NULL;
3771 NTSTATUS status;
3772 bool posix_open = false;
3773 bool need_re_stat = false;
3774 uint32_t access_mask = SEC_DIR_ADD_SUBDIR;
3776 if (!CAN_WRITE(conn) || (access_mask & ~(conn->share_access))) {
3777 DEBUG(5,("mkdir_internal: failing share access "
3778 "%s\n", lp_servicename(talloc_tos(), SNUM(conn))));
3779 return NT_STATUS_ACCESS_DENIED;
3782 if (!parent_dirname(talloc_tos(), smb_dname->base_name, &parent_dir,
3783 NULL)) {
3784 return NT_STATUS_NO_MEMORY;
3787 if (file_attributes & FILE_FLAG_POSIX_SEMANTICS) {
3788 posix_open = true;
3789 mode = (mode_t)(file_attributes & ~FILE_FLAG_POSIX_SEMANTICS);
3790 } else {
3791 mode = unix_mode(conn, FILE_ATTRIBUTE_DIRECTORY, smb_dname, parent_dir);
3794 status = check_parent_access(conn,
3795 smb_dname,
3796 access_mask);
3797 if(!NT_STATUS_IS_OK(status)) {
3798 DEBUG(5,("mkdir_internal: check_parent_access "
3799 "on directory %s for path %s returned %s\n",
3800 parent_dir,
3801 smb_dname->base_name,
3802 nt_errstr(status) ));
3803 return status;
3806 if (SMB_VFS_MKDIR(conn, smb_dname, mode) != 0) {
3807 return map_nt_error_from_unix(errno);
3810 /* Ensure we're checking for a symlink here.... */
3811 /* We don't want to get caught by a symlink racer. */
3813 if (SMB_VFS_LSTAT(conn, smb_dname) == -1) {
3814 DEBUG(2, ("Could not stat directory '%s' just created: %s\n",
3815 smb_fname_str_dbg(smb_dname), strerror(errno)));
3816 return map_nt_error_from_unix(errno);
3819 if (!S_ISDIR(smb_dname->st.st_ex_mode)) {
3820 DEBUG(0, ("Directory '%s' just created is not a directory !\n",
3821 smb_fname_str_dbg(smb_dname)));
3822 return NT_STATUS_NOT_A_DIRECTORY;
3825 if (lp_store_dos_attributes(SNUM(conn))) {
3826 if (!posix_open) {
3827 file_set_dosmode(conn, smb_dname,
3828 file_attributes | FILE_ATTRIBUTE_DIRECTORY,
3829 parent_dir, true);
3833 if (lp_inherit_permissions(SNUM(conn))) {
3834 inherit_access_posix_acl(conn, parent_dir,
3835 smb_dname->base_name, mode);
3836 need_re_stat = true;
3839 if (!posix_open) {
3841 * Check if high bits should have been set,
3842 * then (if bits are missing): add them.
3843 * Consider bits automagically set by UNIX, i.e. SGID bit from parent
3844 * dir.
3846 if ((mode & ~(S_IRWXU|S_IRWXG|S_IRWXO)) &&
3847 (mode & ~smb_dname->st.st_ex_mode)) {
3848 SMB_VFS_CHMOD(conn, smb_dname,
3849 (smb_dname->st.st_ex_mode |
3850 (mode & ~smb_dname->st.st_ex_mode)));
3851 need_re_stat = true;
3855 /* Change the owner if required. */
3856 if (lp_inherit_owner(SNUM(conn)) != INHERIT_OWNER_NO) {
3857 change_dir_owner_to_parent(conn, parent_dir,
3858 smb_dname->base_name,
3859 &smb_dname->st);
3860 need_re_stat = true;
3863 if (need_re_stat) {
3864 if (SMB_VFS_LSTAT(conn, smb_dname) == -1) {
3865 DEBUG(2, ("Could not stat directory '%s' just created: %s\n",
3866 smb_fname_str_dbg(smb_dname), strerror(errno)));
3867 return map_nt_error_from_unix(errno);
3871 notify_fname(conn, NOTIFY_ACTION_ADDED, FILE_NOTIFY_CHANGE_DIR_NAME,
3872 smb_dname->base_name);
3874 return NT_STATUS_OK;
3877 /****************************************************************************
3878 Open a directory from an NT SMB call.
3879 ****************************************************************************/
3881 static NTSTATUS open_directory(connection_struct *conn,
3882 struct smb_request *req,
3883 struct smb_filename *smb_dname,
3884 uint32_t access_mask,
3885 uint32_t share_access,
3886 uint32_t create_disposition,
3887 uint32_t create_options,
3888 uint32_t file_attributes,
3889 int *pinfo,
3890 files_struct **result)
3892 files_struct *fsp = NULL;
3893 bool dir_existed = VALID_STAT(smb_dname->st) ? True : False;
3894 struct share_mode_lock *lck = NULL;
3895 NTSTATUS status;
3896 struct timespec mtimespec;
3897 int info = 0;
3898 bool ok;
3900 if (is_ntfs_stream_smb_fname(smb_dname)) {
3901 DEBUG(2, ("open_directory: %s is a stream name!\n",
3902 smb_fname_str_dbg(smb_dname)));
3903 return NT_STATUS_NOT_A_DIRECTORY;
3906 if (!(file_attributes & FILE_FLAG_POSIX_SEMANTICS)) {
3907 /* Ensure we have a directory attribute. */
3908 file_attributes |= FILE_ATTRIBUTE_DIRECTORY;
3911 DEBUG(5,("open_directory: opening directory %s, access_mask = 0x%x, "
3912 "share_access = 0x%x create_options = 0x%x, "
3913 "create_disposition = 0x%x, file_attributes = 0x%x\n",
3914 smb_fname_str_dbg(smb_dname),
3915 (unsigned int)access_mask,
3916 (unsigned int)share_access,
3917 (unsigned int)create_options,
3918 (unsigned int)create_disposition,
3919 (unsigned int)file_attributes));
3921 status = smbd_calculate_access_mask(conn, smb_dname, false,
3922 access_mask, &access_mask);
3923 if (!NT_STATUS_IS_OK(status)) {
3924 DEBUG(10, ("open_directory: smbd_calculate_access_mask "
3925 "on file %s returned %s\n",
3926 smb_fname_str_dbg(smb_dname),
3927 nt_errstr(status)));
3928 return status;
3931 if ((access_mask & SEC_FLAG_SYSTEM_SECURITY) &&
3932 !security_token_has_privilege(get_current_nttok(conn),
3933 SEC_PRIV_SECURITY)) {
3934 DEBUG(10, ("open_directory: open on %s "
3935 "failed - SEC_FLAG_SYSTEM_SECURITY denied.\n",
3936 smb_fname_str_dbg(smb_dname)));
3937 return NT_STATUS_PRIVILEGE_NOT_HELD;
3940 switch( create_disposition ) {
3941 case FILE_OPEN:
3943 if (!dir_existed) {
3944 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3947 info = FILE_WAS_OPENED;
3948 break;
3950 case FILE_CREATE:
3952 /* If directory exists error. If directory doesn't
3953 * exist create. */
3955 if (dir_existed) {
3956 status = NT_STATUS_OBJECT_NAME_COLLISION;
3957 DEBUG(2, ("open_directory: unable to create "
3958 "%s. Error was %s\n",
3959 smb_fname_str_dbg(smb_dname),
3960 nt_errstr(status)));
3961 return status;
3964 status = mkdir_internal(conn, smb_dname,
3965 file_attributes);
3967 if (!NT_STATUS_IS_OK(status)) {
3968 DEBUG(2, ("open_directory: unable to create "
3969 "%s. Error was %s\n",
3970 smb_fname_str_dbg(smb_dname),
3971 nt_errstr(status)));
3972 return status;
3975 info = FILE_WAS_CREATED;
3976 break;
3978 case FILE_OPEN_IF:
3980 * If directory exists open. If directory doesn't
3981 * exist create.
3984 if (dir_existed) {
3985 status = NT_STATUS_OK;
3986 info = FILE_WAS_OPENED;
3987 } else {
3988 status = mkdir_internal(conn, smb_dname,
3989 file_attributes);
3991 if (NT_STATUS_IS_OK(status)) {
3992 info = FILE_WAS_CREATED;
3993 } else {
3994 /* Cope with create race. */
3995 if (!NT_STATUS_EQUAL(status,
3996 NT_STATUS_OBJECT_NAME_COLLISION)) {
3997 DEBUG(2, ("open_directory: unable to create "
3998 "%s. Error was %s\n",
3999 smb_fname_str_dbg(smb_dname),
4000 nt_errstr(status)));
4001 return status;
4005 * If mkdir_internal() returned
4006 * NT_STATUS_OBJECT_NAME_COLLISION
4007 * we still must lstat the path.
4010 if (SMB_VFS_LSTAT(conn, smb_dname)
4011 == -1) {
4012 DEBUG(2, ("Could not stat "
4013 "directory '%s' just "
4014 "opened: %s\n",
4015 smb_fname_str_dbg(
4016 smb_dname),
4017 strerror(errno)));
4018 return map_nt_error_from_unix(
4019 errno);
4022 info = FILE_WAS_OPENED;
4026 break;
4028 case FILE_SUPERSEDE:
4029 case FILE_OVERWRITE:
4030 case FILE_OVERWRITE_IF:
4031 default:
4032 DEBUG(5,("open_directory: invalid create_disposition "
4033 "0x%x for directory %s\n",
4034 (unsigned int)create_disposition,
4035 smb_fname_str_dbg(smb_dname)));
4036 return NT_STATUS_INVALID_PARAMETER;
4039 if(!S_ISDIR(smb_dname->st.st_ex_mode)) {
4040 DEBUG(5,("open_directory: %s is not a directory !\n",
4041 smb_fname_str_dbg(smb_dname)));
4042 return NT_STATUS_NOT_A_DIRECTORY;
4045 if (info == FILE_WAS_OPENED) {
4046 status = smbd_check_access_rights(conn,
4047 smb_dname,
4048 false,
4049 access_mask);
4050 if (!NT_STATUS_IS_OK(status)) {
4051 DEBUG(10, ("open_directory: smbd_check_access_rights on "
4052 "file %s failed with %s\n",
4053 smb_fname_str_dbg(smb_dname),
4054 nt_errstr(status)));
4055 return status;
4059 status = file_new(req, conn, &fsp);
4060 if(!NT_STATUS_IS_OK(status)) {
4061 return status;
4065 * Setup the files_struct for it.
4068 fsp->file_id = vfs_file_id_from_sbuf(conn, &smb_dname->st);
4069 fsp->vuid = req ? req->vuid : UID_FIELD_INVALID;
4070 fsp->file_pid = req ? req->smbpid : 0;
4071 fsp->can_lock = False;
4072 fsp->can_read = False;
4073 fsp->can_write = False;
4075 fsp->share_access = share_access;
4076 fsp->fh->private_options = 0;
4078 * According to Samba4, SEC_FILE_READ_ATTRIBUTE is always granted,
4080 fsp->access_mask = access_mask | FILE_READ_ATTRIBUTES;
4081 fsp->print_file = NULL;
4082 fsp->modified = False;
4083 fsp->oplock_type = NO_OPLOCK;
4084 fsp->sent_oplock_break = NO_BREAK_SENT;
4085 fsp->is_directory = True;
4086 if (file_attributes & FILE_FLAG_POSIX_SEMANTICS) {
4087 fsp->posix_flags |= FSP_POSIX_FLAGS_ALL;
4089 status = fsp_set_smb_fname(fsp, smb_dname);
4090 if (!NT_STATUS_IS_OK(status)) {
4091 file_free(req, fsp);
4092 return status;
4095 /* Don't store old timestamps for directory
4096 handles in the internal database. We don't
4097 update them in there if new objects
4098 are creaded in the directory. Currently
4099 we only update timestamps on file writes.
4100 See bug #9870.
4102 ZERO_STRUCT(mtimespec);
4104 if (access_mask & (FILE_LIST_DIRECTORY|
4105 FILE_ADD_FILE|
4106 FILE_ADD_SUBDIRECTORY|
4107 FILE_TRAVERSE|
4108 DELETE_ACCESS|
4109 FILE_DELETE_CHILD)) {
4110 #ifdef O_DIRECTORY
4111 status = fd_open(conn, fsp, O_RDONLY|O_DIRECTORY, 0);
4112 #else
4113 /* POSIX allows us to open a directory with O_RDONLY. */
4114 status = fd_open(conn, fsp, O_RDONLY, 0);
4115 #endif
4116 if (!NT_STATUS_IS_OK(status)) {
4117 DEBUG(5, ("open_directory: Could not open fd for "
4118 "%s (%s)\n",
4119 smb_fname_str_dbg(smb_dname),
4120 nt_errstr(status)));
4121 file_free(req, fsp);
4122 return status;
4124 } else {
4125 fsp->fh->fd = -1;
4126 DEBUG(10, ("Not opening Directory %s\n",
4127 smb_fname_str_dbg(smb_dname)));
4130 status = vfs_stat_fsp(fsp);
4131 if (!NT_STATUS_IS_OK(status)) {
4132 fd_close(fsp);
4133 file_free(req, fsp);
4134 return status;
4137 if(!S_ISDIR(fsp->fsp_name->st.st_ex_mode)) {
4138 DEBUG(5,("open_directory: %s is not a directory !\n",
4139 smb_fname_str_dbg(smb_dname)));
4140 fd_close(fsp);
4141 file_free(req, fsp);
4142 return NT_STATUS_NOT_A_DIRECTORY;
4145 /* Ensure there was no race condition. We need to check
4146 * dev/inode but not permissions, as these can change
4147 * legitimately */
4148 if (!check_same_dev_ino(&smb_dname->st, &fsp->fsp_name->st)) {
4149 DEBUG(5,("open_directory: stat struct differs for "
4150 "directory %s.\n",
4151 smb_fname_str_dbg(smb_dname)));
4152 fd_close(fsp);
4153 file_free(req, fsp);
4154 return NT_STATUS_ACCESS_DENIED;
4157 lck = get_share_mode_lock(talloc_tos(), fsp->file_id,
4158 conn->connectpath, smb_dname,
4159 &mtimespec);
4161 if (lck == NULL) {
4162 DEBUG(0, ("open_directory: Could not get share mode lock for "
4163 "%s\n", smb_fname_str_dbg(smb_dname)));
4164 fd_close(fsp);
4165 file_free(req, fsp);
4166 return NT_STATUS_SHARING_VIOLATION;
4169 if (has_delete_on_close(lck, fsp->name_hash)) {
4170 TALLOC_FREE(lck);
4171 fd_close(fsp);
4172 file_free(req, fsp);
4173 return NT_STATUS_DELETE_PENDING;
4176 status = open_mode_check(conn, lck,
4177 access_mask, share_access);
4179 if (!NT_STATUS_IS_OK(status)) {
4180 TALLOC_FREE(lck);
4181 fd_close(fsp);
4182 file_free(req, fsp);
4183 return status;
4186 ok = set_share_mode(lck, fsp, get_current_uid(conn),
4187 req ? req->mid : 0, NO_OPLOCK,
4188 UINT32_MAX);
4189 if (!ok) {
4190 TALLOC_FREE(lck);
4191 fd_close(fsp);
4192 file_free(req, fsp);
4193 return NT_STATUS_NO_MEMORY;
4196 /* For directories the delete on close bit at open time seems
4197 always to be honored on close... See test 19 in Samba4 BASE-DELETE. */
4198 if (create_options & FILE_DELETE_ON_CLOSE) {
4199 status = can_set_delete_on_close(fsp, 0);
4200 if (!NT_STATUS_IS_OK(status) && !NT_STATUS_EQUAL(status, NT_STATUS_DIRECTORY_NOT_EMPTY)) {
4201 del_share_mode(lck, fsp);
4202 TALLOC_FREE(lck);
4203 fd_close(fsp);
4204 file_free(req, fsp);
4205 return status;
4208 if (NT_STATUS_IS_OK(status)) {
4209 /* Note that here we set the *inital* delete on close flag,
4210 not the regular one. The magic gets handled in close. */
4211 fsp->initial_delete_on_close = True;
4217 * Deal with other opens having a modified write time. Is this
4218 * possible for directories?
4220 struct timespec write_time = get_share_mode_write_time(lck);
4222 if (!null_timespec(write_time)) {
4223 update_stat_ex_mtime(&fsp->fsp_name->st, write_time);
4227 TALLOC_FREE(lck);
4229 if (pinfo) {
4230 *pinfo = info;
4233 *result = fsp;
4234 return NT_STATUS_OK;
4237 NTSTATUS create_directory(connection_struct *conn, struct smb_request *req,
4238 struct smb_filename *smb_dname)
4240 NTSTATUS status;
4241 files_struct *fsp;
4243 status = SMB_VFS_CREATE_FILE(
4244 conn, /* conn */
4245 req, /* req */
4246 0, /* root_dir_fid */
4247 smb_dname, /* fname */
4248 FILE_READ_ATTRIBUTES, /* access_mask */
4249 FILE_SHARE_NONE, /* share_access */
4250 FILE_CREATE, /* create_disposition*/
4251 FILE_DIRECTORY_FILE, /* create_options */
4252 FILE_ATTRIBUTE_DIRECTORY, /* file_attributes */
4253 0, /* oplock_request */
4254 NULL, /* lease */
4255 0, /* allocation_size */
4256 0, /* private_flags */
4257 NULL, /* sd */
4258 NULL, /* ea_list */
4259 &fsp, /* result */
4260 NULL, /* pinfo */
4261 NULL, NULL); /* create context */
4263 if (NT_STATUS_IS_OK(status)) {
4264 close_file(req, fsp, NORMAL_CLOSE);
4267 return status;
4270 /****************************************************************************
4271 Receive notification that one of our open files has been renamed by another
4272 smbd process.
4273 ****************************************************************************/
4275 void msg_file_was_renamed(struct messaging_context *msg,
4276 void *private_data,
4277 uint32_t msg_type,
4278 struct server_id server_id,
4279 DATA_BLOB *data)
4281 files_struct *fsp;
4282 char *frm = (char *)data->data;
4283 struct file_id id;
4284 const char *sharepath;
4285 const char *base_name;
4286 const char *stream_name;
4287 struct smb_filename *smb_fname = NULL;
4288 size_t sp_len, bn_len;
4289 NTSTATUS status;
4290 struct smbd_server_connection *sconn =
4291 talloc_get_type_abort(private_data,
4292 struct smbd_server_connection);
4294 if (data->data == NULL
4295 || data->length < MSG_FILE_RENAMED_MIN_SIZE + 2) {
4296 DEBUG(0, ("msg_file_was_renamed: Got invalid msg len %d\n",
4297 (int)data->length));
4298 return;
4301 /* Unpack the message. */
4302 pull_file_id_24(frm, &id);
4303 sharepath = &frm[24];
4304 sp_len = strlen(sharepath);
4305 base_name = sharepath + sp_len + 1;
4306 bn_len = strlen(base_name);
4307 stream_name = sharepath + sp_len + 1 + bn_len + 1;
4309 /* stream_name must always be NULL if there is no stream. */
4310 if (stream_name[0] == '\0') {
4311 stream_name = NULL;
4314 smb_fname = synthetic_smb_fname(talloc_tos(),
4315 base_name,
4316 stream_name,
4317 NULL,
4319 if (smb_fname == NULL) {
4320 return;
4323 DEBUG(10,("msg_file_was_renamed: Got rename message for sharepath %s, new name %s, "
4324 "file_id %s\n",
4325 sharepath, smb_fname_str_dbg(smb_fname),
4326 file_id_string_tos(&id)));
4328 for(fsp = file_find_di_first(sconn, id); fsp;
4329 fsp = file_find_di_next(fsp)) {
4330 if (memcmp(fsp->conn->connectpath, sharepath, sp_len) == 0) {
4332 DEBUG(10,("msg_file_was_renamed: renaming file %s from %s -> %s\n",
4333 fsp_fnum_dbg(fsp), fsp_str_dbg(fsp),
4334 smb_fname_str_dbg(smb_fname)));
4335 status = fsp_set_smb_fname(fsp, smb_fname);
4336 if (!NT_STATUS_IS_OK(status)) {
4337 goto out;
4339 } else {
4340 /* TODO. JRA. */
4341 /* Now we have the complete path we can work out if this is
4342 actually within this share and adjust newname accordingly. */
4343 DEBUG(10,("msg_file_was_renamed: share mismatch (sharepath %s "
4344 "not sharepath %s) "
4345 "%s from %s -> %s\n",
4346 fsp->conn->connectpath,
4347 sharepath,
4348 fsp_fnum_dbg(fsp),
4349 fsp_str_dbg(fsp),
4350 smb_fname_str_dbg(smb_fname)));
4353 out:
4354 TALLOC_FREE(smb_fname);
4355 return;
4359 * If a main file is opened for delete, all streams need to be checked for
4360 * !FILE_SHARE_DELETE. Do this by opening with DELETE_ACCESS.
4361 * If that works, delete them all by setting the delete on close and close.
4364 static NTSTATUS open_streams_for_delete(connection_struct *conn,
4365 const struct smb_filename *smb_fname)
4367 struct stream_struct *stream_info = NULL;
4368 files_struct **streams = NULL;
4369 int i;
4370 unsigned int num_streams = 0;
4371 TALLOC_CTX *frame = talloc_stackframe();
4372 NTSTATUS status;
4374 status = vfs_streaminfo(conn, NULL, smb_fname, talloc_tos(),
4375 &num_streams, &stream_info);
4377 if (NT_STATUS_EQUAL(status, NT_STATUS_NOT_IMPLEMENTED)
4378 || NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
4379 DEBUG(10, ("no streams around\n"));
4380 TALLOC_FREE(frame);
4381 return NT_STATUS_OK;
4384 if (!NT_STATUS_IS_OK(status)) {
4385 DEBUG(10, ("vfs_streaminfo failed: %s\n",
4386 nt_errstr(status)));
4387 goto fail;
4390 DEBUG(10, ("open_streams_for_delete found %d streams\n",
4391 num_streams));
4393 if (num_streams == 0) {
4394 TALLOC_FREE(frame);
4395 return NT_STATUS_OK;
4398 streams = talloc_array(talloc_tos(), files_struct *, num_streams);
4399 if (streams == NULL) {
4400 DEBUG(0, ("talloc failed\n"));
4401 status = NT_STATUS_NO_MEMORY;
4402 goto fail;
4405 for (i=0; i<num_streams; i++) {
4406 struct smb_filename *smb_fname_cp;
4408 if (strequal(stream_info[i].name, "::$DATA")) {
4409 streams[i] = NULL;
4410 continue;
4413 smb_fname_cp = synthetic_smb_fname(talloc_tos(),
4414 smb_fname->base_name,
4415 stream_info[i].name,
4416 NULL,
4417 (smb_fname->flags &
4418 ~SMB_FILENAME_POSIX_PATH));
4419 if (smb_fname_cp == NULL) {
4420 status = NT_STATUS_NO_MEMORY;
4421 goto fail;
4424 if (SMB_VFS_STAT(conn, smb_fname_cp) == -1) {
4425 DEBUG(10, ("Unable to stat stream: %s\n",
4426 smb_fname_str_dbg(smb_fname_cp)));
4429 status = SMB_VFS_CREATE_FILE(
4430 conn, /* conn */
4431 NULL, /* req */
4432 0, /* root_dir_fid */
4433 smb_fname_cp, /* fname */
4434 DELETE_ACCESS, /* access_mask */
4435 (FILE_SHARE_READ | /* share_access */
4436 FILE_SHARE_WRITE | FILE_SHARE_DELETE),
4437 FILE_OPEN, /* create_disposition*/
4438 0, /* create_options */
4439 FILE_ATTRIBUTE_NORMAL, /* file_attributes */
4440 0, /* oplock_request */
4441 NULL, /* lease */
4442 0, /* allocation_size */
4443 NTCREATEX_OPTIONS_PRIVATE_STREAM_DELETE, /* private_flags */
4444 NULL, /* sd */
4445 NULL, /* ea_list */
4446 &streams[i], /* result */
4447 NULL, /* pinfo */
4448 NULL, NULL); /* create context */
4450 if (!NT_STATUS_IS_OK(status)) {
4451 DEBUG(10, ("Could not open stream %s: %s\n",
4452 smb_fname_str_dbg(smb_fname_cp),
4453 nt_errstr(status)));
4455 TALLOC_FREE(smb_fname_cp);
4456 break;
4458 TALLOC_FREE(smb_fname_cp);
4462 * don't touch the variable "status" beyond this point :-)
4465 for (i -= 1 ; i >= 0; i--) {
4466 if (streams[i] == NULL) {
4467 continue;
4470 DEBUG(10, ("Closing stream # %d, %s\n", i,
4471 fsp_str_dbg(streams[i])));
4472 close_file(NULL, streams[i], NORMAL_CLOSE);
4475 fail:
4476 TALLOC_FREE(frame);
4477 return status;
4480 /*********************************************************************
4481 Create a default ACL by inheriting from the parent. If no inheritance
4482 from the parent available, don't set anything. This will leave the actual
4483 permissions the new file or directory already got from the filesystem
4484 as the NT ACL when read.
4485 *********************************************************************/
4487 static NTSTATUS inherit_new_acl(files_struct *fsp)
4489 TALLOC_CTX *frame = talloc_stackframe();
4490 char *parent_name = NULL;
4491 struct security_descriptor *parent_desc = NULL;
4492 NTSTATUS status = NT_STATUS_OK;
4493 struct security_descriptor *psd = NULL;
4494 const struct dom_sid *owner_sid = NULL;
4495 const struct dom_sid *group_sid = NULL;
4496 uint32_t security_info_sent = (SECINFO_OWNER | SECINFO_GROUP | SECINFO_DACL);
4497 struct security_token *token = fsp->conn->session_info->security_token;
4498 bool inherit_owner =
4499 (lp_inherit_owner(SNUM(fsp->conn)) == INHERIT_OWNER_WINDOWS_AND_UNIX);
4500 bool inheritable_components = false;
4501 bool try_builtin_administrators = false;
4502 const struct dom_sid *BA_U_sid = NULL;
4503 const struct dom_sid *BA_G_sid = NULL;
4504 bool try_system = false;
4505 const struct dom_sid *SY_U_sid = NULL;
4506 const struct dom_sid *SY_G_sid = NULL;
4507 size_t size = 0;
4508 struct smb_filename *parent_smb_fname = NULL;
4510 if (!parent_dirname(frame, fsp->fsp_name->base_name, &parent_name, NULL)) {
4511 TALLOC_FREE(frame);
4512 return NT_STATUS_NO_MEMORY;
4514 parent_smb_fname = synthetic_smb_fname(talloc_tos(),
4515 parent_name,
4516 NULL,
4517 NULL,
4518 fsp->fsp_name->flags);
4520 if (parent_smb_fname == NULL) {
4521 TALLOC_FREE(frame);
4522 return NT_STATUS_NO_MEMORY;
4525 status = SMB_VFS_GET_NT_ACL(fsp->conn,
4526 parent_smb_fname,
4527 (SECINFO_OWNER | SECINFO_GROUP | SECINFO_DACL),
4528 frame,
4529 &parent_desc);
4530 if (!NT_STATUS_IS_OK(status)) {
4531 TALLOC_FREE(frame);
4532 return status;
4535 inheritable_components = sd_has_inheritable_components(parent_desc,
4536 fsp->is_directory);
4538 if (!inheritable_components && !inherit_owner) {
4539 TALLOC_FREE(frame);
4540 /* Nothing to inherit and not setting owner. */
4541 return NT_STATUS_OK;
4544 /* Create an inherited descriptor from the parent. */
4546 if (DEBUGLEVEL >= 10) {
4547 DEBUG(10,("inherit_new_acl: parent acl for %s is:\n",
4548 fsp_str_dbg(fsp) ));
4549 NDR_PRINT_DEBUG(security_descriptor, parent_desc);
4552 /* Inherit from parent descriptor if "inherit owner" set. */
4553 if (inherit_owner) {
4554 owner_sid = parent_desc->owner_sid;
4555 group_sid = parent_desc->group_sid;
4558 if (owner_sid == NULL) {
4559 if (security_token_has_builtin_administrators(token)) {
4560 try_builtin_administrators = true;
4561 } else if (security_token_is_system(token)) {
4562 try_builtin_administrators = true;
4563 try_system = true;
4567 if (group_sid == NULL &&
4568 token->num_sids == PRIMARY_GROUP_SID_INDEX)
4570 if (security_token_is_system(token)) {
4571 try_builtin_administrators = true;
4572 try_system = true;
4576 if (try_builtin_administrators) {
4577 struct unixid ids;
4578 bool ok;
4580 ZERO_STRUCT(ids);
4581 ok = sids_to_unixids(&global_sid_Builtin_Administrators, 1, &ids);
4582 if (ok) {
4583 switch (ids.type) {
4584 case ID_TYPE_BOTH:
4585 BA_U_sid = &global_sid_Builtin_Administrators;
4586 BA_G_sid = &global_sid_Builtin_Administrators;
4587 break;
4588 case ID_TYPE_UID:
4589 BA_U_sid = &global_sid_Builtin_Administrators;
4590 break;
4591 case ID_TYPE_GID:
4592 BA_G_sid = &global_sid_Builtin_Administrators;
4593 break;
4594 default:
4595 break;
4600 if (try_system) {
4601 struct unixid ids;
4602 bool ok;
4604 ZERO_STRUCT(ids);
4605 ok = sids_to_unixids(&global_sid_System, 1, &ids);
4606 if (ok) {
4607 switch (ids.type) {
4608 case ID_TYPE_BOTH:
4609 SY_U_sid = &global_sid_System;
4610 SY_G_sid = &global_sid_System;
4611 break;
4612 case ID_TYPE_UID:
4613 SY_U_sid = &global_sid_System;
4614 break;
4615 case ID_TYPE_GID:
4616 SY_G_sid = &global_sid_System;
4617 break;
4618 default:
4619 break;
4624 if (owner_sid == NULL) {
4625 owner_sid = BA_U_sid;
4628 if (owner_sid == NULL) {
4629 owner_sid = SY_U_sid;
4632 if (group_sid == NULL) {
4633 group_sid = SY_G_sid;
4636 if (try_system && group_sid == NULL) {
4637 group_sid = BA_G_sid;
4640 if (owner_sid == NULL) {
4641 owner_sid = &token->sids[PRIMARY_USER_SID_INDEX];
4643 if (group_sid == NULL) {
4644 if (token->num_sids == PRIMARY_GROUP_SID_INDEX) {
4645 group_sid = &token->sids[PRIMARY_USER_SID_INDEX];
4646 } else {
4647 group_sid = &token->sids[PRIMARY_GROUP_SID_INDEX];
4651 status = se_create_child_secdesc(frame,
4652 &psd,
4653 &size,
4654 parent_desc,
4655 owner_sid,
4656 group_sid,
4657 fsp->is_directory);
4658 if (!NT_STATUS_IS_OK(status)) {
4659 TALLOC_FREE(frame);
4660 return status;
4663 /* If inheritable_components == false,
4664 se_create_child_secdesc()
4665 creates a security desriptor with a NULL dacl
4666 entry, but with SEC_DESC_DACL_PRESENT. We need
4667 to remove that flag. */
4669 if (!inheritable_components) {
4670 security_info_sent &= ~SECINFO_DACL;
4671 psd->type &= ~SEC_DESC_DACL_PRESENT;
4674 if (DEBUGLEVEL >= 10) {
4675 DEBUG(10,("inherit_new_acl: child acl for %s is:\n",
4676 fsp_str_dbg(fsp) ));
4677 NDR_PRINT_DEBUG(security_descriptor, psd);
4680 if (inherit_owner) {
4681 /* We need to be root to force this. */
4682 become_root();
4684 status = SMB_VFS_FSET_NT_ACL(fsp,
4685 security_info_sent,
4686 psd);
4687 if (inherit_owner) {
4688 unbecome_root();
4690 TALLOC_FREE(frame);
4691 return status;
4695 * If we already have a lease, it must match the new file id. [MS-SMB2]
4696 * 3.3.5.9.8 speaks about INVALID_PARAMETER if an already used lease key is
4697 * used for a different file name.
4700 struct lease_match_state {
4701 /* Input parameters. */
4702 TALLOC_CTX *mem_ctx;
4703 const char *servicepath;
4704 const struct smb_filename *fname;
4705 bool file_existed;
4706 struct file_id id;
4707 /* Return parameters. */
4708 uint32_t num_file_ids;
4709 struct file_id *ids;
4710 NTSTATUS match_status;
4713 /*************************************************************
4714 File doesn't exist but this lease key+guid is already in use.
4716 This is only allowable in the dynamic share case where the
4717 service path must be different.
4719 There is a small race condition here in the multi-connection
4720 case where a client sends two create calls on different connections,
4721 where the file doesn't exist and one smbd creates the leases_db
4722 entry first, but this will get fixed by the multichannel cleanup
4723 when all identical client_guids get handled by a single smbd.
4724 **************************************************************/
4726 static void lease_match_parser_new_file(
4727 uint32_t num_files,
4728 const struct leases_db_file *files,
4729 struct lease_match_state *state)
4731 uint32_t i;
4733 for (i = 0; i < num_files; i++) {
4734 const struct leases_db_file *f = &files[i];
4735 if (strequal(state->servicepath, f->servicepath)) {
4736 state->match_status = NT_STATUS_INVALID_PARAMETER;
4737 return;
4741 /* Dynamic share case. Break leases on all other files. */
4742 state->match_status = leases_db_copy_file_ids(state->mem_ctx,
4743 num_files,
4744 files,
4745 &state->ids);
4746 if (!NT_STATUS_IS_OK(state->match_status)) {
4747 return;
4750 state->num_file_ids = num_files;
4751 state->match_status = NT_STATUS_OPLOCK_NOT_GRANTED;
4752 return;
4755 static void lease_match_parser(
4756 uint32_t num_files,
4757 const struct leases_db_file *files,
4758 void *private_data)
4760 struct lease_match_state *state =
4761 (struct lease_match_state *)private_data;
4762 uint32_t i;
4764 if (!state->file_existed) {
4766 * Deal with name mismatch or
4767 * possible dynamic share case separately
4768 * to make code clearer.
4770 lease_match_parser_new_file(num_files,
4771 files,
4772 state);
4773 return;
4776 /* File existed. */
4777 state->match_status = NT_STATUS_OK;
4779 for (i = 0; i < num_files; i++) {
4780 const struct leases_db_file *f = &files[i];
4782 /* Everything should be the same. */
4783 if (!file_id_equal(&state->id, &f->id)) {
4784 /* This should catch all dynamic share cases. */
4785 state->match_status = NT_STATUS_OPLOCK_NOT_GRANTED;
4786 break;
4788 if (!strequal(f->servicepath, state->servicepath)) {
4789 state->match_status = NT_STATUS_INVALID_PARAMETER;
4790 break;
4792 if (!strequal(f->base_name, state->fname->base_name)) {
4793 state->match_status = NT_STATUS_INVALID_PARAMETER;
4794 break;
4796 if (!strequal(f->stream_name, state->fname->stream_name)) {
4797 state->match_status = NT_STATUS_INVALID_PARAMETER;
4798 break;
4802 if (NT_STATUS_IS_OK(state->match_status)) {
4804 * Common case - just opening another handle on a
4805 * file on a non-dynamic share.
4807 return;
4810 if (NT_STATUS_EQUAL(state->match_status, NT_STATUS_INVALID_PARAMETER)) {
4811 /* Mismatched path. Error back to client. */
4812 return;
4816 * File id mismatch. Dynamic share case NT_STATUS_OPLOCK_NOT_GRANTED.
4817 * Don't allow leases.
4820 state->match_status = leases_db_copy_file_ids(state->mem_ctx,
4821 num_files,
4822 files,
4823 &state->ids);
4824 if (!NT_STATUS_IS_OK(state->match_status)) {
4825 return;
4828 state->num_file_ids = num_files;
4829 state->match_status = NT_STATUS_OPLOCK_NOT_GRANTED;
4830 return;
4833 static NTSTATUS lease_match(connection_struct *conn,
4834 struct smb_request *req,
4835 struct smb2_lease_key *lease_key,
4836 const char *servicepath,
4837 const struct smb_filename *fname,
4838 uint16_t *p_version,
4839 uint16_t *p_epoch)
4841 struct smbd_server_connection *sconn = req->sconn;
4842 TALLOC_CTX *tos = talloc_tos();
4843 struct lease_match_state state = {
4844 .mem_ctx = tos,
4845 .servicepath = servicepath,
4846 .fname = fname,
4847 .match_status = NT_STATUS_OK
4849 uint32_t i;
4850 NTSTATUS status;
4852 state.file_existed = VALID_STAT(fname->st);
4853 if (state.file_existed) {
4854 state.id = vfs_file_id_from_sbuf(conn, &fname->st);
4855 } else {
4856 memset(&state.id, '\0', sizeof(state.id));
4859 status = leases_db_parse(&sconn->client->connections->smb2.client.guid,
4860 lease_key, lease_match_parser, &state);
4861 if (!NT_STATUS_IS_OK(status)) {
4863 * Not found or error means okay: We can make the lease pass
4865 return NT_STATUS_OK;
4867 if (!NT_STATUS_EQUAL(state.match_status, NT_STATUS_OPLOCK_NOT_GRANTED)) {
4869 * Anything but NT_STATUS_OPLOCK_NOT_GRANTED, let the caller
4870 * deal with it.
4872 return state.match_status;
4875 /* We have to break all existing leases. */
4876 for (i = 0; i < state.num_file_ids; i++) {
4877 struct share_mode_lock *lck;
4878 struct share_mode_data *d;
4879 uint32_t j;
4881 if (file_id_equal(&state.ids[i], &state.id)) {
4882 /* Don't need to break our own file. */
4883 continue;
4886 lck = get_existing_share_mode_lock(talloc_tos(), state.ids[i]);
4887 if (lck == NULL) {
4888 /* Race condition - file already closed. */
4889 continue;
4891 d = lck->data;
4892 for (j=0; j<d->num_share_modes; j++) {
4893 struct share_mode_entry *e = &d->share_modes[j];
4894 uint32_t e_lease_type = get_lease_type(d, e);
4895 struct share_mode_lease *l = NULL;
4897 if (share_mode_stale_pid(d, j)) {
4898 continue;
4901 if (e->op_type == LEASE_OPLOCK) {
4902 l = &lck->data->leases[e->lease_idx];
4903 if (!smb2_lease_key_equal(&l->lease_key,
4904 lease_key)) {
4905 continue;
4907 *p_epoch = l->epoch;
4908 *p_version = l->lease_version;
4911 if (e_lease_type == SMB2_LEASE_NONE) {
4912 continue;
4915 send_break_message(conn->sconn->msg_ctx, e,
4916 SMB2_LEASE_NONE);
4919 * Windows 7 and 8 lease clients
4920 * are broken in that they will not
4921 * respond to lease break requests
4922 * whilst waiting for an outstanding
4923 * open request on that lease handle
4924 * on the same TCP connection, due
4925 * to holding an internal inode lock.
4927 * This means we can't reschedule
4928 * ourselves here, but must return
4929 * from the create.
4931 * Work around:
4933 * Send the breaks and then return
4934 * SMB2_LEASE_NONE in the lease handle
4935 * to cause them to acknowledge the
4936 * lease break. Consulatation with
4937 * Microsoft engineering confirmed
4938 * this approach is safe.
4942 TALLOC_FREE(lck);
4945 * Ensure we don't grant anything more so we
4946 * never upgrade.
4948 return NT_STATUS_OPLOCK_NOT_GRANTED;
4952 * Wrapper around open_file_ntcreate and open_directory
4955 static NTSTATUS create_file_unixpath(connection_struct *conn,
4956 struct smb_request *req,
4957 struct smb_filename *smb_fname,
4958 uint32_t access_mask,
4959 uint32_t share_access,
4960 uint32_t create_disposition,
4961 uint32_t create_options,
4962 uint32_t file_attributes,
4963 uint32_t oplock_request,
4964 struct smb2_lease *lease,
4965 uint64_t allocation_size,
4966 uint32_t private_flags,
4967 struct security_descriptor *sd,
4968 struct ea_list *ea_list,
4970 files_struct **result,
4971 int *pinfo)
4973 int info = FILE_WAS_OPENED;
4974 files_struct *base_fsp = NULL;
4975 files_struct *fsp = NULL;
4976 NTSTATUS status;
4978 DEBUG(10,("create_file_unixpath: access_mask = 0x%x "
4979 "file_attributes = 0x%x, share_access = 0x%x, "
4980 "create_disposition = 0x%x create_options = 0x%x "
4981 "oplock_request = 0x%x private_flags = 0x%x "
4982 "ea_list = 0x%p, sd = 0x%p, "
4983 "fname = %s\n",
4984 (unsigned int)access_mask,
4985 (unsigned int)file_attributes,
4986 (unsigned int)share_access,
4987 (unsigned int)create_disposition,
4988 (unsigned int)create_options,
4989 (unsigned int)oplock_request,
4990 (unsigned int)private_flags,
4991 ea_list, sd, smb_fname_str_dbg(smb_fname)));
4993 if (create_options & FILE_OPEN_BY_FILE_ID) {
4994 status = NT_STATUS_NOT_SUPPORTED;
4995 goto fail;
4998 if (create_options & NTCREATEX_OPTIONS_INVALID_PARAM_MASK) {
4999 status = NT_STATUS_INVALID_PARAMETER;
5000 goto fail;
5003 if (req == NULL) {
5004 oplock_request |= INTERNAL_OPEN_ONLY;
5007 if (lease != NULL) {
5008 uint16_t epoch = lease->lease_epoch;
5009 uint16_t version = lease->lease_version;
5010 status = lease_match(conn,
5011 req,
5012 &lease->lease_key,
5013 conn->connectpath,
5014 smb_fname,
5015 &version,
5016 &epoch);
5017 if (NT_STATUS_EQUAL(status, NT_STATUS_OPLOCK_NOT_GRANTED)) {
5018 /* Dynamic share file. No leases and update epoch... */
5019 lease->lease_state = SMB2_LEASE_NONE;
5020 lease->lease_epoch = epoch;
5021 lease->lease_version = version;
5022 } else if (!NT_STATUS_IS_OK(status)) {
5023 goto fail;
5027 if ((conn->fs_capabilities & FILE_NAMED_STREAMS)
5028 && (access_mask & DELETE_ACCESS)
5029 && !is_ntfs_stream_smb_fname(smb_fname)) {
5031 * We can't open a file with DELETE access if any of the
5032 * streams is open without FILE_SHARE_DELETE
5034 status = open_streams_for_delete(conn, smb_fname);
5036 if (!NT_STATUS_IS_OK(status)) {
5037 goto fail;
5041 if ((access_mask & SEC_FLAG_SYSTEM_SECURITY) &&
5042 !security_token_has_privilege(get_current_nttok(conn),
5043 SEC_PRIV_SECURITY)) {
5044 DEBUG(10, ("create_file_unixpath: open on %s "
5045 "failed - SEC_FLAG_SYSTEM_SECURITY denied.\n",
5046 smb_fname_str_dbg(smb_fname)));
5047 status = NT_STATUS_PRIVILEGE_NOT_HELD;
5048 goto fail;
5051 if ((conn->fs_capabilities & FILE_NAMED_STREAMS)
5052 && is_ntfs_stream_smb_fname(smb_fname)
5053 && (!(private_flags & NTCREATEX_OPTIONS_PRIVATE_STREAM_DELETE))) {
5054 uint32_t base_create_disposition;
5055 struct smb_filename *smb_fname_base = NULL;
5057 if (create_options & FILE_DIRECTORY_FILE) {
5058 status = NT_STATUS_NOT_A_DIRECTORY;
5059 goto fail;
5062 switch (create_disposition) {
5063 case FILE_OPEN:
5064 base_create_disposition = FILE_OPEN;
5065 break;
5066 default:
5067 base_create_disposition = FILE_OPEN_IF;
5068 break;
5071 /* Create an smb_filename with stream_name == NULL. */
5072 smb_fname_base = synthetic_smb_fname(talloc_tos(),
5073 smb_fname->base_name,
5074 NULL,
5075 NULL,
5076 smb_fname->flags);
5077 if (smb_fname_base == NULL) {
5078 status = NT_STATUS_NO_MEMORY;
5079 goto fail;
5082 if (SMB_VFS_STAT(conn, smb_fname_base) == -1) {
5083 DEBUG(10, ("Unable to stat stream: %s\n",
5084 smb_fname_str_dbg(smb_fname_base)));
5085 } else {
5087 * https://bugzilla.samba.org/show_bug.cgi?id=10229
5088 * We need to check if the requested access mask
5089 * could be used to open the underlying file (if
5090 * it existed), as we're passing in zero for the
5091 * access mask to the base filename.
5093 status = check_base_file_access(conn,
5094 smb_fname_base,
5095 access_mask);
5097 if (!NT_STATUS_IS_OK(status)) {
5098 DEBUG(10, ("Permission check "
5099 "for base %s failed: "
5100 "%s\n", smb_fname->base_name,
5101 nt_errstr(status)));
5102 goto fail;
5106 /* Open the base file. */
5107 status = create_file_unixpath(conn, NULL, smb_fname_base, 0,
5108 FILE_SHARE_READ
5109 | FILE_SHARE_WRITE
5110 | FILE_SHARE_DELETE,
5111 base_create_disposition,
5112 0, 0, 0, NULL, 0, 0, NULL, NULL,
5113 &base_fsp, NULL);
5114 TALLOC_FREE(smb_fname_base);
5116 if (!NT_STATUS_IS_OK(status)) {
5117 DEBUG(10, ("create_file_unixpath for base %s failed: "
5118 "%s\n", smb_fname->base_name,
5119 nt_errstr(status)));
5120 goto fail;
5122 /* we don't need the low level fd */
5123 fd_close(base_fsp);
5127 * If it's a request for a directory open, deal with it separately.
5130 if (create_options & FILE_DIRECTORY_FILE) {
5132 if (create_options & FILE_NON_DIRECTORY_FILE) {
5133 status = NT_STATUS_INVALID_PARAMETER;
5134 goto fail;
5137 /* Can't open a temp directory. IFS kit test. */
5138 if (!(file_attributes & FILE_FLAG_POSIX_SEMANTICS) &&
5139 (file_attributes & FILE_ATTRIBUTE_TEMPORARY)) {
5140 status = NT_STATUS_INVALID_PARAMETER;
5141 goto fail;
5145 * We will get a create directory here if the Win32
5146 * app specified a security descriptor in the
5147 * CreateDirectory() call.
5150 oplock_request = 0;
5151 status = open_directory(
5152 conn, req, smb_fname, access_mask, share_access,
5153 create_disposition, create_options, file_attributes,
5154 &info, &fsp);
5155 } else {
5158 * Ordinary file case.
5161 status = file_new(req, conn, &fsp);
5162 if(!NT_STATUS_IS_OK(status)) {
5163 goto fail;
5166 status = fsp_set_smb_fname(fsp, smb_fname);
5167 if (!NT_STATUS_IS_OK(status)) {
5168 goto fail;
5171 if (base_fsp) {
5173 * We're opening the stream element of a
5174 * base_fsp we already opened. Set up the
5175 * base_fsp pointer.
5177 fsp->base_fsp = base_fsp;
5180 if (allocation_size) {
5181 fsp->initial_allocation_size = smb_roundup(fsp->conn,
5182 allocation_size);
5185 status = open_file_ntcreate(conn,
5186 req,
5187 access_mask,
5188 share_access,
5189 create_disposition,
5190 create_options,
5191 file_attributes,
5192 oplock_request,
5193 lease,
5194 private_flags,
5195 &info,
5196 fsp);
5198 if(!NT_STATUS_IS_OK(status)) {
5199 file_free(req, fsp);
5200 fsp = NULL;
5203 if (NT_STATUS_EQUAL(status, NT_STATUS_FILE_IS_A_DIRECTORY)) {
5205 /* A stream open never opens a directory */
5207 if (base_fsp) {
5208 status = NT_STATUS_FILE_IS_A_DIRECTORY;
5209 goto fail;
5213 * Fail the open if it was explicitly a non-directory
5214 * file.
5217 if (create_options & FILE_NON_DIRECTORY_FILE) {
5218 status = NT_STATUS_FILE_IS_A_DIRECTORY;
5219 goto fail;
5222 oplock_request = 0;
5223 status = open_directory(
5224 conn, req, smb_fname, access_mask,
5225 share_access, create_disposition,
5226 create_options, file_attributes,
5227 &info, &fsp);
5231 if (!NT_STATUS_IS_OK(status)) {
5232 goto fail;
5235 fsp->base_fsp = base_fsp;
5237 if ((ea_list != NULL) &&
5238 ((info == FILE_WAS_CREATED) || (info == FILE_WAS_OVERWRITTEN))) {
5239 status = set_ea(conn, fsp, fsp->fsp_name, ea_list);
5240 if (!NT_STATUS_IS_OK(status)) {
5241 goto fail;
5245 if (!fsp->is_directory && S_ISDIR(fsp->fsp_name->st.st_ex_mode)) {
5246 status = NT_STATUS_ACCESS_DENIED;
5247 goto fail;
5250 /* Save the requested allocation size. */
5251 if ((info == FILE_WAS_CREATED) || (info == FILE_WAS_OVERWRITTEN)) {
5252 if ((allocation_size > fsp->fsp_name->st.st_ex_size)
5253 && !(fsp->is_directory))
5255 fsp->initial_allocation_size = smb_roundup(
5256 fsp->conn, allocation_size);
5257 if (vfs_allocate_file_space(
5258 fsp, fsp->initial_allocation_size) == -1) {
5259 status = NT_STATUS_DISK_FULL;
5260 goto fail;
5262 } else {
5263 fsp->initial_allocation_size = smb_roundup(
5264 fsp->conn, (uint64_t)fsp->fsp_name->st.st_ex_size);
5266 } else {
5267 fsp->initial_allocation_size = 0;
5270 if ((info == FILE_WAS_CREATED) && lp_nt_acl_support(SNUM(conn)) &&
5271 fsp->base_fsp == NULL) {
5272 if (sd != NULL) {
5274 * According to the MS documentation, the only time the security
5275 * descriptor is applied to the opened file is iff we *created* the
5276 * file; an existing file stays the same.
5278 * Also, it seems (from observation) that you can open the file with
5279 * any access mask but you can still write the sd. We need to override
5280 * the granted access before we call set_sd
5281 * Patch for bug #2242 from Tom Lackemann <cessnatomny@yahoo.com>.
5284 uint32_t sec_info_sent;
5285 uint32_t saved_access_mask = fsp->access_mask;
5287 sec_info_sent = get_sec_info(sd);
5289 fsp->access_mask = FILE_GENERIC_ALL;
5291 if (sec_info_sent & (SECINFO_OWNER|
5292 SECINFO_GROUP|
5293 SECINFO_DACL|
5294 SECINFO_SACL)) {
5295 status = set_sd(fsp, sd, sec_info_sent);
5298 fsp->access_mask = saved_access_mask;
5300 if (!NT_STATUS_IS_OK(status)) {
5301 goto fail;
5303 } else if (lp_inherit_acls(SNUM(conn))) {
5304 /* Inherit from parent. Errors here are not fatal. */
5305 status = inherit_new_acl(fsp);
5306 if (!NT_STATUS_IS_OK(status)) {
5307 DEBUG(10,("inherit_new_acl: failed for %s with %s\n",
5308 fsp_str_dbg(fsp),
5309 nt_errstr(status) ));
5314 if ((conn->fs_capabilities & FILE_FILE_COMPRESSION)
5315 && (create_options & FILE_NO_COMPRESSION)
5316 && (info == FILE_WAS_CREATED)) {
5317 status = SMB_VFS_SET_COMPRESSION(conn, fsp, fsp,
5318 COMPRESSION_FORMAT_NONE);
5319 if (!NT_STATUS_IS_OK(status)) {
5320 DEBUG(1, ("failed to disable compression: %s\n",
5321 nt_errstr(status)));
5325 DEBUG(10, ("create_file_unixpath: info=%d\n", info));
5327 *result = fsp;
5328 if (pinfo != NULL) {
5329 *pinfo = info;
5332 smb_fname->st = fsp->fsp_name->st;
5334 return NT_STATUS_OK;
5336 fail:
5337 DEBUG(10, ("create_file_unixpath: %s\n", nt_errstr(status)));
5339 if (fsp != NULL) {
5340 if (base_fsp && fsp->base_fsp == base_fsp) {
5342 * The close_file below will close
5343 * fsp->base_fsp.
5345 base_fsp = NULL;
5347 close_file(req, fsp, ERROR_CLOSE);
5348 fsp = NULL;
5350 if (base_fsp != NULL) {
5351 close_file(req, base_fsp, ERROR_CLOSE);
5352 base_fsp = NULL;
5354 return status;
5358 * Calculate the full path name given a relative fid.
5360 NTSTATUS get_relative_fid_filename(connection_struct *conn,
5361 struct smb_request *req,
5362 uint16_t root_dir_fid,
5363 const struct smb_filename *smb_fname,
5364 struct smb_filename **smb_fname_out)
5366 files_struct *dir_fsp;
5367 char *parent_fname = NULL;
5368 char *new_base_name = NULL;
5369 uint32_t ucf_flags = ((req != NULL && req->posix_pathnames) ?
5370 UCF_POSIX_PATHNAMES : 0);
5371 NTSTATUS status;
5373 if (root_dir_fid == 0 || !smb_fname) {
5374 status = NT_STATUS_INTERNAL_ERROR;
5375 goto out;
5378 dir_fsp = file_fsp(req, root_dir_fid);
5380 if (dir_fsp == NULL) {
5381 status = NT_STATUS_INVALID_HANDLE;
5382 goto out;
5385 if (is_ntfs_stream_smb_fname(dir_fsp->fsp_name)) {
5386 status = NT_STATUS_INVALID_HANDLE;
5387 goto out;
5390 if (!dir_fsp->is_directory) {
5393 * Check to see if this is a mac fork of some kind.
5396 if ((conn->fs_capabilities & FILE_NAMED_STREAMS) &&
5397 is_ntfs_stream_smb_fname(smb_fname)) {
5398 status = NT_STATUS_OBJECT_PATH_NOT_FOUND;
5399 goto out;
5403 we need to handle the case when we get a
5404 relative open relative to a file and the
5405 pathname is blank - this is a reopen!
5406 (hint from demyn plantenberg)
5409 status = NT_STATUS_INVALID_HANDLE;
5410 goto out;
5413 if (ISDOT(dir_fsp->fsp_name->base_name)) {
5415 * We're at the toplevel dir, the final file name
5416 * must not contain ./, as this is filtered out
5417 * normally by srvstr_get_path and unix_convert
5418 * explicitly rejects paths containing ./.
5420 parent_fname = talloc_strdup(talloc_tos(), "");
5421 if (parent_fname == NULL) {
5422 status = NT_STATUS_NO_MEMORY;
5423 goto out;
5425 } else {
5426 size_t dir_name_len = strlen(dir_fsp->fsp_name->base_name);
5429 * Copy in the base directory name.
5432 parent_fname = talloc_array(talloc_tos(), char,
5433 dir_name_len+2);
5434 if (parent_fname == NULL) {
5435 status = NT_STATUS_NO_MEMORY;
5436 goto out;
5438 memcpy(parent_fname, dir_fsp->fsp_name->base_name,
5439 dir_name_len+1);
5442 * Ensure it ends in a '/'.
5443 * We used TALLOC_SIZE +2 to add space for the '/'.
5446 if(dir_name_len
5447 && (parent_fname[dir_name_len-1] != '\\')
5448 && (parent_fname[dir_name_len-1] != '/')) {
5449 parent_fname[dir_name_len] = '/';
5450 parent_fname[dir_name_len+1] = '\0';
5454 new_base_name = talloc_asprintf(talloc_tos(), "%s%s", parent_fname,
5455 smb_fname->base_name);
5456 if (new_base_name == NULL) {
5457 status = NT_STATUS_NO_MEMORY;
5458 goto out;
5461 status = filename_convert(req,
5462 conn,
5463 req->flags2 & FLAGS2_DFS_PATHNAMES,
5464 new_base_name,
5465 ucf_flags,
5466 NULL,
5467 smb_fname_out);
5468 if (!NT_STATUS_IS_OK(status)) {
5469 goto out;
5472 out:
5473 TALLOC_FREE(parent_fname);
5474 TALLOC_FREE(new_base_name);
5475 return status;
5478 NTSTATUS create_file_default(connection_struct *conn,
5479 struct smb_request *req,
5480 uint16_t root_dir_fid,
5481 struct smb_filename *smb_fname,
5482 uint32_t access_mask,
5483 uint32_t share_access,
5484 uint32_t create_disposition,
5485 uint32_t create_options,
5486 uint32_t file_attributes,
5487 uint32_t oplock_request,
5488 struct smb2_lease *lease,
5489 uint64_t allocation_size,
5490 uint32_t private_flags,
5491 struct security_descriptor *sd,
5492 struct ea_list *ea_list,
5493 files_struct **result,
5494 int *pinfo,
5495 const struct smb2_create_blobs *in_context_blobs,
5496 struct smb2_create_blobs *out_context_blobs)
5498 int info = FILE_WAS_OPENED;
5499 files_struct *fsp = NULL;
5500 NTSTATUS status;
5501 bool stream_name = false;
5503 DEBUG(10,("create_file: access_mask = 0x%x "
5504 "file_attributes = 0x%x, share_access = 0x%x, "
5505 "create_disposition = 0x%x create_options = 0x%x "
5506 "oplock_request = 0x%x "
5507 "private_flags = 0x%x "
5508 "root_dir_fid = 0x%x, ea_list = 0x%p, sd = 0x%p, "
5509 "fname = %s\n",
5510 (unsigned int)access_mask,
5511 (unsigned int)file_attributes,
5512 (unsigned int)share_access,
5513 (unsigned int)create_disposition,
5514 (unsigned int)create_options,
5515 (unsigned int)oplock_request,
5516 (unsigned int)private_flags,
5517 (unsigned int)root_dir_fid,
5518 ea_list, sd, smb_fname_str_dbg(smb_fname)));
5521 * Calculate the filename from the root_dir_if if necessary.
5524 if (root_dir_fid != 0) {
5525 struct smb_filename *smb_fname_out = NULL;
5526 status = get_relative_fid_filename(conn, req, root_dir_fid,
5527 smb_fname, &smb_fname_out);
5528 if (!NT_STATUS_IS_OK(status)) {
5529 goto fail;
5531 smb_fname = smb_fname_out;
5535 * Check to see if this is a mac fork of some kind.
5538 stream_name = is_ntfs_stream_smb_fname(smb_fname);
5539 if (stream_name) {
5540 enum FAKE_FILE_TYPE fake_file_type;
5542 fake_file_type = is_fake_file(smb_fname);
5544 if (fake_file_type != FAKE_FILE_TYPE_NONE) {
5547 * Here we go! support for changing the disk quotas
5548 * --metze
5550 * We need to fake up to open this MAGIC QUOTA file
5551 * and return a valid FID.
5553 * w2k close this file directly after openening xp
5554 * also tries a QUERY_FILE_INFO on the file and then
5555 * close it
5557 status = open_fake_file(req, conn, req->vuid,
5558 fake_file_type, smb_fname,
5559 access_mask, &fsp);
5560 if (!NT_STATUS_IS_OK(status)) {
5561 goto fail;
5564 ZERO_STRUCT(smb_fname->st);
5565 goto done;
5568 if (!(conn->fs_capabilities & FILE_NAMED_STREAMS)) {
5569 status = NT_STATUS_OBJECT_NAME_NOT_FOUND;
5570 goto fail;
5574 if (is_ntfs_default_stream_smb_fname(smb_fname)) {
5575 int ret;
5576 smb_fname->stream_name = NULL;
5577 /* We have to handle this error here. */
5578 if (create_options & FILE_DIRECTORY_FILE) {
5579 status = NT_STATUS_NOT_A_DIRECTORY;
5580 goto fail;
5582 if (req != NULL && req->posix_pathnames) {
5583 ret = SMB_VFS_LSTAT(conn, smb_fname);
5584 } else {
5585 ret = SMB_VFS_STAT(conn, smb_fname);
5588 if (ret == 0 && VALID_STAT_OF_DIR(smb_fname->st)) {
5589 status = NT_STATUS_FILE_IS_A_DIRECTORY;
5590 goto fail;
5594 status = create_file_unixpath(
5595 conn, req, smb_fname, access_mask, share_access,
5596 create_disposition, create_options, file_attributes,
5597 oplock_request, lease, allocation_size, private_flags,
5598 sd, ea_list,
5599 &fsp, &info);
5601 if (!NT_STATUS_IS_OK(status)) {
5602 goto fail;
5605 done:
5606 DEBUG(10, ("create_file: info=%d\n", info));
5608 *result = fsp;
5609 if (pinfo != NULL) {
5610 *pinfo = info;
5612 return NT_STATUS_OK;
5614 fail:
5615 DEBUG(10, ("create_file: %s\n", nt_errstr(status)));
5617 if (fsp != NULL) {
5618 close_file(req, fsp, ERROR_CLOSE);
5619 fsp = NULL;
5621 return status;