s3: libsmb: Do some hardening in the receive processing of cli_shadow_copy_data_recv().
[Samba.git] / source3 / smbd / open.c
blob2ae6f835bbcde2fd52efd2754616f9cdf389aaf2
1 /*
2 Unix SMB/CIFS implementation.
3 file opening and share modes
4 Copyright (C) Andrew Tridgell 1992-1998
5 Copyright (C) Jeremy Allison 2001-2004
6 Copyright (C) Volker Lendecke 2005
8 This program is free software; you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation; either version 3 of the License, or
11 (at your option) any later version.
13 This program is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with this program. If not, see <http://www.gnu.org/licenses/>.
22 #include "includes.h"
23 #include "system/filesys.h"
24 #include "printing.h"
25 #include "smbd/smbd.h"
26 #include "smbd/globals.h"
27 #include "fake_file.h"
28 #include "../libcli/security/security.h"
29 #include "../librpc/gen_ndr/ndr_security.h"
30 #include "../librpc/gen_ndr/open_files.h"
31 #include "../librpc/gen_ndr/idmap.h"
32 #include "../librpc/gen_ndr/ioctl.h"
33 #include "passdb/lookup_sid.h"
34 #include "auth.h"
35 #include "serverid.h"
36 #include "messages.h"
37 #include "source3/lib/dbwrap/dbwrap_watch.h"
38 #include "locking/leases_db.h"
39 #include "librpc/gen_ndr/ndr_leases_db.h"
41 extern const struct generic_mapping file_generic_mapping;
43 struct deferred_open_record {
44 bool delayed_for_oplocks;
45 bool async_open;
46 struct file_id id;
49 /****************************************************************************
50 If the requester wanted DELETE_ACCESS and was rejected because
51 the file ACL didn't include DELETE_ACCESS, see if the parent ACL
52 overrides this.
53 ****************************************************************************/
55 static bool parent_override_delete(connection_struct *conn,
56 const struct smb_filename *smb_fname,
57 uint32_t access_mask,
58 uint32_t rejected_mask)
60 if ((access_mask & DELETE_ACCESS) &&
61 (rejected_mask & DELETE_ACCESS) &&
62 can_delete_file_in_directory(conn, smb_fname)) {
63 return true;
65 return false;
68 /****************************************************************************
69 Check if we have open rights.
70 ****************************************************************************/
72 NTSTATUS smbd_check_access_rights(struct connection_struct *conn,
73 const struct smb_filename *smb_fname,
74 bool use_privs,
75 uint32_t access_mask)
77 /* Check if we have rights to open. */
78 NTSTATUS status;
79 struct security_descriptor *sd = NULL;
80 uint32_t rejected_share_access;
81 uint32_t rejected_mask = access_mask;
82 uint32_t do_not_check_mask = 0;
84 rejected_share_access = access_mask & ~(conn->share_access);
86 if (rejected_share_access) {
87 DEBUG(10, ("smbd_check_access_rights: rejected share access 0x%x "
88 "on %s (0x%x)\n",
89 (unsigned int)access_mask,
90 smb_fname_str_dbg(smb_fname),
91 (unsigned int)rejected_share_access ));
92 return NT_STATUS_ACCESS_DENIED;
95 if (!use_privs && get_current_uid(conn) == (uid_t)0) {
96 /* I'm sorry sir, I didn't know you were root... */
97 DEBUG(10,("smbd_check_access_rights: root override "
98 "on %s. Granting 0x%x\n",
99 smb_fname_str_dbg(smb_fname),
100 (unsigned int)access_mask ));
101 return NT_STATUS_OK;
104 if ((access_mask & DELETE_ACCESS) && !lp_acl_check_permissions(SNUM(conn))) {
105 DEBUG(10,("smbd_check_access_rights: not checking ACL "
106 "on DELETE_ACCESS on file %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 &&
113 VALID_STAT(smb_fname->st) &&
114 S_ISLNK(smb_fname->st.st_ex_mode)) {
115 /* We can always delete a symlink. */
116 DEBUG(10,("smbd_check_access_rights: not checking ACL "
117 "on DELETE_ACCESS on symlink %s.\n",
118 smb_fname_str_dbg(smb_fname) ));
119 return NT_STATUS_OK;
122 status = SMB_VFS_GET_NT_ACL(conn, smb_fname,
123 (SECINFO_OWNER |
124 SECINFO_GROUP |
125 SECINFO_DACL), talloc_tos(), &sd);
127 if (!NT_STATUS_IS_OK(status)) {
128 DEBUG(10, ("smbd_check_access_rights: Could not get acl "
129 "on %s: %s\n",
130 smb_fname_str_dbg(smb_fname),
131 nt_errstr(status)));
133 if (NT_STATUS_EQUAL(status, NT_STATUS_ACCESS_DENIED)) {
134 goto access_denied;
137 return status;
141 * If we can access the path to this file, by
142 * default we have FILE_READ_ATTRIBUTES from the
143 * containing directory. See the section:
144 * "Algorithm to Check Access to an Existing File"
145 * in MS-FSA.pdf.
147 * se_file_access_check() also takes care of
148 * owner WRITE_DAC and READ_CONTROL.
150 do_not_check_mask = FILE_READ_ATTRIBUTES;
153 * Samba 3.6 and earlier granted execute access even
154 * if the ACL did not contain execute rights.
155 * Samba 4.0 is more correct and checks it.
156 * The compatibilty mode allows one to skip this check
157 * to smoothen upgrades.
159 if (lp_acl_allow_execute_always(SNUM(conn))) {
160 do_not_check_mask |= FILE_EXECUTE;
163 status = se_file_access_check(sd,
164 get_current_nttok(conn),
165 use_privs,
166 (access_mask & ~do_not_check_mask),
167 &rejected_mask);
169 DEBUG(10,("smbd_check_access_rights: file %s requesting "
170 "0x%x returning 0x%x (%s)\n",
171 smb_fname_str_dbg(smb_fname),
172 (unsigned int)access_mask,
173 (unsigned int)rejected_mask,
174 nt_errstr(status) ));
176 if (!NT_STATUS_IS_OK(status)) {
177 if (DEBUGLEVEL >= 10) {
178 DEBUG(10,("smbd_check_access_rights: acl for %s is:\n",
179 smb_fname_str_dbg(smb_fname) ));
180 NDR_PRINT_DEBUG(security_descriptor, sd);
184 TALLOC_FREE(sd);
186 if (NT_STATUS_IS_OK(status) ||
187 !NT_STATUS_EQUAL(status, NT_STATUS_ACCESS_DENIED)) {
188 return status;
191 /* Here we know status == NT_STATUS_ACCESS_DENIED. */
193 access_denied:
195 if ((access_mask & FILE_WRITE_ATTRIBUTES) &&
196 (rejected_mask & FILE_WRITE_ATTRIBUTES) &&
197 !lp_store_dos_attributes(SNUM(conn)) &&
198 (lp_map_readonly(SNUM(conn)) ||
199 lp_map_archive(SNUM(conn)) ||
200 lp_map_hidden(SNUM(conn)) ||
201 lp_map_system(SNUM(conn)))) {
202 rejected_mask &= ~FILE_WRITE_ATTRIBUTES;
204 DEBUG(10,("smbd_check_access_rights: "
205 "overrode "
206 "FILE_WRITE_ATTRIBUTES "
207 "on file %s\n",
208 smb_fname_str_dbg(smb_fname)));
211 if (parent_override_delete(conn,
212 smb_fname,
213 access_mask,
214 rejected_mask)) {
215 /* Were we trying to do an open
216 * for delete and didn't get DELETE
217 * access (only) ? Check if the
218 * directory allows DELETE_CHILD.
219 * See here:
220 * http://blogs.msdn.com/oldnewthing/archive/2004/06/04/148426.aspx
221 * for details. */
223 rejected_mask &= ~DELETE_ACCESS;
225 DEBUG(10,("smbd_check_access_rights: "
226 "overrode "
227 "DELETE_ACCESS on "
228 "file %s\n",
229 smb_fname_str_dbg(smb_fname)));
232 if (rejected_mask != 0) {
233 return NT_STATUS_ACCESS_DENIED;
235 return NT_STATUS_OK;
238 static NTSTATUS check_parent_access(struct connection_struct *conn,
239 struct smb_filename *smb_fname,
240 uint32_t access_mask)
242 NTSTATUS status;
243 char *parent_dir = NULL;
244 struct security_descriptor *parent_sd = NULL;
245 uint32_t access_granted = 0;
246 struct smb_filename *parent_smb_fname = NULL;
248 if (!parent_dirname(talloc_tos(),
249 smb_fname->base_name,
250 &parent_dir,
251 NULL)) {
252 return NT_STATUS_NO_MEMORY;
255 parent_smb_fname = synthetic_smb_fname(talloc_tos(),
256 parent_dir,
257 NULL,
258 NULL,
259 smb_fname->flags);
260 if (parent_smb_fname == NULL) {
261 return NT_STATUS_NO_MEMORY;
264 if (get_current_uid(conn) == (uid_t)0) {
265 /* I'm sorry sir, I didn't know you were root... */
266 DEBUG(10,("check_parent_access: root override "
267 "on %s. Granting 0x%x\n",
268 smb_fname_str_dbg(smb_fname),
269 (unsigned int)access_mask ));
270 return NT_STATUS_OK;
273 status = SMB_VFS_GET_NT_ACL(conn,
274 parent_smb_fname,
275 SECINFO_DACL,
276 talloc_tos(),
277 &parent_sd);
279 if (!NT_STATUS_IS_OK(status)) {
280 DEBUG(5,("check_parent_access: SMB_VFS_GET_NT_ACL failed for "
281 "%s with error %s\n",
282 parent_dir,
283 nt_errstr(status)));
284 return status;
288 * If we can access the path to this file, by
289 * default we have FILE_READ_ATTRIBUTES from the
290 * containing directory. See the section:
291 * "Algorithm to Check Access to an Existing File"
292 * in MS-FSA.pdf.
294 * se_file_access_check() also takes care of
295 * owner WRITE_DAC and READ_CONTROL.
297 status = se_file_access_check(parent_sd,
298 get_current_nttok(conn),
299 false,
300 (access_mask & ~FILE_READ_ATTRIBUTES),
301 &access_granted);
302 if(!NT_STATUS_IS_OK(status)) {
303 DEBUG(5,("check_parent_access: access check "
304 "on directory %s for "
305 "path %s for mask 0x%x returned (0x%x) %s\n",
306 parent_dir,
307 smb_fname->base_name,
308 access_mask,
309 access_granted,
310 nt_errstr(status) ));
311 return status;
314 return NT_STATUS_OK;
317 /****************************************************************************
318 Ensure when opening a base file for a stream open that we have permissions
319 to do so given the access mask on the base file.
320 ****************************************************************************/
322 static NTSTATUS check_base_file_access(struct connection_struct *conn,
323 struct smb_filename *smb_fname,
324 uint32_t access_mask)
326 NTSTATUS status;
328 status = smbd_calculate_access_mask(conn, smb_fname,
329 false,
330 access_mask,
331 &access_mask);
332 if (!NT_STATUS_IS_OK(status)) {
333 DEBUG(10, ("smbd_calculate_access_mask "
334 "on file %s returned %s\n",
335 smb_fname_str_dbg(smb_fname),
336 nt_errstr(status)));
337 return status;
340 if (access_mask & (FILE_WRITE_DATA|FILE_APPEND_DATA)) {
341 uint32_t dosattrs;
342 if (!CAN_WRITE(conn)) {
343 return NT_STATUS_ACCESS_DENIED;
345 dosattrs = dos_mode(conn, smb_fname);
346 if (IS_DOS_READONLY(dosattrs)) {
347 return NT_STATUS_ACCESS_DENIED;
351 return smbd_check_access_rights(conn,
352 smb_fname,
353 false,
354 access_mask);
357 /****************************************************************************
358 fd support routines - attempt to do a dos_open.
359 ****************************************************************************/
361 NTSTATUS fd_open(struct connection_struct *conn,
362 files_struct *fsp,
363 int flags,
364 mode_t mode)
366 struct smb_filename *smb_fname = fsp->fsp_name;
367 NTSTATUS status = NT_STATUS_OK;
369 #ifdef O_NOFOLLOW
371 * Never follow symlinks on a POSIX client. The
372 * client should be doing this.
375 if ((fsp->posix_flags & FSP_POSIX_FLAGS_OPEN) || !lp_follow_symlinks(SNUM(conn))) {
376 flags |= O_NOFOLLOW;
378 #endif
380 fsp->fh->fd = SMB_VFS_OPEN(conn, smb_fname, fsp, flags, mode);
381 if (fsp->fh->fd == -1) {
382 int posix_errno = errno;
383 #ifdef O_NOFOLLOW
384 #if defined(ENOTSUP) && defined(OSF1)
385 /* handle special Tru64 errno */
386 if (errno == ENOTSUP) {
387 posix_errno = ELOOP;
389 #endif /* ENOTSUP */
390 #ifdef EFTYPE
391 /* fix broken NetBSD errno */
392 if (errno == EFTYPE) {
393 posix_errno = ELOOP;
395 #endif /* EFTYPE */
396 /* fix broken FreeBSD errno */
397 if (errno == EMLINK) {
398 posix_errno = ELOOP;
400 #endif /* O_NOFOLLOW */
401 status = map_nt_error_from_unix(posix_errno);
402 if (errno == EMFILE) {
403 static time_t last_warned = 0L;
405 if (time((time_t *) NULL) > last_warned) {
406 DEBUG(0,("Too many open files, unable "
407 "to open more! smbd's max "
408 "open files = %d\n",
409 lp_max_open_files()));
410 last_warned = time((time_t *) NULL);
416 DEBUG(10,("fd_open: name %s, flags = 0%o mode = 0%o, fd = %d. %s\n",
417 smb_fname_str_dbg(smb_fname), flags, (int)mode, fsp->fh->fd,
418 (fsp->fh->fd == -1) ? strerror(errno) : "" ));
420 return status;
423 /****************************************************************************
424 Close the file associated with a fsp.
425 ****************************************************************************/
427 NTSTATUS fd_close(files_struct *fsp)
429 int ret;
431 if (fsp->dptr) {
432 dptr_CloseDir(fsp);
434 if (fsp->fh->fd == -1) {
435 return NT_STATUS_OK; /* What we used to call a stat open. */
437 if (fsp->fh->ref_count > 1) {
438 return NT_STATUS_OK; /* Shared handle. Only close last reference. */
441 ret = SMB_VFS_CLOSE(fsp);
442 fsp->fh->fd = -1;
443 if (ret == -1) {
444 return map_nt_error_from_unix(errno);
446 return NT_STATUS_OK;
449 /****************************************************************************
450 Change the ownership of a file to that of the parent directory.
451 Do this by fd if possible.
452 ****************************************************************************/
454 void change_file_owner_to_parent(connection_struct *conn,
455 const char *inherit_from_dir,
456 files_struct *fsp)
458 struct smb_filename *smb_fname_parent;
459 int ret;
461 smb_fname_parent = synthetic_smb_fname(talloc_tos(),
462 inherit_from_dir,
463 NULL,
464 NULL,
466 if (smb_fname_parent == NULL) {
467 return;
470 ret = SMB_VFS_STAT(conn, smb_fname_parent);
471 if (ret == -1) {
472 DEBUG(0,("change_file_owner_to_parent: failed to stat parent "
473 "directory %s. Error was %s\n",
474 smb_fname_str_dbg(smb_fname_parent),
475 strerror(errno)));
476 TALLOC_FREE(smb_fname_parent);
477 return;
480 if (smb_fname_parent->st.st_ex_uid == fsp->fsp_name->st.st_ex_uid) {
481 /* Already this uid - no need to change. */
482 DEBUG(10,("change_file_owner_to_parent: file %s "
483 "is already owned by uid %d\n",
484 fsp_str_dbg(fsp),
485 (int)fsp->fsp_name->st.st_ex_uid ));
486 TALLOC_FREE(smb_fname_parent);
487 return;
490 become_root();
491 ret = SMB_VFS_FCHOWN(fsp, smb_fname_parent->st.st_ex_uid, (gid_t)-1);
492 unbecome_root();
493 if (ret == -1) {
494 DEBUG(0,("change_file_owner_to_parent: failed to fchown "
495 "file %s to parent directory uid %u. Error "
496 "was %s\n", fsp_str_dbg(fsp),
497 (unsigned int)smb_fname_parent->st.st_ex_uid,
498 strerror(errno) ));
499 } else {
500 DEBUG(10,("change_file_owner_to_parent: changed new file %s to "
501 "parent directory uid %u.\n", fsp_str_dbg(fsp),
502 (unsigned int)smb_fname_parent->st.st_ex_uid));
503 /* Ensure the uid entry is updated. */
504 fsp->fsp_name->st.st_ex_uid = smb_fname_parent->st.st_ex_uid;
507 TALLOC_FREE(smb_fname_parent);
510 NTSTATUS change_dir_owner_to_parent(connection_struct *conn,
511 const char *inherit_from_dir,
512 const char *fname,
513 SMB_STRUCT_STAT *psbuf)
515 struct smb_filename *smb_fname_parent;
516 struct smb_filename *smb_fname_cwd = NULL;
517 char *saved_dir = NULL;
518 TALLOC_CTX *ctx = talloc_tos();
519 NTSTATUS status = NT_STATUS_OK;
520 int ret;
522 smb_fname_parent = synthetic_smb_fname(ctx,
523 inherit_from_dir,
524 NULL,
525 NULL,
527 if (smb_fname_parent == NULL) {
528 return NT_STATUS_NO_MEMORY;
531 ret = SMB_VFS_STAT(conn, smb_fname_parent);
532 if (ret == -1) {
533 status = map_nt_error_from_unix(errno);
534 DEBUG(0,("change_dir_owner_to_parent: failed to stat parent "
535 "directory %s. Error was %s\n",
536 smb_fname_str_dbg(smb_fname_parent),
537 strerror(errno)));
538 goto out;
541 /* We've already done an lstat into psbuf, and we know it's a
542 directory. If we can cd into the directory and the dev/ino
543 are the same then we can safely chown without races as
544 we're locking the directory in place by being in it. This
545 should work on any UNIX (thanks tridge :-). JRA.
548 saved_dir = vfs_GetWd(ctx,conn);
549 if (!saved_dir) {
550 status = map_nt_error_from_unix(errno);
551 DEBUG(0,("change_dir_owner_to_parent: failed to get "
552 "current working directory. Error was %s\n",
553 strerror(errno)));
554 goto out;
557 /* Chdir into the new path. */
558 if (vfs_ChDir(conn, fname) == -1) {
559 status = map_nt_error_from_unix(errno);
560 DEBUG(0,("change_dir_owner_to_parent: failed to change "
561 "current working directory to %s. Error "
562 "was %s\n", fname, strerror(errno) ));
563 goto chdir;
566 smb_fname_cwd = synthetic_smb_fname(ctx, ".", NULL, NULL, 0);
567 if (smb_fname_cwd == NULL) {
568 status = NT_STATUS_NO_MEMORY;
569 goto chdir;
572 ret = SMB_VFS_STAT(conn, smb_fname_cwd);
573 if (ret == -1) {
574 status = map_nt_error_from_unix(errno);
575 DEBUG(0,("change_dir_owner_to_parent: failed to stat "
576 "directory '.' (%s) Error was %s\n",
577 fname, strerror(errno)));
578 goto chdir;
581 /* Ensure we're pointing at the same place. */
582 if (smb_fname_cwd->st.st_ex_dev != psbuf->st_ex_dev ||
583 smb_fname_cwd->st.st_ex_ino != psbuf->st_ex_ino) {
584 DEBUG(0,("change_dir_owner_to_parent: "
585 "device/inode on directory %s changed. "
586 "Refusing to chown !\n", fname ));
587 status = NT_STATUS_ACCESS_DENIED;
588 goto chdir;
591 if (smb_fname_parent->st.st_ex_uid == smb_fname_cwd->st.st_ex_uid) {
592 /* Already this uid - no need to change. */
593 DEBUG(10,("change_dir_owner_to_parent: directory %s "
594 "is already owned by uid %d\n",
595 fname,
596 (int)smb_fname_cwd->st.st_ex_uid ));
597 status = NT_STATUS_OK;
598 goto chdir;
601 become_root();
602 ret = SMB_VFS_LCHOWN(conn,
603 smb_fname_cwd,
604 smb_fname_parent->st.st_ex_uid,
605 (gid_t)-1);
606 unbecome_root();
607 if (ret == -1) {
608 status = map_nt_error_from_unix(errno);
609 DEBUG(10,("change_dir_owner_to_parent: failed to chown "
610 "directory %s to parent directory uid %u. "
611 "Error was %s\n", fname,
612 (unsigned int)smb_fname_parent->st.st_ex_uid,
613 strerror(errno) ));
614 } else {
615 DEBUG(10,("change_dir_owner_to_parent: changed ownership of new "
616 "directory %s to parent directory uid %u.\n",
617 fname, (unsigned int)smb_fname_parent->st.st_ex_uid ));
618 /* Ensure the uid entry is updated. */
619 psbuf->st_ex_uid = smb_fname_parent->st.st_ex_uid;
622 chdir:
623 vfs_ChDir(conn,saved_dir);
624 out:
625 TALLOC_FREE(smb_fname_parent);
626 TALLOC_FREE(smb_fname_cwd);
627 return status;
630 /****************************************************************************
631 Open a file - returning a guaranteed ATOMIC indication of if the
632 file was created or not.
633 ****************************************************************************/
635 static NTSTATUS fd_open_atomic(struct connection_struct *conn,
636 files_struct *fsp,
637 int flags,
638 mode_t mode,
639 bool *file_created)
641 NTSTATUS status = NT_STATUS_UNSUCCESSFUL;
642 bool file_existed = VALID_STAT(fsp->fsp_name->st);
644 *file_created = false;
646 if (!(flags & O_CREAT)) {
648 * We're not creating the file, just pass through.
650 return fd_open(conn, fsp, flags, mode);
653 if (flags & O_EXCL) {
655 * Fail if already exists, just pass through.
657 status = fd_open(conn, fsp, flags, mode);
660 * Here we've opened with O_CREAT|O_EXCL. If that went
661 * NT_STATUS_OK, we *know* we created this file.
663 *file_created = NT_STATUS_IS_OK(status);
665 return status;
669 * Now it gets tricky. We have O_CREAT, but not O_EXCL.
670 * To know absolutely if we created the file or not,
671 * we can never call O_CREAT without O_EXCL. So if
672 * we think the file existed, try without O_CREAT|O_EXCL.
673 * If we think the file didn't exist, try with
674 * O_CREAT|O_EXCL. Keep bouncing between these two
675 * requests until either the file is created, or
676 * opened. Either way, we keep going until we get
677 * a returnable result (error, or open/create).
680 while(1) {
681 int curr_flags = flags;
683 if (file_existed) {
684 /* Just try open, do not create. */
685 curr_flags &= ~(O_CREAT);
686 status = fd_open(conn, fsp, curr_flags, mode);
687 if (NT_STATUS_EQUAL(status,
688 NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
690 * Someone deleted it in the meantime.
691 * Retry with O_EXCL.
693 file_existed = false;
694 DEBUG(10,("fd_open_atomic: file %s existed. "
695 "Retry.\n",
696 smb_fname_str_dbg(fsp->fsp_name)));
697 continue;
699 } else {
700 /* Try create exclusively, fail if it exists. */
701 curr_flags |= O_EXCL;
702 status = fd_open(conn, fsp, curr_flags, mode);
703 if (NT_STATUS_EQUAL(status,
704 NT_STATUS_OBJECT_NAME_COLLISION)) {
706 * Someone created it in the meantime.
707 * Retry without O_CREAT.
709 file_existed = true;
710 DEBUG(10,("fd_open_atomic: file %s "
711 "did not exist. Retry.\n",
712 smb_fname_str_dbg(fsp->fsp_name)));
713 continue;
715 if (NT_STATUS_IS_OK(status)) {
717 * Here we've opened with O_CREAT|O_EXCL
718 * and got success. We *know* we created
719 * this file.
721 *file_created = true;
724 /* Create is done, or failed. */
725 break;
727 return status;
730 /****************************************************************************
731 Open a file.
732 ****************************************************************************/
734 static NTSTATUS open_file(files_struct *fsp,
735 connection_struct *conn,
736 struct smb_request *req,
737 const char *parent_dir,
738 int flags,
739 mode_t unx_mode,
740 uint32_t access_mask, /* client requested access mask. */
741 uint32_t open_access_mask, /* what we're actually using in the open. */
742 bool *p_file_created)
744 struct smb_filename *smb_fname = fsp->fsp_name;
745 NTSTATUS status = NT_STATUS_OK;
746 int accmode = (flags & O_ACCMODE);
747 int local_flags = flags;
748 bool file_existed = VALID_STAT(fsp->fsp_name->st);
750 fsp->fh->fd = -1;
751 errno = EPERM;
753 /* Check permissions */
756 * This code was changed after seeing a client open request
757 * containing the open mode of (DENY_WRITE/read-only) with
758 * the 'create if not exist' bit set. The previous code
759 * would fail to open the file read only on a read-only share
760 * as it was checking the flags parameter directly against O_RDONLY,
761 * this was failing as the flags parameter was set to O_RDONLY|O_CREAT.
762 * JRA.
765 if (!CAN_WRITE(conn)) {
766 /* It's a read-only share - fail if we wanted to write. */
767 if(accmode != O_RDONLY || (flags & O_TRUNC) || (flags & O_APPEND)) {
768 DEBUG(3,("Permission denied opening %s\n",
769 smb_fname_str_dbg(smb_fname)));
770 return NT_STATUS_ACCESS_DENIED;
772 if (flags & O_CREAT) {
773 /* We don't want to write - but we must make sure that
774 O_CREAT doesn't create the file if we have write
775 access into the directory.
777 flags &= ~(O_CREAT|O_EXCL);
778 local_flags &= ~(O_CREAT|O_EXCL);
783 * This little piece of insanity is inspired by the
784 * fact that an NT client can open a file for O_RDONLY,
785 * but set the create disposition to FILE_EXISTS_TRUNCATE.
786 * If the client *can* write to the file, then it expects to
787 * truncate the file, even though it is opening for readonly.
788 * Quicken uses this stupid trick in backup file creation...
789 * Thanks *greatly* to "David W. Chapman Jr." <dwcjr@inethouston.net>
790 * for helping track this one down. It didn't bite us in 2.0.x
791 * as we always opened files read-write in that release. JRA.
794 if ((accmode == O_RDONLY) && ((flags & O_TRUNC) == O_TRUNC)) {
795 DEBUG(10,("open_file: truncate requested on read-only open "
796 "for file %s\n", smb_fname_str_dbg(smb_fname)));
797 local_flags = (flags & ~O_ACCMODE)|O_RDWR;
800 if ((open_access_mask & (FILE_READ_DATA|FILE_WRITE_DATA|FILE_APPEND_DATA|FILE_EXECUTE)) ||
801 (!file_existed && (local_flags & O_CREAT)) ||
802 ((local_flags & O_TRUNC) == O_TRUNC) ) {
803 const char *wild;
804 int ret;
806 #if defined(O_NONBLOCK) && defined(S_ISFIFO)
808 * We would block on opening a FIFO with no one else on the
809 * other end. Do what we used to do and add O_NONBLOCK to the
810 * open flags. JRA.
813 if (file_existed && S_ISFIFO(smb_fname->st.st_ex_mode)) {
814 local_flags &= ~O_TRUNC; /* Can't truncate a FIFO. */
815 local_flags |= O_NONBLOCK;
817 #endif
819 /* Don't create files with Microsoft wildcard characters. */
820 if (fsp->base_fsp) {
822 * wildcard characters are allowed in stream names
823 * only test the basefilename
825 wild = fsp->base_fsp->fsp_name->base_name;
826 } else {
827 wild = smb_fname->base_name;
829 if ((local_flags & O_CREAT) && !file_existed &&
830 !(fsp->posix_flags & FSP_POSIX_FLAGS_PATHNAMES) &&
831 ms_has_wild(wild)) {
832 return NT_STATUS_OBJECT_NAME_INVALID;
835 /* Can we access this file ? */
836 if (!fsp->base_fsp) {
837 /* Only do this check on non-stream open. */
838 if (file_existed) {
839 status = smbd_check_access_rights(conn,
840 smb_fname,
841 false,
842 access_mask);
844 if (!NT_STATUS_IS_OK(status)) {
845 DEBUG(10, ("open_file: "
846 "smbd_check_access_rights "
847 "on file %s returned %s\n",
848 smb_fname_str_dbg(smb_fname),
849 nt_errstr(status)));
852 if (!NT_STATUS_IS_OK(status) &&
853 !NT_STATUS_EQUAL(status,
854 NT_STATUS_OBJECT_NAME_NOT_FOUND))
856 return status;
859 if (NT_STATUS_EQUAL(status,
860 NT_STATUS_OBJECT_NAME_NOT_FOUND))
862 DEBUG(10, ("open_file: "
863 "file %s vanished since we "
864 "checked for existence.\n",
865 smb_fname_str_dbg(smb_fname)));
866 file_existed = false;
867 SET_STAT_INVALID(fsp->fsp_name->st);
871 if (!file_existed) {
872 if (!(local_flags & O_CREAT)) {
873 /* File didn't exist and no O_CREAT. */
874 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
877 status = check_parent_access(conn,
878 smb_fname,
879 SEC_DIR_ADD_FILE);
880 if (!NT_STATUS_IS_OK(status)) {
881 DEBUG(10, ("open_file: "
882 "check_parent_access on "
883 "file %s returned %s\n",
884 smb_fname_str_dbg(smb_fname),
885 nt_errstr(status) ));
886 return status;
892 * Actually do the open - if O_TRUNC is needed handle it
893 * below under the share mode lock.
895 status = fd_open_atomic(conn, fsp, local_flags & ~O_TRUNC,
896 unx_mode, p_file_created);
897 if (!NT_STATUS_IS_OK(status)) {
898 DEBUG(3,("Error opening file %s (%s) (local_flags=%d) "
899 "(flags=%d)\n", smb_fname_str_dbg(smb_fname),
900 nt_errstr(status),local_flags,flags));
901 return status;
904 ret = SMB_VFS_FSTAT(fsp, &smb_fname->st);
905 if (ret == -1) {
906 /* If we have an fd, this stat should succeed. */
907 DEBUG(0,("Error doing fstat on open file %s "
908 "(%s)\n",
909 smb_fname_str_dbg(smb_fname),
910 strerror(errno) ));
911 status = map_nt_error_from_unix(errno);
912 fd_close(fsp);
913 return status;
916 if (*p_file_created) {
917 /* We created this file. */
919 bool need_re_stat = false;
920 /* Do all inheritance work after we've
921 done a successful fstat call and filled
922 in the stat struct in fsp->fsp_name. */
924 /* Inherit the ACL if required */
925 if (lp_inherit_permissions(SNUM(conn))) {
926 inherit_access_posix_acl(conn, parent_dir,
927 smb_fname->base_name,
928 unx_mode);
929 need_re_stat = true;
932 /* Change the owner if required. */
933 if (lp_inherit_owner(SNUM(conn))) {
934 change_file_owner_to_parent(conn, parent_dir,
935 fsp);
936 need_re_stat = true;
939 if (need_re_stat) {
940 ret = SMB_VFS_FSTAT(fsp, &smb_fname->st);
941 /* If we have an fd, this stat should succeed. */
942 if (ret == -1) {
943 DEBUG(0,("Error doing fstat on open file %s "
944 "(%s)\n",
945 smb_fname_str_dbg(smb_fname),
946 strerror(errno) ));
950 notify_fname(conn, NOTIFY_ACTION_ADDED,
951 FILE_NOTIFY_CHANGE_FILE_NAME,
952 smb_fname->base_name);
954 } else {
955 fsp->fh->fd = -1; /* What we used to call a stat open. */
956 if (!file_existed) {
957 /* File must exist for a stat open. */
958 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
961 status = smbd_check_access_rights(conn,
962 smb_fname,
963 false,
964 access_mask);
966 if (NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND) &&
967 (fsp->posix_flags & FSP_POSIX_FLAGS_OPEN) &&
968 S_ISLNK(smb_fname->st.st_ex_mode)) {
969 /* This is a POSIX stat open for delete
970 * or rename on a symlink that points
971 * nowhere. Allow. */
972 DEBUG(10,("open_file: allowing POSIX "
973 "open on bad symlink %s\n",
974 smb_fname_str_dbg(smb_fname)));
975 status = NT_STATUS_OK;
978 if (!NT_STATUS_IS_OK(status)) {
979 DEBUG(10,("open_file: "
980 "smbd_check_access_rights on file "
981 "%s returned %s\n",
982 smb_fname_str_dbg(smb_fname),
983 nt_errstr(status) ));
984 return status;
989 * POSIX allows read-only opens of directories. We don't
990 * want to do this (we use a different code path for this)
991 * so catch a directory open and return an EISDIR. JRA.
994 if(S_ISDIR(smb_fname->st.st_ex_mode)) {
995 fd_close(fsp);
996 errno = EISDIR;
997 return NT_STATUS_FILE_IS_A_DIRECTORY;
1000 fsp->file_id = vfs_file_id_from_sbuf(conn, &smb_fname->st);
1001 fsp->vuid = req ? req->vuid : UID_FIELD_INVALID;
1002 fsp->file_pid = req ? req->smbpid : 0;
1003 fsp->can_lock = True;
1004 fsp->can_read = ((access_mask & FILE_READ_DATA) != 0);
1005 fsp->can_write =
1006 CAN_WRITE(conn) &&
1007 ((access_mask & (FILE_WRITE_DATA | FILE_APPEND_DATA)) != 0);
1008 fsp->print_file = NULL;
1009 fsp->modified = False;
1010 fsp->sent_oplock_break = NO_BREAK_SENT;
1011 fsp->is_directory = False;
1012 if (conn->aio_write_behind_list &&
1013 is_in_path(smb_fname->base_name, conn->aio_write_behind_list,
1014 conn->case_sensitive)) {
1015 fsp->aio_write_behind = True;
1018 fsp->wcp = NULL; /* Write cache pointer. */
1020 DEBUG(2,("%s opened file %s read=%s write=%s (numopen=%d)\n",
1021 conn->session_info->unix_info->unix_name,
1022 smb_fname_str_dbg(smb_fname),
1023 BOOLSTR(fsp->can_read), BOOLSTR(fsp->can_write),
1024 conn->num_files_open));
1026 errno = 0;
1027 return NT_STATUS_OK;
1030 /****************************************************************************
1031 Check if we can open a file with a share mode.
1032 Returns True if conflict, False if not.
1033 ****************************************************************************/
1035 static bool share_conflict(struct share_mode_entry *entry,
1036 uint32_t access_mask,
1037 uint32_t share_access)
1039 DEBUG(10,("share_conflict: entry->access_mask = 0x%x, "
1040 "entry->share_access = 0x%x, "
1041 "entry->private_options = 0x%x\n",
1042 (unsigned int)entry->access_mask,
1043 (unsigned int)entry->share_access,
1044 (unsigned int)entry->private_options));
1046 if (server_id_is_disconnected(&entry->pid)) {
1048 * note: cleanup should have been done by
1049 * delay_for_batch_oplocks()
1051 return false;
1054 DEBUG(10,("share_conflict: access_mask = 0x%x, share_access = 0x%x\n",
1055 (unsigned int)access_mask, (unsigned int)share_access));
1057 if ((entry->access_mask & (FILE_WRITE_DATA|
1058 FILE_APPEND_DATA|
1059 FILE_READ_DATA|
1060 FILE_EXECUTE|
1061 DELETE_ACCESS)) == 0) {
1062 DEBUG(10,("share_conflict: No conflict due to "
1063 "entry->access_mask = 0x%x\n",
1064 (unsigned int)entry->access_mask ));
1065 return False;
1068 if ((access_mask & (FILE_WRITE_DATA|
1069 FILE_APPEND_DATA|
1070 FILE_READ_DATA|
1071 FILE_EXECUTE|
1072 DELETE_ACCESS)) == 0) {
1073 DEBUG(10,("share_conflict: No conflict due to "
1074 "access_mask = 0x%x\n",
1075 (unsigned int)access_mask ));
1076 return False;
1079 #if 1 /* JRA TEST - Superdebug. */
1080 #define CHECK_MASK(num, am, right, sa, share) \
1081 DEBUG(10,("share_conflict: [%d] am (0x%x) & right (0x%x) = 0x%x\n", \
1082 (unsigned int)(num), (unsigned int)(am), \
1083 (unsigned int)(right), (unsigned int)(am)&(right) )); \
1084 DEBUG(10,("share_conflict: [%d] sa (0x%x) & share (0x%x) = 0x%x\n", \
1085 (unsigned int)(num), (unsigned int)(sa), \
1086 (unsigned int)(share), (unsigned int)(sa)&(share) )); \
1087 if (((am) & (right)) && !((sa) & (share))) { \
1088 DEBUG(10,("share_conflict: check %d conflict am = 0x%x, right = 0x%x, \
1089 sa = 0x%x, share = 0x%x\n", (num), (unsigned int)(am), (unsigned int)(right), (unsigned int)(sa), \
1090 (unsigned int)(share) )); \
1091 return True; \
1093 #else
1094 #define CHECK_MASK(num, am, right, sa, share) \
1095 if (((am) & (right)) && !((sa) & (share))) { \
1096 DEBUG(10,("share_conflict: check %d conflict am = 0x%x, right = 0x%x, \
1097 sa = 0x%x, share = 0x%x\n", (num), (unsigned int)(am), (unsigned int)(right), (unsigned int)(sa), \
1098 (unsigned int)(share) )); \
1099 return True; \
1101 #endif
1103 CHECK_MASK(1, entry->access_mask, FILE_WRITE_DATA | FILE_APPEND_DATA,
1104 share_access, FILE_SHARE_WRITE);
1105 CHECK_MASK(2, access_mask, FILE_WRITE_DATA | FILE_APPEND_DATA,
1106 entry->share_access, FILE_SHARE_WRITE);
1108 CHECK_MASK(3, entry->access_mask, FILE_READ_DATA | FILE_EXECUTE,
1109 share_access, FILE_SHARE_READ);
1110 CHECK_MASK(4, access_mask, FILE_READ_DATA | FILE_EXECUTE,
1111 entry->share_access, FILE_SHARE_READ);
1113 CHECK_MASK(5, entry->access_mask, DELETE_ACCESS,
1114 share_access, FILE_SHARE_DELETE);
1115 CHECK_MASK(6, access_mask, DELETE_ACCESS,
1116 entry->share_access, FILE_SHARE_DELETE);
1118 DEBUG(10,("share_conflict: No conflict.\n"));
1119 return False;
1122 #if defined(DEVELOPER)
1123 static void validate_my_share_entries(struct smbd_server_connection *sconn,
1124 int num,
1125 struct share_mode_entry *share_entry)
1127 struct server_id self = messaging_server_id(sconn->msg_ctx);
1128 files_struct *fsp;
1130 if (!serverid_equal(&self, &share_entry->pid)) {
1131 return;
1134 if (share_entry->op_mid == 0) {
1135 /* INTERNAL_OPEN_ONLY */
1136 return;
1139 if (!is_valid_share_mode_entry(share_entry)) {
1140 return;
1143 fsp = file_find_dif(sconn, share_entry->id,
1144 share_entry->share_file_id);
1145 if (!fsp) {
1146 DEBUG(0,("validate_my_share_entries: PANIC : %s\n",
1147 share_mode_str(talloc_tos(), num, share_entry) ));
1148 smb_panic("validate_my_share_entries: Cannot match a "
1149 "share entry with an open file\n");
1152 if (((uint16_t)fsp->oplock_type) != share_entry->op_type) {
1153 goto panic;
1156 return;
1158 panic:
1160 char *str;
1161 DEBUG(0,("validate_my_share_entries: PANIC : %s\n",
1162 share_mode_str(talloc_tos(), num, share_entry) ));
1163 str = talloc_asprintf(talloc_tos(),
1164 "validate_my_share_entries: "
1165 "file %s, oplock_type = 0x%x, op_type = 0x%x\n",
1166 fsp->fsp_name->base_name,
1167 (unsigned int)fsp->oplock_type,
1168 (unsigned int)share_entry->op_type );
1169 smb_panic(str);
1172 #endif
1174 bool is_stat_open(uint32_t access_mask)
1176 const uint32_t stat_open_bits =
1177 (SYNCHRONIZE_ACCESS|
1178 FILE_READ_ATTRIBUTES|
1179 FILE_WRITE_ATTRIBUTES);
1181 return (((access_mask & stat_open_bits) != 0) &&
1182 ((access_mask & ~stat_open_bits) == 0));
1185 static bool has_delete_on_close(struct share_mode_lock *lck,
1186 uint32_t name_hash)
1188 struct share_mode_data *d = lck->data;
1189 uint32_t i;
1191 if (d->num_share_modes == 0) {
1192 return false;
1194 if (!is_delete_on_close_set(lck, name_hash)) {
1195 return false;
1197 for (i=0; i<d->num_share_modes; i++) {
1198 if (!share_mode_stale_pid(d, i)) {
1199 return true;
1202 return false;
1205 /****************************************************************************
1206 Deal with share modes
1207 Invariant: Share mode must be locked on entry and exit.
1208 Returns -1 on error, or number of share modes on success (may be zero).
1209 ****************************************************************************/
1211 static NTSTATUS open_mode_check(connection_struct *conn,
1212 struct share_mode_lock *lck,
1213 uint32_t access_mask,
1214 uint32_t share_access)
1216 uint32_t i;
1218 if(lck->data->num_share_modes == 0) {
1219 return NT_STATUS_OK;
1222 if (is_stat_open(access_mask)) {
1223 /* Stat open that doesn't trigger oplock breaks or share mode
1224 * checks... ! JRA. */
1225 return NT_STATUS_OK;
1229 * Check if the share modes will give us access.
1232 #if defined(DEVELOPER)
1233 for(i = 0; i < lck->data->num_share_modes; i++) {
1234 validate_my_share_entries(conn->sconn, i,
1235 &lck->data->share_modes[i]);
1237 #endif
1239 /* Now we check the share modes, after any oplock breaks. */
1240 for(i = 0; i < lck->data->num_share_modes; i++) {
1242 if (!is_valid_share_mode_entry(&lck->data->share_modes[i])) {
1243 continue;
1246 /* someone else has a share lock on it, check to see if we can
1247 * too */
1248 if (share_conflict(&lck->data->share_modes[i],
1249 access_mask, share_access)) {
1251 if (share_mode_stale_pid(lck->data, i)) {
1252 continue;
1255 return NT_STATUS_SHARING_VIOLATION;
1259 return NT_STATUS_OK;
1263 * Send a break message to the oplock holder and delay the open for
1264 * our client.
1267 NTSTATUS send_break_message(struct messaging_context *msg_ctx,
1268 const struct share_mode_entry *exclusive,
1269 uint16_t break_to)
1271 NTSTATUS status;
1272 char msg[MSG_SMB_SHARE_MODE_ENTRY_SIZE];
1273 struct server_id_buf tmp;
1275 DEBUG(10, ("Sending break request to PID %s\n",
1276 server_id_str_buf(exclusive->pid, &tmp)));
1278 /* Create the message. */
1279 share_mode_entry_to_message(msg, exclusive);
1281 /* Overload entry->op_type */
1283 * This is a cut from uint32_t to uint16_t, but so far only the lower 3
1284 * bits (LEASE_WRITE/HANDLE/READ are used anyway.
1286 SSVAL(msg,OP_BREAK_MSG_OP_TYPE_OFFSET, break_to);
1288 status = messaging_send_buf(msg_ctx, exclusive->pid,
1289 MSG_SMB_BREAK_REQUEST,
1290 (uint8_t *)msg, sizeof(msg));
1291 if (!NT_STATUS_IS_OK(status)) {
1292 DEBUG(3, ("Could not send oplock break message: %s\n",
1293 nt_errstr(status)));
1296 return status;
1300 * Do internal consistency checks on the share mode for a file.
1303 static bool validate_oplock_types(struct share_mode_lock *lck)
1305 struct share_mode_data *d = lck->data;
1306 bool batch = false;
1307 bool ex_or_batch = false;
1308 bool level2 = false;
1309 bool no_oplock = false;
1310 uint32_t num_non_stat_opens = 0;
1311 uint32_t i;
1313 for (i=0; i<d->num_share_modes; i++) {
1314 struct share_mode_entry *e = &d->share_modes[i];
1316 if (!is_valid_share_mode_entry(e)) {
1317 continue;
1320 if (e->op_mid == 0) {
1321 /* INTERNAL_OPEN_ONLY */
1322 continue;
1325 if (e->op_type == NO_OPLOCK && is_stat_open(e->access_mask)) {
1326 /* We ignore stat opens in the table - they
1327 always have NO_OPLOCK and never get or
1328 cause breaks. JRA. */
1329 continue;
1332 num_non_stat_opens += 1;
1334 if (BATCH_OPLOCK_TYPE(e->op_type)) {
1335 /* batch - can only be one. */
1336 if (share_mode_stale_pid(d, i)) {
1337 DEBUG(10, ("Found stale batch oplock\n"));
1338 continue;
1340 if (ex_or_batch || batch || level2 || no_oplock) {
1341 DEBUG(0, ("Bad batch oplock entry %u.",
1342 (unsigned)i));
1343 return false;
1345 batch = true;
1348 if (EXCLUSIVE_OPLOCK_TYPE(e->op_type)) {
1349 if (share_mode_stale_pid(d, i)) {
1350 DEBUG(10, ("Found stale duplicate oplock\n"));
1351 continue;
1353 /* Exclusive or batch - can only be one. */
1354 if (ex_or_batch || level2 || no_oplock) {
1355 DEBUG(0, ("Bad exclusive or batch oplock "
1356 "entry %u.", (unsigned)i));
1357 return false;
1359 ex_or_batch = true;
1362 if (LEVEL_II_OPLOCK_TYPE(e->op_type)) {
1363 if (batch || ex_or_batch) {
1364 if (share_mode_stale_pid(d, i)) {
1365 DEBUG(10, ("Found stale LevelII "
1366 "oplock\n"));
1367 continue;
1369 DEBUG(0, ("Bad levelII oplock entry %u.",
1370 (unsigned)i));
1371 return false;
1373 level2 = true;
1376 if (e->op_type == NO_OPLOCK) {
1377 if (batch || ex_or_batch) {
1378 if (share_mode_stale_pid(d, i)) {
1379 DEBUG(10, ("Found stale NO_OPLOCK "
1380 "entry\n"));
1381 continue;
1383 DEBUG(0, ("Bad no oplock entry %u.",
1384 (unsigned)i));
1385 return false;
1387 no_oplock = true;
1391 remove_stale_share_mode_entries(d);
1393 if ((batch || ex_or_batch) && (num_non_stat_opens != 1)) {
1394 DEBUG(1, ("got batch (%d) or ex (%d) non-exclusively (%d)\n",
1395 (int)batch, (int)ex_or_batch,
1396 (int)d->num_share_modes));
1397 return false;
1400 return true;
1403 static bool delay_for_oplock(files_struct *fsp,
1404 int oplock_request,
1405 const struct smb2_lease *lease,
1406 struct share_mode_lock *lck,
1407 bool have_sharing_violation,
1408 uint32_t create_disposition,
1409 bool first_open_attempt)
1411 struct share_mode_data *d = lck->data;
1412 uint32_t i;
1413 bool delay = false;
1414 bool will_overwrite;
1416 if ((oplock_request & INTERNAL_OPEN_ONLY) ||
1417 is_stat_open(fsp->access_mask)) {
1418 return false;
1421 switch (create_disposition) {
1422 case FILE_SUPERSEDE:
1423 case FILE_OVERWRITE:
1424 case FILE_OVERWRITE_IF:
1425 will_overwrite = true;
1426 break;
1427 default:
1428 will_overwrite = false;
1429 break;
1432 for (i=0; i<d->num_share_modes; i++) {
1433 struct share_mode_entry *e = &d->share_modes[i];
1434 struct share_mode_lease *l = NULL;
1435 uint32_t e_lease_type = get_lease_type(d, e);
1436 uint32_t break_to;
1437 uint32_t delay_mask = 0;
1439 if (e->op_type == LEASE_OPLOCK) {
1440 l = &d->leases[e->lease_idx];
1443 if (have_sharing_violation) {
1444 delay_mask = SMB2_LEASE_HANDLE;
1445 } else {
1446 delay_mask = SMB2_LEASE_WRITE;
1449 break_to = e_lease_type & ~delay_mask;
1451 if (will_overwrite) {
1453 * we'll decide about SMB2_LEASE_READ later.
1455 * Maybe the break will be defered
1457 break_to &= ~SMB2_LEASE_HANDLE;
1460 DEBUG(10, ("entry %u: e_lease_type %u, will_overwrite: %u\n",
1461 (unsigned)i, (unsigned)e_lease_type,
1462 (unsigned)will_overwrite));
1464 if (lease != NULL && l != NULL) {
1465 bool ign;
1467 ign = smb2_lease_equal(fsp_client_guid(fsp),
1468 &lease->lease_key,
1469 &l->client_guid,
1470 &l->lease_key);
1471 if (ign) {
1472 continue;
1476 if ((e_lease_type & ~break_to) == 0) {
1477 if (l != NULL && l->breaking) {
1478 delay = true;
1480 continue;
1483 if (share_mode_stale_pid(d, i)) {
1484 continue;
1487 if (will_overwrite) {
1489 * If we break anyway break to NONE directly.
1490 * Otherwise vfs_set_filelen() will trigger the
1491 * break.
1493 break_to &= ~(SMB2_LEASE_READ|SMB2_LEASE_WRITE);
1496 if (e->op_type != LEASE_OPLOCK) {
1498 * Oplocks only support breaking to R or NONE.
1500 break_to &= ~(SMB2_LEASE_HANDLE|SMB2_LEASE_WRITE);
1503 DEBUG(10, ("breaking from %d to %d\n",
1504 (int)e_lease_type, (int)break_to));
1505 send_break_message(fsp->conn->sconn->msg_ctx, e,
1506 break_to);
1507 if (e_lease_type & delay_mask) {
1508 delay = true;
1510 if (l != NULL && l->breaking && !first_open_attempt) {
1511 delay = true;
1513 continue;
1516 return delay;
1519 static bool file_has_brlocks(files_struct *fsp)
1521 struct byte_range_lock *br_lck;
1523 br_lck = brl_get_locks_readonly(fsp);
1524 if (!br_lck)
1525 return false;
1527 return (brl_num_locks(br_lck) > 0);
1530 int find_share_mode_lease(struct share_mode_data *d,
1531 const struct GUID *client_guid,
1532 const struct smb2_lease_key *key)
1534 uint32_t i;
1536 for (i=0; i<d->num_leases; i++) {
1537 struct share_mode_lease *l = &d->leases[i];
1539 if (smb2_lease_equal(client_guid,
1540 key,
1541 &l->client_guid,
1542 &l->lease_key)) {
1543 return i;
1547 return -1;
1550 struct fsp_lease *find_fsp_lease(struct files_struct *new_fsp,
1551 const struct smb2_lease_key *key,
1552 const struct share_mode_lease *l)
1554 struct files_struct *fsp;
1557 * TODO: Measure how expensive this loop is with thousands of open
1558 * handles...
1561 for (fsp = file_find_di_first(new_fsp->conn->sconn, new_fsp->file_id);
1562 fsp != NULL;
1563 fsp = file_find_di_next(fsp)) {
1565 if (fsp == new_fsp) {
1566 continue;
1568 if (fsp->oplock_type != LEASE_OPLOCK) {
1569 continue;
1571 if (smb2_lease_key_equal(&fsp->lease->lease.lease_key, key)) {
1572 fsp->lease->ref_count += 1;
1573 return fsp->lease;
1577 /* Not found - must be leased in another smbd. */
1578 new_fsp->lease = talloc_zero(new_fsp->conn->sconn, struct fsp_lease);
1579 if (new_fsp->lease == NULL) {
1580 return NULL;
1582 new_fsp->lease->ref_count = 1;
1583 new_fsp->lease->sconn = new_fsp->conn->sconn;
1584 new_fsp->lease->lease.lease_key = *key;
1585 new_fsp->lease->lease.lease_state = l->current_state;
1587 * We internally treat all leases as V2 and update
1588 * the epoch, but when sending breaks it matters if
1589 * the requesting lease was v1 or v2.
1591 new_fsp->lease->lease.lease_version = l->lease_version;
1592 new_fsp->lease->lease.lease_epoch = l->epoch;
1593 return new_fsp->lease;
1596 static NTSTATUS grant_fsp_lease(struct files_struct *fsp,
1597 struct share_mode_lock *lck,
1598 const struct smb2_lease *lease,
1599 uint32_t *p_lease_idx,
1600 uint32_t granted)
1602 struct share_mode_data *d = lck->data;
1603 const struct GUID *client_guid = fsp_client_guid(fsp);
1604 struct share_mode_lease *tmp;
1605 NTSTATUS status;
1606 int idx;
1608 idx = find_share_mode_lease(d, client_guid, &lease->lease_key);
1610 if (idx != -1) {
1611 struct share_mode_lease *l = &d->leases[idx];
1612 bool do_upgrade;
1613 uint32_t existing, requested;
1615 fsp->lease = find_fsp_lease(fsp, &lease->lease_key, l);
1616 if (fsp->lease == NULL) {
1617 DEBUG(1, ("Did not find existing lease for file %s\n",
1618 fsp_str_dbg(fsp)));
1619 return NT_STATUS_NO_MEMORY;
1622 *p_lease_idx = idx;
1625 * Upgrade only if the requested lease is a strict upgrade.
1627 existing = l->current_state;
1628 requested = lease->lease_state;
1631 * Tricky: This test makes sure that "requested" is a
1632 * strict bitwise superset of "existing".
1634 do_upgrade = ((existing & requested) == existing);
1637 * Upgrade only if there's a change.
1639 do_upgrade &= (granted != existing);
1642 * Upgrade only if other leases don't prevent what was asked
1643 * for.
1645 do_upgrade &= (granted == requested);
1648 * only upgrade if we are not in breaking state
1650 do_upgrade &= !l->breaking;
1652 DEBUG(10, ("existing=%"PRIu32", requested=%"PRIu32", "
1653 "granted=%"PRIu32", do_upgrade=%d\n",
1654 existing, requested, granted, (int)do_upgrade));
1656 if (do_upgrade) {
1657 l->current_state = granted;
1658 l->epoch += 1;
1661 /* Ensure we're in sync with current lease state. */
1662 fsp_lease_update(lck, fsp_client_guid(fsp), fsp->lease);
1663 return NT_STATUS_OK;
1667 * Create new lease
1670 tmp = talloc_realloc(d, d->leases, struct share_mode_lease,
1671 d->num_leases+1);
1672 if (tmp == NULL) {
1674 * See [MS-SMB2]
1676 return NT_STATUS_INSUFFICIENT_RESOURCES;
1678 d->leases = tmp;
1680 fsp->lease = talloc_zero(fsp->conn->sconn, struct fsp_lease);
1681 if (fsp->lease == NULL) {
1682 return NT_STATUS_INSUFFICIENT_RESOURCES;
1684 fsp->lease->ref_count = 1;
1685 fsp->lease->sconn = fsp->conn->sconn;
1686 fsp->lease->lease.lease_version = lease->lease_version;
1687 fsp->lease->lease.lease_key = lease->lease_key;
1688 fsp->lease->lease.lease_state = granted;
1689 fsp->lease->lease.lease_epoch = lease->lease_epoch + 1;
1691 *p_lease_idx = d->num_leases;
1693 d->leases[d->num_leases] = (struct share_mode_lease) {
1694 .client_guid = *client_guid,
1695 .lease_key = fsp->lease->lease.lease_key,
1696 .current_state = fsp->lease->lease.lease_state,
1697 .lease_version = fsp->lease->lease.lease_version,
1698 .epoch = fsp->lease->lease.lease_epoch,
1701 status = leases_db_add(client_guid,
1702 &lease->lease_key,
1703 &fsp->file_id,
1704 fsp->conn->connectpath,
1705 fsp->fsp_name->base_name,
1706 fsp->fsp_name->stream_name);
1707 if (!NT_STATUS_IS_OK(status)) {
1708 DEBUG(10, ("%s: leases_db_add failed: %s\n", __func__,
1709 nt_errstr(status)));
1710 TALLOC_FREE(fsp->lease);
1711 return NT_STATUS_INSUFFICIENT_RESOURCES;
1714 d->num_leases += 1;
1715 d->modified = true;
1717 return NT_STATUS_OK;
1720 static bool is_same_lease(const files_struct *fsp,
1721 const struct share_mode_data *d,
1722 const struct share_mode_entry *e,
1723 const struct smb2_lease *lease)
1725 if (e->op_type != LEASE_OPLOCK) {
1726 return false;
1728 if (lease == NULL) {
1729 return false;
1732 return smb2_lease_equal(fsp_client_guid(fsp),
1733 &lease->lease_key,
1734 &d->leases[e->lease_idx].client_guid,
1735 &d->leases[e->lease_idx].lease_key);
1738 static NTSTATUS grant_fsp_oplock_type(struct smb_request *req,
1739 struct files_struct *fsp,
1740 struct share_mode_lock *lck,
1741 int oplock_request,
1742 struct smb2_lease *lease)
1744 struct share_mode_data *d = lck->data;
1745 bool got_handle_lease = false;
1746 bool got_oplock = false;
1747 uint32_t i;
1748 uint32_t granted;
1749 uint32_t lease_idx = UINT32_MAX;
1750 bool ok;
1751 NTSTATUS status;
1753 if (oplock_request & INTERNAL_OPEN_ONLY) {
1754 /* No oplocks on internal open. */
1755 oplock_request = NO_OPLOCK;
1756 DEBUG(10,("grant_fsp_oplock_type: oplock type 0x%x on file %s\n",
1757 fsp->oplock_type, fsp_str_dbg(fsp)));
1760 if (oplock_request == LEASE_OPLOCK) {
1761 if (lease == NULL) {
1763 * The SMB2 layer should have checked this
1765 return NT_STATUS_INTERNAL_ERROR;
1768 granted = lease->lease_state;
1770 if (lp_kernel_oplocks(SNUM(fsp->conn))) {
1771 DEBUG(10, ("No lease granted because kernel oplocks are enabled\n"));
1772 granted = SMB2_LEASE_NONE;
1774 if ((granted & (SMB2_LEASE_READ|SMB2_LEASE_WRITE)) == 0) {
1775 DEBUG(10, ("No read or write lease requested\n"));
1776 granted = SMB2_LEASE_NONE;
1778 if (granted == SMB2_LEASE_WRITE) {
1779 DEBUG(10, ("pure write lease requested\n"));
1780 granted = SMB2_LEASE_NONE;
1782 if (granted == (SMB2_LEASE_WRITE|SMB2_LEASE_HANDLE)) {
1783 DEBUG(10, ("write and handle lease requested\n"));
1784 granted = SMB2_LEASE_NONE;
1786 } else {
1787 granted = map_oplock_to_lease_type(
1788 oplock_request & ~SAMBA_PRIVATE_OPLOCK_MASK);
1791 if (lp_locking(fsp->conn->params) && file_has_brlocks(fsp)) {
1792 DEBUG(10,("grant_fsp_oplock_type: file %s has byte range locks\n",
1793 fsp_str_dbg(fsp)));
1794 granted &= ~SMB2_LEASE_READ;
1797 for (i=0; i<d->num_share_modes; i++) {
1798 struct share_mode_entry *e = &d->share_modes[i];
1799 uint32_t e_lease_type;
1801 e_lease_type = get_lease_type(d, e);
1803 if ((granted & SMB2_LEASE_WRITE) &&
1804 !is_same_lease(fsp, d, e, lease) &&
1805 !share_mode_stale_pid(d, i)) {
1807 * Can grant only one writer
1809 granted &= ~SMB2_LEASE_WRITE;
1812 if ((e_lease_type & SMB2_LEASE_HANDLE) && !got_handle_lease &&
1813 !share_mode_stale_pid(d, i)) {
1814 got_handle_lease = true;
1817 if ((e->op_type != LEASE_OPLOCK) && !got_oplock &&
1818 !share_mode_stale_pid(d, i)) {
1819 got_oplock = true;
1823 if ((granted & SMB2_LEASE_READ) && !(granted & SMB2_LEASE_WRITE)) {
1824 bool allow_level2 =
1825 (global_client_caps & CAP_LEVEL_II_OPLOCKS) &&
1826 lp_level2_oplocks(SNUM(fsp->conn));
1828 if (!allow_level2) {
1829 granted = SMB2_LEASE_NONE;
1833 if (oplock_request == LEASE_OPLOCK) {
1834 if (got_oplock) {
1835 granted &= ~SMB2_LEASE_HANDLE;
1838 fsp->oplock_type = LEASE_OPLOCK;
1840 status = grant_fsp_lease(fsp, lck, lease, &lease_idx,
1841 granted);
1842 if (!NT_STATUS_IS_OK(status)) {
1843 return status;
1846 *lease = fsp->lease->lease;
1847 DEBUG(10, ("lease_state=%d\n", lease->lease_state));
1848 } else {
1849 if (got_handle_lease) {
1850 granted = SMB2_LEASE_NONE;
1853 switch (granted) {
1854 case SMB2_LEASE_READ|SMB2_LEASE_WRITE|SMB2_LEASE_HANDLE:
1855 fsp->oplock_type = BATCH_OPLOCK|EXCLUSIVE_OPLOCK;
1856 break;
1857 case SMB2_LEASE_READ|SMB2_LEASE_WRITE:
1858 fsp->oplock_type = EXCLUSIVE_OPLOCK;
1859 break;
1860 case SMB2_LEASE_READ|SMB2_LEASE_HANDLE:
1861 case SMB2_LEASE_READ:
1862 fsp->oplock_type = LEVEL_II_OPLOCK;
1863 break;
1864 default:
1865 fsp->oplock_type = NO_OPLOCK;
1866 break;
1869 status = set_file_oplock(fsp);
1870 if (!NT_STATUS_IS_OK(status)) {
1872 * Could not get the kernel oplock
1874 fsp->oplock_type = NO_OPLOCK;
1878 ok = set_share_mode(lck, fsp, get_current_uid(fsp->conn),
1879 req ? req->mid : 0,
1880 fsp->oplock_type,
1881 lease_idx);
1882 if (!ok) {
1883 return NT_STATUS_NO_MEMORY;
1886 ok = update_num_read_oplocks(fsp, lck);
1887 if (!ok) {
1888 del_share_mode(lck, fsp);
1889 return NT_STATUS_INTERNAL_ERROR;
1892 DEBUG(10,("grant_fsp_oplock_type: oplock type 0x%x on file %s\n",
1893 fsp->oplock_type, fsp_str_dbg(fsp)));
1895 return NT_STATUS_OK;
1898 static bool request_timed_out(struct timeval request_time,
1899 struct timeval timeout)
1901 struct timeval now, end_time;
1902 GetTimeOfDay(&now);
1903 end_time = timeval_sum(&request_time, &timeout);
1904 return (timeval_compare(&end_time, &now) < 0);
1907 struct defer_open_state {
1908 struct smbXsrv_connection *xconn;
1909 uint64_t mid;
1912 static void defer_open_done(struct tevent_req *req);
1914 /****************************************************************************
1915 Handle the 1 second delay in returning a SHARING_VIOLATION error.
1916 ****************************************************************************/
1918 static void defer_open(struct share_mode_lock *lck,
1919 struct timeval request_time,
1920 struct timeval timeout,
1921 struct smb_request *req,
1922 struct deferred_open_record *state)
1924 struct deferred_open_record *open_rec;
1926 DEBUG(10,("defer_open_sharing_error: time [%u.%06u] adding deferred "
1927 "open entry for mid %llu\n",
1928 (unsigned int)request_time.tv_sec,
1929 (unsigned int)request_time.tv_usec,
1930 (unsigned long long)req->mid));
1932 open_rec = talloc(NULL, struct deferred_open_record);
1933 if (open_rec == NULL) {
1934 TALLOC_FREE(lck);
1935 exit_server("talloc failed");
1938 *open_rec = *state;
1940 if (lck) {
1941 struct defer_open_state *watch_state;
1942 struct tevent_req *watch_req;
1943 bool ret;
1945 watch_state = talloc(open_rec, struct defer_open_state);
1946 if (watch_state == NULL) {
1947 exit_server("talloc failed");
1949 watch_state->xconn = req->xconn;
1950 watch_state->mid = req->mid;
1952 DEBUG(10, ("defering mid %llu\n",
1953 (unsigned long long)req->mid));
1955 watch_req = dbwrap_watched_watch_send(
1956 watch_state, req->sconn->ev_ctx, lck->data->record,
1957 (struct server_id){0});
1958 if (watch_req == NULL) {
1959 exit_server("Could not watch share mode record");
1961 tevent_req_set_callback(watch_req, defer_open_done,
1962 watch_state);
1964 ret = tevent_req_set_endtime(
1965 watch_req, req->sconn->ev_ctx,
1966 timeval_sum(&request_time, &timeout));
1967 SMB_ASSERT(ret);
1970 if (!push_deferred_open_message_smb(req, request_time, timeout,
1971 state->id, open_rec)) {
1972 TALLOC_FREE(lck);
1973 exit_server("push_deferred_open_message_smb failed");
1977 static void defer_open_done(struct tevent_req *req)
1979 struct defer_open_state *state = tevent_req_callback_data(
1980 req, struct defer_open_state);
1981 NTSTATUS status;
1982 bool ret;
1984 status = dbwrap_watched_watch_recv(req, talloc_tos(), NULL, NULL,
1985 NULL);
1986 TALLOC_FREE(req);
1987 if (!NT_STATUS_IS_OK(status)) {
1988 DEBUG(5, ("dbwrap_watched_watch_recv returned %s\n",
1989 nt_errstr(status)));
1991 * Even if it failed, retry anyway. TODO: We need a way to
1992 * tell a re-scheduled open about that error.
1996 DEBUG(10, ("scheduling mid %llu\n", (unsigned long long)state->mid));
1998 ret = schedule_deferred_open_message_smb(state->xconn, state->mid);
1999 SMB_ASSERT(ret);
2000 TALLOC_FREE(state);
2004 /****************************************************************************
2005 On overwrite open ensure that the attributes match.
2006 ****************************************************************************/
2008 static bool open_match_attributes(connection_struct *conn,
2009 uint32_t old_dos_attr,
2010 uint32_t new_dos_attr,
2011 mode_t existing_unx_mode,
2012 mode_t new_unx_mode,
2013 mode_t *returned_unx_mode)
2015 uint32_t noarch_old_dos_attr, noarch_new_dos_attr;
2017 noarch_old_dos_attr = (old_dos_attr & ~FILE_ATTRIBUTE_ARCHIVE);
2018 noarch_new_dos_attr = (new_dos_attr & ~FILE_ATTRIBUTE_ARCHIVE);
2020 if((noarch_old_dos_attr == 0 && noarch_new_dos_attr != 0) ||
2021 (noarch_old_dos_attr != 0 && ((noarch_old_dos_attr & noarch_new_dos_attr) == noarch_old_dos_attr))) {
2022 *returned_unx_mode = new_unx_mode;
2023 } else {
2024 *returned_unx_mode = (mode_t)0;
2027 DEBUG(10,("open_match_attributes: old_dos_attr = 0x%x, "
2028 "existing_unx_mode = 0%o, new_dos_attr = 0x%x "
2029 "returned_unx_mode = 0%o\n",
2030 (unsigned int)old_dos_attr,
2031 (unsigned int)existing_unx_mode,
2032 (unsigned int)new_dos_attr,
2033 (unsigned int)*returned_unx_mode ));
2035 /* If we're mapping SYSTEM and HIDDEN ensure they match. */
2036 if (lp_map_system(SNUM(conn)) || lp_store_dos_attributes(SNUM(conn))) {
2037 if ((old_dos_attr & FILE_ATTRIBUTE_SYSTEM) &&
2038 !(new_dos_attr & FILE_ATTRIBUTE_SYSTEM)) {
2039 return False;
2042 if (lp_map_hidden(SNUM(conn)) || lp_store_dos_attributes(SNUM(conn))) {
2043 if ((old_dos_attr & FILE_ATTRIBUTE_HIDDEN) &&
2044 !(new_dos_attr & FILE_ATTRIBUTE_HIDDEN)) {
2045 return False;
2048 return True;
2051 /****************************************************************************
2052 Special FCB or DOS processing in the case of a sharing violation.
2053 Try and find a duplicated file handle.
2054 ****************************************************************************/
2056 static NTSTATUS fcb_or_dos_open(struct smb_request *req,
2057 connection_struct *conn,
2058 files_struct *fsp_to_dup_into,
2059 const struct smb_filename *smb_fname,
2060 struct file_id id,
2061 uint16_t file_pid,
2062 uint64_t vuid,
2063 uint32_t access_mask,
2064 uint32_t share_access,
2065 uint32_t create_options)
2067 files_struct *fsp;
2069 DEBUG(5,("fcb_or_dos_open: attempting old open semantics for "
2070 "file %s.\n", smb_fname_str_dbg(smb_fname)));
2072 for(fsp = file_find_di_first(conn->sconn, id); fsp;
2073 fsp = file_find_di_next(fsp)) {
2075 DEBUG(10,("fcb_or_dos_open: checking file %s, fd = %d, "
2076 "vuid = %llu, file_pid = %u, private_options = 0x%x "
2077 "access_mask = 0x%x\n", fsp_str_dbg(fsp),
2078 fsp->fh->fd, (unsigned long long)fsp->vuid,
2079 (unsigned int)fsp->file_pid,
2080 (unsigned int)fsp->fh->private_options,
2081 (unsigned int)fsp->access_mask ));
2083 if (fsp != fsp_to_dup_into &&
2084 fsp->fh->fd != -1 &&
2085 fsp->vuid == vuid &&
2086 fsp->file_pid == file_pid &&
2087 (fsp->fh->private_options & (NTCREATEX_OPTIONS_PRIVATE_DENY_DOS |
2088 NTCREATEX_OPTIONS_PRIVATE_DENY_FCB)) &&
2089 (fsp->access_mask & FILE_WRITE_DATA) &&
2090 strequal(fsp->fsp_name->base_name, smb_fname->base_name) &&
2091 strequal(fsp->fsp_name->stream_name,
2092 smb_fname->stream_name)) {
2093 DEBUG(10,("fcb_or_dos_open: file match\n"));
2094 break;
2098 if (!fsp) {
2099 return NT_STATUS_NOT_FOUND;
2102 /* quite an insane set of semantics ... */
2103 if (is_executable(smb_fname->base_name) &&
2104 (fsp->fh->private_options & NTCREATEX_OPTIONS_PRIVATE_DENY_DOS)) {
2105 DEBUG(10,("fcb_or_dos_open: file fail due to is_executable.\n"));
2106 return NT_STATUS_INVALID_PARAMETER;
2109 /* We need to duplicate this fsp. */
2110 return dup_file_fsp(req, fsp, access_mask, share_access,
2111 create_options, fsp_to_dup_into);
2114 static void schedule_defer_open(struct share_mode_lock *lck,
2115 struct file_id id,
2116 struct timeval request_time,
2117 struct smb_request *req)
2119 struct deferred_open_record state;
2121 /* This is a relative time, added to the absolute
2122 request_time value to get the absolute timeout time.
2123 Note that if this is the second or greater time we enter
2124 this codepath for this particular request mid then
2125 request_time is left as the absolute time of the *first*
2126 time this request mid was processed. This is what allows
2127 the request to eventually time out. */
2129 struct timeval timeout;
2131 /* Normally the smbd we asked should respond within
2132 * OPLOCK_BREAK_TIMEOUT seconds regardless of whether
2133 * the client did, give twice the timeout as a safety
2134 * measure here in case the other smbd is stuck
2135 * somewhere else. */
2137 timeout = timeval_set(OPLOCK_BREAK_TIMEOUT*2, 0);
2139 /* Nothing actually uses state.delayed_for_oplocks
2140 but it's handy to differentiate in debug messages
2141 between a 30 second delay due to oplock break, and
2142 a 1 second delay for share mode conflicts. */
2144 state.delayed_for_oplocks = True;
2145 state.async_open = false;
2146 state.id = id;
2148 if (!request_timed_out(request_time, timeout)) {
2149 defer_open(lck, request_time, timeout, req, &state);
2153 /****************************************************************************
2154 Reschedule an open call that went asynchronous.
2155 ****************************************************************************/
2157 static void schedule_async_open(struct timeval request_time,
2158 struct smb_request *req)
2160 struct deferred_open_record state;
2161 struct timeval timeout;
2163 timeout = timeval_set(20, 0);
2165 ZERO_STRUCT(state);
2166 state.delayed_for_oplocks = false;
2167 state.async_open = true;
2169 if (!request_timed_out(request_time, timeout)) {
2170 defer_open(NULL, request_time, timeout, req, &state);
2174 /****************************************************************************
2175 Work out what access_mask to use from what the client sent us.
2176 ****************************************************************************/
2178 static NTSTATUS smbd_calculate_maximum_allowed_access(
2179 connection_struct *conn,
2180 const struct smb_filename *smb_fname,
2181 bool use_privs,
2182 uint32_t *p_access_mask)
2184 struct security_descriptor *sd;
2185 uint32_t access_granted;
2186 NTSTATUS status;
2188 if (!use_privs && (get_current_uid(conn) == (uid_t)0)) {
2189 *p_access_mask |= FILE_GENERIC_ALL;
2190 return NT_STATUS_OK;
2193 status = SMB_VFS_GET_NT_ACL(conn, smb_fname,
2194 (SECINFO_OWNER |
2195 SECINFO_GROUP |
2196 SECINFO_DACL),
2197 talloc_tos(), &sd);
2199 if (NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
2201 * File did not exist
2203 *p_access_mask = FILE_GENERIC_ALL;
2204 return NT_STATUS_OK;
2206 if (!NT_STATUS_IS_OK(status)) {
2207 DEBUG(10,("Could not get acl on file %s: %s\n",
2208 smb_fname_str_dbg(smb_fname),
2209 nt_errstr(status)));
2210 return NT_STATUS_ACCESS_DENIED;
2214 * If we can access the path to this file, by
2215 * default we have FILE_READ_ATTRIBUTES from the
2216 * containing directory. See the section:
2217 * "Algorithm to Check Access to an Existing File"
2218 * in MS-FSA.pdf.
2220 * se_file_access_check()
2221 * also takes care of owner WRITE_DAC and READ_CONTROL.
2223 status = se_file_access_check(sd,
2224 get_current_nttok(conn),
2225 use_privs,
2226 (*p_access_mask & ~FILE_READ_ATTRIBUTES),
2227 &access_granted);
2229 TALLOC_FREE(sd);
2231 if (!NT_STATUS_IS_OK(status)) {
2232 DEBUG(10, ("Access denied on file %s: "
2233 "when calculating maximum access\n",
2234 smb_fname_str_dbg(smb_fname)));
2235 return NT_STATUS_ACCESS_DENIED;
2237 *p_access_mask = (access_granted | FILE_READ_ATTRIBUTES);
2239 if (!(access_granted & DELETE_ACCESS)) {
2240 if (can_delete_file_in_directory(conn, smb_fname)) {
2241 *p_access_mask |= DELETE_ACCESS;
2245 return NT_STATUS_OK;
2248 NTSTATUS smbd_calculate_access_mask(connection_struct *conn,
2249 const struct smb_filename *smb_fname,
2250 bool use_privs,
2251 uint32_t access_mask,
2252 uint32_t *access_mask_out)
2254 NTSTATUS status;
2255 uint32_t orig_access_mask = access_mask;
2256 uint32_t rejected_share_access;
2259 * Convert GENERIC bits to specific bits.
2262 se_map_generic(&access_mask, &file_generic_mapping);
2264 /* Calculate MAXIMUM_ALLOWED_ACCESS if requested. */
2265 if (access_mask & MAXIMUM_ALLOWED_ACCESS) {
2267 status = smbd_calculate_maximum_allowed_access(
2268 conn, smb_fname, use_privs, &access_mask);
2270 if (!NT_STATUS_IS_OK(status)) {
2271 return status;
2274 access_mask &= conn->share_access;
2277 rejected_share_access = access_mask & ~(conn->share_access);
2279 if (rejected_share_access) {
2280 DEBUG(10, ("smbd_calculate_access_mask: Access denied on "
2281 "file %s: rejected by share access mask[0x%08X] "
2282 "orig[0x%08X] mapped[0x%08X] reject[0x%08X]\n",
2283 smb_fname_str_dbg(smb_fname),
2284 conn->share_access,
2285 orig_access_mask, access_mask,
2286 rejected_share_access));
2287 return NT_STATUS_ACCESS_DENIED;
2290 *access_mask_out = access_mask;
2291 return NT_STATUS_OK;
2294 /****************************************************************************
2295 Remove the deferred open entry under lock.
2296 ****************************************************************************/
2298 /****************************************************************************
2299 Return true if this is a state pointer to an asynchronous create.
2300 ****************************************************************************/
2302 bool is_deferred_open_async(const struct deferred_open_record *rec)
2304 return rec->async_open;
2307 static bool clear_ads(uint32_t create_disposition)
2309 bool ret = false;
2311 switch (create_disposition) {
2312 case FILE_SUPERSEDE:
2313 case FILE_OVERWRITE_IF:
2314 case FILE_OVERWRITE:
2315 ret = true;
2316 break;
2317 default:
2318 break;
2320 return ret;
2323 static int disposition_to_open_flags(uint32_t create_disposition)
2325 int ret = 0;
2328 * Currently we're using FILE_SUPERSEDE as the same as
2329 * FILE_OVERWRITE_IF but they really are
2330 * different. FILE_SUPERSEDE deletes an existing file
2331 * (requiring delete access) then recreates it.
2334 switch (create_disposition) {
2335 case FILE_SUPERSEDE:
2336 case FILE_OVERWRITE_IF:
2338 * If file exists replace/overwrite. If file doesn't
2339 * exist create.
2341 ret = O_CREAT|O_TRUNC;
2342 break;
2344 case FILE_OPEN:
2346 * If file exists open. If file doesn't exist error.
2348 ret = 0;
2349 break;
2351 case FILE_OVERWRITE:
2353 * If file exists overwrite. If file doesn't exist
2354 * error.
2356 ret = O_TRUNC;
2357 break;
2359 case FILE_CREATE:
2361 * If file exists error. If file doesn't exist create.
2363 ret = O_CREAT|O_EXCL;
2364 break;
2366 case FILE_OPEN_IF:
2368 * If file exists open. If file doesn't exist create.
2370 ret = O_CREAT;
2371 break;
2373 return ret;
2376 static int calculate_open_access_flags(uint32_t access_mask,
2377 uint32_t private_flags)
2379 bool need_write, need_read;
2382 * Note that we ignore the append flag as append does not
2383 * mean the same thing under DOS and Unix.
2386 need_write = (access_mask & (FILE_WRITE_DATA | FILE_APPEND_DATA));
2387 if (!need_write) {
2388 return O_RDONLY;
2391 /* DENY_DOS opens are always underlying read-write on the
2392 file handle, no matter what the requested access mask
2393 says. */
2395 need_read =
2396 ((private_flags & NTCREATEX_OPTIONS_PRIVATE_DENY_DOS) ||
2397 access_mask & (FILE_READ_ATTRIBUTES|FILE_READ_DATA|
2398 FILE_READ_EA|FILE_EXECUTE));
2400 if (!need_read) {
2401 return O_WRONLY;
2403 return O_RDWR;
2406 /****************************************************************************
2407 Open a file with a share mode. Passed in an already created files_struct *.
2408 ****************************************************************************/
2410 static NTSTATUS open_file_ntcreate(connection_struct *conn,
2411 struct smb_request *req,
2412 uint32_t access_mask, /* access bits (FILE_READ_DATA etc.) */
2413 uint32_t share_access, /* share constants (FILE_SHARE_READ etc) */
2414 uint32_t create_disposition, /* FILE_OPEN_IF etc. */
2415 uint32_t create_options, /* options such as delete on close. */
2416 uint32_t new_dos_attributes, /* attributes used for new file. */
2417 int oplock_request, /* internal Samba oplock codes. */
2418 struct smb2_lease *lease,
2419 /* Information (FILE_EXISTS etc.) */
2420 uint32_t private_flags, /* Samba specific flags. */
2421 int *pinfo,
2422 files_struct *fsp)
2424 struct smb_filename *smb_fname = fsp->fsp_name;
2425 int flags=0;
2426 int flags2=0;
2427 bool file_existed = VALID_STAT(smb_fname->st);
2428 bool def_acl = False;
2429 bool posix_open = False;
2430 bool new_file_created = False;
2431 bool first_open_attempt = true;
2432 NTSTATUS fsp_open = NT_STATUS_ACCESS_DENIED;
2433 mode_t new_unx_mode = (mode_t)0;
2434 mode_t unx_mode = (mode_t)0;
2435 int info;
2436 uint32_t existing_dos_attributes = 0;
2437 struct timeval request_time = timeval_zero();
2438 struct share_mode_lock *lck = NULL;
2439 uint32_t open_access_mask = access_mask;
2440 NTSTATUS status;
2441 char *parent_dir;
2442 SMB_STRUCT_STAT saved_stat = smb_fname->st;
2443 struct timespec old_write_time;
2444 struct file_id id;
2446 if (conn->printer) {
2448 * Printers are handled completely differently.
2449 * Most of the passed parameters are ignored.
2452 if (pinfo) {
2453 *pinfo = FILE_WAS_CREATED;
2456 DEBUG(10, ("open_file_ntcreate: printer open fname=%s\n",
2457 smb_fname_str_dbg(smb_fname)));
2459 if (!req) {
2460 DEBUG(0,("open_file_ntcreate: printer open without "
2461 "an SMB request!\n"));
2462 return NT_STATUS_INTERNAL_ERROR;
2465 return print_spool_open(fsp, smb_fname->base_name,
2466 req->vuid);
2469 if (!parent_dirname(talloc_tos(), smb_fname->base_name, &parent_dir,
2470 NULL)) {
2471 return NT_STATUS_NO_MEMORY;
2474 if (new_dos_attributes & FILE_FLAG_POSIX_SEMANTICS) {
2475 posix_open = True;
2476 unx_mode = (mode_t)(new_dos_attributes & ~FILE_FLAG_POSIX_SEMANTICS);
2477 new_dos_attributes = 0;
2478 } else {
2479 /* Windows allows a new file to be created and
2480 silently removes a FILE_ATTRIBUTE_DIRECTORY
2481 sent by the client. Do the same. */
2483 new_dos_attributes &= ~FILE_ATTRIBUTE_DIRECTORY;
2485 /* We add FILE_ATTRIBUTE_ARCHIVE to this as this mode is only used if the file is
2486 * created new. */
2487 unx_mode = unix_mode(conn, new_dos_attributes | FILE_ATTRIBUTE_ARCHIVE,
2488 smb_fname, parent_dir);
2491 DEBUG(10, ("open_file_ntcreate: fname=%s, dos_attrs=0x%x "
2492 "access_mask=0x%x share_access=0x%x "
2493 "create_disposition = 0x%x create_options=0x%x "
2494 "unix mode=0%o oplock_request=%d private_flags = 0x%x\n",
2495 smb_fname_str_dbg(smb_fname), new_dos_attributes,
2496 access_mask, share_access, create_disposition,
2497 create_options, (unsigned int)unx_mode, oplock_request,
2498 (unsigned int)private_flags));
2500 if (req == NULL) {
2501 /* Ensure req == NULL means INTERNAL_OPEN_ONLY */
2502 SMB_ASSERT(((oplock_request & INTERNAL_OPEN_ONLY) != 0));
2503 } else {
2504 /* And req != NULL means no INTERNAL_OPEN_ONLY */
2505 SMB_ASSERT(((oplock_request & INTERNAL_OPEN_ONLY) == 0));
2509 * Only non-internal opens can be deferred at all
2512 if (req) {
2513 struct deferred_open_record *open_rec;
2514 if (get_deferred_open_message_state(req,
2515 &request_time,
2516 &open_rec)) {
2517 /* Remember the absolute time of the original
2518 request with this mid. We'll use it later to
2519 see if this has timed out. */
2521 /* If it was an async create retry, the file
2522 didn't exist. */
2524 if (is_deferred_open_async(open_rec)) {
2525 SET_STAT_INVALID(smb_fname->st);
2526 file_existed = false;
2529 /* Ensure we don't reprocess this message. */
2530 remove_deferred_open_message_smb(req->xconn, req->mid);
2532 first_open_attempt = false;
2536 if (!posix_open) {
2537 new_dos_attributes &= SAMBA_ATTRIBUTES_MASK;
2538 if (file_existed) {
2540 * Only use strored DOS attributes for checks
2541 * against requested attributes (below via
2542 * open_match_attributes()), cf bug #11992
2543 * for details. -slow
2545 uint32_t attr = 0;
2547 status = SMB_VFS_GET_DOS_ATTRIBUTES(conn, smb_fname, &attr);
2548 if (NT_STATUS_IS_OK(status)) {
2549 existing_dos_attributes = attr;
2554 /* ignore any oplock requests if oplocks are disabled */
2555 if (!lp_oplocks(SNUM(conn)) ||
2556 IS_VETO_OPLOCK_PATH(conn, smb_fname->base_name)) {
2557 /* Mask off everything except the private Samba bits. */
2558 oplock_request &= SAMBA_PRIVATE_OPLOCK_MASK;
2561 /* this is for OS/2 long file names - say we don't support them */
2562 if (req != NULL && !req->posix_pathnames &&
2563 strstr(smb_fname->base_name,".+,;=[].")) {
2564 /* OS/2 Workplace shell fix may be main code stream in a later
2565 * release. */
2566 DEBUG(5,("open_file_ntcreate: OS/2 long filenames are not "
2567 "supported.\n"));
2568 if (use_nt_status()) {
2569 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
2571 return NT_STATUS_DOS(ERRDOS, ERRcannotopen);
2574 switch( create_disposition ) {
2575 case FILE_OPEN:
2576 /* If file exists open. If file doesn't exist error. */
2577 if (!file_existed) {
2578 DEBUG(5,("open_file_ntcreate: FILE_OPEN "
2579 "requested for file %s and file "
2580 "doesn't exist.\n",
2581 smb_fname_str_dbg(smb_fname)));
2582 errno = ENOENT;
2583 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
2585 break;
2587 case FILE_OVERWRITE:
2588 /* If file exists overwrite. If file doesn't exist
2589 * error. */
2590 if (!file_existed) {
2591 DEBUG(5,("open_file_ntcreate: FILE_OVERWRITE "
2592 "requested for file %s and file "
2593 "doesn't exist.\n",
2594 smb_fname_str_dbg(smb_fname) ));
2595 errno = ENOENT;
2596 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
2598 break;
2600 case FILE_CREATE:
2601 /* If file exists error. If file doesn't exist
2602 * create. */
2603 if (file_existed) {
2604 DEBUG(5,("open_file_ntcreate: FILE_CREATE "
2605 "requested for file %s and file "
2606 "already exists.\n",
2607 smb_fname_str_dbg(smb_fname)));
2608 if (S_ISDIR(smb_fname->st.st_ex_mode)) {
2609 errno = EISDIR;
2610 } else {
2611 errno = EEXIST;
2613 return map_nt_error_from_unix(errno);
2615 break;
2617 case FILE_SUPERSEDE:
2618 case FILE_OVERWRITE_IF:
2619 case FILE_OPEN_IF:
2620 break;
2621 default:
2622 return NT_STATUS_INVALID_PARAMETER;
2625 flags2 = disposition_to_open_flags(create_disposition);
2627 /* We only care about matching attributes on file exists and
2628 * overwrite. */
2630 if (!posix_open && file_existed &&
2631 ((create_disposition == FILE_OVERWRITE) ||
2632 (create_disposition == FILE_OVERWRITE_IF))) {
2633 if (!open_match_attributes(conn, existing_dos_attributes,
2634 new_dos_attributes,
2635 smb_fname->st.st_ex_mode,
2636 unx_mode, &new_unx_mode)) {
2637 DEBUG(5,("open_file_ntcreate: attributes missmatch "
2638 "for file %s (%x %x) (0%o, 0%o)\n",
2639 smb_fname_str_dbg(smb_fname),
2640 existing_dos_attributes,
2641 new_dos_attributes,
2642 (unsigned int)smb_fname->st.st_ex_mode,
2643 (unsigned int)unx_mode ));
2644 errno = EACCES;
2645 return NT_STATUS_ACCESS_DENIED;
2649 status = smbd_calculate_access_mask(conn, smb_fname,
2650 false,
2651 access_mask,
2652 &access_mask);
2653 if (!NT_STATUS_IS_OK(status)) {
2654 DEBUG(10, ("open_file_ntcreate: smbd_calculate_access_mask "
2655 "on file %s returned %s\n",
2656 smb_fname_str_dbg(smb_fname), nt_errstr(status)));
2657 return status;
2660 open_access_mask = access_mask;
2662 if (flags2 & O_TRUNC) {
2663 open_access_mask |= FILE_WRITE_DATA; /* This will cause oplock breaks. */
2666 DEBUG(10, ("open_file_ntcreate: fname=%s, after mapping "
2667 "access_mask=0x%x\n", smb_fname_str_dbg(smb_fname),
2668 access_mask));
2671 * Note that we ignore the append flag as append does not
2672 * mean the same thing under DOS and Unix.
2675 flags = calculate_open_access_flags(access_mask, private_flags);
2678 * Currently we only look at FILE_WRITE_THROUGH for create options.
2681 #if defined(O_SYNC)
2682 if ((create_options & FILE_WRITE_THROUGH) && lp_strict_sync(SNUM(conn))) {
2683 flags2 |= O_SYNC;
2685 #endif /* O_SYNC */
2687 if (posix_open && (access_mask & FILE_APPEND_DATA)) {
2688 flags2 |= O_APPEND;
2691 if (!posix_open && !CAN_WRITE(conn)) {
2693 * We should really return a permission denied error if either
2694 * O_CREAT or O_TRUNC are set, but for compatibility with
2695 * older versions of Samba we just AND them out.
2697 flags2 &= ~(O_CREAT|O_TRUNC);
2700 if (first_open_attempt && lp_kernel_oplocks(SNUM(conn))) {
2702 * With kernel oplocks the open breaking an oplock
2703 * blocks until the oplock holder has given up the
2704 * oplock or closed the file. We prevent this by first
2705 * trying to open the file with O_NONBLOCK (see "man
2706 * fcntl" on Linux). For the second try, triggered by
2707 * an oplock break response, we do not need this
2708 * anymore.
2710 * This is true under the assumption that only Samba
2711 * requests kernel oplocks. Once someone else like
2712 * NFSv4 starts to use that API, we will have to
2713 * modify this by communicating with the NFSv4 server.
2715 flags2 |= O_NONBLOCK;
2719 * Ensure we can't write on a read-only share or file.
2722 if (flags != O_RDONLY && file_existed &&
2723 (!CAN_WRITE(conn) || IS_DOS_READONLY(existing_dos_attributes))) {
2724 DEBUG(5,("open_file_ntcreate: write access requested for "
2725 "file %s on read only %s\n",
2726 smb_fname_str_dbg(smb_fname),
2727 !CAN_WRITE(conn) ? "share" : "file" ));
2728 errno = EACCES;
2729 return NT_STATUS_ACCESS_DENIED;
2732 fsp->file_id = vfs_file_id_from_sbuf(conn, &smb_fname->st);
2733 fsp->share_access = share_access;
2734 fsp->fh->private_options = private_flags;
2735 fsp->access_mask = open_access_mask; /* We change this to the
2736 * requested access_mask after
2737 * the open is done. */
2738 if (posix_open) {
2739 fsp->posix_flags |= FSP_POSIX_FLAGS_ALL;
2742 if (timeval_is_zero(&request_time)) {
2743 request_time = fsp->open_time;
2747 * Ensure we pay attention to default ACLs on directories if required.
2750 if ((flags2 & O_CREAT) && lp_inherit_acls(SNUM(conn)) &&
2751 (def_acl = directory_has_default_acl(conn, parent_dir))) {
2752 unx_mode = (0777 & lp_create_mask(SNUM(conn)));
2755 DEBUG(4,("calling open_file with flags=0x%X flags2=0x%X mode=0%o, "
2756 "access_mask = 0x%x, open_access_mask = 0x%x\n",
2757 (unsigned int)flags, (unsigned int)flags2,
2758 (unsigned int)unx_mode, (unsigned int)access_mask,
2759 (unsigned int)open_access_mask));
2761 fsp_open = open_file(fsp, conn, req, parent_dir,
2762 flags|flags2, unx_mode, access_mask,
2763 open_access_mask, &new_file_created);
2765 if (NT_STATUS_EQUAL(fsp_open, NT_STATUS_NETWORK_BUSY)) {
2766 struct deferred_open_record state;
2769 * EWOULDBLOCK/EAGAIN maps to NETWORK_BUSY.
2771 if (file_existed && S_ISFIFO(fsp->fsp_name->st.st_ex_mode)) {
2772 DEBUG(10, ("FIFO busy\n"));
2773 return NT_STATUS_NETWORK_BUSY;
2775 if (req == NULL) {
2776 DEBUG(10, ("Internal open busy\n"));
2777 return NT_STATUS_NETWORK_BUSY;
2781 * From here on we assume this is an oplock break triggered
2784 lck = get_existing_share_mode_lock(talloc_tos(), fsp->file_id);
2785 if (lck == NULL) {
2786 state.delayed_for_oplocks = false;
2787 state.async_open = false;
2788 state.id = fsp->file_id;
2789 defer_open(NULL, request_time, timeval_set(0, 0),
2790 req, &state);
2791 DEBUG(10, ("No share mode lock found after "
2792 "EWOULDBLOCK, retrying sync\n"));
2793 return NT_STATUS_SHARING_VIOLATION;
2796 if (!validate_oplock_types(lck)) {
2797 smb_panic("validate_oplock_types failed");
2800 if (delay_for_oplock(fsp, 0, lease, lck, false,
2801 create_disposition, first_open_attempt)) {
2802 schedule_defer_open(lck, fsp->file_id, request_time,
2803 req);
2804 TALLOC_FREE(lck);
2805 DEBUG(10, ("Sent oplock break request to kernel "
2806 "oplock holder\n"));
2807 return NT_STATUS_SHARING_VIOLATION;
2811 * No oplock from Samba around. Immediately retry with
2812 * a blocking open.
2814 state.delayed_for_oplocks = false;
2815 state.async_open = false;
2816 state.id = fsp->file_id;
2817 defer_open(lck, request_time, timeval_set(0, 0), req, &state);
2818 TALLOC_FREE(lck);
2819 DEBUG(10, ("No Samba oplock around after EWOULDBLOCK. "
2820 "Retrying sync\n"));
2821 return NT_STATUS_SHARING_VIOLATION;
2824 if (!NT_STATUS_IS_OK(fsp_open)) {
2825 if (NT_STATUS_EQUAL(fsp_open, NT_STATUS_RETRY)) {
2826 schedule_async_open(request_time, req);
2828 return fsp_open;
2831 if (new_file_created) {
2833 * As we atomically create using O_CREAT|O_EXCL,
2834 * then if new_file_created is true, then
2835 * file_existed *MUST* have been false (even
2836 * if the file was previously detected as being
2837 * there).
2839 file_existed = false;
2842 if (file_existed && !check_same_dev_ino(&saved_stat, &smb_fname->st)) {
2844 * The file did exist, but some other (local or NFS)
2845 * process either renamed/unlinked and re-created the
2846 * file with different dev/ino after we walked the path,
2847 * but before we did the open. We could retry the
2848 * open but it's a rare enough case it's easier to
2849 * just fail the open to prevent creating any problems
2850 * in the open file db having the wrong dev/ino key.
2852 fd_close(fsp);
2853 DEBUG(1,("open_file_ntcreate: file %s - dev/ino mismatch. "
2854 "Old (dev=0x%llu, ino =0x%llu). "
2855 "New (dev=0x%llu, ino=0x%llu). Failing open "
2856 " with NT_STATUS_ACCESS_DENIED.\n",
2857 smb_fname_str_dbg(smb_fname),
2858 (unsigned long long)saved_stat.st_ex_dev,
2859 (unsigned long long)saved_stat.st_ex_ino,
2860 (unsigned long long)smb_fname->st.st_ex_dev,
2861 (unsigned long long)smb_fname->st.st_ex_ino));
2862 return NT_STATUS_ACCESS_DENIED;
2865 old_write_time = smb_fname->st.st_ex_mtime;
2868 * Deal with the race condition where two smbd's detect the
2869 * file doesn't exist and do the create at the same time. One
2870 * of them will win and set a share mode, the other (ie. this
2871 * one) should check if the requested share mode for this
2872 * create is allowed.
2876 * Now the file exists and fsp is successfully opened,
2877 * fsp->dev and fsp->inode are valid and should replace the
2878 * dev=0,inode=0 from a non existent file. Spotted by
2879 * Nadav Danieli <nadavd@exanet.com>. JRA.
2882 id = fsp->file_id;
2884 lck = get_share_mode_lock(talloc_tos(), id,
2885 conn->connectpath,
2886 smb_fname, &old_write_time);
2888 if (lck == NULL) {
2889 DEBUG(0, ("open_file_ntcreate: Could not get share "
2890 "mode lock for %s\n",
2891 smb_fname_str_dbg(smb_fname)));
2892 fd_close(fsp);
2893 return NT_STATUS_SHARING_VIOLATION;
2896 /* Get the types we need to examine. */
2897 if (!validate_oplock_types(lck)) {
2898 smb_panic("validate_oplock_types failed");
2901 if (has_delete_on_close(lck, fsp->name_hash)) {
2902 TALLOC_FREE(lck);
2903 fd_close(fsp);
2904 return NT_STATUS_DELETE_PENDING;
2907 status = open_mode_check(conn, lck,
2908 access_mask, share_access);
2910 if (NT_STATUS_EQUAL(status, NT_STATUS_SHARING_VIOLATION) ||
2911 (lck->data->num_share_modes > 0)) {
2913 * This comes from ancient times out of open_mode_check. I
2914 * have no clue whether this is still necessary. I can't think
2915 * of a case where this would actually matter further down in
2916 * this function. I leave it here for further investigation
2917 * :-)
2919 file_existed = true;
2922 if ((req != NULL) &&
2923 delay_for_oplock(
2924 fsp, oplock_request, lease, lck,
2925 NT_STATUS_EQUAL(status, NT_STATUS_SHARING_VIOLATION),
2926 create_disposition, first_open_attempt)) {
2927 schedule_defer_open(lck, fsp->file_id, request_time, req);
2928 TALLOC_FREE(lck);
2929 fd_close(fsp);
2930 return NT_STATUS_SHARING_VIOLATION;
2933 if (!NT_STATUS_IS_OK(status)) {
2934 uint32_t can_access_mask;
2935 bool can_access = True;
2937 SMB_ASSERT(NT_STATUS_EQUAL(status, NT_STATUS_SHARING_VIOLATION));
2939 /* Check if this can be done with the deny_dos and fcb
2940 * calls. */
2941 if (private_flags &
2942 (NTCREATEX_OPTIONS_PRIVATE_DENY_DOS|
2943 NTCREATEX_OPTIONS_PRIVATE_DENY_FCB)) {
2944 if (req == NULL) {
2945 DEBUG(0, ("DOS open without an SMB "
2946 "request!\n"));
2947 TALLOC_FREE(lck);
2948 fd_close(fsp);
2949 return NT_STATUS_INTERNAL_ERROR;
2952 /* Use the client requested access mask here,
2953 * not the one we open with. */
2954 status = fcb_or_dos_open(req,
2955 conn,
2956 fsp,
2957 smb_fname,
2959 req->smbpid,
2960 req->vuid,
2961 access_mask,
2962 share_access,
2963 create_options);
2965 if (NT_STATUS_IS_OK(status)) {
2966 TALLOC_FREE(lck);
2967 if (pinfo) {
2968 *pinfo = FILE_WAS_OPENED;
2970 return NT_STATUS_OK;
2975 * This next line is a subtlety we need for
2976 * MS-Access. If a file open will fail due to share
2977 * permissions and also for security (access) reasons,
2978 * we need to return the access failed error, not the
2979 * share error. We can't open the file due to kernel
2980 * oplock deadlock (it's possible we failed above on
2981 * the open_mode_check()) so use a userspace check.
2984 if (flags & O_RDWR) {
2985 can_access_mask = FILE_READ_DATA|FILE_WRITE_DATA;
2986 } else if (flags & O_WRONLY) {
2987 can_access_mask = FILE_WRITE_DATA;
2988 } else {
2989 can_access_mask = FILE_READ_DATA;
2992 if (((can_access_mask & FILE_WRITE_DATA) &&
2993 !CAN_WRITE(conn)) ||
2994 !NT_STATUS_IS_OK(smbd_check_access_rights(conn,
2995 smb_fname,
2996 false,
2997 can_access_mask))) {
2998 can_access = False;
3002 * If we're returning a share violation, ensure we
3003 * cope with the braindead 1 second delay (SMB1 only).
3006 if (!(oplock_request & INTERNAL_OPEN_ONLY) &&
3007 !conn->sconn->using_smb2 &&
3008 lp_defer_sharing_violations()) {
3009 struct timeval timeout;
3010 struct deferred_open_record state;
3011 int timeout_usecs;
3013 /* this is a hack to speed up torture tests
3014 in 'make test' */
3015 timeout_usecs = lp_parm_int(SNUM(conn),
3016 "smbd","sharedelay",
3017 SHARING_VIOLATION_USEC_WAIT);
3019 /* This is a relative time, added to the absolute
3020 request_time value to get the absolute timeout time.
3021 Note that if this is the second or greater time we enter
3022 this codepath for this particular request mid then
3023 request_time is left as the absolute time of the *first*
3024 time this request mid was processed. This is what allows
3025 the request to eventually time out. */
3027 timeout = timeval_set(0, timeout_usecs);
3029 /* Nothing actually uses state.delayed_for_oplocks
3030 but it's handy to differentiate in debug messages
3031 between a 30 second delay due to oplock break, and
3032 a 1 second delay for share mode conflicts. */
3034 state.delayed_for_oplocks = False;
3035 state.async_open = false;
3036 state.id = id;
3038 if ((req != NULL)
3039 && !request_timed_out(request_time,
3040 timeout)) {
3041 defer_open(lck, request_time, timeout,
3042 req, &state);
3046 TALLOC_FREE(lck);
3047 fd_close(fsp);
3048 if (can_access) {
3050 * We have detected a sharing violation here
3051 * so return the correct error code
3053 status = NT_STATUS_SHARING_VIOLATION;
3054 } else {
3055 status = NT_STATUS_ACCESS_DENIED;
3057 return status;
3060 /* Should we atomically (to the client at least) truncate ? */
3061 if ((!new_file_created) &&
3062 (flags2 & O_TRUNC) &&
3063 (!S_ISFIFO(fsp->fsp_name->st.st_ex_mode))) {
3064 int ret;
3066 ret = vfs_set_filelen(fsp, 0);
3067 if (ret != 0) {
3068 status = map_nt_error_from_unix(errno);
3069 TALLOC_FREE(lck);
3070 fd_close(fsp);
3071 return status;
3076 * We have the share entry *locked*.....
3079 /* Delete streams if create_disposition requires it */
3080 if (!new_file_created && clear_ads(create_disposition) &&
3081 !is_ntfs_stream_smb_fname(smb_fname)) {
3082 status = delete_all_streams(conn, smb_fname);
3083 if (!NT_STATUS_IS_OK(status)) {
3084 TALLOC_FREE(lck);
3085 fd_close(fsp);
3086 return status;
3090 /* note that we ignore failure for the following. It is
3091 basically a hack for NFS, and NFS will never set one of
3092 these only read them. Nobody but Samba can ever set a deny
3093 mode and we have already checked our more authoritative
3094 locking database for permission to set this deny mode. If
3095 the kernel refuses the operations then the kernel is wrong.
3096 note that GPFS supports it as well - jmcd */
3098 if (fsp->fh->fd != -1 && lp_kernel_share_modes(SNUM(conn))) {
3099 int ret_flock;
3101 * Beware: streams implementing VFS modules may
3102 * implement streams in a way that fsp will have the
3103 * basefile open in the fsp fd, so lacking a distinct
3104 * fd for the stream kernel_flock will apply on the
3105 * basefile which is wrong. The actual check is
3106 * deffered to the VFS module implementing the
3107 * kernel_flock call.
3109 ret_flock = SMB_VFS_KERNEL_FLOCK(fsp, share_access, access_mask);
3110 if(ret_flock == -1 ){
3112 TALLOC_FREE(lck);
3113 fd_close(fsp);
3115 return NT_STATUS_SHARING_VIOLATION;
3118 fsp->kernel_share_modes_taken = true;
3122 * At this point onwards, we can guarantee that the share entry
3123 * is locked, whether we created the file or not, and that the
3124 * deny mode is compatible with all current opens.
3128 * According to Samba4, SEC_FILE_READ_ATTRIBUTE is always granted,
3129 * but we don't have to store this - just ignore it on access check.
3131 if (conn->sconn->using_smb2) {
3133 * SMB2 doesn't return it (according to Microsoft tests).
3134 * Test Case: TestSuite_ScenarioNo009GrantedAccessTestS0
3135 * File created with access = 0x7 (Read, Write, Delete)
3136 * Query Info on file returns 0x87 (Read, Write, Delete, Read Attributes)
3138 fsp->access_mask = access_mask;
3139 } else {
3140 /* But SMB1 does. */
3141 fsp->access_mask = access_mask | FILE_READ_ATTRIBUTES;
3144 if (file_existed) {
3146 * stat opens on existing files don't get oplocks.
3147 * They can get leases.
3149 * Note that we check for stat open on the *open_access_mask*,
3150 * i.e. the access mask we actually used to do the open,
3151 * not the one the client asked for (which is in
3152 * fsp->access_mask). This is due to the fact that
3153 * FILE_OVERWRITE and FILE_OVERWRITE_IF add in O_TRUNC,
3154 * which adds FILE_WRITE_DATA to open_access_mask.
3156 if (is_stat_open(open_access_mask) && lease == NULL) {
3157 oplock_request = NO_OPLOCK;
3161 if (new_file_created) {
3162 info = FILE_WAS_CREATED;
3163 } else {
3164 if (flags2 & O_TRUNC) {
3165 info = FILE_WAS_OVERWRITTEN;
3166 } else {
3167 info = FILE_WAS_OPENED;
3171 if (pinfo) {
3172 *pinfo = info;
3176 * Setup the oplock info in both the shared memory and
3177 * file structs.
3179 status = grant_fsp_oplock_type(req, fsp, lck, oplock_request, lease);
3180 if (!NT_STATUS_IS_OK(status)) {
3181 TALLOC_FREE(lck);
3182 fd_close(fsp);
3183 return status;
3186 /* Handle strange delete on close create semantics. */
3187 if (create_options & FILE_DELETE_ON_CLOSE) {
3189 status = can_set_delete_on_close(fsp, new_dos_attributes);
3191 if (!NT_STATUS_IS_OK(status)) {
3192 /* Remember to delete the mode we just added. */
3193 del_share_mode(lck, fsp);
3194 TALLOC_FREE(lck);
3195 fd_close(fsp);
3196 return status;
3198 /* Note that here we set the *inital* delete on close flag,
3199 not the regular one. The magic gets handled in close. */
3200 fsp->initial_delete_on_close = True;
3203 if (info != FILE_WAS_OPENED) {
3204 /* Overwritten files should be initially set as archive */
3205 if ((info == FILE_WAS_OVERWRITTEN && lp_map_archive(SNUM(conn))) ||
3206 lp_store_dos_attributes(SNUM(conn))) {
3207 if (!posix_open) {
3208 if (file_set_dosmode(conn, smb_fname,
3209 new_dos_attributes | FILE_ATTRIBUTE_ARCHIVE,
3210 parent_dir, true) == 0) {
3211 unx_mode = smb_fname->st.st_ex_mode;
3217 /* Determine sparse flag. */
3218 if (posix_open) {
3219 /* POSIX opens are sparse by default. */
3220 fsp->is_sparse = true;
3221 } else {
3222 fsp->is_sparse = (file_existed &&
3223 (existing_dos_attributes & FILE_ATTRIBUTE_SPARSE));
3227 * Take care of inherited ACLs on created files - if default ACL not
3228 * selected.
3231 if (!posix_open && new_file_created && !def_acl) {
3233 int saved_errno = errno; /* We might get ENOSYS in the next
3234 * call.. */
3236 if (SMB_VFS_FCHMOD_ACL(fsp, unx_mode) == -1 &&
3237 errno == ENOSYS) {
3238 errno = saved_errno; /* Ignore ENOSYS */
3241 } else if (new_unx_mode) {
3243 int ret = -1;
3245 /* Attributes need changing. File already existed. */
3248 int saved_errno = errno; /* We might get ENOSYS in the
3249 * next call.. */
3250 ret = SMB_VFS_FCHMOD_ACL(fsp, new_unx_mode);
3252 if (ret == -1 && errno == ENOSYS) {
3253 errno = saved_errno; /* Ignore ENOSYS */
3254 } else {
3255 DEBUG(5, ("open_file_ntcreate: reset "
3256 "attributes of file %s to 0%o\n",
3257 smb_fname_str_dbg(smb_fname),
3258 (unsigned int)new_unx_mode));
3259 ret = 0; /* Don't do the fchmod below. */
3263 if ((ret == -1) &&
3264 (SMB_VFS_FCHMOD(fsp, new_unx_mode) == -1))
3265 DEBUG(5, ("open_file_ntcreate: failed to reset "
3266 "attributes of file %s to 0%o\n",
3267 smb_fname_str_dbg(smb_fname),
3268 (unsigned int)new_unx_mode));
3273 * Deal with other opens having a modified write time.
3275 struct timespec write_time = get_share_mode_write_time(lck);
3277 if (!null_timespec(write_time)) {
3278 update_stat_ex_mtime(&fsp->fsp_name->st, write_time);
3282 TALLOC_FREE(lck);
3284 return NT_STATUS_OK;
3287 static NTSTATUS mkdir_internal(connection_struct *conn,
3288 struct smb_filename *smb_dname,
3289 uint32_t file_attributes)
3291 mode_t mode;
3292 char *parent_dir = NULL;
3293 NTSTATUS status;
3294 bool posix_open = false;
3295 bool need_re_stat = false;
3296 uint32_t access_mask = SEC_DIR_ADD_SUBDIR;
3298 if (!CAN_WRITE(conn) || (access_mask & ~(conn->share_access))) {
3299 DEBUG(5,("mkdir_internal: failing share access "
3300 "%s\n", lp_servicename(talloc_tos(), SNUM(conn))));
3301 return NT_STATUS_ACCESS_DENIED;
3304 if (!parent_dirname(talloc_tos(), smb_dname->base_name, &parent_dir,
3305 NULL)) {
3306 return NT_STATUS_NO_MEMORY;
3309 if (file_attributes & FILE_FLAG_POSIX_SEMANTICS) {
3310 posix_open = true;
3311 mode = (mode_t)(file_attributes & ~FILE_FLAG_POSIX_SEMANTICS);
3312 } else {
3313 mode = unix_mode(conn, FILE_ATTRIBUTE_DIRECTORY, smb_dname, parent_dir);
3316 status = check_parent_access(conn,
3317 smb_dname,
3318 access_mask);
3319 if(!NT_STATUS_IS_OK(status)) {
3320 DEBUG(5,("mkdir_internal: check_parent_access "
3321 "on directory %s for path %s returned %s\n",
3322 parent_dir,
3323 smb_dname->base_name,
3324 nt_errstr(status) ));
3325 return status;
3328 if (SMB_VFS_MKDIR(conn, smb_dname, mode) != 0) {
3329 return map_nt_error_from_unix(errno);
3332 /* Ensure we're checking for a symlink here.... */
3333 /* We don't want to get caught by a symlink racer. */
3335 if (SMB_VFS_LSTAT(conn, smb_dname) == -1) {
3336 DEBUG(2, ("Could not stat directory '%s' just created: %s\n",
3337 smb_fname_str_dbg(smb_dname), strerror(errno)));
3338 return map_nt_error_from_unix(errno);
3341 if (!S_ISDIR(smb_dname->st.st_ex_mode)) {
3342 DEBUG(0, ("Directory '%s' just created is not a directory !\n",
3343 smb_fname_str_dbg(smb_dname)));
3344 return NT_STATUS_NOT_A_DIRECTORY;
3347 if (lp_store_dos_attributes(SNUM(conn))) {
3348 if (!posix_open) {
3349 file_set_dosmode(conn, smb_dname,
3350 file_attributes | FILE_ATTRIBUTE_DIRECTORY,
3351 parent_dir, true);
3355 if (lp_inherit_permissions(SNUM(conn))) {
3356 inherit_access_posix_acl(conn, parent_dir,
3357 smb_dname->base_name, mode);
3358 need_re_stat = true;
3361 if (!posix_open) {
3363 * Check if high bits should have been set,
3364 * then (if bits are missing): add them.
3365 * Consider bits automagically set by UNIX, i.e. SGID bit from parent
3366 * dir.
3368 if ((mode & ~(S_IRWXU|S_IRWXG|S_IRWXO)) &&
3369 (mode & ~smb_dname->st.st_ex_mode)) {
3370 SMB_VFS_CHMOD(conn, smb_dname,
3371 (smb_dname->st.st_ex_mode |
3372 (mode & ~smb_dname->st.st_ex_mode)));
3373 need_re_stat = true;
3377 /* Change the owner if required. */
3378 if (lp_inherit_owner(SNUM(conn))) {
3379 change_dir_owner_to_parent(conn, parent_dir,
3380 smb_dname->base_name,
3381 &smb_dname->st);
3382 need_re_stat = true;
3385 if (need_re_stat) {
3386 if (SMB_VFS_LSTAT(conn, smb_dname) == -1) {
3387 DEBUG(2, ("Could not stat directory '%s' just created: %s\n",
3388 smb_fname_str_dbg(smb_dname), strerror(errno)));
3389 return map_nt_error_from_unix(errno);
3393 notify_fname(conn, NOTIFY_ACTION_ADDED, FILE_NOTIFY_CHANGE_DIR_NAME,
3394 smb_dname->base_name);
3396 return NT_STATUS_OK;
3399 /****************************************************************************
3400 Open a directory from an NT SMB call.
3401 ****************************************************************************/
3403 static NTSTATUS open_directory(connection_struct *conn,
3404 struct smb_request *req,
3405 struct smb_filename *smb_dname,
3406 uint32_t access_mask,
3407 uint32_t share_access,
3408 uint32_t create_disposition,
3409 uint32_t create_options,
3410 uint32_t file_attributes,
3411 int *pinfo,
3412 files_struct **result)
3414 files_struct *fsp = NULL;
3415 bool dir_existed = VALID_STAT(smb_dname->st) ? True : False;
3416 struct share_mode_lock *lck = NULL;
3417 NTSTATUS status;
3418 struct timespec mtimespec;
3419 int info = 0;
3420 bool ok;
3422 if (is_ntfs_stream_smb_fname(smb_dname)) {
3423 DEBUG(2, ("open_directory: %s is a stream name!\n",
3424 smb_fname_str_dbg(smb_dname)));
3425 return NT_STATUS_NOT_A_DIRECTORY;
3428 if (!(file_attributes & FILE_FLAG_POSIX_SEMANTICS)) {
3429 /* Ensure we have a directory attribute. */
3430 file_attributes |= FILE_ATTRIBUTE_DIRECTORY;
3433 DEBUG(5,("open_directory: opening directory %s, access_mask = 0x%x, "
3434 "share_access = 0x%x create_options = 0x%x, "
3435 "create_disposition = 0x%x, file_attributes = 0x%x\n",
3436 smb_fname_str_dbg(smb_dname),
3437 (unsigned int)access_mask,
3438 (unsigned int)share_access,
3439 (unsigned int)create_options,
3440 (unsigned int)create_disposition,
3441 (unsigned int)file_attributes));
3443 status = smbd_calculate_access_mask(conn, smb_dname, false,
3444 access_mask, &access_mask);
3445 if (!NT_STATUS_IS_OK(status)) {
3446 DEBUG(10, ("open_directory: smbd_calculate_access_mask "
3447 "on file %s returned %s\n",
3448 smb_fname_str_dbg(smb_dname),
3449 nt_errstr(status)));
3450 return status;
3453 if ((access_mask & SEC_FLAG_SYSTEM_SECURITY) &&
3454 !security_token_has_privilege(get_current_nttok(conn),
3455 SEC_PRIV_SECURITY)) {
3456 DEBUG(10, ("open_directory: open on %s "
3457 "failed - SEC_FLAG_SYSTEM_SECURITY denied.\n",
3458 smb_fname_str_dbg(smb_dname)));
3459 return NT_STATUS_PRIVILEGE_NOT_HELD;
3462 switch( create_disposition ) {
3463 case FILE_OPEN:
3465 if (!dir_existed) {
3466 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3469 info = FILE_WAS_OPENED;
3470 break;
3472 case FILE_CREATE:
3474 /* If directory exists error. If directory doesn't
3475 * exist create. */
3477 if (dir_existed) {
3478 status = NT_STATUS_OBJECT_NAME_COLLISION;
3479 DEBUG(2, ("open_directory: unable to create "
3480 "%s. Error was %s\n",
3481 smb_fname_str_dbg(smb_dname),
3482 nt_errstr(status)));
3483 return status;
3486 status = mkdir_internal(conn, smb_dname,
3487 file_attributes);
3489 if (!NT_STATUS_IS_OK(status)) {
3490 DEBUG(2, ("open_directory: unable to create "
3491 "%s. Error was %s\n",
3492 smb_fname_str_dbg(smb_dname),
3493 nt_errstr(status)));
3494 return status;
3497 info = FILE_WAS_CREATED;
3498 break;
3500 case FILE_OPEN_IF:
3502 * If directory exists open. If directory doesn't
3503 * exist create.
3506 if (dir_existed) {
3507 status = NT_STATUS_OK;
3508 info = FILE_WAS_OPENED;
3509 } else {
3510 status = mkdir_internal(conn, smb_dname,
3511 file_attributes);
3513 if (NT_STATUS_IS_OK(status)) {
3514 info = FILE_WAS_CREATED;
3515 } else {
3516 /* Cope with create race. */
3517 if (!NT_STATUS_EQUAL(status,
3518 NT_STATUS_OBJECT_NAME_COLLISION)) {
3519 DEBUG(2, ("open_directory: unable to create "
3520 "%s. Error was %s\n",
3521 smb_fname_str_dbg(smb_dname),
3522 nt_errstr(status)));
3523 return status;
3527 * If mkdir_internal() returned
3528 * NT_STATUS_OBJECT_NAME_COLLISION
3529 * we still must lstat the path.
3532 if (SMB_VFS_LSTAT(conn, smb_dname)
3533 == -1) {
3534 DEBUG(2, ("Could not stat "
3535 "directory '%s' just "
3536 "opened: %s\n",
3537 smb_fname_str_dbg(
3538 smb_dname),
3539 strerror(errno)));
3540 return map_nt_error_from_unix(
3541 errno);
3544 info = FILE_WAS_OPENED;
3548 break;
3550 case FILE_SUPERSEDE:
3551 case FILE_OVERWRITE:
3552 case FILE_OVERWRITE_IF:
3553 default:
3554 DEBUG(5,("open_directory: invalid create_disposition "
3555 "0x%x for directory %s\n",
3556 (unsigned int)create_disposition,
3557 smb_fname_str_dbg(smb_dname)));
3558 return NT_STATUS_INVALID_PARAMETER;
3561 if(!S_ISDIR(smb_dname->st.st_ex_mode)) {
3562 DEBUG(5,("open_directory: %s is not a directory !\n",
3563 smb_fname_str_dbg(smb_dname)));
3564 return NT_STATUS_NOT_A_DIRECTORY;
3567 if (info == FILE_WAS_OPENED) {
3568 status = smbd_check_access_rights(conn,
3569 smb_dname,
3570 false,
3571 access_mask);
3572 if (!NT_STATUS_IS_OK(status)) {
3573 DEBUG(10, ("open_directory: smbd_check_access_rights on "
3574 "file %s failed with %s\n",
3575 smb_fname_str_dbg(smb_dname),
3576 nt_errstr(status)));
3577 return status;
3581 status = file_new(req, conn, &fsp);
3582 if(!NT_STATUS_IS_OK(status)) {
3583 return status;
3587 * Setup the files_struct for it.
3590 fsp->file_id = vfs_file_id_from_sbuf(conn, &smb_dname->st);
3591 fsp->vuid = req ? req->vuid : UID_FIELD_INVALID;
3592 fsp->file_pid = req ? req->smbpid : 0;
3593 fsp->can_lock = False;
3594 fsp->can_read = False;
3595 fsp->can_write = False;
3597 fsp->share_access = share_access;
3598 fsp->fh->private_options = 0;
3600 * According to Samba4, SEC_FILE_READ_ATTRIBUTE is always granted,
3602 fsp->access_mask = access_mask | FILE_READ_ATTRIBUTES;
3603 fsp->print_file = NULL;
3604 fsp->modified = False;
3605 fsp->oplock_type = NO_OPLOCK;
3606 fsp->sent_oplock_break = NO_BREAK_SENT;
3607 fsp->is_directory = True;
3608 if (file_attributes & FILE_FLAG_POSIX_SEMANTICS) {
3609 fsp->posix_flags |= FSP_POSIX_FLAGS_ALL;
3611 status = fsp_set_smb_fname(fsp, smb_dname);
3612 if (!NT_STATUS_IS_OK(status)) {
3613 file_free(req, fsp);
3614 return status;
3617 /* Don't store old timestamps for directory
3618 handles in the internal database. We don't
3619 update them in there if new objects
3620 are creaded in the directory. Currently
3621 we only update timestamps on file writes.
3622 See bug #9870.
3624 ZERO_STRUCT(mtimespec);
3626 if (access_mask & (FILE_LIST_DIRECTORY|
3627 FILE_ADD_FILE|
3628 FILE_ADD_SUBDIRECTORY|
3629 FILE_TRAVERSE|
3630 DELETE_ACCESS|
3631 FILE_DELETE_CHILD)) {
3632 #ifdef O_DIRECTORY
3633 status = fd_open(conn, fsp, O_RDONLY|O_DIRECTORY, 0);
3634 #else
3635 /* POSIX allows us to open a directory with O_RDONLY. */
3636 status = fd_open(conn, fsp, O_RDONLY, 0);
3637 #endif
3638 if (!NT_STATUS_IS_OK(status)) {
3639 DEBUG(5, ("open_directory: Could not open fd for "
3640 "%s (%s)\n",
3641 smb_fname_str_dbg(smb_dname),
3642 nt_errstr(status)));
3643 file_free(req, fsp);
3644 return status;
3646 } else {
3647 fsp->fh->fd = -1;
3648 DEBUG(10, ("Not opening Directory %s\n",
3649 smb_fname_str_dbg(smb_dname)));
3652 status = vfs_stat_fsp(fsp);
3653 if (!NT_STATUS_IS_OK(status)) {
3654 fd_close(fsp);
3655 file_free(req, fsp);
3656 return status;
3659 if(!S_ISDIR(fsp->fsp_name->st.st_ex_mode)) {
3660 DEBUG(5,("open_directory: %s is not a directory !\n",
3661 smb_fname_str_dbg(smb_dname)));
3662 fd_close(fsp);
3663 file_free(req, fsp);
3664 return NT_STATUS_NOT_A_DIRECTORY;
3667 /* Ensure there was no race condition. We need to check
3668 * dev/inode but not permissions, as these can change
3669 * legitimately */
3670 if (!check_same_dev_ino(&smb_dname->st, &fsp->fsp_name->st)) {
3671 DEBUG(5,("open_directory: stat struct differs for "
3672 "directory %s.\n",
3673 smb_fname_str_dbg(smb_dname)));
3674 fd_close(fsp);
3675 file_free(req, fsp);
3676 return NT_STATUS_ACCESS_DENIED;
3679 lck = get_share_mode_lock(talloc_tos(), fsp->file_id,
3680 conn->connectpath, smb_dname,
3681 &mtimespec);
3683 if (lck == NULL) {
3684 DEBUG(0, ("open_directory: Could not get share mode lock for "
3685 "%s\n", smb_fname_str_dbg(smb_dname)));
3686 fd_close(fsp);
3687 file_free(req, fsp);
3688 return NT_STATUS_SHARING_VIOLATION;
3691 if (has_delete_on_close(lck, fsp->name_hash)) {
3692 TALLOC_FREE(lck);
3693 fd_close(fsp);
3694 file_free(req, fsp);
3695 return NT_STATUS_DELETE_PENDING;
3698 status = open_mode_check(conn, lck,
3699 access_mask, share_access);
3701 if (!NT_STATUS_IS_OK(status)) {
3702 TALLOC_FREE(lck);
3703 fd_close(fsp);
3704 file_free(req, fsp);
3705 return status;
3708 ok = set_share_mode(lck, fsp, get_current_uid(conn),
3709 req ? req->mid : 0, NO_OPLOCK,
3710 UINT32_MAX);
3711 if (!ok) {
3712 TALLOC_FREE(lck);
3713 fd_close(fsp);
3714 file_free(req, fsp);
3715 return NT_STATUS_NO_MEMORY;
3718 /* For directories the delete on close bit at open time seems
3719 always to be honored on close... See test 19 in Samba4 BASE-DELETE. */
3720 if (create_options & FILE_DELETE_ON_CLOSE) {
3721 status = can_set_delete_on_close(fsp, 0);
3722 if (!NT_STATUS_IS_OK(status) && !NT_STATUS_EQUAL(status, NT_STATUS_DIRECTORY_NOT_EMPTY)) {
3723 del_share_mode(lck, fsp);
3724 TALLOC_FREE(lck);
3725 fd_close(fsp);
3726 file_free(req, fsp);
3727 return status;
3730 if (NT_STATUS_IS_OK(status)) {
3731 /* Note that here we set the *inital* delete on close flag,
3732 not the regular one. The magic gets handled in close. */
3733 fsp->initial_delete_on_close = True;
3739 * Deal with other opens having a modified write time. Is this
3740 * possible for directories?
3742 struct timespec write_time = get_share_mode_write_time(lck);
3744 if (!null_timespec(write_time)) {
3745 update_stat_ex_mtime(&fsp->fsp_name->st, write_time);
3749 TALLOC_FREE(lck);
3751 if (pinfo) {
3752 *pinfo = info;
3755 *result = fsp;
3756 return NT_STATUS_OK;
3759 NTSTATUS create_directory(connection_struct *conn, struct smb_request *req,
3760 struct smb_filename *smb_dname)
3762 NTSTATUS status;
3763 files_struct *fsp;
3765 status = SMB_VFS_CREATE_FILE(
3766 conn, /* conn */
3767 req, /* req */
3768 0, /* root_dir_fid */
3769 smb_dname, /* fname */
3770 FILE_READ_ATTRIBUTES, /* access_mask */
3771 FILE_SHARE_NONE, /* share_access */
3772 FILE_CREATE, /* create_disposition*/
3773 FILE_DIRECTORY_FILE, /* create_options */
3774 FILE_ATTRIBUTE_DIRECTORY, /* file_attributes */
3775 0, /* oplock_request */
3776 NULL, /* lease */
3777 0, /* allocation_size */
3778 0, /* private_flags */
3779 NULL, /* sd */
3780 NULL, /* ea_list */
3781 &fsp, /* result */
3782 NULL, /* pinfo */
3783 NULL, NULL); /* create context */
3785 if (NT_STATUS_IS_OK(status)) {
3786 close_file(req, fsp, NORMAL_CLOSE);
3789 return status;
3792 /****************************************************************************
3793 Receive notification that one of our open files has been renamed by another
3794 smbd process.
3795 ****************************************************************************/
3797 void msg_file_was_renamed(struct messaging_context *msg,
3798 void *private_data,
3799 uint32_t msg_type,
3800 struct server_id server_id,
3801 DATA_BLOB *data)
3803 files_struct *fsp;
3804 char *frm = (char *)data->data;
3805 struct file_id id;
3806 const char *sharepath;
3807 const char *base_name;
3808 const char *stream_name;
3809 struct smb_filename *smb_fname = NULL;
3810 size_t sp_len, bn_len;
3811 NTSTATUS status;
3812 struct smbd_server_connection *sconn =
3813 talloc_get_type_abort(private_data,
3814 struct smbd_server_connection);
3816 if (data->data == NULL
3817 || data->length < MSG_FILE_RENAMED_MIN_SIZE + 2) {
3818 DEBUG(0, ("msg_file_was_renamed: Got invalid msg len %d\n",
3819 (int)data->length));
3820 return;
3823 /* Unpack the message. */
3824 pull_file_id_24(frm, &id);
3825 sharepath = &frm[24];
3826 sp_len = strlen(sharepath);
3827 base_name = sharepath + sp_len + 1;
3828 bn_len = strlen(base_name);
3829 stream_name = sharepath + sp_len + 1 + bn_len + 1;
3831 /* stream_name must always be NULL if there is no stream. */
3832 if (stream_name[0] == '\0') {
3833 stream_name = NULL;
3836 smb_fname = synthetic_smb_fname(talloc_tos(),
3837 base_name,
3838 stream_name,
3839 NULL,
3841 if (smb_fname == NULL) {
3842 return;
3845 DEBUG(10,("msg_file_was_renamed: Got rename message for sharepath %s, new name %s, "
3846 "file_id %s\n",
3847 sharepath, smb_fname_str_dbg(smb_fname),
3848 file_id_string_tos(&id)));
3850 for(fsp = file_find_di_first(sconn, id); fsp;
3851 fsp = file_find_di_next(fsp)) {
3852 if (memcmp(fsp->conn->connectpath, sharepath, sp_len) == 0) {
3854 DEBUG(10,("msg_file_was_renamed: renaming file %s from %s -> %s\n",
3855 fsp_fnum_dbg(fsp), fsp_str_dbg(fsp),
3856 smb_fname_str_dbg(smb_fname)));
3857 status = fsp_set_smb_fname(fsp, smb_fname);
3858 if (!NT_STATUS_IS_OK(status)) {
3859 goto out;
3861 } else {
3862 /* TODO. JRA. */
3863 /* Now we have the complete path we can work out if this is
3864 actually within this share and adjust newname accordingly. */
3865 DEBUG(10,("msg_file_was_renamed: share mismatch (sharepath %s "
3866 "not sharepath %s) "
3867 "%s from %s -> %s\n",
3868 fsp->conn->connectpath,
3869 sharepath,
3870 fsp_fnum_dbg(fsp),
3871 fsp_str_dbg(fsp),
3872 smb_fname_str_dbg(smb_fname)));
3875 out:
3876 TALLOC_FREE(smb_fname);
3877 return;
3881 * If a main file is opened for delete, all streams need to be checked for
3882 * !FILE_SHARE_DELETE. Do this by opening with DELETE_ACCESS.
3883 * If that works, delete them all by setting the delete on close and close.
3886 static NTSTATUS open_streams_for_delete(connection_struct *conn,
3887 const struct smb_filename *smb_fname)
3889 struct stream_struct *stream_info = NULL;
3890 files_struct **streams = NULL;
3891 int i;
3892 unsigned int num_streams = 0;
3893 TALLOC_CTX *frame = talloc_stackframe();
3894 NTSTATUS status;
3896 status = vfs_streaminfo(conn, NULL, smb_fname, talloc_tos(),
3897 &num_streams, &stream_info);
3899 if (NT_STATUS_EQUAL(status, NT_STATUS_NOT_IMPLEMENTED)
3900 || NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
3901 DEBUG(10, ("no streams around\n"));
3902 TALLOC_FREE(frame);
3903 return NT_STATUS_OK;
3906 if (!NT_STATUS_IS_OK(status)) {
3907 DEBUG(10, ("vfs_streaminfo failed: %s\n",
3908 nt_errstr(status)));
3909 goto fail;
3912 DEBUG(10, ("open_streams_for_delete found %d streams\n",
3913 num_streams));
3915 if (num_streams == 0) {
3916 TALLOC_FREE(frame);
3917 return NT_STATUS_OK;
3920 streams = talloc_array(talloc_tos(), files_struct *, num_streams);
3921 if (streams == NULL) {
3922 DEBUG(0, ("talloc failed\n"));
3923 status = NT_STATUS_NO_MEMORY;
3924 goto fail;
3927 for (i=0; i<num_streams; i++) {
3928 struct smb_filename *smb_fname_cp;
3930 if (strequal(stream_info[i].name, "::$DATA")) {
3931 streams[i] = NULL;
3932 continue;
3935 smb_fname_cp = synthetic_smb_fname(talloc_tos(),
3936 smb_fname->base_name,
3937 stream_info[i].name,
3938 NULL,
3939 (smb_fname->flags &
3940 ~SMB_FILENAME_POSIX_PATH));
3941 if (smb_fname_cp == NULL) {
3942 status = NT_STATUS_NO_MEMORY;
3943 goto fail;
3946 if (SMB_VFS_STAT(conn, smb_fname_cp) == -1) {
3947 DEBUG(10, ("Unable to stat stream: %s\n",
3948 smb_fname_str_dbg(smb_fname_cp)));
3951 status = SMB_VFS_CREATE_FILE(
3952 conn, /* conn */
3953 NULL, /* req */
3954 0, /* root_dir_fid */
3955 smb_fname_cp, /* fname */
3956 DELETE_ACCESS, /* access_mask */
3957 (FILE_SHARE_READ | /* share_access */
3958 FILE_SHARE_WRITE | FILE_SHARE_DELETE),
3959 FILE_OPEN, /* create_disposition*/
3960 0, /* create_options */
3961 FILE_ATTRIBUTE_NORMAL, /* file_attributes */
3962 0, /* oplock_request */
3963 NULL, /* lease */
3964 0, /* allocation_size */
3965 NTCREATEX_OPTIONS_PRIVATE_STREAM_DELETE, /* private_flags */
3966 NULL, /* sd */
3967 NULL, /* ea_list */
3968 &streams[i], /* result */
3969 NULL, /* pinfo */
3970 NULL, NULL); /* create context */
3972 if (!NT_STATUS_IS_OK(status)) {
3973 DEBUG(10, ("Could not open stream %s: %s\n",
3974 smb_fname_str_dbg(smb_fname_cp),
3975 nt_errstr(status)));
3977 TALLOC_FREE(smb_fname_cp);
3978 break;
3980 TALLOC_FREE(smb_fname_cp);
3984 * don't touch the variable "status" beyond this point :-)
3987 for (i -= 1 ; i >= 0; i--) {
3988 if (streams[i] == NULL) {
3989 continue;
3992 DEBUG(10, ("Closing stream # %d, %s\n", i,
3993 fsp_str_dbg(streams[i])));
3994 close_file(NULL, streams[i], NORMAL_CLOSE);
3997 fail:
3998 TALLOC_FREE(frame);
3999 return status;
4002 /*********************************************************************
4003 Create a default ACL by inheriting from the parent. If no inheritance
4004 from the parent available, don't set anything. This will leave the actual
4005 permissions the new file or directory already got from the filesystem
4006 as the NT ACL when read.
4007 *********************************************************************/
4009 static NTSTATUS inherit_new_acl(files_struct *fsp)
4011 TALLOC_CTX *frame = talloc_stackframe();
4012 char *parent_name = NULL;
4013 struct security_descriptor *parent_desc = NULL;
4014 NTSTATUS status = NT_STATUS_OK;
4015 struct security_descriptor *psd = NULL;
4016 const struct dom_sid *owner_sid = NULL;
4017 const struct dom_sid *group_sid = NULL;
4018 uint32_t security_info_sent = (SECINFO_OWNER | SECINFO_GROUP | SECINFO_DACL);
4019 struct security_token *token = fsp->conn->session_info->security_token;
4020 bool inherit_owner = lp_inherit_owner(SNUM(fsp->conn));
4021 bool inheritable_components = false;
4022 bool try_builtin_administrators = false;
4023 const struct dom_sid *BA_U_sid = NULL;
4024 const struct dom_sid *BA_G_sid = NULL;
4025 bool try_system = false;
4026 const struct dom_sid *SY_U_sid = NULL;
4027 const struct dom_sid *SY_G_sid = NULL;
4028 size_t size = 0;
4029 struct smb_filename *parent_smb_fname = NULL;
4031 if (!parent_dirname(frame, fsp->fsp_name->base_name, &parent_name, NULL)) {
4032 TALLOC_FREE(frame);
4033 return NT_STATUS_NO_MEMORY;
4035 parent_smb_fname = synthetic_smb_fname(talloc_tos(),
4036 parent_name,
4037 NULL,
4038 NULL,
4039 fsp->fsp_name->flags);
4041 if (parent_smb_fname == NULL) {
4042 TALLOC_FREE(frame);
4043 return NT_STATUS_NO_MEMORY;
4046 status = SMB_VFS_GET_NT_ACL(fsp->conn,
4047 parent_smb_fname,
4048 (SECINFO_OWNER | SECINFO_GROUP | SECINFO_DACL),
4049 frame,
4050 &parent_desc);
4051 if (!NT_STATUS_IS_OK(status)) {
4052 TALLOC_FREE(frame);
4053 return status;
4056 inheritable_components = sd_has_inheritable_components(parent_desc,
4057 fsp->is_directory);
4059 if (!inheritable_components && !inherit_owner) {
4060 TALLOC_FREE(frame);
4061 /* Nothing to inherit and not setting owner. */
4062 return NT_STATUS_OK;
4065 /* Create an inherited descriptor from the parent. */
4067 if (DEBUGLEVEL >= 10) {
4068 DEBUG(10,("inherit_new_acl: parent acl for %s is:\n",
4069 fsp_str_dbg(fsp) ));
4070 NDR_PRINT_DEBUG(security_descriptor, parent_desc);
4073 /* Inherit from parent descriptor if "inherit owner" set. */
4074 if (inherit_owner) {
4075 owner_sid = parent_desc->owner_sid;
4076 group_sid = parent_desc->group_sid;
4079 if (owner_sid == NULL) {
4080 if (security_token_has_builtin_administrators(token)) {
4081 try_builtin_administrators = true;
4082 } else if (security_token_is_system(token)) {
4083 try_builtin_administrators = true;
4084 try_system = true;
4088 if (group_sid == NULL &&
4089 token->num_sids == PRIMARY_GROUP_SID_INDEX)
4091 if (security_token_is_system(token)) {
4092 try_builtin_administrators = true;
4093 try_system = true;
4097 if (try_builtin_administrators) {
4098 struct unixid ids;
4099 bool ok;
4101 ZERO_STRUCT(ids);
4102 ok = sids_to_unixids(&global_sid_Builtin_Administrators, 1, &ids);
4103 if (ok) {
4104 switch (ids.type) {
4105 case ID_TYPE_BOTH:
4106 BA_U_sid = &global_sid_Builtin_Administrators;
4107 BA_G_sid = &global_sid_Builtin_Administrators;
4108 break;
4109 case ID_TYPE_UID:
4110 BA_U_sid = &global_sid_Builtin_Administrators;
4111 break;
4112 case ID_TYPE_GID:
4113 BA_G_sid = &global_sid_Builtin_Administrators;
4114 break;
4115 default:
4116 break;
4121 if (try_system) {
4122 struct unixid ids;
4123 bool ok;
4125 ZERO_STRUCT(ids);
4126 ok = sids_to_unixids(&global_sid_System, 1, &ids);
4127 if (ok) {
4128 switch (ids.type) {
4129 case ID_TYPE_BOTH:
4130 SY_U_sid = &global_sid_System;
4131 SY_G_sid = &global_sid_System;
4132 break;
4133 case ID_TYPE_UID:
4134 SY_U_sid = &global_sid_System;
4135 break;
4136 case ID_TYPE_GID:
4137 SY_G_sid = &global_sid_System;
4138 break;
4139 default:
4140 break;
4145 if (owner_sid == NULL) {
4146 owner_sid = BA_U_sid;
4149 if (owner_sid == NULL) {
4150 owner_sid = SY_U_sid;
4153 if (group_sid == NULL) {
4154 group_sid = SY_G_sid;
4157 if (try_system && group_sid == NULL) {
4158 group_sid = BA_G_sid;
4161 if (owner_sid == NULL) {
4162 owner_sid = &token->sids[PRIMARY_USER_SID_INDEX];
4164 if (group_sid == NULL) {
4165 if (token->num_sids == PRIMARY_GROUP_SID_INDEX) {
4166 group_sid = &token->sids[PRIMARY_USER_SID_INDEX];
4167 } else {
4168 group_sid = &token->sids[PRIMARY_GROUP_SID_INDEX];
4172 status = se_create_child_secdesc(frame,
4173 &psd,
4174 &size,
4175 parent_desc,
4176 owner_sid,
4177 group_sid,
4178 fsp->is_directory);
4179 if (!NT_STATUS_IS_OK(status)) {
4180 TALLOC_FREE(frame);
4181 return status;
4184 /* If inheritable_components == false,
4185 se_create_child_secdesc()
4186 creates a security desriptor with a NULL dacl
4187 entry, but with SEC_DESC_DACL_PRESENT. We need
4188 to remove that flag. */
4190 if (!inheritable_components) {
4191 security_info_sent &= ~SECINFO_DACL;
4192 psd->type &= ~SEC_DESC_DACL_PRESENT;
4195 if (DEBUGLEVEL >= 10) {
4196 DEBUG(10,("inherit_new_acl: child acl for %s is:\n",
4197 fsp_str_dbg(fsp) ));
4198 NDR_PRINT_DEBUG(security_descriptor, psd);
4201 if (inherit_owner) {
4202 /* We need to be root to force this. */
4203 become_root();
4205 status = SMB_VFS_FSET_NT_ACL(fsp,
4206 security_info_sent,
4207 psd);
4208 if (inherit_owner) {
4209 unbecome_root();
4211 TALLOC_FREE(frame);
4212 return status;
4216 * If we already have a lease, it must match the new file id. [MS-SMB2]
4217 * 3.3.5.9.8 speaks about INVALID_PARAMETER if an already used lease key is
4218 * used for a different file name.
4221 struct lease_match_state {
4222 /* Input parameters. */
4223 TALLOC_CTX *mem_ctx;
4224 const char *servicepath;
4225 const struct smb_filename *fname;
4226 bool file_existed;
4227 struct file_id id;
4228 /* Return parameters. */
4229 uint32_t num_file_ids;
4230 struct file_id *ids;
4231 NTSTATUS match_status;
4234 /*************************************************************
4235 File doesn't exist but this lease key+guid is already in use.
4237 This is only allowable in the dynamic share case where the
4238 service path must be different.
4240 There is a small race condition here in the multi-connection
4241 case where a client sends two create calls on different connections,
4242 where the file doesn't exist and one smbd creates the leases_db
4243 entry first, but this will get fixed by the multichannel cleanup
4244 when all identical client_guids get handled by a single smbd.
4245 **************************************************************/
4247 static void lease_match_parser_new_file(
4248 uint32_t num_files,
4249 const struct leases_db_file *files,
4250 struct lease_match_state *state)
4252 uint32_t i;
4254 for (i = 0; i < num_files; i++) {
4255 const struct leases_db_file *f = &files[i];
4256 if (strequal(state->servicepath, f->servicepath)) {
4257 state->match_status = NT_STATUS_INVALID_PARAMETER;
4258 return;
4262 /* Dynamic share case. Break leases on all other files. */
4263 state->match_status = leases_db_copy_file_ids(state->mem_ctx,
4264 num_files,
4265 files,
4266 &state->ids);
4267 if (!NT_STATUS_IS_OK(state->match_status)) {
4268 return;
4271 state->num_file_ids = num_files;
4272 state->match_status = NT_STATUS_OPLOCK_NOT_GRANTED;
4273 return;
4276 static void lease_match_parser(
4277 uint32_t num_files,
4278 const struct leases_db_file *files,
4279 void *private_data)
4281 struct lease_match_state *state =
4282 (struct lease_match_state *)private_data;
4283 uint32_t i;
4285 if (!state->file_existed) {
4287 * Deal with name mismatch or
4288 * possible dynamic share case separately
4289 * to make code clearer.
4291 lease_match_parser_new_file(num_files,
4292 files,
4293 state);
4294 return;
4297 /* File existed. */
4298 state->match_status = NT_STATUS_OK;
4300 for (i = 0; i < num_files; i++) {
4301 const struct leases_db_file *f = &files[i];
4303 /* Everything should be the same. */
4304 if (!file_id_equal(&state->id, &f->id)) {
4305 /* This should catch all dynamic share cases. */
4306 state->match_status = NT_STATUS_OPLOCK_NOT_GRANTED;
4307 break;
4309 if (!strequal(f->servicepath, state->servicepath)) {
4310 state->match_status = NT_STATUS_INVALID_PARAMETER;
4311 break;
4313 if (!strequal(f->base_name, state->fname->base_name)) {
4314 state->match_status = NT_STATUS_INVALID_PARAMETER;
4315 break;
4317 if (!strequal(f->stream_name, state->fname->stream_name)) {
4318 state->match_status = NT_STATUS_INVALID_PARAMETER;
4319 break;
4323 if (NT_STATUS_IS_OK(state->match_status)) {
4325 * Common case - just opening another handle on a
4326 * file on a non-dynamic share.
4328 return;
4331 if (NT_STATUS_EQUAL(state->match_status, NT_STATUS_INVALID_PARAMETER)) {
4332 /* Mismatched path. Error back to client. */
4333 return;
4337 * File id mismatch. Dynamic share case NT_STATUS_OPLOCK_NOT_GRANTED.
4338 * Don't allow leases.
4341 state->match_status = leases_db_copy_file_ids(state->mem_ctx,
4342 num_files,
4343 files,
4344 &state->ids);
4345 if (!NT_STATUS_IS_OK(state->match_status)) {
4346 return;
4349 state->num_file_ids = num_files;
4350 state->match_status = NT_STATUS_OPLOCK_NOT_GRANTED;
4351 return;
4354 static NTSTATUS lease_match(connection_struct *conn,
4355 struct smb_request *req,
4356 struct smb2_lease_key *lease_key,
4357 const char *servicepath,
4358 const struct smb_filename *fname,
4359 uint16_t *p_version,
4360 uint16_t *p_epoch)
4362 struct smbd_server_connection *sconn = req->sconn;
4363 TALLOC_CTX *tos = talloc_tos();
4364 struct lease_match_state state = {
4365 .mem_ctx = tos,
4366 .servicepath = servicepath,
4367 .fname = fname,
4368 .match_status = NT_STATUS_OK
4370 uint32_t i;
4371 NTSTATUS status;
4373 state.file_existed = VALID_STAT(fname->st);
4374 if (state.file_existed) {
4375 state.id = vfs_file_id_from_sbuf(conn, &fname->st);
4376 } else {
4377 memset(&state.id, '\0', sizeof(state.id));
4380 status = leases_db_parse(&sconn->client->connections->smb2.client.guid,
4381 lease_key, lease_match_parser, &state);
4382 if (!NT_STATUS_IS_OK(status)) {
4384 * Not found or error means okay: We can make the lease pass
4386 return NT_STATUS_OK;
4388 if (!NT_STATUS_EQUAL(state.match_status, NT_STATUS_OPLOCK_NOT_GRANTED)) {
4390 * Anything but NT_STATUS_OPLOCK_NOT_GRANTED, let the caller
4391 * deal with it.
4393 return state.match_status;
4396 /* We have to break all existing leases. */
4397 for (i = 0; i < state.num_file_ids; i++) {
4398 struct share_mode_lock *lck;
4399 struct share_mode_data *d;
4400 uint32_t j;
4402 if (file_id_equal(&state.ids[i], &state.id)) {
4403 /* Don't need to break our own file. */
4404 continue;
4407 lck = get_existing_share_mode_lock(talloc_tos(), state.ids[i]);
4408 if (lck == NULL) {
4409 /* Race condition - file already closed. */
4410 continue;
4412 d = lck->data;
4413 for (j=0; j<d->num_share_modes; j++) {
4414 struct share_mode_entry *e = &d->share_modes[j];
4415 uint32_t e_lease_type = get_lease_type(d, e);
4416 struct share_mode_lease *l = NULL;
4418 if (share_mode_stale_pid(d, j)) {
4419 continue;
4422 if (e->op_type == LEASE_OPLOCK) {
4423 l = &lck->data->leases[e->lease_idx];
4424 if (!smb2_lease_key_equal(&l->lease_key,
4425 lease_key)) {
4426 continue;
4428 *p_epoch = l->epoch;
4429 *p_version = l->lease_version;
4432 if (e_lease_type == SMB2_LEASE_NONE) {
4433 continue;
4436 send_break_message(conn->sconn->msg_ctx, e,
4437 SMB2_LEASE_NONE);
4440 * Windows 7 and 8 lease clients
4441 * are broken in that they will not
4442 * respond to lease break requests
4443 * whilst waiting for an outstanding
4444 * open request on that lease handle
4445 * on the same TCP connection, due
4446 * to holding an internal inode lock.
4448 * This means we can't reschedule
4449 * ourselves here, but must return
4450 * from the create.
4452 * Work around:
4454 * Send the breaks and then return
4455 * SMB2_LEASE_NONE in the lease handle
4456 * to cause them to acknowledge the
4457 * lease break. Consulatation with
4458 * Microsoft engineering confirmed
4459 * this approach is safe.
4463 TALLOC_FREE(lck);
4466 * Ensure we don't grant anything more so we
4467 * never upgrade.
4469 return NT_STATUS_OPLOCK_NOT_GRANTED;
4473 * Wrapper around open_file_ntcreate and open_directory
4476 static NTSTATUS create_file_unixpath(connection_struct *conn,
4477 struct smb_request *req,
4478 struct smb_filename *smb_fname,
4479 uint32_t access_mask,
4480 uint32_t share_access,
4481 uint32_t create_disposition,
4482 uint32_t create_options,
4483 uint32_t file_attributes,
4484 uint32_t oplock_request,
4485 struct smb2_lease *lease,
4486 uint64_t allocation_size,
4487 uint32_t private_flags,
4488 struct security_descriptor *sd,
4489 struct ea_list *ea_list,
4491 files_struct **result,
4492 int *pinfo)
4494 int info = FILE_WAS_OPENED;
4495 files_struct *base_fsp = NULL;
4496 files_struct *fsp = NULL;
4497 NTSTATUS status;
4499 DEBUG(10,("create_file_unixpath: access_mask = 0x%x "
4500 "file_attributes = 0x%x, share_access = 0x%x, "
4501 "create_disposition = 0x%x create_options = 0x%x "
4502 "oplock_request = 0x%x private_flags = 0x%x "
4503 "ea_list = 0x%p, sd = 0x%p, "
4504 "fname = %s\n",
4505 (unsigned int)access_mask,
4506 (unsigned int)file_attributes,
4507 (unsigned int)share_access,
4508 (unsigned int)create_disposition,
4509 (unsigned int)create_options,
4510 (unsigned int)oplock_request,
4511 (unsigned int)private_flags,
4512 ea_list, sd, smb_fname_str_dbg(smb_fname)));
4514 if (create_options & FILE_OPEN_BY_FILE_ID) {
4515 status = NT_STATUS_NOT_SUPPORTED;
4516 goto fail;
4519 if (create_options & NTCREATEX_OPTIONS_INVALID_PARAM_MASK) {
4520 status = NT_STATUS_INVALID_PARAMETER;
4521 goto fail;
4524 if (req == NULL) {
4525 oplock_request |= INTERNAL_OPEN_ONLY;
4528 if (lease != NULL) {
4529 uint16_t epoch = lease->lease_epoch;
4530 uint16_t version = lease->lease_version;
4531 status = lease_match(conn,
4532 req,
4533 &lease->lease_key,
4534 conn->connectpath,
4535 smb_fname,
4536 &version,
4537 &epoch);
4538 if (NT_STATUS_EQUAL(status, NT_STATUS_OPLOCK_NOT_GRANTED)) {
4539 /* Dynamic share file. No leases and update epoch... */
4540 lease->lease_state = SMB2_LEASE_NONE;
4541 lease->lease_epoch = epoch;
4542 lease->lease_version = version;
4543 } else if (!NT_STATUS_IS_OK(status)) {
4544 goto fail;
4548 if ((conn->fs_capabilities & FILE_NAMED_STREAMS)
4549 && (access_mask & DELETE_ACCESS)
4550 && !is_ntfs_stream_smb_fname(smb_fname)) {
4552 * We can't open a file with DELETE access if any of the
4553 * streams is open without FILE_SHARE_DELETE
4555 status = open_streams_for_delete(conn, smb_fname);
4557 if (!NT_STATUS_IS_OK(status)) {
4558 goto fail;
4562 if ((access_mask & SEC_FLAG_SYSTEM_SECURITY) &&
4563 !security_token_has_privilege(get_current_nttok(conn),
4564 SEC_PRIV_SECURITY)) {
4565 DEBUG(10, ("create_file_unixpath: open on %s "
4566 "failed - SEC_FLAG_SYSTEM_SECURITY denied.\n",
4567 smb_fname_str_dbg(smb_fname)));
4568 status = NT_STATUS_PRIVILEGE_NOT_HELD;
4569 goto fail;
4572 if ((conn->fs_capabilities & FILE_NAMED_STREAMS)
4573 && is_ntfs_stream_smb_fname(smb_fname)
4574 && (!(private_flags & NTCREATEX_OPTIONS_PRIVATE_STREAM_DELETE))) {
4575 uint32_t base_create_disposition;
4576 struct smb_filename *smb_fname_base = NULL;
4578 if (create_options & FILE_DIRECTORY_FILE) {
4579 status = NT_STATUS_NOT_A_DIRECTORY;
4580 goto fail;
4583 switch (create_disposition) {
4584 case FILE_OPEN:
4585 base_create_disposition = FILE_OPEN;
4586 break;
4587 default:
4588 base_create_disposition = FILE_OPEN_IF;
4589 break;
4592 /* Create an smb_filename with stream_name == NULL. */
4593 smb_fname_base = synthetic_smb_fname(talloc_tos(),
4594 smb_fname->base_name,
4595 NULL,
4596 NULL,
4597 smb_fname->flags);
4598 if (smb_fname_base == NULL) {
4599 status = NT_STATUS_NO_MEMORY;
4600 goto fail;
4603 if (SMB_VFS_STAT(conn, smb_fname_base) == -1) {
4604 DEBUG(10, ("Unable to stat stream: %s\n",
4605 smb_fname_str_dbg(smb_fname_base)));
4606 } else {
4608 * https://bugzilla.samba.org/show_bug.cgi?id=10229
4609 * We need to check if the requested access mask
4610 * could be used to open the underlying file (if
4611 * it existed), as we're passing in zero for the
4612 * access mask to the base filename.
4614 status = check_base_file_access(conn,
4615 smb_fname_base,
4616 access_mask);
4618 if (!NT_STATUS_IS_OK(status)) {
4619 DEBUG(10, ("Permission check "
4620 "for base %s failed: "
4621 "%s\n", smb_fname->base_name,
4622 nt_errstr(status)));
4623 goto fail;
4627 /* Open the base file. */
4628 status = create_file_unixpath(conn, NULL, smb_fname_base, 0,
4629 FILE_SHARE_READ
4630 | FILE_SHARE_WRITE
4631 | FILE_SHARE_DELETE,
4632 base_create_disposition,
4633 0, 0, 0, NULL, 0, 0, NULL, NULL,
4634 &base_fsp, NULL);
4635 TALLOC_FREE(smb_fname_base);
4637 if (!NT_STATUS_IS_OK(status)) {
4638 DEBUG(10, ("create_file_unixpath for base %s failed: "
4639 "%s\n", smb_fname->base_name,
4640 nt_errstr(status)));
4641 goto fail;
4643 /* we don't need the low level fd */
4644 fd_close(base_fsp);
4648 * If it's a request for a directory open, deal with it separately.
4651 if (create_options & FILE_DIRECTORY_FILE) {
4653 if (create_options & FILE_NON_DIRECTORY_FILE) {
4654 status = NT_STATUS_INVALID_PARAMETER;
4655 goto fail;
4658 /* Can't open a temp directory. IFS kit test. */
4659 if (!(file_attributes & FILE_FLAG_POSIX_SEMANTICS) &&
4660 (file_attributes & FILE_ATTRIBUTE_TEMPORARY)) {
4661 status = NT_STATUS_INVALID_PARAMETER;
4662 goto fail;
4666 * We will get a create directory here if the Win32
4667 * app specified a security descriptor in the
4668 * CreateDirectory() call.
4671 oplock_request = 0;
4672 status = open_directory(
4673 conn, req, smb_fname, access_mask, share_access,
4674 create_disposition, create_options, file_attributes,
4675 &info, &fsp);
4676 } else {
4679 * Ordinary file case.
4682 status = file_new(req, conn, &fsp);
4683 if(!NT_STATUS_IS_OK(status)) {
4684 goto fail;
4687 status = fsp_set_smb_fname(fsp, smb_fname);
4688 if (!NT_STATUS_IS_OK(status)) {
4689 goto fail;
4692 if (base_fsp) {
4694 * We're opening the stream element of a
4695 * base_fsp we already opened. Set up the
4696 * base_fsp pointer.
4698 fsp->base_fsp = base_fsp;
4701 if (allocation_size) {
4702 fsp->initial_allocation_size = smb_roundup(fsp->conn,
4703 allocation_size);
4706 status = open_file_ntcreate(conn,
4707 req,
4708 access_mask,
4709 share_access,
4710 create_disposition,
4711 create_options,
4712 file_attributes,
4713 oplock_request,
4714 lease,
4715 private_flags,
4716 &info,
4717 fsp);
4719 if(!NT_STATUS_IS_OK(status)) {
4720 file_free(req, fsp);
4721 fsp = NULL;
4724 if (NT_STATUS_EQUAL(status, NT_STATUS_FILE_IS_A_DIRECTORY)) {
4726 /* A stream open never opens a directory */
4728 if (base_fsp) {
4729 status = NT_STATUS_FILE_IS_A_DIRECTORY;
4730 goto fail;
4734 * Fail the open if it was explicitly a non-directory
4735 * file.
4738 if (create_options & FILE_NON_DIRECTORY_FILE) {
4739 status = NT_STATUS_FILE_IS_A_DIRECTORY;
4740 goto fail;
4743 oplock_request = 0;
4744 status = open_directory(
4745 conn, req, smb_fname, access_mask,
4746 share_access, create_disposition,
4747 create_options, file_attributes,
4748 &info, &fsp);
4752 if (!NT_STATUS_IS_OK(status)) {
4753 goto fail;
4756 fsp->base_fsp = base_fsp;
4758 if ((ea_list != NULL) &&
4759 ((info == FILE_WAS_CREATED) || (info == FILE_WAS_OVERWRITTEN))) {
4760 status = set_ea(conn, fsp, fsp->fsp_name, ea_list);
4761 if (!NT_STATUS_IS_OK(status)) {
4762 goto fail;
4766 if (!fsp->is_directory && S_ISDIR(fsp->fsp_name->st.st_ex_mode)) {
4767 status = NT_STATUS_ACCESS_DENIED;
4768 goto fail;
4771 /* Save the requested allocation size. */
4772 if ((info == FILE_WAS_CREATED) || (info == FILE_WAS_OVERWRITTEN)) {
4773 if ((allocation_size > fsp->fsp_name->st.st_ex_size)
4774 && !(fsp->is_directory))
4776 fsp->initial_allocation_size = smb_roundup(
4777 fsp->conn, allocation_size);
4778 if (vfs_allocate_file_space(
4779 fsp, fsp->initial_allocation_size) == -1) {
4780 status = NT_STATUS_DISK_FULL;
4781 goto fail;
4783 } else {
4784 fsp->initial_allocation_size = smb_roundup(
4785 fsp->conn, (uint64_t)fsp->fsp_name->st.st_ex_size);
4787 } else {
4788 fsp->initial_allocation_size = 0;
4791 if ((info == FILE_WAS_CREATED) && lp_nt_acl_support(SNUM(conn)) &&
4792 fsp->base_fsp == NULL) {
4793 if (sd != NULL) {
4795 * According to the MS documentation, the only time the security
4796 * descriptor is applied to the opened file is iff we *created* the
4797 * file; an existing file stays the same.
4799 * Also, it seems (from observation) that you can open the file with
4800 * any access mask but you can still write the sd. We need to override
4801 * the granted access before we call set_sd
4802 * Patch for bug #2242 from Tom Lackemann <cessnatomny@yahoo.com>.
4805 uint32_t sec_info_sent;
4806 uint32_t saved_access_mask = fsp->access_mask;
4808 sec_info_sent = get_sec_info(sd);
4810 fsp->access_mask = FILE_GENERIC_ALL;
4812 if (sec_info_sent & (SECINFO_OWNER|
4813 SECINFO_GROUP|
4814 SECINFO_DACL|
4815 SECINFO_SACL)) {
4816 status = set_sd(fsp, sd, sec_info_sent);
4819 fsp->access_mask = saved_access_mask;
4821 if (!NT_STATUS_IS_OK(status)) {
4822 goto fail;
4824 } else if (lp_inherit_acls(SNUM(conn))) {
4825 /* Inherit from parent. Errors here are not fatal. */
4826 status = inherit_new_acl(fsp);
4827 if (!NT_STATUS_IS_OK(status)) {
4828 DEBUG(10,("inherit_new_acl: failed for %s with %s\n",
4829 fsp_str_dbg(fsp),
4830 nt_errstr(status) ));
4835 if ((conn->fs_capabilities & FILE_FILE_COMPRESSION)
4836 && (create_options & FILE_NO_COMPRESSION)
4837 && (info == FILE_WAS_CREATED)) {
4838 status = SMB_VFS_SET_COMPRESSION(conn, fsp, fsp,
4839 COMPRESSION_FORMAT_NONE);
4840 if (!NT_STATUS_IS_OK(status)) {
4841 DEBUG(1, ("failed to disable compression: %s\n",
4842 nt_errstr(status)));
4846 DEBUG(10, ("create_file_unixpath: info=%d\n", info));
4848 *result = fsp;
4849 if (pinfo != NULL) {
4850 *pinfo = info;
4853 smb_fname->st = fsp->fsp_name->st;
4855 return NT_STATUS_OK;
4857 fail:
4858 DEBUG(10, ("create_file_unixpath: %s\n", nt_errstr(status)));
4860 if (fsp != NULL) {
4861 if (base_fsp && fsp->base_fsp == base_fsp) {
4863 * The close_file below will close
4864 * fsp->base_fsp.
4866 base_fsp = NULL;
4868 close_file(req, fsp, ERROR_CLOSE);
4869 fsp = NULL;
4871 if (base_fsp != NULL) {
4872 close_file(req, base_fsp, ERROR_CLOSE);
4873 base_fsp = NULL;
4875 return status;
4879 * Calculate the full path name given a relative fid.
4881 NTSTATUS get_relative_fid_filename(connection_struct *conn,
4882 struct smb_request *req,
4883 uint16_t root_dir_fid,
4884 const struct smb_filename *smb_fname,
4885 struct smb_filename **smb_fname_out)
4887 files_struct *dir_fsp;
4888 char *parent_fname = NULL;
4889 char *new_base_name = NULL;
4890 uint32_t ucf_flags = ((req != NULL && req->posix_pathnames) ?
4891 UCF_POSIX_PATHNAMES : 0);
4892 NTSTATUS status;
4894 if (root_dir_fid == 0 || !smb_fname) {
4895 status = NT_STATUS_INTERNAL_ERROR;
4896 goto out;
4899 dir_fsp = file_fsp(req, root_dir_fid);
4901 if (dir_fsp == NULL) {
4902 status = NT_STATUS_INVALID_HANDLE;
4903 goto out;
4906 if (is_ntfs_stream_smb_fname(dir_fsp->fsp_name)) {
4907 status = NT_STATUS_INVALID_HANDLE;
4908 goto out;
4911 if (!dir_fsp->is_directory) {
4914 * Check to see if this is a mac fork of some kind.
4917 if ((conn->fs_capabilities & FILE_NAMED_STREAMS) &&
4918 is_ntfs_stream_smb_fname(smb_fname)) {
4919 status = NT_STATUS_OBJECT_PATH_NOT_FOUND;
4920 goto out;
4924 we need to handle the case when we get a
4925 relative open relative to a file and the
4926 pathname is blank - this is a reopen!
4927 (hint from demyn plantenberg)
4930 status = NT_STATUS_INVALID_HANDLE;
4931 goto out;
4934 if (ISDOT(dir_fsp->fsp_name->base_name)) {
4936 * We're at the toplevel dir, the final file name
4937 * must not contain ./, as this is filtered out
4938 * normally by srvstr_get_path and unix_convert
4939 * explicitly rejects paths containing ./.
4941 parent_fname = talloc_strdup(talloc_tos(), "");
4942 if (parent_fname == NULL) {
4943 status = NT_STATUS_NO_MEMORY;
4944 goto out;
4946 } else {
4947 size_t dir_name_len = strlen(dir_fsp->fsp_name->base_name);
4950 * Copy in the base directory name.
4953 parent_fname = talloc_array(talloc_tos(), char,
4954 dir_name_len+2);
4955 if (parent_fname == NULL) {
4956 status = NT_STATUS_NO_MEMORY;
4957 goto out;
4959 memcpy(parent_fname, dir_fsp->fsp_name->base_name,
4960 dir_name_len+1);
4963 * Ensure it ends in a '/'.
4964 * We used TALLOC_SIZE +2 to add space for the '/'.
4967 if(dir_name_len
4968 && (parent_fname[dir_name_len-1] != '\\')
4969 && (parent_fname[dir_name_len-1] != '/')) {
4970 parent_fname[dir_name_len] = '/';
4971 parent_fname[dir_name_len+1] = '\0';
4975 new_base_name = talloc_asprintf(talloc_tos(), "%s%s", parent_fname,
4976 smb_fname->base_name);
4977 if (new_base_name == NULL) {
4978 status = NT_STATUS_NO_MEMORY;
4979 goto out;
4982 status = filename_convert(req,
4983 conn,
4984 req->flags2 & FLAGS2_DFS_PATHNAMES,
4985 new_base_name,
4986 ucf_flags,
4987 NULL,
4988 smb_fname_out);
4989 if (!NT_STATUS_IS_OK(status)) {
4990 goto out;
4993 out:
4994 TALLOC_FREE(parent_fname);
4995 TALLOC_FREE(new_base_name);
4996 return status;
4999 NTSTATUS create_file_default(connection_struct *conn,
5000 struct smb_request *req,
5001 uint16_t root_dir_fid,
5002 struct smb_filename *smb_fname,
5003 uint32_t access_mask,
5004 uint32_t share_access,
5005 uint32_t create_disposition,
5006 uint32_t create_options,
5007 uint32_t file_attributes,
5008 uint32_t oplock_request,
5009 struct smb2_lease *lease,
5010 uint64_t allocation_size,
5011 uint32_t private_flags,
5012 struct security_descriptor *sd,
5013 struct ea_list *ea_list,
5014 files_struct **result,
5015 int *pinfo,
5016 const struct smb2_create_blobs *in_context_blobs,
5017 struct smb2_create_blobs *out_context_blobs)
5019 int info = FILE_WAS_OPENED;
5020 files_struct *fsp = NULL;
5021 NTSTATUS status;
5022 bool stream_name = false;
5024 DEBUG(10,("create_file: access_mask = 0x%x "
5025 "file_attributes = 0x%x, share_access = 0x%x, "
5026 "create_disposition = 0x%x create_options = 0x%x "
5027 "oplock_request = 0x%x "
5028 "private_flags = 0x%x "
5029 "root_dir_fid = 0x%x, ea_list = 0x%p, sd = 0x%p, "
5030 "fname = %s\n",
5031 (unsigned int)access_mask,
5032 (unsigned int)file_attributes,
5033 (unsigned int)share_access,
5034 (unsigned int)create_disposition,
5035 (unsigned int)create_options,
5036 (unsigned int)oplock_request,
5037 (unsigned int)private_flags,
5038 (unsigned int)root_dir_fid,
5039 ea_list, sd, smb_fname_str_dbg(smb_fname)));
5042 * Calculate the filename from the root_dir_if if necessary.
5045 if (root_dir_fid != 0) {
5046 struct smb_filename *smb_fname_out = NULL;
5047 status = get_relative_fid_filename(conn, req, root_dir_fid,
5048 smb_fname, &smb_fname_out);
5049 if (!NT_STATUS_IS_OK(status)) {
5050 goto fail;
5052 smb_fname = smb_fname_out;
5056 * Check to see if this is a mac fork of some kind.
5059 stream_name = is_ntfs_stream_smb_fname(smb_fname);
5060 if (stream_name) {
5061 enum FAKE_FILE_TYPE fake_file_type;
5063 fake_file_type = is_fake_file(smb_fname);
5065 if (fake_file_type != FAKE_FILE_TYPE_NONE) {
5068 * Here we go! support for changing the disk quotas
5069 * --metze
5071 * We need to fake up to open this MAGIC QUOTA file
5072 * and return a valid FID.
5074 * w2k close this file directly after openening xp
5075 * also tries a QUERY_FILE_INFO on the file and then
5076 * close it
5078 status = open_fake_file(req, conn, req->vuid,
5079 fake_file_type, smb_fname,
5080 access_mask, &fsp);
5081 if (!NT_STATUS_IS_OK(status)) {
5082 goto fail;
5085 ZERO_STRUCT(smb_fname->st);
5086 goto done;
5089 if (!(conn->fs_capabilities & FILE_NAMED_STREAMS)) {
5090 status = NT_STATUS_OBJECT_NAME_NOT_FOUND;
5091 goto fail;
5095 if (is_ntfs_default_stream_smb_fname(smb_fname)) {
5096 int ret;
5097 smb_fname->stream_name = NULL;
5098 /* We have to handle this error here. */
5099 if (create_options & FILE_DIRECTORY_FILE) {
5100 status = NT_STATUS_NOT_A_DIRECTORY;
5101 goto fail;
5103 if (req != NULL && req->posix_pathnames) {
5104 ret = SMB_VFS_LSTAT(conn, smb_fname);
5105 } else {
5106 ret = SMB_VFS_STAT(conn, smb_fname);
5109 if (ret == 0 && VALID_STAT_OF_DIR(smb_fname->st)) {
5110 status = NT_STATUS_FILE_IS_A_DIRECTORY;
5111 goto fail;
5115 status = create_file_unixpath(
5116 conn, req, smb_fname, access_mask, share_access,
5117 create_disposition, create_options, file_attributes,
5118 oplock_request, lease, allocation_size, private_flags,
5119 sd, ea_list,
5120 &fsp, &info);
5122 if (!NT_STATUS_IS_OK(status)) {
5123 goto fail;
5126 done:
5127 DEBUG(10, ("create_file: info=%d\n", info));
5129 *result = fsp;
5130 if (pinfo != NULL) {
5131 *pinfo = info;
5133 return NT_STATUS_OK;
5135 fail:
5136 DEBUG(10, ("create_file: %s\n", nt_errstr(status)));
5138 if (fsp != NULL) {
5139 close_file(req, fsp, ERROR_CLOSE);
5140 fsp = NULL;
5142 return status;