s3: smbd: Add missing out of memory check.
[Samba.git] / source3 / smbd / open.c
blobe8464ed83b2bba0e7b030bbfaf0cb48b6223f114
1 /*
2 Unix SMB/CIFS implementation.
3 file opening and share modes
4 Copyright (C) Andrew Tridgell 1992-1998
5 Copyright (C) Jeremy Allison 2001-2004
6 Copyright (C) Volker Lendecke 2005
7 Copyright (C) Ralph Boehme 2017
9 This program is free software; you can redistribute it and/or modify
10 it under the terms of the GNU General Public License as published by
11 the Free Software Foundation; either version 3 of the License, or
12 (at your option) any later version.
14 This program is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 GNU General Public License for more details.
19 You should have received a copy of the GNU General Public License
20 along with this program. If not, see <http://www.gnu.org/licenses/>.
23 #include "includes.h"
24 #include "system/filesys.h"
25 #include "lib/util/server_id.h"
26 #include "printing.h"
27 #include "smbd/smbd.h"
28 #include "smbd/globals.h"
29 #include "fake_file.h"
30 #include "../libcli/security/security.h"
31 #include "../librpc/gen_ndr/ndr_security.h"
32 #include "../librpc/gen_ndr/open_files.h"
33 #include "../librpc/gen_ndr/idmap.h"
34 #include "../librpc/gen_ndr/ioctl.h"
35 #include "passdb/lookup_sid.h"
36 #include "auth.h"
37 #include "serverid.h"
38 #include "messages.h"
39 #include "source3/lib/dbwrap/dbwrap_watch.h"
40 #include "locking/leases_db.h"
41 #include "librpc/gen_ndr/ndr_leases_db.h"
43 extern const struct generic_mapping file_generic_mapping;
45 struct deferred_open_record {
46 bool delayed_for_oplocks;
47 bool async_open;
48 struct file_id id;
51 * Timer for async opens, needed because they don't use a watch on
52 * a locking.tdb record. This is currently only used for real async
53 * opens and just terminates smbd if the async open times out.
55 struct tevent_timer *te;
58 /****************************************************************************
59 If the requester wanted DELETE_ACCESS and was rejected because
60 the file ACL didn't include DELETE_ACCESS, see if the parent ACL
61 overrides this.
62 ****************************************************************************/
64 static bool parent_override_delete(connection_struct *conn,
65 const struct smb_filename *smb_fname,
66 uint32_t access_mask,
67 uint32_t rejected_mask)
69 if ((access_mask & DELETE_ACCESS) &&
70 (rejected_mask & DELETE_ACCESS) &&
71 can_delete_file_in_directory(conn, smb_fname)) {
72 return true;
74 return false;
77 /****************************************************************************
78 Check if we have open rights.
79 ****************************************************************************/
81 NTSTATUS smbd_check_access_rights(struct connection_struct *conn,
82 const struct smb_filename *smb_fname,
83 bool use_privs,
84 uint32_t access_mask)
86 /* Check if we have rights to open. */
87 NTSTATUS status;
88 struct security_descriptor *sd = NULL;
89 uint32_t rejected_share_access;
90 uint32_t rejected_mask = access_mask;
91 uint32_t do_not_check_mask = 0;
93 rejected_share_access = access_mask & ~(conn->share_access);
95 if (rejected_share_access) {
96 DEBUG(10, ("smbd_check_access_rights: rejected share access 0x%x "
97 "on %s (0x%x)\n",
98 (unsigned int)access_mask,
99 smb_fname_str_dbg(smb_fname),
100 (unsigned int)rejected_share_access ));
101 return NT_STATUS_ACCESS_DENIED;
104 if (!use_privs && get_current_uid(conn) == (uid_t)0) {
105 /* I'm sorry sir, I didn't know you were root... */
106 DEBUG(10,("smbd_check_access_rights: root override "
107 "on %s. Granting 0x%x\n",
108 smb_fname_str_dbg(smb_fname),
109 (unsigned int)access_mask ));
110 return NT_STATUS_OK;
113 if ((access_mask & DELETE_ACCESS) && !lp_acl_check_permissions(SNUM(conn))) {
114 DEBUG(10,("smbd_check_access_rights: not checking ACL "
115 "on DELETE_ACCESS on file %s. Granting 0x%x\n",
116 smb_fname_str_dbg(smb_fname),
117 (unsigned int)access_mask ));
118 return NT_STATUS_OK;
121 if (access_mask == DELETE_ACCESS &&
122 VALID_STAT(smb_fname->st) &&
123 S_ISLNK(smb_fname->st.st_ex_mode)) {
124 /* We can always delete a symlink. */
125 DEBUG(10,("smbd_check_access_rights: not checking ACL "
126 "on DELETE_ACCESS on symlink %s.\n",
127 smb_fname_str_dbg(smb_fname) ));
128 return NT_STATUS_OK;
131 status = SMB_VFS_GET_NT_ACL(conn, smb_fname,
132 (SECINFO_OWNER |
133 SECINFO_GROUP |
134 SECINFO_DACL), talloc_tos(), &sd);
136 if (!NT_STATUS_IS_OK(status)) {
137 DEBUG(10, ("smbd_check_access_rights: Could not get acl "
138 "on %s: %s\n",
139 smb_fname_str_dbg(smb_fname),
140 nt_errstr(status)));
142 if (NT_STATUS_EQUAL(status, NT_STATUS_ACCESS_DENIED)) {
143 goto access_denied;
146 return status;
150 * If we can access the path to this file, by
151 * default we have FILE_READ_ATTRIBUTES from the
152 * containing directory. See the section:
153 * "Algorithm to Check Access to an Existing File"
154 * in MS-FSA.pdf.
156 * se_file_access_check() also takes care of
157 * owner WRITE_DAC and READ_CONTROL.
159 do_not_check_mask = FILE_READ_ATTRIBUTES;
162 * Samba 3.6 and earlier granted execute access even
163 * if the ACL did not contain execute rights.
164 * Samba 4.0 is more correct and checks it.
165 * The compatibilty mode allows one to skip this check
166 * to smoothen upgrades.
168 if (lp_acl_allow_execute_always(SNUM(conn))) {
169 do_not_check_mask |= FILE_EXECUTE;
172 status = se_file_access_check(sd,
173 get_current_nttok(conn),
174 use_privs,
175 (access_mask & ~do_not_check_mask),
176 &rejected_mask);
178 DEBUG(10,("smbd_check_access_rights: file %s requesting "
179 "0x%x returning 0x%x (%s)\n",
180 smb_fname_str_dbg(smb_fname),
181 (unsigned int)access_mask,
182 (unsigned int)rejected_mask,
183 nt_errstr(status) ));
185 if (!NT_STATUS_IS_OK(status)) {
186 if (DEBUGLEVEL >= 10) {
187 DEBUG(10,("smbd_check_access_rights: acl for %s is:\n",
188 smb_fname_str_dbg(smb_fname) ));
189 NDR_PRINT_DEBUG(security_descriptor, sd);
193 TALLOC_FREE(sd);
195 if (NT_STATUS_IS_OK(status) ||
196 !NT_STATUS_EQUAL(status, NT_STATUS_ACCESS_DENIED)) {
197 return status;
200 /* Here we know status == NT_STATUS_ACCESS_DENIED. */
202 access_denied:
204 if ((access_mask & FILE_WRITE_ATTRIBUTES) &&
205 (rejected_mask & FILE_WRITE_ATTRIBUTES) &&
206 !lp_store_dos_attributes(SNUM(conn)) &&
207 (lp_map_readonly(SNUM(conn)) ||
208 lp_map_archive(SNUM(conn)) ||
209 lp_map_hidden(SNUM(conn)) ||
210 lp_map_system(SNUM(conn)))) {
211 rejected_mask &= ~FILE_WRITE_ATTRIBUTES;
213 DEBUG(10,("smbd_check_access_rights: "
214 "overrode "
215 "FILE_WRITE_ATTRIBUTES "
216 "on file %s\n",
217 smb_fname_str_dbg(smb_fname)));
220 if (parent_override_delete(conn,
221 smb_fname,
222 access_mask,
223 rejected_mask)) {
224 /* Were we trying to do an open
225 * for delete and didn't get DELETE
226 * access (only) ? Check if the
227 * directory allows DELETE_CHILD.
228 * See here:
229 * http://blogs.msdn.com/oldnewthing/archive/2004/06/04/148426.aspx
230 * for details. */
232 rejected_mask &= ~DELETE_ACCESS;
234 DEBUG(10,("smbd_check_access_rights: "
235 "overrode "
236 "DELETE_ACCESS on "
237 "file %s\n",
238 smb_fname_str_dbg(smb_fname)));
241 if (rejected_mask != 0) {
242 return NT_STATUS_ACCESS_DENIED;
244 return NT_STATUS_OK;
247 NTSTATUS check_parent_access(struct connection_struct *conn,
248 struct smb_filename *smb_fname,
249 uint32_t access_mask)
251 NTSTATUS status;
252 char *parent_dir = NULL;
253 struct security_descriptor *parent_sd = NULL;
254 uint32_t access_granted = 0;
255 struct smb_filename *parent_smb_fname = NULL;
257 if (!parent_dirname(talloc_tos(),
258 smb_fname->base_name,
259 &parent_dir,
260 NULL)) {
261 return NT_STATUS_NO_MEMORY;
264 parent_smb_fname = synthetic_smb_fname(talloc_tos(),
265 parent_dir,
266 NULL,
267 NULL,
268 smb_fname->flags);
269 if (parent_smb_fname == NULL) {
270 return NT_STATUS_NO_MEMORY;
273 if (get_current_uid(conn) == (uid_t)0) {
274 /* I'm sorry sir, I didn't know you were root... */
275 DEBUG(10,("check_parent_access: root override "
276 "on %s. Granting 0x%x\n",
277 smb_fname_str_dbg(smb_fname),
278 (unsigned int)access_mask ));
279 return NT_STATUS_OK;
282 status = SMB_VFS_GET_NT_ACL(conn,
283 parent_smb_fname,
284 SECINFO_DACL,
285 talloc_tos(),
286 &parent_sd);
288 if (!NT_STATUS_IS_OK(status)) {
289 DEBUG(5,("check_parent_access: SMB_VFS_GET_NT_ACL failed for "
290 "%s with error %s\n",
291 parent_dir,
292 nt_errstr(status)));
293 return status;
297 * If we can access the path to this file, by
298 * default we have FILE_READ_ATTRIBUTES from the
299 * containing directory. See the section:
300 * "Algorithm to Check Access to an Existing File"
301 * in MS-FSA.pdf.
303 * se_file_access_check() also takes care of
304 * owner WRITE_DAC and READ_CONTROL.
306 status = se_file_access_check(parent_sd,
307 get_current_nttok(conn),
308 false,
309 (access_mask & ~FILE_READ_ATTRIBUTES),
310 &access_granted);
311 if(!NT_STATUS_IS_OK(status)) {
312 DEBUG(5,("check_parent_access: access check "
313 "on directory %s for "
314 "path %s for mask 0x%x returned (0x%x) %s\n",
315 parent_dir,
316 smb_fname->base_name,
317 access_mask,
318 access_granted,
319 nt_errstr(status) ));
320 return status;
323 return NT_STATUS_OK;
326 /****************************************************************************
327 Ensure when opening a base file for a stream open that we have permissions
328 to do so given the access mask on the base file.
329 ****************************************************************************/
331 static NTSTATUS check_base_file_access(struct connection_struct *conn,
332 struct smb_filename *smb_fname,
333 uint32_t access_mask)
335 NTSTATUS status;
337 status = smbd_calculate_access_mask(conn, smb_fname,
338 false,
339 access_mask,
340 &access_mask);
341 if (!NT_STATUS_IS_OK(status)) {
342 DEBUG(10, ("smbd_calculate_access_mask "
343 "on file %s returned %s\n",
344 smb_fname_str_dbg(smb_fname),
345 nt_errstr(status)));
346 return status;
349 if (access_mask & (FILE_WRITE_DATA|FILE_APPEND_DATA)) {
350 uint32_t dosattrs;
351 if (!CAN_WRITE(conn)) {
352 return NT_STATUS_ACCESS_DENIED;
354 dosattrs = dos_mode(conn, smb_fname);
355 if (IS_DOS_READONLY(dosattrs)) {
356 return NT_STATUS_ACCESS_DENIED;
360 return smbd_check_access_rights(conn,
361 smb_fname,
362 false,
363 access_mask);
366 /****************************************************************************
367 Handle differing symlink errno's
368 ****************************************************************************/
370 static int link_errno_convert(int err)
372 #if defined(ENOTSUP) && defined(OSF1)
373 /* handle special Tru64 errno */
374 if (err == ENOTSUP) {
375 err = ELOOP;
377 #endif /* ENOTSUP */
378 #ifdef EFTYPE
379 /* fix broken NetBSD errno */
380 if (err == EFTYPE) {
381 err = ELOOP;
383 #endif /* EFTYPE */
384 /* fix broken FreeBSD errno */
385 if (err == EMLINK) {
386 err = ELOOP;
388 return err;
391 static int non_widelink_open(struct connection_struct *conn,
392 const struct smb_filename *conn_rootdir_fname,
393 files_struct *fsp,
394 struct smb_filename *smb_fname,
395 int flags,
396 mode_t mode,
397 unsigned int link_depth);
399 /****************************************************************************
400 Follow a symlink in userspace.
401 ****************************************************************************/
403 static int process_symlink_open(struct connection_struct *conn,
404 const struct smb_filename *conn_rootdir_fname,
405 files_struct *fsp,
406 struct smb_filename *smb_fname,
407 int flags,
408 mode_t mode,
409 unsigned int link_depth)
411 int fd = -1;
412 char *link_target = NULL;
413 struct smb_filename target_fname = {0};
414 int link_len = -1;
415 struct smb_filename *oldwd_fname = NULL;
416 size_t rootdir_len = 0;
417 struct smb_filename *resolved_fname = NULL;
418 char *resolved_name = NULL;
419 bool matched = false;
420 int saved_errno = 0;
423 * Ensure we don't get stuck in a symlink loop.
425 link_depth++;
426 if (link_depth >= 20) {
427 errno = ELOOP;
428 goto out;
431 /* Allocate space for the link target. */
432 link_target = talloc_array(talloc_tos(), char, PATH_MAX);
433 if (link_target == NULL) {
434 errno = ENOMEM;
435 goto out;
438 /* Read the link target. */
439 link_len = SMB_VFS_READLINK(conn,
440 smb_fname,
441 link_target,
442 PATH_MAX - 1);
443 if (link_len == -1) {
444 goto out;
447 /* Ensure it's at least null terminated. */
448 link_target[link_len] = '\0';
449 target_fname = (struct smb_filename){ .base_name = link_target };
451 /* Convert to an absolute path. */
452 resolved_fname = SMB_VFS_REALPATH(conn, talloc_tos(), &target_fname);
453 if (resolved_fname == NULL) {
454 goto out;
456 resolved_name = resolved_fname->base_name;
459 * We know conn_rootdir starts with '/' and
460 * does not end in '/'. FIXME ! Should we
461 * smb_assert this ?
463 rootdir_len = strlen(conn_rootdir_fname->base_name);
465 matched = (strncmp(conn_rootdir_fname->base_name,
466 resolved_name,
467 rootdir_len) == 0);
468 if (!matched) {
469 errno = EACCES;
470 goto out;
474 * Turn into a path relative to the share root.
476 if (resolved_name[rootdir_len] == '\0') {
477 /* Link to the root of the share. */
478 TALLOC_FREE(smb_fname->base_name);
479 smb_fname->base_name = talloc_strdup(smb_fname, ".");
480 } else if (resolved_name[rootdir_len] == '/') {
481 TALLOC_FREE(smb_fname->base_name);
482 smb_fname->base_name = talloc_strdup(smb_fname,
483 &resolved_name[rootdir_len+1]);
484 } else {
485 errno = EACCES;
486 goto out;
489 if (smb_fname->base_name == NULL) {
490 errno = ENOMEM;
491 goto out;
494 oldwd_fname = vfs_GetWd(talloc_tos(), conn);
495 if (oldwd_fname == NULL) {
496 goto out;
499 /* Ensure we operate from the root of the share. */
500 if (vfs_ChDir(conn, conn_rootdir_fname) == -1) {
501 goto out;
504 /* And do it all again.. */
505 fd = non_widelink_open(conn,
506 conn_rootdir_fname,
507 fsp,
508 smb_fname,
509 flags,
510 mode,
511 link_depth);
512 if (fd == -1) {
513 saved_errno = errno;
516 out:
518 TALLOC_FREE(resolved_fname);
519 TALLOC_FREE(link_target);
520 if (oldwd_fname != NULL) {
521 int ret = vfs_ChDir(conn, oldwd_fname);
522 if (ret == -1) {
523 smb_panic("unable to get back to old directory\n");
525 TALLOC_FREE(oldwd_fname);
527 if (saved_errno != 0) {
528 errno = saved_errno;
530 return fd;
533 /****************************************************************************
534 Non-widelink open.
535 ****************************************************************************/
537 static int non_widelink_open(struct connection_struct *conn,
538 const struct smb_filename *conn_rootdir_fname,
539 files_struct *fsp,
540 struct smb_filename *smb_fname,
541 int flags,
542 mode_t mode,
543 unsigned int link_depth)
545 NTSTATUS status;
546 int fd = -1;
547 struct smb_filename *smb_fname_rel = NULL;
548 int saved_errno = 0;
549 struct smb_filename *oldwd_fname = NULL;
550 char *parent_dir = NULL;
551 struct smb_filename parent_dir_fname = {0};
552 const char *final_component = NULL;
554 if (!parent_dirname(talloc_tos(),
555 smb_fname->base_name,
556 &parent_dir,
557 &final_component)) {
558 goto out;
561 parent_dir_fname = (struct smb_filename) { .base_name = parent_dir };
563 oldwd_fname = vfs_GetWd(talloc_tos(), conn);
564 if (oldwd_fname == NULL) {
565 goto out;
568 /* Pin parent directory in place. */
569 if (vfs_ChDir(conn, &parent_dir_fname) == -1) {
570 goto out;
573 /* Ensure the relative path is below the share. */
574 status = check_reduced_name(conn, parent_dir, final_component);
575 if (!NT_STATUS_IS_OK(status)) {
576 saved_errno = map_errno_from_nt_status(status);
577 goto out;
580 smb_fname_rel = synthetic_smb_fname(talloc_tos(),
581 final_component,
582 smb_fname->stream_name,
583 &smb_fname->st,
584 smb_fname->flags);
585 if (smb_fname_rel == NULL) {
586 saved_errno = ENOMEM;
587 goto out;
590 flags |= O_NOFOLLOW;
593 struct smb_filename *tmp_name = fsp->fsp_name;
594 fsp->fsp_name = smb_fname_rel;
595 fd = SMB_VFS_OPEN(conn, smb_fname_rel, fsp, flags, mode);
596 fsp->fsp_name = tmp_name;
599 if (fd == -1) {
600 saved_errno = link_errno_convert(errno);
602 * Trying to open a symlink to a directory with O_NOFOLLOW and
603 * O_DIRECTORY can return either of ELOOP and ENOTDIR. So
604 * ENOTDIR really means: might be a symlink, but we're not sure.
605 * In this case, we just assume there's a symlink. If we were
606 * wrong, process_symlink_open() will return EINVAL. We check
607 * this below, and fall back to returning the initial
608 * saved_errno.
610 * BUG: https://bugzilla.samba.org/show_bug.cgi?id=12860
612 if (saved_errno == ELOOP || saved_errno == ENOTDIR) {
613 if (fsp->posix_flags & FSP_POSIX_FLAGS_OPEN) {
614 /* Never follow symlinks on posix open. */
615 goto out;
617 if (!lp_follow_symlinks(SNUM(conn))) {
618 /* Explicitly no symlinks. */
619 goto out;
622 * We may have a symlink. Follow in userspace
623 * to ensure it's under the share definition.
625 fd = process_symlink_open(conn,
626 conn_rootdir_fname,
627 fsp,
628 smb_fname_rel,
629 flags,
630 mode,
631 link_depth);
632 if (fd == -1) {
633 if (saved_errno == ENOTDIR &&
634 errno == EINVAL) {
636 * O_DIRECTORY on neither a directory,
637 * nor a symlink. Just return
638 * saved_errno from initial open()
640 goto out;
642 saved_errno =
643 link_errno_convert(errno);
648 out:
650 TALLOC_FREE(parent_dir);
651 TALLOC_FREE(smb_fname_rel);
653 if (oldwd_fname != NULL) {
654 int ret = vfs_ChDir(conn, oldwd_fname);
655 if (ret == -1) {
656 smb_panic("unable to get back to old directory\n");
658 TALLOC_FREE(oldwd_fname);
660 if (saved_errno != 0) {
661 errno = saved_errno;
663 return fd;
666 /****************************************************************************
667 fd support routines - attempt to do a dos_open.
668 ****************************************************************************/
670 NTSTATUS fd_open(struct connection_struct *conn,
671 files_struct *fsp,
672 int flags,
673 mode_t mode)
675 struct smb_filename *smb_fname = fsp->fsp_name;
676 NTSTATUS status = NT_STATUS_OK;
679 * Never follow symlinks on a POSIX client. The
680 * client should be doing this.
683 if ((fsp->posix_flags & FSP_POSIX_FLAGS_OPEN) || !lp_follow_symlinks(SNUM(conn))) {
684 flags |= O_NOFOLLOW;
687 /* Ensure path is below share definition. */
688 if (!lp_widelinks(SNUM(conn))) {
689 struct smb_filename *conn_rootdir_fname = NULL;
690 const char *conn_rootdir = SMB_VFS_CONNECTPATH(conn,
691 smb_fname->base_name);
692 int saved_errno = 0;
694 if (conn_rootdir == NULL) {
695 return NT_STATUS_NO_MEMORY;
697 conn_rootdir_fname = synthetic_smb_fname(talloc_tos(),
698 conn_rootdir,
699 NULL,
700 NULL,
702 if (conn_rootdir_fname == NULL) {
703 return NT_STATUS_NO_MEMORY;
707 * Only follow symlinks within a share
708 * definition.
710 fsp->fh->fd = non_widelink_open(conn,
711 conn_rootdir_fname,
712 fsp,
713 smb_fname,
714 flags,
715 mode,
717 if (fsp->fh->fd == -1) {
718 saved_errno = errno;
720 TALLOC_FREE(conn_rootdir_fname);
721 if (saved_errno != 0) {
722 errno = saved_errno;
724 } else {
725 fsp->fh->fd = SMB_VFS_OPEN(conn, smb_fname, fsp, flags, mode);
728 if (fsp->fh->fd == -1) {
729 int posix_errno = link_errno_convert(errno);
730 status = map_nt_error_from_unix(posix_errno);
731 if (errno == EMFILE) {
732 static time_t last_warned = 0L;
734 if (time((time_t *) NULL) > last_warned) {
735 DEBUG(0,("Too many open files, unable "
736 "to open more! smbd's max "
737 "open files = %d\n",
738 lp_max_open_files()));
739 last_warned = time((time_t *) NULL);
745 DEBUG(10,("fd_open: name %s, flags = 0%o mode = 0%o, fd = %d. %s\n",
746 smb_fname_str_dbg(smb_fname), flags, (int)mode, fsp->fh->fd,
747 (fsp->fh->fd == -1) ? strerror(errno) : "" ));
749 return status;
752 /****************************************************************************
753 Close the file associated with a fsp.
754 ****************************************************************************/
756 NTSTATUS fd_close(files_struct *fsp)
758 int ret;
760 if (fsp->dptr) {
761 dptr_CloseDir(fsp);
763 if (fsp->fh->fd == -1) {
764 return NT_STATUS_OK; /* What we used to call a stat open. */
766 if (fsp->fh->ref_count > 1) {
767 return NT_STATUS_OK; /* Shared handle. Only close last reference. */
770 ret = SMB_VFS_CLOSE(fsp);
771 fsp->fh->fd = -1;
772 if (ret == -1) {
773 return map_nt_error_from_unix(errno);
775 return NT_STATUS_OK;
778 /****************************************************************************
779 Change the ownership of a file to that of the parent directory.
780 Do this by fd if possible.
781 ****************************************************************************/
783 void change_file_owner_to_parent(connection_struct *conn,
784 const char *inherit_from_dir,
785 files_struct *fsp)
787 struct smb_filename *smb_fname_parent;
788 int ret;
790 smb_fname_parent = synthetic_smb_fname(talloc_tos(),
791 inherit_from_dir,
792 NULL,
793 NULL,
795 if (smb_fname_parent == NULL) {
796 return;
799 ret = SMB_VFS_STAT(conn, smb_fname_parent);
800 if (ret == -1) {
801 DEBUG(0,("change_file_owner_to_parent: failed to stat parent "
802 "directory %s. Error was %s\n",
803 smb_fname_str_dbg(smb_fname_parent),
804 strerror(errno)));
805 TALLOC_FREE(smb_fname_parent);
806 return;
809 if (smb_fname_parent->st.st_ex_uid == fsp->fsp_name->st.st_ex_uid) {
810 /* Already this uid - no need to change. */
811 DEBUG(10,("change_file_owner_to_parent: file %s "
812 "is already owned by uid %d\n",
813 fsp_str_dbg(fsp),
814 (int)fsp->fsp_name->st.st_ex_uid ));
815 TALLOC_FREE(smb_fname_parent);
816 return;
819 become_root();
820 ret = SMB_VFS_FCHOWN(fsp, smb_fname_parent->st.st_ex_uid, (gid_t)-1);
821 unbecome_root();
822 if (ret == -1) {
823 DEBUG(0,("change_file_owner_to_parent: failed to fchown "
824 "file %s to parent directory uid %u. Error "
825 "was %s\n", fsp_str_dbg(fsp),
826 (unsigned int)smb_fname_parent->st.st_ex_uid,
827 strerror(errno) ));
828 } else {
829 DEBUG(10,("change_file_owner_to_parent: changed new file %s to "
830 "parent directory uid %u.\n", fsp_str_dbg(fsp),
831 (unsigned int)smb_fname_parent->st.st_ex_uid));
832 /* Ensure the uid entry is updated. */
833 fsp->fsp_name->st.st_ex_uid = smb_fname_parent->st.st_ex_uid;
836 TALLOC_FREE(smb_fname_parent);
839 static NTSTATUS change_dir_owner_to_parent(connection_struct *conn,
840 const char *inherit_from_dir,
841 struct smb_filename *smb_dname,
842 SMB_STRUCT_STAT *psbuf)
844 struct smb_filename *smb_fname_parent;
845 struct smb_filename *smb_fname_cwd = NULL;
846 struct smb_filename *saved_dir_fname = NULL;
847 TALLOC_CTX *ctx = talloc_tos();
848 NTSTATUS status = NT_STATUS_OK;
849 int ret;
851 smb_fname_parent = synthetic_smb_fname(ctx,
852 inherit_from_dir,
853 NULL,
854 NULL,
856 if (smb_fname_parent == NULL) {
857 return NT_STATUS_NO_MEMORY;
860 ret = SMB_VFS_STAT(conn, smb_fname_parent);
861 if (ret == -1) {
862 status = map_nt_error_from_unix(errno);
863 DEBUG(0,("change_dir_owner_to_parent: failed to stat parent "
864 "directory %s. Error was %s\n",
865 smb_fname_str_dbg(smb_fname_parent),
866 strerror(errno)));
867 goto out;
870 /* We've already done an lstat into psbuf, and we know it's a
871 directory. If we can cd into the directory and the dev/ino
872 are the same then we can safely chown without races as
873 we're locking the directory in place by being in it. This
874 should work on any UNIX (thanks tridge :-). JRA.
877 saved_dir_fname = vfs_GetWd(ctx,conn);
878 if (!saved_dir_fname) {
879 status = map_nt_error_from_unix(errno);
880 DEBUG(0,("change_dir_owner_to_parent: failed to get "
881 "current working directory. Error was %s\n",
882 strerror(errno)));
883 goto out;
886 /* Chdir into the new path. */
887 if (vfs_ChDir(conn, smb_dname) == -1) {
888 status = map_nt_error_from_unix(errno);
889 DEBUG(0,("change_dir_owner_to_parent: failed to change "
890 "current working directory to %s. Error "
891 "was %s\n", smb_dname->base_name, strerror(errno) ));
892 goto chdir;
895 smb_fname_cwd = synthetic_smb_fname(ctx, ".", NULL, NULL, 0);
896 if (smb_fname_cwd == NULL) {
897 status = NT_STATUS_NO_MEMORY;
898 goto chdir;
901 ret = SMB_VFS_STAT(conn, smb_fname_cwd);
902 if (ret == -1) {
903 status = map_nt_error_from_unix(errno);
904 DEBUG(0,("change_dir_owner_to_parent: failed to stat "
905 "directory '.' (%s) Error was %s\n",
906 smb_dname->base_name, strerror(errno)));
907 goto chdir;
910 /* Ensure we're pointing at the same place. */
911 if (smb_fname_cwd->st.st_ex_dev != psbuf->st_ex_dev ||
912 smb_fname_cwd->st.st_ex_ino != psbuf->st_ex_ino) {
913 DEBUG(0,("change_dir_owner_to_parent: "
914 "device/inode on directory %s changed. "
915 "Refusing to chown !\n",
916 smb_dname->base_name ));
917 status = NT_STATUS_ACCESS_DENIED;
918 goto chdir;
921 if (smb_fname_parent->st.st_ex_uid == smb_fname_cwd->st.st_ex_uid) {
922 /* Already this uid - no need to change. */
923 DEBUG(10,("change_dir_owner_to_parent: directory %s "
924 "is already owned by uid %d\n",
925 smb_dname->base_name,
926 (int)smb_fname_cwd->st.st_ex_uid ));
927 status = NT_STATUS_OK;
928 goto chdir;
931 become_root();
932 ret = SMB_VFS_LCHOWN(conn,
933 smb_fname_cwd,
934 smb_fname_parent->st.st_ex_uid,
935 (gid_t)-1);
936 unbecome_root();
937 if (ret == -1) {
938 status = map_nt_error_from_unix(errno);
939 DEBUG(10,("change_dir_owner_to_parent: failed to chown "
940 "directory %s to parent directory uid %u. "
941 "Error was %s\n",
942 smb_dname->base_name,
943 (unsigned int)smb_fname_parent->st.st_ex_uid,
944 strerror(errno) ));
945 } else {
946 DEBUG(10,("change_dir_owner_to_parent: changed ownership of new "
947 "directory %s to parent directory uid %u.\n",
948 smb_dname->base_name,
949 (unsigned int)smb_fname_parent->st.st_ex_uid ));
950 /* Ensure the uid entry is updated. */
951 psbuf->st_ex_uid = smb_fname_parent->st.st_ex_uid;
954 chdir:
955 vfs_ChDir(conn, saved_dir_fname);
956 out:
957 TALLOC_FREE(saved_dir_fname);
958 TALLOC_FREE(smb_fname_parent);
959 TALLOC_FREE(smb_fname_cwd);
960 return status;
963 /****************************************************************************
964 Open a file - returning a guaranteed ATOMIC indication of if the
965 file was created or not.
966 ****************************************************************************/
968 static NTSTATUS fd_open_atomic(struct connection_struct *conn,
969 files_struct *fsp,
970 int flags,
971 mode_t mode,
972 bool *file_created)
974 NTSTATUS status = NT_STATUS_UNSUCCESSFUL;
975 NTSTATUS retry_status;
976 bool file_existed = VALID_STAT(fsp->fsp_name->st);
977 int curr_flags;
979 *file_created = false;
981 if (!(flags & O_CREAT)) {
983 * We're not creating the file, just pass through.
985 return fd_open(conn, fsp, flags, mode);
988 if (flags & O_EXCL) {
990 * Fail if already exists, just pass through.
992 status = fd_open(conn, fsp, flags, mode);
995 * Here we've opened with O_CREAT|O_EXCL. If that went
996 * NT_STATUS_OK, we *know* we created this file.
998 *file_created = NT_STATUS_IS_OK(status);
1000 return status;
1004 * Now it gets tricky. We have O_CREAT, but not O_EXCL.
1005 * To know absolutely if we created the file or not,
1006 * we can never call O_CREAT without O_EXCL. So if
1007 * we think the file existed, try without O_CREAT|O_EXCL.
1008 * If we think the file didn't exist, try with
1009 * O_CREAT|O_EXCL.
1011 * The big problem here is dangling symlinks. Opening
1012 * without O_NOFOLLOW means both bad symlink
1013 * and missing path return -1, ENOENT from open(). As POSIX
1014 * is pathname based it's not possible to tell
1015 * the difference between these two cases in a
1016 * non-racy way, so change to try only two attempts before
1017 * giving up.
1019 * We don't have this problem for the O_NOFOLLOW
1020 * case as it just returns NT_STATUS_OBJECT_PATH_NOT_FOUND
1021 * mapped from the ELOOP POSIX error.
1024 curr_flags = flags;
1026 if (file_existed) {
1027 curr_flags &= ~(O_CREAT);
1028 retry_status = NT_STATUS_OBJECT_NAME_NOT_FOUND;
1029 } else {
1030 curr_flags |= O_EXCL;
1031 retry_status = NT_STATUS_OBJECT_NAME_COLLISION;
1034 status = fd_open(conn, fsp, curr_flags, mode);
1035 if (NT_STATUS_IS_OK(status)) {
1036 if (!file_existed) {
1037 *file_created = true;
1039 return NT_STATUS_OK;
1041 if (!NT_STATUS_EQUAL(status, retry_status)) {
1042 return status;
1045 curr_flags = flags;
1048 * Keep file_existed up to date for clarity.
1050 if (NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
1051 file_existed = false;
1052 curr_flags |= O_EXCL;
1053 DBG_DEBUG("file %s did not exist. Retry.\n",
1054 smb_fname_str_dbg(fsp->fsp_name));
1055 } else {
1056 file_existed = true;
1057 curr_flags &= ~(O_CREAT);
1058 DBG_DEBUG("file %s existed. Retry.\n",
1059 smb_fname_str_dbg(fsp->fsp_name));
1062 status = fd_open(conn, fsp, curr_flags, mode);
1064 if (NT_STATUS_IS_OK(status) && (!file_existed)) {
1065 *file_created = true;
1068 return status;
1071 /****************************************************************************
1072 Open a file.
1073 ****************************************************************************/
1075 static NTSTATUS open_file(files_struct *fsp,
1076 connection_struct *conn,
1077 struct smb_request *req,
1078 const char *parent_dir,
1079 int flags,
1080 mode_t unx_mode,
1081 uint32_t access_mask, /* client requested access mask. */
1082 uint32_t open_access_mask, /* what we're actually using in the open. */
1083 bool *p_file_created)
1085 struct smb_filename *smb_fname = fsp->fsp_name;
1086 NTSTATUS status = NT_STATUS_OK;
1087 int accmode = (flags & O_ACCMODE);
1088 int local_flags = flags;
1089 bool file_existed = VALID_STAT(fsp->fsp_name->st);
1091 fsp->fh->fd = -1;
1092 errno = EPERM;
1094 /* Check permissions */
1097 * This code was changed after seeing a client open request
1098 * containing the open mode of (DENY_WRITE/read-only) with
1099 * the 'create if not exist' bit set. The previous code
1100 * would fail to open the file read only on a read-only share
1101 * as it was checking the flags parameter directly against O_RDONLY,
1102 * this was failing as the flags parameter was set to O_RDONLY|O_CREAT.
1103 * JRA.
1106 if (!CAN_WRITE(conn)) {
1107 /* It's a read-only share - fail if we wanted to write. */
1108 if(accmode != O_RDONLY || (flags & O_TRUNC) || (flags & O_APPEND)) {
1109 DEBUG(3,("Permission denied opening %s\n",
1110 smb_fname_str_dbg(smb_fname)));
1111 return NT_STATUS_ACCESS_DENIED;
1113 if (flags & O_CREAT) {
1114 /* We don't want to write - but we must make sure that
1115 O_CREAT doesn't create the file if we have write
1116 access into the directory.
1118 flags &= ~(O_CREAT|O_EXCL);
1119 local_flags &= ~(O_CREAT|O_EXCL);
1124 * This little piece of insanity is inspired by the
1125 * fact that an NT client can open a file for O_RDONLY,
1126 * but set the create disposition to FILE_EXISTS_TRUNCATE.
1127 * If the client *can* write to the file, then it expects to
1128 * truncate the file, even though it is opening for readonly.
1129 * Quicken uses this stupid trick in backup file creation...
1130 * Thanks *greatly* to "David W. Chapman Jr." <dwcjr@inethouston.net>
1131 * for helping track this one down. It didn't bite us in 2.0.x
1132 * as we always opened files read-write in that release. JRA.
1135 if ((accmode == O_RDONLY) && ((flags & O_TRUNC) == O_TRUNC)) {
1136 DEBUG(10,("open_file: truncate requested on read-only open "
1137 "for file %s\n", smb_fname_str_dbg(smb_fname)));
1138 local_flags = (flags & ~O_ACCMODE)|O_RDWR;
1141 if ((open_access_mask & (FILE_READ_DATA|FILE_WRITE_DATA|FILE_APPEND_DATA|FILE_EXECUTE)) ||
1142 (!file_existed && (local_flags & O_CREAT)) ||
1143 ((local_flags & O_TRUNC) == O_TRUNC) ) {
1144 const char *wild;
1145 int ret;
1147 #if defined(O_NONBLOCK) && defined(S_ISFIFO)
1149 * We would block on opening a FIFO with no one else on the
1150 * other end. Do what we used to do and add O_NONBLOCK to the
1151 * open flags. JRA.
1154 if (file_existed && S_ISFIFO(smb_fname->st.st_ex_mode)) {
1155 local_flags &= ~O_TRUNC; /* Can't truncate a FIFO. */
1156 local_flags |= O_NONBLOCK;
1158 #endif
1160 /* Don't create files with Microsoft wildcard characters. */
1161 if (fsp->base_fsp) {
1163 * wildcard characters are allowed in stream names
1164 * only test the basefilename
1166 wild = fsp->base_fsp->fsp_name->base_name;
1167 } else {
1168 wild = smb_fname->base_name;
1170 if ((local_flags & O_CREAT) && !file_existed &&
1171 !(fsp->posix_flags & FSP_POSIX_FLAGS_PATHNAMES) &&
1172 ms_has_wild(wild)) {
1173 return NT_STATUS_OBJECT_NAME_INVALID;
1176 /* Can we access this file ? */
1177 if (!fsp->base_fsp) {
1178 /* Only do this check on non-stream open. */
1179 if (file_existed) {
1180 status = smbd_check_access_rights(conn,
1181 smb_fname,
1182 false,
1183 access_mask);
1185 if (!NT_STATUS_IS_OK(status)) {
1186 DEBUG(10, ("open_file: "
1187 "smbd_check_access_rights "
1188 "on file %s returned %s\n",
1189 smb_fname_str_dbg(smb_fname),
1190 nt_errstr(status)));
1193 if (!NT_STATUS_IS_OK(status) &&
1194 !NT_STATUS_EQUAL(status,
1195 NT_STATUS_OBJECT_NAME_NOT_FOUND))
1197 return status;
1200 if (NT_STATUS_EQUAL(status,
1201 NT_STATUS_OBJECT_NAME_NOT_FOUND))
1203 DEBUG(10, ("open_file: "
1204 "file %s vanished since we "
1205 "checked for existence.\n",
1206 smb_fname_str_dbg(smb_fname)));
1207 file_existed = false;
1208 SET_STAT_INVALID(fsp->fsp_name->st);
1212 if (!file_existed) {
1213 if (!(local_flags & O_CREAT)) {
1214 /* File didn't exist and no O_CREAT. */
1215 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
1218 status = check_parent_access(conn,
1219 smb_fname,
1220 SEC_DIR_ADD_FILE);
1221 if (!NT_STATUS_IS_OK(status)) {
1222 DEBUG(10, ("open_file: "
1223 "check_parent_access on "
1224 "file %s returned %s\n",
1225 smb_fname_str_dbg(smb_fname),
1226 nt_errstr(status) ));
1227 return status;
1233 * Actually do the open - if O_TRUNC is needed handle it
1234 * below under the share mode lock.
1236 status = fd_open_atomic(conn, fsp, local_flags & ~O_TRUNC,
1237 unx_mode, p_file_created);
1238 if (!NT_STATUS_IS_OK(status)) {
1239 DEBUG(3,("Error opening file %s (%s) (local_flags=%d) "
1240 "(flags=%d)\n", smb_fname_str_dbg(smb_fname),
1241 nt_errstr(status),local_flags,flags));
1242 return status;
1245 if (local_flags & O_NONBLOCK) {
1247 * GPFS can return ETIMEDOUT for pread on
1248 * nonblocking file descriptors when files
1249 * migrated to tape need to be recalled. I
1250 * could imagine this happens elsehwere
1251 * too. With blocking file descriptors this
1252 * does not happen.
1254 ret = set_blocking(fsp->fh->fd, true);
1255 if (ret == -1) {
1256 status = map_nt_error_from_unix(errno);
1257 DBG_WARNING("Could not set fd to blocking: "
1258 "%s\n", strerror(errno));
1259 fd_close(fsp);
1260 return status;
1264 ret = SMB_VFS_FSTAT(fsp, &smb_fname->st);
1265 if (ret == -1) {
1266 /* If we have an fd, this stat should succeed. */
1267 DEBUG(0,("Error doing fstat on open file %s "
1268 "(%s)\n",
1269 smb_fname_str_dbg(smb_fname),
1270 strerror(errno) ));
1271 status = map_nt_error_from_unix(errno);
1272 fd_close(fsp);
1273 return status;
1276 if (*p_file_created) {
1277 /* We created this file. */
1279 bool need_re_stat = false;
1280 /* Do all inheritance work after we've
1281 done a successful fstat call and filled
1282 in the stat struct in fsp->fsp_name. */
1284 /* Inherit the ACL if required */
1285 if (lp_inherit_permissions(SNUM(conn))) {
1286 inherit_access_posix_acl(conn, parent_dir,
1287 smb_fname,
1288 unx_mode);
1289 need_re_stat = true;
1292 /* Change the owner if required. */
1293 if (lp_inherit_owner(SNUM(conn)) != INHERIT_OWNER_NO) {
1294 change_file_owner_to_parent(conn, parent_dir,
1295 fsp);
1296 need_re_stat = true;
1299 if (need_re_stat) {
1300 ret = SMB_VFS_FSTAT(fsp, &smb_fname->st);
1301 /* If we have an fd, this stat should succeed. */
1302 if (ret == -1) {
1303 DEBUG(0,("Error doing fstat on open file %s "
1304 "(%s)\n",
1305 smb_fname_str_dbg(smb_fname),
1306 strerror(errno) ));
1310 notify_fname(conn, NOTIFY_ACTION_ADDED,
1311 FILE_NOTIFY_CHANGE_FILE_NAME,
1312 smb_fname->base_name);
1314 } else {
1315 fsp->fh->fd = -1; /* What we used to call a stat open. */
1316 if (!file_existed) {
1317 /* File must exist for a stat open. */
1318 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
1321 status = smbd_check_access_rights(conn,
1322 smb_fname,
1323 false,
1324 access_mask);
1326 if (NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND) &&
1327 (fsp->posix_flags & FSP_POSIX_FLAGS_OPEN) &&
1328 S_ISLNK(smb_fname->st.st_ex_mode)) {
1329 /* This is a POSIX stat open for delete
1330 * or rename on a symlink that points
1331 * nowhere. Allow. */
1332 DEBUG(10,("open_file: allowing POSIX "
1333 "open on bad symlink %s\n",
1334 smb_fname_str_dbg(smb_fname)));
1335 status = NT_STATUS_OK;
1338 if (!NT_STATUS_IS_OK(status)) {
1339 DEBUG(10,("open_file: "
1340 "smbd_check_access_rights on file "
1341 "%s returned %s\n",
1342 smb_fname_str_dbg(smb_fname),
1343 nt_errstr(status) ));
1344 return status;
1349 * POSIX allows read-only opens of directories. We don't
1350 * want to do this (we use a different code path for this)
1351 * so catch a directory open and return an EISDIR. JRA.
1354 if(S_ISDIR(smb_fname->st.st_ex_mode)) {
1355 fd_close(fsp);
1356 errno = EISDIR;
1357 return NT_STATUS_FILE_IS_A_DIRECTORY;
1360 fsp->file_id = vfs_file_id_from_sbuf(conn, &smb_fname->st);
1361 fsp->vuid = req ? req->vuid : UID_FIELD_INVALID;
1362 fsp->file_pid = req ? req->smbpid : 0;
1363 fsp->can_lock = True;
1364 fsp->can_read = ((access_mask & FILE_READ_DATA) != 0);
1365 fsp->can_write =
1366 CAN_WRITE(conn) &&
1367 ((access_mask & (FILE_WRITE_DATA | FILE_APPEND_DATA)) != 0);
1368 fsp->print_file = NULL;
1369 fsp->modified = False;
1370 fsp->sent_oplock_break = NO_BREAK_SENT;
1371 fsp->is_directory = False;
1372 if (conn->aio_write_behind_list &&
1373 is_in_path(smb_fname->base_name, conn->aio_write_behind_list,
1374 conn->case_sensitive)) {
1375 fsp->aio_write_behind = True;
1378 fsp->wcp = NULL; /* Write cache pointer. */
1380 DEBUG(2,("%s opened file %s read=%s write=%s (numopen=%d)\n",
1381 conn->session_info->unix_info->unix_name,
1382 smb_fname_str_dbg(smb_fname),
1383 BOOLSTR(fsp->can_read), BOOLSTR(fsp->can_write),
1384 conn->num_files_open));
1386 errno = 0;
1387 return NT_STATUS_OK;
1390 /****************************************************************************
1391 Check if we can open a file with a share mode.
1392 Returns True if conflict, False if not.
1393 ****************************************************************************/
1395 static bool share_conflict(struct share_mode_entry *entry,
1396 uint32_t access_mask,
1397 uint32_t share_access)
1399 DEBUG(10,("share_conflict: entry->access_mask = 0x%x, "
1400 "entry->share_access = 0x%x, "
1401 "entry->private_options = 0x%x\n",
1402 (unsigned int)entry->access_mask,
1403 (unsigned int)entry->share_access,
1404 (unsigned int)entry->private_options));
1406 if (server_id_is_disconnected(&entry->pid)) {
1408 * note: cleanup should have been done by
1409 * delay_for_batch_oplocks()
1411 return false;
1414 DEBUG(10,("share_conflict: access_mask = 0x%x, share_access = 0x%x\n",
1415 (unsigned int)access_mask, (unsigned int)share_access));
1417 if ((entry->access_mask & (FILE_WRITE_DATA|
1418 FILE_APPEND_DATA|
1419 FILE_READ_DATA|
1420 FILE_EXECUTE|
1421 DELETE_ACCESS)) == 0) {
1422 DEBUG(10,("share_conflict: No conflict due to "
1423 "entry->access_mask = 0x%x\n",
1424 (unsigned int)entry->access_mask ));
1425 return False;
1428 if ((access_mask & (FILE_WRITE_DATA|
1429 FILE_APPEND_DATA|
1430 FILE_READ_DATA|
1431 FILE_EXECUTE|
1432 DELETE_ACCESS)) == 0) {
1433 DEBUG(10,("share_conflict: No conflict due to "
1434 "access_mask = 0x%x\n",
1435 (unsigned int)access_mask ));
1436 return False;
1439 #if 1 /* JRA TEST - Superdebug. */
1440 #define CHECK_MASK(num, am, right, sa, share) \
1441 DEBUG(10,("share_conflict: [%d] am (0x%x) & right (0x%x) = 0x%x\n", \
1442 (unsigned int)(num), (unsigned int)(am), \
1443 (unsigned int)(right), (unsigned int)(am)&(right) )); \
1444 DEBUG(10,("share_conflict: [%d] sa (0x%x) & share (0x%x) = 0x%x\n", \
1445 (unsigned int)(num), (unsigned int)(sa), \
1446 (unsigned int)(share), (unsigned int)(sa)&(share) )); \
1447 if (((am) & (right)) && !((sa) & (share))) { \
1448 DEBUG(10,("share_conflict: check %d conflict am = 0x%x, right = 0x%x, \
1449 sa = 0x%x, share = 0x%x\n", (num), (unsigned int)(am), (unsigned int)(right), (unsigned int)(sa), \
1450 (unsigned int)(share) )); \
1451 return True; \
1453 #else
1454 #define CHECK_MASK(num, am, right, sa, share) \
1455 if (((am) & (right)) && !((sa) & (share))) { \
1456 DEBUG(10,("share_conflict: check %d conflict am = 0x%x, right = 0x%x, \
1457 sa = 0x%x, share = 0x%x\n", (num), (unsigned int)(am), (unsigned int)(right), (unsigned int)(sa), \
1458 (unsigned int)(share) )); \
1459 return True; \
1461 #endif
1463 CHECK_MASK(1, entry->access_mask, FILE_WRITE_DATA | FILE_APPEND_DATA,
1464 share_access, FILE_SHARE_WRITE);
1465 CHECK_MASK(2, access_mask, FILE_WRITE_DATA | FILE_APPEND_DATA,
1466 entry->share_access, FILE_SHARE_WRITE);
1468 CHECK_MASK(3, entry->access_mask, FILE_READ_DATA | FILE_EXECUTE,
1469 share_access, FILE_SHARE_READ);
1470 CHECK_MASK(4, access_mask, FILE_READ_DATA | FILE_EXECUTE,
1471 entry->share_access, FILE_SHARE_READ);
1473 CHECK_MASK(5, entry->access_mask, DELETE_ACCESS,
1474 share_access, FILE_SHARE_DELETE);
1475 CHECK_MASK(6, access_mask, DELETE_ACCESS,
1476 entry->share_access, FILE_SHARE_DELETE);
1478 DEBUG(10,("share_conflict: No conflict.\n"));
1479 return False;
1482 #if defined(DEVELOPER)
1483 static void validate_my_share_entries(struct smbd_server_connection *sconn,
1484 int num,
1485 struct share_mode_entry *share_entry)
1487 struct server_id self = messaging_server_id(sconn->msg_ctx);
1488 files_struct *fsp;
1490 if (!serverid_equal(&self, &share_entry->pid)) {
1491 return;
1494 if (share_entry->op_mid == 0) {
1495 /* INTERNAL_OPEN_ONLY */
1496 return;
1499 if (!is_valid_share_mode_entry(share_entry)) {
1500 return;
1503 fsp = file_find_dif(sconn, share_entry->id,
1504 share_entry->share_file_id);
1505 if (!fsp) {
1506 DEBUG(0,("validate_my_share_entries: PANIC : %s\n",
1507 share_mode_str(talloc_tos(), num, share_entry) ));
1508 smb_panic("validate_my_share_entries: Cannot match a "
1509 "share entry with an open file\n");
1512 if (((uint16_t)fsp->oplock_type) != share_entry->op_type) {
1513 goto panic;
1516 return;
1518 panic:
1520 char *str;
1521 DEBUG(0,("validate_my_share_entries: PANIC : %s\n",
1522 share_mode_str(talloc_tos(), num, share_entry) ));
1523 str = talloc_asprintf(talloc_tos(),
1524 "validate_my_share_entries: "
1525 "file %s, oplock_type = 0x%x, op_type = 0x%x\n",
1526 fsp->fsp_name->base_name,
1527 (unsigned int)fsp->oplock_type,
1528 (unsigned int)share_entry->op_type );
1529 smb_panic(str);
1532 #endif
1534 bool is_stat_open(uint32_t access_mask)
1536 const uint32_t stat_open_bits =
1537 (SYNCHRONIZE_ACCESS|
1538 FILE_READ_ATTRIBUTES|
1539 FILE_WRITE_ATTRIBUTES);
1541 return (((access_mask & stat_open_bits) != 0) &&
1542 ((access_mask & ~stat_open_bits) == 0));
1545 static bool has_delete_on_close(struct share_mode_lock *lck,
1546 uint32_t name_hash)
1548 struct share_mode_data *d = lck->data;
1549 uint32_t i;
1551 if (d->num_share_modes == 0) {
1552 return false;
1554 if (!is_delete_on_close_set(lck, name_hash)) {
1555 return false;
1557 for (i=0; i<d->num_share_modes; i++) {
1558 if (!share_mode_stale_pid(d, i)) {
1559 return true;
1562 return false;
1565 /****************************************************************************
1566 Deal with share modes
1567 Invariant: Share mode must be locked on entry and exit.
1568 Returns -1 on error, or number of share modes on success (may be zero).
1569 ****************************************************************************/
1571 static NTSTATUS open_mode_check(connection_struct *conn,
1572 struct share_mode_lock *lck,
1573 uint32_t access_mask,
1574 uint32_t share_access)
1576 uint32_t i;
1578 if(lck->data->num_share_modes == 0) {
1579 return NT_STATUS_OK;
1582 if (is_stat_open(access_mask)) {
1583 /* Stat open that doesn't trigger oplock breaks or share mode
1584 * checks... ! JRA. */
1585 return NT_STATUS_OK;
1589 * Check if the share modes will give us access.
1592 #if defined(DEVELOPER)
1593 for(i = 0; i < lck->data->num_share_modes; i++) {
1594 validate_my_share_entries(conn->sconn, i,
1595 &lck->data->share_modes[i]);
1597 #endif
1599 /* Now we check the share modes, after any oplock breaks. */
1600 for(i = 0; i < lck->data->num_share_modes; i++) {
1602 if (!is_valid_share_mode_entry(&lck->data->share_modes[i])) {
1603 continue;
1606 /* someone else has a share lock on it, check to see if we can
1607 * too */
1608 if (share_conflict(&lck->data->share_modes[i],
1609 access_mask, share_access)) {
1611 if (share_mode_stale_pid(lck->data, i)) {
1612 continue;
1615 return NT_STATUS_SHARING_VIOLATION;
1619 return NT_STATUS_OK;
1623 * Send a break message to the oplock holder and delay the open for
1624 * our client.
1627 NTSTATUS send_break_message(struct messaging_context *msg_ctx,
1628 const struct share_mode_entry *exclusive,
1629 uint16_t break_to)
1631 NTSTATUS status;
1632 char msg[MSG_SMB_SHARE_MODE_ENTRY_SIZE];
1633 struct server_id_buf tmp;
1635 DEBUG(10, ("Sending break request to PID %s\n",
1636 server_id_str_buf(exclusive->pid, &tmp)));
1638 /* Create the message. */
1639 share_mode_entry_to_message(msg, exclusive);
1641 /* Overload entry->op_type */
1643 * This is a cut from uint32_t to uint16_t, but so far only the lower 3
1644 * bits (LEASE_WRITE/HANDLE/READ are used anyway.
1646 SSVAL(msg,OP_BREAK_MSG_OP_TYPE_OFFSET, break_to);
1648 status = messaging_send_buf(msg_ctx, exclusive->pid,
1649 MSG_SMB_BREAK_REQUEST,
1650 (uint8_t *)msg, sizeof(msg));
1651 if (!NT_STATUS_IS_OK(status)) {
1652 DEBUG(3, ("Could not send oplock break message: %s\n",
1653 nt_errstr(status)));
1656 return status;
1660 * Do internal consistency checks on the share mode for a file.
1663 static bool validate_oplock_types(struct share_mode_lock *lck)
1665 struct share_mode_data *d = lck->data;
1666 bool batch = false;
1667 bool ex_or_batch = false;
1668 bool level2 = false;
1669 bool no_oplock = false;
1670 uint32_t num_non_stat_opens = 0;
1671 uint32_t i;
1673 for (i=0; i<d->num_share_modes; i++) {
1674 struct share_mode_entry *e = &d->share_modes[i];
1676 if (!is_valid_share_mode_entry(e)) {
1677 continue;
1680 if (e->op_mid == 0) {
1681 /* INTERNAL_OPEN_ONLY */
1682 continue;
1685 if (e->op_type == NO_OPLOCK && is_stat_open(e->access_mask)) {
1686 /* We ignore stat opens in the table - they
1687 always have NO_OPLOCK and never get or
1688 cause breaks. JRA. */
1689 continue;
1692 num_non_stat_opens += 1;
1694 if (BATCH_OPLOCK_TYPE(e->op_type)) {
1695 /* batch - can only be one. */
1696 if (share_mode_stale_pid(d, i)) {
1697 DEBUG(10, ("Found stale batch oplock\n"));
1698 continue;
1700 if (ex_or_batch || batch || level2 || no_oplock) {
1701 DEBUG(0, ("Bad batch oplock entry %u.",
1702 (unsigned)i));
1703 return false;
1705 batch = true;
1708 if (EXCLUSIVE_OPLOCK_TYPE(e->op_type)) {
1709 if (share_mode_stale_pid(d, i)) {
1710 DEBUG(10, ("Found stale duplicate oplock\n"));
1711 continue;
1713 /* Exclusive or batch - can only be one. */
1714 if (ex_or_batch || level2 || no_oplock) {
1715 DEBUG(0, ("Bad exclusive or batch oplock "
1716 "entry %u.", (unsigned)i));
1717 return false;
1719 ex_or_batch = true;
1722 if (LEVEL_II_OPLOCK_TYPE(e->op_type)) {
1723 if (batch || ex_or_batch) {
1724 if (share_mode_stale_pid(d, i)) {
1725 DEBUG(10, ("Found stale LevelII "
1726 "oplock\n"));
1727 continue;
1729 DEBUG(0, ("Bad levelII oplock entry %u.",
1730 (unsigned)i));
1731 return false;
1733 level2 = true;
1736 if (e->op_type == NO_OPLOCK) {
1737 if (batch || ex_or_batch) {
1738 if (share_mode_stale_pid(d, i)) {
1739 DEBUG(10, ("Found stale NO_OPLOCK "
1740 "entry\n"));
1741 continue;
1743 DEBUG(0, ("Bad no oplock entry %u.",
1744 (unsigned)i));
1745 return false;
1747 no_oplock = true;
1751 remove_stale_share_mode_entries(d);
1753 if ((batch || ex_or_batch) && (num_non_stat_opens != 1)) {
1754 DEBUG(1, ("got batch (%d) or ex (%d) non-exclusively (%d)\n",
1755 (int)batch, (int)ex_or_batch,
1756 (int)d->num_share_modes));
1757 return false;
1760 return true;
1763 static bool delay_for_oplock(files_struct *fsp,
1764 int oplock_request,
1765 const struct smb2_lease *lease,
1766 struct share_mode_lock *lck,
1767 bool have_sharing_violation,
1768 uint32_t create_disposition,
1769 bool first_open_attempt)
1771 struct share_mode_data *d = lck->data;
1772 uint32_t i;
1773 bool delay = false;
1774 bool will_overwrite;
1776 if ((oplock_request & INTERNAL_OPEN_ONLY) ||
1777 is_stat_open(fsp->access_mask)) {
1778 return false;
1781 switch (create_disposition) {
1782 case FILE_SUPERSEDE:
1783 case FILE_OVERWRITE:
1784 case FILE_OVERWRITE_IF:
1785 will_overwrite = true;
1786 break;
1787 default:
1788 will_overwrite = false;
1789 break;
1792 for (i=0; i<d->num_share_modes; i++) {
1793 struct share_mode_entry *e = &d->share_modes[i];
1794 struct share_mode_lease *l = NULL;
1795 uint32_t e_lease_type = get_lease_type(d, e);
1796 uint32_t break_to;
1797 uint32_t delay_mask = 0;
1799 if (e->op_type == LEASE_OPLOCK) {
1800 l = &d->leases[e->lease_idx];
1803 if (have_sharing_violation) {
1804 delay_mask = SMB2_LEASE_HANDLE;
1805 } else {
1806 delay_mask = SMB2_LEASE_WRITE;
1809 break_to = e_lease_type & ~delay_mask;
1811 if (will_overwrite) {
1813 * we'll decide about SMB2_LEASE_READ later.
1815 * Maybe the break will be deferred
1817 break_to &= ~SMB2_LEASE_HANDLE;
1820 DEBUG(10, ("entry %u: e_lease_type %u, will_overwrite: %u\n",
1821 (unsigned)i, (unsigned)e_lease_type,
1822 (unsigned)will_overwrite));
1824 if (lease != NULL && l != NULL) {
1825 bool ign;
1827 ign = smb2_lease_equal(fsp_client_guid(fsp),
1828 &lease->lease_key,
1829 &l->client_guid,
1830 &l->lease_key);
1831 if (ign) {
1832 continue;
1836 if ((e_lease_type & ~break_to) == 0) {
1837 if (l != NULL && l->breaking) {
1838 delay = true;
1840 continue;
1843 if (share_mode_stale_pid(d, i)) {
1844 continue;
1847 if (will_overwrite) {
1849 * If we break anyway break to NONE directly.
1850 * Otherwise vfs_set_filelen() will trigger the
1851 * break.
1853 break_to &= ~(SMB2_LEASE_READ|SMB2_LEASE_WRITE);
1856 if (e->op_type != LEASE_OPLOCK) {
1858 * Oplocks only support breaking to R or NONE.
1860 break_to &= ~(SMB2_LEASE_HANDLE|SMB2_LEASE_WRITE);
1863 DEBUG(10, ("breaking from %d to %d\n",
1864 (int)e_lease_type, (int)break_to));
1865 send_break_message(fsp->conn->sconn->msg_ctx, e,
1866 break_to);
1867 if (e_lease_type & delay_mask) {
1868 delay = true;
1870 if (l != NULL && l->breaking && !first_open_attempt) {
1871 delay = true;
1873 continue;
1876 return delay;
1880 * Return lease or oplock state from a share mode
1882 static uint32_t get_lease_type_from_share_mode(const struct share_mode_data *d)
1884 uint32_t e_lease_type = 0;
1885 uint32_t i;
1887 for (i=0; i < d->num_share_modes; i++) {
1888 struct share_mode_entry *e = &d->share_modes[i];
1890 e_lease_type |= get_lease_type(d, e);
1893 return e_lease_type;
1896 static bool file_has_brlocks(files_struct *fsp)
1898 struct byte_range_lock *br_lck;
1900 br_lck = brl_get_locks_readonly(fsp);
1901 if (!br_lck)
1902 return false;
1904 return (brl_num_locks(br_lck) > 0);
1907 int find_share_mode_lease(struct share_mode_data *d,
1908 const struct GUID *client_guid,
1909 const struct smb2_lease_key *key)
1911 uint32_t i;
1913 for (i=0; i<d->num_leases; i++) {
1914 struct share_mode_lease *l = &d->leases[i];
1916 if (smb2_lease_equal(client_guid,
1917 key,
1918 &l->client_guid,
1919 &l->lease_key)) {
1920 return i;
1924 return -1;
1927 struct fsp_lease *find_fsp_lease(struct files_struct *new_fsp,
1928 const struct smb2_lease_key *key,
1929 const struct share_mode_lease *l)
1931 struct files_struct *fsp;
1934 * TODO: Measure how expensive this loop is with thousands of open
1935 * handles...
1938 for (fsp = file_find_di_first(new_fsp->conn->sconn, new_fsp->file_id);
1939 fsp != NULL;
1940 fsp = file_find_di_next(fsp)) {
1942 if (fsp == new_fsp) {
1943 continue;
1945 if (fsp->oplock_type != LEASE_OPLOCK) {
1946 continue;
1948 if (smb2_lease_key_equal(&fsp->lease->lease.lease_key, key)) {
1949 fsp->lease->ref_count += 1;
1950 return fsp->lease;
1954 /* Not found - must be leased in another smbd. */
1955 new_fsp->lease = talloc_zero(new_fsp->conn->sconn, struct fsp_lease);
1956 if (new_fsp->lease == NULL) {
1957 return NULL;
1959 new_fsp->lease->ref_count = 1;
1960 new_fsp->lease->sconn = new_fsp->conn->sconn;
1961 new_fsp->lease->lease.lease_key = *key;
1962 new_fsp->lease->lease.lease_state = l->current_state;
1964 * We internally treat all leases as V2 and update
1965 * the epoch, but when sending breaks it matters if
1966 * the requesting lease was v1 or v2.
1968 new_fsp->lease->lease.lease_version = l->lease_version;
1969 new_fsp->lease->lease.lease_epoch = l->epoch;
1970 return new_fsp->lease;
1973 static NTSTATUS grant_fsp_lease(struct files_struct *fsp,
1974 struct share_mode_lock *lck,
1975 const struct smb2_lease *lease,
1976 uint32_t *p_lease_idx,
1977 uint32_t granted)
1979 struct share_mode_data *d = lck->data;
1980 const struct GUID *client_guid = fsp_client_guid(fsp);
1981 struct share_mode_lease *tmp;
1982 NTSTATUS status;
1983 int idx;
1985 idx = find_share_mode_lease(d, client_guid, &lease->lease_key);
1987 if (idx != -1) {
1988 struct share_mode_lease *l = &d->leases[idx];
1989 bool do_upgrade;
1990 uint32_t existing, requested;
1992 fsp->lease = find_fsp_lease(fsp, &lease->lease_key, l);
1993 if (fsp->lease == NULL) {
1994 DEBUG(1, ("Did not find existing lease for file %s\n",
1995 fsp_str_dbg(fsp)));
1996 return NT_STATUS_NO_MEMORY;
1999 *p_lease_idx = idx;
2002 * Upgrade only if the requested lease is a strict upgrade.
2004 existing = l->current_state;
2005 requested = lease->lease_state;
2008 * Tricky: This test makes sure that "requested" is a
2009 * strict bitwise superset of "existing".
2011 do_upgrade = ((existing & requested) == existing);
2014 * Upgrade only if there's a change.
2016 do_upgrade &= (granted != existing);
2019 * Upgrade only if other leases don't prevent what was asked
2020 * for.
2022 do_upgrade &= (granted == requested);
2025 * only upgrade if we are not in breaking state
2027 do_upgrade &= !l->breaking;
2029 DEBUG(10, ("existing=%"PRIu32", requested=%"PRIu32", "
2030 "granted=%"PRIu32", do_upgrade=%d\n",
2031 existing, requested, granted, (int)do_upgrade));
2033 if (do_upgrade) {
2034 l->current_state = granted;
2035 l->epoch += 1;
2038 /* Ensure we're in sync with current lease state. */
2039 fsp_lease_update(lck, fsp_client_guid(fsp), fsp->lease);
2040 return NT_STATUS_OK;
2044 * Create new lease
2047 tmp = talloc_realloc(d, d->leases, struct share_mode_lease,
2048 d->num_leases+1);
2049 if (tmp == NULL) {
2051 * See [MS-SMB2]
2053 return NT_STATUS_INSUFFICIENT_RESOURCES;
2055 d->leases = tmp;
2057 fsp->lease = talloc_zero(fsp->conn->sconn, struct fsp_lease);
2058 if (fsp->lease == NULL) {
2059 return NT_STATUS_INSUFFICIENT_RESOURCES;
2061 fsp->lease->ref_count = 1;
2062 fsp->lease->sconn = fsp->conn->sconn;
2063 fsp->lease->lease.lease_version = lease->lease_version;
2064 fsp->lease->lease.lease_key = lease->lease_key;
2065 fsp->lease->lease.lease_state = granted;
2066 fsp->lease->lease.lease_epoch = lease->lease_epoch + 1;
2068 *p_lease_idx = d->num_leases;
2070 d->leases[d->num_leases] = (struct share_mode_lease) {
2071 .client_guid = *client_guid,
2072 .lease_key = fsp->lease->lease.lease_key,
2073 .current_state = fsp->lease->lease.lease_state,
2074 .lease_version = fsp->lease->lease.lease_version,
2075 .epoch = fsp->lease->lease.lease_epoch,
2078 status = leases_db_add(client_guid,
2079 &lease->lease_key,
2080 &fsp->file_id,
2081 fsp->conn->connectpath,
2082 fsp->fsp_name->base_name,
2083 fsp->fsp_name->stream_name);
2084 if (!NT_STATUS_IS_OK(status)) {
2085 DEBUG(10, ("%s: leases_db_add failed: %s\n", __func__,
2086 nt_errstr(status)));
2087 TALLOC_FREE(fsp->lease);
2088 return NT_STATUS_INSUFFICIENT_RESOURCES;
2091 d->num_leases += 1;
2092 d->modified = true;
2094 return NT_STATUS_OK;
2097 static bool is_same_lease(const files_struct *fsp,
2098 const struct share_mode_data *d,
2099 const struct share_mode_entry *e,
2100 const struct smb2_lease *lease)
2102 if (e->op_type != LEASE_OPLOCK) {
2103 return false;
2105 if (lease == NULL) {
2106 return false;
2109 return smb2_lease_equal(fsp_client_guid(fsp),
2110 &lease->lease_key,
2111 &d->leases[e->lease_idx].client_guid,
2112 &d->leases[e->lease_idx].lease_key);
2115 static NTSTATUS grant_fsp_oplock_type(struct smb_request *req,
2116 struct files_struct *fsp,
2117 struct share_mode_lock *lck,
2118 int oplock_request,
2119 struct smb2_lease *lease)
2121 struct share_mode_data *d = lck->data;
2122 bool got_handle_lease = false;
2123 bool got_oplock = false;
2124 uint32_t i;
2125 uint32_t granted;
2126 uint32_t lease_idx = UINT32_MAX;
2127 bool ok;
2128 NTSTATUS status;
2130 if (oplock_request & INTERNAL_OPEN_ONLY) {
2131 /* No oplocks on internal open. */
2132 oplock_request = NO_OPLOCK;
2133 DEBUG(10,("grant_fsp_oplock_type: oplock type 0x%x on file %s\n",
2134 fsp->oplock_type, fsp_str_dbg(fsp)));
2137 if (oplock_request == LEASE_OPLOCK) {
2138 if (lease == NULL) {
2140 * The SMB2 layer should have checked this
2142 return NT_STATUS_INTERNAL_ERROR;
2145 granted = lease->lease_state;
2147 if (lp_kernel_oplocks(SNUM(fsp->conn))) {
2148 DEBUG(10, ("No lease granted because kernel oplocks are enabled\n"));
2149 granted = SMB2_LEASE_NONE;
2151 if ((granted & (SMB2_LEASE_READ|SMB2_LEASE_WRITE)) == 0) {
2152 DEBUG(10, ("No read or write lease requested\n"));
2153 granted = SMB2_LEASE_NONE;
2155 if (granted == SMB2_LEASE_WRITE) {
2156 DEBUG(10, ("pure write lease requested\n"));
2157 granted = SMB2_LEASE_NONE;
2159 if (granted == (SMB2_LEASE_WRITE|SMB2_LEASE_HANDLE)) {
2160 DEBUG(10, ("write and handle lease requested\n"));
2161 granted = SMB2_LEASE_NONE;
2163 } else {
2164 granted = map_oplock_to_lease_type(
2165 oplock_request & ~SAMBA_PRIVATE_OPLOCK_MASK);
2168 if (lp_locking(fsp->conn->params) && file_has_brlocks(fsp)) {
2169 DEBUG(10,("grant_fsp_oplock_type: file %s has byte range locks\n",
2170 fsp_str_dbg(fsp)));
2171 granted &= ~SMB2_LEASE_READ;
2174 for (i=0; i<d->num_share_modes; i++) {
2175 struct share_mode_entry *e = &d->share_modes[i];
2176 uint32_t e_lease_type;
2178 e_lease_type = get_lease_type(d, e);
2180 if ((granted & SMB2_LEASE_WRITE) &&
2181 !is_same_lease(fsp, d, e, lease) &&
2182 !share_mode_stale_pid(d, i)) {
2184 * Can grant only one writer
2186 granted &= ~SMB2_LEASE_WRITE;
2189 if ((e_lease_type & SMB2_LEASE_HANDLE) && !got_handle_lease &&
2190 !share_mode_stale_pid(d, i)) {
2191 got_handle_lease = true;
2194 if ((e->op_type != LEASE_OPLOCK) && !got_oplock &&
2195 !share_mode_stale_pid(d, i)) {
2196 got_oplock = true;
2200 if ((granted & SMB2_LEASE_READ) && !(granted & SMB2_LEASE_WRITE)) {
2201 bool allow_level2 =
2202 (global_client_caps & CAP_LEVEL_II_OPLOCKS) &&
2203 lp_level2_oplocks(SNUM(fsp->conn));
2205 if (!allow_level2) {
2206 granted = SMB2_LEASE_NONE;
2210 if (oplock_request == LEASE_OPLOCK) {
2211 if (got_oplock) {
2212 granted &= ~SMB2_LEASE_HANDLE;
2215 fsp->oplock_type = LEASE_OPLOCK;
2217 status = grant_fsp_lease(fsp, lck, lease, &lease_idx,
2218 granted);
2219 if (!NT_STATUS_IS_OK(status)) {
2220 return status;
2223 *lease = fsp->lease->lease;
2224 DEBUG(10, ("lease_state=%d\n", lease->lease_state));
2225 } else {
2226 if (got_handle_lease) {
2227 granted = SMB2_LEASE_NONE;
2230 switch (granted) {
2231 case SMB2_LEASE_READ|SMB2_LEASE_WRITE|SMB2_LEASE_HANDLE:
2232 fsp->oplock_type = BATCH_OPLOCK|EXCLUSIVE_OPLOCK;
2233 break;
2234 case SMB2_LEASE_READ|SMB2_LEASE_WRITE:
2235 fsp->oplock_type = EXCLUSIVE_OPLOCK;
2236 break;
2237 case SMB2_LEASE_READ|SMB2_LEASE_HANDLE:
2238 case SMB2_LEASE_READ:
2239 fsp->oplock_type = LEVEL_II_OPLOCK;
2240 break;
2241 default:
2242 fsp->oplock_type = NO_OPLOCK;
2243 break;
2246 status = set_file_oplock(fsp);
2247 if (!NT_STATUS_IS_OK(status)) {
2249 * Could not get the kernel oplock
2251 fsp->oplock_type = NO_OPLOCK;
2255 ok = set_share_mode(lck, fsp, get_current_uid(fsp->conn),
2256 req ? req->mid : 0,
2257 fsp->oplock_type,
2258 lease_idx);
2259 if (!ok) {
2260 return NT_STATUS_NO_MEMORY;
2263 ok = update_num_read_oplocks(fsp, lck);
2264 if (!ok) {
2265 del_share_mode(lck, fsp);
2266 return NT_STATUS_INTERNAL_ERROR;
2269 DEBUG(10,("grant_fsp_oplock_type: oplock type 0x%x on file %s\n",
2270 fsp->oplock_type, fsp_str_dbg(fsp)));
2272 return NT_STATUS_OK;
2275 static bool request_timed_out(struct timeval request_time,
2276 struct timeval timeout)
2278 struct timeval now, end_time;
2279 GetTimeOfDay(&now);
2280 end_time = timeval_sum(&request_time, &timeout);
2281 return (timeval_compare(&end_time, &now) < 0);
2284 static struct deferred_open_record *deferred_open_record_create(
2285 bool delayed_for_oplocks,
2286 bool async_open,
2287 struct file_id id)
2289 struct deferred_open_record *record = NULL;
2291 record = talloc(NULL, struct deferred_open_record);
2292 if (record == NULL) {
2293 return NULL;
2296 *record = (struct deferred_open_record) {
2297 .delayed_for_oplocks = delayed_for_oplocks,
2298 .async_open = async_open,
2299 .id = id,
2302 return record;
2305 struct defer_open_state {
2306 struct smbXsrv_connection *xconn;
2307 uint64_t mid;
2308 struct file_id file_id;
2309 struct timeval request_time;
2310 struct timeval timeout;
2311 bool kernel_oplock;
2312 uint32_t lease_type;
2315 static void defer_open_done(struct tevent_req *req);
2318 * Defer an open and watch a locking.tdb record
2320 * This defers an open that gets rescheduled once the locking.tdb record watch
2321 * is triggered by a change to the record.
2323 * It is used to defer opens that triggered an oplock break and for the SMB1
2324 * sharing violation delay.
2326 static void defer_open(struct share_mode_lock *lck,
2327 struct timeval request_time,
2328 struct timeval timeout,
2329 struct smb_request *req,
2330 bool delayed_for_oplocks,
2331 bool kernel_oplock,
2332 struct file_id id)
2334 struct deferred_open_record *open_rec = NULL;
2335 struct timeval abs_timeout;
2336 struct defer_open_state *watch_state;
2337 struct tevent_req *watch_req;
2338 bool ok;
2340 abs_timeout = timeval_sum(&request_time, &timeout);
2342 DBG_DEBUG("request time [%s] timeout [%s] mid [%" PRIu64 "] "
2343 "delayed_for_oplocks [%s] kernel_oplock [%s] file_id [%s]\n",
2344 timeval_string(talloc_tos(), &request_time, false),
2345 timeval_string(talloc_tos(), &abs_timeout, false),
2346 req->mid,
2347 delayed_for_oplocks ? "yes" : "no",
2348 kernel_oplock ? "yes" : "no",
2349 file_id_string_tos(&id));
2351 open_rec = deferred_open_record_create(delayed_for_oplocks,
2352 false,
2353 id);
2354 if (open_rec == NULL) {
2355 TALLOC_FREE(lck);
2356 exit_server("talloc failed");
2359 watch_state = talloc(open_rec, struct defer_open_state);
2360 if (watch_state == NULL) {
2361 exit_server("talloc failed");
2363 watch_state->xconn = req->xconn;
2364 watch_state->mid = req->mid;
2365 watch_state->file_id = lck->data->id;
2366 watch_state->request_time = request_time;
2367 watch_state->timeout = timeout;
2368 watch_state->kernel_oplock = kernel_oplock;
2369 watch_state->lease_type = get_lease_type_from_share_mode(lck->data);
2371 DBG_DEBUG("defering mid %" PRIu64 "\n", req->mid);
2373 watch_req = dbwrap_watched_watch_send(watch_state,
2374 req->sconn->ev_ctx,
2375 lck->data->record,
2376 (struct server_id){0});
2377 if (watch_req == NULL) {
2378 exit_server("Could not watch share mode record");
2380 tevent_req_set_callback(watch_req, defer_open_done, watch_state);
2382 ok = tevent_req_set_endtime(watch_req, req->sconn->ev_ctx, abs_timeout);
2383 if (!ok) {
2384 exit_server("tevent_req_set_endtime failed");
2387 ok = push_deferred_open_message_smb(req, request_time, timeout,
2388 open_rec->id, open_rec);
2389 if (!ok) {
2390 TALLOC_FREE(lck);
2391 exit_server("push_deferred_open_message_smb failed");
2395 static void defer_open_done(struct tevent_req *req)
2397 struct defer_open_state *state = tevent_req_callback_data(
2398 req, struct defer_open_state);
2399 struct tevent_req *watch_req = NULL;
2400 struct share_mode_lock *lck = NULL;
2401 bool schedule_req = true;
2402 struct timeval timeout;
2403 NTSTATUS status;
2404 bool ok;
2406 status = dbwrap_watched_watch_recv(req, talloc_tos(), NULL, NULL,
2407 NULL);
2408 TALLOC_FREE(req);
2409 if (!NT_STATUS_IS_OK(status)) {
2410 DEBUG(5, ("dbwrap_watched_watch_recv returned %s\n",
2411 nt_errstr(status)));
2413 * Even if it failed, retry anyway. TODO: We need a way to
2414 * tell a re-scheduled open about that error.
2416 if (NT_STATUS_EQUAL(status, NT_STATUS_IO_TIMEOUT) &&
2417 state->kernel_oplock)
2420 * If we reschedule but the kernel oplock is still hold
2421 * we would block in the second open as that will be a
2422 * blocking open attempt.
2424 exit_server("Kernel oplock holder didn't "
2425 "respond to break message");
2429 if (state->kernel_oplock) {
2430 lck = get_existing_share_mode_lock(talloc_tos(), state->file_id);
2431 if (lck != NULL) {
2432 uint32_t lease_type;
2434 lease_type = get_lease_type_from_share_mode(lck->data);
2436 if ((lease_type != 0) &&
2437 (lease_type == state->lease_type))
2439 DBG_DEBUG("Unchanged lease: %" PRIu32 "\n",
2440 lease_type);
2441 schedule_req = false;
2446 if (schedule_req) {
2447 DBG_DEBUG("scheduling mid %" PRIu64 "\n", state->mid);
2449 ok = schedule_deferred_open_message_smb(state->xconn,
2450 state->mid);
2451 if (!ok) {
2452 exit_server("schedule_deferred_open_message_smb failed");
2454 TALLOC_FREE(lck);
2455 TALLOC_FREE(state);
2456 return;
2459 DBG_DEBUG("Keep waiting for oplock release for [%s/%s%s] "
2460 "mid: %" PRIu64 "\n",
2461 lck->data->servicepath,
2462 lck->data->base_name,
2463 lck->data->stream_name ? lck->data->stream_name : "",
2464 state->mid);
2466 watch_req = dbwrap_watched_watch_send(state,
2467 state->xconn->ev_ctx,
2468 lck->data->record,
2469 (struct server_id){0});
2470 if (watch_req == NULL) {
2471 exit_server("Could not watch share mode record");
2473 tevent_req_set_callback(watch_req, defer_open_done, state);
2475 timeout = timeval_sum(&state->request_time, &state->timeout);
2476 ok = tevent_req_set_endtime(watch_req, state->xconn->ev_ctx, timeout);
2477 if (!ok) {
2478 exit_server("tevent_req_set_endtime failed");
2481 TALLOC_FREE(lck);
2485 * Reschedule an open for immediate execution
2487 static void retry_open(struct timeval request_time,
2488 struct smb_request *req,
2489 struct file_id id)
2491 struct deferred_open_record *open_rec = NULL;
2492 bool ok;
2494 DBG_DEBUG("request time [%s] mid [%" PRIu64 "] file_id [%s]\n",
2495 timeval_string(talloc_tos(), &request_time, false),
2496 req->mid,
2497 file_id_string_tos(&id));
2499 open_rec = deferred_open_record_create(false, false, id);
2500 if (open_rec == NULL) {
2501 exit_server("talloc failed");
2504 ok = push_deferred_open_message_smb(req,
2505 request_time,
2506 timeval_set(0, 0),
2508 open_rec);
2509 if (!ok) {
2510 exit_server("push_deferred_open_message_smb failed");
2513 ok = schedule_deferred_open_message_smb(req->xconn, req->mid);
2514 if (!ok) {
2515 exit_server("schedule_deferred_open_message_smb failed");
2519 /****************************************************************************
2520 On overwrite open ensure that the attributes match.
2521 ****************************************************************************/
2523 static bool open_match_attributes(connection_struct *conn,
2524 uint32_t old_dos_attr,
2525 uint32_t new_dos_attr,
2526 mode_t existing_unx_mode,
2527 mode_t new_unx_mode,
2528 mode_t *returned_unx_mode)
2530 uint32_t noarch_old_dos_attr, noarch_new_dos_attr;
2532 noarch_old_dos_attr = (old_dos_attr & ~FILE_ATTRIBUTE_ARCHIVE);
2533 noarch_new_dos_attr = (new_dos_attr & ~FILE_ATTRIBUTE_ARCHIVE);
2535 if((noarch_old_dos_attr == 0 && noarch_new_dos_attr != 0) ||
2536 (noarch_old_dos_attr != 0 && ((noarch_old_dos_attr & noarch_new_dos_attr) == noarch_old_dos_attr))) {
2537 *returned_unx_mode = new_unx_mode;
2538 } else {
2539 *returned_unx_mode = (mode_t)0;
2542 DEBUG(10,("open_match_attributes: old_dos_attr = 0x%x, "
2543 "existing_unx_mode = 0%o, new_dos_attr = 0x%x "
2544 "returned_unx_mode = 0%o\n",
2545 (unsigned int)old_dos_attr,
2546 (unsigned int)existing_unx_mode,
2547 (unsigned int)new_dos_attr,
2548 (unsigned int)*returned_unx_mode ));
2550 /* If we're mapping SYSTEM and HIDDEN ensure they match. */
2551 if (lp_map_system(SNUM(conn)) || lp_store_dos_attributes(SNUM(conn))) {
2552 if ((old_dos_attr & FILE_ATTRIBUTE_SYSTEM) &&
2553 !(new_dos_attr & FILE_ATTRIBUTE_SYSTEM)) {
2554 return False;
2557 if (lp_map_hidden(SNUM(conn)) || lp_store_dos_attributes(SNUM(conn))) {
2558 if ((old_dos_attr & FILE_ATTRIBUTE_HIDDEN) &&
2559 !(new_dos_attr & FILE_ATTRIBUTE_HIDDEN)) {
2560 return False;
2563 return True;
2566 /****************************************************************************
2567 Special FCB or DOS processing in the case of a sharing violation.
2568 Try and find a duplicated file handle.
2569 ****************************************************************************/
2571 static NTSTATUS fcb_or_dos_open(struct smb_request *req,
2572 connection_struct *conn,
2573 files_struct *fsp_to_dup_into,
2574 const struct smb_filename *smb_fname,
2575 struct file_id id,
2576 uint16_t file_pid,
2577 uint64_t vuid,
2578 uint32_t access_mask,
2579 uint32_t share_access,
2580 uint32_t create_options)
2582 files_struct *fsp;
2584 DEBUG(5,("fcb_or_dos_open: attempting old open semantics for "
2585 "file %s.\n", smb_fname_str_dbg(smb_fname)));
2587 for(fsp = file_find_di_first(conn->sconn, id); fsp;
2588 fsp = file_find_di_next(fsp)) {
2590 DEBUG(10,("fcb_or_dos_open: checking file %s, fd = %d, "
2591 "vuid = %llu, file_pid = %u, private_options = 0x%x "
2592 "access_mask = 0x%x\n", fsp_str_dbg(fsp),
2593 fsp->fh->fd, (unsigned long long)fsp->vuid,
2594 (unsigned int)fsp->file_pid,
2595 (unsigned int)fsp->fh->private_options,
2596 (unsigned int)fsp->access_mask ));
2598 if (fsp != fsp_to_dup_into &&
2599 fsp->fh->fd != -1 &&
2600 fsp->vuid == vuid &&
2601 fsp->file_pid == file_pid &&
2602 (fsp->fh->private_options & (NTCREATEX_OPTIONS_PRIVATE_DENY_DOS |
2603 NTCREATEX_OPTIONS_PRIVATE_DENY_FCB)) &&
2604 (fsp->access_mask & FILE_WRITE_DATA) &&
2605 strequal(fsp->fsp_name->base_name, smb_fname->base_name) &&
2606 strequal(fsp->fsp_name->stream_name,
2607 smb_fname->stream_name)) {
2608 DEBUG(10,("fcb_or_dos_open: file match\n"));
2609 break;
2613 if (!fsp) {
2614 return NT_STATUS_NOT_FOUND;
2617 /* quite an insane set of semantics ... */
2618 if (is_executable(smb_fname->base_name) &&
2619 (fsp->fh->private_options & NTCREATEX_OPTIONS_PRIVATE_DENY_DOS)) {
2620 DEBUG(10,("fcb_or_dos_open: file fail due to is_executable.\n"));
2621 return NT_STATUS_INVALID_PARAMETER;
2624 /* We need to duplicate this fsp. */
2625 return dup_file_fsp(req, fsp, access_mask, share_access,
2626 create_options, fsp_to_dup_into);
2629 static void schedule_defer_open(struct share_mode_lock *lck,
2630 struct file_id id,
2631 struct timeval request_time,
2632 struct smb_request *req,
2633 bool kernel_oplock)
2635 /* This is a relative time, added to the absolute
2636 request_time value to get the absolute timeout time.
2637 Note that if this is the second or greater time we enter
2638 this codepath for this particular request mid then
2639 request_time is left as the absolute time of the *first*
2640 time this request mid was processed. This is what allows
2641 the request to eventually time out. */
2643 struct timeval timeout;
2645 /* Normally the smbd we asked should respond within
2646 * OPLOCK_BREAK_TIMEOUT seconds regardless of whether
2647 * the client did, give twice the timeout as a safety
2648 * measure here in case the other smbd is stuck
2649 * somewhere else. */
2651 timeout = timeval_set(OPLOCK_BREAK_TIMEOUT*2, 0);
2653 if (request_timed_out(request_time, timeout)) {
2654 return;
2657 defer_open(lck, request_time, timeout, req, true, kernel_oplock, id);
2660 /****************************************************************************
2661 Reschedule an open call that went asynchronous.
2662 ****************************************************************************/
2664 static void schedule_async_open_timer(struct tevent_context *ev,
2665 struct tevent_timer *te,
2666 struct timeval current_time,
2667 void *private_data)
2669 exit_server("async open timeout");
2672 static void schedule_async_open(struct timeval request_time,
2673 struct smb_request *req)
2675 struct deferred_open_record *open_rec = NULL;
2676 struct timeval timeout = timeval_set(20, 0);
2677 bool ok;
2679 if (request_timed_out(request_time, timeout)) {
2680 return;
2683 open_rec = deferred_open_record_create(false, true, (struct file_id){0});
2684 if (open_rec == NULL) {
2685 exit_server("deferred_open_record_create failed");
2688 ok = push_deferred_open_message_smb(req, request_time, timeout,
2689 (struct file_id){0}, open_rec);
2690 if (!ok) {
2691 exit_server("push_deferred_open_message_smb failed");
2694 open_rec->te = tevent_add_timer(req->sconn->ev_ctx,
2695 req,
2696 timeval_current_ofs(20, 0),
2697 schedule_async_open_timer,
2698 open_rec);
2699 if (open_rec->te == NULL) {
2700 exit_server("tevent_add_timer failed");
2704 /****************************************************************************
2705 Work out what access_mask to use from what the client sent us.
2706 ****************************************************************************/
2708 static NTSTATUS smbd_calculate_maximum_allowed_access(
2709 connection_struct *conn,
2710 const struct smb_filename *smb_fname,
2711 bool use_privs,
2712 uint32_t *p_access_mask)
2714 struct security_descriptor *sd;
2715 uint32_t access_granted;
2716 NTSTATUS status;
2718 if (!use_privs && (get_current_uid(conn) == (uid_t)0)) {
2719 *p_access_mask |= FILE_GENERIC_ALL;
2720 return NT_STATUS_OK;
2723 status = SMB_VFS_GET_NT_ACL(conn, smb_fname,
2724 (SECINFO_OWNER |
2725 SECINFO_GROUP |
2726 SECINFO_DACL),
2727 talloc_tos(), &sd);
2729 if (NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
2731 * File did not exist
2733 *p_access_mask = FILE_GENERIC_ALL;
2734 return NT_STATUS_OK;
2736 if (!NT_STATUS_IS_OK(status)) {
2737 DEBUG(10,("Could not get acl on file %s: %s\n",
2738 smb_fname_str_dbg(smb_fname),
2739 nt_errstr(status)));
2740 return NT_STATUS_ACCESS_DENIED;
2744 * If we can access the path to this file, by
2745 * default we have FILE_READ_ATTRIBUTES from the
2746 * containing directory. See the section:
2747 * "Algorithm to Check Access to an Existing File"
2748 * in MS-FSA.pdf.
2750 * se_file_access_check()
2751 * also takes care of owner WRITE_DAC and READ_CONTROL.
2753 status = se_file_access_check(sd,
2754 get_current_nttok(conn),
2755 use_privs,
2756 (*p_access_mask & ~FILE_READ_ATTRIBUTES),
2757 &access_granted);
2759 TALLOC_FREE(sd);
2761 if (!NT_STATUS_IS_OK(status)) {
2762 DEBUG(10, ("Access denied on file %s: "
2763 "when calculating maximum access\n",
2764 smb_fname_str_dbg(smb_fname)));
2765 return NT_STATUS_ACCESS_DENIED;
2767 *p_access_mask = (access_granted | FILE_READ_ATTRIBUTES);
2769 if (!(access_granted & DELETE_ACCESS)) {
2770 if (can_delete_file_in_directory(conn, smb_fname)) {
2771 *p_access_mask |= DELETE_ACCESS;
2775 return NT_STATUS_OK;
2778 NTSTATUS smbd_calculate_access_mask(connection_struct *conn,
2779 const struct smb_filename *smb_fname,
2780 bool use_privs,
2781 uint32_t access_mask,
2782 uint32_t *access_mask_out)
2784 NTSTATUS status;
2785 uint32_t orig_access_mask = access_mask;
2786 uint32_t rejected_share_access;
2788 if (access_mask & SEC_MASK_INVALID) {
2789 DBG_DEBUG("access_mask [%8x] contains invalid bits\n",
2790 access_mask);
2791 return NT_STATUS_ACCESS_DENIED;
2795 * Convert GENERIC bits to specific bits.
2798 se_map_generic(&access_mask, &file_generic_mapping);
2800 /* Calculate MAXIMUM_ALLOWED_ACCESS if requested. */
2801 if (access_mask & MAXIMUM_ALLOWED_ACCESS) {
2803 status = smbd_calculate_maximum_allowed_access(
2804 conn, smb_fname, use_privs, &access_mask);
2806 if (!NT_STATUS_IS_OK(status)) {
2807 return status;
2810 access_mask &= conn->share_access;
2813 rejected_share_access = access_mask & ~(conn->share_access);
2815 if (rejected_share_access) {
2816 DEBUG(10, ("smbd_calculate_access_mask: Access denied on "
2817 "file %s: rejected by share access mask[0x%08X] "
2818 "orig[0x%08X] mapped[0x%08X] reject[0x%08X]\n",
2819 smb_fname_str_dbg(smb_fname),
2820 conn->share_access,
2821 orig_access_mask, access_mask,
2822 rejected_share_access));
2823 return NT_STATUS_ACCESS_DENIED;
2826 *access_mask_out = access_mask;
2827 return NT_STATUS_OK;
2830 /****************************************************************************
2831 Remove the deferred open entry under lock.
2832 ****************************************************************************/
2834 /****************************************************************************
2835 Return true if this is a state pointer to an asynchronous create.
2836 ****************************************************************************/
2838 bool is_deferred_open_async(const struct deferred_open_record *rec)
2840 return rec->async_open;
2843 static bool clear_ads(uint32_t create_disposition)
2845 bool ret = false;
2847 switch (create_disposition) {
2848 case FILE_SUPERSEDE:
2849 case FILE_OVERWRITE_IF:
2850 case FILE_OVERWRITE:
2851 ret = true;
2852 break;
2853 default:
2854 break;
2856 return ret;
2859 static int disposition_to_open_flags(uint32_t create_disposition)
2861 int ret = 0;
2864 * Currently we're using FILE_SUPERSEDE as the same as
2865 * FILE_OVERWRITE_IF but they really are
2866 * different. FILE_SUPERSEDE deletes an existing file
2867 * (requiring delete access) then recreates it.
2870 switch (create_disposition) {
2871 case FILE_SUPERSEDE:
2872 case FILE_OVERWRITE_IF:
2874 * If file exists replace/overwrite. If file doesn't
2875 * exist create.
2877 ret = O_CREAT|O_TRUNC;
2878 break;
2880 case FILE_OPEN:
2882 * If file exists open. If file doesn't exist error.
2884 ret = 0;
2885 break;
2887 case FILE_OVERWRITE:
2889 * If file exists overwrite. If file doesn't exist
2890 * error.
2892 ret = O_TRUNC;
2893 break;
2895 case FILE_CREATE:
2897 * If file exists error. If file doesn't exist create.
2899 ret = O_CREAT|O_EXCL;
2900 break;
2902 case FILE_OPEN_IF:
2904 * If file exists open. If file doesn't exist create.
2906 ret = O_CREAT;
2907 break;
2909 return ret;
2912 static int calculate_open_access_flags(uint32_t access_mask,
2913 uint32_t private_flags)
2915 bool need_write, need_read;
2918 * Note that we ignore the append flag as append does not
2919 * mean the same thing under DOS and Unix.
2922 need_write = (access_mask & (FILE_WRITE_DATA | FILE_APPEND_DATA));
2923 if (!need_write) {
2924 return O_RDONLY;
2927 /* DENY_DOS opens are always underlying read-write on the
2928 file handle, no matter what the requested access mask
2929 says. */
2931 need_read =
2932 ((private_flags & NTCREATEX_OPTIONS_PRIVATE_DENY_DOS) ||
2933 access_mask & (FILE_READ_ATTRIBUTES|FILE_READ_DATA|
2934 FILE_READ_EA|FILE_EXECUTE));
2936 if (!need_read) {
2937 return O_WRONLY;
2939 return O_RDWR;
2942 /****************************************************************************
2943 Open a file with a share mode. Passed in an already created files_struct *.
2944 ****************************************************************************/
2946 static NTSTATUS open_file_ntcreate(connection_struct *conn,
2947 struct smb_request *req,
2948 uint32_t access_mask, /* access bits (FILE_READ_DATA etc.) */
2949 uint32_t share_access, /* share constants (FILE_SHARE_READ etc) */
2950 uint32_t create_disposition, /* FILE_OPEN_IF etc. */
2951 uint32_t create_options, /* options such as delete on close. */
2952 uint32_t new_dos_attributes, /* attributes used for new file. */
2953 int oplock_request, /* internal Samba oplock codes. */
2954 struct smb2_lease *lease,
2955 /* Information (FILE_EXISTS etc.) */
2956 uint32_t private_flags, /* Samba specific flags. */
2957 int *pinfo,
2958 files_struct *fsp)
2960 struct smb_filename *smb_fname = fsp->fsp_name;
2961 int flags=0;
2962 int flags2=0;
2963 bool file_existed = VALID_STAT(smb_fname->st);
2964 bool def_acl = False;
2965 bool posix_open = False;
2966 bool new_file_created = False;
2967 bool first_open_attempt = true;
2968 NTSTATUS fsp_open = NT_STATUS_ACCESS_DENIED;
2969 mode_t new_unx_mode = (mode_t)0;
2970 mode_t unx_mode = (mode_t)0;
2971 int info;
2972 uint32_t existing_dos_attributes = 0;
2973 struct timeval request_time = timeval_zero();
2974 struct share_mode_lock *lck = NULL;
2975 uint32_t open_access_mask = access_mask;
2976 NTSTATUS status;
2977 char *parent_dir;
2978 SMB_STRUCT_STAT saved_stat = smb_fname->st;
2979 struct timespec old_write_time;
2980 struct file_id id;
2982 if (conn->printer) {
2984 * Printers are handled completely differently.
2985 * Most of the passed parameters are ignored.
2988 if (pinfo) {
2989 *pinfo = FILE_WAS_CREATED;
2992 DEBUG(10, ("open_file_ntcreate: printer open fname=%s\n",
2993 smb_fname_str_dbg(smb_fname)));
2995 if (!req) {
2996 DEBUG(0,("open_file_ntcreate: printer open without "
2997 "an SMB request!\n"));
2998 return NT_STATUS_INTERNAL_ERROR;
3001 return print_spool_open(fsp, smb_fname->base_name,
3002 req->vuid);
3005 if (!parent_dirname(talloc_tos(), smb_fname->base_name, &parent_dir,
3006 NULL)) {
3007 return NT_STATUS_NO_MEMORY;
3010 if (new_dos_attributes & FILE_FLAG_POSIX_SEMANTICS) {
3011 posix_open = True;
3012 unx_mode = (mode_t)(new_dos_attributes & ~FILE_FLAG_POSIX_SEMANTICS);
3013 new_dos_attributes = 0;
3014 } else {
3015 /* Windows allows a new file to be created and
3016 silently removes a FILE_ATTRIBUTE_DIRECTORY
3017 sent by the client. Do the same. */
3019 new_dos_attributes &= ~FILE_ATTRIBUTE_DIRECTORY;
3021 /* We add FILE_ATTRIBUTE_ARCHIVE to this as this mode is only used if the file is
3022 * created new. */
3023 unx_mode = unix_mode(conn, new_dos_attributes | FILE_ATTRIBUTE_ARCHIVE,
3024 smb_fname, parent_dir);
3027 DEBUG(10, ("open_file_ntcreate: fname=%s, dos_attrs=0x%x "
3028 "access_mask=0x%x share_access=0x%x "
3029 "create_disposition = 0x%x create_options=0x%x "
3030 "unix mode=0%o oplock_request=%d private_flags = 0x%x\n",
3031 smb_fname_str_dbg(smb_fname), new_dos_attributes,
3032 access_mask, share_access, create_disposition,
3033 create_options, (unsigned int)unx_mode, oplock_request,
3034 (unsigned int)private_flags));
3036 if (req == NULL) {
3037 /* Ensure req == NULL means INTERNAL_OPEN_ONLY */
3038 SMB_ASSERT(((oplock_request & INTERNAL_OPEN_ONLY) != 0));
3039 } else {
3040 /* And req != NULL means no INTERNAL_OPEN_ONLY */
3041 SMB_ASSERT(((oplock_request & INTERNAL_OPEN_ONLY) == 0));
3045 * Only non-internal opens can be deferred at all
3048 if (req) {
3049 struct deferred_open_record *open_rec;
3050 if (get_deferred_open_message_state(req,
3051 &request_time,
3052 &open_rec)) {
3053 /* Remember the absolute time of the original
3054 request with this mid. We'll use it later to
3055 see if this has timed out. */
3057 /* If it was an async create retry, the file
3058 didn't exist. */
3060 if (is_deferred_open_async(open_rec)) {
3061 SET_STAT_INVALID(smb_fname->st);
3062 file_existed = false;
3065 /* Ensure we don't reprocess this message. */
3066 remove_deferred_open_message_smb(req->xconn, req->mid);
3068 first_open_attempt = false;
3072 if (!posix_open) {
3073 new_dos_attributes &= SAMBA_ATTRIBUTES_MASK;
3074 if (file_existed) {
3076 * Only use strored DOS attributes for checks
3077 * against requested attributes (below via
3078 * open_match_attributes()), cf bug #11992
3079 * for details. -slow
3081 uint32_t attr = 0;
3083 status = SMB_VFS_GET_DOS_ATTRIBUTES(conn, smb_fname, &attr);
3084 if (NT_STATUS_IS_OK(status)) {
3085 existing_dos_attributes = attr;
3090 /* ignore any oplock requests if oplocks are disabled */
3091 if (!lp_oplocks(SNUM(conn)) ||
3092 IS_VETO_OPLOCK_PATH(conn, smb_fname->base_name)) {
3093 /* Mask off everything except the private Samba bits. */
3094 oplock_request &= SAMBA_PRIVATE_OPLOCK_MASK;
3097 /* this is for OS/2 long file names - say we don't support them */
3098 if (req != NULL && !req->posix_pathnames &&
3099 strstr(smb_fname->base_name,".+,;=[].")) {
3100 /* OS/2 Workplace shell fix may be main code stream in a later
3101 * release. */
3102 DEBUG(5,("open_file_ntcreate: OS/2 long filenames are not "
3103 "supported.\n"));
3104 if (use_nt_status()) {
3105 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3107 return NT_STATUS_DOS(ERRDOS, ERRcannotopen);
3110 switch( create_disposition ) {
3111 case FILE_OPEN:
3112 /* If file exists open. If file doesn't exist error. */
3113 if (!file_existed) {
3114 DEBUG(5,("open_file_ntcreate: FILE_OPEN "
3115 "requested for file %s and file "
3116 "doesn't exist.\n",
3117 smb_fname_str_dbg(smb_fname)));
3118 errno = ENOENT;
3119 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3121 break;
3123 case FILE_OVERWRITE:
3124 /* If file exists overwrite. If file doesn't exist
3125 * error. */
3126 if (!file_existed) {
3127 DEBUG(5,("open_file_ntcreate: FILE_OVERWRITE "
3128 "requested for file %s and file "
3129 "doesn't exist.\n",
3130 smb_fname_str_dbg(smb_fname) ));
3131 errno = ENOENT;
3132 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3134 break;
3136 case FILE_CREATE:
3137 /* If file exists error. If file doesn't exist
3138 * create. */
3139 if (file_existed) {
3140 DEBUG(5,("open_file_ntcreate: FILE_CREATE "
3141 "requested for file %s and file "
3142 "already exists.\n",
3143 smb_fname_str_dbg(smb_fname)));
3144 if (S_ISDIR(smb_fname->st.st_ex_mode)) {
3145 errno = EISDIR;
3146 } else {
3147 errno = EEXIST;
3149 return map_nt_error_from_unix(errno);
3151 break;
3153 case FILE_SUPERSEDE:
3154 case FILE_OVERWRITE_IF:
3155 case FILE_OPEN_IF:
3156 break;
3157 default:
3158 return NT_STATUS_INVALID_PARAMETER;
3161 flags2 = disposition_to_open_flags(create_disposition);
3163 /* We only care about matching attributes on file exists and
3164 * overwrite. */
3166 if (!posix_open && file_existed &&
3167 ((create_disposition == FILE_OVERWRITE) ||
3168 (create_disposition == FILE_OVERWRITE_IF))) {
3169 if (!open_match_attributes(conn, existing_dos_attributes,
3170 new_dos_attributes,
3171 smb_fname->st.st_ex_mode,
3172 unx_mode, &new_unx_mode)) {
3173 DEBUG(5,("open_file_ntcreate: attributes missmatch "
3174 "for file %s (%x %x) (0%o, 0%o)\n",
3175 smb_fname_str_dbg(smb_fname),
3176 existing_dos_attributes,
3177 new_dos_attributes,
3178 (unsigned int)smb_fname->st.st_ex_mode,
3179 (unsigned int)unx_mode ));
3180 errno = EACCES;
3181 return NT_STATUS_ACCESS_DENIED;
3185 status = smbd_calculate_access_mask(conn, smb_fname,
3186 false,
3187 access_mask,
3188 &access_mask);
3189 if (!NT_STATUS_IS_OK(status)) {
3190 DEBUG(10, ("open_file_ntcreate: smbd_calculate_access_mask "
3191 "on file %s returned %s\n",
3192 smb_fname_str_dbg(smb_fname), nt_errstr(status)));
3193 return status;
3196 open_access_mask = access_mask;
3198 if (flags2 & O_TRUNC) {
3199 open_access_mask |= FILE_WRITE_DATA; /* This will cause oplock breaks. */
3202 DEBUG(10, ("open_file_ntcreate: fname=%s, after mapping "
3203 "access_mask=0x%x\n", smb_fname_str_dbg(smb_fname),
3204 access_mask));
3207 * Note that we ignore the append flag as append does not
3208 * mean the same thing under DOS and Unix.
3211 flags = calculate_open_access_flags(access_mask, private_flags);
3214 * Currently we only look at FILE_WRITE_THROUGH for create options.
3217 #if defined(O_SYNC)
3218 if ((create_options & FILE_WRITE_THROUGH) && lp_strict_sync(SNUM(conn))) {
3219 flags2 |= O_SYNC;
3221 #endif /* O_SYNC */
3223 if (posix_open && (access_mask & FILE_APPEND_DATA)) {
3224 flags2 |= O_APPEND;
3227 if (!posix_open && !CAN_WRITE(conn)) {
3229 * We should really return a permission denied error if either
3230 * O_CREAT or O_TRUNC are set, but for compatibility with
3231 * older versions of Samba we just AND them out.
3233 flags2 &= ~(O_CREAT|O_TRUNC);
3236 if (first_open_attempt && lp_kernel_oplocks(SNUM(conn))) {
3238 * With kernel oplocks the open breaking an oplock
3239 * blocks until the oplock holder has given up the
3240 * oplock or closed the file. We prevent this by first
3241 * trying to open the file with O_NONBLOCK (see "man
3242 * fcntl" on Linux). For the second try, triggered by
3243 * an oplock break response, we do not need this
3244 * anymore.
3246 * This is true under the assumption that only Samba
3247 * requests kernel oplocks. Once someone else like
3248 * NFSv4 starts to use that API, we will have to
3249 * modify this by communicating with the NFSv4 server.
3251 flags2 |= O_NONBLOCK;
3255 * Ensure we can't write on a read-only share or file.
3258 if (flags != O_RDONLY && file_existed &&
3259 (!CAN_WRITE(conn) || IS_DOS_READONLY(existing_dos_attributes))) {
3260 DEBUG(5,("open_file_ntcreate: write access requested for "
3261 "file %s on read only %s\n",
3262 smb_fname_str_dbg(smb_fname),
3263 !CAN_WRITE(conn) ? "share" : "file" ));
3264 errno = EACCES;
3265 return NT_STATUS_ACCESS_DENIED;
3268 fsp->file_id = vfs_file_id_from_sbuf(conn, &smb_fname->st);
3269 fsp->share_access = share_access;
3270 fsp->fh->private_options = private_flags;
3271 fsp->access_mask = open_access_mask; /* We change this to the
3272 * requested access_mask after
3273 * the open is done. */
3274 if (posix_open) {
3275 fsp->posix_flags |= FSP_POSIX_FLAGS_ALL;
3278 if (timeval_is_zero(&request_time)) {
3279 request_time = fsp->open_time;
3283 * Ensure we pay attention to default ACLs on directories if required.
3286 if ((flags2 & O_CREAT) && lp_inherit_acls(SNUM(conn)) &&
3287 (def_acl = directory_has_default_acl(conn, parent_dir))) {
3288 unx_mode = (0777 & lp_create_mask(SNUM(conn)));
3291 DEBUG(4,("calling open_file with flags=0x%X flags2=0x%X mode=0%o, "
3292 "access_mask = 0x%x, open_access_mask = 0x%x\n",
3293 (unsigned int)flags, (unsigned int)flags2,
3294 (unsigned int)unx_mode, (unsigned int)access_mask,
3295 (unsigned int)open_access_mask));
3297 fsp_open = open_file(fsp, conn, req, parent_dir,
3298 flags|flags2, unx_mode, access_mask,
3299 open_access_mask, &new_file_created);
3301 if (NT_STATUS_EQUAL(fsp_open, NT_STATUS_NETWORK_BUSY)) {
3302 bool delay;
3305 * This handles the kernel oplock case:
3307 * the file has an active kernel oplock and the open() returned
3308 * EWOULDBLOCK/EAGAIN which maps to NETWORK_BUSY.
3310 * "Samba locking.tdb oplocks" are handled below after acquiring
3311 * the sharemode lock with get_share_mode_lock().
3313 if (file_existed && S_ISFIFO(fsp->fsp_name->st.st_ex_mode)) {
3314 DEBUG(10, ("FIFO busy\n"));
3315 return NT_STATUS_NETWORK_BUSY;
3317 if (req == NULL) {
3318 DEBUG(10, ("Internal open busy\n"));
3319 return NT_STATUS_NETWORK_BUSY;
3323 * From here on we assume this is an oplock break triggered
3326 lck = get_existing_share_mode_lock(talloc_tos(), fsp->file_id);
3327 if (lck == NULL) {
3328 retry_open(request_time, req, fsp->file_id);
3329 DEBUG(10, ("No share mode lock found after "
3330 "EWOULDBLOCK, retrying sync\n"));
3331 return NT_STATUS_SHARING_VIOLATION;
3334 if (!validate_oplock_types(lck)) {
3335 smb_panic("validate_oplock_types failed");
3338 delay = delay_for_oplock(fsp, 0, lease, lck, false,
3339 create_disposition,
3340 first_open_attempt);
3341 if (delay) {
3342 schedule_defer_open(lck, fsp->file_id, request_time,
3343 req, true);
3344 TALLOC_FREE(lck);
3345 DEBUG(10, ("Sent oplock break request to kernel "
3346 "oplock holder\n"));
3347 return NT_STATUS_SHARING_VIOLATION;
3351 * No oplock from Samba around. Immediately retry with
3352 * a blocking open.
3354 retry_open(request_time, req, fsp->file_id);
3356 TALLOC_FREE(lck);
3357 DEBUG(10, ("No Samba oplock around after EWOULDBLOCK. "
3358 "Retrying sync\n"));
3359 return NT_STATUS_SHARING_VIOLATION;
3362 if (!NT_STATUS_IS_OK(fsp_open)) {
3363 if (NT_STATUS_EQUAL(fsp_open, NT_STATUS_RETRY)) {
3364 schedule_async_open(request_time, req);
3366 return fsp_open;
3369 if (new_file_created) {
3371 * As we atomically create using O_CREAT|O_EXCL,
3372 * then if new_file_created is true, then
3373 * file_existed *MUST* have been false (even
3374 * if the file was previously detected as being
3375 * there).
3377 file_existed = false;
3380 if (file_existed && !check_same_dev_ino(&saved_stat, &smb_fname->st)) {
3382 * The file did exist, but some other (local or NFS)
3383 * process either renamed/unlinked and re-created the
3384 * file with different dev/ino after we walked the path,
3385 * but before we did the open. We could retry the
3386 * open but it's a rare enough case it's easier to
3387 * just fail the open to prevent creating any problems
3388 * in the open file db having the wrong dev/ino key.
3390 fd_close(fsp);
3391 DEBUG(1,("open_file_ntcreate: file %s - dev/ino mismatch. "
3392 "Old (dev=0x%llu, ino =0x%llu). "
3393 "New (dev=0x%llu, ino=0x%llu). Failing open "
3394 " with NT_STATUS_ACCESS_DENIED.\n",
3395 smb_fname_str_dbg(smb_fname),
3396 (unsigned long long)saved_stat.st_ex_dev,
3397 (unsigned long long)saved_stat.st_ex_ino,
3398 (unsigned long long)smb_fname->st.st_ex_dev,
3399 (unsigned long long)smb_fname->st.st_ex_ino));
3400 return NT_STATUS_ACCESS_DENIED;
3403 old_write_time = smb_fname->st.st_ex_mtime;
3406 * Deal with the race condition where two smbd's detect the
3407 * file doesn't exist and do the create at the same time. One
3408 * of them will win and set a share mode, the other (ie. this
3409 * one) should check if the requested share mode for this
3410 * create is allowed.
3414 * Now the file exists and fsp is successfully opened,
3415 * fsp->dev and fsp->inode are valid and should replace the
3416 * dev=0,inode=0 from a non existent file. Spotted by
3417 * Nadav Danieli <nadavd@exanet.com>. JRA.
3420 id = fsp->file_id;
3422 lck = get_share_mode_lock(talloc_tos(), id,
3423 conn->connectpath,
3424 smb_fname, &old_write_time);
3426 if (lck == NULL) {
3427 DEBUG(0, ("open_file_ntcreate: Could not get share "
3428 "mode lock for %s\n",
3429 smb_fname_str_dbg(smb_fname)));
3430 fd_close(fsp);
3431 return NT_STATUS_SHARING_VIOLATION;
3434 /* Get the types we need to examine. */
3435 if (!validate_oplock_types(lck)) {
3436 smb_panic("validate_oplock_types failed");
3439 if (has_delete_on_close(lck, fsp->name_hash)) {
3440 TALLOC_FREE(lck);
3441 fd_close(fsp);
3442 return NT_STATUS_DELETE_PENDING;
3445 status = open_mode_check(conn, lck,
3446 access_mask, share_access);
3448 if (NT_STATUS_EQUAL(status, NT_STATUS_SHARING_VIOLATION) ||
3449 (lck->data->num_share_modes > 0)) {
3451 * This comes from ancient times out of open_mode_check. I
3452 * have no clue whether this is still necessary. I can't think
3453 * of a case where this would actually matter further down in
3454 * this function. I leave it here for further investigation
3455 * :-)
3457 file_existed = true;
3460 if (req != NULL) {
3462 * Handle oplocks, deferring the request if delay_for_oplock()
3463 * triggered a break message and we have to wait for the break
3464 * response.
3466 bool delay;
3467 bool sharing_violation = NT_STATUS_EQUAL(
3468 status, NT_STATUS_SHARING_VIOLATION);
3470 delay = delay_for_oplock(fsp, oplock_request, lease, lck,
3471 sharing_violation,
3472 create_disposition,
3473 first_open_attempt);
3474 if (delay) {
3475 schedule_defer_open(lck, fsp->file_id,
3476 request_time, req, false);
3477 TALLOC_FREE(lck);
3478 fd_close(fsp);
3479 return NT_STATUS_SHARING_VIOLATION;
3483 if (!NT_STATUS_IS_OK(status)) {
3484 uint32_t can_access_mask;
3485 bool can_access = True;
3487 SMB_ASSERT(NT_STATUS_EQUAL(status, NT_STATUS_SHARING_VIOLATION));
3489 /* Check if this can be done with the deny_dos and fcb
3490 * calls. */
3491 if (private_flags &
3492 (NTCREATEX_OPTIONS_PRIVATE_DENY_DOS|
3493 NTCREATEX_OPTIONS_PRIVATE_DENY_FCB)) {
3494 if (req == NULL) {
3495 DEBUG(0, ("DOS open without an SMB "
3496 "request!\n"));
3497 TALLOC_FREE(lck);
3498 fd_close(fsp);
3499 return NT_STATUS_INTERNAL_ERROR;
3502 /* Use the client requested access mask here,
3503 * not the one we open with. */
3504 status = fcb_or_dos_open(req,
3505 conn,
3506 fsp,
3507 smb_fname,
3509 req->smbpid,
3510 req->vuid,
3511 access_mask,
3512 share_access,
3513 create_options);
3515 if (NT_STATUS_IS_OK(status)) {
3516 TALLOC_FREE(lck);
3517 if (pinfo) {
3518 *pinfo = FILE_WAS_OPENED;
3520 return NT_STATUS_OK;
3525 * This next line is a subtlety we need for
3526 * MS-Access. If a file open will fail due to share
3527 * permissions and also for security (access) reasons,
3528 * we need to return the access failed error, not the
3529 * share error. We can't open the file due to kernel
3530 * oplock deadlock (it's possible we failed above on
3531 * the open_mode_check()) so use a userspace check.
3534 if (flags & O_RDWR) {
3535 can_access_mask = FILE_READ_DATA|FILE_WRITE_DATA;
3536 } else if (flags & O_WRONLY) {
3537 can_access_mask = FILE_WRITE_DATA;
3538 } else {
3539 can_access_mask = FILE_READ_DATA;
3542 if (((can_access_mask & FILE_WRITE_DATA) &&
3543 !CAN_WRITE(conn)) ||
3544 !NT_STATUS_IS_OK(smbd_check_access_rights(conn,
3545 smb_fname,
3546 false,
3547 can_access_mask))) {
3548 can_access = False;
3552 * If we're returning a share violation, ensure we
3553 * cope with the braindead 1 second delay (SMB1 only).
3556 if (!(oplock_request & INTERNAL_OPEN_ONLY) &&
3557 !conn->sconn->using_smb2 &&
3558 lp_defer_sharing_violations()) {
3559 struct timeval timeout;
3560 int timeout_usecs;
3562 /* this is a hack to speed up torture tests
3563 in 'make test' */
3564 timeout_usecs = lp_parm_int(SNUM(conn),
3565 "smbd","sharedelay",
3566 SHARING_VIOLATION_USEC_WAIT);
3568 /* This is a relative time, added to the absolute
3569 request_time value to get the absolute timeout time.
3570 Note that if this is the second or greater time we enter
3571 this codepath for this particular request mid then
3572 request_time is left as the absolute time of the *first*
3573 time this request mid was processed. This is what allows
3574 the request to eventually time out. */
3576 timeout = timeval_set(0, timeout_usecs);
3578 if (!request_timed_out(request_time, timeout)) {
3579 defer_open(lck, request_time, timeout, req,
3580 false, false, id);
3584 TALLOC_FREE(lck);
3585 fd_close(fsp);
3586 if (can_access) {
3588 * We have detected a sharing violation here
3589 * so return the correct error code
3591 status = NT_STATUS_SHARING_VIOLATION;
3592 } else {
3593 status = NT_STATUS_ACCESS_DENIED;
3595 return status;
3598 /* Should we atomically (to the client at least) truncate ? */
3599 if ((!new_file_created) &&
3600 (flags2 & O_TRUNC) &&
3601 (!S_ISFIFO(fsp->fsp_name->st.st_ex_mode))) {
3602 int ret;
3604 ret = vfs_set_filelen(fsp, 0);
3605 if (ret != 0) {
3606 status = map_nt_error_from_unix(errno);
3607 TALLOC_FREE(lck);
3608 fd_close(fsp);
3609 return status;
3614 * We have the share entry *locked*.....
3617 /* Delete streams if create_disposition requires it */
3618 if (!new_file_created && clear_ads(create_disposition) &&
3619 !is_ntfs_stream_smb_fname(smb_fname)) {
3620 status = delete_all_streams(conn, smb_fname);
3621 if (!NT_STATUS_IS_OK(status)) {
3622 TALLOC_FREE(lck);
3623 fd_close(fsp);
3624 return status;
3628 /* note that we ignore failure for the following. It is
3629 basically a hack for NFS, and NFS will never set one of
3630 these only read them. Nobody but Samba can ever set a deny
3631 mode and we have already checked our more authoritative
3632 locking database for permission to set this deny mode. If
3633 the kernel refuses the operations then the kernel is wrong.
3634 note that GPFS supports it as well - jmcd */
3636 if (fsp->fh->fd != -1 && lp_kernel_share_modes(SNUM(conn))) {
3637 int ret_flock;
3639 * Beware: streams implementing VFS modules may
3640 * implement streams in a way that fsp will have the
3641 * basefile open in the fsp fd, so lacking a distinct
3642 * fd for the stream kernel_flock will apply on the
3643 * basefile which is wrong. The actual check is
3644 * deffered to the VFS module implementing the
3645 * kernel_flock call.
3647 ret_flock = SMB_VFS_KERNEL_FLOCK(fsp, share_access, access_mask);
3648 if(ret_flock == -1 ){
3650 TALLOC_FREE(lck);
3651 fd_close(fsp);
3653 return NT_STATUS_SHARING_VIOLATION;
3656 fsp->kernel_share_modes_taken = true;
3660 * At this point onwards, we can guarantee that the share entry
3661 * is locked, whether we created the file or not, and that the
3662 * deny mode is compatible with all current opens.
3666 * According to Samba4, SEC_FILE_READ_ATTRIBUTE is always granted,
3667 * but we don't have to store this - just ignore it on access check.
3669 if (conn->sconn->using_smb2) {
3671 * SMB2 doesn't return it (according to Microsoft tests).
3672 * Test Case: TestSuite_ScenarioNo009GrantedAccessTestS0
3673 * File created with access = 0x7 (Read, Write, Delete)
3674 * Query Info on file returns 0x87 (Read, Write, Delete, Read Attributes)
3676 fsp->access_mask = access_mask;
3677 } else {
3678 /* But SMB1 does. */
3679 fsp->access_mask = access_mask | FILE_READ_ATTRIBUTES;
3682 if (file_existed) {
3684 * stat opens on existing files don't get oplocks.
3685 * They can get leases.
3687 * Note that we check for stat open on the *open_access_mask*,
3688 * i.e. the access mask we actually used to do the open,
3689 * not the one the client asked for (which is in
3690 * fsp->access_mask). This is due to the fact that
3691 * FILE_OVERWRITE and FILE_OVERWRITE_IF add in O_TRUNC,
3692 * which adds FILE_WRITE_DATA to open_access_mask.
3694 if (is_stat_open(open_access_mask) && lease == NULL) {
3695 oplock_request = NO_OPLOCK;
3699 if (new_file_created) {
3700 info = FILE_WAS_CREATED;
3701 } else {
3702 if (flags2 & O_TRUNC) {
3703 info = FILE_WAS_OVERWRITTEN;
3704 } else {
3705 info = FILE_WAS_OPENED;
3709 if (pinfo) {
3710 *pinfo = info;
3714 * Setup the oplock info in both the shared memory and
3715 * file structs.
3717 status = grant_fsp_oplock_type(req, fsp, lck, oplock_request, lease);
3718 if (!NT_STATUS_IS_OK(status)) {
3719 TALLOC_FREE(lck);
3720 fd_close(fsp);
3721 return status;
3724 /* Handle strange delete on close create semantics. */
3725 if (create_options & FILE_DELETE_ON_CLOSE) {
3727 status = can_set_delete_on_close(fsp, new_dos_attributes);
3729 if (!NT_STATUS_IS_OK(status)) {
3730 /* Remember to delete the mode we just added. */
3731 del_share_mode(lck, fsp);
3732 TALLOC_FREE(lck);
3733 fd_close(fsp);
3734 return status;
3736 /* Note that here we set the *inital* delete on close flag,
3737 not the regular one. The magic gets handled in close. */
3738 fsp->initial_delete_on_close = True;
3741 if (info != FILE_WAS_OPENED) {
3742 /* Overwritten files should be initially set as archive */
3743 if ((info == FILE_WAS_OVERWRITTEN && lp_map_archive(SNUM(conn))) ||
3744 lp_store_dos_attributes(SNUM(conn))) {
3745 if (!posix_open) {
3746 if (file_set_dosmode(conn, smb_fname,
3747 new_dos_attributes | FILE_ATTRIBUTE_ARCHIVE,
3748 parent_dir, true) == 0) {
3749 unx_mode = smb_fname->st.st_ex_mode;
3755 /* Determine sparse flag. */
3756 if (posix_open) {
3757 /* POSIX opens are sparse by default. */
3758 fsp->is_sparse = true;
3759 } else {
3760 fsp->is_sparse = (file_existed &&
3761 (existing_dos_attributes & FILE_ATTRIBUTE_SPARSE));
3765 * Take care of inherited ACLs on created files - if default ACL not
3766 * selected.
3769 if (!posix_open && new_file_created && !def_acl) {
3771 int saved_errno = errno; /* We might get ENOSYS in the next
3772 * call.. */
3774 if (SMB_VFS_FCHMOD_ACL(fsp, unx_mode) == -1 &&
3775 errno == ENOSYS) {
3776 errno = saved_errno; /* Ignore ENOSYS */
3779 } else if (new_unx_mode) {
3781 int ret = -1;
3783 /* Attributes need changing. File already existed. */
3786 int saved_errno = errno; /* We might get ENOSYS in the
3787 * next call.. */
3788 ret = SMB_VFS_FCHMOD_ACL(fsp, new_unx_mode);
3790 if (ret == -1 && errno == ENOSYS) {
3791 errno = saved_errno; /* Ignore ENOSYS */
3792 } else {
3793 DEBUG(5, ("open_file_ntcreate: reset "
3794 "attributes of file %s to 0%o\n",
3795 smb_fname_str_dbg(smb_fname),
3796 (unsigned int)new_unx_mode));
3797 ret = 0; /* Don't do the fchmod below. */
3801 if ((ret == -1) &&
3802 (SMB_VFS_FCHMOD(fsp, new_unx_mode) == -1))
3803 DEBUG(5, ("open_file_ntcreate: failed to reset "
3804 "attributes of file %s to 0%o\n",
3805 smb_fname_str_dbg(smb_fname),
3806 (unsigned int)new_unx_mode));
3811 * Deal with other opens having a modified write time.
3813 struct timespec write_time = get_share_mode_write_time(lck);
3815 if (!null_timespec(write_time)) {
3816 update_stat_ex_mtime(&fsp->fsp_name->st, write_time);
3820 TALLOC_FREE(lck);
3822 return NT_STATUS_OK;
3825 static NTSTATUS mkdir_internal(connection_struct *conn,
3826 struct smb_filename *smb_dname,
3827 uint32_t file_attributes)
3829 mode_t mode;
3830 char *parent_dir = NULL;
3831 NTSTATUS status;
3832 bool posix_open = false;
3833 bool need_re_stat = false;
3834 uint32_t access_mask = SEC_DIR_ADD_SUBDIR;
3836 if (!CAN_WRITE(conn) || (access_mask & ~(conn->share_access))) {
3837 DEBUG(5,("mkdir_internal: failing share access "
3838 "%s\n", lp_servicename(talloc_tos(), SNUM(conn))));
3839 return NT_STATUS_ACCESS_DENIED;
3842 if (!parent_dirname(talloc_tos(), smb_dname->base_name, &parent_dir,
3843 NULL)) {
3844 return NT_STATUS_NO_MEMORY;
3847 if (file_attributes & FILE_FLAG_POSIX_SEMANTICS) {
3848 posix_open = true;
3849 mode = (mode_t)(file_attributes & ~FILE_FLAG_POSIX_SEMANTICS);
3850 } else {
3851 mode = unix_mode(conn, FILE_ATTRIBUTE_DIRECTORY, smb_dname, parent_dir);
3854 status = check_parent_access(conn,
3855 smb_dname,
3856 access_mask);
3857 if(!NT_STATUS_IS_OK(status)) {
3858 DEBUG(5,("mkdir_internal: check_parent_access "
3859 "on directory %s for path %s returned %s\n",
3860 parent_dir,
3861 smb_dname->base_name,
3862 nt_errstr(status) ));
3863 return status;
3866 if (SMB_VFS_MKDIR(conn, smb_dname, mode) != 0) {
3867 return map_nt_error_from_unix(errno);
3870 /* Ensure we're checking for a symlink here.... */
3871 /* We don't want to get caught by a symlink racer. */
3873 if (SMB_VFS_LSTAT(conn, smb_dname) == -1) {
3874 DEBUG(2, ("Could not stat directory '%s' just created: %s\n",
3875 smb_fname_str_dbg(smb_dname), strerror(errno)));
3876 return map_nt_error_from_unix(errno);
3879 if (!S_ISDIR(smb_dname->st.st_ex_mode)) {
3880 DEBUG(0, ("Directory '%s' just created is not a directory !\n",
3881 smb_fname_str_dbg(smb_dname)));
3882 return NT_STATUS_NOT_A_DIRECTORY;
3885 if (lp_store_dos_attributes(SNUM(conn))) {
3886 if (!posix_open) {
3887 file_set_dosmode(conn, smb_dname,
3888 file_attributes | FILE_ATTRIBUTE_DIRECTORY,
3889 parent_dir, true);
3893 if (lp_inherit_permissions(SNUM(conn))) {
3894 inherit_access_posix_acl(conn, parent_dir,
3895 smb_dname, mode);
3896 need_re_stat = true;
3899 if (!posix_open) {
3901 * Check if high bits should have been set,
3902 * then (if bits are missing): add them.
3903 * Consider bits automagically set by UNIX, i.e. SGID bit from parent
3904 * dir.
3906 if ((mode & ~(S_IRWXU|S_IRWXG|S_IRWXO)) &&
3907 (mode & ~smb_dname->st.st_ex_mode)) {
3908 SMB_VFS_CHMOD(conn, smb_dname,
3909 (smb_dname->st.st_ex_mode |
3910 (mode & ~smb_dname->st.st_ex_mode)));
3911 need_re_stat = true;
3915 /* Change the owner if required. */
3916 if (lp_inherit_owner(SNUM(conn)) != INHERIT_OWNER_NO) {
3917 change_dir_owner_to_parent(conn, parent_dir,
3918 smb_dname,
3919 &smb_dname->st);
3920 need_re_stat = true;
3923 if (need_re_stat) {
3924 if (SMB_VFS_LSTAT(conn, smb_dname) == -1) {
3925 DEBUG(2, ("Could not stat directory '%s' just created: %s\n",
3926 smb_fname_str_dbg(smb_dname), strerror(errno)));
3927 return map_nt_error_from_unix(errno);
3931 notify_fname(conn, NOTIFY_ACTION_ADDED, FILE_NOTIFY_CHANGE_DIR_NAME,
3932 smb_dname->base_name);
3934 return NT_STATUS_OK;
3937 /****************************************************************************
3938 Open a directory from an NT SMB call.
3939 ****************************************************************************/
3941 static NTSTATUS open_directory(connection_struct *conn,
3942 struct smb_request *req,
3943 struct smb_filename *smb_dname,
3944 uint32_t access_mask,
3945 uint32_t share_access,
3946 uint32_t create_disposition,
3947 uint32_t create_options,
3948 uint32_t file_attributes,
3949 int *pinfo,
3950 files_struct **result)
3952 files_struct *fsp = NULL;
3953 bool dir_existed = VALID_STAT(smb_dname->st) ? True : False;
3954 struct share_mode_lock *lck = NULL;
3955 NTSTATUS status;
3956 struct timespec mtimespec;
3957 int info = 0;
3958 bool ok;
3960 if (is_ntfs_stream_smb_fname(smb_dname)) {
3961 DEBUG(2, ("open_directory: %s is a stream name!\n",
3962 smb_fname_str_dbg(smb_dname)));
3963 return NT_STATUS_NOT_A_DIRECTORY;
3966 if (!(file_attributes & FILE_FLAG_POSIX_SEMANTICS)) {
3967 /* Ensure we have a directory attribute. */
3968 file_attributes |= FILE_ATTRIBUTE_DIRECTORY;
3971 DEBUG(5,("open_directory: opening directory %s, access_mask = 0x%x, "
3972 "share_access = 0x%x create_options = 0x%x, "
3973 "create_disposition = 0x%x, file_attributes = 0x%x\n",
3974 smb_fname_str_dbg(smb_dname),
3975 (unsigned int)access_mask,
3976 (unsigned int)share_access,
3977 (unsigned int)create_options,
3978 (unsigned int)create_disposition,
3979 (unsigned int)file_attributes));
3981 status = smbd_calculate_access_mask(conn, smb_dname, false,
3982 access_mask, &access_mask);
3983 if (!NT_STATUS_IS_OK(status)) {
3984 DEBUG(10, ("open_directory: smbd_calculate_access_mask "
3985 "on file %s returned %s\n",
3986 smb_fname_str_dbg(smb_dname),
3987 nt_errstr(status)));
3988 return status;
3991 if ((access_mask & SEC_FLAG_SYSTEM_SECURITY) &&
3992 !security_token_has_privilege(get_current_nttok(conn),
3993 SEC_PRIV_SECURITY)) {
3994 DEBUG(10, ("open_directory: open on %s "
3995 "failed - SEC_FLAG_SYSTEM_SECURITY denied.\n",
3996 smb_fname_str_dbg(smb_dname)));
3997 return NT_STATUS_PRIVILEGE_NOT_HELD;
4000 switch( create_disposition ) {
4001 case FILE_OPEN:
4003 if (!dir_existed) {
4004 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
4007 info = FILE_WAS_OPENED;
4008 break;
4010 case FILE_CREATE:
4012 /* If directory exists error. If directory doesn't
4013 * exist create. */
4015 if (dir_existed) {
4016 status = NT_STATUS_OBJECT_NAME_COLLISION;
4017 DEBUG(2, ("open_directory: unable to create "
4018 "%s. Error was %s\n",
4019 smb_fname_str_dbg(smb_dname),
4020 nt_errstr(status)));
4021 return status;
4024 status = mkdir_internal(conn, smb_dname,
4025 file_attributes);
4027 if (!NT_STATUS_IS_OK(status)) {
4028 DEBUG(2, ("open_directory: unable to create "
4029 "%s. Error was %s\n",
4030 smb_fname_str_dbg(smb_dname),
4031 nt_errstr(status)));
4032 return status;
4035 info = FILE_WAS_CREATED;
4036 break;
4038 case FILE_OPEN_IF:
4040 * If directory exists open. If directory doesn't
4041 * exist create.
4044 if (dir_existed) {
4045 status = NT_STATUS_OK;
4046 info = FILE_WAS_OPENED;
4047 } else {
4048 status = mkdir_internal(conn, smb_dname,
4049 file_attributes);
4051 if (NT_STATUS_IS_OK(status)) {
4052 info = FILE_WAS_CREATED;
4053 } else {
4054 /* Cope with create race. */
4055 if (!NT_STATUS_EQUAL(status,
4056 NT_STATUS_OBJECT_NAME_COLLISION)) {
4057 DEBUG(2, ("open_directory: unable to create "
4058 "%s. Error was %s\n",
4059 smb_fname_str_dbg(smb_dname),
4060 nt_errstr(status)));
4061 return status;
4065 * If mkdir_internal() returned
4066 * NT_STATUS_OBJECT_NAME_COLLISION
4067 * we still must lstat the path.
4070 if (SMB_VFS_LSTAT(conn, smb_dname)
4071 == -1) {
4072 DEBUG(2, ("Could not stat "
4073 "directory '%s' just "
4074 "opened: %s\n",
4075 smb_fname_str_dbg(
4076 smb_dname),
4077 strerror(errno)));
4078 return map_nt_error_from_unix(
4079 errno);
4082 info = FILE_WAS_OPENED;
4086 break;
4088 case FILE_SUPERSEDE:
4089 case FILE_OVERWRITE:
4090 case FILE_OVERWRITE_IF:
4091 default:
4092 DEBUG(5,("open_directory: invalid create_disposition "
4093 "0x%x for directory %s\n",
4094 (unsigned int)create_disposition,
4095 smb_fname_str_dbg(smb_dname)));
4096 return NT_STATUS_INVALID_PARAMETER;
4099 if(!S_ISDIR(smb_dname->st.st_ex_mode)) {
4100 DEBUG(5,("open_directory: %s is not a directory !\n",
4101 smb_fname_str_dbg(smb_dname)));
4102 return NT_STATUS_NOT_A_DIRECTORY;
4105 if (info == FILE_WAS_OPENED) {
4106 status = smbd_check_access_rights(conn,
4107 smb_dname,
4108 false,
4109 access_mask);
4110 if (!NT_STATUS_IS_OK(status)) {
4111 DEBUG(10, ("open_directory: smbd_check_access_rights on "
4112 "file %s failed with %s\n",
4113 smb_fname_str_dbg(smb_dname),
4114 nt_errstr(status)));
4115 return status;
4119 status = file_new(req, conn, &fsp);
4120 if(!NT_STATUS_IS_OK(status)) {
4121 return status;
4125 * Setup the files_struct for it.
4128 fsp->file_id = vfs_file_id_from_sbuf(conn, &smb_dname->st);
4129 fsp->vuid = req ? req->vuid : UID_FIELD_INVALID;
4130 fsp->file_pid = req ? req->smbpid : 0;
4131 fsp->can_lock = False;
4132 fsp->can_read = False;
4133 fsp->can_write = False;
4135 fsp->share_access = share_access;
4136 fsp->fh->private_options = 0;
4138 * According to Samba4, SEC_FILE_READ_ATTRIBUTE is always granted,
4140 fsp->access_mask = access_mask | FILE_READ_ATTRIBUTES;
4141 fsp->print_file = NULL;
4142 fsp->modified = False;
4143 fsp->oplock_type = NO_OPLOCK;
4144 fsp->sent_oplock_break = NO_BREAK_SENT;
4145 fsp->is_directory = True;
4146 if (file_attributes & FILE_FLAG_POSIX_SEMANTICS) {
4147 fsp->posix_flags |= FSP_POSIX_FLAGS_ALL;
4149 status = fsp_set_smb_fname(fsp, smb_dname);
4150 if (!NT_STATUS_IS_OK(status)) {
4151 file_free(req, fsp);
4152 return status;
4155 /* Don't store old timestamps for directory
4156 handles in the internal database. We don't
4157 update them in there if new objects
4158 are creaded in the directory. Currently
4159 we only update timestamps on file writes.
4160 See bug #9870.
4162 ZERO_STRUCT(mtimespec);
4164 if (access_mask & (FILE_LIST_DIRECTORY|
4165 FILE_ADD_FILE|
4166 FILE_ADD_SUBDIRECTORY|
4167 FILE_TRAVERSE|
4168 DELETE_ACCESS|
4169 FILE_DELETE_CHILD)) {
4170 #ifdef O_DIRECTORY
4171 status = fd_open(conn, fsp, O_RDONLY|O_DIRECTORY, 0);
4172 #else
4173 /* POSIX allows us to open a directory with O_RDONLY. */
4174 status = fd_open(conn, fsp, O_RDONLY, 0);
4175 #endif
4176 if (!NT_STATUS_IS_OK(status)) {
4177 DEBUG(5, ("open_directory: Could not open fd for "
4178 "%s (%s)\n",
4179 smb_fname_str_dbg(smb_dname),
4180 nt_errstr(status)));
4181 file_free(req, fsp);
4182 return status;
4184 } else {
4185 fsp->fh->fd = -1;
4186 DEBUG(10, ("Not opening Directory %s\n",
4187 smb_fname_str_dbg(smb_dname)));
4190 status = vfs_stat_fsp(fsp);
4191 if (!NT_STATUS_IS_OK(status)) {
4192 fd_close(fsp);
4193 file_free(req, fsp);
4194 return status;
4197 if(!S_ISDIR(fsp->fsp_name->st.st_ex_mode)) {
4198 DEBUG(5,("open_directory: %s is not a directory !\n",
4199 smb_fname_str_dbg(smb_dname)));
4200 fd_close(fsp);
4201 file_free(req, fsp);
4202 return NT_STATUS_NOT_A_DIRECTORY;
4205 /* Ensure there was no race condition. We need to check
4206 * dev/inode but not permissions, as these can change
4207 * legitimately */
4208 if (!check_same_dev_ino(&smb_dname->st, &fsp->fsp_name->st)) {
4209 DEBUG(5,("open_directory: stat struct differs for "
4210 "directory %s.\n",
4211 smb_fname_str_dbg(smb_dname)));
4212 fd_close(fsp);
4213 file_free(req, fsp);
4214 return NT_STATUS_ACCESS_DENIED;
4217 lck = get_share_mode_lock(talloc_tos(), fsp->file_id,
4218 conn->connectpath, smb_dname,
4219 &mtimespec);
4221 if (lck == NULL) {
4222 DEBUG(0, ("open_directory: Could not get share mode lock for "
4223 "%s\n", smb_fname_str_dbg(smb_dname)));
4224 fd_close(fsp);
4225 file_free(req, fsp);
4226 return NT_STATUS_SHARING_VIOLATION;
4229 if (has_delete_on_close(lck, fsp->name_hash)) {
4230 TALLOC_FREE(lck);
4231 fd_close(fsp);
4232 file_free(req, fsp);
4233 return NT_STATUS_DELETE_PENDING;
4236 status = open_mode_check(conn, lck,
4237 access_mask, share_access);
4239 if (!NT_STATUS_IS_OK(status)) {
4240 TALLOC_FREE(lck);
4241 fd_close(fsp);
4242 file_free(req, fsp);
4243 return status;
4246 ok = set_share_mode(lck, fsp, get_current_uid(conn),
4247 req ? req->mid : 0, NO_OPLOCK,
4248 UINT32_MAX);
4249 if (!ok) {
4250 TALLOC_FREE(lck);
4251 fd_close(fsp);
4252 file_free(req, fsp);
4253 return NT_STATUS_NO_MEMORY;
4256 /* For directories the delete on close bit at open time seems
4257 always to be honored on close... See test 19 in Samba4 BASE-DELETE. */
4258 if (create_options & FILE_DELETE_ON_CLOSE) {
4259 status = can_set_delete_on_close(fsp, 0);
4260 if (!NT_STATUS_IS_OK(status) && !NT_STATUS_EQUAL(status, NT_STATUS_DIRECTORY_NOT_EMPTY)) {
4261 del_share_mode(lck, fsp);
4262 TALLOC_FREE(lck);
4263 fd_close(fsp);
4264 file_free(req, fsp);
4265 return status;
4268 if (NT_STATUS_IS_OK(status)) {
4269 /* Note that here we set the *inital* delete on close flag,
4270 not the regular one. The magic gets handled in close. */
4271 fsp->initial_delete_on_close = True;
4277 * Deal with other opens having a modified write time. Is this
4278 * possible for directories?
4280 struct timespec write_time = get_share_mode_write_time(lck);
4282 if (!null_timespec(write_time)) {
4283 update_stat_ex_mtime(&fsp->fsp_name->st, write_time);
4287 TALLOC_FREE(lck);
4289 if (pinfo) {
4290 *pinfo = info;
4293 *result = fsp;
4294 return NT_STATUS_OK;
4297 NTSTATUS create_directory(connection_struct *conn, struct smb_request *req,
4298 struct smb_filename *smb_dname)
4300 NTSTATUS status;
4301 files_struct *fsp;
4303 status = SMB_VFS_CREATE_FILE(
4304 conn, /* conn */
4305 req, /* req */
4306 0, /* root_dir_fid */
4307 smb_dname, /* fname */
4308 FILE_READ_ATTRIBUTES, /* access_mask */
4309 FILE_SHARE_NONE, /* share_access */
4310 FILE_CREATE, /* create_disposition*/
4311 FILE_DIRECTORY_FILE, /* create_options */
4312 FILE_ATTRIBUTE_DIRECTORY, /* file_attributes */
4313 0, /* oplock_request */
4314 NULL, /* lease */
4315 0, /* allocation_size */
4316 0, /* private_flags */
4317 NULL, /* sd */
4318 NULL, /* ea_list */
4319 &fsp, /* result */
4320 NULL, /* pinfo */
4321 NULL, NULL); /* create context */
4323 if (NT_STATUS_IS_OK(status)) {
4324 close_file(req, fsp, NORMAL_CLOSE);
4327 return status;
4330 /****************************************************************************
4331 Receive notification that one of our open files has been renamed by another
4332 smbd process.
4333 ****************************************************************************/
4335 void msg_file_was_renamed(struct messaging_context *msg,
4336 void *private_data,
4337 uint32_t msg_type,
4338 struct server_id server_id,
4339 DATA_BLOB *data)
4341 files_struct *fsp;
4342 char *frm = (char *)data->data;
4343 struct file_id id;
4344 const char *sharepath;
4345 const char *base_name;
4346 const char *stream_name;
4347 struct smb_filename *smb_fname = NULL;
4348 size_t sp_len, bn_len;
4349 NTSTATUS status;
4350 struct smbd_server_connection *sconn =
4351 talloc_get_type_abort(private_data,
4352 struct smbd_server_connection);
4354 if (data->data == NULL
4355 || data->length < MSG_FILE_RENAMED_MIN_SIZE + 2) {
4356 DEBUG(0, ("msg_file_was_renamed: Got invalid msg len %d\n",
4357 (int)data->length));
4358 return;
4361 /* Unpack the message. */
4362 pull_file_id_24(frm, &id);
4363 sharepath = &frm[24];
4364 sp_len = strlen(sharepath);
4365 base_name = sharepath + sp_len + 1;
4366 bn_len = strlen(base_name);
4367 stream_name = sharepath + sp_len + 1 + bn_len + 1;
4369 /* stream_name must always be NULL if there is no stream. */
4370 if (stream_name[0] == '\0') {
4371 stream_name = NULL;
4374 smb_fname = synthetic_smb_fname(talloc_tos(),
4375 base_name,
4376 stream_name,
4377 NULL,
4379 if (smb_fname == NULL) {
4380 return;
4383 DEBUG(10,("msg_file_was_renamed: Got rename message for sharepath %s, new name %s, "
4384 "file_id %s\n",
4385 sharepath, smb_fname_str_dbg(smb_fname),
4386 file_id_string_tos(&id)));
4388 for(fsp = file_find_di_first(sconn, id); fsp;
4389 fsp = file_find_di_next(fsp)) {
4390 if (memcmp(fsp->conn->connectpath, sharepath, sp_len) == 0) {
4392 DEBUG(10,("msg_file_was_renamed: renaming file %s from %s -> %s\n",
4393 fsp_fnum_dbg(fsp), fsp_str_dbg(fsp),
4394 smb_fname_str_dbg(smb_fname)));
4395 status = fsp_set_smb_fname(fsp, smb_fname);
4396 if (!NT_STATUS_IS_OK(status)) {
4397 goto out;
4399 } else {
4400 /* TODO. JRA. */
4401 /* Now we have the complete path we can work out if this is
4402 actually within this share and adjust newname accordingly. */
4403 DEBUG(10,("msg_file_was_renamed: share mismatch (sharepath %s "
4404 "not sharepath %s) "
4405 "%s from %s -> %s\n",
4406 fsp->conn->connectpath,
4407 sharepath,
4408 fsp_fnum_dbg(fsp),
4409 fsp_str_dbg(fsp),
4410 smb_fname_str_dbg(smb_fname)));
4413 out:
4414 TALLOC_FREE(smb_fname);
4415 return;
4419 * If a main file is opened for delete, all streams need to be checked for
4420 * !FILE_SHARE_DELETE. Do this by opening with DELETE_ACCESS.
4421 * If that works, delete them all by setting the delete on close and close.
4424 static NTSTATUS open_streams_for_delete(connection_struct *conn,
4425 const struct smb_filename *smb_fname)
4427 struct stream_struct *stream_info = NULL;
4428 files_struct **streams = NULL;
4429 int i;
4430 unsigned int num_streams = 0;
4431 TALLOC_CTX *frame = talloc_stackframe();
4432 NTSTATUS status;
4434 status = vfs_streaminfo(conn, NULL, smb_fname, talloc_tos(),
4435 &num_streams, &stream_info);
4437 if (NT_STATUS_EQUAL(status, NT_STATUS_NOT_IMPLEMENTED)
4438 || NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
4439 DEBUG(10, ("no streams around\n"));
4440 TALLOC_FREE(frame);
4441 return NT_STATUS_OK;
4444 if (!NT_STATUS_IS_OK(status)) {
4445 DEBUG(10, ("vfs_streaminfo failed: %s\n",
4446 nt_errstr(status)));
4447 goto fail;
4450 DEBUG(10, ("open_streams_for_delete found %d streams\n",
4451 num_streams));
4453 if (num_streams == 0) {
4454 TALLOC_FREE(frame);
4455 return NT_STATUS_OK;
4458 streams = talloc_array(talloc_tos(), files_struct *, num_streams);
4459 if (streams == NULL) {
4460 DEBUG(0, ("talloc failed\n"));
4461 status = NT_STATUS_NO_MEMORY;
4462 goto fail;
4465 for (i=0; i<num_streams; i++) {
4466 struct smb_filename *smb_fname_cp;
4468 if (strequal(stream_info[i].name, "::$DATA")) {
4469 streams[i] = NULL;
4470 continue;
4473 smb_fname_cp = synthetic_smb_fname(talloc_tos(),
4474 smb_fname->base_name,
4475 stream_info[i].name,
4476 NULL,
4477 (smb_fname->flags &
4478 ~SMB_FILENAME_POSIX_PATH));
4479 if (smb_fname_cp == NULL) {
4480 status = NT_STATUS_NO_MEMORY;
4481 goto fail;
4484 if (SMB_VFS_STAT(conn, smb_fname_cp) == -1) {
4485 DEBUG(10, ("Unable to stat stream: %s\n",
4486 smb_fname_str_dbg(smb_fname_cp)));
4489 status = SMB_VFS_CREATE_FILE(
4490 conn, /* conn */
4491 NULL, /* req */
4492 0, /* root_dir_fid */
4493 smb_fname_cp, /* fname */
4494 DELETE_ACCESS, /* access_mask */
4495 (FILE_SHARE_READ | /* share_access */
4496 FILE_SHARE_WRITE | FILE_SHARE_DELETE),
4497 FILE_OPEN, /* create_disposition*/
4498 0, /* create_options */
4499 FILE_ATTRIBUTE_NORMAL, /* file_attributes */
4500 0, /* oplock_request */
4501 NULL, /* lease */
4502 0, /* allocation_size */
4503 NTCREATEX_OPTIONS_PRIVATE_STREAM_DELETE, /* private_flags */
4504 NULL, /* sd */
4505 NULL, /* ea_list */
4506 &streams[i], /* result */
4507 NULL, /* pinfo */
4508 NULL, NULL); /* create context */
4510 if (!NT_STATUS_IS_OK(status)) {
4511 DEBUG(10, ("Could not open stream %s: %s\n",
4512 smb_fname_str_dbg(smb_fname_cp),
4513 nt_errstr(status)));
4515 TALLOC_FREE(smb_fname_cp);
4516 break;
4518 TALLOC_FREE(smb_fname_cp);
4522 * don't touch the variable "status" beyond this point :-)
4525 for (i -= 1 ; i >= 0; i--) {
4526 if (streams[i] == NULL) {
4527 continue;
4530 DEBUG(10, ("Closing stream # %d, %s\n", i,
4531 fsp_str_dbg(streams[i])));
4532 close_file(NULL, streams[i], NORMAL_CLOSE);
4535 fail:
4536 TALLOC_FREE(frame);
4537 return status;
4540 /*********************************************************************
4541 Create a default ACL by inheriting from the parent. If no inheritance
4542 from the parent available, don't set anything. This will leave the actual
4543 permissions the new file or directory already got from the filesystem
4544 as the NT ACL when read.
4545 *********************************************************************/
4547 static NTSTATUS inherit_new_acl(files_struct *fsp)
4549 TALLOC_CTX *frame = talloc_stackframe();
4550 char *parent_name = NULL;
4551 struct security_descriptor *parent_desc = NULL;
4552 NTSTATUS status = NT_STATUS_OK;
4553 struct security_descriptor *psd = NULL;
4554 const struct dom_sid *owner_sid = NULL;
4555 const struct dom_sid *group_sid = NULL;
4556 uint32_t security_info_sent = (SECINFO_OWNER | SECINFO_GROUP | SECINFO_DACL);
4557 struct security_token *token = fsp->conn->session_info->security_token;
4558 bool inherit_owner =
4559 (lp_inherit_owner(SNUM(fsp->conn)) == INHERIT_OWNER_WINDOWS_AND_UNIX);
4560 bool inheritable_components = false;
4561 bool try_builtin_administrators = false;
4562 const struct dom_sid *BA_U_sid = NULL;
4563 const struct dom_sid *BA_G_sid = NULL;
4564 bool try_system = false;
4565 const struct dom_sid *SY_U_sid = NULL;
4566 const struct dom_sid *SY_G_sid = NULL;
4567 size_t size = 0;
4568 struct smb_filename *parent_smb_fname = NULL;
4570 if (!parent_dirname(frame, fsp->fsp_name->base_name, &parent_name, NULL)) {
4571 TALLOC_FREE(frame);
4572 return NT_STATUS_NO_MEMORY;
4574 parent_smb_fname = synthetic_smb_fname(talloc_tos(),
4575 parent_name,
4576 NULL,
4577 NULL,
4578 fsp->fsp_name->flags);
4580 if (parent_smb_fname == NULL) {
4581 TALLOC_FREE(frame);
4582 return NT_STATUS_NO_MEMORY;
4585 status = SMB_VFS_GET_NT_ACL(fsp->conn,
4586 parent_smb_fname,
4587 (SECINFO_OWNER | SECINFO_GROUP | SECINFO_DACL),
4588 frame,
4589 &parent_desc);
4590 if (!NT_STATUS_IS_OK(status)) {
4591 TALLOC_FREE(frame);
4592 return status;
4595 inheritable_components = sd_has_inheritable_components(parent_desc,
4596 fsp->is_directory);
4598 if (!inheritable_components && !inherit_owner) {
4599 TALLOC_FREE(frame);
4600 /* Nothing to inherit and not setting owner. */
4601 return NT_STATUS_OK;
4604 /* Create an inherited descriptor from the parent. */
4606 if (DEBUGLEVEL >= 10) {
4607 DEBUG(10,("inherit_new_acl: parent acl for %s is:\n",
4608 fsp_str_dbg(fsp) ));
4609 NDR_PRINT_DEBUG(security_descriptor, parent_desc);
4612 /* Inherit from parent descriptor if "inherit owner" set. */
4613 if (inherit_owner) {
4614 owner_sid = parent_desc->owner_sid;
4615 group_sid = parent_desc->group_sid;
4618 if (owner_sid == NULL) {
4619 if (security_token_has_builtin_administrators(token)) {
4620 try_builtin_administrators = true;
4621 } else if (security_token_is_system(token)) {
4622 try_builtin_administrators = true;
4623 try_system = true;
4627 if (group_sid == NULL &&
4628 token->num_sids == PRIMARY_GROUP_SID_INDEX)
4630 if (security_token_is_system(token)) {
4631 try_builtin_administrators = true;
4632 try_system = true;
4636 if (try_builtin_administrators) {
4637 struct unixid ids;
4638 bool ok;
4640 ZERO_STRUCT(ids);
4641 ok = sids_to_unixids(&global_sid_Builtin_Administrators, 1, &ids);
4642 if (ok) {
4643 switch (ids.type) {
4644 case ID_TYPE_BOTH:
4645 BA_U_sid = &global_sid_Builtin_Administrators;
4646 BA_G_sid = &global_sid_Builtin_Administrators;
4647 break;
4648 case ID_TYPE_UID:
4649 BA_U_sid = &global_sid_Builtin_Administrators;
4650 break;
4651 case ID_TYPE_GID:
4652 BA_G_sid = &global_sid_Builtin_Administrators;
4653 break;
4654 default:
4655 break;
4660 if (try_system) {
4661 struct unixid ids;
4662 bool ok;
4664 ZERO_STRUCT(ids);
4665 ok = sids_to_unixids(&global_sid_System, 1, &ids);
4666 if (ok) {
4667 switch (ids.type) {
4668 case ID_TYPE_BOTH:
4669 SY_U_sid = &global_sid_System;
4670 SY_G_sid = &global_sid_System;
4671 break;
4672 case ID_TYPE_UID:
4673 SY_U_sid = &global_sid_System;
4674 break;
4675 case ID_TYPE_GID:
4676 SY_G_sid = &global_sid_System;
4677 break;
4678 default:
4679 break;
4684 if (owner_sid == NULL) {
4685 owner_sid = BA_U_sid;
4688 if (owner_sid == NULL) {
4689 owner_sid = SY_U_sid;
4692 if (group_sid == NULL) {
4693 group_sid = SY_G_sid;
4696 if (try_system && group_sid == NULL) {
4697 group_sid = BA_G_sid;
4700 if (owner_sid == NULL) {
4701 owner_sid = &token->sids[PRIMARY_USER_SID_INDEX];
4703 if (group_sid == NULL) {
4704 if (token->num_sids == PRIMARY_GROUP_SID_INDEX) {
4705 group_sid = &token->sids[PRIMARY_USER_SID_INDEX];
4706 } else {
4707 group_sid = &token->sids[PRIMARY_GROUP_SID_INDEX];
4711 status = se_create_child_secdesc(frame,
4712 &psd,
4713 &size,
4714 parent_desc,
4715 owner_sid,
4716 group_sid,
4717 fsp->is_directory);
4718 if (!NT_STATUS_IS_OK(status)) {
4719 TALLOC_FREE(frame);
4720 return status;
4723 /* If inheritable_components == false,
4724 se_create_child_secdesc()
4725 creates a security desriptor with a NULL dacl
4726 entry, but with SEC_DESC_DACL_PRESENT. We need
4727 to remove that flag. */
4729 if (!inheritable_components) {
4730 security_info_sent &= ~SECINFO_DACL;
4731 psd->type &= ~SEC_DESC_DACL_PRESENT;
4734 if (DEBUGLEVEL >= 10) {
4735 DEBUG(10,("inherit_new_acl: child acl for %s is:\n",
4736 fsp_str_dbg(fsp) ));
4737 NDR_PRINT_DEBUG(security_descriptor, psd);
4740 if (inherit_owner) {
4741 /* We need to be root to force this. */
4742 become_root();
4744 status = SMB_VFS_FSET_NT_ACL(fsp,
4745 security_info_sent,
4746 psd);
4747 if (inherit_owner) {
4748 unbecome_root();
4750 TALLOC_FREE(frame);
4751 return status;
4755 * If we already have a lease, it must match the new file id. [MS-SMB2]
4756 * 3.3.5.9.8 speaks about INVALID_PARAMETER if an already used lease key is
4757 * used for a different file name.
4760 struct lease_match_state {
4761 /* Input parameters. */
4762 TALLOC_CTX *mem_ctx;
4763 const char *servicepath;
4764 const struct smb_filename *fname;
4765 bool file_existed;
4766 struct file_id id;
4767 /* Return parameters. */
4768 uint32_t num_file_ids;
4769 struct file_id *ids;
4770 NTSTATUS match_status;
4773 /*************************************************************
4774 File doesn't exist but this lease key+guid is already in use.
4776 This is only allowable in the dynamic share case where the
4777 service path must be different.
4779 There is a small race condition here in the multi-connection
4780 case where a client sends two create calls on different connections,
4781 where the file doesn't exist and one smbd creates the leases_db
4782 entry first, but this will get fixed by the multichannel cleanup
4783 when all identical client_guids get handled by a single smbd.
4784 **************************************************************/
4786 static void lease_match_parser_new_file(
4787 uint32_t num_files,
4788 const struct leases_db_file *files,
4789 struct lease_match_state *state)
4791 uint32_t i;
4793 for (i = 0; i < num_files; i++) {
4794 const struct leases_db_file *f = &files[i];
4795 if (strequal(state->servicepath, f->servicepath)) {
4796 state->match_status = NT_STATUS_INVALID_PARAMETER;
4797 return;
4801 /* Dynamic share case. Break leases on all other files. */
4802 state->match_status = leases_db_copy_file_ids(state->mem_ctx,
4803 num_files,
4804 files,
4805 &state->ids);
4806 if (!NT_STATUS_IS_OK(state->match_status)) {
4807 return;
4810 state->num_file_ids = num_files;
4811 state->match_status = NT_STATUS_OPLOCK_NOT_GRANTED;
4812 return;
4815 static void lease_match_parser(
4816 uint32_t num_files,
4817 const struct leases_db_file *files,
4818 void *private_data)
4820 struct lease_match_state *state =
4821 (struct lease_match_state *)private_data;
4822 uint32_t i;
4824 if (!state->file_existed) {
4826 * Deal with name mismatch or
4827 * possible dynamic share case separately
4828 * to make code clearer.
4830 lease_match_parser_new_file(num_files,
4831 files,
4832 state);
4833 return;
4836 /* File existed. */
4837 state->match_status = NT_STATUS_OK;
4839 for (i = 0; i < num_files; i++) {
4840 const struct leases_db_file *f = &files[i];
4842 /* Everything should be the same. */
4843 if (!file_id_equal(&state->id, &f->id)) {
4844 /* This should catch all dynamic share cases. */
4845 state->match_status = NT_STATUS_OPLOCK_NOT_GRANTED;
4846 break;
4848 if (!strequal(f->servicepath, state->servicepath)) {
4849 state->match_status = NT_STATUS_INVALID_PARAMETER;
4850 break;
4852 if (!strequal(f->base_name, state->fname->base_name)) {
4853 state->match_status = NT_STATUS_INVALID_PARAMETER;
4854 break;
4856 if (!strequal(f->stream_name, state->fname->stream_name)) {
4857 state->match_status = NT_STATUS_INVALID_PARAMETER;
4858 break;
4862 if (NT_STATUS_IS_OK(state->match_status)) {
4864 * Common case - just opening another handle on a
4865 * file on a non-dynamic share.
4867 return;
4870 if (NT_STATUS_EQUAL(state->match_status, NT_STATUS_INVALID_PARAMETER)) {
4871 /* Mismatched path. Error back to client. */
4872 return;
4876 * File id mismatch. Dynamic share case NT_STATUS_OPLOCK_NOT_GRANTED.
4877 * Don't allow leases.
4880 state->match_status = leases_db_copy_file_ids(state->mem_ctx,
4881 num_files,
4882 files,
4883 &state->ids);
4884 if (!NT_STATUS_IS_OK(state->match_status)) {
4885 return;
4888 state->num_file_ids = num_files;
4889 state->match_status = NT_STATUS_OPLOCK_NOT_GRANTED;
4890 return;
4893 static NTSTATUS lease_match(connection_struct *conn,
4894 struct smb_request *req,
4895 struct smb2_lease_key *lease_key,
4896 const char *servicepath,
4897 const struct smb_filename *fname,
4898 uint16_t *p_version,
4899 uint16_t *p_epoch)
4901 struct smbd_server_connection *sconn = req->sconn;
4902 TALLOC_CTX *tos = talloc_tos();
4903 struct lease_match_state state = {
4904 .mem_ctx = tos,
4905 .servicepath = servicepath,
4906 .fname = fname,
4907 .match_status = NT_STATUS_OK
4909 uint32_t i;
4910 NTSTATUS status;
4912 state.file_existed = VALID_STAT(fname->st);
4913 if (state.file_existed) {
4914 state.id = vfs_file_id_from_sbuf(conn, &fname->st);
4915 } else {
4916 memset(&state.id, '\0', sizeof(state.id));
4919 status = leases_db_parse(&sconn->client->connections->smb2.client.guid,
4920 lease_key, lease_match_parser, &state);
4921 if (!NT_STATUS_IS_OK(status)) {
4923 * Not found or error means okay: We can make the lease pass
4925 return NT_STATUS_OK;
4927 if (!NT_STATUS_EQUAL(state.match_status, NT_STATUS_OPLOCK_NOT_GRANTED)) {
4929 * Anything but NT_STATUS_OPLOCK_NOT_GRANTED, let the caller
4930 * deal with it.
4932 return state.match_status;
4935 /* We have to break all existing leases. */
4936 for (i = 0; i < state.num_file_ids; i++) {
4937 struct share_mode_lock *lck;
4938 struct share_mode_data *d;
4939 uint32_t j;
4941 if (file_id_equal(&state.ids[i], &state.id)) {
4942 /* Don't need to break our own file. */
4943 continue;
4946 lck = get_existing_share_mode_lock(talloc_tos(), state.ids[i]);
4947 if (lck == NULL) {
4948 /* Race condition - file already closed. */
4949 continue;
4951 d = lck->data;
4952 for (j=0; j<d->num_share_modes; j++) {
4953 struct share_mode_entry *e = &d->share_modes[j];
4954 uint32_t e_lease_type = get_lease_type(d, e);
4955 struct share_mode_lease *l = NULL;
4957 if (share_mode_stale_pid(d, j)) {
4958 continue;
4961 if (e->op_type == LEASE_OPLOCK) {
4962 l = &lck->data->leases[e->lease_idx];
4963 if (!smb2_lease_key_equal(&l->lease_key,
4964 lease_key)) {
4965 continue;
4967 *p_epoch = l->epoch;
4968 *p_version = l->lease_version;
4971 if (e_lease_type == SMB2_LEASE_NONE) {
4972 continue;
4975 send_break_message(conn->sconn->msg_ctx, e,
4976 SMB2_LEASE_NONE);
4979 * Windows 7 and 8 lease clients
4980 * are broken in that they will not
4981 * respond to lease break requests
4982 * whilst waiting for an outstanding
4983 * open request on that lease handle
4984 * on the same TCP connection, due
4985 * to holding an internal inode lock.
4987 * This means we can't reschedule
4988 * ourselves here, but must return
4989 * from the create.
4991 * Work around:
4993 * Send the breaks and then return
4994 * SMB2_LEASE_NONE in the lease handle
4995 * to cause them to acknowledge the
4996 * lease break. Consulatation with
4997 * Microsoft engineering confirmed
4998 * this approach is safe.
5002 TALLOC_FREE(lck);
5005 * Ensure we don't grant anything more so we
5006 * never upgrade.
5008 return NT_STATUS_OPLOCK_NOT_GRANTED;
5012 * Wrapper around open_file_ntcreate and open_directory
5015 static NTSTATUS create_file_unixpath(connection_struct *conn,
5016 struct smb_request *req,
5017 struct smb_filename *smb_fname,
5018 uint32_t access_mask,
5019 uint32_t share_access,
5020 uint32_t create_disposition,
5021 uint32_t create_options,
5022 uint32_t file_attributes,
5023 uint32_t oplock_request,
5024 struct smb2_lease *lease,
5025 uint64_t allocation_size,
5026 uint32_t private_flags,
5027 struct security_descriptor *sd,
5028 struct ea_list *ea_list,
5030 files_struct **result,
5031 int *pinfo)
5033 int info = FILE_WAS_OPENED;
5034 files_struct *base_fsp = NULL;
5035 files_struct *fsp = NULL;
5036 NTSTATUS status;
5038 DEBUG(10,("create_file_unixpath: access_mask = 0x%x "
5039 "file_attributes = 0x%x, share_access = 0x%x, "
5040 "create_disposition = 0x%x create_options = 0x%x "
5041 "oplock_request = 0x%x private_flags = 0x%x "
5042 "ea_list = 0x%p, sd = 0x%p, "
5043 "fname = %s\n",
5044 (unsigned int)access_mask,
5045 (unsigned int)file_attributes,
5046 (unsigned int)share_access,
5047 (unsigned int)create_disposition,
5048 (unsigned int)create_options,
5049 (unsigned int)oplock_request,
5050 (unsigned int)private_flags,
5051 ea_list, sd, smb_fname_str_dbg(smb_fname)));
5053 if (create_options & FILE_OPEN_BY_FILE_ID) {
5054 status = NT_STATUS_NOT_SUPPORTED;
5055 goto fail;
5058 if (create_options & NTCREATEX_OPTIONS_INVALID_PARAM_MASK) {
5059 status = NT_STATUS_INVALID_PARAMETER;
5060 goto fail;
5063 if (req == NULL) {
5064 oplock_request |= INTERNAL_OPEN_ONLY;
5067 if (lease != NULL) {
5068 uint16_t epoch = lease->lease_epoch;
5069 uint16_t version = lease->lease_version;
5070 status = lease_match(conn,
5071 req,
5072 &lease->lease_key,
5073 conn->connectpath,
5074 smb_fname,
5075 &version,
5076 &epoch);
5077 if (NT_STATUS_EQUAL(status, NT_STATUS_OPLOCK_NOT_GRANTED)) {
5078 /* Dynamic share file. No leases and update epoch... */
5079 lease->lease_state = SMB2_LEASE_NONE;
5080 lease->lease_epoch = epoch;
5081 lease->lease_version = version;
5082 } else if (!NT_STATUS_IS_OK(status)) {
5083 goto fail;
5087 if ((conn->fs_capabilities & FILE_NAMED_STREAMS)
5088 && (access_mask & DELETE_ACCESS)
5089 && !is_ntfs_stream_smb_fname(smb_fname)) {
5091 * We can't open a file with DELETE access if any of the
5092 * streams is open without FILE_SHARE_DELETE
5094 status = open_streams_for_delete(conn, smb_fname);
5096 if (!NT_STATUS_IS_OK(status)) {
5097 goto fail;
5101 if ((access_mask & SEC_FLAG_SYSTEM_SECURITY) &&
5102 !security_token_has_privilege(get_current_nttok(conn),
5103 SEC_PRIV_SECURITY)) {
5104 DEBUG(10, ("create_file_unixpath: open on %s "
5105 "failed - SEC_FLAG_SYSTEM_SECURITY denied.\n",
5106 smb_fname_str_dbg(smb_fname)));
5107 status = NT_STATUS_PRIVILEGE_NOT_HELD;
5108 goto fail;
5111 if ((conn->fs_capabilities & FILE_NAMED_STREAMS)
5112 && is_ntfs_stream_smb_fname(smb_fname)
5113 && (!(private_flags & NTCREATEX_OPTIONS_PRIVATE_STREAM_DELETE))) {
5114 uint32_t base_create_disposition;
5115 struct smb_filename *smb_fname_base = NULL;
5117 if (create_options & FILE_DIRECTORY_FILE) {
5118 status = NT_STATUS_NOT_A_DIRECTORY;
5119 goto fail;
5122 switch (create_disposition) {
5123 case FILE_OPEN:
5124 base_create_disposition = FILE_OPEN;
5125 break;
5126 default:
5127 base_create_disposition = FILE_OPEN_IF;
5128 break;
5131 /* Create an smb_filename with stream_name == NULL. */
5132 smb_fname_base = synthetic_smb_fname(talloc_tos(),
5133 smb_fname->base_name,
5134 NULL,
5135 NULL,
5136 smb_fname->flags);
5137 if (smb_fname_base == NULL) {
5138 status = NT_STATUS_NO_MEMORY;
5139 goto fail;
5142 if (SMB_VFS_STAT(conn, smb_fname_base) == -1) {
5143 DEBUG(10, ("Unable to stat stream: %s\n",
5144 smb_fname_str_dbg(smb_fname_base)));
5145 } else {
5147 * https://bugzilla.samba.org/show_bug.cgi?id=10229
5148 * We need to check if the requested access mask
5149 * could be used to open the underlying file (if
5150 * it existed), as we're passing in zero for the
5151 * access mask to the base filename.
5153 status = check_base_file_access(conn,
5154 smb_fname_base,
5155 access_mask);
5157 if (!NT_STATUS_IS_OK(status)) {
5158 DEBUG(10, ("Permission check "
5159 "for base %s failed: "
5160 "%s\n", smb_fname->base_name,
5161 nt_errstr(status)));
5162 goto fail;
5166 /* Open the base file. */
5167 status = create_file_unixpath(conn, NULL, smb_fname_base, 0,
5168 FILE_SHARE_READ
5169 | FILE_SHARE_WRITE
5170 | FILE_SHARE_DELETE,
5171 base_create_disposition,
5172 0, 0, 0, NULL, 0, 0, NULL, NULL,
5173 &base_fsp, NULL);
5174 TALLOC_FREE(smb_fname_base);
5176 if (!NT_STATUS_IS_OK(status)) {
5177 DEBUG(10, ("create_file_unixpath for base %s failed: "
5178 "%s\n", smb_fname->base_name,
5179 nt_errstr(status)));
5180 goto fail;
5182 /* we don't need the low level fd */
5183 fd_close(base_fsp);
5187 * If it's a request for a directory open, deal with it separately.
5190 if (create_options & FILE_DIRECTORY_FILE) {
5192 if (create_options & FILE_NON_DIRECTORY_FILE) {
5193 status = NT_STATUS_INVALID_PARAMETER;
5194 goto fail;
5197 /* Can't open a temp directory. IFS kit test. */
5198 if (!(file_attributes & FILE_FLAG_POSIX_SEMANTICS) &&
5199 (file_attributes & FILE_ATTRIBUTE_TEMPORARY)) {
5200 status = NT_STATUS_INVALID_PARAMETER;
5201 goto fail;
5205 * We will get a create directory here if the Win32
5206 * app specified a security descriptor in the
5207 * CreateDirectory() call.
5210 oplock_request = 0;
5211 status = open_directory(
5212 conn, req, smb_fname, access_mask, share_access,
5213 create_disposition, create_options, file_attributes,
5214 &info, &fsp);
5215 } else {
5218 * Ordinary file case.
5221 status = file_new(req, conn, &fsp);
5222 if(!NT_STATUS_IS_OK(status)) {
5223 goto fail;
5226 status = fsp_set_smb_fname(fsp, smb_fname);
5227 if (!NT_STATUS_IS_OK(status)) {
5228 goto fail;
5231 if (base_fsp) {
5233 * We're opening the stream element of a
5234 * base_fsp we already opened. Set up the
5235 * base_fsp pointer.
5237 fsp->base_fsp = base_fsp;
5240 if (allocation_size) {
5241 fsp->initial_allocation_size = smb_roundup(fsp->conn,
5242 allocation_size);
5245 status = open_file_ntcreate(conn,
5246 req,
5247 access_mask,
5248 share_access,
5249 create_disposition,
5250 create_options,
5251 file_attributes,
5252 oplock_request,
5253 lease,
5254 private_flags,
5255 &info,
5256 fsp);
5258 if(!NT_STATUS_IS_OK(status)) {
5259 file_free(req, fsp);
5260 fsp = NULL;
5263 if (NT_STATUS_EQUAL(status, NT_STATUS_FILE_IS_A_DIRECTORY)) {
5265 /* A stream open never opens a directory */
5267 if (base_fsp) {
5268 status = NT_STATUS_FILE_IS_A_DIRECTORY;
5269 goto fail;
5273 * Fail the open if it was explicitly a non-directory
5274 * file.
5277 if (create_options & FILE_NON_DIRECTORY_FILE) {
5278 status = NT_STATUS_FILE_IS_A_DIRECTORY;
5279 goto fail;
5282 oplock_request = 0;
5283 status = open_directory(
5284 conn, req, smb_fname, access_mask,
5285 share_access, create_disposition,
5286 create_options, file_attributes,
5287 &info, &fsp);
5291 if (!NT_STATUS_IS_OK(status)) {
5292 goto fail;
5295 fsp->base_fsp = base_fsp;
5297 if ((ea_list != NULL) &&
5298 ((info == FILE_WAS_CREATED) || (info == FILE_WAS_OVERWRITTEN))) {
5299 status = set_ea(conn, fsp, fsp->fsp_name, ea_list);
5300 if (!NT_STATUS_IS_OK(status)) {
5301 goto fail;
5305 if (!fsp->is_directory && S_ISDIR(fsp->fsp_name->st.st_ex_mode)) {
5306 status = NT_STATUS_ACCESS_DENIED;
5307 goto fail;
5310 /* Save the requested allocation size. */
5311 if ((info == FILE_WAS_CREATED) || (info == FILE_WAS_OVERWRITTEN)) {
5312 if ((allocation_size > fsp->fsp_name->st.st_ex_size)
5313 && !(fsp->is_directory))
5315 fsp->initial_allocation_size = smb_roundup(
5316 fsp->conn, allocation_size);
5317 if (vfs_allocate_file_space(
5318 fsp, fsp->initial_allocation_size) == -1) {
5319 status = NT_STATUS_DISK_FULL;
5320 goto fail;
5322 } else {
5323 fsp->initial_allocation_size = smb_roundup(
5324 fsp->conn, (uint64_t)fsp->fsp_name->st.st_ex_size);
5326 } else {
5327 fsp->initial_allocation_size = 0;
5330 if ((info == FILE_WAS_CREATED) && lp_nt_acl_support(SNUM(conn)) &&
5331 fsp->base_fsp == NULL) {
5332 if (sd != NULL) {
5334 * According to the MS documentation, the only time the security
5335 * descriptor is applied to the opened file is iff we *created* the
5336 * file; an existing file stays the same.
5338 * Also, it seems (from observation) that you can open the file with
5339 * any access mask but you can still write the sd. We need to override
5340 * the granted access before we call set_sd
5341 * Patch for bug #2242 from Tom Lackemann <cessnatomny@yahoo.com>.
5344 uint32_t sec_info_sent;
5345 uint32_t saved_access_mask = fsp->access_mask;
5347 sec_info_sent = get_sec_info(sd);
5349 fsp->access_mask = FILE_GENERIC_ALL;
5351 if (sec_info_sent & (SECINFO_OWNER|
5352 SECINFO_GROUP|
5353 SECINFO_DACL|
5354 SECINFO_SACL)) {
5355 status = set_sd(fsp, sd, sec_info_sent);
5358 fsp->access_mask = saved_access_mask;
5360 if (!NT_STATUS_IS_OK(status)) {
5361 goto fail;
5363 } else if (lp_inherit_acls(SNUM(conn))) {
5364 /* Inherit from parent. Errors here are not fatal. */
5365 status = inherit_new_acl(fsp);
5366 if (!NT_STATUS_IS_OK(status)) {
5367 DEBUG(10,("inherit_new_acl: failed for %s with %s\n",
5368 fsp_str_dbg(fsp),
5369 nt_errstr(status) ));
5374 if ((conn->fs_capabilities & FILE_FILE_COMPRESSION)
5375 && (create_options & FILE_NO_COMPRESSION)
5376 && (info == FILE_WAS_CREATED)) {
5377 status = SMB_VFS_SET_COMPRESSION(conn, fsp, fsp,
5378 COMPRESSION_FORMAT_NONE);
5379 if (!NT_STATUS_IS_OK(status)) {
5380 DEBUG(1, ("failed to disable compression: %s\n",
5381 nt_errstr(status)));
5385 DEBUG(10, ("create_file_unixpath: info=%d\n", info));
5387 *result = fsp;
5388 if (pinfo != NULL) {
5389 *pinfo = info;
5392 smb_fname->st = fsp->fsp_name->st;
5394 return NT_STATUS_OK;
5396 fail:
5397 DEBUG(10, ("create_file_unixpath: %s\n", nt_errstr(status)));
5399 if (fsp != NULL) {
5400 if (base_fsp && fsp->base_fsp == base_fsp) {
5402 * The close_file below will close
5403 * fsp->base_fsp.
5405 base_fsp = NULL;
5407 close_file(req, fsp, ERROR_CLOSE);
5408 fsp = NULL;
5410 if (base_fsp != NULL) {
5411 close_file(req, base_fsp, ERROR_CLOSE);
5412 base_fsp = NULL;
5414 return status;
5418 * Calculate the full path name given a relative fid.
5420 NTSTATUS get_relative_fid_filename(connection_struct *conn,
5421 struct smb_request *req,
5422 uint16_t root_dir_fid,
5423 const struct smb_filename *smb_fname,
5424 struct smb_filename **smb_fname_out)
5426 files_struct *dir_fsp;
5427 char *parent_fname = NULL;
5428 char *new_base_name = NULL;
5429 uint32_t ucf_flags = ucf_flags_from_smb_request(req);
5430 NTSTATUS status;
5432 if (root_dir_fid == 0 || !smb_fname) {
5433 status = NT_STATUS_INTERNAL_ERROR;
5434 goto out;
5437 dir_fsp = file_fsp(req, root_dir_fid);
5439 if (dir_fsp == NULL) {
5440 status = NT_STATUS_INVALID_HANDLE;
5441 goto out;
5444 if (is_ntfs_stream_smb_fname(dir_fsp->fsp_name)) {
5445 status = NT_STATUS_INVALID_HANDLE;
5446 goto out;
5449 if (!dir_fsp->is_directory) {
5452 * Check to see if this is a mac fork of some kind.
5455 if ((conn->fs_capabilities & FILE_NAMED_STREAMS) &&
5456 is_ntfs_stream_smb_fname(smb_fname)) {
5457 status = NT_STATUS_OBJECT_PATH_NOT_FOUND;
5458 goto out;
5462 we need to handle the case when we get a
5463 relative open relative to a file and the
5464 pathname is blank - this is a reopen!
5465 (hint from demyn plantenberg)
5468 status = NT_STATUS_INVALID_HANDLE;
5469 goto out;
5472 if (ISDOT(dir_fsp->fsp_name->base_name)) {
5474 * We're at the toplevel dir, the final file name
5475 * must not contain ./, as this is filtered out
5476 * normally by srvstr_get_path and unix_convert
5477 * explicitly rejects paths containing ./.
5479 parent_fname = talloc_strdup(talloc_tos(), "");
5480 if (parent_fname == NULL) {
5481 status = NT_STATUS_NO_MEMORY;
5482 goto out;
5484 } else {
5485 size_t dir_name_len = strlen(dir_fsp->fsp_name->base_name);
5488 * Copy in the base directory name.
5491 parent_fname = talloc_array(talloc_tos(), char,
5492 dir_name_len+2);
5493 if (parent_fname == NULL) {
5494 status = NT_STATUS_NO_MEMORY;
5495 goto out;
5497 memcpy(parent_fname, dir_fsp->fsp_name->base_name,
5498 dir_name_len+1);
5501 * Ensure it ends in a '/'.
5502 * We used TALLOC_SIZE +2 to add space for the '/'.
5505 if(dir_name_len
5506 && (parent_fname[dir_name_len-1] != '\\')
5507 && (parent_fname[dir_name_len-1] != '/')) {
5508 parent_fname[dir_name_len] = '/';
5509 parent_fname[dir_name_len+1] = '\0';
5513 new_base_name = talloc_asprintf(talloc_tos(), "%s%s", parent_fname,
5514 smb_fname->base_name);
5515 if (new_base_name == NULL) {
5516 status = NT_STATUS_NO_MEMORY;
5517 goto out;
5520 status = filename_convert(req,
5521 conn,
5522 new_base_name,
5523 ucf_flags,
5524 NULL,
5525 smb_fname_out);
5526 if (!NT_STATUS_IS_OK(status)) {
5527 goto out;
5530 out:
5531 TALLOC_FREE(parent_fname);
5532 TALLOC_FREE(new_base_name);
5533 return status;
5536 NTSTATUS create_file_default(connection_struct *conn,
5537 struct smb_request *req,
5538 uint16_t root_dir_fid,
5539 struct smb_filename *smb_fname,
5540 uint32_t access_mask,
5541 uint32_t share_access,
5542 uint32_t create_disposition,
5543 uint32_t create_options,
5544 uint32_t file_attributes,
5545 uint32_t oplock_request,
5546 struct smb2_lease *lease,
5547 uint64_t allocation_size,
5548 uint32_t private_flags,
5549 struct security_descriptor *sd,
5550 struct ea_list *ea_list,
5551 files_struct **result,
5552 int *pinfo,
5553 const struct smb2_create_blobs *in_context_blobs,
5554 struct smb2_create_blobs *out_context_blobs)
5556 int info = FILE_WAS_OPENED;
5557 files_struct *fsp = NULL;
5558 NTSTATUS status;
5559 bool stream_name = false;
5561 DEBUG(10,("create_file: access_mask = 0x%x "
5562 "file_attributes = 0x%x, share_access = 0x%x, "
5563 "create_disposition = 0x%x create_options = 0x%x "
5564 "oplock_request = 0x%x "
5565 "private_flags = 0x%x "
5566 "root_dir_fid = 0x%x, ea_list = 0x%p, sd = 0x%p, "
5567 "fname = %s\n",
5568 (unsigned int)access_mask,
5569 (unsigned int)file_attributes,
5570 (unsigned int)share_access,
5571 (unsigned int)create_disposition,
5572 (unsigned int)create_options,
5573 (unsigned int)oplock_request,
5574 (unsigned int)private_flags,
5575 (unsigned int)root_dir_fid,
5576 ea_list, sd, smb_fname_str_dbg(smb_fname)));
5579 * Calculate the filename from the root_dir_if if necessary.
5582 if (root_dir_fid != 0) {
5583 struct smb_filename *smb_fname_out = NULL;
5584 status = get_relative_fid_filename(conn, req, root_dir_fid,
5585 smb_fname, &smb_fname_out);
5586 if (!NT_STATUS_IS_OK(status)) {
5587 goto fail;
5589 smb_fname = smb_fname_out;
5593 * Check to see if this is a mac fork of some kind.
5596 stream_name = is_ntfs_stream_smb_fname(smb_fname);
5597 if (stream_name) {
5598 enum FAKE_FILE_TYPE fake_file_type;
5600 fake_file_type = is_fake_file(smb_fname);
5602 if (fake_file_type != FAKE_FILE_TYPE_NONE) {
5605 * Here we go! support for changing the disk quotas
5606 * --metze
5608 * We need to fake up to open this MAGIC QUOTA file
5609 * and return a valid FID.
5611 * w2k close this file directly after openening xp
5612 * also tries a QUERY_FILE_INFO on the file and then
5613 * close it
5615 status = open_fake_file(req, conn, req->vuid,
5616 fake_file_type, smb_fname,
5617 access_mask, &fsp);
5618 if (!NT_STATUS_IS_OK(status)) {
5619 goto fail;
5622 ZERO_STRUCT(smb_fname->st);
5623 goto done;
5626 if (!(conn->fs_capabilities & FILE_NAMED_STREAMS)) {
5627 status = NT_STATUS_OBJECT_NAME_NOT_FOUND;
5628 goto fail;
5632 if (is_ntfs_default_stream_smb_fname(smb_fname)) {
5633 int ret;
5634 smb_fname->stream_name = NULL;
5635 /* We have to handle this error here. */
5636 if (create_options & FILE_DIRECTORY_FILE) {
5637 status = NT_STATUS_NOT_A_DIRECTORY;
5638 goto fail;
5640 if (req != NULL && req->posix_pathnames) {
5641 ret = SMB_VFS_LSTAT(conn, smb_fname);
5642 } else {
5643 ret = SMB_VFS_STAT(conn, smb_fname);
5646 if (ret == 0 && VALID_STAT_OF_DIR(smb_fname->st)) {
5647 status = NT_STATUS_FILE_IS_A_DIRECTORY;
5648 goto fail;
5652 status = create_file_unixpath(
5653 conn, req, smb_fname, access_mask, share_access,
5654 create_disposition, create_options, file_attributes,
5655 oplock_request, lease, allocation_size, private_flags,
5656 sd, ea_list,
5657 &fsp, &info);
5659 if (!NT_STATUS_IS_OK(status)) {
5660 goto fail;
5663 done:
5664 DEBUG(10, ("create_file: info=%d\n", info));
5666 *result = fsp;
5667 if (pinfo != NULL) {
5668 *pinfo = info;
5670 return NT_STATUS_OK;
5672 fail:
5673 DEBUG(10, ("create_file: %s\n", nt_errstr(status)));
5675 if (fsp != NULL) {
5676 close_file(req, fsp, ERROR_CLOSE);
5677 fsp = NULL;
5679 return status;