auth/auth_sam_reply: add some const to input parameters
[Samba.git] / source3 / smbd / open.c
blob883c6ae46b7105096158f3de7a14db60a4c09ece
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_record_watch_send(
1956 watch_state, req->sconn->ev_ctx, lck->data->record,
1957 req->sconn->msg_ctx);
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_record_watch_recv(req, talloc_tos(), NULL);
1985 TALLOC_FREE(req);
1986 if (!NT_STATUS_IS_OK(status)) {
1987 DEBUG(5, ("dbwrap_record_watch_recv returned %s\n",
1988 nt_errstr(status)));
1990 * Even if it failed, retry anyway. TODO: We need a way to
1991 * tell a re-scheduled open about that error.
1995 DEBUG(10, ("scheduling mid %llu\n", (unsigned long long)state->mid));
1997 ret = schedule_deferred_open_message_smb(state->xconn, state->mid);
1998 SMB_ASSERT(ret);
1999 TALLOC_FREE(state);
2003 /****************************************************************************
2004 On overwrite open ensure that the attributes match.
2005 ****************************************************************************/
2007 static bool open_match_attributes(connection_struct *conn,
2008 uint32_t old_dos_attr,
2009 uint32_t new_dos_attr,
2010 mode_t existing_unx_mode,
2011 mode_t new_unx_mode,
2012 mode_t *returned_unx_mode)
2014 uint32_t noarch_old_dos_attr, noarch_new_dos_attr;
2016 noarch_old_dos_attr = (old_dos_attr & ~FILE_ATTRIBUTE_ARCHIVE);
2017 noarch_new_dos_attr = (new_dos_attr & ~FILE_ATTRIBUTE_ARCHIVE);
2019 if((noarch_old_dos_attr == 0 && noarch_new_dos_attr != 0) ||
2020 (noarch_old_dos_attr != 0 && ((noarch_old_dos_attr & noarch_new_dos_attr) == noarch_old_dos_attr))) {
2021 *returned_unx_mode = new_unx_mode;
2022 } else {
2023 *returned_unx_mode = (mode_t)0;
2026 DEBUG(10,("open_match_attributes: old_dos_attr = 0x%x, "
2027 "existing_unx_mode = 0%o, new_dos_attr = 0x%x "
2028 "returned_unx_mode = 0%o\n",
2029 (unsigned int)old_dos_attr,
2030 (unsigned int)existing_unx_mode,
2031 (unsigned int)new_dos_attr,
2032 (unsigned int)*returned_unx_mode ));
2034 /* If we're mapping SYSTEM and HIDDEN ensure they match. */
2035 if (lp_map_system(SNUM(conn)) || lp_store_dos_attributes(SNUM(conn))) {
2036 if ((old_dos_attr & FILE_ATTRIBUTE_SYSTEM) &&
2037 !(new_dos_attr & FILE_ATTRIBUTE_SYSTEM)) {
2038 return False;
2041 if (lp_map_hidden(SNUM(conn)) || lp_store_dos_attributes(SNUM(conn))) {
2042 if ((old_dos_attr & FILE_ATTRIBUTE_HIDDEN) &&
2043 !(new_dos_attr & FILE_ATTRIBUTE_HIDDEN)) {
2044 return False;
2047 return True;
2050 /****************************************************************************
2051 Special FCB or DOS processing in the case of a sharing violation.
2052 Try and find a duplicated file handle.
2053 ****************************************************************************/
2055 static NTSTATUS fcb_or_dos_open(struct smb_request *req,
2056 connection_struct *conn,
2057 files_struct *fsp_to_dup_into,
2058 const struct smb_filename *smb_fname,
2059 struct file_id id,
2060 uint16_t file_pid,
2061 uint64_t vuid,
2062 uint32_t access_mask,
2063 uint32_t share_access,
2064 uint32_t create_options)
2066 files_struct *fsp;
2068 DEBUG(5,("fcb_or_dos_open: attempting old open semantics for "
2069 "file %s.\n", smb_fname_str_dbg(smb_fname)));
2071 for(fsp = file_find_di_first(conn->sconn, id); fsp;
2072 fsp = file_find_di_next(fsp)) {
2074 DEBUG(10,("fcb_or_dos_open: checking file %s, fd = %d, "
2075 "vuid = %llu, file_pid = %u, private_options = 0x%x "
2076 "access_mask = 0x%x\n", fsp_str_dbg(fsp),
2077 fsp->fh->fd, (unsigned long long)fsp->vuid,
2078 (unsigned int)fsp->file_pid,
2079 (unsigned int)fsp->fh->private_options,
2080 (unsigned int)fsp->access_mask ));
2082 if (fsp != fsp_to_dup_into &&
2083 fsp->fh->fd != -1 &&
2084 fsp->vuid == vuid &&
2085 fsp->file_pid == file_pid &&
2086 (fsp->fh->private_options & (NTCREATEX_OPTIONS_PRIVATE_DENY_DOS |
2087 NTCREATEX_OPTIONS_PRIVATE_DENY_FCB)) &&
2088 (fsp->access_mask & FILE_WRITE_DATA) &&
2089 strequal(fsp->fsp_name->base_name, smb_fname->base_name) &&
2090 strequal(fsp->fsp_name->stream_name,
2091 smb_fname->stream_name)) {
2092 DEBUG(10,("fcb_or_dos_open: file match\n"));
2093 break;
2097 if (!fsp) {
2098 return NT_STATUS_NOT_FOUND;
2101 /* quite an insane set of semantics ... */
2102 if (is_executable(smb_fname->base_name) &&
2103 (fsp->fh->private_options & NTCREATEX_OPTIONS_PRIVATE_DENY_DOS)) {
2104 DEBUG(10,("fcb_or_dos_open: file fail due to is_executable.\n"));
2105 return NT_STATUS_INVALID_PARAMETER;
2108 /* We need to duplicate this fsp. */
2109 return dup_file_fsp(req, fsp, access_mask, share_access,
2110 create_options, fsp_to_dup_into);
2113 static void schedule_defer_open(struct share_mode_lock *lck,
2114 struct file_id id,
2115 struct timeval request_time,
2116 struct smb_request *req)
2118 struct deferred_open_record state;
2120 /* This is a relative time, added to the absolute
2121 request_time value to get the absolute timeout time.
2122 Note that if this is the second or greater time we enter
2123 this codepath for this particular request mid then
2124 request_time is left as the absolute time of the *first*
2125 time this request mid was processed. This is what allows
2126 the request to eventually time out. */
2128 struct timeval timeout;
2130 /* Normally the smbd we asked should respond within
2131 * OPLOCK_BREAK_TIMEOUT seconds regardless of whether
2132 * the client did, give twice the timeout as a safety
2133 * measure here in case the other smbd is stuck
2134 * somewhere else. */
2136 timeout = timeval_set(OPLOCK_BREAK_TIMEOUT*2, 0);
2138 /* Nothing actually uses state.delayed_for_oplocks
2139 but it's handy to differentiate in debug messages
2140 between a 30 second delay due to oplock break, and
2141 a 1 second delay for share mode conflicts. */
2143 state.delayed_for_oplocks = True;
2144 state.async_open = false;
2145 state.id = id;
2147 if (!request_timed_out(request_time, timeout)) {
2148 defer_open(lck, request_time, timeout, req, &state);
2152 /****************************************************************************
2153 Reschedule an open call that went asynchronous.
2154 ****************************************************************************/
2156 static void schedule_async_open(struct timeval request_time,
2157 struct smb_request *req)
2159 struct deferred_open_record state;
2160 struct timeval timeout;
2162 timeout = timeval_set(20, 0);
2164 ZERO_STRUCT(state);
2165 state.delayed_for_oplocks = false;
2166 state.async_open = true;
2168 if (!request_timed_out(request_time, timeout)) {
2169 defer_open(NULL, request_time, timeout, req, &state);
2173 /****************************************************************************
2174 Work out what access_mask to use from what the client sent us.
2175 ****************************************************************************/
2177 static NTSTATUS smbd_calculate_maximum_allowed_access(
2178 connection_struct *conn,
2179 const struct smb_filename *smb_fname,
2180 bool use_privs,
2181 uint32_t *p_access_mask)
2183 struct security_descriptor *sd;
2184 uint32_t access_granted;
2185 NTSTATUS status;
2187 if (!use_privs && (get_current_uid(conn) == (uid_t)0)) {
2188 *p_access_mask |= FILE_GENERIC_ALL;
2189 return NT_STATUS_OK;
2192 status = SMB_VFS_GET_NT_ACL(conn, smb_fname,
2193 (SECINFO_OWNER |
2194 SECINFO_GROUP |
2195 SECINFO_DACL),
2196 talloc_tos(), &sd);
2198 if (NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
2200 * File did not exist
2202 *p_access_mask = FILE_GENERIC_ALL;
2203 return NT_STATUS_OK;
2205 if (!NT_STATUS_IS_OK(status)) {
2206 DEBUG(10,("Could not get acl on file %s: %s\n",
2207 smb_fname_str_dbg(smb_fname),
2208 nt_errstr(status)));
2209 return NT_STATUS_ACCESS_DENIED;
2213 * If we can access the path to this file, by
2214 * default we have FILE_READ_ATTRIBUTES from the
2215 * containing directory. See the section:
2216 * "Algorithm to Check Access to an Existing File"
2217 * in MS-FSA.pdf.
2219 * se_file_access_check()
2220 * also takes care of owner WRITE_DAC and READ_CONTROL.
2222 status = se_file_access_check(sd,
2223 get_current_nttok(conn),
2224 use_privs,
2225 (*p_access_mask & ~FILE_READ_ATTRIBUTES),
2226 &access_granted);
2228 TALLOC_FREE(sd);
2230 if (!NT_STATUS_IS_OK(status)) {
2231 DEBUG(10, ("Access denied on file %s: "
2232 "when calculating maximum access\n",
2233 smb_fname_str_dbg(smb_fname)));
2234 return NT_STATUS_ACCESS_DENIED;
2236 *p_access_mask = (access_granted | FILE_READ_ATTRIBUTES);
2238 if (!(access_granted & DELETE_ACCESS)) {
2239 if (can_delete_file_in_directory(conn, smb_fname)) {
2240 *p_access_mask |= DELETE_ACCESS;
2244 return NT_STATUS_OK;
2247 NTSTATUS smbd_calculate_access_mask(connection_struct *conn,
2248 const struct smb_filename *smb_fname,
2249 bool use_privs,
2250 uint32_t access_mask,
2251 uint32_t *access_mask_out)
2253 NTSTATUS status;
2254 uint32_t orig_access_mask = access_mask;
2255 uint32_t rejected_share_access;
2258 * Convert GENERIC bits to specific bits.
2261 se_map_generic(&access_mask, &file_generic_mapping);
2263 /* Calculate MAXIMUM_ALLOWED_ACCESS if requested. */
2264 if (access_mask & MAXIMUM_ALLOWED_ACCESS) {
2266 status = smbd_calculate_maximum_allowed_access(
2267 conn, smb_fname, use_privs, &access_mask);
2269 if (!NT_STATUS_IS_OK(status)) {
2270 return status;
2273 access_mask &= conn->share_access;
2276 rejected_share_access = access_mask & ~(conn->share_access);
2278 if (rejected_share_access) {
2279 DEBUG(10, ("smbd_calculate_access_mask: Access denied on "
2280 "file %s: rejected by share access mask[0x%08X] "
2281 "orig[0x%08X] mapped[0x%08X] reject[0x%08X]\n",
2282 smb_fname_str_dbg(smb_fname),
2283 conn->share_access,
2284 orig_access_mask, access_mask,
2285 rejected_share_access));
2286 return NT_STATUS_ACCESS_DENIED;
2289 *access_mask_out = access_mask;
2290 return NT_STATUS_OK;
2293 /****************************************************************************
2294 Remove the deferred open entry under lock.
2295 ****************************************************************************/
2297 /****************************************************************************
2298 Return true if this is a state pointer to an asynchronous create.
2299 ****************************************************************************/
2301 bool is_deferred_open_async(const struct deferred_open_record *rec)
2303 return rec->async_open;
2306 static bool clear_ads(uint32_t create_disposition)
2308 bool ret = false;
2310 switch (create_disposition) {
2311 case FILE_SUPERSEDE:
2312 case FILE_OVERWRITE_IF:
2313 case FILE_OVERWRITE:
2314 ret = true;
2315 break;
2316 default:
2317 break;
2319 return ret;
2322 static int disposition_to_open_flags(uint32_t create_disposition)
2324 int ret = 0;
2327 * Currently we're using FILE_SUPERSEDE as the same as
2328 * FILE_OVERWRITE_IF but they really are
2329 * different. FILE_SUPERSEDE deletes an existing file
2330 * (requiring delete access) then recreates it.
2333 switch (create_disposition) {
2334 case FILE_SUPERSEDE:
2335 case FILE_OVERWRITE_IF:
2337 * If file exists replace/overwrite. If file doesn't
2338 * exist create.
2340 ret = O_CREAT|O_TRUNC;
2341 break;
2343 case FILE_OPEN:
2345 * If file exists open. If file doesn't exist error.
2347 ret = 0;
2348 break;
2350 case FILE_OVERWRITE:
2352 * If file exists overwrite. If file doesn't exist
2353 * error.
2355 ret = O_TRUNC;
2356 break;
2358 case FILE_CREATE:
2360 * If file exists error. If file doesn't exist create.
2362 ret = O_CREAT|O_EXCL;
2363 break;
2365 case FILE_OPEN_IF:
2367 * If file exists open. If file doesn't exist create.
2369 ret = O_CREAT;
2370 break;
2372 return ret;
2375 static int calculate_open_access_flags(uint32_t access_mask,
2376 uint32_t private_flags)
2378 bool need_write, need_read;
2381 * Note that we ignore the append flag as append does not
2382 * mean the same thing under DOS and Unix.
2385 need_write = (access_mask & (FILE_WRITE_DATA | FILE_APPEND_DATA));
2386 if (!need_write) {
2387 return O_RDONLY;
2390 /* DENY_DOS opens are always underlying read-write on the
2391 file handle, no matter what the requested access mask
2392 says. */
2394 need_read =
2395 ((private_flags & NTCREATEX_OPTIONS_PRIVATE_DENY_DOS) ||
2396 access_mask & (FILE_READ_ATTRIBUTES|FILE_READ_DATA|
2397 FILE_READ_EA|FILE_EXECUTE));
2399 if (!need_read) {
2400 return O_WRONLY;
2402 return O_RDWR;
2405 /****************************************************************************
2406 Open a file with a share mode. Passed in an already created files_struct *.
2407 ****************************************************************************/
2409 static NTSTATUS open_file_ntcreate(connection_struct *conn,
2410 struct smb_request *req,
2411 uint32_t access_mask, /* access bits (FILE_READ_DATA etc.) */
2412 uint32_t share_access, /* share constants (FILE_SHARE_READ etc) */
2413 uint32_t create_disposition, /* FILE_OPEN_IF etc. */
2414 uint32_t create_options, /* options such as delete on close. */
2415 uint32_t new_dos_attributes, /* attributes used for new file. */
2416 int oplock_request, /* internal Samba oplock codes. */
2417 struct smb2_lease *lease,
2418 /* Information (FILE_EXISTS etc.) */
2419 uint32_t private_flags, /* Samba specific flags. */
2420 int *pinfo,
2421 files_struct *fsp)
2423 struct smb_filename *smb_fname = fsp->fsp_name;
2424 int flags=0;
2425 int flags2=0;
2426 bool file_existed = VALID_STAT(smb_fname->st);
2427 bool def_acl = False;
2428 bool posix_open = False;
2429 bool new_file_created = False;
2430 bool first_open_attempt = true;
2431 NTSTATUS fsp_open = NT_STATUS_ACCESS_DENIED;
2432 mode_t new_unx_mode = (mode_t)0;
2433 mode_t unx_mode = (mode_t)0;
2434 int info;
2435 uint32_t existing_dos_attributes = 0;
2436 struct timeval request_time = timeval_zero();
2437 struct share_mode_lock *lck = NULL;
2438 uint32_t open_access_mask = access_mask;
2439 NTSTATUS status;
2440 char *parent_dir;
2441 SMB_STRUCT_STAT saved_stat = smb_fname->st;
2442 struct timespec old_write_time;
2443 struct file_id id;
2445 if (conn->printer) {
2447 * Printers are handled completely differently.
2448 * Most of the passed parameters are ignored.
2451 if (pinfo) {
2452 *pinfo = FILE_WAS_CREATED;
2455 DEBUG(10, ("open_file_ntcreate: printer open fname=%s\n",
2456 smb_fname_str_dbg(smb_fname)));
2458 if (!req) {
2459 DEBUG(0,("open_file_ntcreate: printer open without "
2460 "an SMB request!\n"));
2461 return NT_STATUS_INTERNAL_ERROR;
2464 return print_spool_open(fsp, smb_fname->base_name,
2465 req->vuid);
2468 if (!parent_dirname(talloc_tos(), smb_fname->base_name, &parent_dir,
2469 NULL)) {
2470 return NT_STATUS_NO_MEMORY;
2473 if (new_dos_attributes & FILE_FLAG_POSIX_SEMANTICS) {
2474 posix_open = True;
2475 unx_mode = (mode_t)(new_dos_attributes & ~FILE_FLAG_POSIX_SEMANTICS);
2476 new_dos_attributes = 0;
2477 } else {
2478 /* Windows allows a new file to be created and
2479 silently removes a FILE_ATTRIBUTE_DIRECTORY
2480 sent by the client. Do the same. */
2482 new_dos_attributes &= ~FILE_ATTRIBUTE_DIRECTORY;
2484 /* We add FILE_ATTRIBUTE_ARCHIVE to this as this mode is only used if the file is
2485 * created new. */
2486 unx_mode = unix_mode(conn, new_dos_attributes | FILE_ATTRIBUTE_ARCHIVE,
2487 smb_fname, parent_dir);
2490 DEBUG(10, ("open_file_ntcreate: fname=%s, dos_attrs=0x%x "
2491 "access_mask=0x%x share_access=0x%x "
2492 "create_disposition = 0x%x create_options=0x%x "
2493 "unix mode=0%o oplock_request=%d private_flags = 0x%x\n",
2494 smb_fname_str_dbg(smb_fname), new_dos_attributes,
2495 access_mask, share_access, create_disposition,
2496 create_options, (unsigned int)unx_mode, oplock_request,
2497 (unsigned int)private_flags));
2499 if (req == NULL) {
2500 /* Ensure req == NULL means INTERNAL_OPEN_ONLY */
2501 SMB_ASSERT(((oplock_request & INTERNAL_OPEN_ONLY) != 0));
2502 } else {
2503 /* And req != NULL means no INTERNAL_OPEN_ONLY */
2504 SMB_ASSERT(((oplock_request & INTERNAL_OPEN_ONLY) == 0));
2508 * Only non-internal opens can be deferred at all
2511 if (req) {
2512 struct deferred_open_record *open_rec;
2513 if (get_deferred_open_message_state(req,
2514 &request_time,
2515 &open_rec)) {
2516 /* Remember the absolute time of the original
2517 request with this mid. We'll use it later to
2518 see if this has timed out. */
2520 /* If it was an async create retry, the file
2521 didn't exist. */
2523 if (is_deferred_open_async(open_rec)) {
2524 SET_STAT_INVALID(smb_fname->st);
2525 file_existed = false;
2528 /* Ensure we don't reprocess this message. */
2529 remove_deferred_open_message_smb(req->xconn, req->mid);
2531 first_open_attempt = false;
2535 if (!posix_open) {
2536 new_dos_attributes &= SAMBA_ATTRIBUTES_MASK;
2537 if (file_existed) {
2539 * Only use strored DOS attributes for checks
2540 * against requested attributes (below via
2541 * open_match_attributes()), cf bug #11992
2542 * for details. -slow
2544 uint32_t attr = 0;
2546 status = SMB_VFS_GET_DOS_ATTRIBUTES(conn, smb_fname, &attr);
2547 if (NT_STATUS_IS_OK(status)) {
2548 existing_dos_attributes = attr;
2553 /* ignore any oplock requests if oplocks are disabled */
2554 if (!lp_oplocks(SNUM(conn)) ||
2555 IS_VETO_OPLOCK_PATH(conn, smb_fname->base_name)) {
2556 /* Mask off everything except the private Samba bits. */
2557 oplock_request &= SAMBA_PRIVATE_OPLOCK_MASK;
2560 /* this is for OS/2 long file names - say we don't support them */
2561 if (req != NULL && !req->posix_pathnames &&
2562 strstr(smb_fname->base_name,".+,;=[].")) {
2563 /* OS/2 Workplace shell fix may be main code stream in a later
2564 * release. */
2565 DEBUG(5,("open_file_ntcreate: OS/2 long filenames are not "
2566 "supported.\n"));
2567 if (use_nt_status()) {
2568 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
2570 return NT_STATUS_DOS(ERRDOS, ERRcannotopen);
2573 switch( create_disposition ) {
2574 case FILE_OPEN:
2575 /* If file exists open. If file doesn't exist error. */
2576 if (!file_existed) {
2577 DEBUG(5,("open_file_ntcreate: FILE_OPEN "
2578 "requested for file %s and file "
2579 "doesn't exist.\n",
2580 smb_fname_str_dbg(smb_fname)));
2581 errno = ENOENT;
2582 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
2584 break;
2586 case FILE_OVERWRITE:
2587 /* If file exists overwrite. If file doesn't exist
2588 * error. */
2589 if (!file_existed) {
2590 DEBUG(5,("open_file_ntcreate: FILE_OVERWRITE "
2591 "requested for file %s and file "
2592 "doesn't exist.\n",
2593 smb_fname_str_dbg(smb_fname) ));
2594 errno = ENOENT;
2595 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
2597 break;
2599 case FILE_CREATE:
2600 /* If file exists error. If file doesn't exist
2601 * create. */
2602 if (file_existed) {
2603 DEBUG(5,("open_file_ntcreate: FILE_CREATE "
2604 "requested for file %s and file "
2605 "already exists.\n",
2606 smb_fname_str_dbg(smb_fname)));
2607 if (S_ISDIR(smb_fname->st.st_ex_mode)) {
2608 errno = EISDIR;
2609 } else {
2610 errno = EEXIST;
2612 return map_nt_error_from_unix(errno);
2614 break;
2616 case FILE_SUPERSEDE:
2617 case FILE_OVERWRITE_IF:
2618 case FILE_OPEN_IF:
2619 break;
2620 default:
2621 return NT_STATUS_INVALID_PARAMETER;
2624 flags2 = disposition_to_open_flags(create_disposition);
2626 /* We only care about matching attributes on file exists and
2627 * overwrite. */
2629 if (!posix_open && file_existed &&
2630 ((create_disposition == FILE_OVERWRITE) ||
2631 (create_disposition == FILE_OVERWRITE_IF))) {
2632 if (!open_match_attributes(conn, existing_dos_attributes,
2633 new_dos_attributes,
2634 smb_fname->st.st_ex_mode,
2635 unx_mode, &new_unx_mode)) {
2636 DEBUG(5,("open_file_ntcreate: attributes missmatch "
2637 "for file %s (%x %x) (0%o, 0%o)\n",
2638 smb_fname_str_dbg(smb_fname),
2639 existing_dos_attributes,
2640 new_dos_attributes,
2641 (unsigned int)smb_fname->st.st_ex_mode,
2642 (unsigned int)unx_mode ));
2643 errno = EACCES;
2644 return NT_STATUS_ACCESS_DENIED;
2648 status = smbd_calculate_access_mask(conn, smb_fname,
2649 false,
2650 access_mask,
2651 &access_mask);
2652 if (!NT_STATUS_IS_OK(status)) {
2653 DEBUG(10, ("open_file_ntcreate: smbd_calculate_access_mask "
2654 "on file %s returned %s\n",
2655 smb_fname_str_dbg(smb_fname), nt_errstr(status)));
2656 return status;
2659 open_access_mask = access_mask;
2661 if (flags2 & O_TRUNC) {
2662 open_access_mask |= FILE_WRITE_DATA; /* This will cause oplock breaks. */
2665 DEBUG(10, ("open_file_ntcreate: fname=%s, after mapping "
2666 "access_mask=0x%x\n", smb_fname_str_dbg(smb_fname),
2667 access_mask));
2670 * Note that we ignore the append flag as append does not
2671 * mean the same thing under DOS and Unix.
2674 flags = calculate_open_access_flags(access_mask, private_flags);
2677 * Currently we only look at FILE_WRITE_THROUGH for create options.
2680 #if defined(O_SYNC)
2681 if ((create_options & FILE_WRITE_THROUGH) && lp_strict_sync(SNUM(conn))) {
2682 flags2 |= O_SYNC;
2684 #endif /* O_SYNC */
2686 if (posix_open && (access_mask & FILE_APPEND_DATA)) {
2687 flags2 |= O_APPEND;
2690 if (!posix_open && !CAN_WRITE(conn)) {
2692 * We should really return a permission denied error if either
2693 * O_CREAT or O_TRUNC are set, but for compatibility with
2694 * older versions of Samba we just AND them out.
2696 flags2 &= ~(O_CREAT|O_TRUNC);
2699 if (first_open_attempt && lp_kernel_oplocks(SNUM(conn))) {
2701 * With kernel oplocks the open breaking an oplock
2702 * blocks until the oplock holder has given up the
2703 * oplock or closed the file. We prevent this by first
2704 * trying to open the file with O_NONBLOCK (see "man
2705 * fcntl" on Linux). For the second try, triggered by
2706 * an oplock break response, we do not need this
2707 * anymore.
2709 * This is true under the assumption that only Samba
2710 * requests kernel oplocks. Once someone else like
2711 * NFSv4 starts to use that API, we will have to
2712 * modify this by communicating with the NFSv4 server.
2714 flags2 |= O_NONBLOCK;
2718 * Ensure we can't write on a read-only share or file.
2721 if (flags != O_RDONLY && file_existed &&
2722 (!CAN_WRITE(conn) || IS_DOS_READONLY(existing_dos_attributes))) {
2723 DEBUG(5,("open_file_ntcreate: write access requested for "
2724 "file %s on read only %s\n",
2725 smb_fname_str_dbg(smb_fname),
2726 !CAN_WRITE(conn) ? "share" : "file" ));
2727 errno = EACCES;
2728 return NT_STATUS_ACCESS_DENIED;
2731 fsp->file_id = vfs_file_id_from_sbuf(conn, &smb_fname->st);
2732 fsp->share_access = share_access;
2733 fsp->fh->private_options = private_flags;
2734 fsp->access_mask = open_access_mask; /* We change this to the
2735 * requested access_mask after
2736 * the open is done. */
2737 if (posix_open) {
2738 fsp->posix_flags |= FSP_POSIX_FLAGS_ALL;
2741 if (timeval_is_zero(&request_time)) {
2742 request_time = fsp->open_time;
2746 * Ensure we pay attention to default ACLs on directories if required.
2749 if ((flags2 & O_CREAT) && lp_inherit_acls(SNUM(conn)) &&
2750 (def_acl = directory_has_default_acl(conn, parent_dir))) {
2751 unx_mode = (0777 & lp_create_mask(SNUM(conn)));
2754 DEBUG(4,("calling open_file with flags=0x%X flags2=0x%X mode=0%o, "
2755 "access_mask = 0x%x, open_access_mask = 0x%x\n",
2756 (unsigned int)flags, (unsigned int)flags2,
2757 (unsigned int)unx_mode, (unsigned int)access_mask,
2758 (unsigned int)open_access_mask));
2760 fsp_open = open_file(fsp, conn, req, parent_dir,
2761 flags|flags2, unx_mode, access_mask,
2762 open_access_mask, &new_file_created);
2764 if (NT_STATUS_EQUAL(fsp_open, NT_STATUS_NETWORK_BUSY)) {
2765 struct deferred_open_record state;
2768 * EWOULDBLOCK/EAGAIN maps to NETWORK_BUSY.
2770 if (file_existed && S_ISFIFO(fsp->fsp_name->st.st_ex_mode)) {
2771 DEBUG(10, ("FIFO busy\n"));
2772 return NT_STATUS_NETWORK_BUSY;
2774 if (req == NULL) {
2775 DEBUG(10, ("Internal open busy\n"));
2776 return NT_STATUS_NETWORK_BUSY;
2780 * From here on we assume this is an oplock break triggered
2783 lck = get_existing_share_mode_lock(talloc_tos(), fsp->file_id);
2784 if (lck == NULL) {
2785 state.delayed_for_oplocks = false;
2786 state.async_open = false;
2787 state.id = fsp->file_id;
2788 defer_open(NULL, request_time, timeval_set(0, 0),
2789 req, &state);
2790 DEBUG(10, ("No share mode lock found after "
2791 "EWOULDBLOCK, retrying sync\n"));
2792 return NT_STATUS_SHARING_VIOLATION;
2795 if (!validate_oplock_types(lck)) {
2796 smb_panic("validate_oplock_types failed");
2799 if (delay_for_oplock(fsp, 0, lease, lck, false,
2800 create_disposition, first_open_attempt)) {
2801 schedule_defer_open(lck, fsp->file_id, request_time,
2802 req);
2803 TALLOC_FREE(lck);
2804 DEBUG(10, ("Sent oplock break request to kernel "
2805 "oplock holder\n"));
2806 return NT_STATUS_SHARING_VIOLATION;
2810 * No oplock from Samba around. Immediately retry with
2811 * a blocking open.
2813 state.delayed_for_oplocks = false;
2814 state.async_open = false;
2815 state.id = fsp->file_id;
2816 defer_open(lck, request_time, timeval_set(0, 0), req, &state);
2817 TALLOC_FREE(lck);
2818 DEBUG(10, ("No Samba oplock around after EWOULDBLOCK. "
2819 "Retrying sync\n"));
2820 return NT_STATUS_SHARING_VIOLATION;
2823 if (!NT_STATUS_IS_OK(fsp_open)) {
2824 if (NT_STATUS_EQUAL(fsp_open, NT_STATUS_RETRY)) {
2825 schedule_async_open(request_time, req);
2827 return fsp_open;
2830 if (new_file_created) {
2832 * As we atomically create using O_CREAT|O_EXCL,
2833 * then if new_file_created is true, then
2834 * file_existed *MUST* have been false (even
2835 * if the file was previously detected as being
2836 * there).
2838 file_existed = false;
2841 if (file_existed && !check_same_dev_ino(&saved_stat, &smb_fname->st)) {
2843 * The file did exist, but some other (local or NFS)
2844 * process either renamed/unlinked and re-created the
2845 * file with different dev/ino after we walked the path,
2846 * but before we did the open. We could retry the
2847 * open but it's a rare enough case it's easier to
2848 * just fail the open to prevent creating any problems
2849 * in the open file db having the wrong dev/ino key.
2851 fd_close(fsp);
2852 DEBUG(1,("open_file_ntcreate: file %s - dev/ino mismatch. "
2853 "Old (dev=0x%llu, ino =0x%llu). "
2854 "New (dev=0x%llu, ino=0x%llu). Failing open "
2855 " with NT_STATUS_ACCESS_DENIED.\n",
2856 smb_fname_str_dbg(smb_fname),
2857 (unsigned long long)saved_stat.st_ex_dev,
2858 (unsigned long long)saved_stat.st_ex_ino,
2859 (unsigned long long)smb_fname->st.st_ex_dev,
2860 (unsigned long long)smb_fname->st.st_ex_ino));
2861 return NT_STATUS_ACCESS_DENIED;
2864 old_write_time = smb_fname->st.st_ex_mtime;
2867 * Deal with the race condition where two smbd's detect the
2868 * file doesn't exist and do the create at the same time. One
2869 * of them will win and set a share mode, the other (ie. this
2870 * one) should check if the requested share mode for this
2871 * create is allowed.
2875 * Now the file exists and fsp is successfully opened,
2876 * fsp->dev and fsp->inode are valid and should replace the
2877 * dev=0,inode=0 from a non existent file. Spotted by
2878 * Nadav Danieli <nadavd@exanet.com>. JRA.
2881 id = fsp->file_id;
2883 lck = get_share_mode_lock(talloc_tos(), id,
2884 conn->connectpath,
2885 smb_fname, &old_write_time);
2887 if (lck == NULL) {
2888 DEBUG(0, ("open_file_ntcreate: Could not get share "
2889 "mode lock for %s\n",
2890 smb_fname_str_dbg(smb_fname)));
2891 fd_close(fsp);
2892 return NT_STATUS_SHARING_VIOLATION;
2895 /* Get the types we need to examine. */
2896 if (!validate_oplock_types(lck)) {
2897 smb_panic("validate_oplock_types failed");
2900 if (has_delete_on_close(lck, fsp->name_hash)) {
2901 TALLOC_FREE(lck);
2902 fd_close(fsp);
2903 return NT_STATUS_DELETE_PENDING;
2906 status = open_mode_check(conn, lck,
2907 access_mask, share_access);
2909 if (NT_STATUS_EQUAL(status, NT_STATUS_SHARING_VIOLATION) ||
2910 (lck->data->num_share_modes > 0)) {
2912 * This comes from ancient times out of open_mode_check. I
2913 * have no clue whether this is still necessary. I can't think
2914 * of a case where this would actually matter further down in
2915 * this function. I leave it here for further investigation
2916 * :-)
2918 file_existed = true;
2921 if ((req != NULL) &&
2922 delay_for_oplock(
2923 fsp, oplock_request, lease, lck,
2924 NT_STATUS_EQUAL(status, NT_STATUS_SHARING_VIOLATION),
2925 create_disposition, first_open_attempt)) {
2926 schedule_defer_open(lck, fsp->file_id, request_time, req);
2927 TALLOC_FREE(lck);
2928 fd_close(fsp);
2929 return NT_STATUS_SHARING_VIOLATION;
2932 if (!NT_STATUS_IS_OK(status)) {
2933 uint32_t can_access_mask;
2934 bool can_access = True;
2936 SMB_ASSERT(NT_STATUS_EQUAL(status, NT_STATUS_SHARING_VIOLATION));
2938 /* Check if this can be done with the deny_dos and fcb
2939 * calls. */
2940 if (private_flags &
2941 (NTCREATEX_OPTIONS_PRIVATE_DENY_DOS|
2942 NTCREATEX_OPTIONS_PRIVATE_DENY_FCB)) {
2943 if (req == NULL) {
2944 DEBUG(0, ("DOS open without an SMB "
2945 "request!\n"));
2946 TALLOC_FREE(lck);
2947 fd_close(fsp);
2948 return NT_STATUS_INTERNAL_ERROR;
2951 /* Use the client requested access mask here,
2952 * not the one we open with. */
2953 status = fcb_or_dos_open(req,
2954 conn,
2955 fsp,
2956 smb_fname,
2958 req->smbpid,
2959 req->vuid,
2960 access_mask,
2961 share_access,
2962 create_options);
2964 if (NT_STATUS_IS_OK(status)) {
2965 TALLOC_FREE(lck);
2966 if (pinfo) {
2967 *pinfo = FILE_WAS_OPENED;
2969 return NT_STATUS_OK;
2974 * This next line is a subtlety we need for
2975 * MS-Access. If a file open will fail due to share
2976 * permissions and also for security (access) reasons,
2977 * we need to return the access failed error, not the
2978 * share error. We can't open the file due to kernel
2979 * oplock deadlock (it's possible we failed above on
2980 * the open_mode_check()) so use a userspace check.
2983 if (flags & O_RDWR) {
2984 can_access_mask = FILE_READ_DATA|FILE_WRITE_DATA;
2985 } else if (flags & O_WRONLY) {
2986 can_access_mask = FILE_WRITE_DATA;
2987 } else {
2988 can_access_mask = FILE_READ_DATA;
2991 if (((can_access_mask & FILE_WRITE_DATA) &&
2992 !CAN_WRITE(conn)) ||
2993 !NT_STATUS_IS_OK(smbd_check_access_rights(conn,
2994 smb_fname,
2995 false,
2996 can_access_mask))) {
2997 can_access = False;
3001 * If we're returning a share violation, ensure we
3002 * cope with the braindead 1 second delay (SMB1 only).
3005 if (!(oplock_request & INTERNAL_OPEN_ONLY) &&
3006 !conn->sconn->using_smb2 &&
3007 lp_defer_sharing_violations()) {
3008 struct timeval timeout;
3009 struct deferred_open_record state;
3010 int timeout_usecs;
3012 /* this is a hack to speed up torture tests
3013 in 'make test' */
3014 timeout_usecs = lp_parm_int(SNUM(conn),
3015 "smbd","sharedelay",
3016 SHARING_VIOLATION_USEC_WAIT);
3018 /* This is a relative time, added to the absolute
3019 request_time value to get the absolute timeout time.
3020 Note that if this is the second or greater time we enter
3021 this codepath for this particular request mid then
3022 request_time is left as the absolute time of the *first*
3023 time this request mid was processed. This is what allows
3024 the request to eventually time out. */
3026 timeout = timeval_set(0, timeout_usecs);
3028 /* Nothing actually uses state.delayed_for_oplocks
3029 but it's handy to differentiate in debug messages
3030 between a 30 second delay due to oplock break, and
3031 a 1 second delay for share mode conflicts. */
3033 state.delayed_for_oplocks = False;
3034 state.async_open = false;
3035 state.id = id;
3037 if ((req != NULL)
3038 && !request_timed_out(request_time,
3039 timeout)) {
3040 defer_open(lck, request_time, timeout,
3041 req, &state);
3045 TALLOC_FREE(lck);
3046 fd_close(fsp);
3047 if (can_access) {
3049 * We have detected a sharing violation here
3050 * so return the correct error code
3052 status = NT_STATUS_SHARING_VIOLATION;
3053 } else {
3054 status = NT_STATUS_ACCESS_DENIED;
3056 return status;
3059 /* Should we atomically (to the client at least) truncate ? */
3060 if ((!new_file_created) &&
3061 (flags2 & O_TRUNC) &&
3062 (!S_ISFIFO(fsp->fsp_name->st.st_ex_mode))) {
3063 int ret;
3065 ret = vfs_set_filelen(fsp, 0);
3066 if (ret != 0) {
3067 status = map_nt_error_from_unix(errno);
3068 TALLOC_FREE(lck);
3069 fd_close(fsp);
3070 return status;
3075 * We have the share entry *locked*.....
3078 /* Delete streams if create_disposition requires it */
3079 if (!new_file_created && clear_ads(create_disposition) &&
3080 !is_ntfs_stream_smb_fname(smb_fname)) {
3081 status = delete_all_streams(conn, smb_fname);
3082 if (!NT_STATUS_IS_OK(status)) {
3083 TALLOC_FREE(lck);
3084 fd_close(fsp);
3085 return status;
3089 /* note that we ignore failure for the following. It is
3090 basically a hack for NFS, and NFS will never set one of
3091 these only read them. Nobody but Samba can ever set a deny
3092 mode and we have already checked our more authoritative
3093 locking database for permission to set this deny mode. If
3094 the kernel refuses the operations then the kernel is wrong.
3095 note that GPFS supports it as well - jmcd */
3097 if (fsp->fh->fd != -1 && lp_kernel_share_modes(SNUM(conn))) {
3098 int ret_flock;
3100 * Beware: streams implementing VFS modules may
3101 * implement streams in a way that fsp will have the
3102 * basefile open in the fsp fd, so lacking a distinct
3103 * fd for the stream kernel_flock will apply on the
3104 * basefile which is wrong. The actual check is
3105 * deffered to the VFS module implementing the
3106 * kernel_flock call.
3108 ret_flock = SMB_VFS_KERNEL_FLOCK(fsp, share_access, access_mask);
3109 if(ret_flock == -1 ){
3111 TALLOC_FREE(lck);
3112 fd_close(fsp);
3114 return NT_STATUS_SHARING_VIOLATION;
3117 fsp->kernel_share_modes_taken = true;
3121 * At this point onwards, we can guarantee that the share entry
3122 * is locked, whether we created the file or not, and that the
3123 * deny mode is compatible with all current opens.
3127 * According to Samba4, SEC_FILE_READ_ATTRIBUTE is always granted,
3128 * but we don't have to store this - just ignore it on access check.
3130 if (conn->sconn->using_smb2) {
3132 * SMB2 doesn't return it (according to Microsoft tests).
3133 * Test Case: TestSuite_ScenarioNo009GrantedAccessTestS0
3134 * File created with access = 0x7 (Read, Write, Delete)
3135 * Query Info on file returns 0x87 (Read, Write, Delete, Read Attributes)
3137 fsp->access_mask = access_mask;
3138 } else {
3139 /* But SMB1 does. */
3140 fsp->access_mask = access_mask | FILE_READ_ATTRIBUTES;
3143 if (file_existed) {
3145 * stat opens on existing files don't get oplocks.
3146 * They can get leases.
3148 * Note that we check for stat open on the *open_access_mask*,
3149 * i.e. the access mask we actually used to do the open,
3150 * not the one the client asked for (which is in
3151 * fsp->access_mask). This is due to the fact that
3152 * FILE_OVERWRITE and FILE_OVERWRITE_IF add in O_TRUNC,
3153 * which adds FILE_WRITE_DATA to open_access_mask.
3155 if (is_stat_open(open_access_mask) && lease == NULL) {
3156 oplock_request = NO_OPLOCK;
3160 if (new_file_created) {
3161 info = FILE_WAS_CREATED;
3162 } else {
3163 if (flags2 & O_TRUNC) {
3164 info = FILE_WAS_OVERWRITTEN;
3165 } else {
3166 info = FILE_WAS_OPENED;
3170 if (pinfo) {
3171 *pinfo = info;
3175 * Setup the oplock info in both the shared memory and
3176 * file structs.
3178 status = grant_fsp_oplock_type(req, fsp, lck, oplock_request, lease);
3179 if (!NT_STATUS_IS_OK(status)) {
3180 TALLOC_FREE(lck);
3181 fd_close(fsp);
3182 return status;
3185 /* Handle strange delete on close create semantics. */
3186 if (create_options & FILE_DELETE_ON_CLOSE) {
3188 status = can_set_delete_on_close(fsp, new_dos_attributes);
3190 if (!NT_STATUS_IS_OK(status)) {
3191 /* Remember to delete the mode we just added. */
3192 del_share_mode(lck, fsp);
3193 TALLOC_FREE(lck);
3194 fd_close(fsp);
3195 return status;
3197 /* Note that here we set the *inital* delete on close flag,
3198 not the regular one. The magic gets handled in close. */
3199 fsp->initial_delete_on_close = True;
3202 if (info != FILE_WAS_OPENED) {
3203 /* Overwritten files should be initially set as archive */
3204 if ((info == FILE_WAS_OVERWRITTEN && lp_map_archive(SNUM(conn))) ||
3205 lp_store_dos_attributes(SNUM(conn))) {
3206 if (!posix_open) {
3207 if (file_set_dosmode(conn, smb_fname,
3208 new_dos_attributes | FILE_ATTRIBUTE_ARCHIVE,
3209 parent_dir, true) == 0) {
3210 unx_mode = smb_fname->st.st_ex_mode;
3216 /* Determine sparse flag. */
3217 if (posix_open) {
3218 /* POSIX opens are sparse by default. */
3219 fsp->is_sparse = true;
3220 } else {
3221 fsp->is_sparse = (file_existed &&
3222 (existing_dos_attributes & FILE_ATTRIBUTE_SPARSE));
3226 * Take care of inherited ACLs on created files - if default ACL not
3227 * selected.
3230 if (!posix_open && new_file_created && !def_acl) {
3232 int saved_errno = errno; /* We might get ENOSYS in the next
3233 * call.. */
3235 if (SMB_VFS_FCHMOD_ACL(fsp, unx_mode) == -1 &&
3236 errno == ENOSYS) {
3237 errno = saved_errno; /* Ignore ENOSYS */
3240 } else if (new_unx_mode) {
3242 int ret = -1;
3244 /* Attributes need changing. File already existed. */
3247 int saved_errno = errno; /* We might get ENOSYS in the
3248 * next call.. */
3249 ret = SMB_VFS_FCHMOD_ACL(fsp, new_unx_mode);
3251 if (ret == -1 && errno == ENOSYS) {
3252 errno = saved_errno; /* Ignore ENOSYS */
3253 } else {
3254 DEBUG(5, ("open_file_ntcreate: reset "
3255 "attributes of file %s to 0%o\n",
3256 smb_fname_str_dbg(smb_fname),
3257 (unsigned int)new_unx_mode));
3258 ret = 0; /* Don't do the fchmod below. */
3262 if ((ret == -1) &&
3263 (SMB_VFS_FCHMOD(fsp, new_unx_mode) == -1))
3264 DEBUG(5, ("open_file_ntcreate: failed to reset "
3265 "attributes of file %s to 0%o\n",
3266 smb_fname_str_dbg(smb_fname),
3267 (unsigned int)new_unx_mode));
3272 * Deal with other opens having a modified write time.
3274 struct timespec write_time = get_share_mode_write_time(lck);
3276 if (!null_timespec(write_time)) {
3277 update_stat_ex_mtime(&fsp->fsp_name->st, write_time);
3281 TALLOC_FREE(lck);
3283 return NT_STATUS_OK;
3286 static NTSTATUS mkdir_internal(connection_struct *conn,
3287 struct smb_filename *smb_dname,
3288 uint32_t file_attributes)
3290 mode_t mode;
3291 char *parent_dir = NULL;
3292 NTSTATUS status;
3293 bool posix_open = false;
3294 bool need_re_stat = false;
3295 uint32_t access_mask = SEC_DIR_ADD_SUBDIR;
3297 if (!CAN_WRITE(conn) || (access_mask & ~(conn->share_access))) {
3298 DEBUG(5,("mkdir_internal: failing share access "
3299 "%s\n", lp_servicename(talloc_tos(), SNUM(conn))));
3300 return NT_STATUS_ACCESS_DENIED;
3303 if (!parent_dirname(talloc_tos(), smb_dname->base_name, &parent_dir,
3304 NULL)) {
3305 return NT_STATUS_NO_MEMORY;
3308 if (file_attributes & FILE_FLAG_POSIX_SEMANTICS) {
3309 posix_open = true;
3310 mode = (mode_t)(file_attributes & ~FILE_FLAG_POSIX_SEMANTICS);
3311 } else {
3312 mode = unix_mode(conn, FILE_ATTRIBUTE_DIRECTORY, smb_dname, parent_dir);
3315 status = check_parent_access(conn,
3316 smb_dname,
3317 access_mask);
3318 if(!NT_STATUS_IS_OK(status)) {
3319 DEBUG(5,("mkdir_internal: check_parent_access "
3320 "on directory %s for path %s returned %s\n",
3321 parent_dir,
3322 smb_dname->base_name,
3323 nt_errstr(status) ));
3324 return status;
3327 if (SMB_VFS_MKDIR(conn, smb_dname, mode) != 0) {
3328 return map_nt_error_from_unix(errno);
3331 /* Ensure we're checking for a symlink here.... */
3332 /* We don't want to get caught by a symlink racer. */
3334 if (SMB_VFS_LSTAT(conn, smb_dname) == -1) {
3335 DEBUG(2, ("Could not stat directory '%s' just created: %s\n",
3336 smb_fname_str_dbg(smb_dname), strerror(errno)));
3337 return map_nt_error_from_unix(errno);
3340 if (!S_ISDIR(smb_dname->st.st_ex_mode)) {
3341 DEBUG(0, ("Directory '%s' just created is not a directory !\n",
3342 smb_fname_str_dbg(smb_dname)));
3343 return NT_STATUS_NOT_A_DIRECTORY;
3346 if (lp_store_dos_attributes(SNUM(conn))) {
3347 if (!posix_open) {
3348 file_set_dosmode(conn, smb_dname,
3349 file_attributes | FILE_ATTRIBUTE_DIRECTORY,
3350 parent_dir, true);
3354 if (lp_inherit_permissions(SNUM(conn))) {
3355 inherit_access_posix_acl(conn, parent_dir,
3356 smb_dname->base_name, mode);
3357 need_re_stat = true;
3360 if (!posix_open) {
3362 * Check if high bits should have been set,
3363 * then (if bits are missing): add them.
3364 * Consider bits automagically set by UNIX, i.e. SGID bit from parent
3365 * dir.
3367 if ((mode & ~(S_IRWXU|S_IRWXG|S_IRWXO)) &&
3368 (mode & ~smb_dname->st.st_ex_mode)) {
3369 SMB_VFS_CHMOD(conn, smb_dname,
3370 (smb_dname->st.st_ex_mode |
3371 (mode & ~smb_dname->st.st_ex_mode)));
3372 need_re_stat = true;
3376 /* Change the owner if required. */
3377 if (lp_inherit_owner(SNUM(conn))) {
3378 change_dir_owner_to_parent(conn, parent_dir,
3379 smb_dname->base_name,
3380 &smb_dname->st);
3381 need_re_stat = true;
3384 if (need_re_stat) {
3385 if (SMB_VFS_LSTAT(conn, smb_dname) == -1) {
3386 DEBUG(2, ("Could not stat directory '%s' just created: %s\n",
3387 smb_fname_str_dbg(smb_dname), strerror(errno)));
3388 return map_nt_error_from_unix(errno);
3392 notify_fname(conn, NOTIFY_ACTION_ADDED, FILE_NOTIFY_CHANGE_DIR_NAME,
3393 smb_dname->base_name);
3395 return NT_STATUS_OK;
3398 /****************************************************************************
3399 Open a directory from an NT SMB call.
3400 ****************************************************************************/
3402 static NTSTATUS open_directory(connection_struct *conn,
3403 struct smb_request *req,
3404 struct smb_filename *smb_dname,
3405 uint32_t access_mask,
3406 uint32_t share_access,
3407 uint32_t create_disposition,
3408 uint32_t create_options,
3409 uint32_t file_attributes,
3410 int *pinfo,
3411 files_struct **result)
3413 files_struct *fsp = NULL;
3414 bool dir_existed = VALID_STAT(smb_dname->st) ? True : False;
3415 struct share_mode_lock *lck = NULL;
3416 NTSTATUS status;
3417 struct timespec mtimespec;
3418 int info = 0;
3419 bool ok;
3421 if (is_ntfs_stream_smb_fname(smb_dname)) {
3422 DEBUG(2, ("open_directory: %s is a stream name!\n",
3423 smb_fname_str_dbg(smb_dname)));
3424 return NT_STATUS_NOT_A_DIRECTORY;
3427 if (!(file_attributes & FILE_FLAG_POSIX_SEMANTICS)) {
3428 /* Ensure we have a directory attribute. */
3429 file_attributes |= FILE_ATTRIBUTE_DIRECTORY;
3432 DEBUG(5,("open_directory: opening directory %s, access_mask = 0x%x, "
3433 "share_access = 0x%x create_options = 0x%x, "
3434 "create_disposition = 0x%x, file_attributes = 0x%x\n",
3435 smb_fname_str_dbg(smb_dname),
3436 (unsigned int)access_mask,
3437 (unsigned int)share_access,
3438 (unsigned int)create_options,
3439 (unsigned int)create_disposition,
3440 (unsigned int)file_attributes));
3442 status = smbd_calculate_access_mask(conn, smb_dname, false,
3443 access_mask, &access_mask);
3444 if (!NT_STATUS_IS_OK(status)) {
3445 DEBUG(10, ("open_directory: smbd_calculate_access_mask "
3446 "on file %s returned %s\n",
3447 smb_fname_str_dbg(smb_dname),
3448 nt_errstr(status)));
3449 return status;
3452 if ((access_mask & SEC_FLAG_SYSTEM_SECURITY) &&
3453 !security_token_has_privilege(get_current_nttok(conn),
3454 SEC_PRIV_SECURITY)) {
3455 DEBUG(10, ("open_directory: open on %s "
3456 "failed - SEC_FLAG_SYSTEM_SECURITY denied.\n",
3457 smb_fname_str_dbg(smb_dname)));
3458 return NT_STATUS_PRIVILEGE_NOT_HELD;
3461 switch( create_disposition ) {
3462 case FILE_OPEN:
3464 if (!dir_existed) {
3465 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3468 info = FILE_WAS_OPENED;
3469 break;
3471 case FILE_CREATE:
3473 /* If directory exists error. If directory doesn't
3474 * exist create. */
3476 if (dir_existed) {
3477 status = NT_STATUS_OBJECT_NAME_COLLISION;
3478 DEBUG(2, ("open_directory: unable to create "
3479 "%s. Error was %s\n",
3480 smb_fname_str_dbg(smb_dname),
3481 nt_errstr(status)));
3482 return status;
3485 status = mkdir_internal(conn, smb_dname,
3486 file_attributes);
3488 if (!NT_STATUS_IS_OK(status)) {
3489 DEBUG(2, ("open_directory: unable to create "
3490 "%s. Error was %s\n",
3491 smb_fname_str_dbg(smb_dname),
3492 nt_errstr(status)));
3493 return status;
3496 info = FILE_WAS_CREATED;
3497 break;
3499 case FILE_OPEN_IF:
3501 * If directory exists open. If directory doesn't
3502 * exist create.
3505 if (dir_existed) {
3506 status = NT_STATUS_OK;
3507 info = FILE_WAS_OPENED;
3508 } else {
3509 status = mkdir_internal(conn, smb_dname,
3510 file_attributes);
3512 if (NT_STATUS_IS_OK(status)) {
3513 info = FILE_WAS_CREATED;
3514 } else {
3515 /* Cope with create race. */
3516 if (!NT_STATUS_EQUAL(status,
3517 NT_STATUS_OBJECT_NAME_COLLISION)) {
3518 DEBUG(2, ("open_directory: unable to create "
3519 "%s. Error was %s\n",
3520 smb_fname_str_dbg(smb_dname),
3521 nt_errstr(status)));
3522 return status;
3526 * If mkdir_internal() returned
3527 * NT_STATUS_OBJECT_NAME_COLLISION
3528 * we still must lstat the path.
3531 if (SMB_VFS_LSTAT(conn, smb_dname)
3532 == -1) {
3533 DEBUG(2, ("Could not stat "
3534 "directory '%s' just "
3535 "opened: %s\n",
3536 smb_fname_str_dbg(
3537 smb_dname),
3538 strerror(errno)));
3539 return map_nt_error_from_unix(
3540 errno);
3543 info = FILE_WAS_OPENED;
3547 break;
3549 case FILE_SUPERSEDE:
3550 case FILE_OVERWRITE:
3551 case FILE_OVERWRITE_IF:
3552 default:
3553 DEBUG(5,("open_directory: invalid create_disposition "
3554 "0x%x for directory %s\n",
3555 (unsigned int)create_disposition,
3556 smb_fname_str_dbg(smb_dname)));
3557 return NT_STATUS_INVALID_PARAMETER;
3560 if(!S_ISDIR(smb_dname->st.st_ex_mode)) {
3561 DEBUG(5,("open_directory: %s is not a directory !\n",
3562 smb_fname_str_dbg(smb_dname)));
3563 return NT_STATUS_NOT_A_DIRECTORY;
3566 if (info == FILE_WAS_OPENED) {
3567 status = smbd_check_access_rights(conn,
3568 smb_dname,
3569 false,
3570 access_mask);
3571 if (!NT_STATUS_IS_OK(status)) {
3572 DEBUG(10, ("open_directory: smbd_check_access_rights on "
3573 "file %s failed with %s\n",
3574 smb_fname_str_dbg(smb_dname),
3575 nt_errstr(status)));
3576 return status;
3580 status = file_new(req, conn, &fsp);
3581 if(!NT_STATUS_IS_OK(status)) {
3582 return status;
3586 * Setup the files_struct for it.
3589 fsp->file_id = vfs_file_id_from_sbuf(conn, &smb_dname->st);
3590 fsp->vuid = req ? req->vuid : UID_FIELD_INVALID;
3591 fsp->file_pid = req ? req->smbpid : 0;
3592 fsp->can_lock = False;
3593 fsp->can_read = False;
3594 fsp->can_write = False;
3596 fsp->share_access = share_access;
3597 fsp->fh->private_options = 0;
3599 * According to Samba4, SEC_FILE_READ_ATTRIBUTE is always granted,
3601 fsp->access_mask = access_mask | FILE_READ_ATTRIBUTES;
3602 fsp->print_file = NULL;
3603 fsp->modified = False;
3604 fsp->oplock_type = NO_OPLOCK;
3605 fsp->sent_oplock_break = NO_BREAK_SENT;
3606 fsp->is_directory = True;
3607 if (file_attributes & FILE_FLAG_POSIX_SEMANTICS) {
3608 fsp->posix_flags |= FSP_POSIX_FLAGS_ALL;
3610 status = fsp_set_smb_fname(fsp, smb_dname);
3611 if (!NT_STATUS_IS_OK(status)) {
3612 file_free(req, fsp);
3613 return status;
3616 /* Don't store old timestamps for directory
3617 handles in the internal database. We don't
3618 update them in there if new objects
3619 are creaded in the directory. Currently
3620 we only update timestamps on file writes.
3621 See bug #9870.
3623 ZERO_STRUCT(mtimespec);
3625 if (access_mask & (FILE_LIST_DIRECTORY|
3626 FILE_ADD_FILE|
3627 FILE_ADD_SUBDIRECTORY|
3628 FILE_TRAVERSE|
3629 DELETE_ACCESS|
3630 FILE_DELETE_CHILD)) {
3631 #ifdef O_DIRECTORY
3632 status = fd_open(conn, fsp, O_RDONLY|O_DIRECTORY, 0);
3633 #else
3634 /* POSIX allows us to open a directory with O_RDONLY. */
3635 status = fd_open(conn, fsp, O_RDONLY, 0);
3636 #endif
3637 if (!NT_STATUS_IS_OK(status)) {
3638 DEBUG(5, ("open_directory: Could not open fd for "
3639 "%s (%s)\n",
3640 smb_fname_str_dbg(smb_dname),
3641 nt_errstr(status)));
3642 file_free(req, fsp);
3643 return status;
3645 } else {
3646 fsp->fh->fd = -1;
3647 DEBUG(10, ("Not opening Directory %s\n",
3648 smb_fname_str_dbg(smb_dname)));
3651 status = vfs_stat_fsp(fsp);
3652 if (!NT_STATUS_IS_OK(status)) {
3653 fd_close(fsp);
3654 file_free(req, fsp);
3655 return status;
3658 if(!S_ISDIR(fsp->fsp_name->st.st_ex_mode)) {
3659 DEBUG(5,("open_directory: %s is not a directory !\n",
3660 smb_fname_str_dbg(smb_dname)));
3661 fd_close(fsp);
3662 file_free(req, fsp);
3663 return NT_STATUS_NOT_A_DIRECTORY;
3666 /* Ensure there was no race condition. We need to check
3667 * dev/inode but not permissions, as these can change
3668 * legitimately */
3669 if (!check_same_dev_ino(&smb_dname->st, &fsp->fsp_name->st)) {
3670 DEBUG(5,("open_directory: stat struct differs for "
3671 "directory %s.\n",
3672 smb_fname_str_dbg(smb_dname)));
3673 fd_close(fsp);
3674 file_free(req, fsp);
3675 return NT_STATUS_ACCESS_DENIED;
3678 lck = get_share_mode_lock(talloc_tos(), fsp->file_id,
3679 conn->connectpath, smb_dname,
3680 &mtimespec);
3682 if (lck == NULL) {
3683 DEBUG(0, ("open_directory: Could not get share mode lock for "
3684 "%s\n", smb_fname_str_dbg(smb_dname)));
3685 fd_close(fsp);
3686 file_free(req, fsp);
3687 return NT_STATUS_SHARING_VIOLATION;
3690 if (has_delete_on_close(lck, fsp->name_hash)) {
3691 TALLOC_FREE(lck);
3692 fd_close(fsp);
3693 file_free(req, fsp);
3694 return NT_STATUS_DELETE_PENDING;
3697 status = open_mode_check(conn, lck,
3698 access_mask, share_access);
3700 if (!NT_STATUS_IS_OK(status)) {
3701 TALLOC_FREE(lck);
3702 fd_close(fsp);
3703 file_free(req, fsp);
3704 return status;
3707 ok = set_share_mode(lck, fsp, get_current_uid(conn),
3708 req ? req->mid : 0, NO_OPLOCK,
3709 UINT32_MAX);
3710 if (!ok) {
3711 TALLOC_FREE(lck);
3712 fd_close(fsp);
3713 file_free(req, fsp);
3714 return NT_STATUS_NO_MEMORY;
3717 /* For directories the delete on close bit at open time seems
3718 always to be honored on close... See test 19 in Samba4 BASE-DELETE. */
3719 if (create_options & FILE_DELETE_ON_CLOSE) {
3720 status = can_set_delete_on_close(fsp, 0);
3721 if (!NT_STATUS_IS_OK(status) && !NT_STATUS_EQUAL(status, NT_STATUS_DIRECTORY_NOT_EMPTY)) {
3722 del_share_mode(lck, fsp);
3723 TALLOC_FREE(lck);
3724 fd_close(fsp);
3725 file_free(req, fsp);
3726 return status;
3729 if (NT_STATUS_IS_OK(status)) {
3730 /* Note that here we set the *inital* delete on close flag,
3731 not the regular one. The magic gets handled in close. */
3732 fsp->initial_delete_on_close = True;
3738 * Deal with other opens having a modified write time. Is this
3739 * possible for directories?
3741 struct timespec write_time = get_share_mode_write_time(lck);
3743 if (!null_timespec(write_time)) {
3744 update_stat_ex_mtime(&fsp->fsp_name->st, write_time);
3748 TALLOC_FREE(lck);
3750 if (pinfo) {
3751 *pinfo = info;
3754 *result = fsp;
3755 return NT_STATUS_OK;
3758 NTSTATUS create_directory(connection_struct *conn, struct smb_request *req,
3759 struct smb_filename *smb_dname)
3761 NTSTATUS status;
3762 files_struct *fsp;
3764 status = SMB_VFS_CREATE_FILE(
3765 conn, /* conn */
3766 req, /* req */
3767 0, /* root_dir_fid */
3768 smb_dname, /* fname */
3769 FILE_READ_ATTRIBUTES, /* access_mask */
3770 FILE_SHARE_NONE, /* share_access */
3771 FILE_CREATE, /* create_disposition*/
3772 FILE_DIRECTORY_FILE, /* create_options */
3773 FILE_ATTRIBUTE_DIRECTORY, /* file_attributes */
3774 0, /* oplock_request */
3775 NULL, /* lease */
3776 0, /* allocation_size */
3777 0, /* private_flags */
3778 NULL, /* sd */
3779 NULL, /* ea_list */
3780 &fsp, /* result */
3781 NULL, /* pinfo */
3782 NULL, NULL); /* create context */
3784 if (NT_STATUS_IS_OK(status)) {
3785 close_file(req, fsp, NORMAL_CLOSE);
3788 return status;
3791 /****************************************************************************
3792 Receive notification that one of our open files has been renamed by another
3793 smbd process.
3794 ****************************************************************************/
3796 void msg_file_was_renamed(struct messaging_context *msg,
3797 void *private_data,
3798 uint32_t msg_type,
3799 struct server_id server_id,
3800 DATA_BLOB *data)
3802 files_struct *fsp;
3803 char *frm = (char *)data->data;
3804 struct file_id id;
3805 const char *sharepath;
3806 const char *base_name;
3807 const char *stream_name;
3808 struct smb_filename *smb_fname = NULL;
3809 size_t sp_len, bn_len;
3810 NTSTATUS status;
3811 struct smbd_server_connection *sconn =
3812 talloc_get_type_abort(private_data,
3813 struct smbd_server_connection);
3815 if (data->data == NULL
3816 || data->length < MSG_FILE_RENAMED_MIN_SIZE + 2) {
3817 DEBUG(0, ("msg_file_was_renamed: Got invalid msg len %d\n",
3818 (int)data->length));
3819 return;
3822 /* Unpack the message. */
3823 pull_file_id_24(frm, &id);
3824 sharepath = &frm[24];
3825 sp_len = strlen(sharepath);
3826 base_name = sharepath + sp_len + 1;
3827 bn_len = strlen(base_name);
3828 stream_name = sharepath + sp_len + 1 + bn_len + 1;
3830 /* stream_name must always be NULL if there is no stream. */
3831 if (stream_name[0] == '\0') {
3832 stream_name = NULL;
3835 smb_fname = synthetic_smb_fname(talloc_tos(),
3836 base_name,
3837 stream_name,
3838 NULL,
3840 if (smb_fname == NULL) {
3841 return;
3844 DEBUG(10,("msg_file_was_renamed: Got rename message for sharepath %s, new name %s, "
3845 "file_id %s\n",
3846 sharepath, smb_fname_str_dbg(smb_fname),
3847 file_id_string_tos(&id)));
3849 for(fsp = file_find_di_first(sconn, id); fsp;
3850 fsp = file_find_di_next(fsp)) {
3851 if (memcmp(fsp->conn->connectpath, sharepath, sp_len) == 0) {
3853 DEBUG(10,("msg_file_was_renamed: renaming file %s from %s -> %s\n",
3854 fsp_fnum_dbg(fsp), fsp_str_dbg(fsp),
3855 smb_fname_str_dbg(smb_fname)));
3856 status = fsp_set_smb_fname(fsp, smb_fname);
3857 if (!NT_STATUS_IS_OK(status)) {
3858 goto out;
3860 } else {
3861 /* TODO. JRA. */
3862 /* Now we have the complete path we can work out if this is
3863 actually within this share and adjust newname accordingly. */
3864 DEBUG(10,("msg_file_was_renamed: share mismatch (sharepath %s "
3865 "not sharepath %s) "
3866 "%s from %s -> %s\n",
3867 fsp->conn->connectpath,
3868 sharepath,
3869 fsp_fnum_dbg(fsp),
3870 fsp_str_dbg(fsp),
3871 smb_fname_str_dbg(smb_fname)));
3874 out:
3875 TALLOC_FREE(smb_fname);
3876 return;
3880 * If a main file is opened for delete, all streams need to be checked for
3881 * !FILE_SHARE_DELETE. Do this by opening with DELETE_ACCESS.
3882 * If that works, delete them all by setting the delete on close and close.
3885 static NTSTATUS open_streams_for_delete(connection_struct *conn,
3886 const struct smb_filename *smb_fname)
3888 struct stream_struct *stream_info = NULL;
3889 files_struct **streams = NULL;
3890 int i;
3891 unsigned int num_streams = 0;
3892 TALLOC_CTX *frame = talloc_stackframe();
3893 NTSTATUS status;
3895 status = vfs_streaminfo(conn, NULL, smb_fname, talloc_tos(),
3896 &num_streams, &stream_info);
3898 if (NT_STATUS_EQUAL(status, NT_STATUS_NOT_IMPLEMENTED)
3899 || NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
3900 DEBUG(10, ("no streams around\n"));
3901 TALLOC_FREE(frame);
3902 return NT_STATUS_OK;
3905 if (!NT_STATUS_IS_OK(status)) {
3906 DEBUG(10, ("vfs_streaminfo failed: %s\n",
3907 nt_errstr(status)));
3908 goto fail;
3911 DEBUG(10, ("open_streams_for_delete found %d streams\n",
3912 num_streams));
3914 if (num_streams == 0) {
3915 TALLOC_FREE(frame);
3916 return NT_STATUS_OK;
3919 streams = talloc_array(talloc_tos(), files_struct *, num_streams);
3920 if (streams == NULL) {
3921 DEBUG(0, ("talloc failed\n"));
3922 status = NT_STATUS_NO_MEMORY;
3923 goto fail;
3926 for (i=0; i<num_streams; i++) {
3927 struct smb_filename *smb_fname_cp;
3929 if (strequal(stream_info[i].name, "::$DATA")) {
3930 streams[i] = NULL;
3931 continue;
3934 smb_fname_cp = synthetic_smb_fname(talloc_tos(),
3935 smb_fname->base_name,
3936 stream_info[i].name,
3937 NULL,
3938 smb_fname->flags);
3939 if (smb_fname_cp == NULL) {
3940 status = NT_STATUS_NO_MEMORY;
3941 goto fail;
3944 if (SMB_VFS_STAT(conn, smb_fname_cp) == -1) {
3945 DEBUG(10, ("Unable to stat stream: %s\n",
3946 smb_fname_str_dbg(smb_fname_cp)));
3949 status = SMB_VFS_CREATE_FILE(
3950 conn, /* conn */
3951 NULL, /* req */
3952 0, /* root_dir_fid */
3953 smb_fname_cp, /* fname */
3954 DELETE_ACCESS, /* access_mask */
3955 (FILE_SHARE_READ | /* share_access */
3956 FILE_SHARE_WRITE | FILE_SHARE_DELETE),
3957 FILE_OPEN, /* create_disposition*/
3958 0, /* create_options */
3959 FILE_ATTRIBUTE_NORMAL, /* file_attributes */
3960 0, /* oplock_request */
3961 NULL, /* lease */
3962 0, /* allocation_size */
3963 NTCREATEX_OPTIONS_PRIVATE_STREAM_DELETE, /* private_flags */
3964 NULL, /* sd */
3965 NULL, /* ea_list */
3966 &streams[i], /* result */
3967 NULL, /* pinfo */
3968 NULL, NULL); /* create context */
3970 if (!NT_STATUS_IS_OK(status)) {
3971 DEBUG(10, ("Could not open stream %s: %s\n",
3972 smb_fname_str_dbg(smb_fname_cp),
3973 nt_errstr(status)));
3975 TALLOC_FREE(smb_fname_cp);
3976 break;
3978 TALLOC_FREE(smb_fname_cp);
3982 * don't touch the variable "status" beyond this point :-)
3985 for (i -= 1 ; i >= 0; i--) {
3986 if (streams[i] == NULL) {
3987 continue;
3990 DEBUG(10, ("Closing stream # %d, %s\n", i,
3991 fsp_str_dbg(streams[i])));
3992 close_file(NULL, streams[i], NORMAL_CLOSE);
3995 fail:
3996 TALLOC_FREE(frame);
3997 return status;
4000 /*********************************************************************
4001 Create a default ACL by inheriting from the parent. If no inheritance
4002 from the parent available, don't set anything. This will leave the actual
4003 permissions the new file or directory already got from the filesystem
4004 as the NT ACL when read.
4005 *********************************************************************/
4007 static NTSTATUS inherit_new_acl(files_struct *fsp)
4009 TALLOC_CTX *frame = talloc_stackframe();
4010 char *parent_name = NULL;
4011 struct security_descriptor *parent_desc = NULL;
4012 NTSTATUS status = NT_STATUS_OK;
4013 struct security_descriptor *psd = NULL;
4014 const struct dom_sid *owner_sid = NULL;
4015 const struct dom_sid *group_sid = NULL;
4016 uint32_t security_info_sent = (SECINFO_OWNER | SECINFO_GROUP | SECINFO_DACL);
4017 struct security_token *token = fsp->conn->session_info->security_token;
4018 bool inherit_owner = lp_inherit_owner(SNUM(fsp->conn));
4019 bool inheritable_components = false;
4020 bool try_builtin_administrators = false;
4021 const struct dom_sid *BA_U_sid = NULL;
4022 const struct dom_sid *BA_G_sid = NULL;
4023 bool try_system = false;
4024 const struct dom_sid *SY_U_sid = NULL;
4025 const struct dom_sid *SY_G_sid = NULL;
4026 size_t size = 0;
4027 struct smb_filename *parent_smb_fname = NULL;
4029 if (!parent_dirname(frame, fsp->fsp_name->base_name, &parent_name, NULL)) {
4030 TALLOC_FREE(frame);
4031 return NT_STATUS_NO_MEMORY;
4033 parent_smb_fname = synthetic_smb_fname(talloc_tos(),
4034 parent_name,
4035 NULL,
4036 NULL,
4037 fsp->fsp_name->flags);
4039 if (parent_smb_fname == NULL) {
4040 TALLOC_FREE(frame);
4041 return NT_STATUS_NO_MEMORY;
4044 status = SMB_VFS_GET_NT_ACL(fsp->conn,
4045 parent_smb_fname,
4046 (SECINFO_OWNER | SECINFO_GROUP | SECINFO_DACL),
4047 frame,
4048 &parent_desc);
4049 if (!NT_STATUS_IS_OK(status)) {
4050 TALLOC_FREE(frame);
4051 return status;
4054 inheritable_components = sd_has_inheritable_components(parent_desc,
4055 fsp->is_directory);
4057 if (!inheritable_components && !inherit_owner) {
4058 TALLOC_FREE(frame);
4059 /* Nothing to inherit and not setting owner. */
4060 return NT_STATUS_OK;
4063 /* Create an inherited descriptor from the parent. */
4065 if (DEBUGLEVEL >= 10) {
4066 DEBUG(10,("inherit_new_acl: parent acl for %s is:\n",
4067 fsp_str_dbg(fsp) ));
4068 NDR_PRINT_DEBUG(security_descriptor, parent_desc);
4071 /* Inherit from parent descriptor if "inherit owner" set. */
4072 if (inherit_owner) {
4073 owner_sid = parent_desc->owner_sid;
4074 group_sid = parent_desc->group_sid;
4077 if (owner_sid == NULL) {
4078 if (security_token_has_builtin_administrators(token)) {
4079 try_builtin_administrators = true;
4080 } else if (security_token_is_system(token)) {
4081 try_builtin_administrators = true;
4082 try_system = true;
4086 if (group_sid == NULL &&
4087 token->num_sids == PRIMARY_GROUP_SID_INDEX)
4089 if (security_token_is_system(token)) {
4090 try_builtin_administrators = true;
4091 try_system = true;
4095 if (try_builtin_administrators) {
4096 struct unixid ids;
4097 bool ok;
4099 ZERO_STRUCT(ids);
4100 ok = sids_to_unixids(&global_sid_Builtin_Administrators, 1, &ids);
4101 if (ok) {
4102 switch (ids.type) {
4103 case ID_TYPE_BOTH:
4104 BA_U_sid = &global_sid_Builtin_Administrators;
4105 BA_G_sid = &global_sid_Builtin_Administrators;
4106 break;
4107 case ID_TYPE_UID:
4108 BA_U_sid = &global_sid_Builtin_Administrators;
4109 break;
4110 case ID_TYPE_GID:
4111 BA_G_sid = &global_sid_Builtin_Administrators;
4112 break;
4113 default:
4114 break;
4119 if (try_system) {
4120 struct unixid ids;
4121 bool ok;
4123 ZERO_STRUCT(ids);
4124 ok = sids_to_unixids(&global_sid_System, 1, &ids);
4125 if (ok) {
4126 switch (ids.type) {
4127 case ID_TYPE_BOTH:
4128 SY_U_sid = &global_sid_System;
4129 SY_G_sid = &global_sid_System;
4130 break;
4131 case ID_TYPE_UID:
4132 SY_U_sid = &global_sid_System;
4133 break;
4134 case ID_TYPE_GID:
4135 SY_G_sid = &global_sid_System;
4136 break;
4137 default:
4138 break;
4143 if (owner_sid == NULL) {
4144 owner_sid = BA_U_sid;
4147 if (owner_sid == NULL) {
4148 owner_sid = SY_U_sid;
4151 if (group_sid == NULL) {
4152 group_sid = SY_G_sid;
4155 if (try_system && group_sid == NULL) {
4156 group_sid = BA_G_sid;
4159 if (owner_sid == NULL) {
4160 owner_sid = &token->sids[PRIMARY_USER_SID_INDEX];
4162 if (group_sid == NULL) {
4163 if (token->num_sids == PRIMARY_GROUP_SID_INDEX) {
4164 group_sid = &token->sids[PRIMARY_USER_SID_INDEX];
4165 } else {
4166 group_sid = &token->sids[PRIMARY_GROUP_SID_INDEX];
4170 status = se_create_child_secdesc(frame,
4171 &psd,
4172 &size,
4173 parent_desc,
4174 owner_sid,
4175 group_sid,
4176 fsp->is_directory);
4177 if (!NT_STATUS_IS_OK(status)) {
4178 TALLOC_FREE(frame);
4179 return status;
4182 /* If inheritable_components == false,
4183 se_create_child_secdesc()
4184 creates a security desriptor with a NULL dacl
4185 entry, but with SEC_DESC_DACL_PRESENT. We need
4186 to remove that flag. */
4188 if (!inheritable_components) {
4189 security_info_sent &= ~SECINFO_DACL;
4190 psd->type &= ~SEC_DESC_DACL_PRESENT;
4193 if (DEBUGLEVEL >= 10) {
4194 DEBUG(10,("inherit_new_acl: child acl for %s is:\n",
4195 fsp_str_dbg(fsp) ));
4196 NDR_PRINT_DEBUG(security_descriptor, psd);
4199 if (inherit_owner) {
4200 /* We need to be root to force this. */
4201 become_root();
4203 status = SMB_VFS_FSET_NT_ACL(fsp,
4204 security_info_sent,
4205 psd);
4206 if (inherit_owner) {
4207 unbecome_root();
4209 TALLOC_FREE(frame);
4210 return status;
4214 * If we already have a lease, it must match the new file id. [MS-SMB2]
4215 * 3.3.5.9.8 speaks about INVALID_PARAMETER if an already used lease key is
4216 * used for a different file name.
4219 struct lease_match_state {
4220 /* Input parameters. */
4221 TALLOC_CTX *mem_ctx;
4222 const char *servicepath;
4223 const struct smb_filename *fname;
4224 bool file_existed;
4225 struct file_id id;
4226 /* Return parameters. */
4227 uint32_t num_file_ids;
4228 struct file_id *ids;
4229 NTSTATUS match_status;
4232 /*************************************************************
4233 File doesn't exist but this lease key+guid is already in use.
4235 This is only allowable in the dynamic share case where the
4236 service path must be different.
4238 There is a small race condition here in the multi-connection
4239 case where a client sends two create calls on different connections,
4240 where the file doesn't exist and one smbd creates the leases_db
4241 entry first, but this will get fixed by the multichannel cleanup
4242 when all identical client_guids get handled by a single smbd.
4243 **************************************************************/
4245 static void lease_match_parser_new_file(
4246 uint32_t num_files,
4247 const struct leases_db_file *files,
4248 struct lease_match_state *state)
4250 uint32_t i;
4252 for (i = 0; i < num_files; i++) {
4253 const struct leases_db_file *f = &files[i];
4254 if (strequal(state->servicepath, f->servicepath)) {
4255 state->match_status = NT_STATUS_INVALID_PARAMETER;
4256 return;
4260 /* Dynamic share case. Break leases on all other files. */
4261 state->match_status = leases_db_copy_file_ids(state->mem_ctx,
4262 num_files,
4263 files,
4264 &state->ids);
4265 if (!NT_STATUS_IS_OK(state->match_status)) {
4266 return;
4269 state->num_file_ids = num_files;
4270 state->match_status = NT_STATUS_OPLOCK_NOT_GRANTED;
4271 return;
4274 static void lease_match_parser(
4275 uint32_t num_files,
4276 const struct leases_db_file *files,
4277 void *private_data)
4279 struct lease_match_state *state =
4280 (struct lease_match_state *)private_data;
4281 uint32_t i;
4283 if (!state->file_existed) {
4285 * Deal with name mismatch or
4286 * possible dynamic share case separately
4287 * to make code clearer.
4289 lease_match_parser_new_file(num_files,
4290 files,
4291 state);
4292 return;
4295 /* File existed. */
4296 state->match_status = NT_STATUS_OK;
4298 for (i = 0; i < num_files; i++) {
4299 const struct leases_db_file *f = &files[i];
4301 /* Everything should be the same. */
4302 if (!file_id_equal(&state->id, &f->id)) {
4303 /* This should catch all dynamic share cases. */
4304 state->match_status = NT_STATUS_OPLOCK_NOT_GRANTED;
4305 break;
4307 if (!strequal(f->servicepath, state->servicepath)) {
4308 state->match_status = NT_STATUS_INVALID_PARAMETER;
4309 break;
4311 if (!strequal(f->base_name, state->fname->base_name)) {
4312 state->match_status = NT_STATUS_INVALID_PARAMETER;
4313 break;
4315 if (!strequal(f->stream_name, state->fname->stream_name)) {
4316 state->match_status = NT_STATUS_INVALID_PARAMETER;
4317 break;
4321 if (NT_STATUS_IS_OK(state->match_status)) {
4323 * Common case - just opening another handle on a
4324 * file on a non-dynamic share.
4326 return;
4329 if (NT_STATUS_EQUAL(state->match_status, NT_STATUS_INVALID_PARAMETER)) {
4330 /* Mismatched path. Error back to client. */
4331 return;
4335 * File id mismatch. Dynamic share case NT_STATUS_OPLOCK_NOT_GRANTED.
4336 * Don't allow leases.
4339 state->match_status = leases_db_copy_file_ids(state->mem_ctx,
4340 num_files,
4341 files,
4342 &state->ids);
4343 if (!NT_STATUS_IS_OK(state->match_status)) {
4344 return;
4347 state->num_file_ids = num_files;
4348 state->match_status = NT_STATUS_OPLOCK_NOT_GRANTED;
4349 return;
4352 static NTSTATUS lease_match(connection_struct *conn,
4353 struct smb_request *req,
4354 struct smb2_lease_key *lease_key,
4355 const char *servicepath,
4356 const struct smb_filename *fname,
4357 uint16_t *p_version,
4358 uint16_t *p_epoch)
4360 struct smbd_server_connection *sconn = req->sconn;
4361 TALLOC_CTX *tos = talloc_tos();
4362 struct lease_match_state state = {
4363 .mem_ctx = tos,
4364 .servicepath = servicepath,
4365 .fname = fname,
4366 .match_status = NT_STATUS_OK
4368 uint32_t i;
4369 NTSTATUS status;
4371 state.file_existed = VALID_STAT(fname->st);
4372 if (state.file_existed) {
4373 state.id = vfs_file_id_from_sbuf(conn, &fname->st);
4374 } else {
4375 memset(&state.id, '\0', sizeof(state.id));
4378 status = leases_db_parse(&sconn->client->connections->smb2.client.guid,
4379 lease_key, lease_match_parser, &state);
4380 if (!NT_STATUS_IS_OK(status)) {
4382 * Not found or error means okay: We can make the lease pass
4384 return NT_STATUS_OK;
4386 if (!NT_STATUS_EQUAL(state.match_status, NT_STATUS_OPLOCK_NOT_GRANTED)) {
4388 * Anything but NT_STATUS_OPLOCK_NOT_GRANTED, let the caller
4389 * deal with it.
4391 return state.match_status;
4394 /* We have to break all existing leases. */
4395 for (i = 0; i < state.num_file_ids; i++) {
4396 struct share_mode_lock *lck;
4397 struct share_mode_data *d;
4398 uint32_t j;
4400 if (file_id_equal(&state.ids[i], &state.id)) {
4401 /* Don't need to break our own file. */
4402 continue;
4405 lck = get_existing_share_mode_lock(talloc_tos(), state.ids[i]);
4406 if (lck == NULL) {
4407 /* Race condition - file already closed. */
4408 continue;
4410 d = lck->data;
4411 for (j=0; j<d->num_share_modes; j++) {
4412 struct share_mode_entry *e = &d->share_modes[j];
4413 uint32_t e_lease_type = get_lease_type(d, e);
4414 struct share_mode_lease *l = NULL;
4416 if (share_mode_stale_pid(d, j)) {
4417 continue;
4420 if (e->op_type == LEASE_OPLOCK) {
4421 l = &lck->data->leases[e->lease_idx];
4422 if (!smb2_lease_key_equal(&l->lease_key,
4423 lease_key)) {
4424 continue;
4426 *p_epoch = l->epoch;
4427 *p_version = l->lease_version;
4430 if (e_lease_type == SMB2_LEASE_NONE) {
4431 continue;
4434 send_break_message(conn->sconn->msg_ctx, e,
4435 SMB2_LEASE_NONE);
4438 * Windows 7 and 8 lease clients
4439 * are broken in that they will not
4440 * respond to lease break requests
4441 * whilst waiting for an outstanding
4442 * open request on that lease handle
4443 * on the same TCP connection, due
4444 * to holding an internal inode lock.
4446 * This means we can't reschedule
4447 * ourselves here, but must return
4448 * from the create.
4450 * Work around:
4452 * Send the breaks and then return
4453 * SMB2_LEASE_NONE in the lease handle
4454 * to cause them to acknowledge the
4455 * lease break. Consulatation with
4456 * Microsoft engineering confirmed
4457 * this approach is safe.
4461 TALLOC_FREE(lck);
4464 * Ensure we don't grant anything more so we
4465 * never upgrade.
4467 return NT_STATUS_OPLOCK_NOT_GRANTED;
4471 * Wrapper around open_file_ntcreate and open_directory
4474 static NTSTATUS create_file_unixpath(connection_struct *conn,
4475 struct smb_request *req,
4476 struct smb_filename *smb_fname,
4477 uint32_t access_mask,
4478 uint32_t share_access,
4479 uint32_t create_disposition,
4480 uint32_t create_options,
4481 uint32_t file_attributes,
4482 uint32_t oplock_request,
4483 struct smb2_lease *lease,
4484 uint64_t allocation_size,
4485 uint32_t private_flags,
4486 struct security_descriptor *sd,
4487 struct ea_list *ea_list,
4489 files_struct **result,
4490 int *pinfo)
4492 int info = FILE_WAS_OPENED;
4493 files_struct *base_fsp = NULL;
4494 files_struct *fsp = NULL;
4495 NTSTATUS status;
4497 DEBUG(10,("create_file_unixpath: access_mask = 0x%x "
4498 "file_attributes = 0x%x, share_access = 0x%x, "
4499 "create_disposition = 0x%x create_options = 0x%x "
4500 "oplock_request = 0x%x private_flags = 0x%x "
4501 "ea_list = 0x%p, sd = 0x%p, "
4502 "fname = %s\n",
4503 (unsigned int)access_mask,
4504 (unsigned int)file_attributes,
4505 (unsigned int)share_access,
4506 (unsigned int)create_disposition,
4507 (unsigned int)create_options,
4508 (unsigned int)oplock_request,
4509 (unsigned int)private_flags,
4510 ea_list, sd, smb_fname_str_dbg(smb_fname)));
4512 if (create_options & FILE_OPEN_BY_FILE_ID) {
4513 status = NT_STATUS_NOT_SUPPORTED;
4514 goto fail;
4517 if (create_options & NTCREATEX_OPTIONS_INVALID_PARAM_MASK) {
4518 status = NT_STATUS_INVALID_PARAMETER;
4519 goto fail;
4522 if (req == NULL) {
4523 oplock_request |= INTERNAL_OPEN_ONLY;
4526 if (lease != NULL) {
4527 uint16_t epoch = lease->lease_epoch;
4528 uint16_t version = lease->lease_version;
4529 status = lease_match(conn,
4530 req,
4531 &lease->lease_key,
4532 conn->connectpath,
4533 smb_fname,
4534 &version,
4535 &epoch);
4536 if (NT_STATUS_EQUAL(status, NT_STATUS_OPLOCK_NOT_GRANTED)) {
4537 /* Dynamic share file. No leases and update epoch... */
4538 lease->lease_state = SMB2_LEASE_NONE;
4539 lease->lease_epoch = epoch;
4540 lease->lease_version = version;
4541 } else if (!NT_STATUS_IS_OK(status)) {
4542 goto fail;
4546 if ((conn->fs_capabilities & FILE_NAMED_STREAMS)
4547 && (access_mask & DELETE_ACCESS)
4548 && !is_ntfs_stream_smb_fname(smb_fname)) {
4550 * We can't open a file with DELETE access if any of the
4551 * streams is open without FILE_SHARE_DELETE
4553 status = open_streams_for_delete(conn, smb_fname);
4555 if (!NT_STATUS_IS_OK(status)) {
4556 goto fail;
4560 if ((access_mask & SEC_FLAG_SYSTEM_SECURITY) &&
4561 !security_token_has_privilege(get_current_nttok(conn),
4562 SEC_PRIV_SECURITY)) {
4563 DEBUG(10, ("create_file_unixpath: open on %s "
4564 "failed - SEC_FLAG_SYSTEM_SECURITY denied.\n",
4565 smb_fname_str_dbg(smb_fname)));
4566 status = NT_STATUS_PRIVILEGE_NOT_HELD;
4567 goto fail;
4570 if ((conn->fs_capabilities & FILE_NAMED_STREAMS)
4571 && is_ntfs_stream_smb_fname(smb_fname)
4572 && (!(private_flags & NTCREATEX_OPTIONS_PRIVATE_STREAM_DELETE))) {
4573 uint32_t base_create_disposition;
4574 struct smb_filename *smb_fname_base = NULL;
4576 if (create_options & FILE_DIRECTORY_FILE) {
4577 status = NT_STATUS_NOT_A_DIRECTORY;
4578 goto fail;
4581 switch (create_disposition) {
4582 case FILE_OPEN:
4583 base_create_disposition = FILE_OPEN;
4584 break;
4585 default:
4586 base_create_disposition = FILE_OPEN_IF;
4587 break;
4590 /* Create an smb_filename with stream_name == NULL. */
4591 smb_fname_base = synthetic_smb_fname(talloc_tos(),
4592 smb_fname->base_name,
4593 NULL,
4594 NULL,
4595 smb_fname->flags);
4596 if (smb_fname_base == NULL) {
4597 status = NT_STATUS_NO_MEMORY;
4598 goto fail;
4601 if (SMB_VFS_STAT(conn, smb_fname_base) == -1) {
4602 DEBUG(10, ("Unable to stat stream: %s\n",
4603 smb_fname_str_dbg(smb_fname_base)));
4604 } else {
4606 * https://bugzilla.samba.org/show_bug.cgi?id=10229
4607 * We need to check if the requested access mask
4608 * could be used to open the underlying file (if
4609 * it existed), as we're passing in zero for the
4610 * access mask to the base filename.
4612 status = check_base_file_access(conn,
4613 smb_fname_base,
4614 access_mask);
4616 if (!NT_STATUS_IS_OK(status)) {
4617 DEBUG(10, ("Permission check "
4618 "for base %s failed: "
4619 "%s\n", smb_fname->base_name,
4620 nt_errstr(status)));
4621 goto fail;
4625 /* Open the base file. */
4626 status = create_file_unixpath(conn, NULL, smb_fname_base, 0,
4627 FILE_SHARE_READ
4628 | FILE_SHARE_WRITE
4629 | FILE_SHARE_DELETE,
4630 base_create_disposition,
4631 0, 0, 0, NULL, 0, 0, NULL, NULL,
4632 &base_fsp, NULL);
4633 TALLOC_FREE(smb_fname_base);
4635 if (!NT_STATUS_IS_OK(status)) {
4636 DEBUG(10, ("create_file_unixpath for base %s failed: "
4637 "%s\n", smb_fname->base_name,
4638 nt_errstr(status)));
4639 goto fail;
4641 /* we don't need the low level fd */
4642 fd_close(base_fsp);
4646 * If it's a request for a directory open, deal with it separately.
4649 if (create_options & FILE_DIRECTORY_FILE) {
4651 if (create_options & FILE_NON_DIRECTORY_FILE) {
4652 status = NT_STATUS_INVALID_PARAMETER;
4653 goto fail;
4656 /* Can't open a temp directory. IFS kit test. */
4657 if (!(file_attributes & FILE_FLAG_POSIX_SEMANTICS) &&
4658 (file_attributes & FILE_ATTRIBUTE_TEMPORARY)) {
4659 status = NT_STATUS_INVALID_PARAMETER;
4660 goto fail;
4664 * We will get a create directory here if the Win32
4665 * app specified a security descriptor in the
4666 * CreateDirectory() call.
4669 oplock_request = 0;
4670 status = open_directory(
4671 conn, req, smb_fname, access_mask, share_access,
4672 create_disposition, create_options, file_attributes,
4673 &info, &fsp);
4674 } else {
4677 * Ordinary file case.
4680 status = file_new(req, conn, &fsp);
4681 if(!NT_STATUS_IS_OK(status)) {
4682 goto fail;
4685 status = fsp_set_smb_fname(fsp, smb_fname);
4686 if (!NT_STATUS_IS_OK(status)) {
4687 goto fail;
4690 if (base_fsp) {
4692 * We're opening the stream element of a
4693 * base_fsp we already opened. Set up the
4694 * base_fsp pointer.
4696 fsp->base_fsp = base_fsp;
4699 if (allocation_size) {
4700 fsp->initial_allocation_size = smb_roundup(fsp->conn,
4701 allocation_size);
4704 status = open_file_ntcreate(conn,
4705 req,
4706 access_mask,
4707 share_access,
4708 create_disposition,
4709 create_options,
4710 file_attributes,
4711 oplock_request,
4712 lease,
4713 private_flags,
4714 &info,
4715 fsp);
4717 if(!NT_STATUS_IS_OK(status)) {
4718 file_free(req, fsp);
4719 fsp = NULL;
4722 if (NT_STATUS_EQUAL(status, NT_STATUS_FILE_IS_A_DIRECTORY)) {
4724 /* A stream open never opens a directory */
4726 if (base_fsp) {
4727 status = NT_STATUS_FILE_IS_A_DIRECTORY;
4728 goto fail;
4732 * Fail the open if it was explicitly a non-directory
4733 * file.
4736 if (create_options & FILE_NON_DIRECTORY_FILE) {
4737 status = NT_STATUS_FILE_IS_A_DIRECTORY;
4738 goto fail;
4741 oplock_request = 0;
4742 status = open_directory(
4743 conn, req, smb_fname, access_mask,
4744 share_access, create_disposition,
4745 create_options, file_attributes,
4746 &info, &fsp);
4750 if (!NT_STATUS_IS_OK(status)) {
4751 goto fail;
4754 fsp->base_fsp = base_fsp;
4756 if ((ea_list != NULL) &&
4757 ((info == FILE_WAS_CREATED) || (info == FILE_WAS_OVERWRITTEN))) {
4758 status = set_ea(conn, fsp, fsp->fsp_name, ea_list);
4759 if (!NT_STATUS_IS_OK(status)) {
4760 goto fail;
4764 if (!fsp->is_directory && S_ISDIR(fsp->fsp_name->st.st_ex_mode)) {
4765 status = NT_STATUS_ACCESS_DENIED;
4766 goto fail;
4769 /* Save the requested allocation size. */
4770 if ((info == FILE_WAS_CREATED) || (info == FILE_WAS_OVERWRITTEN)) {
4771 if ((allocation_size > fsp->fsp_name->st.st_ex_size)
4772 && !(fsp->is_directory))
4774 fsp->initial_allocation_size = smb_roundup(
4775 fsp->conn, allocation_size);
4776 if (vfs_allocate_file_space(
4777 fsp, fsp->initial_allocation_size) == -1) {
4778 status = NT_STATUS_DISK_FULL;
4779 goto fail;
4781 } else {
4782 fsp->initial_allocation_size = smb_roundup(
4783 fsp->conn, (uint64_t)fsp->fsp_name->st.st_ex_size);
4785 } else {
4786 fsp->initial_allocation_size = 0;
4789 if ((info == FILE_WAS_CREATED) && lp_nt_acl_support(SNUM(conn)) &&
4790 fsp->base_fsp == NULL) {
4791 if (sd != NULL) {
4793 * According to the MS documentation, the only time the security
4794 * descriptor is applied to the opened file is iff we *created* the
4795 * file; an existing file stays the same.
4797 * Also, it seems (from observation) that you can open the file with
4798 * any access mask but you can still write the sd. We need to override
4799 * the granted access before we call set_sd
4800 * Patch for bug #2242 from Tom Lackemann <cessnatomny@yahoo.com>.
4803 uint32_t sec_info_sent;
4804 uint32_t saved_access_mask = fsp->access_mask;
4806 sec_info_sent = get_sec_info(sd);
4808 fsp->access_mask = FILE_GENERIC_ALL;
4810 if (sec_info_sent & (SECINFO_OWNER|
4811 SECINFO_GROUP|
4812 SECINFO_DACL|
4813 SECINFO_SACL)) {
4814 status = set_sd(fsp, sd, sec_info_sent);
4817 fsp->access_mask = saved_access_mask;
4819 if (!NT_STATUS_IS_OK(status)) {
4820 goto fail;
4822 } else if (lp_inherit_acls(SNUM(conn))) {
4823 /* Inherit from parent. Errors here are not fatal. */
4824 status = inherit_new_acl(fsp);
4825 if (!NT_STATUS_IS_OK(status)) {
4826 DEBUG(10,("inherit_new_acl: failed for %s with %s\n",
4827 fsp_str_dbg(fsp),
4828 nt_errstr(status) ));
4833 if ((conn->fs_capabilities & FILE_FILE_COMPRESSION)
4834 && (create_options & FILE_NO_COMPRESSION)
4835 && (info == FILE_WAS_CREATED)) {
4836 status = SMB_VFS_SET_COMPRESSION(conn, fsp, fsp,
4837 COMPRESSION_FORMAT_NONE);
4838 if (!NT_STATUS_IS_OK(status)) {
4839 DEBUG(1, ("failed to disable compression: %s\n",
4840 nt_errstr(status)));
4844 DEBUG(10, ("create_file_unixpath: info=%d\n", info));
4846 *result = fsp;
4847 if (pinfo != NULL) {
4848 *pinfo = info;
4851 smb_fname->st = fsp->fsp_name->st;
4853 return NT_STATUS_OK;
4855 fail:
4856 DEBUG(10, ("create_file_unixpath: %s\n", nt_errstr(status)));
4858 if (fsp != NULL) {
4859 if (base_fsp && fsp->base_fsp == base_fsp) {
4861 * The close_file below will close
4862 * fsp->base_fsp.
4864 base_fsp = NULL;
4866 close_file(req, fsp, ERROR_CLOSE);
4867 fsp = NULL;
4869 if (base_fsp != NULL) {
4870 close_file(req, base_fsp, ERROR_CLOSE);
4871 base_fsp = NULL;
4873 return status;
4877 * Calculate the full path name given a relative fid.
4879 NTSTATUS get_relative_fid_filename(connection_struct *conn,
4880 struct smb_request *req,
4881 uint16_t root_dir_fid,
4882 const struct smb_filename *smb_fname,
4883 struct smb_filename **smb_fname_out)
4885 files_struct *dir_fsp;
4886 char *parent_fname = NULL;
4887 char *new_base_name = NULL;
4888 uint32_t ucf_flags = ((req != NULL && req->posix_pathnames) ?
4889 UCF_POSIX_PATHNAMES : 0);
4890 NTSTATUS status;
4892 if (root_dir_fid == 0 || !smb_fname) {
4893 status = NT_STATUS_INTERNAL_ERROR;
4894 goto out;
4897 dir_fsp = file_fsp(req, root_dir_fid);
4899 if (dir_fsp == NULL) {
4900 status = NT_STATUS_INVALID_HANDLE;
4901 goto out;
4904 if (is_ntfs_stream_smb_fname(dir_fsp->fsp_name)) {
4905 status = NT_STATUS_INVALID_HANDLE;
4906 goto out;
4909 if (!dir_fsp->is_directory) {
4912 * Check to see if this is a mac fork of some kind.
4915 if ((conn->fs_capabilities & FILE_NAMED_STREAMS) &&
4916 is_ntfs_stream_smb_fname(smb_fname)) {
4917 status = NT_STATUS_OBJECT_PATH_NOT_FOUND;
4918 goto out;
4922 we need to handle the case when we get a
4923 relative open relative to a file and the
4924 pathname is blank - this is a reopen!
4925 (hint from demyn plantenberg)
4928 status = NT_STATUS_INVALID_HANDLE;
4929 goto out;
4932 if (ISDOT(dir_fsp->fsp_name->base_name)) {
4934 * We're at the toplevel dir, the final file name
4935 * must not contain ./, as this is filtered out
4936 * normally by srvstr_get_path and unix_convert
4937 * explicitly rejects paths containing ./.
4939 parent_fname = talloc_strdup(talloc_tos(), "");
4940 if (parent_fname == NULL) {
4941 status = NT_STATUS_NO_MEMORY;
4942 goto out;
4944 } else {
4945 size_t dir_name_len = strlen(dir_fsp->fsp_name->base_name);
4948 * Copy in the base directory name.
4951 parent_fname = talloc_array(talloc_tos(), char,
4952 dir_name_len+2);
4953 if (parent_fname == NULL) {
4954 status = NT_STATUS_NO_MEMORY;
4955 goto out;
4957 memcpy(parent_fname, dir_fsp->fsp_name->base_name,
4958 dir_name_len+1);
4961 * Ensure it ends in a '/'.
4962 * We used TALLOC_SIZE +2 to add space for the '/'.
4965 if(dir_name_len
4966 && (parent_fname[dir_name_len-1] != '\\')
4967 && (parent_fname[dir_name_len-1] != '/')) {
4968 parent_fname[dir_name_len] = '/';
4969 parent_fname[dir_name_len+1] = '\0';
4973 new_base_name = talloc_asprintf(talloc_tos(), "%s%s", parent_fname,
4974 smb_fname->base_name);
4975 if (new_base_name == NULL) {
4976 status = NT_STATUS_NO_MEMORY;
4977 goto out;
4980 status = filename_convert(req,
4981 conn,
4982 req->flags2 & FLAGS2_DFS_PATHNAMES,
4983 new_base_name,
4984 ucf_flags,
4985 NULL,
4986 smb_fname_out);
4987 if (!NT_STATUS_IS_OK(status)) {
4988 goto out;
4991 out:
4992 TALLOC_FREE(parent_fname);
4993 TALLOC_FREE(new_base_name);
4994 return status;
4997 NTSTATUS create_file_default(connection_struct *conn,
4998 struct smb_request *req,
4999 uint16_t root_dir_fid,
5000 struct smb_filename *smb_fname,
5001 uint32_t access_mask,
5002 uint32_t share_access,
5003 uint32_t create_disposition,
5004 uint32_t create_options,
5005 uint32_t file_attributes,
5006 uint32_t oplock_request,
5007 struct smb2_lease *lease,
5008 uint64_t allocation_size,
5009 uint32_t private_flags,
5010 struct security_descriptor *sd,
5011 struct ea_list *ea_list,
5012 files_struct **result,
5013 int *pinfo,
5014 const struct smb2_create_blobs *in_context_blobs,
5015 struct smb2_create_blobs *out_context_blobs)
5017 int info = FILE_WAS_OPENED;
5018 files_struct *fsp = NULL;
5019 NTSTATUS status;
5020 bool stream_name = false;
5022 DEBUG(10,("create_file: access_mask = 0x%x "
5023 "file_attributes = 0x%x, share_access = 0x%x, "
5024 "create_disposition = 0x%x create_options = 0x%x "
5025 "oplock_request = 0x%x "
5026 "private_flags = 0x%x "
5027 "root_dir_fid = 0x%x, ea_list = 0x%p, sd = 0x%p, "
5028 "fname = %s\n",
5029 (unsigned int)access_mask,
5030 (unsigned int)file_attributes,
5031 (unsigned int)share_access,
5032 (unsigned int)create_disposition,
5033 (unsigned int)create_options,
5034 (unsigned int)oplock_request,
5035 (unsigned int)private_flags,
5036 (unsigned int)root_dir_fid,
5037 ea_list, sd, smb_fname_str_dbg(smb_fname)));
5040 * Calculate the filename from the root_dir_if if necessary.
5043 if (root_dir_fid != 0) {
5044 struct smb_filename *smb_fname_out = NULL;
5045 status = get_relative_fid_filename(conn, req, root_dir_fid,
5046 smb_fname, &smb_fname_out);
5047 if (!NT_STATUS_IS_OK(status)) {
5048 goto fail;
5050 smb_fname = smb_fname_out;
5054 * Check to see if this is a mac fork of some kind.
5057 stream_name = is_ntfs_stream_smb_fname(smb_fname);
5058 if (stream_name) {
5059 enum FAKE_FILE_TYPE fake_file_type;
5061 fake_file_type = is_fake_file(smb_fname);
5063 if (fake_file_type != FAKE_FILE_TYPE_NONE) {
5066 * Here we go! support for changing the disk quotas
5067 * --metze
5069 * We need to fake up to open this MAGIC QUOTA file
5070 * and return a valid FID.
5072 * w2k close this file directly after openening xp
5073 * also tries a QUERY_FILE_INFO on the file and then
5074 * close it
5076 status = open_fake_file(req, conn, req->vuid,
5077 fake_file_type, smb_fname,
5078 access_mask, &fsp);
5079 if (!NT_STATUS_IS_OK(status)) {
5080 goto fail;
5083 ZERO_STRUCT(smb_fname->st);
5084 goto done;
5087 if (!(conn->fs_capabilities & FILE_NAMED_STREAMS)) {
5088 status = NT_STATUS_OBJECT_NAME_NOT_FOUND;
5089 goto fail;
5093 if (is_ntfs_default_stream_smb_fname(smb_fname)) {
5094 int ret;
5095 smb_fname->stream_name = NULL;
5096 /* We have to handle this error here. */
5097 if (create_options & FILE_DIRECTORY_FILE) {
5098 status = NT_STATUS_NOT_A_DIRECTORY;
5099 goto fail;
5101 if (req != NULL && req->posix_pathnames) {
5102 ret = SMB_VFS_LSTAT(conn, smb_fname);
5103 } else {
5104 ret = SMB_VFS_STAT(conn, smb_fname);
5107 if (ret == 0 && VALID_STAT_OF_DIR(smb_fname->st)) {
5108 status = NT_STATUS_FILE_IS_A_DIRECTORY;
5109 goto fail;
5113 status = create_file_unixpath(
5114 conn, req, smb_fname, access_mask, share_access,
5115 create_disposition, create_options, file_attributes,
5116 oplock_request, lease, allocation_size, private_flags,
5117 sd, ea_list,
5118 &fsp, &info);
5120 if (!NT_STATUS_IS_OK(status)) {
5121 goto fail;
5124 done:
5125 DEBUG(10, ("create_file: info=%d\n", info));
5127 *result = fsp;
5128 if (pinfo != NULL) {
5129 *pinfo = info;
5131 return NT_STATUS_OK;
5133 fail:
5134 DEBUG(10, ("create_file: %s\n", nt_errstr(status)));
5136 if (fsp != NULL) {
5137 close_file(req, fsp, ERROR_CLOSE);
5138 fsp = NULL;
5140 return status;