s3/smbd: remove async_open arg from defer_open()
[Samba.git] / source3 / smbd / open.c
blob0fb82fe3d8a5c46bce002de044c45fee3876687a
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 "lib/util/server_id.h"
25 #include "printing.h"
26 #include "smbd/smbd.h"
27 #include "smbd/globals.h"
28 #include "fake_file.h"
29 #include "../libcli/security/security.h"
30 #include "../librpc/gen_ndr/ndr_security.h"
31 #include "../librpc/gen_ndr/open_files.h"
32 #include "../librpc/gen_ndr/idmap.h"
33 #include "../librpc/gen_ndr/ioctl.h"
34 #include "passdb/lookup_sid.h"
35 #include "auth.h"
36 #include "serverid.h"
37 #include "messages.h"
38 #include "source3/lib/dbwrap/dbwrap_watch.h"
39 #include "locking/leases_db.h"
40 #include "librpc/gen_ndr/ndr_leases_db.h"
42 extern const struct generic_mapping file_generic_mapping;
44 struct deferred_open_record {
45 bool delayed_for_oplocks;
46 bool async_open;
47 struct file_id id;
50 * Timer for async opens, needed because they don't use a watch on
51 * a locking.tdb record. This is currently only used for real async
52 * opens and just terminates smbd if the async open times out.
54 struct tevent_timer *te;
57 /****************************************************************************
58 If the requester wanted DELETE_ACCESS and was rejected because
59 the file ACL didn't include DELETE_ACCESS, see if the parent ACL
60 overrides this.
61 ****************************************************************************/
63 static bool parent_override_delete(connection_struct *conn,
64 const struct smb_filename *smb_fname,
65 uint32_t access_mask,
66 uint32_t rejected_mask)
68 if ((access_mask & DELETE_ACCESS) &&
69 (rejected_mask & DELETE_ACCESS) &&
70 can_delete_file_in_directory(conn, smb_fname)) {
71 return true;
73 return false;
76 /****************************************************************************
77 Check if we have open rights.
78 ****************************************************************************/
80 NTSTATUS smbd_check_access_rights(struct connection_struct *conn,
81 const struct smb_filename *smb_fname,
82 bool use_privs,
83 uint32_t access_mask)
85 /* Check if we have rights to open. */
86 NTSTATUS status;
87 struct security_descriptor *sd = NULL;
88 uint32_t rejected_share_access;
89 uint32_t rejected_mask = access_mask;
90 uint32_t do_not_check_mask = 0;
92 rejected_share_access = access_mask & ~(conn->share_access);
94 if (rejected_share_access) {
95 DEBUG(10, ("smbd_check_access_rights: rejected share access 0x%x "
96 "on %s (0x%x)\n",
97 (unsigned int)access_mask,
98 smb_fname_str_dbg(smb_fname),
99 (unsigned int)rejected_share_access ));
100 return NT_STATUS_ACCESS_DENIED;
103 if (!use_privs && get_current_uid(conn) == (uid_t)0) {
104 /* I'm sorry sir, I didn't know you were root... */
105 DEBUG(10,("smbd_check_access_rights: root override "
106 "on %s. Granting 0x%x\n",
107 smb_fname_str_dbg(smb_fname),
108 (unsigned int)access_mask ));
109 return NT_STATUS_OK;
112 if ((access_mask & DELETE_ACCESS) && !lp_acl_check_permissions(SNUM(conn))) {
113 DEBUG(10,("smbd_check_access_rights: not checking ACL "
114 "on DELETE_ACCESS on file %s. Granting 0x%x\n",
115 smb_fname_str_dbg(smb_fname),
116 (unsigned int)access_mask ));
117 return NT_STATUS_OK;
120 if (access_mask == DELETE_ACCESS &&
121 VALID_STAT(smb_fname->st) &&
122 S_ISLNK(smb_fname->st.st_ex_mode)) {
123 /* We can always delete a symlink. */
124 DEBUG(10,("smbd_check_access_rights: not checking ACL "
125 "on DELETE_ACCESS on symlink %s.\n",
126 smb_fname_str_dbg(smb_fname) ));
127 return NT_STATUS_OK;
130 status = SMB_VFS_GET_NT_ACL(conn, smb_fname,
131 (SECINFO_OWNER |
132 SECINFO_GROUP |
133 SECINFO_DACL), talloc_tos(), &sd);
135 if (!NT_STATUS_IS_OK(status)) {
136 DEBUG(10, ("smbd_check_access_rights: Could not get acl "
137 "on %s: %s\n",
138 smb_fname_str_dbg(smb_fname),
139 nt_errstr(status)));
141 if (NT_STATUS_EQUAL(status, NT_STATUS_ACCESS_DENIED)) {
142 goto access_denied;
145 return status;
149 * If we can access the path to this file, by
150 * default we have FILE_READ_ATTRIBUTES from the
151 * containing directory. See the section:
152 * "Algorithm to Check Access to an Existing File"
153 * in MS-FSA.pdf.
155 * se_file_access_check() also takes care of
156 * owner WRITE_DAC and READ_CONTROL.
158 do_not_check_mask = FILE_READ_ATTRIBUTES;
161 * Samba 3.6 and earlier granted execute access even
162 * if the ACL did not contain execute rights.
163 * Samba 4.0 is more correct and checks it.
164 * The compatibilty mode allows one to skip this check
165 * to smoothen upgrades.
167 if (lp_acl_allow_execute_always(SNUM(conn))) {
168 do_not_check_mask |= FILE_EXECUTE;
171 status = se_file_access_check(sd,
172 get_current_nttok(conn),
173 use_privs,
174 (access_mask & ~do_not_check_mask),
175 &rejected_mask);
177 DEBUG(10,("smbd_check_access_rights: file %s requesting "
178 "0x%x returning 0x%x (%s)\n",
179 smb_fname_str_dbg(smb_fname),
180 (unsigned int)access_mask,
181 (unsigned int)rejected_mask,
182 nt_errstr(status) ));
184 if (!NT_STATUS_IS_OK(status)) {
185 if (DEBUGLEVEL >= 10) {
186 DEBUG(10,("smbd_check_access_rights: acl for %s is:\n",
187 smb_fname_str_dbg(smb_fname) ));
188 NDR_PRINT_DEBUG(security_descriptor, sd);
192 TALLOC_FREE(sd);
194 if (NT_STATUS_IS_OK(status) ||
195 !NT_STATUS_EQUAL(status, NT_STATUS_ACCESS_DENIED)) {
196 return status;
199 /* Here we know status == NT_STATUS_ACCESS_DENIED. */
201 access_denied:
203 if ((access_mask & FILE_WRITE_ATTRIBUTES) &&
204 (rejected_mask & FILE_WRITE_ATTRIBUTES) &&
205 !lp_store_dos_attributes(SNUM(conn)) &&
206 (lp_map_readonly(SNUM(conn)) ||
207 lp_map_archive(SNUM(conn)) ||
208 lp_map_hidden(SNUM(conn)) ||
209 lp_map_system(SNUM(conn)))) {
210 rejected_mask &= ~FILE_WRITE_ATTRIBUTES;
212 DEBUG(10,("smbd_check_access_rights: "
213 "overrode "
214 "FILE_WRITE_ATTRIBUTES "
215 "on file %s\n",
216 smb_fname_str_dbg(smb_fname)));
219 if (parent_override_delete(conn,
220 smb_fname,
221 access_mask,
222 rejected_mask)) {
223 /* Were we trying to do an open
224 * for delete and didn't get DELETE
225 * access (only) ? Check if the
226 * directory allows DELETE_CHILD.
227 * See here:
228 * http://blogs.msdn.com/oldnewthing/archive/2004/06/04/148426.aspx
229 * for details. */
231 rejected_mask &= ~DELETE_ACCESS;
233 DEBUG(10,("smbd_check_access_rights: "
234 "overrode "
235 "DELETE_ACCESS on "
236 "file %s\n",
237 smb_fname_str_dbg(smb_fname)));
240 if (rejected_mask != 0) {
241 return NT_STATUS_ACCESS_DENIED;
243 return NT_STATUS_OK;
246 NTSTATUS check_parent_access(struct connection_struct *conn,
247 struct smb_filename *smb_fname,
248 uint32_t access_mask)
250 NTSTATUS status;
251 char *parent_dir = NULL;
252 struct security_descriptor *parent_sd = NULL;
253 uint32_t access_granted = 0;
254 struct smb_filename *parent_smb_fname = NULL;
256 if (!parent_dirname(talloc_tos(),
257 smb_fname->base_name,
258 &parent_dir,
259 NULL)) {
260 return NT_STATUS_NO_MEMORY;
263 parent_smb_fname = synthetic_smb_fname(talloc_tos(),
264 parent_dir,
265 NULL,
266 NULL,
267 smb_fname->flags);
268 if (parent_smb_fname == NULL) {
269 return NT_STATUS_NO_MEMORY;
272 if (get_current_uid(conn) == (uid_t)0) {
273 /* I'm sorry sir, I didn't know you were root... */
274 DEBUG(10,("check_parent_access: root override "
275 "on %s. Granting 0x%x\n",
276 smb_fname_str_dbg(smb_fname),
277 (unsigned int)access_mask ));
278 return NT_STATUS_OK;
281 status = SMB_VFS_GET_NT_ACL(conn,
282 parent_smb_fname,
283 SECINFO_DACL,
284 talloc_tos(),
285 &parent_sd);
287 if (!NT_STATUS_IS_OK(status)) {
288 DEBUG(5,("check_parent_access: SMB_VFS_GET_NT_ACL failed for "
289 "%s with error %s\n",
290 parent_dir,
291 nt_errstr(status)));
292 return status;
296 * If we can access the path to this file, by
297 * default we have FILE_READ_ATTRIBUTES from the
298 * containing directory. See the section:
299 * "Algorithm to Check Access to an Existing File"
300 * in MS-FSA.pdf.
302 * se_file_access_check() also takes care of
303 * owner WRITE_DAC and READ_CONTROL.
305 status = se_file_access_check(parent_sd,
306 get_current_nttok(conn),
307 false,
308 (access_mask & ~FILE_READ_ATTRIBUTES),
309 &access_granted);
310 if(!NT_STATUS_IS_OK(status)) {
311 DEBUG(5,("check_parent_access: access check "
312 "on directory %s for "
313 "path %s for mask 0x%x returned (0x%x) %s\n",
314 parent_dir,
315 smb_fname->base_name,
316 access_mask,
317 access_granted,
318 nt_errstr(status) ));
319 return status;
322 return NT_STATUS_OK;
325 /****************************************************************************
326 Ensure when opening a base file for a stream open that we have permissions
327 to do so given the access mask on the base file.
328 ****************************************************************************/
330 static NTSTATUS check_base_file_access(struct connection_struct *conn,
331 struct smb_filename *smb_fname,
332 uint32_t access_mask)
334 NTSTATUS status;
336 status = smbd_calculate_access_mask(conn, smb_fname,
337 false,
338 access_mask,
339 &access_mask);
340 if (!NT_STATUS_IS_OK(status)) {
341 DEBUG(10, ("smbd_calculate_access_mask "
342 "on file %s returned %s\n",
343 smb_fname_str_dbg(smb_fname),
344 nt_errstr(status)));
345 return status;
348 if (access_mask & (FILE_WRITE_DATA|FILE_APPEND_DATA)) {
349 uint32_t dosattrs;
350 if (!CAN_WRITE(conn)) {
351 return NT_STATUS_ACCESS_DENIED;
353 dosattrs = dos_mode(conn, smb_fname);
354 if (IS_DOS_READONLY(dosattrs)) {
355 return NT_STATUS_ACCESS_DENIED;
359 return smbd_check_access_rights(conn,
360 smb_fname,
361 false,
362 access_mask);
365 /****************************************************************************
366 fd support routines - attempt to do a dos_open.
367 ****************************************************************************/
369 NTSTATUS fd_open(struct connection_struct *conn,
370 files_struct *fsp,
371 int flags,
372 mode_t mode)
374 struct smb_filename *smb_fname = fsp->fsp_name;
375 NTSTATUS status = NT_STATUS_OK;
377 #ifdef O_NOFOLLOW
379 * Never follow symlinks on a POSIX client. The
380 * client should be doing this.
383 if ((fsp->posix_flags & FSP_POSIX_FLAGS_OPEN) || !lp_follow_symlinks(SNUM(conn))) {
384 flags |= O_NOFOLLOW;
386 #endif
388 fsp->fh->fd = SMB_VFS_OPEN(conn, smb_fname, fsp, flags, mode);
389 if (fsp->fh->fd == -1) {
390 int posix_errno = errno;
391 #ifdef O_NOFOLLOW
392 #if defined(ENOTSUP) && defined(OSF1)
393 /* handle special Tru64 errno */
394 if (errno == ENOTSUP) {
395 posix_errno = ELOOP;
397 #endif /* ENOTSUP */
398 #ifdef EFTYPE
399 /* fix broken NetBSD errno */
400 if (errno == EFTYPE) {
401 posix_errno = ELOOP;
403 #endif /* EFTYPE */
404 /* fix broken FreeBSD errno */
405 if (errno == EMLINK) {
406 posix_errno = ELOOP;
408 #endif /* O_NOFOLLOW */
409 status = map_nt_error_from_unix(posix_errno);
410 if (errno == EMFILE) {
411 static time_t last_warned = 0L;
413 if (time((time_t *) NULL) > last_warned) {
414 DEBUG(0,("Too many open files, unable "
415 "to open more! smbd's max "
416 "open files = %d\n",
417 lp_max_open_files()));
418 last_warned = time((time_t *) NULL);
424 DEBUG(10,("fd_open: name %s, flags = 0%o mode = 0%o, fd = %d. %s\n",
425 smb_fname_str_dbg(smb_fname), flags, (int)mode, fsp->fh->fd,
426 (fsp->fh->fd == -1) ? strerror(errno) : "" ));
428 return status;
431 /****************************************************************************
432 Close the file associated with a fsp.
433 ****************************************************************************/
435 NTSTATUS fd_close(files_struct *fsp)
437 int ret;
439 if (fsp->dptr) {
440 dptr_CloseDir(fsp);
442 if (fsp->fh->fd == -1) {
443 return NT_STATUS_OK; /* What we used to call a stat open. */
445 if (fsp->fh->ref_count > 1) {
446 return NT_STATUS_OK; /* Shared handle. Only close last reference. */
449 ret = SMB_VFS_CLOSE(fsp);
450 fsp->fh->fd = -1;
451 if (ret == -1) {
452 return map_nt_error_from_unix(errno);
454 return NT_STATUS_OK;
457 /****************************************************************************
458 Change the ownership of a file to that of the parent directory.
459 Do this by fd if possible.
460 ****************************************************************************/
462 void change_file_owner_to_parent(connection_struct *conn,
463 const char *inherit_from_dir,
464 files_struct *fsp)
466 struct smb_filename *smb_fname_parent;
467 int ret;
469 smb_fname_parent = synthetic_smb_fname(talloc_tos(),
470 inherit_from_dir,
471 NULL,
472 NULL,
474 if (smb_fname_parent == NULL) {
475 return;
478 ret = SMB_VFS_STAT(conn, smb_fname_parent);
479 if (ret == -1) {
480 DEBUG(0,("change_file_owner_to_parent: failed to stat parent "
481 "directory %s. Error was %s\n",
482 smb_fname_str_dbg(smb_fname_parent),
483 strerror(errno)));
484 TALLOC_FREE(smb_fname_parent);
485 return;
488 if (smb_fname_parent->st.st_ex_uid == fsp->fsp_name->st.st_ex_uid) {
489 /* Already this uid - no need to change. */
490 DEBUG(10,("change_file_owner_to_parent: file %s "
491 "is already owned by uid %d\n",
492 fsp_str_dbg(fsp),
493 (int)fsp->fsp_name->st.st_ex_uid ));
494 TALLOC_FREE(smb_fname_parent);
495 return;
498 become_root();
499 ret = SMB_VFS_FCHOWN(fsp, smb_fname_parent->st.st_ex_uid, (gid_t)-1);
500 unbecome_root();
501 if (ret == -1) {
502 DEBUG(0,("change_file_owner_to_parent: failed to fchown "
503 "file %s to parent directory uid %u. Error "
504 "was %s\n", fsp_str_dbg(fsp),
505 (unsigned int)smb_fname_parent->st.st_ex_uid,
506 strerror(errno) ));
507 } else {
508 DEBUG(10,("change_file_owner_to_parent: changed new file %s to "
509 "parent directory uid %u.\n", fsp_str_dbg(fsp),
510 (unsigned int)smb_fname_parent->st.st_ex_uid));
511 /* Ensure the uid entry is updated. */
512 fsp->fsp_name->st.st_ex_uid = smb_fname_parent->st.st_ex_uid;
515 TALLOC_FREE(smb_fname_parent);
518 NTSTATUS change_dir_owner_to_parent(connection_struct *conn,
519 const char *inherit_from_dir,
520 const char *fname,
521 SMB_STRUCT_STAT *psbuf)
523 struct smb_filename *smb_fname_parent;
524 struct smb_filename *smb_fname_cwd = NULL;
525 char *saved_dir = NULL;
526 TALLOC_CTX *ctx = talloc_tos();
527 NTSTATUS status = NT_STATUS_OK;
528 int ret;
530 smb_fname_parent = synthetic_smb_fname(ctx,
531 inherit_from_dir,
532 NULL,
533 NULL,
535 if (smb_fname_parent == NULL) {
536 return NT_STATUS_NO_MEMORY;
539 ret = SMB_VFS_STAT(conn, smb_fname_parent);
540 if (ret == -1) {
541 status = map_nt_error_from_unix(errno);
542 DEBUG(0,("change_dir_owner_to_parent: failed to stat parent "
543 "directory %s. Error was %s\n",
544 smb_fname_str_dbg(smb_fname_parent),
545 strerror(errno)));
546 goto out;
549 /* We've already done an lstat into psbuf, and we know it's a
550 directory. If we can cd into the directory and the dev/ino
551 are the same then we can safely chown without races as
552 we're locking the directory in place by being in it. This
553 should work on any UNIX (thanks tridge :-). JRA.
556 saved_dir = vfs_GetWd(ctx,conn);
557 if (!saved_dir) {
558 status = map_nt_error_from_unix(errno);
559 DEBUG(0,("change_dir_owner_to_parent: failed to get "
560 "current working directory. Error was %s\n",
561 strerror(errno)));
562 goto out;
565 /* Chdir into the new path. */
566 if (vfs_ChDir(conn, fname) == -1) {
567 status = map_nt_error_from_unix(errno);
568 DEBUG(0,("change_dir_owner_to_parent: failed to change "
569 "current working directory to %s. Error "
570 "was %s\n", fname, strerror(errno) ));
571 goto chdir;
574 smb_fname_cwd = synthetic_smb_fname(ctx, ".", NULL, NULL, 0);
575 if (smb_fname_cwd == NULL) {
576 status = NT_STATUS_NO_MEMORY;
577 goto chdir;
580 ret = SMB_VFS_STAT(conn, smb_fname_cwd);
581 if (ret == -1) {
582 status = map_nt_error_from_unix(errno);
583 DEBUG(0,("change_dir_owner_to_parent: failed to stat "
584 "directory '.' (%s) Error was %s\n",
585 fname, strerror(errno)));
586 goto chdir;
589 /* Ensure we're pointing at the same place. */
590 if (smb_fname_cwd->st.st_ex_dev != psbuf->st_ex_dev ||
591 smb_fname_cwd->st.st_ex_ino != psbuf->st_ex_ino) {
592 DEBUG(0,("change_dir_owner_to_parent: "
593 "device/inode on directory %s changed. "
594 "Refusing to chown !\n", fname ));
595 status = NT_STATUS_ACCESS_DENIED;
596 goto chdir;
599 if (smb_fname_parent->st.st_ex_uid == smb_fname_cwd->st.st_ex_uid) {
600 /* Already this uid - no need to change. */
601 DEBUG(10,("change_dir_owner_to_parent: directory %s "
602 "is already owned by uid %d\n",
603 fname,
604 (int)smb_fname_cwd->st.st_ex_uid ));
605 status = NT_STATUS_OK;
606 goto chdir;
609 become_root();
610 ret = SMB_VFS_LCHOWN(conn,
611 smb_fname_cwd,
612 smb_fname_parent->st.st_ex_uid,
613 (gid_t)-1);
614 unbecome_root();
615 if (ret == -1) {
616 status = map_nt_error_from_unix(errno);
617 DEBUG(10,("change_dir_owner_to_parent: failed to chown "
618 "directory %s to parent directory uid %u. "
619 "Error was %s\n", fname,
620 (unsigned int)smb_fname_parent->st.st_ex_uid,
621 strerror(errno) ));
622 } else {
623 DEBUG(10,("change_dir_owner_to_parent: changed ownership of new "
624 "directory %s to parent directory uid %u.\n",
625 fname, (unsigned int)smb_fname_parent->st.st_ex_uid ));
626 /* Ensure the uid entry is updated. */
627 psbuf->st_ex_uid = smb_fname_parent->st.st_ex_uid;
630 chdir:
631 vfs_ChDir(conn,saved_dir);
632 out:
633 TALLOC_FREE(smb_fname_parent);
634 TALLOC_FREE(smb_fname_cwd);
635 return status;
638 /****************************************************************************
639 Open a file - returning a guaranteed ATOMIC indication of if the
640 file was created or not.
641 ****************************************************************************/
643 static NTSTATUS fd_open_atomic(struct connection_struct *conn,
644 files_struct *fsp,
645 int flags,
646 mode_t mode,
647 bool *file_created)
649 NTSTATUS status = NT_STATUS_UNSUCCESSFUL;
650 NTSTATUS retry_status;
651 bool file_existed = VALID_STAT(fsp->fsp_name->st);
652 int curr_flags;
654 *file_created = false;
656 if (!(flags & O_CREAT)) {
658 * We're not creating the file, just pass through.
660 return fd_open(conn, fsp, flags, mode);
663 if (flags & O_EXCL) {
665 * Fail if already exists, just pass through.
667 status = fd_open(conn, fsp, flags, mode);
670 * Here we've opened with O_CREAT|O_EXCL. If that went
671 * NT_STATUS_OK, we *know* we created this file.
673 *file_created = NT_STATUS_IS_OK(status);
675 return status;
679 * Now it gets tricky. We have O_CREAT, but not O_EXCL.
680 * To know absolutely if we created the file or not,
681 * we can never call O_CREAT without O_EXCL. So if
682 * we think the file existed, try without O_CREAT|O_EXCL.
683 * If we think the file didn't exist, try with
684 * O_CREAT|O_EXCL.
686 * The big problem here is dangling symlinks. Opening
687 * without O_NOFOLLOW means both bad symlink
688 * and missing path return -1, ENOENT from open(). As POSIX
689 * is pathname based it's not possible to tell
690 * the difference between these two cases in a
691 * non-racy way, so change to try only two attempts before
692 * giving up.
694 * We don't have this problem for the O_NOFOLLOW
695 * case as it just returns NT_STATUS_OBJECT_PATH_NOT_FOUND
696 * mapped from the ELOOP POSIX error.
699 curr_flags = flags;
701 if (file_existed) {
702 curr_flags &= ~(O_CREAT);
703 retry_status = NT_STATUS_OBJECT_NAME_NOT_FOUND;
704 } else {
705 curr_flags |= O_EXCL;
706 retry_status = NT_STATUS_OBJECT_NAME_COLLISION;
709 status = fd_open(conn, fsp, curr_flags, mode);
710 if (NT_STATUS_IS_OK(status)) {
711 if (!file_existed) {
712 *file_created = true;
714 return NT_STATUS_OK;
716 if (!NT_STATUS_EQUAL(status, retry_status)) {
717 return status;
720 curr_flags = flags;
723 * Keep file_existed up to date for clarity.
725 if (NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
726 file_existed = false;
727 curr_flags |= O_EXCL;
728 DBG_DEBUG("file %s did not exist. Retry.\n",
729 smb_fname_str_dbg(fsp->fsp_name));
730 } else {
731 file_existed = true;
732 curr_flags &= ~(O_CREAT);
733 DBG_DEBUG("file %s existed. Retry.\n",
734 smb_fname_str_dbg(fsp->fsp_name));
737 status = fd_open(conn, fsp, curr_flags, mode);
739 if (NT_STATUS_IS_OK(status) && (!file_existed)) {
740 *file_created = true;
743 return status;
746 /****************************************************************************
747 Open a file.
748 ****************************************************************************/
750 static NTSTATUS open_file(files_struct *fsp,
751 connection_struct *conn,
752 struct smb_request *req,
753 const char *parent_dir,
754 int flags,
755 mode_t unx_mode,
756 uint32_t access_mask, /* client requested access mask. */
757 uint32_t open_access_mask, /* what we're actually using in the open. */
758 bool *p_file_created)
760 struct smb_filename *smb_fname = fsp->fsp_name;
761 NTSTATUS status = NT_STATUS_OK;
762 int accmode = (flags & O_ACCMODE);
763 int local_flags = flags;
764 bool file_existed = VALID_STAT(fsp->fsp_name->st);
766 fsp->fh->fd = -1;
767 errno = EPERM;
769 /* Check permissions */
772 * This code was changed after seeing a client open request
773 * containing the open mode of (DENY_WRITE/read-only) with
774 * the 'create if not exist' bit set. The previous code
775 * would fail to open the file read only on a read-only share
776 * as it was checking the flags parameter directly against O_RDONLY,
777 * this was failing as the flags parameter was set to O_RDONLY|O_CREAT.
778 * JRA.
781 if (!CAN_WRITE(conn)) {
782 /* It's a read-only share - fail if we wanted to write. */
783 if(accmode != O_RDONLY || (flags & O_TRUNC) || (flags & O_APPEND)) {
784 DEBUG(3,("Permission denied opening %s\n",
785 smb_fname_str_dbg(smb_fname)));
786 return NT_STATUS_ACCESS_DENIED;
788 if (flags & O_CREAT) {
789 /* We don't want to write - but we must make sure that
790 O_CREAT doesn't create the file if we have write
791 access into the directory.
793 flags &= ~(O_CREAT|O_EXCL);
794 local_flags &= ~(O_CREAT|O_EXCL);
799 * This little piece of insanity is inspired by the
800 * fact that an NT client can open a file for O_RDONLY,
801 * but set the create disposition to FILE_EXISTS_TRUNCATE.
802 * If the client *can* write to the file, then it expects to
803 * truncate the file, even though it is opening for readonly.
804 * Quicken uses this stupid trick in backup file creation...
805 * Thanks *greatly* to "David W. Chapman Jr." <dwcjr@inethouston.net>
806 * for helping track this one down. It didn't bite us in 2.0.x
807 * as we always opened files read-write in that release. JRA.
810 if ((accmode == O_RDONLY) && ((flags & O_TRUNC) == O_TRUNC)) {
811 DEBUG(10,("open_file: truncate requested on read-only open "
812 "for file %s\n", smb_fname_str_dbg(smb_fname)));
813 local_flags = (flags & ~O_ACCMODE)|O_RDWR;
816 if ((open_access_mask & (FILE_READ_DATA|FILE_WRITE_DATA|FILE_APPEND_DATA|FILE_EXECUTE)) ||
817 (!file_existed && (local_flags & O_CREAT)) ||
818 ((local_flags & O_TRUNC) == O_TRUNC) ) {
819 const char *wild;
820 int ret;
822 #if defined(O_NONBLOCK) && defined(S_ISFIFO)
824 * We would block on opening a FIFO with no one else on the
825 * other end. Do what we used to do and add O_NONBLOCK to the
826 * open flags. JRA.
829 if (file_existed && S_ISFIFO(smb_fname->st.st_ex_mode)) {
830 local_flags &= ~O_TRUNC; /* Can't truncate a FIFO. */
831 local_flags |= O_NONBLOCK;
833 #endif
835 /* Don't create files with Microsoft wildcard characters. */
836 if (fsp->base_fsp) {
838 * wildcard characters are allowed in stream names
839 * only test the basefilename
841 wild = fsp->base_fsp->fsp_name->base_name;
842 } else {
843 wild = smb_fname->base_name;
845 if ((local_flags & O_CREAT) && !file_existed &&
846 !(fsp->posix_flags & FSP_POSIX_FLAGS_PATHNAMES) &&
847 ms_has_wild(wild)) {
848 return NT_STATUS_OBJECT_NAME_INVALID;
851 /* Can we access this file ? */
852 if (!fsp->base_fsp) {
853 /* Only do this check on non-stream open. */
854 if (file_existed) {
855 status = smbd_check_access_rights(conn,
856 smb_fname,
857 false,
858 access_mask);
860 if (!NT_STATUS_IS_OK(status)) {
861 DEBUG(10, ("open_file: "
862 "smbd_check_access_rights "
863 "on file %s returned %s\n",
864 smb_fname_str_dbg(smb_fname),
865 nt_errstr(status)));
868 if (!NT_STATUS_IS_OK(status) &&
869 !NT_STATUS_EQUAL(status,
870 NT_STATUS_OBJECT_NAME_NOT_FOUND))
872 return status;
875 if (NT_STATUS_EQUAL(status,
876 NT_STATUS_OBJECT_NAME_NOT_FOUND))
878 DEBUG(10, ("open_file: "
879 "file %s vanished since we "
880 "checked for existence.\n",
881 smb_fname_str_dbg(smb_fname)));
882 file_existed = false;
883 SET_STAT_INVALID(fsp->fsp_name->st);
887 if (!file_existed) {
888 if (!(local_flags & O_CREAT)) {
889 /* File didn't exist and no O_CREAT. */
890 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
893 status = check_parent_access(conn,
894 smb_fname,
895 SEC_DIR_ADD_FILE);
896 if (!NT_STATUS_IS_OK(status)) {
897 DEBUG(10, ("open_file: "
898 "check_parent_access on "
899 "file %s returned %s\n",
900 smb_fname_str_dbg(smb_fname),
901 nt_errstr(status) ));
902 return status;
908 * Actually do the open - if O_TRUNC is needed handle it
909 * below under the share mode lock.
911 status = fd_open_atomic(conn, fsp, local_flags & ~O_TRUNC,
912 unx_mode, p_file_created);
913 if (!NT_STATUS_IS_OK(status)) {
914 DEBUG(3,("Error opening file %s (%s) (local_flags=%d) "
915 "(flags=%d)\n", smb_fname_str_dbg(smb_fname),
916 nt_errstr(status),local_flags,flags));
917 return status;
920 if (local_flags & O_NONBLOCK) {
922 * GPFS can return ETIMEDOUT for pread on
923 * nonblocking file descriptors when files
924 * migrated to tape need to be recalled. I
925 * could imagine this happens elsehwere
926 * too. With blocking file descriptors this
927 * does not happen.
929 ret = set_blocking(fsp->fh->fd, true);
930 if (ret == -1) {
931 status = map_nt_error_from_unix(errno);
932 DBG_WARNING("Could not set fd to blocking: "
933 "%s\n", strerror(errno));
934 fd_close(fsp);
935 return status;
939 ret = SMB_VFS_FSTAT(fsp, &smb_fname->st);
940 if (ret == -1) {
941 /* If we have an fd, this stat should succeed. */
942 DEBUG(0,("Error doing fstat on open file %s "
943 "(%s)\n",
944 smb_fname_str_dbg(smb_fname),
945 strerror(errno) ));
946 status = map_nt_error_from_unix(errno);
947 fd_close(fsp);
948 return status;
951 if (*p_file_created) {
952 /* We created this file. */
954 bool need_re_stat = false;
955 /* Do all inheritance work after we've
956 done a successful fstat call and filled
957 in the stat struct in fsp->fsp_name. */
959 /* Inherit the ACL if required */
960 if (lp_inherit_permissions(SNUM(conn))) {
961 inherit_access_posix_acl(conn, parent_dir,
962 smb_fname->base_name,
963 unx_mode);
964 need_re_stat = true;
967 /* Change the owner if required. */
968 if (lp_inherit_owner(SNUM(conn)) != INHERIT_OWNER_NO) {
969 change_file_owner_to_parent(conn, parent_dir,
970 fsp);
971 need_re_stat = true;
974 if (need_re_stat) {
975 ret = SMB_VFS_FSTAT(fsp, &smb_fname->st);
976 /* If we have an fd, this stat should succeed. */
977 if (ret == -1) {
978 DEBUG(0,("Error doing fstat on open file %s "
979 "(%s)\n",
980 smb_fname_str_dbg(smb_fname),
981 strerror(errno) ));
985 notify_fname(conn, NOTIFY_ACTION_ADDED,
986 FILE_NOTIFY_CHANGE_FILE_NAME,
987 smb_fname->base_name);
989 } else {
990 fsp->fh->fd = -1; /* What we used to call a stat open. */
991 if (!file_existed) {
992 /* File must exist for a stat open. */
993 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
996 status = smbd_check_access_rights(conn,
997 smb_fname,
998 false,
999 access_mask);
1001 if (NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND) &&
1002 (fsp->posix_flags & FSP_POSIX_FLAGS_OPEN) &&
1003 S_ISLNK(smb_fname->st.st_ex_mode)) {
1004 /* This is a POSIX stat open for delete
1005 * or rename on a symlink that points
1006 * nowhere. Allow. */
1007 DEBUG(10,("open_file: allowing POSIX "
1008 "open on bad symlink %s\n",
1009 smb_fname_str_dbg(smb_fname)));
1010 status = NT_STATUS_OK;
1013 if (!NT_STATUS_IS_OK(status)) {
1014 DEBUG(10,("open_file: "
1015 "smbd_check_access_rights on file "
1016 "%s returned %s\n",
1017 smb_fname_str_dbg(smb_fname),
1018 nt_errstr(status) ));
1019 return status;
1024 * POSIX allows read-only opens of directories. We don't
1025 * want to do this (we use a different code path for this)
1026 * so catch a directory open and return an EISDIR. JRA.
1029 if(S_ISDIR(smb_fname->st.st_ex_mode)) {
1030 fd_close(fsp);
1031 errno = EISDIR;
1032 return NT_STATUS_FILE_IS_A_DIRECTORY;
1035 fsp->file_id = vfs_file_id_from_sbuf(conn, &smb_fname->st);
1036 fsp->vuid = req ? req->vuid : UID_FIELD_INVALID;
1037 fsp->file_pid = req ? req->smbpid : 0;
1038 fsp->can_lock = True;
1039 fsp->can_read = ((access_mask & FILE_READ_DATA) != 0);
1040 fsp->can_write =
1041 CAN_WRITE(conn) &&
1042 ((access_mask & (FILE_WRITE_DATA | FILE_APPEND_DATA)) != 0);
1043 fsp->print_file = NULL;
1044 fsp->modified = False;
1045 fsp->sent_oplock_break = NO_BREAK_SENT;
1046 fsp->is_directory = False;
1047 if (conn->aio_write_behind_list &&
1048 is_in_path(smb_fname->base_name, conn->aio_write_behind_list,
1049 conn->case_sensitive)) {
1050 fsp->aio_write_behind = True;
1053 fsp->wcp = NULL; /* Write cache pointer. */
1055 DEBUG(2,("%s opened file %s read=%s write=%s (numopen=%d)\n",
1056 conn->session_info->unix_info->unix_name,
1057 smb_fname_str_dbg(smb_fname),
1058 BOOLSTR(fsp->can_read), BOOLSTR(fsp->can_write),
1059 conn->num_files_open));
1061 errno = 0;
1062 return NT_STATUS_OK;
1065 /****************************************************************************
1066 Check if we can open a file with a share mode.
1067 Returns True if conflict, False if not.
1068 ****************************************************************************/
1070 static bool share_conflict(struct share_mode_entry *entry,
1071 uint32_t access_mask,
1072 uint32_t share_access)
1074 DEBUG(10,("share_conflict: entry->access_mask = 0x%x, "
1075 "entry->share_access = 0x%x, "
1076 "entry->private_options = 0x%x\n",
1077 (unsigned int)entry->access_mask,
1078 (unsigned int)entry->share_access,
1079 (unsigned int)entry->private_options));
1081 if (server_id_is_disconnected(&entry->pid)) {
1083 * note: cleanup should have been done by
1084 * delay_for_batch_oplocks()
1086 return false;
1089 DEBUG(10,("share_conflict: access_mask = 0x%x, share_access = 0x%x\n",
1090 (unsigned int)access_mask, (unsigned int)share_access));
1092 if ((entry->access_mask & (FILE_WRITE_DATA|
1093 FILE_APPEND_DATA|
1094 FILE_READ_DATA|
1095 FILE_EXECUTE|
1096 DELETE_ACCESS)) == 0) {
1097 DEBUG(10,("share_conflict: No conflict due to "
1098 "entry->access_mask = 0x%x\n",
1099 (unsigned int)entry->access_mask ));
1100 return False;
1103 if ((access_mask & (FILE_WRITE_DATA|
1104 FILE_APPEND_DATA|
1105 FILE_READ_DATA|
1106 FILE_EXECUTE|
1107 DELETE_ACCESS)) == 0) {
1108 DEBUG(10,("share_conflict: No conflict due to "
1109 "access_mask = 0x%x\n",
1110 (unsigned int)access_mask ));
1111 return False;
1114 #if 1 /* JRA TEST - Superdebug. */
1115 #define CHECK_MASK(num, am, right, sa, share) \
1116 DEBUG(10,("share_conflict: [%d] am (0x%x) & right (0x%x) = 0x%x\n", \
1117 (unsigned int)(num), (unsigned int)(am), \
1118 (unsigned int)(right), (unsigned int)(am)&(right) )); \
1119 DEBUG(10,("share_conflict: [%d] sa (0x%x) & share (0x%x) = 0x%x\n", \
1120 (unsigned int)(num), (unsigned int)(sa), \
1121 (unsigned int)(share), (unsigned int)(sa)&(share) )); \
1122 if (((am) & (right)) && !((sa) & (share))) { \
1123 DEBUG(10,("share_conflict: check %d conflict am = 0x%x, right = 0x%x, \
1124 sa = 0x%x, share = 0x%x\n", (num), (unsigned int)(am), (unsigned int)(right), (unsigned int)(sa), \
1125 (unsigned int)(share) )); \
1126 return True; \
1128 #else
1129 #define CHECK_MASK(num, am, right, sa, share) \
1130 if (((am) & (right)) && !((sa) & (share))) { \
1131 DEBUG(10,("share_conflict: check %d conflict am = 0x%x, right = 0x%x, \
1132 sa = 0x%x, share = 0x%x\n", (num), (unsigned int)(am), (unsigned int)(right), (unsigned int)(sa), \
1133 (unsigned int)(share) )); \
1134 return True; \
1136 #endif
1138 CHECK_MASK(1, entry->access_mask, FILE_WRITE_DATA | FILE_APPEND_DATA,
1139 share_access, FILE_SHARE_WRITE);
1140 CHECK_MASK(2, access_mask, FILE_WRITE_DATA | FILE_APPEND_DATA,
1141 entry->share_access, FILE_SHARE_WRITE);
1143 CHECK_MASK(3, entry->access_mask, FILE_READ_DATA | FILE_EXECUTE,
1144 share_access, FILE_SHARE_READ);
1145 CHECK_MASK(4, access_mask, FILE_READ_DATA | FILE_EXECUTE,
1146 entry->share_access, FILE_SHARE_READ);
1148 CHECK_MASK(5, entry->access_mask, DELETE_ACCESS,
1149 share_access, FILE_SHARE_DELETE);
1150 CHECK_MASK(6, access_mask, DELETE_ACCESS,
1151 entry->share_access, FILE_SHARE_DELETE);
1153 DEBUG(10,("share_conflict: No conflict.\n"));
1154 return False;
1157 #if defined(DEVELOPER)
1158 static void validate_my_share_entries(struct smbd_server_connection *sconn,
1159 int num,
1160 struct share_mode_entry *share_entry)
1162 struct server_id self = messaging_server_id(sconn->msg_ctx);
1163 files_struct *fsp;
1165 if (!serverid_equal(&self, &share_entry->pid)) {
1166 return;
1169 if (share_entry->op_mid == 0) {
1170 /* INTERNAL_OPEN_ONLY */
1171 return;
1174 if (!is_valid_share_mode_entry(share_entry)) {
1175 return;
1178 fsp = file_find_dif(sconn, share_entry->id,
1179 share_entry->share_file_id);
1180 if (!fsp) {
1181 DEBUG(0,("validate_my_share_entries: PANIC : %s\n",
1182 share_mode_str(talloc_tos(), num, share_entry) ));
1183 smb_panic("validate_my_share_entries: Cannot match a "
1184 "share entry with an open file\n");
1187 if (((uint16_t)fsp->oplock_type) != share_entry->op_type) {
1188 goto panic;
1191 return;
1193 panic:
1195 char *str;
1196 DEBUG(0,("validate_my_share_entries: PANIC : %s\n",
1197 share_mode_str(talloc_tos(), num, share_entry) ));
1198 str = talloc_asprintf(talloc_tos(),
1199 "validate_my_share_entries: "
1200 "file %s, oplock_type = 0x%x, op_type = 0x%x\n",
1201 fsp->fsp_name->base_name,
1202 (unsigned int)fsp->oplock_type,
1203 (unsigned int)share_entry->op_type );
1204 smb_panic(str);
1207 #endif
1209 bool is_stat_open(uint32_t access_mask)
1211 const uint32_t stat_open_bits =
1212 (SYNCHRONIZE_ACCESS|
1213 FILE_READ_ATTRIBUTES|
1214 FILE_WRITE_ATTRIBUTES);
1216 return (((access_mask & stat_open_bits) != 0) &&
1217 ((access_mask & ~stat_open_bits) == 0));
1220 static bool has_delete_on_close(struct share_mode_lock *lck,
1221 uint32_t name_hash)
1223 struct share_mode_data *d = lck->data;
1224 uint32_t i;
1226 if (d->num_share_modes == 0) {
1227 return false;
1229 if (!is_delete_on_close_set(lck, name_hash)) {
1230 return false;
1232 for (i=0; i<d->num_share_modes; i++) {
1233 if (!share_mode_stale_pid(d, i)) {
1234 return true;
1237 return false;
1240 /****************************************************************************
1241 Deal with share modes
1242 Invariant: Share mode must be locked on entry and exit.
1243 Returns -1 on error, or number of share modes on success (may be zero).
1244 ****************************************************************************/
1246 static NTSTATUS open_mode_check(connection_struct *conn,
1247 struct share_mode_lock *lck,
1248 uint32_t access_mask,
1249 uint32_t share_access)
1251 uint32_t i;
1253 if(lck->data->num_share_modes == 0) {
1254 return NT_STATUS_OK;
1257 if (is_stat_open(access_mask)) {
1258 /* Stat open that doesn't trigger oplock breaks or share mode
1259 * checks... ! JRA. */
1260 return NT_STATUS_OK;
1264 * Check if the share modes will give us access.
1267 #if defined(DEVELOPER)
1268 for(i = 0; i < lck->data->num_share_modes; i++) {
1269 validate_my_share_entries(conn->sconn, i,
1270 &lck->data->share_modes[i]);
1272 #endif
1274 /* Now we check the share modes, after any oplock breaks. */
1275 for(i = 0; i < lck->data->num_share_modes; i++) {
1277 if (!is_valid_share_mode_entry(&lck->data->share_modes[i])) {
1278 continue;
1281 /* someone else has a share lock on it, check to see if we can
1282 * too */
1283 if (share_conflict(&lck->data->share_modes[i],
1284 access_mask, share_access)) {
1286 if (share_mode_stale_pid(lck->data, i)) {
1287 continue;
1290 return NT_STATUS_SHARING_VIOLATION;
1294 return NT_STATUS_OK;
1298 * Send a break message to the oplock holder and delay the open for
1299 * our client.
1302 NTSTATUS send_break_message(struct messaging_context *msg_ctx,
1303 const struct share_mode_entry *exclusive,
1304 uint16_t break_to)
1306 NTSTATUS status;
1307 char msg[MSG_SMB_SHARE_MODE_ENTRY_SIZE];
1308 struct server_id_buf tmp;
1310 DEBUG(10, ("Sending break request to PID %s\n",
1311 server_id_str_buf(exclusive->pid, &tmp)));
1313 /* Create the message. */
1314 share_mode_entry_to_message(msg, exclusive);
1316 /* Overload entry->op_type */
1318 * This is a cut from uint32_t to uint16_t, but so far only the lower 3
1319 * bits (LEASE_WRITE/HANDLE/READ are used anyway.
1321 SSVAL(msg,OP_BREAK_MSG_OP_TYPE_OFFSET, break_to);
1323 status = messaging_send_buf(msg_ctx, exclusive->pid,
1324 MSG_SMB_BREAK_REQUEST,
1325 (uint8_t *)msg, sizeof(msg));
1326 if (!NT_STATUS_IS_OK(status)) {
1327 DEBUG(3, ("Could not send oplock break message: %s\n",
1328 nt_errstr(status)));
1331 return status;
1335 * Do internal consistency checks on the share mode for a file.
1338 static bool validate_oplock_types(struct share_mode_lock *lck)
1340 struct share_mode_data *d = lck->data;
1341 bool batch = false;
1342 bool ex_or_batch = false;
1343 bool level2 = false;
1344 bool no_oplock = false;
1345 uint32_t num_non_stat_opens = 0;
1346 uint32_t i;
1348 for (i=0; i<d->num_share_modes; i++) {
1349 struct share_mode_entry *e = &d->share_modes[i];
1351 if (!is_valid_share_mode_entry(e)) {
1352 continue;
1355 if (e->op_mid == 0) {
1356 /* INTERNAL_OPEN_ONLY */
1357 continue;
1360 if (e->op_type == NO_OPLOCK && is_stat_open(e->access_mask)) {
1361 /* We ignore stat opens in the table - they
1362 always have NO_OPLOCK and never get or
1363 cause breaks. JRA. */
1364 continue;
1367 num_non_stat_opens += 1;
1369 if (BATCH_OPLOCK_TYPE(e->op_type)) {
1370 /* batch - can only be one. */
1371 if (share_mode_stale_pid(d, i)) {
1372 DEBUG(10, ("Found stale batch oplock\n"));
1373 continue;
1375 if (ex_or_batch || batch || level2 || no_oplock) {
1376 DEBUG(0, ("Bad batch oplock entry %u.",
1377 (unsigned)i));
1378 return false;
1380 batch = true;
1383 if (EXCLUSIVE_OPLOCK_TYPE(e->op_type)) {
1384 if (share_mode_stale_pid(d, i)) {
1385 DEBUG(10, ("Found stale duplicate oplock\n"));
1386 continue;
1388 /* Exclusive or batch - can only be one. */
1389 if (ex_or_batch || level2 || no_oplock) {
1390 DEBUG(0, ("Bad exclusive or batch oplock "
1391 "entry %u.", (unsigned)i));
1392 return false;
1394 ex_or_batch = true;
1397 if (LEVEL_II_OPLOCK_TYPE(e->op_type)) {
1398 if (batch || ex_or_batch) {
1399 if (share_mode_stale_pid(d, i)) {
1400 DEBUG(10, ("Found stale LevelII "
1401 "oplock\n"));
1402 continue;
1404 DEBUG(0, ("Bad levelII oplock entry %u.",
1405 (unsigned)i));
1406 return false;
1408 level2 = true;
1411 if (e->op_type == NO_OPLOCK) {
1412 if (batch || ex_or_batch) {
1413 if (share_mode_stale_pid(d, i)) {
1414 DEBUG(10, ("Found stale NO_OPLOCK "
1415 "entry\n"));
1416 continue;
1418 DEBUG(0, ("Bad no oplock entry %u.",
1419 (unsigned)i));
1420 return false;
1422 no_oplock = true;
1426 remove_stale_share_mode_entries(d);
1428 if ((batch || ex_or_batch) && (num_non_stat_opens != 1)) {
1429 DEBUG(1, ("got batch (%d) or ex (%d) non-exclusively (%d)\n",
1430 (int)batch, (int)ex_or_batch,
1431 (int)d->num_share_modes));
1432 return false;
1435 return true;
1438 static bool delay_for_oplock(files_struct *fsp,
1439 int oplock_request,
1440 const struct smb2_lease *lease,
1441 struct share_mode_lock *lck,
1442 bool have_sharing_violation,
1443 uint32_t create_disposition,
1444 bool first_open_attempt)
1446 struct share_mode_data *d = lck->data;
1447 uint32_t i;
1448 bool delay = false;
1449 bool will_overwrite;
1451 if ((oplock_request & INTERNAL_OPEN_ONLY) ||
1452 is_stat_open(fsp->access_mask)) {
1453 return false;
1456 switch (create_disposition) {
1457 case FILE_SUPERSEDE:
1458 case FILE_OVERWRITE:
1459 case FILE_OVERWRITE_IF:
1460 will_overwrite = true;
1461 break;
1462 default:
1463 will_overwrite = false;
1464 break;
1467 for (i=0; i<d->num_share_modes; i++) {
1468 struct share_mode_entry *e = &d->share_modes[i];
1469 struct share_mode_lease *l = NULL;
1470 uint32_t e_lease_type = get_lease_type(d, e);
1471 uint32_t break_to;
1472 uint32_t delay_mask = 0;
1474 if (e->op_type == LEASE_OPLOCK) {
1475 l = &d->leases[e->lease_idx];
1478 if (have_sharing_violation) {
1479 delay_mask = SMB2_LEASE_HANDLE;
1480 } else {
1481 delay_mask = SMB2_LEASE_WRITE;
1484 break_to = e_lease_type & ~delay_mask;
1486 if (will_overwrite) {
1488 * we'll decide about SMB2_LEASE_READ later.
1490 * Maybe the break will be deferred
1492 break_to &= ~SMB2_LEASE_HANDLE;
1495 DEBUG(10, ("entry %u: e_lease_type %u, will_overwrite: %u\n",
1496 (unsigned)i, (unsigned)e_lease_type,
1497 (unsigned)will_overwrite));
1499 if (lease != NULL && l != NULL) {
1500 bool ign;
1502 ign = smb2_lease_equal(fsp_client_guid(fsp),
1503 &lease->lease_key,
1504 &l->client_guid,
1505 &l->lease_key);
1506 if (ign) {
1507 continue;
1511 if ((e_lease_type & ~break_to) == 0) {
1512 if (l != NULL && l->breaking) {
1513 delay = true;
1515 continue;
1518 if (share_mode_stale_pid(d, i)) {
1519 continue;
1522 if (will_overwrite) {
1524 * If we break anyway break to NONE directly.
1525 * Otherwise vfs_set_filelen() will trigger the
1526 * break.
1528 break_to &= ~(SMB2_LEASE_READ|SMB2_LEASE_WRITE);
1531 if (e->op_type != LEASE_OPLOCK) {
1533 * Oplocks only support breaking to R or NONE.
1535 break_to &= ~(SMB2_LEASE_HANDLE|SMB2_LEASE_WRITE);
1538 DEBUG(10, ("breaking from %d to %d\n",
1539 (int)e_lease_type, (int)break_to));
1540 send_break_message(fsp->conn->sconn->msg_ctx, e,
1541 break_to);
1542 if (e_lease_type & delay_mask) {
1543 delay = true;
1545 if (l != NULL && l->breaking && !first_open_attempt) {
1546 delay = true;
1548 continue;
1551 return delay;
1554 static bool file_has_brlocks(files_struct *fsp)
1556 struct byte_range_lock *br_lck;
1558 br_lck = brl_get_locks_readonly(fsp);
1559 if (!br_lck)
1560 return false;
1562 return (brl_num_locks(br_lck) > 0);
1565 int find_share_mode_lease(struct share_mode_data *d,
1566 const struct GUID *client_guid,
1567 const struct smb2_lease_key *key)
1569 uint32_t i;
1571 for (i=0; i<d->num_leases; i++) {
1572 struct share_mode_lease *l = &d->leases[i];
1574 if (smb2_lease_equal(client_guid,
1575 key,
1576 &l->client_guid,
1577 &l->lease_key)) {
1578 return i;
1582 return -1;
1585 struct fsp_lease *find_fsp_lease(struct files_struct *new_fsp,
1586 const struct smb2_lease_key *key,
1587 const struct share_mode_lease *l)
1589 struct files_struct *fsp;
1592 * TODO: Measure how expensive this loop is with thousands of open
1593 * handles...
1596 for (fsp = file_find_di_first(new_fsp->conn->sconn, new_fsp->file_id);
1597 fsp != NULL;
1598 fsp = file_find_di_next(fsp)) {
1600 if (fsp == new_fsp) {
1601 continue;
1603 if (fsp->oplock_type != LEASE_OPLOCK) {
1604 continue;
1606 if (smb2_lease_key_equal(&fsp->lease->lease.lease_key, key)) {
1607 fsp->lease->ref_count += 1;
1608 return fsp->lease;
1612 /* Not found - must be leased in another smbd. */
1613 new_fsp->lease = talloc_zero(new_fsp->conn->sconn, struct fsp_lease);
1614 if (new_fsp->lease == NULL) {
1615 return NULL;
1617 new_fsp->lease->ref_count = 1;
1618 new_fsp->lease->sconn = new_fsp->conn->sconn;
1619 new_fsp->lease->lease.lease_key = *key;
1620 new_fsp->lease->lease.lease_state = l->current_state;
1622 * We internally treat all leases as V2 and update
1623 * the epoch, but when sending breaks it matters if
1624 * the requesting lease was v1 or v2.
1626 new_fsp->lease->lease.lease_version = l->lease_version;
1627 new_fsp->lease->lease.lease_epoch = l->epoch;
1628 return new_fsp->lease;
1631 static NTSTATUS grant_fsp_lease(struct files_struct *fsp,
1632 struct share_mode_lock *lck,
1633 const struct smb2_lease *lease,
1634 uint32_t *p_lease_idx,
1635 uint32_t granted)
1637 struct share_mode_data *d = lck->data;
1638 const struct GUID *client_guid = fsp_client_guid(fsp);
1639 struct share_mode_lease *tmp;
1640 NTSTATUS status;
1641 int idx;
1643 idx = find_share_mode_lease(d, client_guid, &lease->lease_key);
1645 if (idx != -1) {
1646 struct share_mode_lease *l = &d->leases[idx];
1647 bool do_upgrade;
1648 uint32_t existing, requested;
1650 fsp->lease = find_fsp_lease(fsp, &lease->lease_key, l);
1651 if (fsp->lease == NULL) {
1652 DEBUG(1, ("Did not find existing lease for file %s\n",
1653 fsp_str_dbg(fsp)));
1654 return NT_STATUS_NO_MEMORY;
1657 *p_lease_idx = idx;
1660 * Upgrade only if the requested lease is a strict upgrade.
1662 existing = l->current_state;
1663 requested = lease->lease_state;
1666 * Tricky: This test makes sure that "requested" is a
1667 * strict bitwise superset of "existing".
1669 do_upgrade = ((existing & requested) == existing);
1672 * Upgrade only if there's a change.
1674 do_upgrade &= (granted != existing);
1677 * Upgrade only if other leases don't prevent what was asked
1678 * for.
1680 do_upgrade &= (granted == requested);
1683 * only upgrade if we are not in breaking state
1685 do_upgrade &= !l->breaking;
1687 DEBUG(10, ("existing=%"PRIu32", requested=%"PRIu32", "
1688 "granted=%"PRIu32", do_upgrade=%d\n",
1689 existing, requested, granted, (int)do_upgrade));
1691 if (do_upgrade) {
1692 l->current_state = granted;
1693 l->epoch += 1;
1696 /* Ensure we're in sync with current lease state. */
1697 fsp_lease_update(lck, fsp_client_guid(fsp), fsp->lease);
1698 return NT_STATUS_OK;
1702 * Create new lease
1705 tmp = talloc_realloc(d, d->leases, struct share_mode_lease,
1706 d->num_leases+1);
1707 if (tmp == NULL) {
1709 * See [MS-SMB2]
1711 return NT_STATUS_INSUFFICIENT_RESOURCES;
1713 d->leases = tmp;
1715 fsp->lease = talloc_zero(fsp->conn->sconn, struct fsp_lease);
1716 if (fsp->lease == NULL) {
1717 return NT_STATUS_INSUFFICIENT_RESOURCES;
1719 fsp->lease->ref_count = 1;
1720 fsp->lease->sconn = fsp->conn->sconn;
1721 fsp->lease->lease.lease_version = lease->lease_version;
1722 fsp->lease->lease.lease_key = lease->lease_key;
1723 fsp->lease->lease.lease_state = granted;
1724 fsp->lease->lease.lease_epoch = lease->lease_epoch + 1;
1726 *p_lease_idx = d->num_leases;
1728 d->leases[d->num_leases] = (struct share_mode_lease) {
1729 .client_guid = *client_guid,
1730 .lease_key = fsp->lease->lease.lease_key,
1731 .current_state = fsp->lease->lease.lease_state,
1732 .lease_version = fsp->lease->lease.lease_version,
1733 .epoch = fsp->lease->lease.lease_epoch,
1736 status = leases_db_add(client_guid,
1737 &lease->lease_key,
1738 &fsp->file_id,
1739 fsp->conn->connectpath,
1740 fsp->fsp_name->base_name,
1741 fsp->fsp_name->stream_name);
1742 if (!NT_STATUS_IS_OK(status)) {
1743 DEBUG(10, ("%s: leases_db_add failed: %s\n", __func__,
1744 nt_errstr(status)));
1745 TALLOC_FREE(fsp->lease);
1746 return NT_STATUS_INSUFFICIENT_RESOURCES;
1749 d->num_leases += 1;
1750 d->modified = true;
1752 return NT_STATUS_OK;
1755 static bool is_same_lease(const files_struct *fsp,
1756 const struct share_mode_data *d,
1757 const struct share_mode_entry *e,
1758 const struct smb2_lease *lease)
1760 if (e->op_type != LEASE_OPLOCK) {
1761 return false;
1763 if (lease == NULL) {
1764 return false;
1767 return smb2_lease_equal(fsp_client_guid(fsp),
1768 &lease->lease_key,
1769 &d->leases[e->lease_idx].client_guid,
1770 &d->leases[e->lease_idx].lease_key);
1773 static NTSTATUS grant_fsp_oplock_type(struct smb_request *req,
1774 struct files_struct *fsp,
1775 struct share_mode_lock *lck,
1776 int oplock_request,
1777 struct smb2_lease *lease)
1779 struct share_mode_data *d = lck->data;
1780 bool got_handle_lease = false;
1781 bool got_oplock = false;
1782 uint32_t i;
1783 uint32_t granted;
1784 uint32_t lease_idx = UINT32_MAX;
1785 bool ok;
1786 NTSTATUS status;
1788 if (oplock_request & INTERNAL_OPEN_ONLY) {
1789 /* No oplocks on internal open. */
1790 oplock_request = NO_OPLOCK;
1791 DEBUG(10,("grant_fsp_oplock_type: oplock type 0x%x on file %s\n",
1792 fsp->oplock_type, fsp_str_dbg(fsp)));
1795 if (oplock_request == LEASE_OPLOCK) {
1796 if (lease == NULL) {
1798 * The SMB2 layer should have checked this
1800 return NT_STATUS_INTERNAL_ERROR;
1803 granted = lease->lease_state;
1805 if (lp_kernel_oplocks(SNUM(fsp->conn))) {
1806 DEBUG(10, ("No lease granted because kernel oplocks are enabled\n"));
1807 granted = SMB2_LEASE_NONE;
1809 if ((granted & (SMB2_LEASE_READ|SMB2_LEASE_WRITE)) == 0) {
1810 DEBUG(10, ("No read or write lease requested\n"));
1811 granted = SMB2_LEASE_NONE;
1813 if (granted == SMB2_LEASE_WRITE) {
1814 DEBUG(10, ("pure write lease requested\n"));
1815 granted = SMB2_LEASE_NONE;
1817 if (granted == (SMB2_LEASE_WRITE|SMB2_LEASE_HANDLE)) {
1818 DEBUG(10, ("write and handle lease requested\n"));
1819 granted = SMB2_LEASE_NONE;
1821 } else {
1822 granted = map_oplock_to_lease_type(
1823 oplock_request & ~SAMBA_PRIVATE_OPLOCK_MASK);
1826 if (lp_locking(fsp->conn->params) && file_has_brlocks(fsp)) {
1827 DEBUG(10,("grant_fsp_oplock_type: file %s has byte range locks\n",
1828 fsp_str_dbg(fsp)));
1829 granted &= ~SMB2_LEASE_READ;
1832 for (i=0; i<d->num_share_modes; i++) {
1833 struct share_mode_entry *e = &d->share_modes[i];
1834 uint32_t e_lease_type;
1836 e_lease_type = get_lease_type(d, e);
1838 if ((granted & SMB2_LEASE_WRITE) &&
1839 !is_same_lease(fsp, d, e, lease) &&
1840 !share_mode_stale_pid(d, i)) {
1842 * Can grant only one writer
1844 granted &= ~SMB2_LEASE_WRITE;
1847 if ((e_lease_type & SMB2_LEASE_HANDLE) && !got_handle_lease &&
1848 !share_mode_stale_pid(d, i)) {
1849 got_handle_lease = true;
1852 if ((e->op_type != LEASE_OPLOCK) && !got_oplock &&
1853 !share_mode_stale_pid(d, i)) {
1854 got_oplock = true;
1858 if ((granted & SMB2_LEASE_READ) && !(granted & SMB2_LEASE_WRITE)) {
1859 bool allow_level2 =
1860 (global_client_caps & CAP_LEVEL_II_OPLOCKS) &&
1861 lp_level2_oplocks(SNUM(fsp->conn));
1863 if (!allow_level2) {
1864 granted = SMB2_LEASE_NONE;
1868 if (oplock_request == LEASE_OPLOCK) {
1869 if (got_oplock) {
1870 granted &= ~SMB2_LEASE_HANDLE;
1873 fsp->oplock_type = LEASE_OPLOCK;
1875 status = grant_fsp_lease(fsp, lck, lease, &lease_idx,
1876 granted);
1877 if (!NT_STATUS_IS_OK(status)) {
1878 return status;
1881 *lease = fsp->lease->lease;
1882 DEBUG(10, ("lease_state=%d\n", lease->lease_state));
1883 } else {
1884 if (got_handle_lease) {
1885 granted = SMB2_LEASE_NONE;
1888 switch (granted) {
1889 case SMB2_LEASE_READ|SMB2_LEASE_WRITE|SMB2_LEASE_HANDLE:
1890 fsp->oplock_type = BATCH_OPLOCK|EXCLUSIVE_OPLOCK;
1891 break;
1892 case SMB2_LEASE_READ|SMB2_LEASE_WRITE:
1893 fsp->oplock_type = EXCLUSIVE_OPLOCK;
1894 break;
1895 case SMB2_LEASE_READ|SMB2_LEASE_HANDLE:
1896 case SMB2_LEASE_READ:
1897 fsp->oplock_type = LEVEL_II_OPLOCK;
1898 break;
1899 default:
1900 fsp->oplock_type = NO_OPLOCK;
1901 break;
1904 status = set_file_oplock(fsp);
1905 if (!NT_STATUS_IS_OK(status)) {
1907 * Could not get the kernel oplock
1909 fsp->oplock_type = NO_OPLOCK;
1913 ok = set_share_mode(lck, fsp, get_current_uid(fsp->conn),
1914 req ? req->mid : 0,
1915 fsp->oplock_type,
1916 lease_idx);
1917 if (!ok) {
1918 return NT_STATUS_NO_MEMORY;
1921 ok = update_num_read_oplocks(fsp, lck);
1922 if (!ok) {
1923 del_share_mode(lck, fsp);
1924 return NT_STATUS_INTERNAL_ERROR;
1927 DEBUG(10,("grant_fsp_oplock_type: oplock type 0x%x on file %s\n",
1928 fsp->oplock_type, fsp_str_dbg(fsp)));
1930 return NT_STATUS_OK;
1933 static bool request_timed_out(struct timeval request_time,
1934 struct timeval timeout)
1936 struct timeval now, end_time;
1937 GetTimeOfDay(&now);
1938 end_time = timeval_sum(&request_time, &timeout);
1939 return (timeval_compare(&end_time, &now) < 0);
1942 static struct deferred_open_record *deferred_open_record_create(
1943 bool delayed_for_oplocks,
1944 bool async_open,
1945 struct file_id id)
1947 struct deferred_open_record *record = NULL;
1949 record = talloc(NULL, struct deferred_open_record);
1950 if (record == NULL) {
1951 return NULL;
1954 *record = (struct deferred_open_record) {
1955 .delayed_for_oplocks = delayed_for_oplocks,
1956 .async_open = async_open,
1957 .id = id,
1960 return record;
1963 struct defer_open_state {
1964 struct smbXsrv_connection *xconn;
1965 uint64_t mid;
1968 static void defer_open_done(struct tevent_req *req);
1970 /****************************************************************************
1971 Handle the 1 second delay in returning a SHARING_VIOLATION error.
1972 ****************************************************************************/
1974 static void defer_open(struct share_mode_lock *lck,
1975 struct timeval request_time,
1976 struct timeval timeout,
1977 struct smb_request *req,
1978 bool delayed_for_oplocks,
1979 struct file_id id)
1981 struct deferred_open_record *open_rec = NULL;
1982 struct timeval abs_timeout;
1984 abs_timeout = timeval_sum(&request_time, &timeout);
1986 DBG_DEBUG("request time [%s] timeout [%s] mid [%" PRIu64 "] "
1987 "delayed_for_oplocks [%s] file_id [%s]\n",
1988 timeval_string(talloc_tos(), &request_time, false),
1989 timeval_string(talloc_tos(), &abs_timeout, false),
1990 req->mid,
1991 delayed_for_oplocks ? "yes" : "no",
1992 file_id_string_tos(&id));
1994 open_rec = deferred_open_record_create(delayed_for_oplocks,
1995 false,
1996 id);
1997 if (open_rec == NULL) {
1998 TALLOC_FREE(lck);
1999 exit_server("talloc failed");
2002 if (lck) {
2003 struct defer_open_state *watch_state;
2004 struct tevent_req *watch_req;
2005 bool ret;
2007 watch_state = talloc(open_rec, struct defer_open_state);
2008 if (watch_state == NULL) {
2009 exit_server("talloc failed");
2011 watch_state->xconn = req->xconn;
2012 watch_state->mid = req->mid;
2014 DEBUG(10, ("defering mid %llu\n",
2015 (unsigned long long)req->mid));
2017 watch_req = dbwrap_watched_watch_send(
2018 watch_state, req->sconn->ev_ctx, lck->data->record,
2019 (struct server_id){0});
2020 if (watch_req == NULL) {
2021 exit_server("Could not watch share mode record");
2023 tevent_req_set_callback(watch_req, defer_open_done,
2024 watch_state);
2026 ret = tevent_req_set_endtime(
2027 watch_req, req->sconn->ev_ctx,
2028 abs_timeout);
2029 SMB_ASSERT(ret);
2032 if (!push_deferred_open_message_smb(req, request_time, timeout,
2033 open_rec->id, open_rec)) {
2034 TALLOC_FREE(lck);
2035 exit_server("push_deferred_open_message_smb failed");
2039 static void defer_open_done(struct tevent_req *req)
2041 struct defer_open_state *state = tevent_req_callback_data(
2042 req, struct defer_open_state);
2043 NTSTATUS status;
2044 bool ret;
2046 status = dbwrap_watched_watch_recv(req, talloc_tos(), NULL, NULL,
2047 NULL);
2048 TALLOC_FREE(req);
2049 if (!NT_STATUS_IS_OK(status)) {
2050 DEBUG(5, ("dbwrap_watched_watch_recv returned %s\n",
2051 nt_errstr(status)));
2053 * Even if it failed, retry anyway. TODO: We need a way to
2054 * tell a re-scheduled open about that error.
2058 DEBUG(10, ("scheduling mid %llu\n", (unsigned long long)state->mid));
2060 ret = schedule_deferred_open_message_smb(state->xconn, state->mid);
2061 SMB_ASSERT(ret);
2062 TALLOC_FREE(state);
2066 * Reschedule an open for immediate execution
2068 static void retry_open(struct timeval request_time,
2069 struct smb_request *req,
2070 struct file_id id)
2072 struct deferred_open_record *open_rec = NULL;
2073 bool ok;
2075 DBG_DEBUG("request time [%s] mid [%" PRIu64 "] file_id [%s]\n",
2076 timeval_string(talloc_tos(), &request_time, false),
2077 req->mid,
2078 file_id_string_tos(&id));
2080 open_rec = deferred_open_record_create(false, false, id);
2081 if (open_rec == NULL) {
2082 exit_server("talloc failed");
2085 ok = push_deferred_open_message_smb(req,
2086 request_time,
2087 timeval_set(0, 0),
2089 open_rec);
2090 if (!ok) {
2091 exit_server("push_deferred_open_message_smb failed");
2094 ok = schedule_deferred_open_message_smb(req->xconn, req->mid);
2095 if (!ok) {
2096 exit_server("schedule_deferred_open_message_smb failed");
2100 /****************************************************************************
2101 On overwrite open ensure that the attributes match.
2102 ****************************************************************************/
2104 static bool open_match_attributes(connection_struct *conn,
2105 uint32_t old_dos_attr,
2106 uint32_t new_dos_attr,
2107 mode_t existing_unx_mode,
2108 mode_t new_unx_mode,
2109 mode_t *returned_unx_mode)
2111 uint32_t noarch_old_dos_attr, noarch_new_dos_attr;
2113 noarch_old_dos_attr = (old_dos_attr & ~FILE_ATTRIBUTE_ARCHIVE);
2114 noarch_new_dos_attr = (new_dos_attr & ~FILE_ATTRIBUTE_ARCHIVE);
2116 if((noarch_old_dos_attr == 0 && noarch_new_dos_attr != 0) ||
2117 (noarch_old_dos_attr != 0 && ((noarch_old_dos_attr & noarch_new_dos_attr) == noarch_old_dos_attr))) {
2118 *returned_unx_mode = new_unx_mode;
2119 } else {
2120 *returned_unx_mode = (mode_t)0;
2123 DEBUG(10,("open_match_attributes: old_dos_attr = 0x%x, "
2124 "existing_unx_mode = 0%o, new_dos_attr = 0x%x "
2125 "returned_unx_mode = 0%o\n",
2126 (unsigned int)old_dos_attr,
2127 (unsigned int)existing_unx_mode,
2128 (unsigned int)new_dos_attr,
2129 (unsigned int)*returned_unx_mode ));
2131 /* If we're mapping SYSTEM and HIDDEN ensure they match. */
2132 if (lp_map_system(SNUM(conn)) || lp_store_dos_attributes(SNUM(conn))) {
2133 if ((old_dos_attr & FILE_ATTRIBUTE_SYSTEM) &&
2134 !(new_dos_attr & FILE_ATTRIBUTE_SYSTEM)) {
2135 return False;
2138 if (lp_map_hidden(SNUM(conn)) || lp_store_dos_attributes(SNUM(conn))) {
2139 if ((old_dos_attr & FILE_ATTRIBUTE_HIDDEN) &&
2140 !(new_dos_attr & FILE_ATTRIBUTE_HIDDEN)) {
2141 return False;
2144 return True;
2147 /****************************************************************************
2148 Special FCB or DOS processing in the case of a sharing violation.
2149 Try and find a duplicated file handle.
2150 ****************************************************************************/
2152 static NTSTATUS fcb_or_dos_open(struct smb_request *req,
2153 connection_struct *conn,
2154 files_struct *fsp_to_dup_into,
2155 const struct smb_filename *smb_fname,
2156 struct file_id id,
2157 uint16_t file_pid,
2158 uint64_t vuid,
2159 uint32_t access_mask,
2160 uint32_t share_access,
2161 uint32_t create_options)
2163 files_struct *fsp;
2165 DEBUG(5,("fcb_or_dos_open: attempting old open semantics for "
2166 "file %s.\n", smb_fname_str_dbg(smb_fname)));
2168 for(fsp = file_find_di_first(conn->sconn, id); fsp;
2169 fsp = file_find_di_next(fsp)) {
2171 DEBUG(10,("fcb_or_dos_open: checking file %s, fd = %d, "
2172 "vuid = %llu, file_pid = %u, private_options = 0x%x "
2173 "access_mask = 0x%x\n", fsp_str_dbg(fsp),
2174 fsp->fh->fd, (unsigned long long)fsp->vuid,
2175 (unsigned int)fsp->file_pid,
2176 (unsigned int)fsp->fh->private_options,
2177 (unsigned int)fsp->access_mask ));
2179 if (fsp != fsp_to_dup_into &&
2180 fsp->fh->fd != -1 &&
2181 fsp->vuid == vuid &&
2182 fsp->file_pid == file_pid &&
2183 (fsp->fh->private_options & (NTCREATEX_OPTIONS_PRIVATE_DENY_DOS |
2184 NTCREATEX_OPTIONS_PRIVATE_DENY_FCB)) &&
2185 (fsp->access_mask & FILE_WRITE_DATA) &&
2186 strequal(fsp->fsp_name->base_name, smb_fname->base_name) &&
2187 strequal(fsp->fsp_name->stream_name,
2188 smb_fname->stream_name)) {
2189 DEBUG(10,("fcb_or_dos_open: file match\n"));
2190 break;
2194 if (!fsp) {
2195 return NT_STATUS_NOT_FOUND;
2198 /* quite an insane set of semantics ... */
2199 if (is_executable(smb_fname->base_name) &&
2200 (fsp->fh->private_options & NTCREATEX_OPTIONS_PRIVATE_DENY_DOS)) {
2201 DEBUG(10,("fcb_or_dos_open: file fail due to is_executable.\n"));
2202 return NT_STATUS_INVALID_PARAMETER;
2205 /* We need to duplicate this fsp. */
2206 return dup_file_fsp(req, fsp, access_mask, share_access,
2207 create_options, fsp_to_dup_into);
2210 static void schedule_defer_open(struct share_mode_lock *lck,
2211 struct file_id id,
2212 struct timeval request_time,
2213 struct smb_request *req)
2215 /* This is a relative time, added to the absolute
2216 request_time value to get the absolute timeout time.
2217 Note that if this is the second or greater time we enter
2218 this codepath for this particular request mid then
2219 request_time is left as the absolute time of the *first*
2220 time this request mid was processed. This is what allows
2221 the request to eventually time out. */
2223 struct timeval timeout;
2225 /* Normally the smbd we asked should respond within
2226 * OPLOCK_BREAK_TIMEOUT seconds regardless of whether
2227 * the client did, give twice the timeout as a safety
2228 * measure here in case the other smbd is stuck
2229 * somewhere else. */
2231 timeout = timeval_set(OPLOCK_BREAK_TIMEOUT*2, 0);
2233 if (request_timed_out(request_time, timeout)) {
2234 return;
2237 defer_open(lck, request_time, timeout, req, true, id);
2240 /****************************************************************************
2241 Reschedule an open call that went asynchronous.
2242 ****************************************************************************/
2244 static void schedule_async_open_timer(struct tevent_context *ev,
2245 struct tevent_timer *te,
2246 struct timeval current_time,
2247 void *private_data)
2249 exit_server("async open timeout");
2252 static void schedule_async_open(struct timeval request_time,
2253 struct smb_request *req)
2255 struct deferred_open_record *open_rec = NULL;
2256 struct timeval timeout = timeval_set(20, 0);
2257 bool ok;
2259 if (request_timed_out(request_time, timeout)) {
2260 return;
2263 open_rec = deferred_open_record_create(false, true, (struct file_id){0});
2264 if (open_rec == NULL) {
2265 exit_server("deferred_open_record_create failed");
2268 ok = push_deferred_open_message_smb(req, request_time, timeout,
2269 (struct file_id){0}, open_rec);
2270 if (!ok) {
2271 exit_server("push_deferred_open_message_smb failed");
2274 open_rec->te = tevent_add_timer(req->sconn->ev_ctx,
2275 req,
2276 timeval_current_ofs(20, 0),
2277 schedule_async_open_timer,
2278 open_rec);
2279 if (open_rec->te == NULL) {
2280 exit_server("tevent_add_timer failed");
2284 /****************************************************************************
2285 Work out what access_mask to use from what the client sent us.
2286 ****************************************************************************/
2288 static NTSTATUS smbd_calculate_maximum_allowed_access(
2289 connection_struct *conn,
2290 const struct smb_filename *smb_fname,
2291 bool use_privs,
2292 uint32_t *p_access_mask)
2294 struct security_descriptor *sd;
2295 uint32_t access_granted;
2296 NTSTATUS status;
2298 if (!use_privs && (get_current_uid(conn) == (uid_t)0)) {
2299 *p_access_mask |= FILE_GENERIC_ALL;
2300 return NT_STATUS_OK;
2303 status = SMB_VFS_GET_NT_ACL(conn, smb_fname,
2304 (SECINFO_OWNER |
2305 SECINFO_GROUP |
2306 SECINFO_DACL),
2307 talloc_tos(), &sd);
2309 if (NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
2311 * File did not exist
2313 *p_access_mask = FILE_GENERIC_ALL;
2314 return NT_STATUS_OK;
2316 if (!NT_STATUS_IS_OK(status)) {
2317 DEBUG(10,("Could not get acl on file %s: %s\n",
2318 smb_fname_str_dbg(smb_fname),
2319 nt_errstr(status)));
2320 return NT_STATUS_ACCESS_DENIED;
2324 * If we can access the path to this file, by
2325 * default we have FILE_READ_ATTRIBUTES from the
2326 * containing directory. See the section:
2327 * "Algorithm to Check Access to an Existing File"
2328 * in MS-FSA.pdf.
2330 * se_file_access_check()
2331 * also takes care of owner WRITE_DAC and READ_CONTROL.
2333 status = se_file_access_check(sd,
2334 get_current_nttok(conn),
2335 use_privs,
2336 (*p_access_mask & ~FILE_READ_ATTRIBUTES),
2337 &access_granted);
2339 TALLOC_FREE(sd);
2341 if (!NT_STATUS_IS_OK(status)) {
2342 DEBUG(10, ("Access denied on file %s: "
2343 "when calculating maximum access\n",
2344 smb_fname_str_dbg(smb_fname)));
2345 return NT_STATUS_ACCESS_DENIED;
2347 *p_access_mask = (access_granted | FILE_READ_ATTRIBUTES);
2349 if (!(access_granted & DELETE_ACCESS)) {
2350 if (can_delete_file_in_directory(conn, smb_fname)) {
2351 *p_access_mask |= DELETE_ACCESS;
2355 return NT_STATUS_OK;
2358 NTSTATUS smbd_calculate_access_mask(connection_struct *conn,
2359 const struct smb_filename *smb_fname,
2360 bool use_privs,
2361 uint32_t access_mask,
2362 uint32_t *access_mask_out)
2364 NTSTATUS status;
2365 uint32_t orig_access_mask = access_mask;
2366 uint32_t rejected_share_access;
2368 if (access_mask & SEC_MASK_INVALID) {
2369 DBG_DEBUG("access_mask [%8x] contains invalid bits\n",
2370 access_mask);
2371 return NT_STATUS_ACCESS_DENIED;
2375 * Convert GENERIC bits to specific bits.
2378 se_map_generic(&access_mask, &file_generic_mapping);
2380 /* Calculate MAXIMUM_ALLOWED_ACCESS if requested. */
2381 if (access_mask & MAXIMUM_ALLOWED_ACCESS) {
2383 status = smbd_calculate_maximum_allowed_access(
2384 conn, smb_fname, use_privs, &access_mask);
2386 if (!NT_STATUS_IS_OK(status)) {
2387 return status;
2390 access_mask &= conn->share_access;
2393 rejected_share_access = access_mask & ~(conn->share_access);
2395 if (rejected_share_access) {
2396 DEBUG(10, ("smbd_calculate_access_mask: Access denied on "
2397 "file %s: rejected by share access mask[0x%08X] "
2398 "orig[0x%08X] mapped[0x%08X] reject[0x%08X]\n",
2399 smb_fname_str_dbg(smb_fname),
2400 conn->share_access,
2401 orig_access_mask, access_mask,
2402 rejected_share_access));
2403 return NT_STATUS_ACCESS_DENIED;
2406 *access_mask_out = access_mask;
2407 return NT_STATUS_OK;
2410 /****************************************************************************
2411 Remove the deferred open entry under lock.
2412 ****************************************************************************/
2414 /****************************************************************************
2415 Return true if this is a state pointer to an asynchronous create.
2416 ****************************************************************************/
2418 bool is_deferred_open_async(const struct deferred_open_record *rec)
2420 return rec->async_open;
2423 static bool clear_ads(uint32_t create_disposition)
2425 bool ret = false;
2427 switch (create_disposition) {
2428 case FILE_SUPERSEDE:
2429 case FILE_OVERWRITE_IF:
2430 case FILE_OVERWRITE:
2431 ret = true;
2432 break;
2433 default:
2434 break;
2436 return ret;
2439 static int disposition_to_open_flags(uint32_t create_disposition)
2441 int ret = 0;
2444 * Currently we're using FILE_SUPERSEDE as the same as
2445 * FILE_OVERWRITE_IF but they really are
2446 * different. FILE_SUPERSEDE deletes an existing file
2447 * (requiring delete access) then recreates it.
2450 switch (create_disposition) {
2451 case FILE_SUPERSEDE:
2452 case FILE_OVERWRITE_IF:
2454 * If file exists replace/overwrite. If file doesn't
2455 * exist create.
2457 ret = O_CREAT|O_TRUNC;
2458 break;
2460 case FILE_OPEN:
2462 * If file exists open. If file doesn't exist error.
2464 ret = 0;
2465 break;
2467 case FILE_OVERWRITE:
2469 * If file exists overwrite. If file doesn't exist
2470 * error.
2472 ret = O_TRUNC;
2473 break;
2475 case FILE_CREATE:
2477 * If file exists error. If file doesn't exist create.
2479 ret = O_CREAT|O_EXCL;
2480 break;
2482 case FILE_OPEN_IF:
2484 * If file exists open. If file doesn't exist create.
2486 ret = O_CREAT;
2487 break;
2489 return ret;
2492 static int calculate_open_access_flags(uint32_t access_mask,
2493 uint32_t private_flags)
2495 bool need_write, need_read;
2498 * Note that we ignore the append flag as append does not
2499 * mean the same thing under DOS and Unix.
2502 need_write = (access_mask & (FILE_WRITE_DATA | FILE_APPEND_DATA));
2503 if (!need_write) {
2504 return O_RDONLY;
2507 /* DENY_DOS opens are always underlying read-write on the
2508 file handle, no matter what the requested access mask
2509 says. */
2511 need_read =
2512 ((private_flags & NTCREATEX_OPTIONS_PRIVATE_DENY_DOS) ||
2513 access_mask & (FILE_READ_ATTRIBUTES|FILE_READ_DATA|
2514 FILE_READ_EA|FILE_EXECUTE));
2516 if (!need_read) {
2517 return O_WRONLY;
2519 return O_RDWR;
2522 /****************************************************************************
2523 Open a file with a share mode. Passed in an already created files_struct *.
2524 ****************************************************************************/
2526 static NTSTATUS open_file_ntcreate(connection_struct *conn,
2527 struct smb_request *req,
2528 uint32_t access_mask, /* access bits (FILE_READ_DATA etc.) */
2529 uint32_t share_access, /* share constants (FILE_SHARE_READ etc) */
2530 uint32_t create_disposition, /* FILE_OPEN_IF etc. */
2531 uint32_t create_options, /* options such as delete on close. */
2532 uint32_t new_dos_attributes, /* attributes used for new file. */
2533 int oplock_request, /* internal Samba oplock codes. */
2534 struct smb2_lease *lease,
2535 /* Information (FILE_EXISTS etc.) */
2536 uint32_t private_flags, /* Samba specific flags. */
2537 int *pinfo,
2538 files_struct *fsp)
2540 struct smb_filename *smb_fname = fsp->fsp_name;
2541 int flags=0;
2542 int flags2=0;
2543 bool file_existed = VALID_STAT(smb_fname->st);
2544 bool def_acl = False;
2545 bool posix_open = False;
2546 bool new_file_created = False;
2547 bool first_open_attempt = true;
2548 NTSTATUS fsp_open = NT_STATUS_ACCESS_DENIED;
2549 mode_t new_unx_mode = (mode_t)0;
2550 mode_t unx_mode = (mode_t)0;
2551 int info;
2552 uint32_t existing_dos_attributes = 0;
2553 struct timeval request_time = timeval_zero();
2554 struct share_mode_lock *lck = NULL;
2555 uint32_t open_access_mask = access_mask;
2556 NTSTATUS status;
2557 char *parent_dir;
2558 SMB_STRUCT_STAT saved_stat = smb_fname->st;
2559 struct timespec old_write_time;
2560 struct file_id id;
2562 if (conn->printer) {
2564 * Printers are handled completely differently.
2565 * Most of the passed parameters are ignored.
2568 if (pinfo) {
2569 *pinfo = FILE_WAS_CREATED;
2572 DEBUG(10, ("open_file_ntcreate: printer open fname=%s\n",
2573 smb_fname_str_dbg(smb_fname)));
2575 if (!req) {
2576 DEBUG(0,("open_file_ntcreate: printer open without "
2577 "an SMB request!\n"));
2578 return NT_STATUS_INTERNAL_ERROR;
2581 return print_spool_open(fsp, smb_fname->base_name,
2582 req->vuid);
2585 if (!parent_dirname(talloc_tos(), smb_fname->base_name, &parent_dir,
2586 NULL)) {
2587 return NT_STATUS_NO_MEMORY;
2590 if (new_dos_attributes & FILE_FLAG_POSIX_SEMANTICS) {
2591 posix_open = True;
2592 unx_mode = (mode_t)(new_dos_attributes & ~FILE_FLAG_POSIX_SEMANTICS);
2593 new_dos_attributes = 0;
2594 } else {
2595 /* Windows allows a new file to be created and
2596 silently removes a FILE_ATTRIBUTE_DIRECTORY
2597 sent by the client. Do the same. */
2599 new_dos_attributes &= ~FILE_ATTRIBUTE_DIRECTORY;
2601 /* We add FILE_ATTRIBUTE_ARCHIVE to this as this mode is only used if the file is
2602 * created new. */
2603 unx_mode = unix_mode(conn, new_dos_attributes | FILE_ATTRIBUTE_ARCHIVE,
2604 smb_fname, parent_dir);
2607 DEBUG(10, ("open_file_ntcreate: fname=%s, dos_attrs=0x%x "
2608 "access_mask=0x%x share_access=0x%x "
2609 "create_disposition = 0x%x create_options=0x%x "
2610 "unix mode=0%o oplock_request=%d private_flags = 0x%x\n",
2611 smb_fname_str_dbg(smb_fname), new_dos_attributes,
2612 access_mask, share_access, create_disposition,
2613 create_options, (unsigned int)unx_mode, oplock_request,
2614 (unsigned int)private_flags));
2616 if (req == NULL) {
2617 /* Ensure req == NULL means INTERNAL_OPEN_ONLY */
2618 SMB_ASSERT(((oplock_request & INTERNAL_OPEN_ONLY) != 0));
2619 } else {
2620 /* And req != NULL means no INTERNAL_OPEN_ONLY */
2621 SMB_ASSERT(((oplock_request & INTERNAL_OPEN_ONLY) == 0));
2625 * Only non-internal opens can be deferred at all
2628 if (req) {
2629 struct deferred_open_record *open_rec;
2630 if (get_deferred_open_message_state(req,
2631 &request_time,
2632 &open_rec)) {
2633 /* Remember the absolute time of the original
2634 request with this mid. We'll use it later to
2635 see if this has timed out. */
2637 /* If it was an async create retry, the file
2638 didn't exist. */
2640 if (is_deferred_open_async(open_rec)) {
2641 SET_STAT_INVALID(smb_fname->st);
2642 file_existed = false;
2645 /* Ensure we don't reprocess this message. */
2646 remove_deferred_open_message_smb(req->xconn, req->mid);
2648 first_open_attempt = false;
2652 if (!posix_open) {
2653 new_dos_attributes &= SAMBA_ATTRIBUTES_MASK;
2654 if (file_existed) {
2656 * Only use strored DOS attributes for checks
2657 * against requested attributes (below via
2658 * open_match_attributes()), cf bug #11992
2659 * for details. -slow
2661 uint32_t attr = 0;
2663 status = SMB_VFS_GET_DOS_ATTRIBUTES(conn, smb_fname, &attr);
2664 if (NT_STATUS_IS_OK(status)) {
2665 existing_dos_attributes = attr;
2670 /* ignore any oplock requests if oplocks are disabled */
2671 if (!lp_oplocks(SNUM(conn)) ||
2672 IS_VETO_OPLOCK_PATH(conn, smb_fname->base_name)) {
2673 /* Mask off everything except the private Samba bits. */
2674 oplock_request &= SAMBA_PRIVATE_OPLOCK_MASK;
2677 /* this is for OS/2 long file names - say we don't support them */
2678 if (req != NULL && !req->posix_pathnames &&
2679 strstr(smb_fname->base_name,".+,;=[].")) {
2680 /* OS/2 Workplace shell fix may be main code stream in a later
2681 * release. */
2682 DEBUG(5,("open_file_ntcreate: OS/2 long filenames are not "
2683 "supported.\n"));
2684 if (use_nt_status()) {
2685 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
2687 return NT_STATUS_DOS(ERRDOS, ERRcannotopen);
2690 switch( create_disposition ) {
2691 case FILE_OPEN:
2692 /* If file exists open. If file doesn't exist error. */
2693 if (!file_existed) {
2694 DEBUG(5,("open_file_ntcreate: FILE_OPEN "
2695 "requested for file %s and file "
2696 "doesn't exist.\n",
2697 smb_fname_str_dbg(smb_fname)));
2698 errno = ENOENT;
2699 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
2701 break;
2703 case FILE_OVERWRITE:
2704 /* If file exists overwrite. If file doesn't exist
2705 * error. */
2706 if (!file_existed) {
2707 DEBUG(5,("open_file_ntcreate: FILE_OVERWRITE "
2708 "requested for file %s and file "
2709 "doesn't exist.\n",
2710 smb_fname_str_dbg(smb_fname) ));
2711 errno = ENOENT;
2712 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
2714 break;
2716 case FILE_CREATE:
2717 /* If file exists error. If file doesn't exist
2718 * create. */
2719 if (file_existed) {
2720 DEBUG(5,("open_file_ntcreate: FILE_CREATE "
2721 "requested for file %s and file "
2722 "already exists.\n",
2723 smb_fname_str_dbg(smb_fname)));
2724 if (S_ISDIR(smb_fname->st.st_ex_mode)) {
2725 errno = EISDIR;
2726 } else {
2727 errno = EEXIST;
2729 return map_nt_error_from_unix(errno);
2731 break;
2733 case FILE_SUPERSEDE:
2734 case FILE_OVERWRITE_IF:
2735 case FILE_OPEN_IF:
2736 break;
2737 default:
2738 return NT_STATUS_INVALID_PARAMETER;
2741 flags2 = disposition_to_open_flags(create_disposition);
2743 /* We only care about matching attributes on file exists and
2744 * overwrite. */
2746 if (!posix_open && file_existed &&
2747 ((create_disposition == FILE_OVERWRITE) ||
2748 (create_disposition == FILE_OVERWRITE_IF))) {
2749 if (!open_match_attributes(conn, existing_dos_attributes,
2750 new_dos_attributes,
2751 smb_fname->st.st_ex_mode,
2752 unx_mode, &new_unx_mode)) {
2753 DEBUG(5,("open_file_ntcreate: attributes missmatch "
2754 "for file %s (%x %x) (0%o, 0%o)\n",
2755 smb_fname_str_dbg(smb_fname),
2756 existing_dos_attributes,
2757 new_dos_attributes,
2758 (unsigned int)smb_fname->st.st_ex_mode,
2759 (unsigned int)unx_mode ));
2760 errno = EACCES;
2761 return NT_STATUS_ACCESS_DENIED;
2765 status = smbd_calculate_access_mask(conn, smb_fname,
2766 false,
2767 access_mask,
2768 &access_mask);
2769 if (!NT_STATUS_IS_OK(status)) {
2770 DEBUG(10, ("open_file_ntcreate: smbd_calculate_access_mask "
2771 "on file %s returned %s\n",
2772 smb_fname_str_dbg(smb_fname), nt_errstr(status)));
2773 return status;
2776 open_access_mask = access_mask;
2778 if (flags2 & O_TRUNC) {
2779 open_access_mask |= FILE_WRITE_DATA; /* This will cause oplock breaks. */
2782 DEBUG(10, ("open_file_ntcreate: fname=%s, after mapping "
2783 "access_mask=0x%x\n", smb_fname_str_dbg(smb_fname),
2784 access_mask));
2787 * Note that we ignore the append flag as append does not
2788 * mean the same thing under DOS and Unix.
2791 flags = calculate_open_access_flags(access_mask, private_flags);
2794 * Currently we only look at FILE_WRITE_THROUGH for create options.
2797 #if defined(O_SYNC)
2798 if ((create_options & FILE_WRITE_THROUGH) && lp_strict_sync(SNUM(conn))) {
2799 flags2 |= O_SYNC;
2801 #endif /* O_SYNC */
2803 if (posix_open && (access_mask & FILE_APPEND_DATA)) {
2804 flags2 |= O_APPEND;
2807 if (!posix_open && !CAN_WRITE(conn)) {
2809 * We should really return a permission denied error if either
2810 * O_CREAT or O_TRUNC are set, but for compatibility with
2811 * older versions of Samba we just AND them out.
2813 flags2 &= ~(O_CREAT|O_TRUNC);
2816 if (first_open_attempt && lp_kernel_oplocks(SNUM(conn))) {
2818 * With kernel oplocks the open breaking an oplock
2819 * blocks until the oplock holder has given up the
2820 * oplock or closed the file. We prevent this by first
2821 * trying to open the file with O_NONBLOCK (see "man
2822 * fcntl" on Linux). For the second try, triggered by
2823 * an oplock break response, we do not need this
2824 * anymore.
2826 * This is true under the assumption that only Samba
2827 * requests kernel oplocks. Once someone else like
2828 * NFSv4 starts to use that API, we will have to
2829 * modify this by communicating with the NFSv4 server.
2831 flags2 |= O_NONBLOCK;
2835 * Ensure we can't write on a read-only share or file.
2838 if (flags != O_RDONLY && file_existed &&
2839 (!CAN_WRITE(conn) || IS_DOS_READONLY(existing_dos_attributes))) {
2840 DEBUG(5,("open_file_ntcreate: write access requested for "
2841 "file %s on read only %s\n",
2842 smb_fname_str_dbg(smb_fname),
2843 !CAN_WRITE(conn) ? "share" : "file" ));
2844 errno = EACCES;
2845 return NT_STATUS_ACCESS_DENIED;
2848 fsp->file_id = vfs_file_id_from_sbuf(conn, &smb_fname->st);
2849 fsp->share_access = share_access;
2850 fsp->fh->private_options = private_flags;
2851 fsp->access_mask = open_access_mask; /* We change this to the
2852 * requested access_mask after
2853 * the open is done. */
2854 if (posix_open) {
2855 fsp->posix_flags |= FSP_POSIX_FLAGS_ALL;
2858 if (timeval_is_zero(&request_time)) {
2859 request_time = fsp->open_time;
2863 * Ensure we pay attention to default ACLs on directories if required.
2866 if ((flags2 & O_CREAT) && lp_inherit_acls(SNUM(conn)) &&
2867 (def_acl = directory_has_default_acl(conn, parent_dir))) {
2868 unx_mode = (0777 & lp_create_mask(SNUM(conn)));
2871 DEBUG(4,("calling open_file with flags=0x%X flags2=0x%X mode=0%o, "
2872 "access_mask = 0x%x, open_access_mask = 0x%x\n",
2873 (unsigned int)flags, (unsigned int)flags2,
2874 (unsigned int)unx_mode, (unsigned int)access_mask,
2875 (unsigned int)open_access_mask));
2877 fsp_open = open_file(fsp, conn, req, parent_dir,
2878 flags|flags2, unx_mode, access_mask,
2879 open_access_mask, &new_file_created);
2881 if (NT_STATUS_EQUAL(fsp_open, NT_STATUS_NETWORK_BUSY)) {
2882 bool delay;
2885 * This handles the kernel oplock case:
2887 * the file has an active kernel oplock and the open() returned
2888 * EWOULDBLOCK/EAGAIN which maps to NETWORK_BUSY.
2890 * "Samba locking.tdb oplocks" are handled below after acquiring
2891 * the sharemode lock with get_share_mode_lock().
2893 if (file_existed && S_ISFIFO(fsp->fsp_name->st.st_ex_mode)) {
2894 DEBUG(10, ("FIFO busy\n"));
2895 return NT_STATUS_NETWORK_BUSY;
2897 if (req == NULL) {
2898 DEBUG(10, ("Internal open busy\n"));
2899 return NT_STATUS_NETWORK_BUSY;
2903 * From here on we assume this is an oplock break triggered
2906 lck = get_existing_share_mode_lock(talloc_tos(), fsp->file_id);
2907 if (lck == NULL) {
2908 retry_open(request_time, req, fsp->file_id);
2909 DEBUG(10, ("No share mode lock found after "
2910 "EWOULDBLOCK, retrying sync\n"));
2911 return NT_STATUS_SHARING_VIOLATION;
2914 if (!validate_oplock_types(lck)) {
2915 smb_panic("validate_oplock_types failed");
2918 delay = delay_for_oplock(fsp, 0, lease, lck, false,
2919 create_disposition,
2920 first_open_attempt);
2921 if (delay) {
2922 schedule_defer_open(lck, fsp->file_id, request_time,
2923 req);
2924 TALLOC_FREE(lck);
2925 DEBUG(10, ("Sent oplock break request to kernel "
2926 "oplock holder\n"));
2927 return NT_STATUS_SHARING_VIOLATION;
2931 * No oplock from Samba around. Immediately retry with
2932 * a blocking open.
2934 retry_open(request_time, req, fsp->file_id);
2936 TALLOC_FREE(lck);
2937 DEBUG(10, ("No Samba oplock around after EWOULDBLOCK. "
2938 "Retrying sync\n"));
2939 return NT_STATUS_SHARING_VIOLATION;
2942 if (!NT_STATUS_IS_OK(fsp_open)) {
2943 if (NT_STATUS_EQUAL(fsp_open, NT_STATUS_RETRY)) {
2944 schedule_async_open(request_time, req);
2946 return fsp_open;
2949 if (new_file_created) {
2951 * As we atomically create using O_CREAT|O_EXCL,
2952 * then if new_file_created is true, then
2953 * file_existed *MUST* have been false (even
2954 * if the file was previously detected as being
2955 * there).
2957 file_existed = false;
2960 if (file_existed && !check_same_dev_ino(&saved_stat, &smb_fname->st)) {
2962 * The file did exist, but some other (local or NFS)
2963 * process either renamed/unlinked and re-created the
2964 * file with different dev/ino after we walked the path,
2965 * but before we did the open. We could retry the
2966 * open but it's a rare enough case it's easier to
2967 * just fail the open to prevent creating any problems
2968 * in the open file db having the wrong dev/ino key.
2970 fd_close(fsp);
2971 DEBUG(1,("open_file_ntcreate: file %s - dev/ino mismatch. "
2972 "Old (dev=0x%llu, ino =0x%llu). "
2973 "New (dev=0x%llu, ino=0x%llu). Failing open "
2974 " with NT_STATUS_ACCESS_DENIED.\n",
2975 smb_fname_str_dbg(smb_fname),
2976 (unsigned long long)saved_stat.st_ex_dev,
2977 (unsigned long long)saved_stat.st_ex_ino,
2978 (unsigned long long)smb_fname->st.st_ex_dev,
2979 (unsigned long long)smb_fname->st.st_ex_ino));
2980 return NT_STATUS_ACCESS_DENIED;
2983 old_write_time = smb_fname->st.st_ex_mtime;
2986 * Deal with the race condition where two smbd's detect the
2987 * file doesn't exist and do the create at the same time. One
2988 * of them will win and set a share mode, the other (ie. this
2989 * one) should check if the requested share mode for this
2990 * create is allowed.
2994 * Now the file exists and fsp is successfully opened,
2995 * fsp->dev and fsp->inode are valid and should replace the
2996 * dev=0,inode=0 from a non existent file. Spotted by
2997 * Nadav Danieli <nadavd@exanet.com>. JRA.
3000 id = fsp->file_id;
3002 lck = get_share_mode_lock(talloc_tos(), id,
3003 conn->connectpath,
3004 smb_fname, &old_write_time);
3006 if (lck == NULL) {
3007 DEBUG(0, ("open_file_ntcreate: Could not get share "
3008 "mode lock for %s\n",
3009 smb_fname_str_dbg(smb_fname)));
3010 fd_close(fsp);
3011 return NT_STATUS_SHARING_VIOLATION;
3014 /* Get the types we need to examine. */
3015 if (!validate_oplock_types(lck)) {
3016 smb_panic("validate_oplock_types failed");
3019 if (has_delete_on_close(lck, fsp->name_hash)) {
3020 TALLOC_FREE(lck);
3021 fd_close(fsp);
3022 return NT_STATUS_DELETE_PENDING;
3025 status = open_mode_check(conn, lck,
3026 access_mask, share_access);
3028 if (NT_STATUS_EQUAL(status, NT_STATUS_SHARING_VIOLATION) ||
3029 (lck->data->num_share_modes > 0)) {
3031 * This comes from ancient times out of open_mode_check. I
3032 * have no clue whether this is still necessary. I can't think
3033 * of a case where this would actually matter further down in
3034 * this function. I leave it here for further investigation
3035 * :-)
3037 file_existed = true;
3040 if (req != NULL) {
3042 * Handle oplocks, deferring the request if delay_for_oplock()
3043 * triggered a break message and we have to wait for the break
3044 * response.
3046 bool delay;
3047 bool sharing_violation = NT_STATUS_EQUAL(
3048 status, NT_STATUS_SHARING_VIOLATION);
3050 delay = delay_for_oplock(fsp, oplock_request, lease, lck,
3051 sharing_violation,
3052 create_disposition,
3053 first_open_attempt);
3054 if (delay) {
3055 schedule_defer_open(lck, fsp->file_id,
3056 request_time, req);
3057 TALLOC_FREE(lck);
3058 fd_close(fsp);
3059 return NT_STATUS_SHARING_VIOLATION;
3063 if (!NT_STATUS_IS_OK(status)) {
3064 uint32_t can_access_mask;
3065 bool can_access = True;
3067 SMB_ASSERT(NT_STATUS_EQUAL(status, NT_STATUS_SHARING_VIOLATION));
3069 /* Check if this can be done with the deny_dos and fcb
3070 * calls. */
3071 if (private_flags &
3072 (NTCREATEX_OPTIONS_PRIVATE_DENY_DOS|
3073 NTCREATEX_OPTIONS_PRIVATE_DENY_FCB)) {
3074 if (req == NULL) {
3075 DEBUG(0, ("DOS open without an SMB "
3076 "request!\n"));
3077 TALLOC_FREE(lck);
3078 fd_close(fsp);
3079 return NT_STATUS_INTERNAL_ERROR;
3082 /* Use the client requested access mask here,
3083 * not the one we open with. */
3084 status = fcb_or_dos_open(req,
3085 conn,
3086 fsp,
3087 smb_fname,
3089 req->smbpid,
3090 req->vuid,
3091 access_mask,
3092 share_access,
3093 create_options);
3095 if (NT_STATUS_IS_OK(status)) {
3096 TALLOC_FREE(lck);
3097 if (pinfo) {
3098 *pinfo = FILE_WAS_OPENED;
3100 return NT_STATUS_OK;
3105 * This next line is a subtlety we need for
3106 * MS-Access. If a file open will fail due to share
3107 * permissions and also for security (access) reasons,
3108 * we need to return the access failed error, not the
3109 * share error. We can't open the file due to kernel
3110 * oplock deadlock (it's possible we failed above on
3111 * the open_mode_check()) so use a userspace check.
3114 if (flags & O_RDWR) {
3115 can_access_mask = FILE_READ_DATA|FILE_WRITE_DATA;
3116 } else if (flags & O_WRONLY) {
3117 can_access_mask = FILE_WRITE_DATA;
3118 } else {
3119 can_access_mask = FILE_READ_DATA;
3122 if (((can_access_mask & FILE_WRITE_DATA) &&
3123 !CAN_WRITE(conn)) ||
3124 !NT_STATUS_IS_OK(smbd_check_access_rights(conn,
3125 smb_fname,
3126 false,
3127 can_access_mask))) {
3128 can_access = False;
3132 * If we're returning a share violation, ensure we
3133 * cope with the braindead 1 second delay (SMB1 only).
3136 if (!(oplock_request & INTERNAL_OPEN_ONLY) &&
3137 !conn->sconn->using_smb2 &&
3138 lp_defer_sharing_violations()) {
3139 struct timeval timeout;
3140 int timeout_usecs;
3142 /* this is a hack to speed up torture tests
3143 in 'make test' */
3144 timeout_usecs = lp_parm_int(SNUM(conn),
3145 "smbd","sharedelay",
3146 SHARING_VIOLATION_USEC_WAIT);
3148 /* This is a relative time, added to the absolute
3149 request_time value to get the absolute timeout time.
3150 Note that if this is the second or greater time we enter
3151 this codepath for this particular request mid then
3152 request_time is left as the absolute time of the *first*
3153 time this request mid was processed. This is what allows
3154 the request to eventually time out. */
3156 timeout = timeval_set(0, timeout_usecs);
3158 if (!request_timed_out(request_time, timeout)) {
3159 defer_open(lck, request_time, timeout, req,
3160 false, id);
3164 TALLOC_FREE(lck);
3165 fd_close(fsp);
3166 if (can_access) {
3168 * We have detected a sharing violation here
3169 * so return the correct error code
3171 status = NT_STATUS_SHARING_VIOLATION;
3172 } else {
3173 status = NT_STATUS_ACCESS_DENIED;
3175 return status;
3178 /* Should we atomically (to the client at least) truncate ? */
3179 if ((!new_file_created) &&
3180 (flags2 & O_TRUNC) &&
3181 (!S_ISFIFO(fsp->fsp_name->st.st_ex_mode))) {
3182 int ret;
3184 ret = vfs_set_filelen(fsp, 0);
3185 if (ret != 0) {
3186 status = map_nt_error_from_unix(errno);
3187 TALLOC_FREE(lck);
3188 fd_close(fsp);
3189 return status;
3194 * We have the share entry *locked*.....
3197 /* Delete streams if create_disposition requires it */
3198 if (!new_file_created && clear_ads(create_disposition) &&
3199 !is_ntfs_stream_smb_fname(smb_fname)) {
3200 status = delete_all_streams(conn, smb_fname);
3201 if (!NT_STATUS_IS_OK(status)) {
3202 TALLOC_FREE(lck);
3203 fd_close(fsp);
3204 return status;
3208 /* note that we ignore failure for the following. It is
3209 basically a hack for NFS, and NFS will never set one of
3210 these only read them. Nobody but Samba can ever set a deny
3211 mode and we have already checked our more authoritative
3212 locking database for permission to set this deny mode. If
3213 the kernel refuses the operations then the kernel is wrong.
3214 note that GPFS supports it as well - jmcd */
3216 if (fsp->fh->fd != -1 && lp_kernel_share_modes(SNUM(conn))) {
3217 int ret_flock;
3219 * Beware: streams implementing VFS modules may
3220 * implement streams in a way that fsp will have the
3221 * basefile open in the fsp fd, so lacking a distinct
3222 * fd for the stream kernel_flock will apply on the
3223 * basefile which is wrong. The actual check is
3224 * deffered to the VFS module implementing the
3225 * kernel_flock call.
3227 ret_flock = SMB_VFS_KERNEL_FLOCK(fsp, share_access, access_mask);
3228 if(ret_flock == -1 ){
3230 TALLOC_FREE(lck);
3231 fd_close(fsp);
3233 return NT_STATUS_SHARING_VIOLATION;
3236 fsp->kernel_share_modes_taken = true;
3240 * At this point onwards, we can guarantee that the share entry
3241 * is locked, whether we created the file or not, and that the
3242 * deny mode is compatible with all current opens.
3246 * According to Samba4, SEC_FILE_READ_ATTRIBUTE is always granted,
3247 * but we don't have to store this - just ignore it on access check.
3249 if (conn->sconn->using_smb2) {
3251 * SMB2 doesn't return it (according to Microsoft tests).
3252 * Test Case: TestSuite_ScenarioNo009GrantedAccessTestS0
3253 * File created with access = 0x7 (Read, Write, Delete)
3254 * Query Info on file returns 0x87 (Read, Write, Delete, Read Attributes)
3256 fsp->access_mask = access_mask;
3257 } else {
3258 /* But SMB1 does. */
3259 fsp->access_mask = access_mask | FILE_READ_ATTRIBUTES;
3262 if (file_existed) {
3264 * stat opens on existing files don't get oplocks.
3265 * They can get leases.
3267 * Note that we check for stat open on the *open_access_mask*,
3268 * i.e. the access mask we actually used to do the open,
3269 * not the one the client asked for (which is in
3270 * fsp->access_mask). This is due to the fact that
3271 * FILE_OVERWRITE and FILE_OVERWRITE_IF add in O_TRUNC,
3272 * which adds FILE_WRITE_DATA to open_access_mask.
3274 if (is_stat_open(open_access_mask) && lease == NULL) {
3275 oplock_request = NO_OPLOCK;
3279 if (new_file_created) {
3280 info = FILE_WAS_CREATED;
3281 } else {
3282 if (flags2 & O_TRUNC) {
3283 info = FILE_WAS_OVERWRITTEN;
3284 } else {
3285 info = FILE_WAS_OPENED;
3289 if (pinfo) {
3290 *pinfo = info;
3294 * Setup the oplock info in both the shared memory and
3295 * file structs.
3297 status = grant_fsp_oplock_type(req, fsp, lck, oplock_request, lease);
3298 if (!NT_STATUS_IS_OK(status)) {
3299 TALLOC_FREE(lck);
3300 fd_close(fsp);
3301 return status;
3304 /* Handle strange delete on close create semantics. */
3305 if (create_options & FILE_DELETE_ON_CLOSE) {
3307 status = can_set_delete_on_close(fsp, new_dos_attributes);
3309 if (!NT_STATUS_IS_OK(status)) {
3310 /* Remember to delete the mode we just added. */
3311 del_share_mode(lck, fsp);
3312 TALLOC_FREE(lck);
3313 fd_close(fsp);
3314 return status;
3316 /* Note that here we set the *inital* delete on close flag,
3317 not the regular one. The magic gets handled in close. */
3318 fsp->initial_delete_on_close = True;
3321 if (info != FILE_WAS_OPENED) {
3322 /* Overwritten files should be initially set as archive */
3323 if ((info == FILE_WAS_OVERWRITTEN && lp_map_archive(SNUM(conn))) ||
3324 lp_store_dos_attributes(SNUM(conn))) {
3325 if (!posix_open) {
3326 if (file_set_dosmode(conn, smb_fname,
3327 new_dos_attributes | FILE_ATTRIBUTE_ARCHIVE,
3328 parent_dir, true) == 0) {
3329 unx_mode = smb_fname->st.st_ex_mode;
3335 /* Determine sparse flag. */
3336 if (posix_open) {
3337 /* POSIX opens are sparse by default. */
3338 fsp->is_sparse = true;
3339 } else {
3340 fsp->is_sparse = (file_existed &&
3341 (existing_dos_attributes & FILE_ATTRIBUTE_SPARSE));
3345 * Take care of inherited ACLs on created files - if default ACL not
3346 * selected.
3349 if (!posix_open && new_file_created && !def_acl) {
3351 int saved_errno = errno; /* We might get ENOSYS in the next
3352 * call.. */
3354 if (SMB_VFS_FCHMOD_ACL(fsp, unx_mode) == -1 &&
3355 errno == ENOSYS) {
3356 errno = saved_errno; /* Ignore ENOSYS */
3359 } else if (new_unx_mode) {
3361 int ret = -1;
3363 /* Attributes need changing. File already existed. */
3366 int saved_errno = errno; /* We might get ENOSYS in the
3367 * next call.. */
3368 ret = SMB_VFS_FCHMOD_ACL(fsp, new_unx_mode);
3370 if (ret == -1 && errno == ENOSYS) {
3371 errno = saved_errno; /* Ignore ENOSYS */
3372 } else {
3373 DEBUG(5, ("open_file_ntcreate: reset "
3374 "attributes of file %s to 0%o\n",
3375 smb_fname_str_dbg(smb_fname),
3376 (unsigned int)new_unx_mode));
3377 ret = 0; /* Don't do the fchmod below. */
3381 if ((ret == -1) &&
3382 (SMB_VFS_FCHMOD(fsp, new_unx_mode) == -1))
3383 DEBUG(5, ("open_file_ntcreate: failed to reset "
3384 "attributes of file %s to 0%o\n",
3385 smb_fname_str_dbg(smb_fname),
3386 (unsigned int)new_unx_mode));
3391 * Deal with other opens having a modified write time.
3393 struct timespec write_time = get_share_mode_write_time(lck);
3395 if (!null_timespec(write_time)) {
3396 update_stat_ex_mtime(&fsp->fsp_name->st, write_time);
3400 TALLOC_FREE(lck);
3402 return NT_STATUS_OK;
3405 static NTSTATUS mkdir_internal(connection_struct *conn,
3406 struct smb_filename *smb_dname,
3407 uint32_t file_attributes)
3409 mode_t mode;
3410 char *parent_dir = NULL;
3411 NTSTATUS status;
3412 bool posix_open = false;
3413 bool need_re_stat = false;
3414 uint32_t access_mask = SEC_DIR_ADD_SUBDIR;
3416 if (!CAN_WRITE(conn) || (access_mask & ~(conn->share_access))) {
3417 DEBUG(5,("mkdir_internal: failing share access "
3418 "%s\n", lp_servicename(talloc_tos(), SNUM(conn))));
3419 return NT_STATUS_ACCESS_DENIED;
3422 if (!parent_dirname(talloc_tos(), smb_dname->base_name, &parent_dir,
3423 NULL)) {
3424 return NT_STATUS_NO_MEMORY;
3427 if (file_attributes & FILE_FLAG_POSIX_SEMANTICS) {
3428 posix_open = true;
3429 mode = (mode_t)(file_attributes & ~FILE_FLAG_POSIX_SEMANTICS);
3430 } else {
3431 mode = unix_mode(conn, FILE_ATTRIBUTE_DIRECTORY, smb_dname, parent_dir);
3434 status = check_parent_access(conn,
3435 smb_dname,
3436 access_mask);
3437 if(!NT_STATUS_IS_OK(status)) {
3438 DEBUG(5,("mkdir_internal: check_parent_access "
3439 "on directory %s for path %s returned %s\n",
3440 parent_dir,
3441 smb_dname->base_name,
3442 nt_errstr(status) ));
3443 return status;
3446 if (SMB_VFS_MKDIR(conn, smb_dname, mode) != 0) {
3447 return map_nt_error_from_unix(errno);
3450 /* Ensure we're checking for a symlink here.... */
3451 /* We don't want to get caught by a symlink racer. */
3453 if (SMB_VFS_LSTAT(conn, smb_dname) == -1) {
3454 DEBUG(2, ("Could not stat directory '%s' just created: %s\n",
3455 smb_fname_str_dbg(smb_dname), strerror(errno)));
3456 return map_nt_error_from_unix(errno);
3459 if (!S_ISDIR(smb_dname->st.st_ex_mode)) {
3460 DEBUG(0, ("Directory '%s' just created is not a directory !\n",
3461 smb_fname_str_dbg(smb_dname)));
3462 return NT_STATUS_NOT_A_DIRECTORY;
3465 if (lp_store_dos_attributes(SNUM(conn))) {
3466 if (!posix_open) {
3467 file_set_dosmode(conn, smb_dname,
3468 file_attributes | FILE_ATTRIBUTE_DIRECTORY,
3469 parent_dir, true);
3473 if (lp_inherit_permissions(SNUM(conn))) {
3474 inherit_access_posix_acl(conn, parent_dir,
3475 smb_dname->base_name, mode);
3476 need_re_stat = true;
3479 if (!posix_open) {
3481 * Check if high bits should have been set,
3482 * then (if bits are missing): add them.
3483 * Consider bits automagically set by UNIX, i.e. SGID bit from parent
3484 * dir.
3486 if ((mode & ~(S_IRWXU|S_IRWXG|S_IRWXO)) &&
3487 (mode & ~smb_dname->st.st_ex_mode)) {
3488 SMB_VFS_CHMOD(conn, smb_dname,
3489 (smb_dname->st.st_ex_mode |
3490 (mode & ~smb_dname->st.st_ex_mode)));
3491 need_re_stat = true;
3495 /* Change the owner if required. */
3496 if (lp_inherit_owner(SNUM(conn)) != INHERIT_OWNER_NO) {
3497 change_dir_owner_to_parent(conn, parent_dir,
3498 smb_dname->base_name,
3499 &smb_dname->st);
3500 need_re_stat = true;
3503 if (need_re_stat) {
3504 if (SMB_VFS_LSTAT(conn, smb_dname) == -1) {
3505 DEBUG(2, ("Could not stat directory '%s' just created: %s\n",
3506 smb_fname_str_dbg(smb_dname), strerror(errno)));
3507 return map_nt_error_from_unix(errno);
3511 notify_fname(conn, NOTIFY_ACTION_ADDED, FILE_NOTIFY_CHANGE_DIR_NAME,
3512 smb_dname->base_name);
3514 return NT_STATUS_OK;
3517 /****************************************************************************
3518 Open a directory from an NT SMB call.
3519 ****************************************************************************/
3521 static NTSTATUS open_directory(connection_struct *conn,
3522 struct smb_request *req,
3523 struct smb_filename *smb_dname,
3524 uint32_t access_mask,
3525 uint32_t share_access,
3526 uint32_t create_disposition,
3527 uint32_t create_options,
3528 uint32_t file_attributes,
3529 int *pinfo,
3530 files_struct **result)
3532 files_struct *fsp = NULL;
3533 bool dir_existed = VALID_STAT(smb_dname->st) ? True : False;
3534 struct share_mode_lock *lck = NULL;
3535 NTSTATUS status;
3536 struct timespec mtimespec;
3537 int info = 0;
3538 bool ok;
3540 if (is_ntfs_stream_smb_fname(smb_dname)) {
3541 DEBUG(2, ("open_directory: %s is a stream name!\n",
3542 smb_fname_str_dbg(smb_dname)));
3543 return NT_STATUS_NOT_A_DIRECTORY;
3546 if (!(file_attributes & FILE_FLAG_POSIX_SEMANTICS)) {
3547 /* Ensure we have a directory attribute. */
3548 file_attributes |= FILE_ATTRIBUTE_DIRECTORY;
3551 DEBUG(5,("open_directory: opening directory %s, access_mask = 0x%x, "
3552 "share_access = 0x%x create_options = 0x%x, "
3553 "create_disposition = 0x%x, file_attributes = 0x%x\n",
3554 smb_fname_str_dbg(smb_dname),
3555 (unsigned int)access_mask,
3556 (unsigned int)share_access,
3557 (unsigned int)create_options,
3558 (unsigned int)create_disposition,
3559 (unsigned int)file_attributes));
3561 status = smbd_calculate_access_mask(conn, smb_dname, false,
3562 access_mask, &access_mask);
3563 if (!NT_STATUS_IS_OK(status)) {
3564 DEBUG(10, ("open_directory: smbd_calculate_access_mask "
3565 "on file %s returned %s\n",
3566 smb_fname_str_dbg(smb_dname),
3567 nt_errstr(status)));
3568 return status;
3571 if ((access_mask & SEC_FLAG_SYSTEM_SECURITY) &&
3572 !security_token_has_privilege(get_current_nttok(conn),
3573 SEC_PRIV_SECURITY)) {
3574 DEBUG(10, ("open_directory: open on %s "
3575 "failed - SEC_FLAG_SYSTEM_SECURITY denied.\n",
3576 smb_fname_str_dbg(smb_dname)));
3577 return NT_STATUS_PRIVILEGE_NOT_HELD;
3580 switch( create_disposition ) {
3581 case FILE_OPEN:
3583 if (!dir_existed) {
3584 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3587 info = FILE_WAS_OPENED;
3588 break;
3590 case FILE_CREATE:
3592 /* If directory exists error. If directory doesn't
3593 * exist create. */
3595 if (dir_existed) {
3596 status = NT_STATUS_OBJECT_NAME_COLLISION;
3597 DEBUG(2, ("open_directory: unable to create "
3598 "%s. Error was %s\n",
3599 smb_fname_str_dbg(smb_dname),
3600 nt_errstr(status)));
3601 return status;
3604 status = mkdir_internal(conn, smb_dname,
3605 file_attributes);
3607 if (!NT_STATUS_IS_OK(status)) {
3608 DEBUG(2, ("open_directory: unable to create "
3609 "%s. Error was %s\n",
3610 smb_fname_str_dbg(smb_dname),
3611 nt_errstr(status)));
3612 return status;
3615 info = FILE_WAS_CREATED;
3616 break;
3618 case FILE_OPEN_IF:
3620 * If directory exists open. If directory doesn't
3621 * exist create.
3624 if (dir_existed) {
3625 status = NT_STATUS_OK;
3626 info = FILE_WAS_OPENED;
3627 } else {
3628 status = mkdir_internal(conn, smb_dname,
3629 file_attributes);
3631 if (NT_STATUS_IS_OK(status)) {
3632 info = FILE_WAS_CREATED;
3633 } else {
3634 /* Cope with create race. */
3635 if (!NT_STATUS_EQUAL(status,
3636 NT_STATUS_OBJECT_NAME_COLLISION)) {
3637 DEBUG(2, ("open_directory: unable to create "
3638 "%s. Error was %s\n",
3639 smb_fname_str_dbg(smb_dname),
3640 nt_errstr(status)));
3641 return status;
3645 * If mkdir_internal() returned
3646 * NT_STATUS_OBJECT_NAME_COLLISION
3647 * we still must lstat the path.
3650 if (SMB_VFS_LSTAT(conn, smb_dname)
3651 == -1) {
3652 DEBUG(2, ("Could not stat "
3653 "directory '%s' just "
3654 "opened: %s\n",
3655 smb_fname_str_dbg(
3656 smb_dname),
3657 strerror(errno)));
3658 return map_nt_error_from_unix(
3659 errno);
3662 info = FILE_WAS_OPENED;
3666 break;
3668 case FILE_SUPERSEDE:
3669 case FILE_OVERWRITE:
3670 case FILE_OVERWRITE_IF:
3671 default:
3672 DEBUG(5,("open_directory: invalid create_disposition "
3673 "0x%x for directory %s\n",
3674 (unsigned int)create_disposition,
3675 smb_fname_str_dbg(smb_dname)));
3676 return NT_STATUS_INVALID_PARAMETER;
3679 if(!S_ISDIR(smb_dname->st.st_ex_mode)) {
3680 DEBUG(5,("open_directory: %s is not a directory !\n",
3681 smb_fname_str_dbg(smb_dname)));
3682 return NT_STATUS_NOT_A_DIRECTORY;
3685 if (info == FILE_WAS_OPENED) {
3686 status = smbd_check_access_rights(conn,
3687 smb_dname,
3688 false,
3689 access_mask);
3690 if (!NT_STATUS_IS_OK(status)) {
3691 DEBUG(10, ("open_directory: smbd_check_access_rights on "
3692 "file %s failed with %s\n",
3693 smb_fname_str_dbg(smb_dname),
3694 nt_errstr(status)));
3695 return status;
3699 status = file_new(req, conn, &fsp);
3700 if(!NT_STATUS_IS_OK(status)) {
3701 return status;
3705 * Setup the files_struct for it.
3708 fsp->file_id = vfs_file_id_from_sbuf(conn, &smb_dname->st);
3709 fsp->vuid = req ? req->vuid : UID_FIELD_INVALID;
3710 fsp->file_pid = req ? req->smbpid : 0;
3711 fsp->can_lock = False;
3712 fsp->can_read = False;
3713 fsp->can_write = False;
3715 fsp->share_access = share_access;
3716 fsp->fh->private_options = 0;
3718 * According to Samba4, SEC_FILE_READ_ATTRIBUTE is always granted,
3720 fsp->access_mask = access_mask | FILE_READ_ATTRIBUTES;
3721 fsp->print_file = NULL;
3722 fsp->modified = False;
3723 fsp->oplock_type = NO_OPLOCK;
3724 fsp->sent_oplock_break = NO_BREAK_SENT;
3725 fsp->is_directory = True;
3726 if (file_attributes & FILE_FLAG_POSIX_SEMANTICS) {
3727 fsp->posix_flags |= FSP_POSIX_FLAGS_ALL;
3729 status = fsp_set_smb_fname(fsp, smb_dname);
3730 if (!NT_STATUS_IS_OK(status)) {
3731 file_free(req, fsp);
3732 return status;
3735 /* Don't store old timestamps for directory
3736 handles in the internal database. We don't
3737 update them in there if new objects
3738 are creaded in the directory. Currently
3739 we only update timestamps on file writes.
3740 See bug #9870.
3742 ZERO_STRUCT(mtimespec);
3744 if (access_mask & (FILE_LIST_DIRECTORY|
3745 FILE_ADD_FILE|
3746 FILE_ADD_SUBDIRECTORY|
3747 FILE_TRAVERSE|
3748 DELETE_ACCESS|
3749 FILE_DELETE_CHILD)) {
3750 #ifdef O_DIRECTORY
3751 status = fd_open(conn, fsp, O_RDONLY|O_DIRECTORY, 0);
3752 #else
3753 /* POSIX allows us to open a directory with O_RDONLY. */
3754 status = fd_open(conn, fsp, O_RDONLY, 0);
3755 #endif
3756 if (!NT_STATUS_IS_OK(status)) {
3757 DEBUG(5, ("open_directory: Could not open fd for "
3758 "%s (%s)\n",
3759 smb_fname_str_dbg(smb_dname),
3760 nt_errstr(status)));
3761 file_free(req, fsp);
3762 return status;
3764 } else {
3765 fsp->fh->fd = -1;
3766 DEBUG(10, ("Not opening Directory %s\n",
3767 smb_fname_str_dbg(smb_dname)));
3770 status = vfs_stat_fsp(fsp);
3771 if (!NT_STATUS_IS_OK(status)) {
3772 fd_close(fsp);
3773 file_free(req, fsp);
3774 return status;
3777 if(!S_ISDIR(fsp->fsp_name->st.st_ex_mode)) {
3778 DEBUG(5,("open_directory: %s is not a directory !\n",
3779 smb_fname_str_dbg(smb_dname)));
3780 fd_close(fsp);
3781 file_free(req, fsp);
3782 return NT_STATUS_NOT_A_DIRECTORY;
3785 /* Ensure there was no race condition. We need to check
3786 * dev/inode but not permissions, as these can change
3787 * legitimately */
3788 if (!check_same_dev_ino(&smb_dname->st, &fsp->fsp_name->st)) {
3789 DEBUG(5,("open_directory: stat struct differs for "
3790 "directory %s.\n",
3791 smb_fname_str_dbg(smb_dname)));
3792 fd_close(fsp);
3793 file_free(req, fsp);
3794 return NT_STATUS_ACCESS_DENIED;
3797 lck = get_share_mode_lock(talloc_tos(), fsp->file_id,
3798 conn->connectpath, smb_dname,
3799 &mtimespec);
3801 if (lck == NULL) {
3802 DEBUG(0, ("open_directory: Could not get share mode lock for "
3803 "%s\n", smb_fname_str_dbg(smb_dname)));
3804 fd_close(fsp);
3805 file_free(req, fsp);
3806 return NT_STATUS_SHARING_VIOLATION;
3809 if (has_delete_on_close(lck, fsp->name_hash)) {
3810 TALLOC_FREE(lck);
3811 fd_close(fsp);
3812 file_free(req, fsp);
3813 return NT_STATUS_DELETE_PENDING;
3816 status = open_mode_check(conn, lck,
3817 access_mask, share_access);
3819 if (!NT_STATUS_IS_OK(status)) {
3820 TALLOC_FREE(lck);
3821 fd_close(fsp);
3822 file_free(req, fsp);
3823 return status;
3826 ok = set_share_mode(lck, fsp, get_current_uid(conn),
3827 req ? req->mid : 0, NO_OPLOCK,
3828 UINT32_MAX);
3829 if (!ok) {
3830 TALLOC_FREE(lck);
3831 fd_close(fsp);
3832 file_free(req, fsp);
3833 return NT_STATUS_NO_MEMORY;
3836 /* For directories the delete on close bit at open time seems
3837 always to be honored on close... See test 19 in Samba4 BASE-DELETE. */
3838 if (create_options & FILE_DELETE_ON_CLOSE) {
3839 status = can_set_delete_on_close(fsp, 0);
3840 if (!NT_STATUS_IS_OK(status) && !NT_STATUS_EQUAL(status, NT_STATUS_DIRECTORY_NOT_EMPTY)) {
3841 del_share_mode(lck, fsp);
3842 TALLOC_FREE(lck);
3843 fd_close(fsp);
3844 file_free(req, fsp);
3845 return status;
3848 if (NT_STATUS_IS_OK(status)) {
3849 /* Note that here we set the *inital* delete on close flag,
3850 not the regular one. The magic gets handled in close. */
3851 fsp->initial_delete_on_close = True;
3857 * Deal with other opens having a modified write time. Is this
3858 * possible for directories?
3860 struct timespec write_time = get_share_mode_write_time(lck);
3862 if (!null_timespec(write_time)) {
3863 update_stat_ex_mtime(&fsp->fsp_name->st, write_time);
3867 TALLOC_FREE(lck);
3869 if (pinfo) {
3870 *pinfo = info;
3873 *result = fsp;
3874 return NT_STATUS_OK;
3877 NTSTATUS create_directory(connection_struct *conn, struct smb_request *req,
3878 struct smb_filename *smb_dname)
3880 NTSTATUS status;
3881 files_struct *fsp;
3883 status = SMB_VFS_CREATE_FILE(
3884 conn, /* conn */
3885 req, /* req */
3886 0, /* root_dir_fid */
3887 smb_dname, /* fname */
3888 FILE_READ_ATTRIBUTES, /* access_mask */
3889 FILE_SHARE_NONE, /* share_access */
3890 FILE_CREATE, /* create_disposition*/
3891 FILE_DIRECTORY_FILE, /* create_options */
3892 FILE_ATTRIBUTE_DIRECTORY, /* file_attributes */
3893 0, /* oplock_request */
3894 NULL, /* lease */
3895 0, /* allocation_size */
3896 0, /* private_flags */
3897 NULL, /* sd */
3898 NULL, /* ea_list */
3899 &fsp, /* result */
3900 NULL, /* pinfo */
3901 NULL, NULL); /* create context */
3903 if (NT_STATUS_IS_OK(status)) {
3904 close_file(req, fsp, NORMAL_CLOSE);
3907 return status;
3910 /****************************************************************************
3911 Receive notification that one of our open files has been renamed by another
3912 smbd process.
3913 ****************************************************************************/
3915 void msg_file_was_renamed(struct messaging_context *msg,
3916 void *private_data,
3917 uint32_t msg_type,
3918 struct server_id server_id,
3919 DATA_BLOB *data)
3921 files_struct *fsp;
3922 char *frm = (char *)data->data;
3923 struct file_id id;
3924 const char *sharepath;
3925 const char *base_name;
3926 const char *stream_name;
3927 struct smb_filename *smb_fname = NULL;
3928 size_t sp_len, bn_len;
3929 NTSTATUS status;
3930 struct smbd_server_connection *sconn =
3931 talloc_get_type_abort(private_data,
3932 struct smbd_server_connection);
3934 if (data->data == NULL
3935 || data->length < MSG_FILE_RENAMED_MIN_SIZE + 2) {
3936 DEBUG(0, ("msg_file_was_renamed: Got invalid msg len %d\n",
3937 (int)data->length));
3938 return;
3941 /* Unpack the message. */
3942 pull_file_id_24(frm, &id);
3943 sharepath = &frm[24];
3944 sp_len = strlen(sharepath);
3945 base_name = sharepath + sp_len + 1;
3946 bn_len = strlen(base_name);
3947 stream_name = sharepath + sp_len + 1 + bn_len + 1;
3949 /* stream_name must always be NULL if there is no stream. */
3950 if (stream_name[0] == '\0') {
3951 stream_name = NULL;
3954 smb_fname = synthetic_smb_fname(talloc_tos(),
3955 base_name,
3956 stream_name,
3957 NULL,
3959 if (smb_fname == NULL) {
3960 return;
3963 DEBUG(10,("msg_file_was_renamed: Got rename message for sharepath %s, new name %s, "
3964 "file_id %s\n",
3965 sharepath, smb_fname_str_dbg(smb_fname),
3966 file_id_string_tos(&id)));
3968 for(fsp = file_find_di_first(sconn, id); fsp;
3969 fsp = file_find_di_next(fsp)) {
3970 if (memcmp(fsp->conn->connectpath, sharepath, sp_len) == 0) {
3972 DEBUG(10,("msg_file_was_renamed: renaming file %s from %s -> %s\n",
3973 fsp_fnum_dbg(fsp), fsp_str_dbg(fsp),
3974 smb_fname_str_dbg(smb_fname)));
3975 status = fsp_set_smb_fname(fsp, smb_fname);
3976 if (!NT_STATUS_IS_OK(status)) {
3977 goto out;
3979 } else {
3980 /* TODO. JRA. */
3981 /* Now we have the complete path we can work out if this is
3982 actually within this share and adjust newname accordingly. */
3983 DEBUG(10,("msg_file_was_renamed: share mismatch (sharepath %s "
3984 "not sharepath %s) "
3985 "%s from %s -> %s\n",
3986 fsp->conn->connectpath,
3987 sharepath,
3988 fsp_fnum_dbg(fsp),
3989 fsp_str_dbg(fsp),
3990 smb_fname_str_dbg(smb_fname)));
3993 out:
3994 TALLOC_FREE(smb_fname);
3995 return;
3999 * If a main file is opened for delete, all streams need to be checked for
4000 * !FILE_SHARE_DELETE. Do this by opening with DELETE_ACCESS.
4001 * If that works, delete them all by setting the delete on close and close.
4004 static NTSTATUS open_streams_for_delete(connection_struct *conn,
4005 const struct smb_filename *smb_fname)
4007 struct stream_struct *stream_info = NULL;
4008 files_struct **streams = NULL;
4009 int i;
4010 unsigned int num_streams = 0;
4011 TALLOC_CTX *frame = talloc_stackframe();
4012 NTSTATUS status;
4014 status = vfs_streaminfo(conn, NULL, smb_fname, talloc_tos(),
4015 &num_streams, &stream_info);
4017 if (NT_STATUS_EQUAL(status, NT_STATUS_NOT_IMPLEMENTED)
4018 || NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
4019 DEBUG(10, ("no streams around\n"));
4020 TALLOC_FREE(frame);
4021 return NT_STATUS_OK;
4024 if (!NT_STATUS_IS_OK(status)) {
4025 DEBUG(10, ("vfs_streaminfo failed: %s\n",
4026 nt_errstr(status)));
4027 goto fail;
4030 DEBUG(10, ("open_streams_for_delete found %d streams\n",
4031 num_streams));
4033 if (num_streams == 0) {
4034 TALLOC_FREE(frame);
4035 return NT_STATUS_OK;
4038 streams = talloc_array(talloc_tos(), files_struct *, num_streams);
4039 if (streams == NULL) {
4040 DEBUG(0, ("talloc failed\n"));
4041 status = NT_STATUS_NO_MEMORY;
4042 goto fail;
4045 for (i=0; i<num_streams; i++) {
4046 struct smb_filename *smb_fname_cp;
4048 if (strequal(stream_info[i].name, "::$DATA")) {
4049 streams[i] = NULL;
4050 continue;
4053 smb_fname_cp = synthetic_smb_fname(talloc_tos(),
4054 smb_fname->base_name,
4055 stream_info[i].name,
4056 NULL,
4057 (smb_fname->flags &
4058 ~SMB_FILENAME_POSIX_PATH));
4059 if (smb_fname_cp == NULL) {
4060 status = NT_STATUS_NO_MEMORY;
4061 goto fail;
4064 if (SMB_VFS_STAT(conn, smb_fname_cp) == -1) {
4065 DEBUG(10, ("Unable to stat stream: %s\n",
4066 smb_fname_str_dbg(smb_fname_cp)));
4069 status = SMB_VFS_CREATE_FILE(
4070 conn, /* conn */
4071 NULL, /* req */
4072 0, /* root_dir_fid */
4073 smb_fname_cp, /* fname */
4074 DELETE_ACCESS, /* access_mask */
4075 (FILE_SHARE_READ | /* share_access */
4076 FILE_SHARE_WRITE | FILE_SHARE_DELETE),
4077 FILE_OPEN, /* create_disposition*/
4078 0, /* create_options */
4079 FILE_ATTRIBUTE_NORMAL, /* file_attributes */
4080 0, /* oplock_request */
4081 NULL, /* lease */
4082 0, /* allocation_size */
4083 NTCREATEX_OPTIONS_PRIVATE_STREAM_DELETE, /* private_flags */
4084 NULL, /* sd */
4085 NULL, /* ea_list */
4086 &streams[i], /* result */
4087 NULL, /* pinfo */
4088 NULL, NULL); /* create context */
4090 if (!NT_STATUS_IS_OK(status)) {
4091 DEBUG(10, ("Could not open stream %s: %s\n",
4092 smb_fname_str_dbg(smb_fname_cp),
4093 nt_errstr(status)));
4095 TALLOC_FREE(smb_fname_cp);
4096 break;
4098 TALLOC_FREE(smb_fname_cp);
4102 * don't touch the variable "status" beyond this point :-)
4105 for (i -= 1 ; i >= 0; i--) {
4106 if (streams[i] == NULL) {
4107 continue;
4110 DEBUG(10, ("Closing stream # %d, %s\n", i,
4111 fsp_str_dbg(streams[i])));
4112 close_file(NULL, streams[i], NORMAL_CLOSE);
4115 fail:
4116 TALLOC_FREE(frame);
4117 return status;
4120 /*********************************************************************
4121 Create a default ACL by inheriting from the parent. If no inheritance
4122 from the parent available, don't set anything. This will leave the actual
4123 permissions the new file or directory already got from the filesystem
4124 as the NT ACL when read.
4125 *********************************************************************/
4127 static NTSTATUS inherit_new_acl(files_struct *fsp)
4129 TALLOC_CTX *frame = talloc_stackframe();
4130 char *parent_name = NULL;
4131 struct security_descriptor *parent_desc = NULL;
4132 NTSTATUS status = NT_STATUS_OK;
4133 struct security_descriptor *psd = NULL;
4134 const struct dom_sid *owner_sid = NULL;
4135 const struct dom_sid *group_sid = NULL;
4136 uint32_t security_info_sent = (SECINFO_OWNER | SECINFO_GROUP | SECINFO_DACL);
4137 struct security_token *token = fsp->conn->session_info->security_token;
4138 bool inherit_owner =
4139 (lp_inherit_owner(SNUM(fsp->conn)) == INHERIT_OWNER_WINDOWS_AND_UNIX);
4140 bool inheritable_components = false;
4141 bool try_builtin_administrators = false;
4142 const struct dom_sid *BA_U_sid = NULL;
4143 const struct dom_sid *BA_G_sid = NULL;
4144 bool try_system = false;
4145 const struct dom_sid *SY_U_sid = NULL;
4146 const struct dom_sid *SY_G_sid = NULL;
4147 size_t size = 0;
4148 struct smb_filename *parent_smb_fname = NULL;
4150 if (!parent_dirname(frame, fsp->fsp_name->base_name, &parent_name, NULL)) {
4151 TALLOC_FREE(frame);
4152 return NT_STATUS_NO_MEMORY;
4154 parent_smb_fname = synthetic_smb_fname(talloc_tos(),
4155 parent_name,
4156 NULL,
4157 NULL,
4158 fsp->fsp_name->flags);
4160 if (parent_smb_fname == NULL) {
4161 TALLOC_FREE(frame);
4162 return NT_STATUS_NO_MEMORY;
4165 status = SMB_VFS_GET_NT_ACL(fsp->conn,
4166 parent_smb_fname,
4167 (SECINFO_OWNER | SECINFO_GROUP | SECINFO_DACL),
4168 frame,
4169 &parent_desc);
4170 if (!NT_STATUS_IS_OK(status)) {
4171 TALLOC_FREE(frame);
4172 return status;
4175 inheritable_components = sd_has_inheritable_components(parent_desc,
4176 fsp->is_directory);
4178 if (!inheritable_components && !inherit_owner) {
4179 TALLOC_FREE(frame);
4180 /* Nothing to inherit and not setting owner. */
4181 return NT_STATUS_OK;
4184 /* Create an inherited descriptor from the parent. */
4186 if (DEBUGLEVEL >= 10) {
4187 DEBUG(10,("inherit_new_acl: parent acl for %s is:\n",
4188 fsp_str_dbg(fsp) ));
4189 NDR_PRINT_DEBUG(security_descriptor, parent_desc);
4192 /* Inherit from parent descriptor if "inherit owner" set. */
4193 if (inherit_owner) {
4194 owner_sid = parent_desc->owner_sid;
4195 group_sid = parent_desc->group_sid;
4198 if (owner_sid == NULL) {
4199 if (security_token_has_builtin_administrators(token)) {
4200 try_builtin_administrators = true;
4201 } else if (security_token_is_system(token)) {
4202 try_builtin_administrators = true;
4203 try_system = true;
4207 if (group_sid == NULL &&
4208 token->num_sids == PRIMARY_GROUP_SID_INDEX)
4210 if (security_token_is_system(token)) {
4211 try_builtin_administrators = true;
4212 try_system = true;
4216 if (try_builtin_administrators) {
4217 struct unixid ids;
4218 bool ok;
4220 ZERO_STRUCT(ids);
4221 ok = sids_to_unixids(&global_sid_Builtin_Administrators, 1, &ids);
4222 if (ok) {
4223 switch (ids.type) {
4224 case ID_TYPE_BOTH:
4225 BA_U_sid = &global_sid_Builtin_Administrators;
4226 BA_G_sid = &global_sid_Builtin_Administrators;
4227 break;
4228 case ID_TYPE_UID:
4229 BA_U_sid = &global_sid_Builtin_Administrators;
4230 break;
4231 case ID_TYPE_GID:
4232 BA_G_sid = &global_sid_Builtin_Administrators;
4233 break;
4234 default:
4235 break;
4240 if (try_system) {
4241 struct unixid ids;
4242 bool ok;
4244 ZERO_STRUCT(ids);
4245 ok = sids_to_unixids(&global_sid_System, 1, &ids);
4246 if (ok) {
4247 switch (ids.type) {
4248 case ID_TYPE_BOTH:
4249 SY_U_sid = &global_sid_System;
4250 SY_G_sid = &global_sid_System;
4251 break;
4252 case ID_TYPE_UID:
4253 SY_U_sid = &global_sid_System;
4254 break;
4255 case ID_TYPE_GID:
4256 SY_G_sid = &global_sid_System;
4257 break;
4258 default:
4259 break;
4264 if (owner_sid == NULL) {
4265 owner_sid = BA_U_sid;
4268 if (owner_sid == NULL) {
4269 owner_sid = SY_U_sid;
4272 if (group_sid == NULL) {
4273 group_sid = SY_G_sid;
4276 if (try_system && group_sid == NULL) {
4277 group_sid = BA_G_sid;
4280 if (owner_sid == NULL) {
4281 owner_sid = &token->sids[PRIMARY_USER_SID_INDEX];
4283 if (group_sid == NULL) {
4284 if (token->num_sids == PRIMARY_GROUP_SID_INDEX) {
4285 group_sid = &token->sids[PRIMARY_USER_SID_INDEX];
4286 } else {
4287 group_sid = &token->sids[PRIMARY_GROUP_SID_INDEX];
4291 status = se_create_child_secdesc(frame,
4292 &psd,
4293 &size,
4294 parent_desc,
4295 owner_sid,
4296 group_sid,
4297 fsp->is_directory);
4298 if (!NT_STATUS_IS_OK(status)) {
4299 TALLOC_FREE(frame);
4300 return status;
4303 /* If inheritable_components == false,
4304 se_create_child_secdesc()
4305 creates a security desriptor with a NULL dacl
4306 entry, but with SEC_DESC_DACL_PRESENT. We need
4307 to remove that flag. */
4309 if (!inheritable_components) {
4310 security_info_sent &= ~SECINFO_DACL;
4311 psd->type &= ~SEC_DESC_DACL_PRESENT;
4314 if (DEBUGLEVEL >= 10) {
4315 DEBUG(10,("inherit_new_acl: child acl for %s is:\n",
4316 fsp_str_dbg(fsp) ));
4317 NDR_PRINT_DEBUG(security_descriptor, psd);
4320 if (inherit_owner) {
4321 /* We need to be root to force this. */
4322 become_root();
4324 status = SMB_VFS_FSET_NT_ACL(fsp,
4325 security_info_sent,
4326 psd);
4327 if (inherit_owner) {
4328 unbecome_root();
4330 TALLOC_FREE(frame);
4331 return status;
4335 * If we already have a lease, it must match the new file id. [MS-SMB2]
4336 * 3.3.5.9.8 speaks about INVALID_PARAMETER if an already used lease key is
4337 * used for a different file name.
4340 struct lease_match_state {
4341 /* Input parameters. */
4342 TALLOC_CTX *mem_ctx;
4343 const char *servicepath;
4344 const struct smb_filename *fname;
4345 bool file_existed;
4346 struct file_id id;
4347 /* Return parameters. */
4348 uint32_t num_file_ids;
4349 struct file_id *ids;
4350 NTSTATUS match_status;
4353 /*************************************************************
4354 File doesn't exist but this lease key+guid is already in use.
4356 This is only allowable in the dynamic share case where the
4357 service path must be different.
4359 There is a small race condition here in the multi-connection
4360 case where a client sends two create calls on different connections,
4361 where the file doesn't exist and one smbd creates the leases_db
4362 entry first, but this will get fixed by the multichannel cleanup
4363 when all identical client_guids get handled by a single smbd.
4364 **************************************************************/
4366 static void lease_match_parser_new_file(
4367 uint32_t num_files,
4368 const struct leases_db_file *files,
4369 struct lease_match_state *state)
4371 uint32_t i;
4373 for (i = 0; i < num_files; i++) {
4374 const struct leases_db_file *f = &files[i];
4375 if (strequal(state->servicepath, f->servicepath)) {
4376 state->match_status = NT_STATUS_INVALID_PARAMETER;
4377 return;
4381 /* Dynamic share case. Break leases on all other files. */
4382 state->match_status = leases_db_copy_file_ids(state->mem_ctx,
4383 num_files,
4384 files,
4385 &state->ids);
4386 if (!NT_STATUS_IS_OK(state->match_status)) {
4387 return;
4390 state->num_file_ids = num_files;
4391 state->match_status = NT_STATUS_OPLOCK_NOT_GRANTED;
4392 return;
4395 static void lease_match_parser(
4396 uint32_t num_files,
4397 const struct leases_db_file *files,
4398 void *private_data)
4400 struct lease_match_state *state =
4401 (struct lease_match_state *)private_data;
4402 uint32_t i;
4404 if (!state->file_existed) {
4406 * Deal with name mismatch or
4407 * possible dynamic share case separately
4408 * to make code clearer.
4410 lease_match_parser_new_file(num_files,
4411 files,
4412 state);
4413 return;
4416 /* File existed. */
4417 state->match_status = NT_STATUS_OK;
4419 for (i = 0; i < num_files; i++) {
4420 const struct leases_db_file *f = &files[i];
4422 /* Everything should be the same. */
4423 if (!file_id_equal(&state->id, &f->id)) {
4424 /* This should catch all dynamic share cases. */
4425 state->match_status = NT_STATUS_OPLOCK_NOT_GRANTED;
4426 break;
4428 if (!strequal(f->servicepath, state->servicepath)) {
4429 state->match_status = NT_STATUS_INVALID_PARAMETER;
4430 break;
4432 if (!strequal(f->base_name, state->fname->base_name)) {
4433 state->match_status = NT_STATUS_INVALID_PARAMETER;
4434 break;
4436 if (!strequal(f->stream_name, state->fname->stream_name)) {
4437 state->match_status = NT_STATUS_INVALID_PARAMETER;
4438 break;
4442 if (NT_STATUS_IS_OK(state->match_status)) {
4444 * Common case - just opening another handle on a
4445 * file on a non-dynamic share.
4447 return;
4450 if (NT_STATUS_EQUAL(state->match_status, NT_STATUS_INVALID_PARAMETER)) {
4451 /* Mismatched path. Error back to client. */
4452 return;
4456 * File id mismatch. Dynamic share case NT_STATUS_OPLOCK_NOT_GRANTED.
4457 * Don't allow leases.
4460 state->match_status = leases_db_copy_file_ids(state->mem_ctx,
4461 num_files,
4462 files,
4463 &state->ids);
4464 if (!NT_STATUS_IS_OK(state->match_status)) {
4465 return;
4468 state->num_file_ids = num_files;
4469 state->match_status = NT_STATUS_OPLOCK_NOT_GRANTED;
4470 return;
4473 static NTSTATUS lease_match(connection_struct *conn,
4474 struct smb_request *req,
4475 struct smb2_lease_key *lease_key,
4476 const char *servicepath,
4477 const struct smb_filename *fname,
4478 uint16_t *p_version,
4479 uint16_t *p_epoch)
4481 struct smbd_server_connection *sconn = req->sconn;
4482 TALLOC_CTX *tos = talloc_tos();
4483 struct lease_match_state state = {
4484 .mem_ctx = tos,
4485 .servicepath = servicepath,
4486 .fname = fname,
4487 .match_status = NT_STATUS_OK
4489 uint32_t i;
4490 NTSTATUS status;
4492 state.file_existed = VALID_STAT(fname->st);
4493 if (state.file_existed) {
4494 state.id = vfs_file_id_from_sbuf(conn, &fname->st);
4495 } else {
4496 memset(&state.id, '\0', sizeof(state.id));
4499 status = leases_db_parse(&sconn->client->connections->smb2.client.guid,
4500 lease_key, lease_match_parser, &state);
4501 if (!NT_STATUS_IS_OK(status)) {
4503 * Not found or error means okay: We can make the lease pass
4505 return NT_STATUS_OK;
4507 if (!NT_STATUS_EQUAL(state.match_status, NT_STATUS_OPLOCK_NOT_GRANTED)) {
4509 * Anything but NT_STATUS_OPLOCK_NOT_GRANTED, let the caller
4510 * deal with it.
4512 return state.match_status;
4515 /* We have to break all existing leases. */
4516 for (i = 0; i < state.num_file_ids; i++) {
4517 struct share_mode_lock *lck;
4518 struct share_mode_data *d;
4519 uint32_t j;
4521 if (file_id_equal(&state.ids[i], &state.id)) {
4522 /* Don't need to break our own file. */
4523 continue;
4526 lck = get_existing_share_mode_lock(talloc_tos(), state.ids[i]);
4527 if (lck == NULL) {
4528 /* Race condition - file already closed. */
4529 continue;
4531 d = lck->data;
4532 for (j=0; j<d->num_share_modes; j++) {
4533 struct share_mode_entry *e = &d->share_modes[j];
4534 uint32_t e_lease_type = get_lease_type(d, e);
4535 struct share_mode_lease *l = NULL;
4537 if (share_mode_stale_pid(d, j)) {
4538 continue;
4541 if (e->op_type == LEASE_OPLOCK) {
4542 l = &lck->data->leases[e->lease_idx];
4543 if (!smb2_lease_key_equal(&l->lease_key,
4544 lease_key)) {
4545 continue;
4547 *p_epoch = l->epoch;
4548 *p_version = l->lease_version;
4551 if (e_lease_type == SMB2_LEASE_NONE) {
4552 continue;
4555 send_break_message(conn->sconn->msg_ctx, e,
4556 SMB2_LEASE_NONE);
4559 * Windows 7 and 8 lease clients
4560 * are broken in that they will not
4561 * respond to lease break requests
4562 * whilst waiting for an outstanding
4563 * open request on that lease handle
4564 * on the same TCP connection, due
4565 * to holding an internal inode lock.
4567 * This means we can't reschedule
4568 * ourselves here, but must return
4569 * from the create.
4571 * Work around:
4573 * Send the breaks and then return
4574 * SMB2_LEASE_NONE in the lease handle
4575 * to cause them to acknowledge the
4576 * lease break. Consulatation with
4577 * Microsoft engineering confirmed
4578 * this approach is safe.
4582 TALLOC_FREE(lck);
4585 * Ensure we don't grant anything more so we
4586 * never upgrade.
4588 return NT_STATUS_OPLOCK_NOT_GRANTED;
4592 * Wrapper around open_file_ntcreate and open_directory
4595 static NTSTATUS create_file_unixpath(connection_struct *conn,
4596 struct smb_request *req,
4597 struct smb_filename *smb_fname,
4598 uint32_t access_mask,
4599 uint32_t share_access,
4600 uint32_t create_disposition,
4601 uint32_t create_options,
4602 uint32_t file_attributes,
4603 uint32_t oplock_request,
4604 struct smb2_lease *lease,
4605 uint64_t allocation_size,
4606 uint32_t private_flags,
4607 struct security_descriptor *sd,
4608 struct ea_list *ea_list,
4610 files_struct **result,
4611 int *pinfo)
4613 int info = FILE_WAS_OPENED;
4614 files_struct *base_fsp = NULL;
4615 files_struct *fsp = NULL;
4616 NTSTATUS status;
4618 DEBUG(10,("create_file_unixpath: access_mask = 0x%x "
4619 "file_attributes = 0x%x, share_access = 0x%x, "
4620 "create_disposition = 0x%x create_options = 0x%x "
4621 "oplock_request = 0x%x private_flags = 0x%x "
4622 "ea_list = 0x%p, sd = 0x%p, "
4623 "fname = %s\n",
4624 (unsigned int)access_mask,
4625 (unsigned int)file_attributes,
4626 (unsigned int)share_access,
4627 (unsigned int)create_disposition,
4628 (unsigned int)create_options,
4629 (unsigned int)oplock_request,
4630 (unsigned int)private_flags,
4631 ea_list, sd, smb_fname_str_dbg(smb_fname)));
4633 if (create_options & FILE_OPEN_BY_FILE_ID) {
4634 status = NT_STATUS_NOT_SUPPORTED;
4635 goto fail;
4638 if (create_options & NTCREATEX_OPTIONS_INVALID_PARAM_MASK) {
4639 status = NT_STATUS_INVALID_PARAMETER;
4640 goto fail;
4643 if (req == NULL) {
4644 oplock_request |= INTERNAL_OPEN_ONLY;
4647 if (lease != NULL) {
4648 uint16_t epoch = lease->lease_epoch;
4649 uint16_t version = lease->lease_version;
4650 status = lease_match(conn,
4651 req,
4652 &lease->lease_key,
4653 conn->connectpath,
4654 smb_fname,
4655 &version,
4656 &epoch);
4657 if (NT_STATUS_EQUAL(status, NT_STATUS_OPLOCK_NOT_GRANTED)) {
4658 /* Dynamic share file. No leases and update epoch... */
4659 lease->lease_state = SMB2_LEASE_NONE;
4660 lease->lease_epoch = epoch;
4661 lease->lease_version = version;
4662 } else if (!NT_STATUS_IS_OK(status)) {
4663 goto fail;
4667 if ((conn->fs_capabilities & FILE_NAMED_STREAMS)
4668 && (access_mask & DELETE_ACCESS)
4669 && !is_ntfs_stream_smb_fname(smb_fname)) {
4671 * We can't open a file with DELETE access if any of the
4672 * streams is open without FILE_SHARE_DELETE
4674 status = open_streams_for_delete(conn, smb_fname);
4676 if (!NT_STATUS_IS_OK(status)) {
4677 goto fail;
4681 if ((access_mask & SEC_FLAG_SYSTEM_SECURITY) &&
4682 !security_token_has_privilege(get_current_nttok(conn),
4683 SEC_PRIV_SECURITY)) {
4684 DEBUG(10, ("create_file_unixpath: open on %s "
4685 "failed - SEC_FLAG_SYSTEM_SECURITY denied.\n",
4686 smb_fname_str_dbg(smb_fname)));
4687 status = NT_STATUS_PRIVILEGE_NOT_HELD;
4688 goto fail;
4691 if ((conn->fs_capabilities & FILE_NAMED_STREAMS)
4692 && is_ntfs_stream_smb_fname(smb_fname)
4693 && (!(private_flags & NTCREATEX_OPTIONS_PRIVATE_STREAM_DELETE))) {
4694 uint32_t base_create_disposition;
4695 struct smb_filename *smb_fname_base = NULL;
4697 if (create_options & FILE_DIRECTORY_FILE) {
4698 status = NT_STATUS_NOT_A_DIRECTORY;
4699 goto fail;
4702 switch (create_disposition) {
4703 case FILE_OPEN:
4704 base_create_disposition = FILE_OPEN;
4705 break;
4706 default:
4707 base_create_disposition = FILE_OPEN_IF;
4708 break;
4711 /* Create an smb_filename with stream_name == NULL. */
4712 smb_fname_base = synthetic_smb_fname(talloc_tos(),
4713 smb_fname->base_name,
4714 NULL,
4715 NULL,
4716 smb_fname->flags);
4717 if (smb_fname_base == NULL) {
4718 status = NT_STATUS_NO_MEMORY;
4719 goto fail;
4722 if (SMB_VFS_STAT(conn, smb_fname_base) == -1) {
4723 DEBUG(10, ("Unable to stat stream: %s\n",
4724 smb_fname_str_dbg(smb_fname_base)));
4725 } else {
4727 * https://bugzilla.samba.org/show_bug.cgi?id=10229
4728 * We need to check if the requested access mask
4729 * could be used to open the underlying file (if
4730 * it existed), as we're passing in zero for the
4731 * access mask to the base filename.
4733 status = check_base_file_access(conn,
4734 smb_fname_base,
4735 access_mask);
4737 if (!NT_STATUS_IS_OK(status)) {
4738 DEBUG(10, ("Permission check "
4739 "for base %s failed: "
4740 "%s\n", smb_fname->base_name,
4741 nt_errstr(status)));
4742 goto fail;
4746 /* Open the base file. */
4747 status = create_file_unixpath(conn, NULL, smb_fname_base, 0,
4748 FILE_SHARE_READ
4749 | FILE_SHARE_WRITE
4750 | FILE_SHARE_DELETE,
4751 base_create_disposition,
4752 0, 0, 0, NULL, 0, 0, NULL, NULL,
4753 &base_fsp, NULL);
4754 TALLOC_FREE(smb_fname_base);
4756 if (!NT_STATUS_IS_OK(status)) {
4757 DEBUG(10, ("create_file_unixpath for base %s failed: "
4758 "%s\n", smb_fname->base_name,
4759 nt_errstr(status)));
4760 goto fail;
4762 /* we don't need the low level fd */
4763 fd_close(base_fsp);
4767 * If it's a request for a directory open, deal with it separately.
4770 if (create_options & FILE_DIRECTORY_FILE) {
4772 if (create_options & FILE_NON_DIRECTORY_FILE) {
4773 status = NT_STATUS_INVALID_PARAMETER;
4774 goto fail;
4777 /* Can't open a temp directory. IFS kit test. */
4778 if (!(file_attributes & FILE_FLAG_POSIX_SEMANTICS) &&
4779 (file_attributes & FILE_ATTRIBUTE_TEMPORARY)) {
4780 status = NT_STATUS_INVALID_PARAMETER;
4781 goto fail;
4785 * We will get a create directory here if the Win32
4786 * app specified a security descriptor in the
4787 * CreateDirectory() call.
4790 oplock_request = 0;
4791 status = open_directory(
4792 conn, req, smb_fname, access_mask, share_access,
4793 create_disposition, create_options, file_attributes,
4794 &info, &fsp);
4795 } else {
4798 * Ordinary file case.
4801 status = file_new(req, conn, &fsp);
4802 if(!NT_STATUS_IS_OK(status)) {
4803 goto fail;
4806 status = fsp_set_smb_fname(fsp, smb_fname);
4807 if (!NT_STATUS_IS_OK(status)) {
4808 goto fail;
4811 if (base_fsp) {
4813 * We're opening the stream element of a
4814 * base_fsp we already opened. Set up the
4815 * base_fsp pointer.
4817 fsp->base_fsp = base_fsp;
4820 if (allocation_size) {
4821 fsp->initial_allocation_size = smb_roundup(fsp->conn,
4822 allocation_size);
4825 status = open_file_ntcreate(conn,
4826 req,
4827 access_mask,
4828 share_access,
4829 create_disposition,
4830 create_options,
4831 file_attributes,
4832 oplock_request,
4833 lease,
4834 private_flags,
4835 &info,
4836 fsp);
4838 if(!NT_STATUS_IS_OK(status)) {
4839 file_free(req, fsp);
4840 fsp = NULL;
4843 if (NT_STATUS_EQUAL(status, NT_STATUS_FILE_IS_A_DIRECTORY)) {
4845 /* A stream open never opens a directory */
4847 if (base_fsp) {
4848 status = NT_STATUS_FILE_IS_A_DIRECTORY;
4849 goto fail;
4853 * Fail the open if it was explicitly a non-directory
4854 * file.
4857 if (create_options & FILE_NON_DIRECTORY_FILE) {
4858 status = NT_STATUS_FILE_IS_A_DIRECTORY;
4859 goto fail;
4862 oplock_request = 0;
4863 status = open_directory(
4864 conn, req, smb_fname, access_mask,
4865 share_access, create_disposition,
4866 create_options, file_attributes,
4867 &info, &fsp);
4871 if (!NT_STATUS_IS_OK(status)) {
4872 goto fail;
4875 fsp->base_fsp = base_fsp;
4877 if ((ea_list != NULL) &&
4878 ((info == FILE_WAS_CREATED) || (info == FILE_WAS_OVERWRITTEN))) {
4879 status = set_ea(conn, fsp, fsp->fsp_name, ea_list);
4880 if (!NT_STATUS_IS_OK(status)) {
4881 goto fail;
4885 if (!fsp->is_directory && S_ISDIR(fsp->fsp_name->st.st_ex_mode)) {
4886 status = NT_STATUS_ACCESS_DENIED;
4887 goto fail;
4890 /* Save the requested allocation size. */
4891 if ((info == FILE_WAS_CREATED) || (info == FILE_WAS_OVERWRITTEN)) {
4892 if ((allocation_size > fsp->fsp_name->st.st_ex_size)
4893 && !(fsp->is_directory))
4895 fsp->initial_allocation_size = smb_roundup(
4896 fsp->conn, allocation_size);
4897 if (vfs_allocate_file_space(
4898 fsp, fsp->initial_allocation_size) == -1) {
4899 status = NT_STATUS_DISK_FULL;
4900 goto fail;
4902 } else {
4903 fsp->initial_allocation_size = smb_roundup(
4904 fsp->conn, (uint64_t)fsp->fsp_name->st.st_ex_size);
4906 } else {
4907 fsp->initial_allocation_size = 0;
4910 if ((info == FILE_WAS_CREATED) && lp_nt_acl_support(SNUM(conn)) &&
4911 fsp->base_fsp == NULL) {
4912 if (sd != NULL) {
4914 * According to the MS documentation, the only time the security
4915 * descriptor is applied to the opened file is iff we *created* the
4916 * file; an existing file stays the same.
4918 * Also, it seems (from observation) that you can open the file with
4919 * any access mask but you can still write the sd. We need to override
4920 * the granted access before we call set_sd
4921 * Patch for bug #2242 from Tom Lackemann <cessnatomny@yahoo.com>.
4924 uint32_t sec_info_sent;
4925 uint32_t saved_access_mask = fsp->access_mask;
4927 sec_info_sent = get_sec_info(sd);
4929 fsp->access_mask = FILE_GENERIC_ALL;
4931 if (sec_info_sent & (SECINFO_OWNER|
4932 SECINFO_GROUP|
4933 SECINFO_DACL|
4934 SECINFO_SACL)) {
4935 status = set_sd(fsp, sd, sec_info_sent);
4938 fsp->access_mask = saved_access_mask;
4940 if (!NT_STATUS_IS_OK(status)) {
4941 goto fail;
4943 } else if (lp_inherit_acls(SNUM(conn))) {
4944 /* Inherit from parent. Errors here are not fatal. */
4945 status = inherit_new_acl(fsp);
4946 if (!NT_STATUS_IS_OK(status)) {
4947 DEBUG(10,("inherit_new_acl: failed for %s with %s\n",
4948 fsp_str_dbg(fsp),
4949 nt_errstr(status) ));
4954 if ((conn->fs_capabilities & FILE_FILE_COMPRESSION)
4955 && (create_options & FILE_NO_COMPRESSION)
4956 && (info == FILE_WAS_CREATED)) {
4957 status = SMB_VFS_SET_COMPRESSION(conn, fsp, fsp,
4958 COMPRESSION_FORMAT_NONE);
4959 if (!NT_STATUS_IS_OK(status)) {
4960 DEBUG(1, ("failed to disable compression: %s\n",
4961 nt_errstr(status)));
4965 DEBUG(10, ("create_file_unixpath: info=%d\n", info));
4967 *result = fsp;
4968 if (pinfo != NULL) {
4969 *pinfo = info;
4972 smb_fname->st = fsp->fsp_name->st;
4974 return NT_STATUS_OK;
4976 fail:
4977 DEBUG(10, ("create_file_unixpath: %s\n", nt_errstr(status)));
4979 if (fsp != NULL) {
4980 if (base_fsp && fsp->base_fsp == base_fsp) {
4982 * The close_file below will close
4983 * fsp->base_fsp.
4985 base_fsp = NULL;
4987 close_file(req, fsp, ERROR_CLOSE);
4988 fsp = NULL;
4990 if (base_fsp != NULL) {
4991 close_file(req, base_fsp, ERROR_CLOSE);
4992 base_fsp = NULL;
4994 return status;
4998 * Calculate the full path name given a relative fid.
5000 NTSTATUS get_relative_fid_filename(connection_struct *conn,
5001 struct smb_request *req,
5002 uint16_t root_dir_fid,
5003 const struct smb_filename *smb_fname,
5004 struct smb_filename **smb_fname_out)
5006 files_struct *dir_fsp;
5007 char *parent_fname = NULL;
5008 char *new_base_name = NULL;
5009 uint32_t ucf_flags = ((req != NULL && req->posix_pathnames) ?
5010 UCF_POSIX_PATHNAMES : 0);
5011 NTSTATUS status;
5013 if (root_dir_fid == 0 || !smb_fname) {
5014 status = NT_STATUS_INTERNAL_ERROR;
5015 goto out;
5018 dir_fsp = file_fsp(req, root_dir_fid);
5020 if (dir_fsp == NULL) {
5021 status = NT_STATUS_INVALID_HANDLE;
5022 goto out;
5025 if (is_ntfs_stream_smb_fname(dir_fsp->fsp_name)) {
5026 status = NT_STATUS_INVALID_HANDLE;
5027 goto out;
5030 if (!dir_fsp->is_directory) {
5033 * Check to see if this is a mac fork of some kind.
5036 if ((conn->fs_capabilities & FILE_NAMED_STREAMS) &&
5037 is_ntfs_stream_smb_fname(smb_fname)) {
5038 status = NT_STATUS_OBJECT_PATH_NOT_FOUND;
5039 goto out;
5043 we need to handle the case when we get a
5044 relative open relative to a file and the
5045 pathname is blank - this is a reopen!
5046 (hint from demyn plantenberg)
5049 status = NT_STATUS_INVALID_HANDLE;
5050 goto out;
5053 if (ISDOT(dir_fsp->fsp_name->base_name)) {
5055 * We're at the toplevel dir, the final file name
5056 * must not contain ./, as this is filtered out
5057 * normally by srvstr_get_path and unix_convert
5058 * explicitly rejects paths containing ./.
5060 parent_fname = talloc_strdup(talloc_tos(), "");
5061 if (parent_fname == NULL) {
5062 status = NT_STATUS_NO_MEMORY;
5063 goto out;
5065 } else {
5066 size_t dir_name_len = strlen(dir_fsp->fsp_name->base_name);
5069 * Copy in the base directory name.
5072 parent_fname = talloc_array(talloc_tos(), char,
5073 dir_name_len+2);
5074 if (parent_fname == NULL) {
5075 status = NT_STATUS_NO_MEMORY;
5076 goto out;
5078 memcpy(parent_fname, dir_fsp->fsp_name->base_name,
5079 dir_name_len+1);
5082 * Ensure it ends in a '/'.
5083 * We used TALLOC_SIZE +2 to add space for the '/'.
5086 if(dir_name_len
5087 && (parent_fname[dir_name_len-1] != '\\')
5088 && (parent_fname[dir_name_len-1] != '/')) {
5089 parent_fname[dir_name_len] = '/';
5090 parent_fname[dir_name_len+1] = '\0';
5094 new_base_name = talloc_asprintf(talloc_tos(), "%s%s", parent_fname,
5095 smb_fname->base_name);
5096 if (new_base_name == NULL) {
5097 status = NT_STATUS_NO_MEMORY;
5098 goto out;
5101 status = filename_convert(req,
5102 conn,
5103 req->flags2 & FLAGS2_DFS_PATHNAMES,
5104 new_base_name,
5105 ucf_flags,
5106 NULL,
5107 smb_fname_out);
5108 if (!NT_STATUS_IS_OK(status)) {
5109 goto out;
5112 out:
5113 TALLOC_FREE(parent_fname);
5114 TALLOC_FREE(new_base_name);
5115 return status;
5118 NTSTATUS create_file_default(connection_struct *conn,
5119 struct smb_request *req,
5120 uint16_t root_dir_fid,
5121 struct smb_filename *smb_fname,
5122 uint32_t access_mask,
5123 uint32_t share_access,
5124 uint32_t create_disposition,
5125 uint32_t create_options,
5126 uint32_t file_attributes,
5127 uint32_t oplock_request,
5128 struct smb2_lease *lease,
5129 uint64_t allocation_size,
5130 uint32_t private_flags,
5131 struct security_descriptor *sd,
5132 struct ea_list *ea_list,
5133 files_struct **result,
5134 int *pinfo,
5135 const struct smb2_create_blobs *in_context_blobs,
5136 struct smb2_create_blobs *out_context_blobs)
5138 int info = FILE_WAS_OPENED;
5139 files_struct *fsp = NULL;
5140 NTSTATUS status;
5141 bool stream_name = false;
5143 DEBUG(10,("create_file: access_mask = 0x%x "
5144 "file_attributes = 0x%x, share_access = 0x%x, "
5145 "create_disposition = 0x%x create_options = 0x%x "
5146 "oplock_request = 0x%x "
5147 "private_flags = 0x%x "
5148 "root_dir_fid = 0x%x, ea_list = 0x%p, sd = 0x%p, "
5149 "fname = %s\n",
5150 (unsigned int)access_mask,
5151 (unsigned int)file_attributes,
5152 (unsigned int)share_access,
5153 (unsigned int)create_disposition,
5154 (unsigned int)create_options,
5155 (unsigned int)oplock_request,
5156 (unsigned int)private_flags,
5157 (unsigned int)root_dir_fid,
5158 ea_list, sd, smb_fname_str_dbg(smb_fname)));
5161 * Calculate the filename from the root_dir_if if necessary.
5164 if (root_dir_fid != 0) {
5165 struct smb_filename *smb_fname_out = NULL;
5166 status = get_relative_fid_filename(conn, req, root_dir_fid,
5167 smb_fname, &smb_fname_out);
5168 if (!NT_STATUS_IS_OK(status)) {
5169 goto fail;
5171 smb_fname = smb_fname_out;
5175 * Check to see if this is a mac fork of some kind.
5178 stream_name = is_ntfs_stream_smb_fname(smb_fname);
5179 if (stream_name) {
5180 enum FAKE_FILE_TYPE fake_file_type;
5182 fake_file_type = is_fake_file(smb_fname);
5184 if (fake_file_type != FAKE_FILE_TYPE_NONE) {
5187 * Here we go! support for changing the disk quotas
5188 * --metze
5190 * We need to fake up to open this MAGIC QUOTA file
5191 * and return a valid FID.
5193 * w2k close this file directly after openening xp
5194 * also tries a QUERY_FILE_INFO on the file and then
5195 * close it
5197 status = open_fake_file(req, conn, req->vuid,
5198 fake_file_type, smb_fname,
5199 access_mask, &fsp);
5200 if (!NT_STATUS_IS_OK(status)) {
5201 goto fail;
5204 ZERO_STRUCT(smb_fname->st);
5205 goto done;
5208 if (!(conn->fs_capabilities & FILE_NAMED_STREAMS)) {
5209 status = NT_STATUS_OBJECT_NAME_NOT_FOUND;
5210 goto fail;
5214 if (is_ntfs_default_stream_smb_fname(smb_fname)) {
5215 int ret;
5216 smb_fname->stream_name = NULL;
5217 /* We have to handle this error here. */
5218 if (create_options & FILE_DIRECTORY_FILE) {
5219 status = NT_STATUS_NOT_A_DIRECTORY;
5220 goto fail;
5222 if (req != NULL && req->posix_pathnames) {
5223 ret = SMB_VFS_LSTAT(conn, smb_fname);
5224 } else {
5225 ret = SMB_VFS_STAT(conn, smb_fname);
5228 if (ret == 0 && VALID_STAT_OF_DIR(smb_fname->st)) {
5229 status = NT_STATUS_FILE_IS_A_DIRECTORY;
5230 goto fail;
5234 status = create_file_unixpath(
5235 conn, req, smb_fname, access_mask, share_access,
5236 create_disposition, create_options, file_attributes,
5237 oplock_request, lease, allocation_size, private_flags,
5238 sd, ea_list,
5239 &fsp, &info);
5241 if (!NT_STATUS_IS_OK(status)) {
5242 goto fail;
5245 done:
5246 DEBUG(10, ("create_file: info=%d\n", info));
5248 *result = fsp;
5249 if (pinfo != NULL) {
5250 *pinfo = info;
5252 return NT_STATUS_OK;
5254 fail:
5255 DEBUG(10, ("create_file: %s\n", nt_errstr(status)));
5257 if (fsp != NULL) {
5258 close_file(req, fsp, ERROR_CLOSE);
5259 fsp = NULL;
5261 return status;