s3/smbd: fix schedule_async_open() timer
[Samba.git] / source3 / smbd / open.c
blobe76395d54e31edede44f03d2dee42c16e6c4bcfe
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
8 This program is free software; you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation; either version 3 of the License, or
11 (at your option) any later version.
13 This program is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with this program. If not, see <http://www.gnu.org/licenses/>.
22 #include "includes.h"
23 #include "system/filesys.h"
24 #include "printing.h"
25 #include "smbd/smbd.h"
26 #include "smbd/globals.h"
27 #include "fake_file.h"
28 #include "../libcli/security/security.h"
29 #include "../librpc/gen_ndr/ndr_security.h"
30 #include "../librpc/gen_ndr/open_files.h"
31 #include "../librpc/gen_ndr/idmap.h"
32 #include "../librpc/gen_ndr/ioctl.h"
33 #include "passdb/lookup_sid.h"
34 #include "auth.h"
35 #include "serverid.h"
36 #include "messages.h"
37 #include "source3/lib/dbwrap/dbwrap_watch.h"
38 #include "locking/leases_db.h"
39 #include "librpc/gen_ndr/ndr_leases_db.h"
41 extern const struct generic_mapping file_generic_mapping;
43 struct deferred_open_record {
44 bool delayed_for_oplocks;
45 bool async_open;
46 struct file_id id;
49 * Timer for async opens, needed because they don't use a watch on
50 * a locking.tdb record. This is currently only used for real async
51 * opens and just terminates smbd if the async open times out.
53 struct tevent_timer *te;
56 /****************************************************************************
57 If the requester wanted DELETE_ACCESS and was rejected because
58 the file ACL didn't include DELETE_ACCESS, see if the parent ACL
59 overrides this.
60 ****************************************************************************/
62 static bool parent_override_delete(connection_struct *conn,
63 const struct smb_filename *smb_fname,
64 uint32_t access_mask,
65 uint32_t rejected_mask)
67 if ((access_mask & DELETE_ACCESS) &&
68 (rejected_mask & DELETE_ACCESS) &&
69 can_delete_file_in_directory(conn, smb_fname)) {
70 return true;
72 return false;
75 /****************************************************************************
76 Check if we have open rights.
77 ****************************************************************************/
79 NTSTATUS smbd_check_access_rights(struct connection_struct *conn,
80 const struct smb_filename *smb_fname,
81 bool use_privs,
82 uint32_t access_mask)
84 /* Check if we have rights to open. */
85 NTSTATUS status;
86 struct security_descriptor *sd = NULL;
87 uint32_t rejected_share_access;
88 uint32_t rejected_mask = access_mask;
89 uint32_t do_not_check_mask = 0;
91 rejected_share_access = access_mask & ~(conn->share_access);
93 if (rejected_share_access) {
94 DEBUG(10, ("smbd_check_access_rights: rejected share access 0x%x "
95 "on %s (0x%x)\n",
96 (unsigned int)access_mask,
97 smb_fname_str_dbg(smb_fname),
98 (unsigned int)rejected_share_access ));
99 return NT_STATUS_ACCESS_DENIED;
102 if (!use_privs && get_current_uid(conn) == (uid_t)0) {
103 /* I'm sorry sir, I didn't know you were root... */
104 DEBUG(10,("smbd_check_access_rights: root override "
105 "on %s. Granting 0x%x\n",
106 smb_fname_str_dbg(smb_fname),
107 (unsigned int)access_mask ));
108 return NT_STATUS_OK;
111 if ((access_mask & DELETE_ACCESS) && !lp_acl_check_permissions(SNUM(conn))) {
112 DEBUG(10,("smbd_check_access_rights: not checking ACL "
113 "on DELETE_ACCESS on file %s. Granting 0x%x\n",
114 smb_fname_str_dbg(smb_fname),
115 (unsigned int)access_mask ));
116 return NT_STATUS_OK;
119 if (access_mask == DELETE_ACCESS &&
120 VALID_STAT(smb_fname->st) &&
121 S_ISLNK(smb_fname->st.st_ex_mode)) {
122 /* We can always delete a symlink. */
123 DEBUG(10,("smbd_check_access_rights: not checking ACL "
124 "on DELETE_ACCESS on symlink %s.\n",
125 smb_fname_str_dbg(smb_fname) ));
126 return NT_STATUS_OK;
129 status = SMB_VFS_GET_NT_ACL(conn, smb_fname->base_name,
130 (SECINFO_OWNER |
131 SECINFO_GROUP |
132 SECINFO_DACL), talloc_tos(), &sd);
134 if (!NT_STATUS_IS_OK(status)) {
135 DEBUG(10, ("smbd_check_access_rights: Could not get acl "
136 "on %s: %s\n",
137 smb_fname_str_dbg(smb_fname),
138 nt_errstr(status)));
140 if (NT_STATUS_EQUAL(status, NT_STATUS_ACCESS_DENIED)) {
141 goto access_denied;
144 return status;
148 * If we can access the path to this file, by
149 * default we have FILE_READ_ATTRIBUTES from the
150 * containing directory. See the section:
151 * "Algorithm to Check Access to an Existing File"
152 * in MS-FSA.pdf.
154 * se_file_access_check() also takes care of
155 * owner WRITE_DAC and READ_CONTROL.
157 do_not_check_mask = FILE_READ_ATTRIBUTES;
160 * Samba 3.6 and earlier granted execute access even
161 * if the ACL did not contain execute rights.
162 * Samba 4.0 is more correct and checks it.
163 * The compatibilty mode allows one to skip this check
164 * to smoothen upgrades.
166 if (lp_acl_allow_execute_always(SNUM(conn))) {
167 do_not_check_mask |= FILE_EXECUTE;
170 status = se_file_access_check(sd,
171 get_current_nttok(conn),
172 use_privs,
173 (access_mask & ~do_not_check_mask),
174 &rejected_mask);
176 DEBUG(10,("smbd_check_access_rights: file %s requesting "
177 "0x%x returning 0x%x (%s)\n",
178 smb_fname_str_dbg(smb_fname),
179 (unsigned int)access_mask,
180 (unsigned int)rejected_mask,
181 nt_errstr(status) ));
183 if (!NT_STATUS_IS_OK(status)) {
184 if (DEBUGLEVEL >= 10) {
185 DEBUG(10,("smbd_check_access_rights: acl for %s is:\n",
186 smb_fname_str_dbg(smb_fname) ));
187 NDR_PRINT_DEBUG(security_descriptor, sd);
191 TALLOC_FREE(sd);
193 if (NT_STATUS_IS_OK(status) ||
194 !NT_STATUS_EQUAL(status, NT_STATUS_ACCESS_DENIED)) {
195 return status;
198 /* Here we know status == NT_STATUS_ACCESS_DENIED. */
200 access_denied:
202 if ((access_mask & FILE_WRITE_ATTRIBUTES) &&
203 (rejected_mask & FILE_WRITE_ATTRIBUTES) &&
204 !lp_store_dos_attributes(SNUM(conn)) &&
205 (lp_map_readonly(SNUM(conn)) ||
206 lp_map_archive(SNUM(conn)) ||
207 lp_map_hidden(SNUM(conn)) ||
208 lp_map_system(SNUM(conn)))) {
209 rejected_mask &= ~FILE_WRITE_ATTRIBUTES;
211 DEBUG(10,("smbd_check_access_rights: "
212 "overrode "
213 "FILE_WRITE_ATTRIBUTES "
214 "on file %s\n",
215 smb_fname_str_dbg(smb_fname)));
218 if (parent_override_delete(conn,
219 smb_fname,
220 access_mask,
221 rejected_mask)) {
222 /* Were we trying to do an open
223 * for delete and didn't get DELETE
224 * access (only) ? Check if the
225 * directory allows DELETE_CHILD.
226 * See here:
227 * http://blogs.msdn.com/oldnewthing/archive/2004/06/04/148426.aspx
228 * for details. */
230 rejected_mask &= ~DELETE_ACCESS;
232 DEBUG(10,("smbd_check_access_rights: "
233 "overrode "
234 "DELETE_ACCESS on "
235 "file %s\n",
236 smb_fname_str_dbg(smb_fname)));
239 if (rejected_mask != 0) {
240 return NT_STATUS_ACCESS_DENIED;
242 return NT_STATUS_OK;
245 NTSTATUS check_parent_access(struct connection_struct *conn,
246 struct smb_filename *smb_fname,
247 uint32_t access_mask)
249 NTSTATUS status;
250 char *parent_dir = NULL;
251 struct security_descriptor *parent_sd = NULL;
252 uint32_t access_granted = 0;
254 if (!parent_dirname(talloc_tos(),
255 smb_fname->base_name,
256 &parent_dir,
257 NULL)) {
258 return NT_STATUS_NO_MEMORY;
261 if (get_current_uid(conn) == (uid_t)0) {
262 /* I'm sorry sir, I didn't know you were root... */
263 DEBUG(10,("check_parent_access: root override "
264 "on %s. Granting 0x%x\n",
265 smb_fname_str_dbg(smb_fname),
266 (unsigned int)access_mask ));
267 return NT_STATUS_OK;
270 status = SMB_VFS_GET_NT_ACL(conn,
271 parent_dir,
272 SECINFO_DACL,
273 talloc_tos(),
274 &parent_sd);
276 if (!NT_STATUS_IS_OK(status)) {
277 DEBUG(5,("check_parent_access: SMB_VFS_GET_NT_ACL failed for "
278 "%s with error %s\n",
279 parent_dir,
280 nt_errstr(status)));
281 return status;
285 * If we can access the path to this file, by
286 * default we have FILE_READ_ATTRIBUTES from the
287 * containing directory. See the section:
288 * "Algorithm to Check Access to an Existing File"
289 * in MS-FSA.pdf.
291 * se_file_access_check() also takes care of
292 * owner WRITE_DAC and READ_CONTROL.
294 status = se_file_access_check(parent_sd,
295 get_current_nttok(conn),
296 false,
297 (access_mask & ~FILE_READ_ATTRIBUTES),
298 &access_granted);
299 if(!NT_STATUS_IS_OK(status)) {
300 DEBUG(5,("check_parent_access: access check "
301 "on directory %s for "
302 "path %s for mask 0x%x returned (0x%x) %s\n",
303 parent_dir,
304 smb_fname->base_name,
305 access_mask,
306 access_granted,
307 nt_errstr(status) ));
308 return status;
311 return NT_STATUS_OK;
314 /****************************************************************************
315 Ensure when opening a base file for a stream open that we have permissions
316 to do so given the access mask on the base file.
317 ****************************************************************************/
319 static NTSTATUS check_base_file_access(struct connection_struct *conn,
320 struct smb_filename *smb_fname,
321 uint32_t access_mask)
323 NTSTATUS status;
325 status = smbd_calculate_access_mask(conn, smb_fname,
326 false,
327 access_mask,
328 &access_mask);
329 if (!NT_STATUS_IS_OK(status)) {
330 DEBUG(10, ("smbd_calculate_access_mask "
331 "on file %s returned %s\n",
332 smb_fname_str_dbg(smb_fname),
333 nt_errstr(status)));
334 return status;
337 if (access_mask & (FILE_WRITE_DATA|FILE_APPEND_DATA)) {
338 uint32_t dosattrs;
339 if (!CAN_WRITE(conn)) {
340 return NT_STATUS_ACCESS_DENIED;
342 dosattrs = dos_mode(conn, smb_fname);
343 if (IS_DOS_READONLY(dosattrs)) {
344 return NT_STATUS_ACCESS_DENIED;
348 return smbd_check_access_rights(conn,
349 smb_fname,
350 false,
351 access_mask);
354 /****************************************************************************
355 fd support routines - attempt to do a dos_open.
356 ****************************************************************************/
358 NTSTATUS fd_open(struct connection_struct *conn,
359 files_struct *fsp,
360 int flags,
361 mode_t mode)
363 struct smb_filename *smb_fname = fsp->fsp_name;
364 NTSTATUS status = NT_STATUS_OK;
366 #ifdef O_NOFOLLOW
368 * Never follow symlinks on a POSIX client. The
369 * client should be doing this.
372 if ((fsp->posix_flags & FSP_POSIX_FLAGS_OPEN) || !lp_follow_symlinks(SNUM(conn))) {
373 flags |= O_NOFOLLOW;
375 #endif
377 fsp->fh->fd = SMB_VFS_OPEN(conn, smb_fname, fsp, flags, mode);
378 if (fsp->fh->fd == -1) {
379 int posix_errno = errno;
380 #ifdef O_NOFOLLOW
381 #if defined(ENOTSUP) && defined(OSF1)
382 /* handle special Tru64 errno */
383 if (errno == ENOTSUP) {
384 posix_errno = ELOOP;
386 #endif /* ENOTSUP */
387 #ifdef EFTYPE
388 /* fix broken NetBSD errno */
389 if (errno == EFTYPE) {
390 posix_errno = ELOOP;
392 #endif /* EFTYPE */
393 /* fix broken FreeBSD errno */
394 if (errno == EMLINK) {
395 posix_errno = ELOOP;
397 #endif /* O_NOFOLLOW */
398 status = map_nt_error_from_unix(posix_errno);
399 if (errno == EMFILE) {
400 static time_t last_warned = 0L;
402 if (time((time_t *) NULL) > last_warned) {
403 DEBUG(0,("Too many open files, unable "
404 "to open more! smbd's max "
405 "open files = %d\n",
406 lp_max_open_files()));
407 last_warned = time((time_t *) NULL);
413 DEBUG(10,("fd_open: name %s, flags = 0%o mode = 0%o, fd = %d. %s\n",
414 smb_fname_str_dbg(smb_fname), flags, (int)mode, fsp->fh->fd,
415 (fsp->fh->fd == -1) ? strerror(errno) : "" ));
417 return status;
420 /****************************************************************************
421 Close the file associated with a fsp.
422 ****************************************************************************/
424 NTSTATUS fd_close(files_struct *fsp)
426 int ret;
428 if (fsp->dptr) {
429 dptr_CloseDir(fsp);
431 if (fsp->fh->fd == -1) {
432 return NT_STATUS_OK; /* What we used to call a stat open. */
434 if (fsp->fh->ref_count > 1) {
435 return NT_STATUS_OK; /* Shared handle. Only close last reference. */
438 ret = SMB_VFS_CLOSE(fsp);
439 fsp->fh->fd = -1;
440 if (ret == -1) {
441 return map_nt_error_from_unix(errno);
443 return NT_STATUS_OK;
446 /****************************************************************************
447 Change the ownership of a file to that of the parent directory.
448 Do this by fd if possible.
449 ****************************************************************************/
451 void change_file_owner_to_parent(connection_struct *conn,
452 const char *inherit_from_dir,
453 files_struct *fsp)
455 struct smb_filename *smb_fname_parent;
456 int ret;
458 smb_fname_parent = synthetic_smb_fname(talloc_tos(), inherit_from_dir,
459 NULL, NULL);
460 if (smb_fname_parent == NULL) {
461 return;
464 ret = SMB_VFS_STAT(conn, smb_fname_parent);
465 if (ret == -1) {
466 DEBUG(0,("change_file_owner_to_parent: failed to stat parent "
467 "directory %s. Error was %s\n",
468 smb_fname_str_dbg(smb_fname_parent),
469 strerror(errno)));
470 TALLOC_FREE(smb_fname_parent);
471 return;
474 if (smb_fname_parent->st.st_ex_uid == fsp->fsp_name->st.st_ex_uid) {
475 /* Already this uid - no need to change. */
476 DEBUG(10,("change_file_owner_to_parent: file %s "
477 "is already owned by uid %d\n",
478 fsp_str_dbg(fsp),
479 (int)fsp->fsp_name->st.st_ex_uid ));
480 TALLOC_FREE(smb_fname_parent);
481 return;
484 become_root();
485 ret = SMB_VFS_FCHOWN(fsp, smb_fname_parent->st.st_ex_uid, (gid_t)-1);
486 unbecome_root();
487 if (ret == -1) {
488 DEBUG(0,("change_file_owner_to_parent: failed to fchown "
489 "file %s to parent directory uid %u. Error "
490 "was %s\n", fsp_str_dbg(fsp),
491 (unsigned int)smb_fname_parent->st.st_ex_uid,
492 strerror(errno) ));
493 } else {
494 DEBUG(10,("change_file_owner_to_parent: changed new file %s to "
495 "parent directory uid %u.\n", fsp_str_dbg(fsp),
496 (unsigned int)smb_fname_parent->st.st_ex_uid));
497 /* Ensure the uid entry is updated. */
498 fsp->fsp_name->st.st_ex_uid = smb_fname_parent->st.st_ex_uid;
501 TALLOC_FREE(smb_fname_parent);
504 NTSTATUS change_dir_owner_to_parent(connection_struct *conn,
505 const char *inherit_from_dir,
506 const char *fname,
507 SMB_STRUCT_STAT *psbuf)
509 struct smb_filename *smb_fname_parent;
510 struct smb_filename *smb_fname_cwd = NULL;
511 char *saved_dir = NULL;
512 TALLOC_CTX *ctx = talloc_tos();
513 NTSTATUS status = NT_STATUS_OK;
514 int ret;
516 smb_fname_parent = synthetic_smb_fname(ctx, inherit_from_dir,
517 NULL, NULL);
518 if (smb_fname_parent == NULL) {
519 return NT_STATUS_NO_MEMORY;
522 ret = SMB_VFS_STAT(conn, smb_fname_parent);
523 if (ret == -1) {
524 status = map_nt_error_from_unix(errno);
525 DEBUG(0,("change_dir_owner_to_parent: failed to stat parent "
526 "directory %s. Error was %s\n",
527 smb_fname_str_dbg(smb_fname_parent),
528 strerror(errno)));
529 goto out;
532 /* We've already done an lstat into psbuf, and we know it's a
533 directory. If we can cd into the directory and the dev/ino
534 are the same then we can safely chown without races as
535 we're locking the directory in place by being in it. This
536 should work on any UNIX (thanks tridge :-). JRA.
539 saved_dir = vfs_GetWd(ctx,conn);
540 if (!saved_dir) {
541 status = map_nt_error_from_unix(errno);
542 DEBUG(0,("change_dir_owner_to_parent: failed to get "
543 "current working directory. Error was %s\n",
544 strerror(errno)));
545 goto out;
548 /* Chdir into the new path. */
549 if (vfs_ChDir(conn, fname) == -1) {
550 status = map_nt_error_from_unix(errno);
551 DEBUG(0,("change_dir_owner_to_parent: failed to change "
552 "current working directory to %s. Error "
553 "was %s\n", fname, strerror(errno) ));
554 goto chdir;
557 smb_fname_cwd = synthetic_smb_fname(ctx, ".", NULL, NULL);
558 if (smb_fname_cwd == NULL) {
559 status = NT_STATUS_NO_MEMORY;
560 goto chdir;
563 ret = SMB_VFS_STAT(conn, smb_fname_cwd);
564 if (ret == -1) {
565 status = map_nt_error_from_unix(errno);
566 DEBUG(0,("change_dir_owner_to_parent: failed to stat "
567 "directory '.' (%s) Error was %s\n",
568 fname, strerror(errno)));
569 goto chdir;
572 /* Ensure we're pointing at the same place. */
573 if (smb_fname_cwd->st.st_ex_dev != psbuf->st_ex_dev ||
574 smb_fname_cwd->st.st_ex_ino != psbuf->st_ex_ino) {
575 DEBUG(0,("change_dir_owner_to_parent: "
576 "device/inode on directory %s changed. "
577 "Refusing to chown !\n", fname ));
578 status = NT_STATUS_ACCESS_DENIED;
579 goto chdir;
582 if (smb_fname_parent->st.st_ex_uid == smb_fname_cwd->st.st_ex_uid) {
583 /* Already this uid - no need to change. */
584 DEBUG(10,("change_dir_owner_to_parent: directory %s "
585 "is already owned by uid %d\n",
586 fname,
587 (int)smb_fname_cwd->st.st_ex_uid ));
588 status = NT_STATUS_OK;
589 goto chdir;
592 become_root();
593 ret = SMB_VFS_LCHOWN(conn, ".", smb_fname_parent->st.st_ex_uid,
594 (gid_t)-1);
595 unbecome_root();
596 if (ret == -1) {
597 status = map_nt_error_from_unix(errno);
598 DEBUG(10,("change_dir_owner_to_parent: failed to chown "
599 "directory %s to parent directory uid %u. "
600 "Error was %s\n", fname,
601 (unsigned int)smb_fname_parent->st.st_ex_uid,
602 strerror(errno) ));
603 } else {
604 DEBUG(10,("change_dir_owner_to_parent: changed ownership of new "
605 "directory %s to parent directory uid %u.\n",
606 fname, (unsigned int)smb_fname_parent->st.st_ex_uid ));
607 /* Ensure the uid entry is updated. */
608 psbuf->st_ex_uid = smb_fname_parent->st.st_ex_uid;
611 chdir:
612 vfs_ChDir(conn,saved_dir);
613 out:
614 TALLOC_FREE(smb_fname_parent);
615 TALLOC_FREE(smb_fname_cwd);
616 return status;
619 /****************************************************************************
620 Open a file - returning a guaranteed ATOMIC indication of if the
621 file was created or not.
622 ****************************************************************************/
624 static NTSTATUS fd_open_atomic(struct connection_struct *conn,
625 files_struct *fsp,
626 int flags,
627 mode_t mode,
628 bool *file_created)
630 NTSTATUS status = NT_STATUS_UNSUCCESSFUL;
631 NTSTATUS retry_status;
632 bool file_existed = VALID_STAT(fsp->fsp_name->st);
633 int curr_flags;
635 *file_created = false;
637 if (!(flags & O_CREAT)) {
639 * We're not creating the file, just pass through.
641 return fd_open(conn, fsp, flags, mode);
644 if (flags & O_EXCL) {
646 * Fail if already exists, just pass through.
648 status = fd_open(conn, fsp, flags, mode);
651 * Here we've opened with O_CREAT|O_EXCL. If that went
652 * NT_STATUS_OK, we *know* we created this file.
654 *file_created = NT_STATUS_IS_OK(status);
656 return status;
660 * Now it gets tricky. We have O_CREAT, but not O_EXCL.
661 * To know absolutely if we created the file or not,
662 * we can never call O_CREAT without O_EXCL. So if
663 * we think the file existed, try without O_CREAT|O_EXCL.
664 * If we think the file didn't exist, try with
665 * O_CREAT|O_EXCL.
667 * The big problem here is dangling symlinks. Opening
668 * without O_NOFOLLOW means both bad symlink
669 * and missing path return -1, ENOENT from open(). As POSIX
670 * is pathname based it's not possible to tell
671 * the difference between these two cases in a
672 * non-racy way, so change to try only two attempts before
673 * giving up.
675 * We don't have this problem for the O_NOFOLLOW
676 * case as it just returns NT_STATUS_OBJECT_PATH_NOT_FOUND
677 * mapped from the ELOOP POSIX error.
680 curr_flags = flags;
682 if (file_existed) {
683 curr_flags &= ~(O_CREAT);
684 retry_status = NT_STATUS_OBJECT_NAME_NOT_FOUND;
685 } else {
686 curr_flags |= O_EXCL;
687 retry_status = NT_STATUS_OBJECT_NAME_COLLISION;
690 status = fd_open(conn, fsp, curr_flags, mode);
691 if (NT_STATUS_IS_OK(status)) {
692 if (!file_existed) {
693 *file_created = true;
695 return NT_STATUS_OK;
697 if (!NT_STATUS_EQUAL(status, retry_status)) {
698 return status;
701 curr_flags = flags;
704 * Keep file_existed up to date for clarity.
706 if (NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
707 file_existed = false;
708 curr_flags |= O_EXCL;
709 DBG_DEBUG("file %s did not exist. Retry.\n",
710 smb_fname_str_dbg(fsp->fsp_name));
711 } else {
712 file_existed = true;
713 curr_flags &= ~(O_CREAT);
714 DBG_DEBUG("file %s existed. Retry.\n",
715 smb_fname_str_dbg(fsp->fsp_name));
718 status = fd_open(conn, fsp, curr_flags, mode);
720 if (NT_STATUS_IS_OK(status) && (!file_existed)) {
721 *file_created = true;
724 return status;
727 /****************************************************************************
728 Open a file.
729 ****************************************************************************/
731 static NTSTATUS open_file(files_struct *fsp,
732 connection_struct *conn,
733 struct smb_request *req,
734 const char *parent_dir,
735 int flags,
736 mode_t unx_mode,
737 uint32_t access_mask, /* client requested access mask. */
738 uint32_t open_access_mask, /* what we're actually using in the open. */
739 bool *p_file_created)
741 struct smb_filename *smb_fname = fsp->fsp_name;
742 NTSTATUS status = NT_STATUS_OK;
743 int accmode = (flags & O_ACCMODE);
744 int local_flags = flags;
745 bool file_existed = VALID_STAT(fsp->fsp_name->st);
747 fsp->fh->fd = -1;
748 errno = EPERM;
750 /* Check permissions */
753 * This code was changed after seeing a client open request
754 * containing the open mode of (DENY_WRITE/read-only) with
755 * the 'create if not exist' bit set. The previous code
756 * would fail to open the file read only on a read-only share
757 * as it was checking the flags parameter directly against O_RDONLY,
758 * this was failing as the flags parameter was set to O_RDONLY|O_CREAT.
759 * JRA.
762 if (!CAN_WRITE(conn)) {
763 /* It's a read-only share - fail if we wanted to write. */
764 if(accmode != O_RDONLY || (flags & O_TRUNC) || (flags & O_APPEND)) {
765 DEBUG(3,("Permission denied opening %s\n",
766 smb_fname_str_dbg(smb_fname)));
767 return NT_STATUS_ACCESS_DENIED;
769 if (flags & O_CREAT) {
770 /* We don't want to write - but we must make sure that
771 O_CREAT doesn't create the file if we have write
772 access into the directory.
774 flags &= ~(O_CREAT|O_EXCL);
775 local_flags &= ~(O_CREAT|O_EXCL);
780 * This little piece of insanity is inspired by the
781 * fact that an NT client can open a file for O_RDONLY,
782 * but set the create disposition to FILE_EXISTS_TRUNCATE.
783 * If the client *can* write to the file, then it expects to
784 * truncate the file, even though it is opening for readonly.
785 * Quicken uses this stupid trick in backup file creation...
786 * Thanks *greatly* to "David W. Chapman Jr." <dwcjr@inethouston.net>
787 * for helping track this one down. It didn't bite us in 2.0.x
788 * as we always opened files read-write in that release. JRA.
791 if ((accmode == O_RDONLY) && ((flags & O_TRUNC) == O_TRUNC)) {
792 DEBUG(10,("open_file: truncate requested on read-only open "
793 "for file %s\n", smb_fname_str_dbg(smb_fname)));
794 local_flags = (flags & ~O_ACCMODE)|O_RDWR;
797 if ((open_access_mask & (FILE_READ_DATA|FILE_WRITE_DATA|FILE_APPEND_DATA|FILE_EXECUTE)) ||
798 (!file_existed && (local_flags & O_CREAT)) ||
799 ((local_flags & O_TRUNC) == O_TRUNC) ) {
800 const char *wild;
801 int ret;
803 #if defined(O_NONBLOCK) && defined(S_ISFIFO)
805 * We would block on opening a FIFO with no one else on the
806 * other end. Do what we used to do and add O_NONBLOCK to the
807 * open flags. JRA.
810 if (file_existed && S_ISFIFO(smb_fname->st.st_ex_mode)) {
811 local_flags &= ~O_TRUNC; /* Can't truncate a FIFO. */
812 local_flags |= O_NONBLOCK;
814 #endif
816 /* Don't create files with Microsoft wildcard characters. */
817 if (fsp->base_fsp) {
819 * wildcard characters are allowed in stream names
820 * only test the basefilename
822 wild = fsp->base_fsp->fsp_name->base_name;
823 } else {
824 wild = smb_fname->base_name;
826 if ((local_flags & O_CREAT) && !file_existed &&
827 !(fsp->posix_flags & FSP_POSIX_FLAGS_PATHNAMES) &&
828 ms_has_wild(wild)) {
829 return NT_STATUS_OBJECT_NAME_INVALID;
832 /* Can we access this file ? */
833 if (!fsp->base_fsp) {
834 /* Only do this check on non-stream open. */
835 if (file_existed) {
836 status = smbd_check_access_rights(conn,
837 smb_fname,
838 false,
839 access_mask);
841 if (!NT_STATUS_IS_OK(status)) {
842 DEBUG(10, ("open_file: "
843 "smbd_check_access_rights "
844 "on file %s returned %s\n",
845 smb_fname_str_dbg(smb_fname),
846 nt_errstr(status)));
849 if (!NT_STATUS_IS_OK(status) &&
850 !NT_STATUS_EQUAL(status,
851 NT_STATUS_OBJECT_NAME_NOT_FOUND))
853 return status;
856 if (NT_STATUS_EQUAL(status,
857 NT_STATUS_OBJECT_NAME_NOT_FOUND))
859 DEBUG(10, ("open_file: "
860 "file %s vanished since we "
861 "checked for existence.\n",
862 smb_fname_str_dbg(smb_fname)));
863 file_existed = false;
864 SET_STAT_INVALID(fsp->fsp_name->st);
868 if (!file_existed) {
869 if (!(local_flags & O_CREAT)) {
870 /* File didn't exist and no O_CREAT. */
871 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
874 status = check_parent_access(conn,
875 smb_fname,
876 SEC_DIR_ADD_FILE);
877 if (!NT_STATUS_IS_OK(status)) {
878 DEBUG(10, ("open_file: "
879 "check_parent_access on "
880 "file %s returned %s\n",
881 smb_fname_str_dbg(smb_fname),
882 nt_errstr(status) ));
883 return status;
889 * Actually do the open - if O_TRUNC is needed handle it
890 * below under the share mode lock.
892 status = fd_open_atomic(conn, fsp, local_flags & ~O_TRUNC,
893 unx_mode, p_file_created);
894 if (!NT_STATUS_IS_OK(status)) {
895 DEBUG(3,("Error opening file %s (%s) (local_flags=%d) "
896 "(flags=%d)\n", smb_fname_str_dbg(smb_fname),
897 nt_errstr(status),local_flags,flags));
898 return status;
901 if (local_flags & O_NONBLOCK) {
903 * GPFS can return ETIMEDOUT for pread on
904 * nonblocking file descriptors when files
905 * migrated to tape need to be recalled. I
906 * could imagine this happens elsehwere
907 * too. With blocking file descriptors this
908 * does not happen.
910 ret = set_blocking(fsp->fh->fd, true);
911 if (ret == -1) {
912 status = map_nt_error_from_unix(errno);
913 DBG_WARNING("Could not set fd to blocking: "
914 "%s\n", strerror(errno));
915 fd_close(fsp);
916 return status;
920 ret = SMB_VFS_FSTAT(fsp, &smb_fname->st);
921 if (ret == -1) {
922 /* If we have an fd, this stat should succeed. */
923 DEBUG(0,("Error doing fstat on open file %s "
924 "(%s)\n",
925 smb_fname_str_dbg(smb_fname),
926 strerror(errno) ));
927 status = map_nt_error_from_unix(errno);
928 fd_close(fsp);
929 return status;
932 if (*p_file_created) {
933 /* We created this file. */
935 bool need_re_stat = false;
936 /* Do all inheritance work after we've
937 done a successful fstat call and filled
938 in the stat struct in fsp->fsp_name. */
940 /* Inherit the ACL if required */
941 if (lp_inherit_permissions(SNUM(conn))) {
942 inherit_access_posix_acl(conn, parent_dir,
943 smb_fname->base_name,
944 unx_mode);
945 need_re_stat = true;
948 /* Change the owner if required. */
949 if (lp_inherit_owner(SNUM(conn))) {
950 change_file_owner_to_parent(conn, parent_dir,
951 fsp);
952 need_re_stat = true;
955 if (need_re_stat) {
956 ret = SMB_VFS_FSTAT(fsp, &smb_fname->st);
957 /* If we have an fd, this stat should succeed. */
958 if (ret == -1) {
959 DEBUG(0,("Error doing fstat on open file %s "
960 "(%s)\n",
961 smb_fname_str_dbg(smb_fname),
962 strerror(errno) ));
966 notify_fname(conn, NOTIFY_ACTION_ADDED,
967 FILE_NOTIFY_CHANGE_FILE_NAME,
968 smb_fname->base_name);
970 } else {
971 fsp->fh->fd = -1; /* What we used to call a stat open. */
972 if (!file_existed) {
973 /* File must exist for a stat open. */
974 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
977 status = smbd_check_access_rights(conn,
978 smb_fname,
979 false,
980 access_mask);
982 if (NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND) &&
983 (fsp->posix_flags & FSP_POSIX_FLAGS_OPEN) &&
984 S_ISLNK(smb_fname->st.st_ex_mode)) {
985 /* This is a POSIX stat open for delete
986 * or rename on a symlink that points
987 * nowhere. Allow. */
988 DEBUG(10,("open_file: allowing POSIX "
989 "open on bad symlink %s\n",
990 smb_fname_str_dbg(smb_fname)));
991 status = NT_STATUS_OK;
994 if (!NT_STATUS_IS_OK(status)) {
995 DEBUG(10,("open_file: "
996 "smbd_check_access_rights on file "
997 "%s returned %s\n",
998 smb_fname_str_dbg(smb_fname),
999 nt_errstr(status) ));
1000 return status;
1005 * POSIX allows read-only opens of directories. We don't
1006 * want to do this (we use a different code path for this)
1007 * so catch a directory open and return an EISDIR. JRA.
1010 if(S_ISDIR(smb_fname->st.st_ex_mode)) {
1011 fd_close(fsp);
1012 errno = EISDIR;
1013 return NT_STATUS_FILE_IS_A_DIRECTORY;
1016 fsp->file_id = vfs_file_id_from_sbuf(conn, &smb_fname->st);
1017 fsp->vuid = req ? req->vuid : UID_FIELD_INVALID;
1018 fsp->file_pid = req ? req->smbpid : 0;
1019 fsp->can_lock = True;
1020 fsp->can_read = ((access_mask & FILE_READ_DATA) != 0);
1021 fsp->can_write =
1022 CAN_WRITE(conn) &&
1023 ((access_mask & (FILE_WRITE_DATA | FILE_APPEND_DATA)) != 0);
1024 fsp->print_file = NULL;
1025 fsp->modified = False;
1026 fsp->sent_oplock_break = NO_BREAK_SENT;
1027 fsp->is_directory = False;
1028 if (conn->aio_write_behind_list &&
1029 is_in_path(smb_fname->base_name, conn->aio_write_behind_list,
1030 conn->case_sensitive)) {
1031 fsp->aio_write_behind = True;
1034 fsp->wcp = NULL; /* Write cache pointer. */
1036 DEBUG(2,("%s opened file %s read=%s write=%s (numopen=%d)\n",
1037 conn->session_info->unix_info->unix_name,
1038 smb_fname_str_dbg(smb_fname),
1039 BOOLSTR(fsp->can_read), BOOLSTR(fsp->can_write),
1040 conn->num_files_open));
1042 errno = 0;
1043 return NT_STATUS_OK;
1046 /****************************************************************************
1047 Check if we can open a file with a share mode.
1048 Returns True if conflict, False if not.
1049 ****************************************************************************/
1051 static bool share_conflict(struct share_mode_entry *entry,
1052 uint32_t access_mask,
1053 uint32_t share_access)
1055 DEBUG(10,("share_conflict: entry->access_mask = 0x%x, "
1056 "entry->share_access = 0x%x, "
1057 "entry->private_options = 0x%x\n",
1058 (unsigned int)entry->access_mask,
1059 (unsigned int)entry->share_access,
1060 (unsigned int)entry->private_options));
1062 if (server_id_is_disconnected(&entry->pid)) {
1064 * note: cleanup should have been done by
1065 * delay_for_batch_oplocks()
1067 return false;
1070 DEBUG(10,("share_conflict: access_mask = 0x%x, share_access = 0x%x\n",
1071 (unsigned int)access_mask, (unsigned int)share_access));
1073 if ((entry->access_mask & (FILE_WRITE_DATA|
1074 FILE_APPEND_DATA|
1075 FILE_READ_DATA|
1076 FILE_EXECUTE|
1077 DELETE_ACCESS)) == 0) {
1078 DEBUG(10,("share_conflict: No conflict due to "
1079 "entry->access_mask = 0x%x\n",
1080 (unsigned int)entry->access_mask ));
1081 return False;
1084 if ((access_mask & (FILE_WRITE_DATA|
1085 FILE_APPEND_DATA|
1086 FILE_READ_DATA|
1087 FILE_EXECUTE|
1088 DELETE_ACCESS)) == 0) {
1089 DEBUG(10,("share_conflict: No conflict due to "
1090 "access_mask = 0x%x\n",
1091 (unsigned int)access_mask ));
1092 return False;
1095 #if 1 /* JRA TEST - Superdebug. */
1096 #define CHECK_MASK(num, am, right, sa, share) \
1097 DEBUG(10,("share_conflict: [%d] am (0x%x) & right (0x%x) = 0x%x\n", \
1098 (unsigned int)(num), (unsigned int)(am), \
1099 (unsigned int)(right), (unsigned int)(am)&(right) )); \
1100 DEBUG(10,("share_conflict: [%d] sa (0x%x) & share (0x%x) = 0x%x\n", \
1101 (unsigned int)(num), (unsigned int)(sa), \
1102 (unsigned int)(share), (unsigned int)(sa)&(share) )); \
1103 if (((am) & (right)) && !((sa) & (share))) { \
1104 DEBUG(10,("share_conflict: check %d conflict am = 0x%x, right = 0x%x, \
1105 sa = 0x%x, share = 0x%x\n", (num), (unsigned int)(am), (unsigned int)(right), (unsigned int)(sa), \
1106 (unsigned int)(share) )); \
1107 return True; \
1109 #else
1110 #define CHECK_MASK(num, am, right, sa, share) \
1111 if (((am) & (right)) && !((sa) & (share))) { \
1112 DEBUG(10,("share_conflict: check %d conflict am = 0x%x, right = 0x%x, \
1113 sa = 0x%x, share = 0x%x\n", (num), (unsigned int)(am), (unsigned int)(right), (unsigned int)(sa), \
1114 (unsigned int)(share) )); \
1115 return True; \
1117 #endif
1119 CHECK_MASK(1, entry->access_mask, FILE_WRITE_DATA | FILE_APPEND_DATA,
1120 share_access, FILE_SHARE_WRITE);
1121 CHECK_MASK(2, access_mask, FILE_WRITE_DATA | FILE_APPEND_DATA,
1122 entry->share_access, FILE_SHARE_WRITE);
1124 CHECK_MASK(3, entry->access_mask, FILE_READ_DATA | FILE_EXECUTE,
1125 share_access, FILE_SHARE_READ);
1126 CHECK_MASK(4, access_mask, FILE_READ_DATA | FILE_EXECUTE,
1127 entry->share_access, FILE_SHARE_READ);
1129 CHECK_MASK(5, entry->access_mask, DELETE_ACCESS,
1130 share_access, FILE_SHARE_DELETE);
1131 CHECK_MASK(6, access_mask, DELETE_ACCESS,
1132 entry->share_access, FILE_SHARE_DELETE);
1134 DEBUG(10,("share_conflict: No conflict.\n"));
1135 return False;
1138 #if defined(DEVELOPER)
1139 static void validate_my_share_entries(struct smbd_server_connection *sconn,
1140 int num,
1141 struct share_mode_entry *share_entry)
1143 struct server_id self = messaging_server_id(sconn->msg_ctx);
1144 files_struct *fsp;
1146 if (!serverid_equal(&self, &share_entry->pid)) {
1147 return;
1150 if (share_entry->op_mid == 0) {
1151 /* INTERNAL_OPEN_ONLY */
1152 return;
1155 if (!is_valid_share_mode_entry(share_entry)) {
1156 return;
1159 fsp = file_find_dif(sconn, share_entry->id,
1160 share_entry->share_file_id);
1161 if (!fsp) {
1162 DEBUG(0,("validate_my_share_entries: PANIC : %s\n",
1163 share_mode_str(talloc_tos(), num, share_entry) ));
1164 smb_panic("validate_my_share_entries: Cannot match a "
1165 "share entry with an open file\n");
1168 if (((uint16_t)fsp->oplock_type) != share_entry->op_type) {
1169 goto panic;
1172 return;
1174 panic:
1176 char *str;
1177 DEBUG(0,("validate_my_share_entries: PANIC : %s\n",
1178 share_mode_str(talloc_tos(), num, share_entry) ));
1179 str = talloc_asprintf(talloc_tos(),
1180 "validate_my_share_entries: "
1181 "file %s, oplock_type = 0x%x, op_type = 0x%x\n",
1182 fsp->fsp_name->base_name,
1183 (unsigned int)fsp->oplock_type,
1184 (unsigned int)share_entry->op_type );
1185 smb_panic(str);
1188 #endif
1190 bool is_stat_open(uint32_t access_mask)
1192 const uint32_t stat_open_bits =
1193 (SYNCHRONIZE_ACCESS|
1194 FILE_READ_ATTRIBUTES|
1195 FILE_WRITE_ATTRIBUTES);
1197 return (((access_mask & stat_open_bits) != 0) &&
1198 ((access_mask & ~stat_open_bits) == 0));
1201 static bool has_delete_on_close(struct share_mode_lock *lck,
1202 uint32_t name_hash)
1204 struct share_mode_data *d = lck->data;
1205 uint32_t i;
1207 if (d->num_share_modes == 0) {
1208 return false;
1210 if (!is_delete_on_close_set(lck, name_hash)) {
1211 return false;
1213 for (i=0; i<d->num_share_modes; i++) {
1214 if (!share_mode_stale_pid(d, i)) {
1215 return true;
1218 return false;
1221 /****************************************************************************
1222 Deal with share modes
1223 Invariant: Share mode must be locked on entry and exit.
1224 Returns -1 on error, or number of share modes on success (may be zero).
1225 ****************************************************************************/
1227 static NTSTATUS open_mode_check(connection_struct *conn,
1228 struct share_mode_lock *lck,
1229 uint32_t access_mask,
1230 uint32_t share_access)
1232 int i;
1234 if(lck->data->num_share_modes == 0) {
1235 return NT_STATUS_OK;
1238 if (is_stat_open(access_mask)) {
1239 /* Stat open that doesn't trigger oplock breaks or share mode
1240 * checks... ! JRA. */
1241 return NT_STATUS_OK;
1245 * Check if the share modes will give us access.
1248 #if defined(DEVELOPER)
1249 for(i = 0; i < lck->data->num_share_modes; i++) {
1250 validate_my_share_entries(conn->sconn, i,
1251 &lck->data->share_modes[i]);
1253 #endif
1255 /* Now we check the share modes, after any oplock breaks. */
1256 for(i = 0; i < lck->data->num_share_modes; i++) {
1258 if (!is_valid_share_mode_entry(&lck->data->share_modes[i])) {
1259 continue;
1262 /* someone else has a share lock on it, check to see if we can
1263 * too */
1264 if (share_conflict(&lck->data->share_modes[i],
1265 access_mask, share_access)) {
1267 if (share_mode_stale_pid(lck->data, i)) {
1268 continue;
1271 return NT_STATUS_SHARING_VIOLATION;
1275 return NT_STATUS_OK;
1279 * Send a break message to the oplock holder and delay the open for
1280 * our client.
1283 NTSTATUS send_break_message(struct messaging_context *msg_ctx,
1284 const struct share_mode_entry *exclusive,
1285 uint16_t break_to)
1287 NTSTATUS status;
1288 char msg[MSG_SMB_SHARE_MODE_ENTRY_SIZE];
1289 struct server_id_buf tmp;
1291 DEBUG(10, ("Sending break request to PID %s\n",
1292 server_id_str_buf(exclusive->pid, &tmp)));
1294 /* Create the message. */
1295 share_mode_entry_to_message(msg, exclusive);
1297 /* Overload entry->op_type */
1299 * This is a cut from uint32_t to uint16_t, but so far only the lower 3
1300 * bits (LEASE_WRITE/HANDLE/READ are used anyway.
1302 SSVAL(msg,OP_BREAK_MSG_OP_TYPE_OFFSET, break_to);
1304 status = messaging_send_buf(msg_ctx, exclusive->pid,
1305 MSG_SMB_BREAK_REQUEST,
1306 (uint8_t *)msg, sizeof(msg));
1307 if (!NT_STATUS_IS_OK(status)) {
1308 DEBUG(3, ("Could not send oplock break message: %s\n",
1309 nt_errstr(status)));
1312 return status;
1316 * Do internal consistency checks on the share mode for a file.
1319 static bool validate_oplock_types(struct share_mode_lock *lck)
1321 struct share_mode_data *d = lck->data;
1322 bool batch = false;
1323 bool ex_or_batch = false;
1324 bool level2 = false;
1325 bool no_oplock = false;
1326 uint32_t num_non_stat_opens = 0;
1327 uint32_t i;
1329 for (i=0; i<d->num_share_modes; i++) {
1330 struct share_mode_entry *e = &d->share_modes[i];
1332 if (!is_valid_share_mode_entry(e)) {
1333 continue;
1336 if (e->op_mid == 0) {
1337 /* INTERNAL_OPEN_ONLY */
1338 continue;
1341 if (e->op_type == NO_OPLOCK && is_stat_open(e->access_mask)) {
1342 /* We ignore stat opens in the table - they
1343 always have NO_OPLOCK and never get or
1344 cause breaks. JRA. */
1345 continue;
1348 num_non_stat_opens += 1;
1350 if (BATCH_OPLOCK_TYPE(e->op_type)) {
1351 /* batch - can only be one. */
1352 if (share_mode_stale_pid(d, i)) {
1353 DEBUG(10, ("Found stale batch oplock\n"));
1354 continue;
1356 if (ex_or_batch || batch || level2 || no_oplock) {
1357 DEBUG(0, ("Bad batch oplock entry %u.",
1358 (unsigned)i));
1359 return false;
1361 batch = true;
1364 if (EXCLUSIVE_OPLOCK_TYPE(e->op_type)) {
1365 if (share_mode_stale_pid(d, i)) {
1366 DEBUG(10, ("Found stale duplicate oplock\n"));
1367 continue;
1369 /* Exclusive or batch - can only be one. */
1370 if (ex_or_batch || level2 || no_oplock) {
1371 DEBUG(0, ("Bad exclusive or batch oplock "
1372 "entry %u.", (unsigned)i));
1373 return false;
1375 ex_or_batch = true;
1378 if (LEVEL_II_OPLOCK_TYPE(e->op_type)) {
1379 if (batch || ex_or_batch) {
1380 if (share_mode_stale_pid(d, i)) {
1381 DEBUG(10, ("Found stale LevelII "
1382 "oplock\n"));
1383 continue;
1385 DEBUG(0, ("Bad levelII oplock entry %u.",
1386 (unsigned)i));
1387 return false;
1389 level2 = true;
1392 if (e->op_type == NO_OPLOCK) {
1393 if (batch || ex_or_batch) {
1394 if (share_mode_stale_pid(d, i)) {
1395 DEBUG(10, ("Found stale NO_OPLOCK "
1396 "entry\n"));
1397 continue;
1399 DEBUG(0, ("Bad no oplock entry %u.",
1400 (unsigned)i));
1401 return false;
1403 no_oplock = true;
1407 remove_stale_share_mode_entries(d);
1409 if ((batch || ex_or_batch) && (num_non_stat_opens != 1)) {
1410 DEBUG(1, ("got batch (%d) or ex (%d) non-exclusively (%d)\n",
1411 (int)batch, (int)ex_or_batch,
1412 (int)d->num_share_modes));
1413 return false;
1416 return true;
1419 static bool delay_for_oplock(files_struct *fsp,
1420 int oplock_request,
1421 const struct smb2_lease *lease,
1422 struct share_mode_lock *lck,
1423 bool have_sharing_violation,
1424 uint32_t create_disposition,
1425 bool first_open_attempt)
1427 struct share_mode_data *d = lck->data;
1428 uint32_t i;
1429 bool delay = false;
1430 bool will_overwrite;
1432 if ((oplock_request & INTERNAL_OPEN_ONLY) ||
1433 is_stat_open(fsp->access_mask)) {
1434 return false;
1437 switch (create_disposition) {
1438 case FILE_SUPERSEDE:
1439 case FILE_OVERWRITE:
1440 case FILE_OVERWRITE_IF:
1441 will_overwrite = true;
1442 break;
1443 default:
1444 will_overwrite = false;
1445 break;
1448 for (i=0; i<d->num_share_modes; i++) {
1449 struct share_mode_entry *e = &d->share_modes[i];
1450 struct share_mode_lease *l = NULL;
1451 uint32_t e_lease_type = get_lease_type(d, e);
1452 uint32_t break_to;
1453 uint32_t delay_mask = 0;
1455 if (e->op_type == LEASE_OPLOCK) {
1456 l = &d->leases[e->lease_idx];
1459 if (have_sharing_violation) {
1460 delay_mask = SMB2_LEASE_HANDLE;
1461 } else {
1462 delay_mask = SMB2_LEASE_WRITE;
1465 break_to = e_lease_type & ~delay_mask;
1467 if (will_overwrite) {
1469 * we'll decide about SMB2_LEASE_READ later.
1471 * Maybe the break will be defered
1473 break_to &= ~SMB2_LEASE_HANDLE;
1476 DEBUG(10, ("entry %u: e_lease_type %u, will_overwrite: %u\n",
1477 (unsigned)i, (unsigned)e_lease_type,
1478 (unsigned)will_overwrite));
1480 if (lease != NULL && l != NULL) {
1481 bool ign;
1483 ign = smb2_lease_equal(fsp_client_guid(fsp),
1484 &lease->lease_key,
1485 &l->client_guid,
1486 &l->lease_key);
1487 if (ign) {
1488 continue;
1492 if ((e_lease_type & ~break_to) == 0) {
1493 if (l != NULL && l->breaking) {
1494 delay = true;
1496 continue;
1499 if (share_mode_stale_pid(d, i)) {
1500 continue;
1503 if (will_overwrite) {
1505 * If we break anyway break to NONE directly.
1506 * Otherwise vfs_set_filelen() will trigger the
1507 * break.
1509 break_to &= ~(SMB2_LEASE_READ|SMB2_LEASE_WRITE);
1512 if (e->op_type != LEASE_OPLOCK) {
1514 * Oplocks only support breaking to R or NONE.
1516 break_to &= ~(SMB2_LEASE_HANDLE|SMB2_LEASE_WRITE);
1519 DEBUG(10, ("breaking from %d to %d\n",
1520 (int)e_lease_type, (int)break_to));
1521 send_break_message(fsp->conn->sconn->msg_ctx, e,
1522 break_to);
1523 if (e_lease_type & delay_mask) {
1524 delay = true;
1526 if (l != NULL && l->breaking && !first_open_attempt) {
1527 delay = true;
1529 continue;
1532 return delay;
1535 static bool file_has_brlocks(files_struct *fsp)
1537 struct byte_range_lock *br_lck;
1539 br_lck = brl_get_locks_readonly(fsp);
1540 if (!br_lck)
1541 return false;
1543 return (brl_num_locks(br_lck) > 0);
1546 int find_share_mode_lease(struct share_mode_data *d,
1547 const struct GUID *client_guid,
1548 const struct smb2_lease_key *key)
1550 uint32_t i;
1552 for (i=0; i<d->num_leases; i++) {
1553 struct share_mode_lease *l = &d->leases[i];
1555 if (smb2_lease_equal(client_guid,
1556 key,
1557 &l->client_guid,
1558 &l->lease_key)) {
1559 return i;
1563 return -1;
1566 struct fsp_lease *find_fsp_lease(struct files_struct *new_fsp,
1567 const struct smb2_lease_key *key,
1568 const struct share_mode_lease *l)
1570 struct files_struct *fsp;
1573 * TODO: Measure how expensive this loop is with thousands of open
1574 * handles...
1577 for (fsp = file_find_di_first(new_fsp->conn->sconn, new_fsp->file_id);
1578 fsp != NULL;
1579 fsp = file_find_di_next(fsp)) {
1581 if (fsp == new_fsp) {
1582 continue;
1584 if (fsp->oplock_type != LEASE_OPLOCK) {
1585 continue;
1587 if (smb2_lease_key_equal(&fsp->lease->lease.lease_key, key)) {
1588 fsp->lease->ref_count += 1;
1589 return fsp->lease;
1593 /* Not found - must be leased in another smbd. */
1594 new_fsp->lease = talloc_zero(new_fsp->conn->sconn, struct fsp_lease);
1595 if (new_fsp->lease == NULL) {
1596 return NULL;
1598 new_fsp->lease->ref_count = 1;
1599 new_fsp->lease->sconn = new_fsp->conn->sconn;
1600 new_fsp->lease->lease.lease_key = *key;
1601 new_fsp->lease->lease.lease_state = l->current_state;
1603 * We internally treat all leases as V2 and update
1604 * the epoch, but when sending breaks it matters if
1605 * the requesting lease was v1 or v2.
1607 new_fsp->lease->lease.lease_version = l->lease_version;
1608 new_fsp->lease->lease.lease_epoch = l->epoch;
1609 return new_fsp->lease;
1612 static NTSTATUS grant_fsp_lease(struct files_struct *fsp,
1613 struct share_mode_lock *lck,
1614 const struct smb2_lease *lease,
1615 uint32_t *p_lease_idx,
1616 uint32_t granted)
1618 struct share_mode_data *d = lck->data;
1619 const struct GUID *client_guid = fsp_client_guid(fsp);
1620 struct share_mode_lease *tmp;
1621 NTSTATUS status;
1622 int idx;
1624 idx = find_share_mode_lease(d, client_guid, &lease->lease_key);
1626 if (idx != -1) {
1627 struct share_mode_lease *l = &d->leases[idx];
1628 bool do_upgrade;
1629 uint32_t existing, requested;
1631 fsp->lease = find_fsp_lease(fsp, &lease->lease_key, l);
1632 if (fsp->lease == NULL) {
1633 DEBUG(1, ("Did not find existing lease for file %s\n",
1634 fsp_str_dbg(fsp)));
1635 return NT_STATUS_NO_MEMORY;
1638 *p_lease_idx = idx;
1641 * Upgrade only if the requested lease is a strict upgrade.
1643 existing = l->current_state;
1644 requested = lease->lease_state;
1647 * Tricky: This test makes sure that "requested" is a
1648 * strict bitwise superset of "existing".
1650 do_upgrade = ((existing & requested) == existing);
1653 * Upgrade only if there's a change.
1655 do_upgrade &= (granted != existing);
1658 * Upgrade only if other leases don't prevent what was asked
1659 * for.
1661 do_upgrade &= (granted == requested);
1664 * only upgrade if we are not in breaking state
1666 do_upgrade &= !l->breaking;
1668 DEBUG(10, ("existing=%"PRIu32", requested=%"PRIu32", "
1669 "granted=%"PRIu32", do_upgrade=%d\n",
1670 existing, requested, granted, (int)do_upgrade));
1672 if (do_upgrade) {
1673 l->current_state = granted;
1674 l->epoch += 1;
1677 /* Ensure we're in sync with current lease state. */
1678 fsp_lease_update(lck, fsp_client_guid(fsp), fsp->lease);
1679 return NT_STATUS_OK;
1683 * Create new lease
1686 tmp = talloc_realloc(d, d->leases, struct share_mode_lease,
1687 d->num_leases+1);
1688 if (tmp == NULL) {
1690 * See [MS-SMB2]
1692 return NT_STATUS_INSUFFICIENT_RESOURCES;
1694 d->leases = tmp;
1696 fsp->lease = talloc_zero(fsp->conn->sconn, struct fsp_lease);
1697 if (fsp->lease == NULL) {
1698 return NT_STATUS_INSUFFICIENT_RESOURCES;
1700 fsp->lease->ref_count = 1;
1701 fsp->lease->sconn = fsp->conn->sconn;
1702 fsp->lease->lease.lease_version = lease->lease_version;
1703 fsp->lease->lease.lease_key = lease->lease_key;
1704 fsp->lease->lease.lease_state = granted;
1705 fsp->lease->lease.lease_epoch = lease->lease_epoch + 1;
1707 *p_lease_idx = d->num_leases;
1709 d->leases[d->num_leases] = (struct share_mode_lease) {
1710 .client_guid = *client_guid,
1711 .lease_key = fsp->lease->lease.lease_key,
1712 .current_state = fsp->lease->lease.lease_state,
1713 .lease_version = fsp->lease->lease.lease_version,
1714 .epoch = fsp->lease->lease.lease_epoch,
1717 status = leases_db_add(client_guid,
1718 &lease->lease_key,
1719 &fsp->file_id,
1720 fsp->conn->connectpath,
1721 fsp->fsp_name->base_name,
1722 fsp->fsp_name->stream_name);
1723 if (!NT_STATUS_IS_OK(status)) {
1724 DEBUG(10, ("%s: leases_db_add failed: %s\n", __func__,
1725 nt_errstr(status)));
1726 TALLOC_FREE(fsp->lease);
1727 return NT_STATUS_INSUFFICIENT_RESOURCES;
1730 d->num_leases += 1;
1731 d->modified = true;
1733 return NT_STATUS_OK;
1736 static bool is_same_lease(const files_struct *fsp,
1737 const struct share_mode_data *d,
1738 const struct share_mode_entry *e,
1739 const struct smb2_lease *lease)
1741 if (e->op_type != LEASE_OPLOCK) {
1742 return false;
1744 if (lease == NULL) {
1745 return false;
1748 return smb2_lease_equal(fsp_client_guid(fsp),
1749 &lease->lease_key,
1750 &d->leases[e->lease_idx].client_guid,
1751 &d->leases[e->lease_idx].lease_key);
1754 static NTSTATUS grant_fsp_oplock_type(struct smb_request *req,
1755 struct files_struct *fsp,
1756 struct share_mode_lock *lck,
1757 int oplock_request,
1758 struct smb2_lease *lease)
1760 struct share_mode_data *d = lck->data;
1761 bool got_handle_lease = false;
1762 bool got_oplock = false;
1763 uint32_t i;
1764 uint32_t granted;
1765 uint32_t lease_idx = UINT32_MAX;
1766 bool ok;
1767 NTSTATUS status;
1769 if (oplock_request & INTERNAL_OPEN_ONLY) {
1770 /* No oplocks on internal open. */
1771 oplock_request = NO_OPLOCK;
1772 DEBUG(10,("grant_fsp_oplock_type: oplock type 0x%x on file %s\n",
1773 fsp->oplock_type, fsp_str_dbg(fsp)));
1776 if (oplock_request == LEASE_OPLOCK) {
1777 if (lease == NULL) {
1779 * The SMB2 layer should have checked this
1781 return NT_STATUS_INTERNAL_ERROR;
1784 granted = lease->lease_state;
1786 if (lp_kernel_oplocks(SNUM(fsp->conn))) {
1787 DEBUG(10, ("No lease granted because kernel oplocks are enabled\n"));
1788 granted = SMB2_LEASE_NONE;
1790 if ((granted & (SMB2_LEASE_READ|SMB2_LEASE_WRITE)) == 0) {
1791 DEBUG(10, ("No read or write lease requested\n"));
1792 granted = SMB2_LEASE_NONE;
1794 if (granted == SMB2_LEASE_WRITE) {
1795 DEBUG(10, ("pure write lease requested\n"));
1796 granted = SMB2_LEASE_NONE;
1798 if (granted == (SMB2_LEASE_WRITE|SMB2_LEASE_HANDLE)) {
1799 DEBUG(10, ("write and handle lease requested\n"));
1800 granted = SMB2_LEASE_NONE;
1802 } else {
1803 granted = map_oplock_to_lease_type(
1804 oplock_request & ~SAMBA_PRIVATE_OPLOCK_MASK);
1807 if (lp_locking(fsp->conn->params) && file_has_brlocks(fsp)) {
1808 DEBUG(10,("grant_fsp_oplock_type: file %s has byte range locks\n",
1809 fsp_str_dbg(fsp)));
1810 granted &= ~SMB2_LEASE_READ;
1813 for (i=0; i<d->num_share_modes; i++) {
1814 struct share_mode_entry *e = &d->share_modes[i];
1815 uint32_t e_lease_type;
1817 e_lease_type = get_lease_type(d, e);
1819 if ((granted & SMB2_LEASE_WRITE) &&
1820 !is_same_lease(fsp, d, e, lease) &&
1821 !share_mode_stale_pid(d, i)) {
1823 * Can grant only one writer
1825 granted &= ~SMB2_LEASE_WRITE;
1828 if ((e_lease_type & SMB2_LEASE_HANDLE) && !got_handle_lease &&
1829 !share_mode_stale_pid(d, i)) {
1830 got_handle_lease = true;
1833 if ((e->op_type != LEASE_OPLOCK) && !got_oplock &&
1834 !share_mode_stale_pid(d, i)) {
1835 got_oplock = true;
1839 if ((granted & SMB2_LEASE_READ) && !(granted & SMB2_LEASE_WRITE)) {
1840 bool allow_level2 =
1841 (global_client_caps & CAP_LEVEL_II_OPLOCKS) &&
1842 lp_level2_oplocks(SNUM(fsp->conn));
1844 if (!allow_level2) {
1845 granted = SMB2_LEASE_NONE;
1849 if (oplock_request == LEASE_OPLOCK) {
1850 if (got_oplock) {
1851 granted &= ~SMB2_LEASE_HANDLE;
1854 fsp->oplock_type = LEASE_OPLOCK;
1856 status = grant_fsp_lease(fsp, lck, lease, &lease_idx,
1857 granted);
1858 if (!NT_STATUS_IS_OK(status)) {
1859 return status;
1862 *lease = fsp->lease->lease;
1863 DEBUG(10, ("lease_state=%d\n", lease->lease_state));
1864 } else {
1865 if (got_handle_lease) {
1866 granted = SMB2_LEASE_NONE;
1869 switch (granted) {
1870 case SMB2_LEASE_READ|SMB2_LEASE_WRITE|SMB2_LEASE_HANDLE:
1871 fsp->oplock_type = BATCH_OPLOCK|EXCLUSIVE_OPLOCK;
1872 break;
1873 case SMB2_LEASE_READ|SMB2_LEASE_WRITE:
1874 fsp->oplock_type = EXCLUSIVE_OPLOCK;
1875 break;
1876 case SMB2_LEASE_READ|SMB2_LEASE_HANDLE:
1877 case SMB2_LEASE_READ:
1878 fsp->oplock_type = LEVEL_II_OPLOCK;
1879 break;
1880 default:
1881 fsp->oplock_type = NO_OPLOCK;
1882 break;
1885 status = set_file_oplock(fsp);
1886 if (!NT_STATUS_IS_OK(status)) {
1888 * Could not get the kernel oplock
1890 fsp->oplock_type = NO_OPLOCK;
1894 ok = set_share_mode(lck, fsp, get_current_uid(fsp->conn),
1895 req ? req->mid : 0,
1896 fsp->oplock_type,
1897 lease_idx);
1898 if (!ok) {
1899 return NT_STATUS_NO_MEMORY;
1902 ok = update_num_read_oplocks(fsp, lck);
1903 if (!ok) {
1904 del_share_mode(lck, fsp);
1905 return NT_STATUS_INTERNAL_ERROR;
1908 DEBUG(10,("grant_fsp_oplock_type: oplock type 0x%x on file %s\n",
1909 fsp->oplock_type, fsp_str_dbg(fsp)));
1911 return NT_STATUS_OK;
1914 static bool request_timed_out(struct timeval request_time,
1915 struct timeval timeout)
1917 struct timeval now, end_time;
1918 GetTimeOfDay(&now);
1919 end_time = timeval_sum(&request_time, &timeout);
1920 return (timeval_compare(&end_time, &now) < 0);
1923 static struct deferred_open_record *deferred_open_record_create(
1924 bool delayed_for_oplocks,
1925 bool async_open,
1926 struct file_id id)
1928 struct deferred_open_record *record = NULL;
1930 record = talloc(NULL, struct deferred_open_record);
1931 if (record == NULL) {
1932 return NULL;
1935 *record = (struct deferred_open_record) {
1936 .delayed_for_oplocks = delayed_for_oplocks,
1937 .async_open = async_open,
1938 .id = id,
1941 return record;
1944 struct defer_open_state {
1945 struct smbXsrv_connection *xconn;
1946 uint64_t mid;
1949 static void defer_open_done(struct tevent_req *req);
1951 /****************************************************************************
1952 Handle the 1 second delay in returning a SHARING_VIOLATION error.
1953 ****************************************************************************/
1955 static void defer_open(struct share_mode_lock *lck,
1956 struct timeval request_time,
1957 struct timeval timeout,
1958 struct smb_request *req,
1959 bool delayed_for_oplocks,
1960 bool async_open,
1961 struct file_id id)
1963 struct deferred_open_record *open_rec = NULL;
1964 struct timeval abs_timeout;
1966 abs_timeout = timeval_sum(&request_time, &timeout);
1968 DBG_DEBUG("request time [%s] timeout [%s] mid [%" PRIu64 "] "
1969 "delayed_for_oplocks [%s] async_open [%s] file_id [%s]\n",
1970 timeval_string(talloc_tos(), &request_time, false),
1971 timeval_string(talloc_tos(), &abs_timeout, false),
1972 req->mid,
1973 delayed_for_oplocks ? "yes" : "no",
1974 async_open ? "yes" : "no",
1975 file_id_string_tos(&id));
1977 open_rec = deferred_open_record_create(delayed_for_oplocks,
1978 async_open,
1979 id);
1980 if (open_rec == NULL) {
1981 TALLOC_FREE(lck);
1982 exit_server("talloc failed");
1985 if (lck) {
1986 struct defer_open_state *watch_state;
1987 struct tevent_req *watch_req;
1988 bool ret;
1990 watch_state = talloc(open_rec, struct defer_open_state);
1991 if (watch_state == NULL) {
1992 exit_server("talloc failed");
1994 watch_state->xconn = req->xconn;
1995 watch_state->mid = req->mid;
1997 DEBUG(10, ("defering mid %llu\n",
1998 (unsigned long long)req->mid));
2000 watch_req = dbwrap_record_watch_send(
2001 watch_state, req->sconn->ev_ctx, lck->data->record,
2002 req->sconn->msg_ctx);
2003 if (watch_req == NULL) {
2004 exit_server("Could not watch share mode record");
2006 tevent_req_set_callback(watch_req, defer_open_done,
2007 watch_state);
2009 ret = tevent_req_set_endtime(
2010 watch_req, req->sconn->ev_ctx,
2011 abs_timeout);
2012 SMB_ASSERT(ret);
2015 if (!push_deferred_open_message_smb(req, request_time, timeout,
2016 open_rec->id, open_rec)) {
2017 TALLOC_FREE(lck);
2018 exit_server("push_deferred_open_message_smb failed");
2022 static void defer_open_done(struct tevent_req *req)
2024 struct defer_open_state *state = tevent_req_callback_data(
2025 req, struct defer_open_state);
2026 NTSTATUS status;
2027 bool ret;
2029 status = dbwrap_record_watch_recv(req, talloc_tos(), NULL);
2030 TALLOC_FREE(req);
2031 if (!NT_STATUS_IS_OK(status)) {
2032 DEBUG(5, ("dbwrap_record_watch_recv returned %s\n",
2033 nt_errstr(status)));
2035 * Even if it failed, retry anyway. TODO: We need a way to
2036 * tell a re-scheduled open about that error.
2040 DEBUG(10, ("scheduling mid %llu\n", (unsigned long long)state->mid));
2042 ret = schedule_deferred_open_message_smb(state->xconn, state->mid);
2043 SMB_ASSERT(ret);
2044 TALLOC_FREE(state);
2048 * Reschedule an open for immediate execution
2050 static void retry_open(struct timeval request_time,
2051 struct smb_request *req,
2052 struct file_id id)
2054 struct deferred_open_record *open_rec = NULL;
2055 bool ok;
2057 DBG_DEBUG("request time [%s] mid [%" PRIu64 "] file_id [%s]\n",
2058 timeval_string(talloc_tos(), &request_time, false),
2059 req->mid,
2060 file_id_string_tos(&id));
2062 open_rec = deferred_open_record_create(false, false, id);
2063 if (open_rec == NULL) {
2064 exit_server("talloc failed");
2067 ok = push_deferred_open_message_smb(req,
2068 request_time,
2069 timeval_set(0, 0),
2071 open_rec);
2072 if (!ok) {
2073 exit_server("push_deferred_open_message_smb failed");
2076 ok = schedule_deferred_open_message_smb(req->xconn, req->mid);
2077 if (!ok) {
2078 exit_server("schedule_deferred_open_message_smb failed");
2082 /****************************************************************************
2083 On overwrite open ensure that the attributes match.
2084 ****************************************************************************/
2086 static bool open_match_attributes(connection_struct *conn,
2087 uint32_t old_dos_attr,
2088 uint32_t new_dos_attr,
2089 mode_t existing_unx_mode,
2090 mode_t new_unx_mode,
2091 mode_t *returned_unx_mode)
2093 uint32_t noarch_old_dos_attr, noarch_new_dos_attr;
2095 noarch_old_dos_attr = (old_dos_attr & ~FILE_ATTRIBUTE_ARCHIVE);
2096 noarch_new_dos_attr = (new_dos_attr & ~FILE_ATTRIBUTE_ARCHIVE);
2098 if((noarch_old_dos_attr == 0 && noarch_new_dos_attr != 0) ||
2099 (noarch_old_dos_attr != 0 && ((noarch_old_dos_attr & noarch_new_dos_attr) == noarch_old_dos_attr))) {
2100 *returned_unx_mode = new_unx_mode;
2101 } else {
2102 *returned_unx_mode = (mode_t)0;
2105 DEBUG(10,("open_match_attributes: old_dos_attr = 0x%x, "
2106 "existing_unx_mode = 0%o, new_dos_attr = 0x%x "
2107 "returned_unx_mode = 0%o\n",
2108 (unsigned int)old_dos_attr,
2109 (unsigned int)existing_unx_mode,
2110 (unsigned int)new_dos_attr,
2111 (unsigned int)*returned_unx_mode ));
2113 /* If we're mapping SYSTEM and HIDDEN ensure they match. */
2114 if (lp_map_system(SNUM(conn)) || lp_store_dos_attributes(SNUM(conn))) {
2115 if ((old_dos_attr & FILE_ATTRIBUTE_SYSTEM) &&
2116 !(new_dos_attr & FILE_ATTRIBUTE_SYSTEM)) {
2117 return False;
2120 if (lp_map_hidden(SNUM(conn)) || lp_store_dos_attributes(SNUM(conn))) {
2121 if ((old_dos_attr & FILE_ATTRIBUTE_HIDDEN) &&
2122 !(new_dos_attr & FILE_ATTRIBUTE_HIDDEN)) {
2123 return False;
2126 return True;
2129 /****************************************************************************
2130 Special FCB or DOS processing in the case of a sharing violation.
2131 Try and find a duplicated file handle.
2132 ****************************************************************************/
2134 static NTSTATUS fcb_or_dos_open(struct smb_request *req,
2135 connection_struct *conn,
2136 files_struct *fsp_to_dup_into,
2137 const struct smb_filename *smb_fname,
2138 struct file_id id,
2139 uint16_t file_pid,
2140 uint64_t vuid,
2141 uint32_t access_mask,
2142 uint32_t share_access,
2143 uint32_t create_options)
2145 files_struct *fsp;
2147 DEBUG(5,("fcb_or_dos_open: attempting old open semantics for "
2148 "file %s.\n", smb_fname_str_dbg(smb_fname)));
2150 for(fsp = file_find_di_first(conn->sconn, id); fsp;
2151 fsp = file_find_di_next(fsp)) {
2153 DEBUG(10,("fcb_or_dos_open: checking file %s, fd = %d, "
2154 "vuid = %llu, file_pid = %u, private_options = 0x%x "
2155 "access_mask = 0x%x\n", fsp_str_dbg(fsp),
2156 fsp->fh->fd, (unsigned long long)fsp->vuid,
2157 (unsigned int)fsp->file_pid,
2158 (unsigned int)fsp->fh->private_options,
2159 (unsigned int)fsp->access_mask ));
2161 if (fsp != fsp_to_dup_into &&
2162 fsp->fh->fd != -1 &&
2163 fsp->vuid == vuid &&
2164 fsp->file_pid == file_pid &&
2165 (fsp->fh->private_options & (NTCREATEX_OPTIONS_PRIVATE_DENY_DOS |
2166 NTCREATEX_OPTIONS_PRIVATE_DENY_FCB)) &&
2167 (fsp->access_mask & FILE_WRITE_DATA) &&
2168 strequal(fsp->fsp_name->base_name, smb_fname->base_name) &&
2169 strequal(fsp->fsp_name->stream_name,
2170 smb_fname->stream_name)) {
2171 DEBUG(10,("fcb_or_dos_open: file match\n"));
2172 break;
2176 if (!fsp) {
2177 return NT_STATUS_NOT_FOUND;
2180 /* quite an insane set of semantics ... */
2181 if (is_executable(smb_fname->base_name) &&
2182 (fsp->fh->private_options & NTCREATEX_OPTIONS_PRIVATE_DENY_DOS)) {
2183 DEBUG(10,("fcb_or_dos_open: file fail due to is_executable.\n"));
2184 return NT_STATUS_INVALID_PARAMETER;
2187 /* We need to duplicate this fsp. */
2188 return dup_file_fsp(req, fsp, access_mask, share_access,
2189 create_options, fsp_to_dup_into);
2192 static void schedule_defer_open(struct share_mode_lock *lck,
2193 struct file_id id,
2194 struct timeval request_time,
2195 struct smb_request *req)
2197 /* This is a relative time, added to the absolute
2198 request_time value to get the absolute timeout time.
2199 Note that if this is the second or greater time we enter
2200 this codepath for this particular request mid then
2201 request_time is left as the absolute time of the *first*
2202 time this request mid was processed. This is what allows
2203 the request to eventually time out. */
2205 struct timeval timeout;
2207 /* Normally the smbd we asked should respond within
2208 * OPLOCK_BREAK_TIMEOUT seconds regardless of whether
2209 * the client did, give twice the timeout as a safety
2210 * measure here in case the other smbd is stuck
2211 * somewhere else. */
2213 timeout = timeval_set(OPLOCK_BREAK_TIMEOUT*2, 0);
2215 if (request_timed_out(request_time, timeout)) {
2216 return;
2219 defer_open(lck, request_time, timeout, req, true, false, id);
2222 /****************************************************************************
2223 Reschedule an open call that went asynchronous.
2224 ****************************************************************************/
2226 static void schedule_async_open_timer(struct tevent_context *ev,
2227 struct tevent_timer *te,
2228 struct timeval current_time,
2229 void *private_data)
2231 exit_server("async open timeout");
2234 static void schedule_async_open(struct timeval request_time,
2235 struct smb_request *req)
2237 struct deferred_open_record *open_rec = NULL;
2238 struct timeval timeout = timeval_set(20, 0);
2239 bool ok;
2241 if (request_timed_out(request_time, timeout)) {
2242 return;
2245 open_rec = deferred_open_record_create(false, true, (struct file_id){0});
2246 if (open_rec == NULL) {
2247 exit_server("deferred_open_record_create failed");
2250 ok = push_deferred_open_message_smb(req, request_time, timeout,
2251 (struct file_id){0}, open_rec);
2252 if (!ok) {
2253 exit_server("push_deferred_open_message_smb failed");
2256 open_rec->te = tevent_add_timer(req->sconn->ev_ctx,
2257 req,
2258 timeval_current_ofs(20, 0),
2259 schedule_async_open_timer,
2260 open_rec);
2261 if (open_rec->te == NULL) {
2262 exit_server("tevent_add_timer failed");
2266 /****************************************************************************
2267 Work out what access_mask to use from what the client sent us.
2268 ****************************************************************************/
2270 static NTSTATUS smbd_calculate_maximum_allowed_access(
2271 connection_struct *conn,
2272 const struct smb_filename *smb_fname,
2273 bool use_privs,
2274 uint32_t *p_access_mask)
2276 struct security_descriptor *sd;
2277 uint32_t access_granted;
2278 NTSTATUS status;
2280 if (!use_privs && (get_current_uid(conn) == (uid_t)0)) {
2281 *p_access_mask |= FILE_GENERIC_ALL;
2282 return NT_STATUS_OK;
2285 status = SMB_VFS_GET_NT_ACL(conn, smb_fname->base_name,
2286 (SECINFO_OWNER |
2287 SECINFO_GROUP |
2288 SECINFO_DACL),
2289 talloc_tos(), &sd);
2291 if (NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
2293 * File did not exist
2295 *p_access_mask = FILE_GENERIC_ALL;
2296 return NT_STATUS_OK;
2298 if (!NT_STATUS_IS_OK(status)) {
2299 DEBUG(10,("Could not get acl on file %s: %s\n",
2300 smb_fname_str_dbg(smb_fname),
2301 nt_errstr(status)));
2302 return NT_STATUS_ACCESS_DENIED;
2306 * If we can access the path to this file, by
2307 * default we have FILE_READ_ATTRIBUTES from the
2308 * containing directory. See the section:
2309 * "Algorithm to Check Access to an Existing File"
2310 * in MS-FSA.pdf.
2312 * se_file_access_check()
2313 * also takes care of owner WRITE_DAC and READ_CONTROL.
2315 status = se_file_access_check(sd,
2316 get_current_nttok(conn),
2317 use_privs,
2318 (*p_access_mask & ~FILE_READ_ATTRIBUTES),
2319 &access_granted);
2321 TALLOC_FREE(sd);
2323 if (!NT_STATUS_IS_OK(status)) {
2324 DEBUG(10, ("Access denied on file %s: "
2325 "when calculating maximum access\n",
2326 smb_fname_str_dbg(smb_fname)));
2327 return NT_STATUS_ACCESS_DENIED;
2329 *p_access_mask = (access_granted | FILE_READ_ATTRIBUTES);
2331 if (!(access_granted & DELETE_ACCESS)) {
2332 if (can_delete_file_in_directory(conn, smb_fname)) {
2333 *p_access_mask |= DELETE_ACCESS;
2337 return NT_STATUS_OK;
2340 NTSTATUS smbd_calculate_access_mask(connection_struct *conn,
2341 const struct smb_filename *smb_fname,
2342 bool use_privs,
2343 uint32_t access_mask,
2344 uint32_t *access_mask_out)
2346 NTSTATUS status;
2347 uint32_t orig_access_mask = access_mask;
2348 uint32_t rejected_share_access;
2350 if (access_mask & SEC_MASK_INVALID) {
2351 DBG_DEBUG("access_mask [%8x] contains invalid bits\n",
2352 access_mask);
2353 return NT_STATUS_ACCESS_DENIED;
2357 * Convert GENERIC bits to specific bits.
2360 se_map_generic(&access_mask, &file_generic_mapping);
2362 /* Calculate MAXIMUM_ALLOWED_ACCESS if requested. */
2363 if (access_mask & MAXIMUM_ALLOWED_ACCESS) {
2365 status = smbd_calculate_maximum_allowed_access(
2366 conn, smb_fname, use_privs, &access_mask);
2368 if (!NT_STATUS_IS_OK(status)) {
2369 return status;
2372 access_mask &= conn->share_access;
2375 rejected_share_access = access_mask & ~(conn->share_access);
2377 if (rejected_share_access) {
2378 DEBUG(10, ("smbd_calculate_access_mask: Access denied on "
2379 "file %s: rejected by share access mask[0x%08X] "
2380 "orig[0x%08X] mapped[0x%08X] reject[0x%08X]\n",
2381 smb_fname_str_dbg(smb_fname),
2382 conn->share_access,
2383 orig_access_mask, access_mask,
2384 rejected_share_access));
2385 return NT_STATUS_ACCESS_DENIED;
2388 *access_mask_out = access_mask;
2389 return NT_STATUS_OK;
2392 /****************************************************************************
2393 Remove the deferred open entry under lock.
2394 ****************************************************************************/
2396 /****************************************************************************
2397 Return true if this is a state pointer to an asynchronous create.
2398 ****************************************************************************/
2400 bool is_deferred_open_async(const struct deferred_open_record *rec)
2402 return rec->async_open;
2405 static bool clear_ads(uint32_t create_disposition)
2407 bool ret = false;
2409 switch (create_disposition) {
2410 case FILE_SUPERSEDE:
2411 case FILE_OVERWRITE_IF:
2412 case FILE_OVERWRITE:
2413 ret = true;
2414 break;
2415 default:
2416 break;
2418 return ret;
2421 static int disposition_to_open_flags(uint32_t create_disposition)
2423 int ret = 0;
2426 * Currently we're using FILE_SUPERSEDE as the same as
2427 * FILE_OVERWRITE_IF but they really are
2428 * different. FILE_SUPERSEDE deletes an existing file
2429 * (requiring delete access) then recreates it.
2432 switch (create_disposition) {
2433 case FILE_SUPERSEDE:
2434 case FILE_OVERWRITE_IF:
2436 * If file exists replace/overwrite. If file doesn't
2437 * exist create.
2439 ret = O_CREAT|O_TRUNC;
2440 break;
2442 case FILE_OPEN:
2444 * If file exists open. If file doesn't exist error.
2446 ret = 0;
2447 break;
2449 case FILE_OVERWRITE:
2451 * If file exists overwrite. If file doesn't exist
2452 * error.
2454 ret = O_TRUNC;
2455 break;
2457 case FILE_CREATE:
2459 * If file exists error. If file doesn't exist create.
2461 ret = O_CREAT|O_EXCL;
2462 break;
2464 case FILE_OPEN_IF:
2466 * If file exists open. If file doesn't exist create.
2468 ret = O_CREAT;
2469 break;
2471 return ret;
2474 static int calculate_open_access_flags(uint32_t access_mask,
2475 uint32_t private_flags)
2477 bool need_write, need_read;
2480 * Note that we ignore the append flag as append does not
2481 * mean the same thing under DOS and Unix.
2484 need_write = (access_mask & (FILE_WRITE_DATA | FILE_APPEND_DATA));
2485 if (!need_write) {
2486 return O_RDONLY;
2489 /* DENY_DOS opens are always underlying read-write on the
2490 file handle, no matter what the requested access mask
2491 says. */
2493 need_read =
2494 ((private_flags & NTCREATEX_OPTIONS_PRIVATE_DENY_DOS) ||
2495 access_mask & (FILE_READ_ATTRIBUTES|FILE_READ_DATA|
2496 FILE_READ_EA|FILE_EXECUTE));
2498 if (!need_read) {
2499 return O_WRONLY;
2501 return O_RDWR;
2504 /****************************************************************************
2505 Open a file with a share mode. Passed in an already created files_struct *.
2506 ****************************************************************************/
2508 static NTSTATUS open_file_ntcreate(connection_struct *conn,
2509 struct smb_request *req,
2510 uint32_t access_mask, /* access bits (FILE_READ_DATA etc.) */
2511 uint32_t share_access, /* share constants (FILE_SHARE_READ etc) */
2512 uint32_t create_disposition, /* FILE_OPEN_IF etc. */
2513 uint32_t create_options, /* options such as delete on close. */
2514 uint32_t new_dos_attributes, /* attributes used for new file. */
2515 int oplock_request, /* internal Samba oplock codes. */
2516 struct smb2_lease *lease,
2517 /* Information (FILE_EXISTS etc.) */
2518 uint32_t private_flags, /* Samba specific flags. */
2519 int *pinfo,
2520 files_struct *fsp)
2522 struct smb_filename *smb_fname = fsp->fsp_name;
2523 int flags=0;
2524 int flags2=0;
2525 bool file_existed = VALID_STAT(smb_fname->st);
2526 bool def_acl = False;
2527 bool posix_open = False;
2528 bool new_file_created = False;
2529 bool first_open_attempt = true;
2530 NTSTATUS fsp_open = NT_STATUS_ACCESS_DENIED;
2531 mode_t new_unx_mode = (mode_t)0;
2532 mode_t unx_mode = (mode_t)0;
2533 int info;
2534 uint32_t existing_dos_attributes = 0;
2535 struct timeval request_time = timeval_zero();
2536 struct share_mode_lock *lck = NULL;
2537 uint32_t open_access_mask = access_mask;
2538 NTSTATUS status;
2539 char *parent_dir;
2540 SMB_STRUCT_STAT saved_stat = smb_fname->st;
2541 struct timespec old_write_time;
2542 struct file_id id;
2544 if (conn->printer) {
2546 * Printers are handled completely differently.
2547 * Most of the passed parameters are ignored.
2550 if (pinfo) {
2551 *pinfo = FILE_WAS_CREATED;
2554 DEBUG(10, ("open_file_ntcreate: printer open fname=%s\n",
2555 smb_fname_str_dbg(smb_fname)));
2557 if (!req) {
2558 DEBUG(0,("open_file_ntcreate: printer open without "
2559 "an SMB request!\n"));
2560 return NT_STATUS_INTERNAL_ERROR;
2563 return print_spool_open(fsp, smb_fname->base_name,
2564 req->vuid);
2567 if (!parent_dirname(talloc_tos(), smb_fname->base_name, &parent_dir,
2568 NULL)) {
2569 return NT_STATUS_NO_MEMORY;
2572 if (new_dos_attributes & FILE_FLAG_POSIX_SEMANTICS) {
2573 posix_open = True;
2574 unx_mode = (mode_t)(new_dos_attributes & ~FILE_FLAG_POSIX_SEMANTICS);
2575 new_dos_attributes = 0;
2576 } else {
2577 /* Windows allows a new file to be created and
2578 silently removes a FILE_ATTRIBUTE_DIRECTORY
2579 sent by the client. Do the same. */
2581 new_dos_attributes &= ~FILE_ATTRIBUTE_DIRECTORY;
2583 /* We add FILE_ATTRIBUTE_ARCHIVE to this as this mode is only used if the file is
2584 * created new. */
2585 unx_mode = unix_mode(conn, new_dos_attributes | FILE_ATTRIBUTE_ARCHIVE,
2586 smb_fname, parent_dir);
2589 DEBUG(10, ("open_file_ntcreate: fname=%s, dos_attrs=0x%x "
2590 "access_mask=0x%x share_access=0x%x "
2591 "create_disposition = 0x%x create_options=0x%x "
2592 "unix mode=0%o oplock_request=%d private_flags = 0x%x\n",
2593 smb_fname_str_dbg(smb_fname), new_dos_attributes,
2594 access_mask, share_access, create_disposition,
2595 create_options, (unsigned int)unx_mode, oplock_request,
2596 (unsigned int)private_flags));
2598 if (req == NULL) {
2599 /* Ensure req == NULL means INTERNAL_OPEN_ONLY */
2600 SMB_ASSERT(((oplock_request & INTERNAL_OPEN_ONLY) != 0));
2601 } else {
2602 /* And req != NULL means no INTERNAL_OPEN_ONLY */
2603 SMB_ASSERT(((oplock_request & INTERNAL_OPEN_ONLY) == 0));
2607 * Only non-internal opens can be deferred at all
2610 if (req) {
2611 struct deferred_open_record *open_rec;
2612 if (get_deferred_open_message_state(req,
2613 &request_time,
2614 &open_rec)) {
2615 /* Remember the absolute time of the original
2616 request with this mid. We'll use it later to
2617 see if this has timed out. */
2619 /* If it was an async create retry, the file
2620 didn't exist. */
2622 if (is_deferred_open_async(open_rec)) {
2623 SET_STAT_INVALID(smb_fname->st);
2624 file_existed = false;
2627 /* Ensure we don't reprocess this message. */
2628 remove_deferred_open_message_smb(req->xconn, req->mid);
2630 first_open_attempt = false;
2634 if (!posix_open) {
2635 new_dos_attributes &= SAMBA_ATTRIBUTES_MASK;
2636 if (file_existed) {
2638 * Only use strored DOS attributes for checks
2639 * against requested attributes (below via
2640 * open_match_attributes()), cf bug #11992
2641 * for details. -slow
2643 bool ok;
2644 uint32_t attr = 0;
2646 ok = get_ea_dos_attribute(conn, smb_fname, &attr);
2647 if (ok) {
2648 existing_dos_attributes = attr;
2653 /* ignore any oplock requests if oplocks are disabled */
2654 if (!lp_oplocks(SNUM(conn)) ||
2655 IS_VETO_OPLOCK_PATH(conn, smb_fname->base_name)) {
2656 /* Mask off everything except the private Samba bits. */
2657 oplock_request &= SAMBA_PRIVATE_OPLOCK_MASK;
2660 /* this is for OS/2 long file names - say we don't support them */
2661 if (req != NULL && !req->posix_pathnames &&
2662 strstr(smb_fname->base_name,".+,;=[].")) {
2663 /* OS/2 Workplace shell fix may be main code stream in a later
2664 * release. */
2665 DEBUG(5,("open_file_ntcreate: OS/2 long filenames are not "
2666 "supported.\n"));
2667 if (use_nt_status()) {
2668 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
2670 return NT_STATUS_DOS(ERRDOS, ERRcannotopen);
2673 switch( create_disposition ) {
2674 case FILE_OPEN:
2675 /* If file exists open. If file doesn't exist error. */
2676 if (!file_existed) {
2677 DEBUG(5,("open_file_ntcreate: FILE_OPEN "
2678 "requested for file %s and file "
2679 "doesn't exist.\n",
2680 smb_fname_str_dbg(smb_fname)));
2681 errno = ENOENT;
2682 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
2684 break;
2686 case FILE_OVERWRITE:
2687 /* If file exists overwrite. If file doesn't exist
2688 * error. */
2689 if (!file_existed) {
2690 DEBUG(5,("open_file_ntcreate: FILE_OVERWRITE "
2691 "requested for file %s and file "
2692 "doesn't exist.\n",
2693 smb_fname_str_dbg(smb_fname) ));
2694 errno = ENOENT;
2695 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
2697 break;
2699 case FILE_CREATE:
2700 /* If file exists error. If file doesn't exist
2701 * create. */
2702 if (file_existed) {
2703 DEBUG(5,("open_file_ntcreate: FILE_CREATE "
2704 "requested for file %s and file "
2705 "already exists.\n",
2706 smb_fname_str_dbg(smb_fname)));
2707 if (S_ISDIR(smb_fname->st.st_ex_mode)) {
2708 errno = EISDIR;
2709 } else {
2710 errno = EEXIST;
2712 return map_nt_error_from_unix(errno);
2714 break;
2716 case FILE_SUPERSEDE:
2717 case FILE_OVERWRITE_IF:
2718 case FILE_OPEN_IF:
2719 break;
2720 default:
2721 return NT_STATUS_INVALID_PARAMETER;
2724 flags2 = disposition_to_open_flags(create_disposition);
2726 /* We only care about matching attributes on file exists and
2727 * overwrite. */
2729 if (!posix_open && file_existed &&
2730 ((create_disposition == FILE_OVERWRITE) ||
2731 (create_disposition == FILE_OVERWRITE_IF))) {
2732 if (!open_match_attributes(conn, existing_dos_attributes,
2733 new_dos_attributes,
2734 smb_fname->st.st_ex_mode,
2735 unx_mode, &new_unx_mode)) {
2736 DEBUG(5,("open_file_ntcreate: attributes missmatch "
2737 "for file %s (%x %x) (0%o, 0%o)\n",
2738 smb_fname_str_dbg(smb_fname),
2739 existing_dos_attributes,
2740 new_dos_attributes,
2741 (unsigned int)smb_fname->st.st_ex_mode,
2742 (unsigned int)unx_mode ));
2743 errno = EACCES;
2744 return NT_STATUS_ACCESS_DENIED;
2748 status = smbd_calculate_access_mask(conn, smb_fname,
2749 false,
2750 access_mask,
2751 &access_mask);
2752 if (!NT_STATUS_IS_OK(status)) {
2753 DEBUG(10, ("open_file_ntcreate: smbd_calculate_access_mask "
2754 "on file %s returned %s\n",
2755 smb_fname_str_dbg(smb_fname), nt_errstr(status)));
2756 return status;
2759 open_access_mask = access_mask;
2761 if (flags2 & O_TRUNC) {
2762 open_access_mask |= FILE_WRITE_DATA; /* This will cause oplock breaks. */
2765 DEBUG(10, ("open_file_ntcreate: fname=%s, after mapping "
2766 "access_mask=0x%x\n", smb_fname_str_dbg(smb_fname),
2767 access_mask));
2770 * Note that we ignore the append flag as append does not
2771 * mean the same thing under DOS and Unix.
2774 flags = calculate_open_access_flags(access_mask, private_flags);
2777 * Currently we only look at FILE_WRITE_THROUGH for create options.
2780 #if defined(O_SYNC)
2781 if ((create_options & FILE_WRITE_THROUGH) && lp_strict_sync(SNUM(conn))) {
2782 flags2 |= O_SYNC;
2784 #endif /* O_SYNC */
2786 if (posix_open && (access_mask & FILE_APPEND_DATA)) {
2787 flags2 |= O_APPEND;
2790 if (!posix_open && !CAN_WRITE(conn)) {
2792 * We should really return a permission denied error if either
2793 * O_CREAT or O_TRUNC are set, but for compatibility with
2794 * older versions of Samba we just AND them out.
2796 flags2 &= ~(O_CREAT|O_TRUNC);
2799 if (first_open_attempt && lp_kernel_oplocks(SNUM(conn))) {
2801 * With kernel oplocks the open breaking an oplock
2802 * blocks until the oplock holder has given up the
2803 * oplock or closed the file. We prevent this by first
2804 * trying to open the file with O_NONBLOCK (see "man
2805 * fcntl" on Linux). For the second try, triggered by
2806 * an oplock break response, we do not need this
2807 * anymore.
2809 * This is true under the assumption that only Samba
2810 * requests kernel oplocks. Once someone else like
2811 * NFSv4 starts to use that API, we will have to
2812 * modify this by communicating with the NFSv4 server.
2814 flags2 |= O_NONBLOCK;
2818 * Ensure we can't write on a read-only share or file.
2821 if (flags != O_RDONLY && file_existed &&
2822 (!CAN_WRITE(conn) || IS_DOS_READONLY(existing_dos_attributes))) {
2823 DEBUG(5,("open_file_ntcreate: write access requested for "
2824 "file %s on read only %s\n",
2825 smb_fname_str_dbg(smb_fname),
2826 !CAN_WRITE(conn) ? "share" : "file" ));
2827 errno = EACCES;
2828 return NT_STATUS_ACCESS_DENIED;
2831 fsp->file_id = vfs_file_id_from_sbuf(conn, &smb_fname->st);
2832 fsp->share_access = share_access;
2833 fsp->fh->private_options = private_flags;
2834 fsp->access_mask = open_access_mask; /* We change this to the
2835 * requested access_mask after
2836 * the open is done. */
2837 if (posix_open) {
2838 fsp->posix_flags |= FSP_POSIX_FLAGS_ALL;
2841 if (timeval_is_zero(&request_time)) {
2842 request_time = fsp->open_time;
2846 * Ensure we pay attention to default ACLs on directories if required.
2849 if ((flags2 & O_CREAT) && lp_inherit_acls(SNUM(conn)) &&
2850 (def_acl = directory_has_default_acl(conn, parent_dir))) {
2851 unx_mode = (0777 & lp_create_mask(SNUM(conn)));
2854 DEBUG(4,("calling open_file with flags=0x%X flags2=0x%X mode=0%o, "
2855 "access_mask = 0x%x, open_access_mask = 0x%x\n",
2856 (unsigned int)flags, (unsigned int)flags2,
2857 (unsigned int)unx_mode, (unsigned int)access_mask,
2858 (unsigned int)open_access_mask));
2860 fsp_open = open_file(fsp, conn, req, parent_dir,
2861 flags|flags2, unx_mode, access_mask,
2862 open_access_mask, &new_file_created);
2864 if (NT_STATUS_EQUAL(fsp_open, NT_STATUS_NETWORK_BUSY)) {
2865 bool delay;
2868 * This handles the kernel oplock case:
2870 * the file has an active kernel oplock and the open() returned
2871 * EWOULDBLOCK/EAGAIN which maps to NETWORK_BUSY.
2873 * "Samba locking.tdb oplocks" are handled below after acquiring
2874 * the sharemode lock with get_share_mode_lock().
2876 if (file_existed && S_ISFIFO(fsp->fsp_name->st.st_ex_mode)) {
2877 DEBUG(10, ("FIFO busy\n"));
2878 return NT_STATUS_NETWORK_BUSY;
2880 if (req == NULL) {
2881 DEBUG(10, ("Internal open busy\n"));
2882 return NT_STATUS_NETWORK_BUSY;
2886 * From here on we assume this is an oplock break triggered
2889 lck = get_existing_share_mode_lock(talloc_tos(), fsp->file_id);
2890 if (lck == NULL) {
2891 retry_open(request_time, req, fsp->file_id);
2892 DEBUG(10, ("No share mode lock found after "
2893 "EWOULDBLOCK, retrying sync\n"));
2894 return NT_STATUS_SHARING_VIOLATION;
2897 if (!validate_oplock_types(lck)) {
2898 smb_panic("validate_oplock_types failed");
2901 delay = delay_for_oplock(fsp, 0, lease, lck, false,
2902 create_disposition,
2903 first_open_attempt);
2904 if (delay) {
2905 schedule_defer_open(lck, fsp->file_id, request_time,
2906 req);
2907 TALLOC_FREE(lck);
2908 DEBUG(10, ("Sent oplock break request to kernel "
2909 "oplock holder\n"));
2910 return NT_STATUS_SHARING_VIOLATION;
2914 * No oplock from Samba around. Immediately retry with
2915 * a blocking open.
2917 retry_open(request_time, req, fsp->file_id);
2919 TALLOC_FREE(lck);
2920 DEBUG(10, ("No Samba oplock around after EWOULDBLOCK. "
2921 "Retrying sync\n"));
2922 return NT_STATUS_SHARING_VIOLATION;
2925 if (!NT_STATUS_IS_OK(fsp_open)) {
2926 if (NT_STATUS_EQUAL(fsp_open, NT_STATUS_RETRY)) {
2927 schedule_async_open(request_time, req);
2929 return fsp_open;
2932 if (new_file_created) {
2934 * As we atomically create using O_CREAT|O_EXCL,
2935 * then if new_file_created is true, then
2936 * file_existed *MUST* have been false (even
2937 * if the file was previously detected as being
2938 * there).
2940 file_existed = false;
2943 if (file_existed && !check_same_dev_ino(&saved_stat, &smb_fname->st)) {
2945 * The file did exist, but some other (local or NFS)
2946 * process either renamed/unlinked and re-created the
2947 * file with different dev/ino after we walked the path,
2948 * but before we did the open. We could retry the
2949 * open but it's a rare enough case it's easier to
2950 * just fail the open to prevent creating any problems
2951 * in the open file db having the wrong dev/ino key.
2953 fd_close(fsp);
2954 DEBUG(1,("open_file_ntcreate: file %s - dev/ino mismatch. "
2955 "Old (dev=0x%llu, ino =0x%llu). "
2956 "New (dev=0x%llu, ino=0x%llu). Failing open "
2957 " with NT_STATUS_ACCESS_DENIED.\n",
2958 smb_fname_str_dbg(smb_fname),
2959 (unsigned long long)saved_stat.st_ex_dev,
2960 (unsigned long long)saved_stat.st_ex_ino,
2961 (unsigned long long)smb_fname->st.st_ex_dev,
2962 (unsigned long long)smb_fname->st.st_ex_ino));
2963 return NT_STATUS_ACCESS_DENIED;
2966 old_write_time = smb_fname->st.st_ex_mtime;
2969 * Deal with the race condition where two smbd's detect the
2970 * file doesn't exist and do the create at the same time. One
2971 * of them will win and set a share mode, the other (ie. this
2972 * one) should check if the requested share mode for this
2973 * create is allowed.
2977 * Now the file exists and fsp is successfully opened,
2978 * fsp->dev and fsp->inode are valid and should replace the
2979 * dev=0,inode=0 from a non existent file. Spotted by
2980 * Nadav Danieli <nadavd@exanet.com>. JRA.
2983 id = fsp->file_id;
2985 lck = get_share_mode_lock(talloc_tos(), id,
2986 conn->connectpath,
2987 smb_fname, &old_write_time);
2989 if (lck == NULL) {
2990 DEBUG(0, ("open_file_ntcreate: Could not get share "
2991 "mode lock for %s\n",
2992 smb_fname_str_dbg(smb_fname)));
2993 fd_close(fsp);
2994 return NT_STATUS_SHARING_VIOLATION;
2997 /* Get the types we need to examine. */
2998 if (!validate_oplock_types(lck)) {
2999 smb_panic("validate_oplock_types failed");
3002 if (has_delete_on_close(lck, fsp->name_hash)) {
3003 TALLOC_FREE(lck);
3004 fd_close(fsp);
3005 return NT_STATUS_DELETE_PENDING;
3008 status = open_mode_check(conn, lck,
3009 access_mask, share_access);
3011 if (NT_STATUS_EQUAL(status, NT_STATUS_SHARING_VIOLATION) ||
3012 (lck->data->num_share_modes > 0)) {
3014 * This comes from ancient times out of open_mode_check. I
3015 * have no clue whether this is still necessary. I can't think
3016 * of a case where this would actually matter further down in
3017 * this function. I leave it here for further investigation
3018 * :-)
3020 file_existed = true;
3023 if (req != NULL) {
3025 * Handle oplocks, deferring the request if delay_for_oplock()
3026 * triggered a break message and we have to wait for the break
3027 * response.
3029 bool delay;
3030 bool sharing_violation = NT_STATUS_EQUAL(
3031 status, NT_STATUS_SHARING_VIOLATION);
3033 delay = delay_for_oplock(fsp, oplock_request, lease, lck,
3034 sharing_violation,
3035 create_disposition,
3036 first_open_attempt);
3037 if (delay) {
3038 schedule_defer_open(lck, fsp->file_id,
3039 request_time, req);
3040 TALLOC_FREE(lck);
3041 fd_close(fsp);
3042 return NT_STATUS_SHARING_VIOLATION;
3046 if (!NT_STATUS_IS_OK(status)) {
3047 uint32_t can_access_mask;
3048 bool can_access = True;
3050 SMB_ASSERT(NT_STATUS_EQUAL(status, NT_STATUS_SHARING_VIOLATION));
3052 /* Check if this can be done with the deny_dos and fcb
3053 * calls. */
3054 if (private_flags &
3055 (NTCREATEX_OPTIONS_PRIVATE_DENY_DOS|
3056 NTCREATEX_OPTIONS_PRIVATE_DENY_FCB)) {
3057 if (req == NULL) {
3058 DEBUG(0, ("DOS open without an SMB "
3059 "request!\n"));
3060 TALLOC_FREE(lck);
3061 fd_close(fsp);
3062 return NT_STATUS_INTERNAL_ERROR;
3065 /* Use the client requested access mask here,
3066 * not the one we open with. */
3067 status = fcb_or_dos_open(req,
3068 conn,
3069 fsp,
3070 smb_fname,
3072 req->smbpid,
3073 req->vuid,
3074 access_mask,
3075 share_access,
3076 create_options);
3078 if (NT_STATUS_IS_OK(status)) {
3079 TALLOC_FREE(lck);
3080 if (pinfo) {
3081 *pinfo = FILE_WAS_OPENED;
3083 return NT_STATUS_OK;
3088 * This next line is a subtlety we need for
3089 * MS-Access. If a file open will fail due to share
3090 * permissions and also for security (access) reasons,
3091 * we need to return the access failed error, not the
3092 * share error. We can't open the file due to kernel
3093 * oplock deadlock (it's possible we failed above on
3094 * the open_mode_check()) so use a userspace check.
3097 if (flags & O_RDWR) {
3098 can_access_mask = FILE_READ_DATA|FILE_WRITE_DATA;
3099 } else if (flags & O_WRONLY) {
3100 can_access_mask = FILE_WRITE_DATA;
3101 } else {
3102 can_access_mask = FILE_READ_DATA;
3105 if (((can_access_mask & FILE_WRITE_DATA) &&
3106 !CAN_WRITE(conn)) ||
3107 !NT_STATUS_IS_OK(smbd_check_access_rights(conn,
3108 smb_fname,
3109 false,
3110 can_access_mask))) {
3111 can_access = False;
3115 * If we're returning a share violation, ensure we
3116 * cope with the braindead 1 second delay (SMB1 only).
3119 if (!(oplock_request & INTERNAL_OPEN_ONLY) &&
3120 !conn->sconn->using_smb2 &&
3121 lp_defer_sharing_violations()) {
3122 struct timeval timeout;
3123 int timeout_usecs;
3125 /* this is a hack to speed up torture tests
3126 in 'make test' */
3127 timeout_usecs = lp_parm_int(SNUM(conn),
3128 "smbd","sharedelay",
3129 SHARING_VIOLATION_USEC_WAIT);
3131 /* This is a relative time, added to the absolute
3132 request_time value to get the absolute timeout time.
3133 Note that if this is the second or greater time we enter
3134 this codepath for this particular request mid then
3135 request_time is left as the absolute time of the *first*
3136 time this request mid was processed. This is what allows
3137 the request to eventually time out. */
3139 timeout = timeval_set(0, timeout_usecs);
3141 if (!request_timed_out(request_time, timeout)) {
3142 defer_open(lck, request_time, timeout, req,
3143 false, false, id);
3147 TALLOC_FREE(lck);
3148 fd_close(fsp);
3149 if (can_access) {
3151 * We have detected a sharing violation here
3152 * so return the correct error code
3154 status = NT_STATUS_SHARING_VIOLATION;
3155 } else {
3156 status = NT_STATUS_ACCESS_DENIED;
3158 return status;
3161 /* Should we atomically (to the client at least) truncate ? */
3162 if ((!new_file_created) &&
3163 (flags2 & O_TRUNC) &&
3164 (!S_ISFIFO(fsp->fsp_name->st.st_ex_mode))) {
3165 int ret;
3167 ret = vfs_set_filelen(fsp, 0);
3168 if (ret != 0) {
3169 status = map_nt_error_from_unix(errno);
3170 TALLOC_FREE(lck);
3171 fd_close(fsp);
3172 return status;
3177 * We have the share entry *locked*.....
3180 /* Delete streams if create_disposition requires it */
3181 if (!new_file_created && clear_ads(create_disposition) &&
3182 !is_ntfs_stream_smb_fname(smb_fname)) {
3183 status = delete_all_streams(conn, smb_fname->base_name);
3184 if (!NT_STATUS_IS_OK(status)) {
3185 TALLOC_FREE(lck);
3186 fd_close(fsp);
3187 return status;
3191 /* note that we ignore failure for the following. It is
3192 basically a hack for NFS, and NFS will never set one of
3193 these only read them. Nobody but Samba can ever set a deny
3194 mode and we have already checked our more authoritative
3195 locking database for permission to set this deny mode. If
3196 the kernel refuses the operations then the kernel is wrong.
3197 note that GPFS supports it as well - jmcd */
3199 if (fsp->fh->fd != -1 && lp_kernel_share_modes(SNUM(conn))) {
3200 int ret_flock;
3202 * Beware: streams implementing VFS modules may
3203 * implement streams in a way that fsp will have the
3204 * basefile open in the fsp fd, so lacking a distinct
3205 * fd for the stream kernel_flock will apply on the
3206 * basefile which is wrong. The actual check is
3207 * deffered to the VFS module implementing the
3208 * kernel_flock call.
3210 ret_flock = SMB_VFS_KERNEL_FLOCK(fsp, share_access, access_mask);
3211 if(ret_flock == -1 ){
3213 TALLOC_FREE(lck);
3214 fd_close(fsp);
3216 return NT_STATUS_SHARING_VIOLATION;
3219 fsp->kernel_share_modes_taken = true;
3223 * At this point onwards, we can guarantee that the share entry
3224 * is locked, whether we created the file or not, and that the
3225 * deny mode is compatible with all current opens.
3229 * According to Samba4, SEC_FILE_READ_ATTRIBUTE is always granted,
3230 * but we don't have to store this - just ignore it on access check.
3232 if (conn->sconn->using_smb2) {
3234 * SMB2 doesn't return it (according to Microsoft tests).
3235 * Test Case: TestSuite_ScenarioNo009GrantedAccessTestS0
3236 * File created with access = 0x7 (Read, Write, Delete)
3237 * Query Info on file returns 0x87 (Read, Write, Delete, Read Attributes)
3239 fsp->access_mask = access_mask;
3240 } else {
3241 /* But SMB1 does. */
3242 fsp->access_mask = access_mask | FILE_READ_ATTRIBUTES;
3245 if (file_existed) {
3247 * stat opens on existing files don't get oplocks.
3248 * They can get leases.
3250 * Note that we check for stat open on the *open_access_mask*,
3251 * i.e. the access mask we actually used to do the open,
3252 * not the one the client asked for (which is in
3253 * fsp->access_mask). This is due to the fact that
3254 * FILE_OVERWRITE and FILE_OVERWRITE_IF add in O_TRUNC,
3255 * which adds FILE_WRITE_DATA to open_access_mask.
3257 if (is_stat_open(open_access_mask) && lease == NULL) {
3258 oplock_request = NO_OPLOCK;
3262 if (new_file_created) {
3263 info = FILE_WAS_CREATED;
3264 } else {
3265 if (flags2 & O_TRUNC) {
3266 info = FILE_WAS_OVERWRITTEN;
3267 } else {
3268 info = FILE_WAS_OPENED;
3272 if (pinfo) {
3273 *pinfo = info;
3277 * Setup the oplock info in both the shared memory and
3278 * file structs.
3280 status = grant_fsp_oplock_type(req, fsp, lck, oplock_request, lease);
3281 if (!NT_STATUS_IS_OK(status)) {
3282 TALLOC_FREE(lck);
3283 fd_close(fsp);
3284 return status;
3287 /* Handle strange delete on close create semantics. */
3288 if (create_options & FILE_DELETE_ON_CLOSE) {
3290 status = can_set_delete_on_close(fsp, new_dos_attributes);
3292 if (!NT_STATUS_IS_OK(status)) {
3293 /* Remember to delete the mode we just added. */
3294 del_share_mode(lck, fsp);
3295 TALLOC_FREE(lck);
3296 fd_close(fsp);
3297 return status;
3299 /* Note that here we set the *inital* delete on close flag,
3300 not the regular one. The magic gets handled in close. */
3301 fsp->initial_delete_on_close = True;
3304 if (info != FILE_WAS_OPENED) {
3305 /* Overwritten files should be initially set as archive */
3306 if ((info == FILE_WAS_OVERWRITTEN && lp_map_archive(SNUM(conn))) ||
3307 lp_store_dos_attributes(SNUM(conn))) {
3308 if (!posix_open) {
3309 if (file_set_dosmode(conn, smb_fname,
3310 new_dos_attributes | FILE_ATTRIBUTE_ARCHIVE,
3311 parent_dir, true) == 0) {
3312 unx_mode = smb_fname->st.st_ex_mode;
3318 /* Determine sparse flag. */
3319 if (posix_open) {
3320 /* POSIX opens are sparse by default. */
3321 fsp->is_sparse = true;
3322 } else {
3323 fsp->is_sparse = (file_existed &&
3324 (existing_dos_attributes & FILE_ATTRIBUTE_SPARSE));
3328 * Take care of inherited ACLs on created files - if default ACL not
3329 * selected.
3332 if (!posix_open && new_file_created && !def_acl) {
3334 int saved_errno = errno; /* We might get ENOSYS in the next
3335 * call.. */
3337 if (SMB_VFS_FCHMOD_ACL(fsp, unx_mode) == -1 &&
3338 errno == ENOSYS) {
3339 errno = saved_errno; /* Ignore ENOSYS */
3342 } else if (new_unx_mode) {
3344 int ret = -1;
3346 /* Attributes need changing. File already existed. */
3349 int saved_errno = errno; /* We might get ENOSYS in the
3350 * next call.. */
3351 ret = SMB_VFS_FCHMOD_ACL(fsp, new_unx_mode);
3353 if (ret == -1 && errno == ENOSYS) {
3354 errno = saved_errno; /* Ignore ENOSYS */
3355 } else {
3356 DEBUG(5, ("open_file_ntcreate: reset "
3357 "attributes of file %s to 0%o\n",
3358 smb_fname_str_dbg(smb_fname),
3359 (unsigned int)new_unx_mode));
3360 ret = 0; /* Don't do the fchmod below. */
3364 if ((ret == -1) &&
3365 (SMB_VFS_FCHMOD(fsp, new_unx_mode) == -1))
3366 DEBUG(5, ("open_file_ntcreate: failed to reset "
3367 "attributes of file %s to 0%o\n",
3368 smb_fname_str_dbg(smb_fname),
3369 (unsigned int)new_unx_mode));
3374 * Deal with other opens having a modified write time.
3376 struct timespec write_time = get_share_mode_write_time(lck);
3378 if (!null_timespec(write_time)) {
3379 update_stat_ex_mtime(&fsp->fsp_name->st, write_time);
3383 TALLOC_FREE(lck);
3385 return NT_STATUS_OK;
3388 static NTSTATUS mkdir_internal(connection_struct *conn,
3389 struct smb_filename *smb_dname,
3390 uint32_t file_attributes)
3392 mode_t mode;
3393 char *parent_dir = NULL;
3394 NTSTATUS status;
3395 bool posix_open = false;
3396 bool need_re_stat = false;
3397 uint32_t access_mask = SEC_DIR_ADD_SUBDIR;
3399 if (!CAN_WRITE(conn) || (access_mask & ~(conn->share_access))) {
3400 DEBUG(5,("mkdir_internal: failing share access "
3401 "%s\n", lp_servicename(talloc_tos(), SNUM(conn))));
3402 return NT_STATUS_ACCESS_DENIED;
3405 if (!parent_dirname(talloc_tos(), smb_dname->base_name, &parent_dir,
3406 NULL)) {
3407 return NT_STATUS_NO_MEMORY;
3410 if (file_attributes & FILE_FLAG_POSIX_SEMANTICS) {
3411 posix_open = true;
3412 mode = (mode_t)(file_attributes & ~FILE_FLAG_POSIX_SEMANTICS);
3413 } else {
3414 mode = unix_mode(conn, FILE_ATTRIBUTE_DIRECTORY, smb_dname, parent_dir);
3417 status = check_parent_access(conn,
3418 smb_dname,
3419 access_mask);
3420 if(!NT_STATUS_IS_OK(status)) {
3421 DEBUG(5,("mkdir_internal: check_parent_access "
3422 "on directory %s for path %s returned %s\n",
3423 parent_dir,
3424 smb_dname->base_name,
3425 nt_errstr(status) ));
3426 return status;
3429 if (SMB_VFS_MKDIR(conn, smb_dname->base_name, mode) != 0) {
3430 return map_nt_error_from_unix(errno);
3433 /* Ensure we're checking for a symlink here.... */
3434 /* We don't want to get caught by a symlink racer. */
3436 if (SMB_VFS_LSTAT(conn, smb_dname) == -1) {
3437 DEBUG(2, ("Could not stat directory '%s' just created: %s\n",
3438 smb_fname_str_dbg(smb_dname), strerror(errno)));
3439 return map_nt_error_from_unix(errno);
3442 if (!S_ISDIR(smb_dname->st.st_ex_mode)) {
3443 DEBUG(0, ("Directory '%s' just created is not a directory !\n",
3444 smb_fname_str_dbg(smb_dname)));
3445 return NT_STATUS_NOT_A_DIRECTORY;
3448 if (lp_store_dos_attributes(SNUM(conn))) {
3449 if (!posix_open) {
3450 file_set_dosmode(conn, smb_dname,
3451 file_attributes | FILE_ATTRIBUTE_DIRECTORY,
3452 parent_dir, true);
3456 if (lp_inherit_permissions(SNUM(conn))) {
3457 inherit_access_posix_acl(conn, parent_dir,
3458 smb_dname->base_name, mode);
3459 need_re_stat = true;
3462 if (!posix_open) {
3464 * Check if high bits should have been set,
3465 * then (if bits are missing): add them.
3466 * Consider bits automagically set by UNIX, i.e. SGID bit from parent
3467 * dir.
3469 if ((mode & ~(S_IRWXU|S_IRWXG|S_IRWXO)) &&
3470 (mode & ~smb_dname->st.st_ex_mode)) {
3471 SMB_VFS_CHMOD(conn, smb_dname->base_name,
3472 (smb_dname->st.st_ex_mode |
3473 (mode & ~smb_dname->st.st_ex_mode)));
3474 need_re_stat = true;
3478 /* Change the owner if required. */
3479 if (lp_inherit_owner(SNUM(conn))) {
3480 change_dir_owner_to_parent(conn, parent_dir,
3481 smb_dname->base_name,
3482 &smb_dname->st);
3483 need_re_stat = true;
3486 if (need_re_stat) {
3487 if (SMB_VFS_LSTAT(conn, smb_dname) == -1) {
3488 DEBUG(2, ("Could not stat directory '%s' just created: %s\n",
3489 smb_fname_str_dbg(smb_dname), strerror(errno)));
3490 return map_nt_error_from_unix(errno);
3494 notify_fname(conn, NOTIFY_ACTION_ADDED, FILE_NOTIFY_CHANGE_DIR_NAME,
3495 smb_dname->base_name);
3497 return NT_STATUS_OK;
3500 /****************************************************************************
3501 Open a directory from an NT SMB call.
3502 ****************************************************************************/
3504 static NTSTATUS open_directory(connection_struct *conn,
3505 struct smb_request *req,
3506 struct smb_filename *smb_dname,
3507 uint32_t access_mask,
3508 uint32_t share_access,
3509 uint32_t create_disposition,
3510 uint32_t create_options,
3511 uint32_t file_attributes,
3512 int *pinfo,
3513 files_struct **result)
3515 files_struct *fsp = NULL;
3516 bool dir_existed = VALID_STAT(smb_dname->st) ? True : False;
3517 struct share_mode_lock *lck = NULL;
3518 NTSTATUS status;
3519 struct timespec mtimespec;
3520 int info = 0;
3521 bool ok;
3523 if (is_ntfs_stream_smb_fname(smb_dname)) {
3524 DEBUG(2, ("open_directory: %s is a stream name!\n",
3525 smb_fname_str_dbg(smb_dname)));
3526 return NT_STATUS_NOT_A_DIRECTORY;
3529 if (!(file_attributes & FILE_FLAG_POSIX_SEMANTICS)) {
3530 /* Ensure we have a directory attribute. */
3531 file_attributes |= FILE_ATTRIBUTE_DIRECTORY;
3534 DEBUG(5,("open_directory: opening directory %s, access_mask = 0x%x, "
3535 "share_access = 0x%x create_options = 0x%x, "
3536 "create_disposition = 0x%x, file_attributes = 0x%x\n",
3537 smb_fname_str_dbg(smb_dname),
3538 (unsigned int)access_mask,
3539 (unsigned int)share_access,
3540 (unsigned int)create_options,
3541 (unsigned int)create_disposition,
3542 (unsigned int)file_attributes));
3544 status = smbd_calculate_access_mask(conn, smb_dname, false,
3545 access_mask, &access_mask);
3546 if (!NT_STATUS_IS_OK(status)) {
3547 DEBUG(10, ("open_directory: smbd_calculate_access_mask "
3548 "on file %s returned %s\n",
3549 smb_fname_str_dbg(smb_dname),
3550 nt_errstr(status)));
3551 return status;
3554 if ((access_mask & SEC_FLAG_SYSTEM_SECURITY) &&
3555 !security_token_has_privilege(get_current_nttok(conn),
3556 SEC_PRIV_SECURITY)) {
3557 DEBUG(10, ("open_directory: open on %s "
3558 "failed - SEC_FLAG_SYSTEM_SECURITY denied.\n",
3559 smb_fname_str_dbg(smb_dname)));
3560 return NT_STATUS_PRIVILEGE_NOT_HELD;
3563 switch( create_disposition ) {
3564 case FILE_OPEN:
3566 if (!dir_existed) {
3567 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3570 info = FILE_WAS_OPENED;
3571 break;
3573 case FILE_CREATE:
3575 /* If directory exists error. If directory doesn't
3576 * exist create. */
3578 if (dir_existed) {
3579 status = NT_STATUS_OBJECT_NAME_COLLISION;
3580 DEBUG(2, ("open_directory: unable to create "
3581 "%s. Error was %s\n",
3582 smb_fname_str_dbg(smb_dname),
3583 nt_errstr(status)));
3584 return status;
3587 status = mkdir_internal(conn, smb_dname,
3588 file_attributes);
3590 if (!NT_STATUS_IS_OK(status)) {
3591 DEBUG(2, ("open_directory: unable to create "
3592 "%s. Error was %s\n",
3593 smb_fname_str_dbg(smb_dname),
3594 nt_errstr(status)));
3595 return status;
3598 info = FILE_WAS_CREATED;
3599 break;
3601 case FILE_OPEN_IF:
3603 * If directory exists open. If directory doesn't
3604 * exist create.
3607 if (dir_existed) {
3608 status = NT_STATUS_OK;
3609 info = FILE_WAS_OPENED;
3610 } else {
3611 status = mkdir_internal(conn, smb_dname,
3612 file_attributes);
3614 if (NT_STATUS_IS_OK(status)) {
3615 info = FILE_WAS_CREATED;
3616 } else {
3617 /* Cope with create race. */
3618 if (!NT_STATUS_EQUAL(status,
3619 NT_STATUS_OBJECT_NAME_COLLISION)) {
3620 DEBUG(2, ("open_directory: unable to create "
3621 "%s. Error was %s\n",
3622 smb_fname_str_dbg(smb_dname),
3623 nt_errstr(status)));
3624 return status;
3628 * If mkdir_internal() returned
3629 * NT_STATUS_OBJECT_NAME_COLLISION
3630 * we still must lstat the path.
3633 if (SMB_VFS_LSTAT(conn, smb_dname)
3634 == -1) {
3635 DEBUG(2, ("Could not stat "
3636 "directory '%s' just "
3637 "opened: %s\n",
3638 smb_fname_str_dbg(
3639 smb_dname),
3640 strerror(errno)));
3641 return map_nt_error_from_unix(
3642 errno);
3645 info = FILE_WAS_OPENED;
3649 break;
3651 case FILE_SUPERSEDE:
3652 case FILE_OVERWRITE:
3653 case FILE_OVERWRITE_IF:
3654 default:
3655 DEBUG(5,("open_directory: invalid create_disposition "
3656 "0x%x for directory %s\n",
3657 (unsigned int)create_disposition,
3658 smb_fname_str_dbg(smb_dname)));
3659 return NT_STATUS_INVALID_PARAMETER;
3662 if(!S_ISDIR(smb_dname->st.st_ex_mode)) {
3663 DEBUG(5,("open_directory: %s is not a directory !\n",
3664 smb_fname_str_dbg(smb_dname)));
3665 return NT_STATUS_NOT_A_DIRECTORY;
3668 if (info == FILE_WAS_OPENED) {
3669 status = smbd_check_access_rights(conn,
3670 smb_dname,
3671 false,
3672 access_mask);
3673 if (!NT_STATUS_IS_OK(status)) {
3674 DEBUG(10, ("open_directory: smbd_check_access_rights on "
3675 "file %s failed with %s\n",
3676 smb_fname_str_dbg(smb_dname),
3677 nt_errstr(status)));
3678 return status;
3682 status = file_new(req, conn, &fsp);
3683 if(!NT_STATUS_IS_OK(status)) {
3684 return status;
3688 * Setup the files_struct for it.
3691 fsp->file_id = vfs_file_id_from_sbuf(conn, &smb_dname->st);
3692 fsp->vuid = req ? req->vuid : UID_FIELD_INVALID;
3693 fsp->file_pid = req ? req->smbpid : 0;
3694 fsp->can_lock = False;
3695 fsp->can_read = False;
3696 fsp->can_write = False;
3698 fsp->share_access = share_access;
3699 fsp->fh->private_options = 0;
3701 * According to Samba4, SEC_FILE_READ_ATTRIBUTE is always granted,
3703 fsp->access_mask = access_mask | FILE_READ_ATTRIBUTES;
3704 fsp->print_file = NULL;
3705 fsp->modified = False;
3706 fsp->oplock_type = NO_OPLOCK;
3707 fsp->sent_oplock_break = NO_BREAK_SENT;
3708 fsp->is_directory = True;
3709 if (file_attributes & FILE_FLAG_POSIX_SEMANTICS) {
3710 fsp->posix_flags |= FSP_POSIX_FLAGS_ALL;
3712 status = fsp_set_smb_fname(fsp, smb_dname);
3713 if (!NT_STATUS_IS_OK(status)) {
3714 file_free(req, fsp);
3715 return status;
3718 /* Don't store old timestamps for directory
3719 handles in the internal database. We don't
3720 update them in there if new objects
3721 are creaded in the directory. Currently
3722 we only update timestamps on file writes.
3723 See bug #9870.
3725 ZERO_STRUCT(mtimespec);
3727 if (access_mask & (FILE_LIST_DIRECTORY|
3728 FILE_ADD_FILE|
3729 FILE_ADD_SUBDIRECTORY|
3730 FILE_TRAVERSE|
3731 DELETE_ACCESS|
3732 FILE_DELETE_CHILD)) {
3733 #ifdef O_DIRECTORY
3734 status = fd_open(conn, fsp, O_RDONLY|O_DIRECTORY, 0);
3735 #else
3736 /* POSIX allows us to open a directory with O_RDONLY. */
3737 status = fd_open(conn, fsp, O_RDONLY, 0);
3738 #endif
3739 if (!NT_STATUS_IS_OK(status)) {
3740 DEBUG(5, ("open_directory: Could not open fd for "
3741 "%s (%s)\n",
3742 smb_fname_str_dbg(smb_dname),
3743 nt_errstr(status)));
3744 file_free(req, fsp);
3745 return status;
3747 } else {
3748 fsp->fh->fd = -1;
3749 DEBUG(10, ("Not opening Directory %s\n",
3750 smb_fname_str_dbg(smb_dname)));
3753 status = vfs_stat_fsp(fsp);
3754 if (!NT_STATUS_IS_OK(status)) {
3755 fd_close(fsp);
3756 file_free(req, fsp);
3757 return status;
3760 if(!S_ISDIR(fsp->fsp_name->st.st_ex_mode)) {
3761 DEBUG(5,("open_directory: %s is not a directory !\n",
3762 smb_fname_str_dbg(smb_dname)));
3763 fd_close(fsp);
3764 file_free(req, fsp);
3765 return NT_STATUS_NOT_A_DIRECTORY;
3768 /* Ensure there was no race condition. We need to check
3769 * dev/inode but not permissions, as these can change
3770 * legitimately */
3771 if (!check_same_dev_ino(&smb_dname->st, &fsp->fsp_name->st)) {
3772 DEBUG(5,("open_directory: stat struct differs for "
3773 "directory %s.\n",
3774 smb_fname_str_dbg(smb_dname)));
3775 fd_close(fsp);
3776 file_free(req, fsp);
3777 return NT_STATUS_ACCESS_DENIED;
3780 lck = get_share_mode_lock(talloc_tos(), fsp->file_id,
3781 conn->connectpath, smb_dname,
3782 &mtimespec);
3784 if (lck == NULL) {
3785 DEBUG(0, ("open_directory: Could not get share mode lock for "
3786 "%s\n", smb_fname_str_dbg(smb_dname)));
3787 fd_close(fsp);
3788 file_free(req, fsp);
3789 return NT_STATUS_SHARING_VIOLATION;
3792 if (has_delete_on_close(lck, fsp->name_hash)) {
3793 TALLOC_FREE(lck);
3794 fd_close(fsp);
3795 file_free(req, fsp);
3796 return NT_STATUS_DELETE_PENDING;
3799 status = open_mode_check(conn, lck,
3800 access_mask, share_access);
3802 if (!NT_STATUS_IS_OK(status)) {
3803 TALLOC_FREE(lck);
3804 fd_close(fsp);
3805 file_free(req, fsp);
3806 return status;
3809 ok = set_share_mode(lck, fsp, get_current_uid(conn),
3810 req ? req->mid : 0, NO_OPLOCK,
3811 UINT32_MAX);
3812 if (!ok) {
3813 TALLOC_FREE(lck);
3814 fd_close(fsp);
3815 file_free(req, fsp);
3816 return NT_STATUS_NO_MEMORY;
3819 /* For directories the delete on close bit at open time seems
3820 always to be honored on close... See test 19 in Samba4 BASE-DELETE. */
3821 if (create_options & FILE_DELETE_ON_CLOSE) {
3822 status = can_set_delete_on_close(fsp, 0);
3823 if (!NT_STATUS_IS_OK(status) && !NT_STATUS_EQUAL(status, NT_STATUS_DIRECTORY_NOT_EMPTY)) {
3824 del_share_mode(lck, fsp);
3825 TALLOC_FREE(lck);
3826 fd_close(fsp);
3827 file_free(req, fsp);
3828 return status;
3831 if (NT_STATUS_IS_OK(status)) {
3832 /* Note that here we set the *inital* delete on close flag,
3833 not the regular one. The magic gets handled in close. */
3834 fsp->initial_delete_on_close = True;
3840 * Deal with other opens having a modified write time. Is this
3841 * possible for directories?
3843 struct timespec write_time = get_share_mode_write_time(lck);
3845 if (!null_timespec(write_time)) {
3846 update_stat_ex_mtime(&fsp->fsp_name->st, write_time);
3850 TALLOC_FREE(lck);
3852 if (pinfo) {
3853 *pinfo = info;
3856 *result = fsp;
3857 return NT_STATUS_OK;
3860 NTSTATUS create_directory(connection_struct *conn, struct smb_request *req,
3861 struct smb_filename *smb_dname)
3863 NTSTATUS status;
3864 files_struct *fsp;
3866 status = SMB_VFS_CREATE_FILE(
3867 conn, /* conn */
3868 req, /* req */
3869 0, /* root_dir_fid */
3870 smb_dname, /* fname */
3871 FILE_READ_ATTRIBUTES, /* access_mask */
3872 FILE_SHARE_NONE, /* share_access */
3873 FILE_CREATE, /* create_disposition*/
3874 FILE_DIRECTORY_FILE, /* create_options */
3875 FILE_ATTRIBUTE_DIRECTORY, /* file_attributes */
3876 0, /* oplock_request */
3877 NULL, /* lease */
3878 0, /* allocation_size */
3879 0, /* private_flags */
3880 NULL, /* sd */
3881 NULL, /* ea_list */
3882 &fsp, /* result */
3883 NULL, /* pinfo */
3884 NULL, NULL); /* create context */
3886 if (NT_STATUS_IS_OK(status)) {
3887 close_file(req, fsp, NORMAL_CLOSE);
3890 return status;
3893 /****************************************************************************
3894 Receive notification that one of our open files has been renamed by another
3895 smbd process.
3896 ****************************************************************************/
3898 void msg_file_was_renamed(struct messaging_context *msg,
3899 void *private_data,
3900 uint32_t msg_type,
3901 struct server_id server_id,
3902 DATA_BLOB *data)
3904 files_struct *fsp;
3905 char *frm = (char *)data->data;
3906 struct file_id id;
3907 const char *sharepath;
3908 const char *base_name;
3909 const char *stream_name;
3910 struct smb_filename *smb_fname = NULL;
3911 size_t sp_len, bn_len;
3912 NTSTATUS status;
3913 struct smbd_server_connection *sconn =
3914 talloc_get_type_abort(private_data,
3915 struct smbd_server_connection);
3917 if (data->data == NULL
3918 || data->length < MSG_FILE_RENAMED_MIN_SIZE + 2) {
3919 DEBUG(0, ("msg_file_was_renamed: Got invalid msg len %d\n",
3920 (int)data->length));
3921 return;
3924 /* Unpack the message. */
3925 pull_file_id_24(frm, &id);
3926 sharepath = &frm[24];
3927 sp_len = strlen(sharepath);
3928 base_name = sharepath + sp_len + 1;
3929 bn_len = strlen(base_name);
3930 stream_name = sharepath + sp_len + 1 + bn_len + 1;
3932 /* stream_name must always be NULL if there is no stream. */
3933 if (stream_name[0] == '\0') {
3934 stream_name = NULL;
3937 smb_fname = synthetic_smb_fname(talloc_tos(), base_name,
3938 stream_name, NULL);
3939 if (smb_fname == NULL) {
3940 return;
3943 DEBUG(10,("msg_file_was_renamed: Got rename message for sharepath %s, new name %s, "
3944 "file_id %s\n",
3945 sharepath, smb_fname_str_dbg(smb_fname),
3946 file_id_string_tos(&id)));
3948 for(fsp = file_find_di_first(sconn, id); fsp;
3949 fsp = file_find_di_next(fsp)) {
3950 if (memcmp(fsp->conn->connectpath, sharepath, sp_len) == 0) {
3952 DEBUG(10,("msg_file_was_renamed: renaming file %s from %s -> %s\n",
3953 fsp_fnum_dbg(fsp), fsp_str_dbg(fsp),
3954 smb_fname_str_dbg(smb_fname)));
3955 status = fsp_set_smb_fname(fsp, smb_fname);
3956 if (!NT_STATUS_IS_OK(status)) {
3957 goto out;
3959 } else {
3960 /* TODO. JRA. */
3961 /* Now we have the complete path we can work out if this is
3962 actually within this share and adjust newname accordingly. */
3963 DEBUG(10,("msg_file_was_renamed: share mismatch (sharepath %s "
3964 "not sharepath %s) "
3965 "%s from %s -> %s\n",
3966 fsp->conn->connectpath,
3967 sharepath,
3968 fsp_fnum_dbg(fsp),
3969 fsp_str_dbg(fsp),
3970 smb_fname_str_dbg(smb_fname)));
3973 out:
3974 TALLOC_FREE(smb_fname);
3975 return;
3979 * If a main file is opened for delete, all streams need to be checked for
3980 * !FILE_SHARE_DELETE. Do this by opening with DELETE_ACCESS.
3981 * If that works, delete them all by setting the delete on close and close.
3984 NTSTATUS open_streams_for_delete(connection_struct *conn,
3985 const char *fname)
3987 struct stream_struct *stream_info = NULL;
3988 files_struct **streams = NULL;
3989 int i;
3990 unsigned int num_streams = 0;
3991 TALLOC_CTX *frame = talloc_stackframe();
3992 NTSTATUS status;
3993 bool saved_posix_pathnames;
3995 status = vfs_streaminfo(conn, NULL, fname, talloc_tos(),
3996 &num_streams, &stream_info);
3998 if (NT_STATUS_EQUAL(status, NT_STATUS_NOT_IMPLEMENTED)
3999 || NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
4000 DEBUG(10, ("no streams around\n"));
4001 TALLOC_FREE(frame);
4002 return NT_STATUS_OK;
4005 if (!NT_STATUS_IS_OK(status)) {
4006 DEBUG(10, ("vfs_streaminfo failed: %s\n",
4007 nt_errstr(status)));
4008 goto fail;
4011 DEBUG(10, ("open_streams_for_delete found %d streams\n",
4012 num_streams));
4014 if (num_streams == 0) {
4015 TALLOC_FREE(frame);
4016 return NT_STATUS_OK;
4019 streams = talloc_array(talloc_tos(), files_struct *, num_streams);
4020 if (streams == NULL) {
4021 DEBUG(0, ("talloc failed\n"));
4022 status = NT_STATUS_NO_MEMORY;
4023 goto fail;
4027 * Any stream names *must* be treated as Windows
4028 * pathnames, even if we're using UNIX extensions.
4031 saved_posix_pathnames = lp_set_posix_pathnames(false);
4033 for (i=0; i<num_streams; i++) {
4034 struct smb_filename *smb_fname;
4036 if (strequal(stream_info[i].name, "::$DATA")) {
4037 streams[i] = NULL;
4038 continue;
4041 smb_fname = synthetic_smb_fname(
4042 talloc_tos(), fname, stream_info[i].name, NULL);
4043 if (smb_fname == NULL) {
4044 status = NT_STATUS_NO_MEMORY;
4045 goto fail;
4048 if (SMB_VFS_STAT(conn, smb_fname) == -1) {
4049 DEBUG(10, ("Unable to stat stream: %s\n",
4050 smb_fname_str_dbg(smb_fname)));
4053 status = SMB_VFS_CREATE_FILE(
4054 conn, /* conn */
4055 NULL, /* req */
4056 0, /* root_dir_fid */
4057 smb_fname, /* fname */
4058 DELETE_ACCESS, /* access_mask */
4059 (FILE_SHARE_READ | /* share_access */
4060 FILE_SHARE_WRITE | FILE_SHARE_DELETE),
4061 FILE_OPEN, /* create_disposition*/
4062 0, /* create_options */
4063 FILE_ATTRIBUTE_NORMAL, /* file_attributes */
4064 0, /* oplock_request */
4065 NULL, /* lease */
4066 0, /* allocation_size */
4067 NTCREATEX_OPTIONS_PRIVATE_STREAM_DELETE, /* private_flags */
4068 NULL, /* sd */
4069 NULL, /* ea_list */
4070 &streams[i], /* result */
4071 NULL, /* pinfo */
4072 NULL, NULL); /* create context */
4074 if (!NT_STATUS_IS_OK(status)) {
4075 DEBUG(10, ("Could not open stream %s: %s\n",
4076 smb_fname_str_dbg(smb_fname),
4077 nt_errstr(status)));
4079 TALLOC_FREE(smb_fname);
4080 break;
4082 TALLOC_FREE(smb_fname);
4086 * don't touch the variable "status" beyond this point :-)
4089 for (i -= 1 ; i >= 0; i--) {
4090 if (streams[i] == NULL) {
4091 continue;
4094 DEBUG(10, ("Closing stream # %d, %s\n", i,
4095 fsp_str_dbg(streams[i])));
4096 close_file(NULL, streams[i], NORMAL_CLOSE);
4099 fail:
4101 (void)lp_set_posix_pathnames(saved_posix_pathnames);
4102 TALLOC_FREE(frame);
4103 return status;
4106 /*********************************************************************
4107 Create a default ACL by inheriting from the parent. If no inheritance
4108 from the parent available, don't set anything. This will leave the actual
4109 permissions the new file or directory already got from the filesystem
4110 as the NT ACL when read.
4111 *********************************************************************/
4113 static NTSTATUS inherit_new_acl(files_struct *fsp)
4115 TALLOC_CTX *frame = talloc_stackframe();
4116 char *parent_name = NULL;
4117 struct security_descriptor *parent_desc = NULL;
4118 NTSTATUS status = NT_STATUS_OK;
4119 struct security_descriptor *psd = NULL;
4120 const struct dom_sid *owner_sid = NULL;
4121 const struct dom_sid *group_sid = NULL;
4122 uint32_t security_info_sent = (SECINFO_OWNER | SECINFO_GROUP | SECINFO_DACL);
4123 struct security_token *token = fsp->conn->session_info->security_token;
4124 bool inherit_owner = lp_inherit_owner(SNUM(fsp->conn));
4125 bool inheritable_components = false;
4126 bool try_builtin_administrators = false;
4127 const struct dom_sid *BA_U_sid = NULL;
4128 const struct dom_sid *BA_G_sid = NULL;
4129 bool try_system = false;
4130 const struct dom_sid *SY_U_sid = NULL;
4131 const struct dom_sid *SY_G_sid = NULL;
4132 size_t size = 0;
4134 if (!parent_dirname(frame, fsp->fsp_name->base_name, &parent_name, NULL)) {
4135 TALLOC_FREE(frame);
4136 return NT_STATUS_NO_MEMORY;
4139 status = SMB_VFS_GET_NT_ACL(fsp->conn,
4140 parent_name,
4141 (SECINFO_OWNER | SECINFO_GROUP | SECINFO_DACL),
4142 frame,
4143 &parent_desc);
4144 if (!NT_STATUS_IS_OK(status)) {
4145 TALLOC_FREE(frame);
4146 return status;
4149 inheritable_components = sd_has_inheritable_components(parent_desc,
4150 fsp->is_directory);
4152 if (!inheritable_components && !inherit_owner) {
4153 TALLOC_FREE(frame);
4154 /* Nothing to inherit and not setting owner. */
4155 return NT_STATUS_OK;
4158 /* Create an inherited descriptor from the parent. */
4160 if (DEBUGLEVEL >= 10) {
4161 DEBUG(10,("inherit_new_acl: parent acl for %s is:\n",
4162 fsp_str_dbg(fsp) ));
4163 NDR_PRINT_DEBUG(security_descriptor, parent_desc);
4166 /* Inherit from parent descriptor if "inherit owner" set. */
4167 if (inherit_owner) {
4168 owner_sid = parent_desc->owner_sid;
4169 group_sid = parent_desc->group_sid;
4172 if (owner_sid == NULL) {
4173 if (security_token_has_builtin_administrators(token)) {
4174 try_builtin_administrators = true;
4175 } else if (security_token_is_system(token)) {
4176 try_builtin_administrators = true;
4177 try_system = true;
4181 if (group_sid == NULL &&
4182 token->num_sids == PRIMARY_GROUP_SID_INDEX)
4184 if (security_token_is_system(token)) {
4185 try_builtin_administrators = true;
4186 try_system = true;
4190 if (try_builtin_administrators) {
4191 struct unixid ids;
4192 bool ok;
4194 ZERO_STRUCT(ids);
4195 ok = sids_to_unixids(&global_sid_Builtin_Administrators, 1, &ids);
4196 if (ok) {
4197 switch (ids.type) {
4198 case ID_TYPE_BOTH:
4199 BA_U_sid = &global_sid_Builtin_Administrators;
4200 BA_G_sid = &global_sid_Builtin_Administrators;
4201 break;
4202 case ID_TYPE_UID:
4203 BA_U_sid = &global_sid_Builtin_Administrators;
4204 break;
4205 case ID_TYPE_GID:
4206 BA_G_sid = &global_sid_Builtin_Administrators;
4207 break;
4208 default:
4209 break;
4214 if (try_system) {
4215 struct unixid ids;
4216 bool ok;
4218 ZERO_STRUCT(ids);
4219 ok = sids_to_unixids(&global_sid_System, 1, &ids);
4220 if (ok) {
4221 switch (ids.type) {
4222 case ID_TYPE_BOTH:
4223 SY_U_sid = &global_sid_System;
4224 SY_G_sid = &global_sid_System;
4225 break;
4226 case ID_TYPE_UID:
4227 SY_U_sid = &global_sid_System;
4228 break;
4229 case ID_TYPE_GID:
4230 SY_G_sid = &global_sid_System;
4231 break;
4232 default:
4233 break;
4238 if (owner_sid == NULL) {
4239 owner_sid = BA_U_sid;
4242 if (owner_sid == NULL) {
4243 owner_sid = SY_U_sid;
4246 if (group_sid == NULL) {
4247 group_sid = SY_G_sid;
4250 if (try_system && group_sid == NULL) {
4251 group_sid = BA_G_sid;
4254 if (owner_sid == NULL) {
4255 owner_sid = &token->sids[PRIMARY_USER_SID_INDEX];
4257 if (group_sid == NULL) {
4258 if (token->num_sids == PRIMARY_GROUP_SID_INDEX) {
4259 group_sid = &token->sids[PRIMARY_USER_SID_INDEX];
4260 } else {
4261 group_sid = &token->sids[PRIMARY_GROUP_SID_INDEX];
4265 status = se_create_child_secdesc(frame,
4266 &psd,
4267 &size,
4268 parent_desc,
4269 owner_sid,
4270 group_sid,
4271 fsp->is_directory);
4272 if (!NT_STATUS_IS_OK(status)) {
4273 TALLOC_FREE(frame);
4274 return status;
4277 /* If inheritable_components == false,
4278 se_create_child_secdesc()
4279 creates a security desriptor with a NULL dacl
4280 entry, but with SEC_DESC_DACL_PRESENT. We need
4281 to remove that flag. */
4283 if (!inheritable_components) {
4284 security_info_sent &= ~SECINFO_DACL;
4285 psd->type &= ~SEC_DESC_DACL_PRESENT;
4288 if (DEBUGLEVEL >= 10) {
4289 DEBUG(10,("inherit_new_acl: child acl for %s is:\n",
4290 fsp_str_dbg(fsp) ));
4291 NDR_PRINT_DEBUG(security_descriptor, psd);
4294 if (inherit_owner) {
4295 /* We need to be root to force this. */
4296 become_root();
4298 status = SMB_VFS_FSET_NT_ACL(fsp,
4299 security_info_sent,
4300 psd);
4301 if (inherit_owner) {
4302 unbecome_root();
4304 TALLOC_FREE(frame);
4305 return status;
4309 * If we already have a lease, it must match the new file id. [MS-SMB2]
4310 * 3.3.5.9.8 speaks about INVALID_PARAMETER if an already used lease key is
4311 * used for a different file name.
4314 struct lease_match_state {
4315 /* Input parameters. */
4316 TALLOC_CTX *mem_ctx;
4317 const char *servicepath;
4318 const struct smb_filename *fname;
4319 bool file_existed;
4320 struct file_id id;
4321 /* Return parameters. */
4322 uint32_t num_file_ids;
4323 struct file_id *ids;
4324 NTSTATUS match_status;
4327 /*************************************************************
4328 File doesn't exist but this lease key+guid is already in use.
4330 This is only allowable in the dynamic share case where the
4331 service path must be different.
4333 There is a small race condition here in the multi-connection
4334 case where a client sends two create calls on different connections,
4335 where the file doesn't exist and one smbd creates the leases_db
4336 entry first, but this will get fixed by the multichannel cleanup
4337 when all identical client_guids get handled by a single smbd.
4338 **************************************************************/
4340 static void lease_match_parser_new_file(
4341 uint32_t num_files,
4342 const struct leases_db_file *files,
4343 struct lease_match_state *state)
4345 uint32_t i;
4347 for (i = 0; i < num_files; i++) {
4348 const struct leases_db_file *f = &files[i];
4349 if (strequal(state->servicepath, f->servicepath)) {
4350 state->match_status = NT_STATUS_INVALID_PARAMETER;
4351 return;
4355 /* Dynamic share case. Break leases on all other files. */
4356 state->match_status = leases_db_copy_file_ids(state->mem_ctx,
4357 num_files,
4358 files,
4359 &state->ids);
4360 if (!NT_STATUS_IS_OK(state->match_status)) {
4361 return;
4364 state->num_file_ids = num_files;
4365 state->match_status = NT_STATUS_OPLOCK_NOT_GRANTED;
4366 return;
4369 static void lease_match_parser(
4370 uint32_t num_files,
4371 const struct leases_db_file *files,
4372 void *private_data)
4374 struct lease_match_state *state =
4375 (struct lease_match_state *)private_data;
4376 uint32_t i;
4378 if (!state->file_existed) {
4380 * Deal with name mismatch or
4381 * possible dynamic share case separately
4382 * to make code clearer.
4384 lease_match_parser_new_file(num_files,
4385 files,
4386 state);
4387 return;
4390 /* File existed. */
4391 state->match_status = NT_STATUS_OK;
4393 for (i = 0; i < num_files; i++) {
4394 const struct leases_db_file *f = &files[i];
4396 /* Everything should be the same. */
4397 if (!file_id_equal(&state->id, &f->id)) {
4398 /* This should catch all dynamic share cases. */
4399 state->match_status = NT_STATUS_OPLOCK_NOT_GRANTED;
4400 break;
4402 if (!strequal(f->servicepath, state->servicepath)) {
4403 state->match_status = NT_STATUS_INVALID_PARAMETER;
4404 break;
4406 if (!strequal(f->base_name, state->fname->base_name)) {
4407 state->match_status = NT_STATUS_INVALID_PARAMETER;
4408 break;
4410 if (!strequal(f->stream_name, state->fname->stream_name)) {
4411 state->match_status = NT_STATUS_INVALID_PARAMETER;
4412 break;
4416 if (NT_STATUS_IS_OK(state->match_status)) {
4418 * Common case - just opening another handle on a
4419 * file on a non-dynamic share.
4421 return;
4424 if (NT_STATUS_EQUAL(state->match_status, NT_STATUS_INVALID_PARAMETER)) {
4425 /* Mismatched path. Error back to client. */
4426 return;
4430 * File id mismatch. Dynamic share case NT_STATUS_OPLOCK_NOT_GRANTED.
4431 * Don't allow leases.
4434 state->match_status = leases_db_copy_file_ids(state->mem_ctx,
4435 num_files,
4436 files,
4437 &state->ids);
4438 if (!NT_STATUS_IS_OK(state->match_status)) {
4439 return;
4442 state->num_file_ids = num_files;
4443 state->match_status = NT_STATUS_OPLOCK_NOT_GRANTED;
4444 return;
4447 static NTSTATUS lease_match(connection_struct *conn,
4448 struct smb_request *req,
4449 struct smb2_lease_key *lease_key,
4450 const char *servicepath,
4451 const struct smb_filename *fname,
4452 uint16_t *p_version,
4453 uint16_t *p_epoch)
4455 struct smbd_server_connection *sconn = req->sconn;
4456 TALLOC_CTX *tos = talloc_tos();
4457 struct lease_match_state state = {
4458 .mem_ctx = tos,
4459 .servicepath = servicepath,
4460 .fname = fname,
4461 .match_status = NT_STATUS_OK
4463 uint32_t i;
4464 NTSTATUS status;
4466 state.file_existed = VALID_STAT(fname->st);
4467 if (state.file_existed) {
4468 state.id = vfs_file_id_from_sbuf(conn, &fname->st);
4469 } else {
4470 memset(&state.id, '\0', sizeof(state.id));
4473 status = leases_db_parse(&sconn->client->connections->smb2.client.guid,
4474 lease_key, lease_match_parser, &state);
4475 if (!NT_STATUS_IS_OK(status)) {
4477 * Not found or error means okay: We can make the lease pass
4479 return NT_STATUS_OK;
4481 if (!NT_STATUS_EQUAL(state.match_status, NT_STATUS_OPLOCK_NOT_GRANTED)) {
4483 * Anything but NT_STATUS_OPLOCK_NOT_GRANTED, let the caller
4484 * deal with it.
4486 return state.match_status;
4489 /* We have to break all existing leases. */
4490 for (i = 0; i < state.num_file_ids; i++) {
4491 struct share_mode_lock *lck;
4492 struct share_mode_data *d;
4493 uint32_t j;
4495 if (file_id_equal(&state.ids[i], &state.id)) {
4496 /* Don't need to break our own file. */
4497 continue;
4500 lck = get_existing_share_mode_lock(talloc_tos(), state.ids[i]);
4501 if (lck == NULL) {
4502 /* Race condition - file already closed. */
4503 continue;
4505 d = lck->data;
4506 for (j=0; j<d->num_share_modes; j++) {
4507 struct share_mode_entry *e = &d->share_modes[j];
4508 uint32_t e_lease_type = get_lease_type(d, e);
4509 struct share_mode_lease *l = NULL;
4511 if (share_mode_stale_pid(d, j)) {
4512 continue;
4515 if (e->op_type == LEASE_OPLOCK) {
4516 l = &lck->data->leases[e->lease_idx];
4517 if (!smb2_lease_key_equal(&l->lease_key,
4518 lease_key)) {
4519 continue;
4521 *p_epoch = l->epoch;
4522 *p_version = l->lease_version;
4525 if (e_lease_type == SMB2_LEASE_NONE) {
4526 continue;
4529 send_break_message(conn->sconn->msg_ctx, e,
4530 SMB2_LEASE_NONE);
4533 * Windows 7 and 8 lease clients
4534 * are broken in that they will not
4535 * respond to lease break requests
4536 * whilst waiting for an outstanding
4537 * open request on that lease handle
4538 * on the same TCP connection, due
4539 * to holding an internal inode lock.
4541 * This means we can't reschedule
4542 * ourselves here, but must return
4543 * from the create.
4545 * Work around:
4547 * Send the breaks and then return
4548 * SMB2_LEASE_NONE in the lease handle
4549 * to cause them to acknowledge the
4550 * lease break. Consulatation with
4551 * Microsoft engineering confirmed
4552 * this approach is safe.
4556 TALLOC_FREE(lck);
4559 * Ensure we don't grant anything more so we
4560 * never upgrade.
4562 return NT_STATUS_OPLOCK_NOT_GRANTED;
4566 * Wrapper around open_file_ntcreate and open_directory
4569 static NTSTATUS create_file_unixpath(connection_struct *conn,
4570 struct smb_request *req,
4571 struct smb_filename *smb_fname,
4572 uint32_t access_mask,
4573 uint32_t share_access,
4574 uint32_t create_disposition,
4575 uint32_t create_options,
4576 uint32_t file_attributes,
4577 uint32_t oplock_request,
4578 struct smb2_lease *lease,
4579 uint64_t allocation_size,
4580 uint32_t private_flags,
4581 struct security_descriptor *sd,
4582 struct ea_list *ea_list,
4584 files_struct **result,
4585 int *pinfo)
4587 int info = FILE_WAS_OPENED;
4588 files_struct *base_fsp = NULL;
4589 files_struct *fsp = NULL;
4590 NTSTATUS status;
4592 DEBUG(10,("create_file_unixpath: access_mask = 0x%x "
4593 "file_attributes = 0x%x, share_access = 0x%x, "
4594 "create_disposition = 0x%x create_options = 0x%x "
4595 "oplock_request = 0x%x private_flags = 0x%x "
4596 "ea_list = 0x%p, sd = 0x%p, "
4597 "fname = %s\n",
4598 (unsigned int)access_mask,
4599 (unsigned int)file_attributes,
4600 (unsigned int)share_access,
4601 (unsigned int)create_disposition,
4602 (unsigned int)create_options,
4603 (unsigned int)oplock_request,
4604 (unsigned int)private_flags,
4605 ea_list, sd, smb_fname_str_dbg(smb_fname)));
4607 if (create_options & FILE_OPEN_BY_FILE_ID) {
4608 status = NT_STATUS_NOT_SUPPORTED;
4609 goto fail;
4612 if (create_options & NTCREATEX_OPTIONS_INVALID_PARAM_MASK) {
4613 status = NT_STATUS_INVALID_PARAMETER;
4614 goto fail;
4617 if (req == NULL) {
4618 oplock_request |= INTERNAL_OPEN_ONLY;
4621 if (lease != NULL) {
4622 uint16_t epoch = lease->lease_epoch;
4623 uint16_t version = lease->lease_version;
4624 status = lease_match(conn,
4625 req,
4626 &lease->lease_key,
4627 conn->connectpath,
4628 smb_fname,
4629 &version,
4630 &epoch);
4631 if (NT_STATUS_EQUAL(status, NT_STATUS_OPLOCK_NOT_GRANTED)) {
4632 /* Dynamic share file. No leases and update epoch... */
4633 lease->lease_state = SMB2_LEASE_NONE;
4634 lease->lease_epoch = epoch;
4635 lease->lease_version = version;
4636 } else if (!NT_STATUS_IS_OK(status)) {
4637 goto fail;
4641 if ((conn->fs_capabilities & FILE_NAMED_STREAMS)
4642 && (access_mask & DELETE_ACCESS)
4643 && !is_ntfs_stream_smb_fname(smb_fname)) {
4645 * We can't open a file with DELETE access if any of the
4646 * streams is open without FILE_SHARE_DELETE
4648 status = open_streams_for_delete(conn, smb_fname->base_name);
4650 if (!NT_STATUS_IS_OK(status)) {
4651 goto fail;
4655 if ((access_mask & SEC_FLAG_SYSTEM_SECURITY) &&
4656 !security_token_has_privilege(get_current_nttok(conn),
4657 SEC_PRIV_SECURITY)) {
4658 DEBUG(10, ("create_file_unixpath: open on %s "
4659 "failed - SEC_FLAG_SYSTEM_SECURITY denied.\n",
4660 smb_fname_str_dbg(smb_fname)));
4661 status = NT_STATUS_PRIVILEGE_NOT_HELD;
4662 goto fail;
4665 if ((conn->fs_capabilities & FILE_NAMED_STREAMS)
4666 && is_ntfs_stream_smb_fname(smb_fname)
4667 && (!(private_flags & NTCREATEX_OPTIONS_PRIVATE_STREAM_DELETE))) {
4668 uint32_t base_create_disposition;
4669 struct smb_filename *smb_fname_base = NULL;
4671 if (create_options & FILE_DIRECTORY_FILE) {
4672 status = NT_STATUS_NOT_A_DIRECTORY;
4673 goto fail;
4676 switch (create_disposition) {
4677 case FILE_OPEN:
4678 base_create_disposition = FILE_OPEN;
4679 break;
4680 default:
4681 base_create_disposition = FILE_OPEN_IF;
4682 break;
4685 /* Create an smb_filename with stream_name == NULL. */
4686 smb_fname_base = synthetic_smb_fname(talloc_tos(),
4687 smb_fname->base_name,
4688 NULL, NULL);
4689 if (smb_fname_base == NULL) {
4690 status = NT_STATUS_NO_MEMORY;
4691 goto fail;
4694 if (SMB_VFS_STAT(conn, smb_fname_base) == -1) {
4695 DEBUG(10, ("Unable to stat stream: %s\n",
4696 smb_fname_str_dbg(smb_fname_base)));
4697 } else {
4699 * https://bugzilla.samba.org/show_bug.cgi?id=10229
4700 * We need to check if the requested access mask
4701 * could be used to open the underlying file (if
4702 * it existed), as we're passing in zero for the
4703 * access mask to the base filename.
4705 status = check_base_file_access(conn,
4706 smb_fname_base,
4707 access_mask);
4709 if (!NT_STATUS_IS_OK(status)) {
4710 DEBUG(10, ("Permission check "
4711 "for base %s failed: "
4712 "%s\n", smb_fname->base_name,
4713 nt_errstr(status)));
4714 goto fail;
4718 /* Open the base file. */
4719 status = create_file_unixpath(conn, NULL, smb_fname_base, 0,
4720 FILE_SHARE_READ
4721 | FILE_SHARE_WRITE
4722 | FILE_SHARE_DELETE,
4723 base_create_disposition,
4724 0, 0, 0, NULL, 0, 0, NULL, NULL,
4725 &base_fsp, NULL);
4726 TALLOC_FREE(smb_fname_base);
4728 if (!NT_STATUS_IS_OK(status)) {
4729 DEBUG(10, ("create_file_unixpath for base %s failed: "
4730 "%s\n", smb_fname->base_name,
4731 nt_errstr(status)));
4732 goto fail;
4734 /* we don't need the low level fd */
4735 fd_close(base_fsp);
4739 * If it's a request for a directory open, deal with it separately.
4742 if (create_options & FILE_DIRECTORY_FILE) {
4744 if (create_options & FILE_NON_DIRECTORY_FILE) {
4745 status = NT_STATUS_INVALID_PARAMETER;
4746 goto fail;
4749 /* Can't open a temp directory. IFS kit test. */
4750 if (!(file_attributes & FILE_FLAG_POSIX_SEMANTICS) &&
4751 (file_attributes & FILE_ATTRIBUTE_TEMPORARY)) {
4752 status = NT_STATUS_INVALID_PARAMETER;
4753 goto fail;
4757 * We will get a create directory here if the Win32
4758 * app specified a security descriptor in the
4759 * CreateDirectory() call.
4762 oplock_request = 0;
4763 status = open_directory(
4764 conn, req, smb_fname, access_mask, share_access,
4765 create_disposition, create_options, file_attributes,
4766 &info, &fsp);
4767 } else {
4770 * Ordinary file case.
4773 status = file_new(req, conn, &fsp);
4774 if(!NT_STATUS_IS_OK(status)) {
4775 goto fail;
4778 status = fsp_set_smb_fname(fsp, smb_fname);
4779 if (!NT_STATUS_IS_OK(status)) {
4780 goto fail;
4783 if (base_fsp) {
4785 * We're opening the stream element of a
4786 * base_fsp we already opened. Set up the
4787 * base_fsp pointer.
4789 fsp->base_fsp = base_fsp;
4792 if (allocation_size) {
4793 fsp->initial_allocation_size = smb_roundup(fsp->conn,
4794 allocation_size);
4797 status = open_file_ntcreate(conn,
4798 req,
4799 access_mask,
4800 share_access,
4801 create_disposition,
4802 create_options,
4803 file_attributes,
4804 oplock_request,
4805 lease,
4806 private_flags,
4807 &info,
4808 fsp);
4810 if(!NT_STATUS_IS_OK(status)) {
4811 file_free(req, fsp);
4812 fsp = NULL;
4815 if (NT_STATUS_EQUAL(status, NT_STATUS_FILE_IS_A_DIRECTORY)) {
4817 /* A stream open never opens a directory */
4819 if (base_fsp) {
4820 status = NT_STATUS_FILE_IS_A_DIRECTORY;
4821 goto fail;
4825 * Fail the open if it was explicitly a non-directory
4826 * file.
4829 if (create_options & FILE_NON_DIRECTORY_FILE) {
4830 status = NT_STATUS_FILE_IS_A_DIRECTORY;
4831 goto fail;
4834 oplock_request = 0;
4835 status = open_directory(
4836 conn, req, smb_fname, access_mask,
4837 share_access, create_disposition,
4838 create_options, file_attributes,
4839 &info, &fsp);
4843 if (!NT_STATUS_IS_OK(status)) {
4844 goto fail;
4847 fsp->base_fsp = base_fsp;
4849 if ((ea_list != NULL) &&
4850 ((info == FILE_WAS_CREATED) || (info == FILE_WAS_OVERWRITTEN))) {
4851 status = set_ea(conn, fsp, fsp->fsp_name, ea_list);
4852 if (!NT_STATUS_IS_OK(status)) {
4853 goto fail;
4857 if (!fsp->is_directory && S_ISDIR(fsp->fsp_name->st.st_ex_mode)) {
4858 status = NT_STATUS_ACCESS_DENIED;
4859 goto fail;
4862 /* Save the requested allocation size. */
4863 if ((info == FILE_WAS_CREATED) || (info == FILE_WAS_OVERWRITTEN)) {
4864 if ((allocation_size > fsp->fsp_name->st.st_ex_size)
4865 && !(fsp->is_directory))
4867 fsp->initial_allocation_size = smb_roundup(
4868 fsp->conn, allocation_size);
4869 if (vfs_allocate_file_space(
4870 fsp, fsp->initial_allocation_size) == -1) {
4871 status = NT_STATUS_DISK_FULL;
4872 goto fail;
4874 } else {
4875 fsp->initial_allocation_size = smb_roundup(
4876 fsp->conn, (uint64_t)fsp->fsp_name->st.st_ex_size);
4878 } else {
4879 fsp->initial_allocation_size = 0;
4882 if ((info == FILE_WAS_CREATED) && lp_nt_acl_support(SNUM(conn)) &&
4883 fsp->base_fsp == NULL) {
4884 if (sd != NULL) {
4886 * According to the MS documentation, the only time the security
4887 * descriptor is applied to the opened file is iff we *created* the
4888 * file; an existing file stays the same.
4890 * Also, it seems (from observation) that you can open the file with
4891 * any access mask but you can still write the sd. We need to override
4892 * the granted access before we call set_sd
4893 * Patch for bug #2242 from Tom Lackemann <cessnatomny@yahoo.com>.
4896 uint32_t sec_info_sent;
4897 uint32_t saved_access_mask = fsp->access_mask;
4899 sec_info_sent = get_sec_info(sd);
4901 fsp->access_mask = FILE_GENERIC_ALL;
4903 if (sec_info_sent & (SECINFO_OWNER|
4904 SECINFO_GROUP|
4905 SECINFO_DACL|
4906 SECINFO_SACL)) {
4907 status = set_sd(fsp, sd, sec_info_sent);
4910 fsp->access_mask = saved_access_mask;
4912 if (!NT_STATUS_IS_OK(status)) {
4913 goto fail;
4915 } else if (lp_inherit_acls(SNUM(conn))) {
4916 /* Inherit from parent. Errors here are not fatal. */
4917 status = inherit_new_acl(fsp);
4918 if (!NT_STATUS_IS_OK(status)) {
4919 DEBUG(10,("inherit_new_acl: failed for %s with %s\n",
4920 fsp_str_dbg(fsp),
4921 nt_errstr(status) ));
4926 if ((conn->fs_capabilities & FILE_FILE_COMPRESSION)
4927 && (create_options & FILE_NO_COMPRESSION)
4928 && (info == FILE_WAS_CREATED)) {
4929 status = SMB_VFS_SET_COMPRESSION(conn, fsp, fsp,
4930 COMPRESSION_FORMAT_NONE);
4931 if (!NT_STATUS_IS_OK(status)) {
4932 DEBUG(1, ("failed to disable compression: %s\n",
4933 nt_errstr(status)));
4937 DEBUG(10, ("create_file_unixpath: info=%d\n", info));
4939 *result = fsp;
4940 if (pinfo != NULL) {
4941 *pinfo = info;
4944 smb_fname->st = fsp->fsp_name->st;
4946 return NT_STATUS_OK;
4948 fail:
4949 DEBUG(10, ("create_file_unixpath: %s\n", nt_errstr(status)));
4951 if (fsp != NULL) {
4952 if (base_fsp && fsp->base_fsp == base_fsp) {
4954 * The close_file below will close
4955 * fsp->base_fsp.
4957 base_fsp = NULL;
4959 close_file(req, fsp, ERROR_CLOSE);
4960 fsp = NULL;
4962 if (base_fsp != NULL) {
4963 close_file(req, base_fsp, ERROR_CLOSE);
4964 base_fsp = NULL;
4966 return status;
4970 * Calculate the full path name given a relative fid.
4972 NTSTATUS get_relative_fid_filename(connection_struct *conn,
4973 struct smb_request *req,
4974 uint16_t root_dir_fid,
4975 const struct smb_filename *smb_fname,
4976 struct smb_filename **smb_fname_out)
4978 files_struct *dir_fsp;
4979 char *parent_fname = NULL;
4980 char *new_base_name = NULL;
4981 uint32_t ucf_flags = ((req != NULL && req->posix_pathnames) ?
4982 UCF_POSIX_PATHNAMES : 0);
4983 NTSTATUS status;
4985 if (root_dir_fid == 0 || !smb_fname) {
4986 status = NT_STATUS_INTERNAL_ERROR;
4987 goto out;
4990 dir_fsp = file_fsp(req, root_dir_fid);
4992 if (dir_fsp == NULL) {
4993 status = NT_STATUS_INVALID_HANDLE;
4994 goto out;
4997 if (is_ntfs_stream_smb_fname(dir_fsp->fsp_name)) {
4998 status = NT_STATUS_INVALID_HANDLE;
4999 goto out;
5002 if (!dir_fsp->is_directory) {
5005 * Check to see if this is a mac fork of some kind.
5008 if ((conn->fs_capabilities & FILE_NAMED_STREAMS) &&
5009 is_ntfs_stream_smb_fname(smb_fname)) {
5010 status = NT_STATUS_OBJECT_PATH_NOT_FOUND;
5011 goto out;
5015 we need to handle the case when we get a
5016 relative open relative to a file and the
5017 pathname is blank - this is a reopen!
5018 (hint from demyn plantenberg)
5021 status = NT_STATUS_INVALID_HANDLE;
5022 goto out;
5025 if (ISDOT(dir_fsp->fsp_name->base_name)) {
5027 * We're at the toplevel dir, the final file name
5028 * must not contain ./, as this is filtered out
5029 * normally by srvstr_get_path and unix_convert
5030 * explicitly rejects paths containing ./.
5032 parent_fname = talloc_strdup(talloc_tos(), "");
5033 if (parent_fname == NULL) {
5034 status = NT_STATUS_NO_MEMORY;
5035 goto out;
5037 } else {
5038 size_t dir_name_len = strlen(dir_fsp->fsp_name->base_name);
5041 * Copy in the base directory name.
5044 parent_fname = talloc_array(talloc_tos(), char,
5045 dir_name_len+2);
5046 if (parent_fname == NULL) {
5047 status = NT_STATUS_NO_MEMORY;
5048 goto out;
5050 memcpy(parent_fname, dir_fsp->fsp_name->base_name,
5051 dir_name_len+1);
5054 * Ensure it ends in a '/'.
5055 * We used TALLOC_SIZE +2 to add space for the '/'.
5058 if(dir_name_len
5059 && (parent_fname[dir_name_len-1] != '\\')
5060 && (parent_fname[dir_name_len-1] != '/')) {
5061 parent_fname[dir_name_len] = '/';
5062 parent_fname[dir_name_len+1] = '\0';
5066 new_base_name = talloc_asprintf(talloc_tos(), "%s%s", parent_fname,
5067 smb_fname->base_name);
5068 if (new_base_name == NULL) {
5069 status = NT_STATUS_NO_MEMORY;
5070 goto out;
5073 status = filename_convert(req,
5074 conn,
5075 req->flags2 & FLAGS2_DFS_PATHNAMES,
5076 new_base_name,
5077 ucf_flags,
5078 NULL,
5079 smb_fname_out);
5080 if (!NT_STATUS_IS_OK(status)) {
5081 goto out;
5084 out:
5085 TALLOC_FREE(parent_fname);
5086 TALLOC_FREE(new_base_name);
5087 return status;
5090 NTSTATUS create_file_default(connection_struct *conn,
5091 struct smb_request *req,
5092 uint16_t root_dir_fid,
5093 struct smb_filename *smb_fname,
5094 uint32_t access_mask,
5095 uint32_t share_access,
5096 uint32_t create_disposition,
5097 uint32_t create_options,
5098 uint32_t file_attributes,
5099 uint32_t oplock_request,
5100 struct smb2_lease *lease,
5101 uint64_t allocation_size,
5102 uint32_t private_flags,
5103 struct security_descriptor *sd,
5104 struct ea_list *ea_list,
5105 files_struct **result,
5106 int *pinfo,
5107 const struct smb2_create_blobs *in_context_blobs,
5108 struct smb2_create_blobs *out_context_blobs)
5110 int info = FILE_WAS_OPENED;
5111 files_struct *fsp = NULL;
5112 NTSTATUS status;
5113 bool stream_name = false;
5115 DEBUG(10,("create_file: access_mask = 0x%x "
5116 "file_attributes = 0x%x, share_access = 0x%x, "
5117 "create_disposition = 0x%x create_options = 0x%x "
5118 "oplock_request = 0x%x "
5119 "private_flags = 0x%x "
5120 "root_dir_fid = 0x%x, ea_list = 0x%p, sd = 0x%p, "
5121 "fname = %s\n",
5122 (unsigned int)access_mask,
5123 (unsigned int)file_attributes,
5124 (unsigned int)share_access,
5125 (unsigned int)create_disposition,
5126 (unsigned int)create_options,
5127 (unsigned int)oplock_request,
5128 (unsigned int)private_flags,
5129 (unsigned int)root_dir_fid,
5130 ea_list, sd, smb_fname_str_dbg(smb_fname)));
5133 * Calculate the filename from the root_dir_if if necessary.
5136 if (root_dir_fid != 0) {
5137 struct smb_filename *smb_fname_out = NULL;
5138 status = get_relative_fid_filename(conn, req, root_dir_fid,
5139 smb_fname, &smb_fname_out);
5140 if (!NT_STATUS_IS_OK(status)) {
5141 goto fail;
5143 smb_fname = smb_fname_out;
5147 * Check to see if this is a mac fork of some kind.
5150 stream_name = is_ntfs_stream_smb_fname(smb_fname);
5151 if (stream_name) {
5152 enum FAKE_FILE_TYPE fake_file_type;
5154 fake_file_type = is_fake_file(smb_fname);
5156 if (fake_file_type != FAKE_FILE_TYPE_NONE) {
5159 * Here we go! support for changing the disk quotas
5160 * --metze
5162 * We need to fake up to open this MAGIC QUOTA file
5163 * and return a valid FID.
5165 * w2k close this file directly after openening xp
5166 * also tries a QUERY_FILE_INFO on the file and then
5167 * close it
5169 status = open_fake_file(req, conn, req->vuid,
5170 fake_file_type, smb_fname,
5171 access_mask, &fsp);
5172 if (!NT_STATUS_IS_OK(status)) {
5173 goto fail;
5176 ZERO_STRUCT(smb_fname->st);
5177 goto done;
5180 if (!(conn->fs_capabilities & FILE_NAMED_STREAMS)) {
5181 status = NT_STATUS_OBJECT_NAME_NOT_FOUND;
5182 goto fail;
5186 if (is_ntfs_default_stream_smb_fname(smb_fname)) {
5187 int ret;
5188 smb_fname->stream_name = NULL;
5189 /* We have to handle this error here. */
5190 if (create_options & FILE_DIRECTORY_FILE) {
5191 status = NT_STATUS_NOT_A_DIRECTORY;
5192 goto fail;
5194 if (req != NULL && req->posix_pathnames) {
5195 ret = SMB_VFS_LSTAT(conn, smb_fname);
5196 } else {
5197 ret = SMB_VFS_STAT(conn, smb_fname);
5200 if (ret == 0 && VALID_STAT_OF_DIR(smb_fname->st)) {
5201 status = NT_STATUS_FILE_IS_A_DIRECTORY;
5202 goto fail;
5206 status = create_file_unixpath(
5207 conn, req, smb_fname, access_mask, share_access,
5208 create_disposition, create_options, file_attributes,
5209 oplock_request, lease, allocation_size, private_flags,
5210 sd, ea_list,
5211 &fsp, &info);
5213 if (!NT_STATUS_IS_OK(status)) {
5214 goto fail;
5217 done:
5218 DEBUG(10, ("create_file: info=%d\n", info));
5220 *result = fsp;
5221 if (pinfo != NULL) {
5222 *pinfo = info;
5224 return NT_STATUS_OK;
5226 fail:
5227 DEBUG(10, ("create_file: %s\n", nt_errstr(status)));
5229 if (fsp != NULL) {
5230 close_file(req, fsp, ERROR_CLOSE);
5231 fsp = NULL;
5233 return status;