Fix the developer O3 build
[Samba.git] / source3 / smbd / open.c
blob773b146cd68fd31bb06a0372548691d845ea9ac0
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->base_name,
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 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;
247 if (!parent_dirname(talloc_tos(),
248 smb_fname->base_name,
249 &parent_dir,
250 NULL)) {
251 return NT_STATUS_NO_MEMORY;
254 if (get_current_uid(conn) == (uid_t)0) {
255 /* I'm sorry sir, I didn't know you were root... */
256 DEBUG(10,("check_parent_access: root override "
257 "on %s. Granting 0x%x\n",
258 smb_fname_str_dbg(smb_fname),
259 (unsigned int)access_mask ));
260 return NT_STATUS_OK;
263 status = SMB_VFS_GET_NT_ACL(conn,
264 parent_dir,
265 SECINFO_DACL,
266 talloc_tos(),
267 &parent_sd);
269 if (!NT_STATUS_IS_OK(status)) {
270 DEBUG(5,("check_parent_access: SMB_VFS_GET_NT_ACL failed for "
271 "%s with error %s\n",
272 parent_dir,
273 nt_errstr(status)));
274 return status;
278 * If we can access the path to this file, by
279 * default we have FILE_READ_ATTRIBUTES from the
280 * containing directory. See the section:
281 * "Algorithm to Check Access to an Existing File"
282 * in MS-FSA.pdf.
284 * se_file_access_check() also takes care of
285 * owner WRITE_DAC and READ_CONTROL.
287 status = se_file_access_check(parent_sd,
288 get_current_nttok(conn),
289 false,
290 (access_mask & ~FILE_READ_ATTRIBUTES),
291 &access_granted);
292 if(!NT_STATUS_IS_OK(status)) {
293 DEBUG(5,("check_parent_access: access check "
294 "on directory %s for "
295 "path %s for mask 0x%x returned (0x%x) %s\n",
296 parent_dir,
297 smb_fname->base_name,
298 access_mask,
299 access_granted,
300 nt_errstr(status) ));
301 return status;
304 return NT_STATUS_OK;
307 /****************************************************************************
308 Ensure when opening a base file for a stream open that we have permissions
309 to do so given the access mask on the base file.
310 ****************************************************************************/
312 static NTSTATUS check_base_file_access(struct connection_struct *conn,
313 struct smb_filename *smb_fname,
314 uint32_t access_mask)
316 NTSTATUS status;
318 status = smbd_calculate_access_mask(conn, smb_fname,
319 false,
320 access_mask,
321 &access_mask);
322 if (!NT_STATUS_IS_OK(status)) {
323 DEBUG(10, ("smbd_calculate_access_mask "
324 "on file %s returned %s\n",
325 smb_fname_str_dbg(smb_fname),
326 nt_errstr(status)));
327 return status;
330 if (access_mask & (FILE_WRITE_DATA|FILE_APPEND_DATA)) {
331 uint32_t dosattrs;
332 if (!CAN_WRITE(conn)) {
333 return NT_STATUS_ACCESS_DENIED;
335 dosattrs = dos_mode(conn, smb_fname);
336 if (IS_DOS_READONLY(dosattrs)) {
337 return NT_STATUS_ACCESS_DENIED;
341 return smbd_check_access_rights(conn,
342 smb_fname,
343 false,
344 access_mask);
347 /****************************************************************************
348 fd support routines - attempt to do a dos_open.
349 ****************************************************************************/
351 NTSTATUS fd_open(struct connection_struct *conn,
352 files_struct *fsp,
353 int flags,
354 mode_t mode)
356 struct smb_filename *smb_fname = fsp->fsp_name;
357 NTSTATUS status = NT_STATUS_OK;
359 #ifdef O_NOFOLLOW
361 * Never follow symlinks on a POSIX client. The
362 * client should be doing this.
365 if (fsp->posix_open || !lp_follow_symlinks(SNUM(conn))) {
366 flags |= O_NOFOLLOW;
368 #endif
370 fsp->fh->fd = SMB_VFS_OPEN(conn, smb_fname, fsp, flags, mode);
371 if (fsp->fh->fd == -1) {
372 int posix_errno = errno;
373 #ifdef O_NOFOLLOW
374 #if defined(ENOTSUP) && defined(OSF1)
375 /* handle special Tru64 errno */
376 if (errno == ENOTSUP) {
377 posix_errno = ELOOP;
379 #endif /* ENOTSUP */
380 #ifdef EFTYPE
381 /* fix broken NetBSD errno */
382 if (errno == EFTYPE) {
383 posix_errno = ELOOP;
385 #endif /* EFTYPE */
386 /* fix broken FreeBSD errno */
387 if (errno == EMLINK) {
388 posix_errno = ELOOP;
390 #endif /* O_NOFOLLOW */
391 status = map_nt_error_from_unix(posix_errno);
392 if (errno == EMFILE) {
393 static time_t last_warned = 0L;
395 if (time((time_t *) NULL) > last_warned) {
396 DEBUG(0,("Too many open files, unable "
397 "to open more! smbd's max "
398 "open files = %d\n",
399 lp_max_open_files()));
400 last_warned = time((time_t *) NULL);
406 DEBUG(10,("fd_open: name %s, flags = 0%o mode = 0%o, fd = %d. %s\n",
407 smb_fname_str_dbg(smb_fname), flags, (int)mode, fsp->fh->fd,
408 (fsp->fh->fd == -1) ? strerror(errno) : "" ));
410 return status;
413 /****************************************************************************
414 Close the file associated with a fsp.
415 ****************************************************************************/
417 NTSTATUS fd_close(files_struct *fsp)
419 int ret;
421 if (fsp->dptr) {
422 dptr_CloseDir(fsp);
424 if (fsp->fh->fd == -1) {
425 return NT_STATUS_OK; /* What we used to call a stat open. */
427 if (fsp->fh->ref_count > 1) {
428 return NT_STATUS_OK; /* Shared handle. Only close last reference. */
431 ret = SMB_VFS_CLOSE(fsp);
432 fsp->fh->fd = -1;
433 if (ret == -1) {
434 return map_nt_error_from_unix(errno);
436 return NT_STATUS_OK;
439 /****************************************************************************
440 Change the ownership of a file to that of the parent directory.
441 Do this by fd if possible.
442 ****************************************************************************/
444 void change_file_owner_to_parent(connection_struct *conn,
445 const char *inherit_from_dir,
446 files_struct *fsp)
448 struct smb_filename *smb_fname_parent;
449 int ret;
451 smb_fname_parent = synthetic_smb_fname(talloc_tos(), inherit_from_dir,
452 NULL, NULL);
453 if (smb_fname_parent == NULL) {
454 return;
457 ret = SMB_VFS_STAT(conn, smb_fname_parent);
458 if (ret == -1) {
459 DEBUG(0,("change_file_owner_to_parent: failed to stat parent "
460 "directory %s. Error was %s\n",
461 smb_fname_str_dbg(smb_fname_parent),
462 strerror(errno)));
463 TALLOC_FREE(smb_fname_parent);
464 return;
467 if (smb_fname_parent->st.st_ex_uid == fsp->fsp_name->st.st_ex_uid) {
468 /* Already this uid - no need to change. */
469 DEBUG(10,("change_file_owner_to_parent: file %s "
470 "is already owned by uid %d\n",
471 fsp_str_dbg(fsp),
472 (int)fsp->fsp_name->st.st_ex_uid ));
473 TALLOC_FREE(smb_fname_parent);
474 return;
477 become_root();
478 ret = SMB_VFS_FCHOWN(fsp, smb_fname_parent->st.st_ex_uid, (gid_t)-1);
479 unbecome_root();
480 if (ret == -1) {
481 DEBUG(0,("change_file_owner_to_parent: failed to fchown "
482 "file %s to parent directory uid %u. Error "
483 "was %s\n", fsp_str_dbg(fsp),
484 (unsigned int)smb_fname_parent->st.st_ex_uid,
485 strerror(errno) ));
486 } else {
487 DEBUG(10,("change_file_owner_to_parent: changed new file %s to "
488 "parent directory uid %u.\n", fsp_str_dbg(fsp),
489 (unsigned int)smb_fname_parent->st.st_ex_uid));
490 /* Ensure the uid entry is updated. */
491 fsp->fsp_name->st.st_ex_uid = smb_fname_parent->st.st_ex_uid;
494 TALLOC_FREE(smb_fname_parent);
497 NTSTATUS change_dir_owner_to_parent(connection_struct *conn,
498 const char *inherit_from_dir,
499 const char *fname,
500 SMB_STRUCT_STAT *psbuf)
502 struct smb_filename *smb_fname_parent;
503 struct smb_filename *smb_fname_cwd = NULL;
504 char *saved_dir = NULL;
505 TALLOC_CTX *ctx = talloc_tos();
506 NTSTATUS status = NT_STATUS_OK;
507 int ret;
509 smb_fname_parent = synthetic_smb_fname(ctx, inherit_from_dir,
510 NULL, NULL);
511 if (smb_fname_parent == NULL) {
512 return NT_STATUS_NO_MEMORY;
515 ret = SMB_VFS_STAT(conn, smb_fname_parent);
516 if (ret == -1) {
517 status = map_nt_error_from_unix(errno);
518 DEBUG(0,("change_dir_owner_to_parent: failed to stat parent "
519 "directory %s. Error was %s\n",
520 smb_fname_str_dbg(smb_fname_parent),
521 strerror(errno)));
522 goto out;
525 /* We've already done an lstat into psbuf, and we know it's a
526 directory. If we can cd into the directory and the dev/ino
527 are the same then we can safely chown without races as
528 we're locking the directory in place by being in it. This
529 should work on any UNIX (thanks tridge :-). JRA.
532 saved_dir = vfs_GetWd(ctx,conn);
533 if (!saved_dir) {
534 status = map_nt_error_from_unix(errno);
535 DEBUG(0,("change_dir_owner_to_parent: failed to get "
536 "current working directory. Error was %s\n",
537 strerror(errno)));
538 goto out;
541 /* Chdir into the new path. */
542 if (vfs_ChDir(conn, fname) == -1) {
543 status = map_nt_error_from_unix(errno);
544 DEBUG(0,("change_dir_owner_to_parent: failed to change "
545 "current working directory to %s. Error "
546 "was %s\n", fname, strerror(errno) ));
547 goto chdir;
550 smb_fname_cwd = synthetic_smb_fname(ctx, ".", NULL, NULL);
551 if (smb_fname_cwd == NULL) {
552 status = NT_STATUS_NO_MEMORY;
553 goto chdir;
556 ret = SMB_VFS_STAT(conn, smb_fname_cwd);
557 if (ret == -1) {
558 status = map_nt_error_from_unix(errno);
559 DEBUG(0,("change_dir_owner_to_parent: failed to stat "
560 "directory '.' (%s) Error was %s\n",
561 fname, strerror(errno)));
562 goto chdir;
565 /* Ensure we're pointing at the same place. */
566 if (smb_fname_cwd->st.st_ex_dev != psbuf->st_ex_dev ||
567 smb_fname_cwd->st.st_ex_ino != psbuf->st_ex_ino) {
568 DEBUG(0,("change_dir_owner_to_parent: "
569 "device/inode on directory %s changed. "
570 "Refusing to chown !\n", fname ));
571 status = NT_STATUS_ACCESS_DENIED;
572 goto chdir;
575 if (smb_fname_parent->st.st_ex_uid == smb_fname_cwd->st.st_ex_uid) {
576 /* Already this uid - no need to change. */
577 DEBUG(10,("change_dir_owner_to_parent: directory %s "
578 "is already owned by uid %d\n",
579 fname,
580 (int)smb_fname_cwd->st.st_ex_uid ));
581 status = NT_STATUS_OK;
582 goto chdir;
585 become_root();
586 ret = SMB_VFS_LCHOWN(conn, ".", smb_fname_parent->st.st_ex_uid,
587 (gid_t)-1);
588 unbecome_root();
589 if (ret == -1) {
590 status = map_nt_error_from_unix(errno);
591 DEBUG(10,("change_dir_owner_to_parent: failed to chown "
592 "directory %s to parent directory uid %u. "
593 "Error was %s\n", fname,
594 (unsigned int)smb_fname_parent->st.st_ex_uid,
595 strerror(errno) ));
596 } else {
597 DEBUG(10,("change_dir_owner_to_parent: changed ownership of new "
598 "directory %s to parent directory uid %u.\n",
599 fname, (unsigned int)smb_fname_parent->st.st_ex_uid ));
600 /* Ensure the uid entry is updated. */
601 psbuf->st_ex_uid = smb_fname_parent->st.st_ex_uid;
604 chdir:
605 vfs_ChDir(conn,saved_dir);
606 out:
607 TALLOC_FREE(smb_fname_parent);
608 TALLOC_FREE(smb_fname_cwd);
609 return status;
612 /****************************************************************************
613 Open a file - returning a guaranteed ATOMIC indication of if the
614 file was created or not.
615 ****************************************************************************/
617 static NTSTATUS fd_open_atomic(struct connection_struct *conn,
618 files_struct *fsp,
619 int flags,
620 mode_t mode,
621 bool *file_created)
623 NTSTATUS status = NT_STATUS_UNSUCCESSFUL;
624 bool file_existed = VALID_STAT(fsp->fsp_name->st);
626 *file_created = false;
628 if (!(flags & O_CREAT)) {
630 * We're not creating the file, just pass through.
632 return fd_open(conn, fsp, flags, mode);
635 if (flags & O_EXCL) {
637 * Fail if already exists, just pass through.
639 status = fd_open(conn, fsp, flags, mode);
642 * Here we've opened with O_CREAT|O_EXCL. If that went
643 * NT_STATUS_OK, we *know* we created this file.
645 *file_created = NT_STATUS_IS_OK(status);
647 return status;
651 * Now it gets tricky. We have O_CREAT, but not O_EXCL.
652 * To know absolutely if we created the file or not,
653 * we can never call O_CREAT without O_EXCL. So if
654 * we think the file existed, try without O_CREAT|O_EXCL.
655 * If we think the file didn't exist, try with
656 * O_CREAT|O_EXCL. Keep bouncing between these two
657 * requests until either the file is created, or
658 * opened. Either way, we keep going until we get
659 * a returnable result (error, or open/create).
662 while(1) {
663 int curr_flags = flags;
665 if (file_existed) {
666 /* Just try open, do not create. */
667 curr_flags &= ~(O_CREAT);
668 status = fd_open(conn, fsp, curr_flags, mode);
669 if (NT_STATUS_EQUAL(status,
670 NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
672 * Someone deleted it in the meantime.
673 * Retry with O_EXCL.
675 file_existed = false;
676 DEBUG(10,("fd_open_atomic: file %s existed. "
677 "Retry.\n",
678 smb_fname_str_dbg(fsp->fsp_name)));
679 continue;
681 } else {
682 /* Try create exclusively, fail if it exists. */
683 curr_flags |= O_EXCL;
684 status = fd_open(conn, fsp, curr_flags, mode);
685 if (NT_STATUS_EQUAL(status,
686 NT_STATUS_OBJECT_NAME_COLLISION)) {
688 * Someone created it in the meantime.
689 * Retry without O_CREAT.
691 file_existed = true;
692 DEBUG(10,("fd_open_atomic: file %s "
693 "did not exist. Retry.\n",
694 smb_fname_str_dbg(fsp->fsp_name)));
695 continue;
697 if (NT_STATUS_IS_OK(status)) {
699 * Here we've opened with O_CREAT|O_EXCL
700 * and got success. We *know* we created
701 * this file.
703 *file_created = true;
706 /* Create is done, or failed. */
707 break;
709 return status;
712 /****************************************************************************
713 Open a file.
714 ****************************************************************************/
716 static NTSTATUS open_file(files_struct *fsp,
717 connection_struct *conn,
718 struct smb_request *req,
719 const char *parent_dir,
720 int flags,
721 mode_t unx_mode,
722 uint32 access_mask, /* client requested access mask. */
723 uint32 open_access_mask, /* what we're actually using in the open. */
724 bool *p_file_created)
726 struct smb_filename *smb_fname = fsp->fsp_name;
727 NTSTATUS status = NT_STATUS_OK;
728 int accmode = (flags & O_ACCMODE);
729 int local_flags = flags;
730 bool file_existed = VALID_STAT(fsp->fsp_name->st);
732 fsp->fh->fd = -1;
733 errno = EPERM;
735 /* Check permissions */
738 * This code was changed after seeing a client open request
739 * containing the open mode of (DENY_WRITE/read-only) with
740 * the 'create if not exist' bit set. The previous code
741 * would fail to open the file read only on a read-only share
742 * as it was checking the flags parameter directly against O_RDONLY,
743 * this was failing as the flags parameter was set to O_RDONLY|O_CREAT.
744 * JRA.
747 if (!CAN_WRITE(conn)) {
748 /* It's a read-only share - fail if we wanted to write. */
749 if(accmode != O_RDONLY || (flags & O_TRUNC) || (flags & O_APPEND)) {
750 DEBUG(3,("Permission denied opening %s\n",
751 smb_fname_str_dbg(smb_fname)));
752 return NT_STATUS_ACCESS_DENIED;
754 if (flags & O_CREAT) {
755 /* We don't want to write - but we must make sure that
756 O_CREAT doesn't create the file if we have write
757 access into the directory.
759 flags &= ~(O_CREAT|O_EXCL);
760 local_flags &= ~(O_CREAT|O_EXCL);
765 * This little piece of insanity is inspired by the
766 * fact that an NT client can open a file for O_RDONLY,
767 * but set the create disposition to FILE_EXISTS_TRUNCATE.
768 * If the client *can* write to the file, then it expects to
769 * truncate the file, even though it is opening for readonly.
770 * Quicken uses this stupid trick in backup file creation...
771 * Thanks *greatly* to "David W. Chapman Jr." <dwcjr@inethouston.net>
772 * for helping track this one down. It didn't bite us in 2.0.x
773 * as we always opened files read-write in that release. JRA.
776 if ((accmode == O_RDONLY) && ((flags & O_TRUNC) == O_TRUNC)) {
777 DEBUG(10,("open_file: truncate requested on read-only open "
778 "for file %s\n", smb_fname_str_dbg(smb_fname)));
779 local_flags = (flags & ~O_ACCMODE)|O_RDWR;
782 if ((open_access_mask & (FILE_READ_DATA|FILE_WRITE_DATA|FILE_APPEND_DATA|FILE_EXECUTE)) ||
783 (!file_existed && (local_flags & O_CREAT)) ||
784 ((local_flags & O_TRUNC) == O_TRUNC) ) {
785 const char *wild;
786 int ret;
788 #if defined(O_NONBLOCK) && defined(S_ISFIFO)
790 * We would block on opening a FIFO with no one else on the
791 * other end. Do what we used to do and add O_NONBLOCK to the
792 * open flags. JRA.
795 if (file_existed && S_ISFIFO(smb_fname->st.st_ex_mode)) {
796 local_flags &= ~O_TRUNC; /* Can't truncate a FIFO. */
797 local_flags |= O_NONBLOCK;
799 #endif
801 /* Don't create files with Microsoft wildcard characters. */
802 if (fsp->base_fsp) {
804 * wildcard characters are allowed in stream names
805 * only test the basefilename
807 wild = fsp->base_fsp->fsp_name->base_name;
808 } else {
809 wild = smb_fname->base_name;
811 if ((local_flags & O_CREAT) && !file_existed &&
812 ms_has_wild(wild)) {
813 return NT_STATUS_OBJECT_NAME_INVALID;
816 /* Can we access this file ? */
817 if (!fsp->base_fsp) {
818 /* Only do this check on non-stream open. */
819 if (file_existed) {
820 status = smbd_check_access_rights(conn,
821 smb_fname,
822 false,
823 access_mask);
825 if (!NT_STATUS_IS_OK(status)) {
826 DEBUG(10, ("open_file: "
827 "smbd_check_access_rights "
828 "on file %s returned %s\n",
829 smb_fname_str_dbg(smb_fname),
830 nt_errstr(status)));
833 if (!NT_STATUS_IS_OK(status) &&
834 !NT_STATUS_EQUAL(status,
835 NT_STATUS_OBJECT_NAME_NOT_FOUND))
837 return status;
840 if (NT_STATUS_EQUAL(status,
841 NT_STATUS_OBJECT_NAME_NOT_FOUND))
843 DEBUG(10, ("open_file: "
844 "file %s vanished since we "
845 "checked for existence.\n",
846 smb_fname_str_dbg(smb_fname)));
847 file_existed = false;
848 SET_STAT_INVALID(fsp->fsp_name->st);
852 if (!file_existed) {
853 if (!(local_flags & O_CREAT)) {
854 /* File didn't exist and no O_CREAT. */
855 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
858 status = check_parent_access(conn,
859 smb_fname,
860 SEC_DIR_ADD_FILE);
861 if (!NT_STATUS_IS_OK(status)) {
862 DEBUG(10, ("open_file: "
863 "check_parent_access on "
864 "file %s returned %s\n",
865 smb_fname_str_dbg(smb_fname),
866 nt_errstr(status) ));
867 return status;
873 * Actually do the open - if O_TRUNC is needed handle it
874 * below under the share mode lock.
876 status = fd_open_atomic(conn, fsp, local_flags & ~O_TRUNC,
877 unx_mode, p_file_created);
878 if (!NT_STATUS_IS_OK(status)) {
879 DEBUG(3,("Error opening file %s (%s) (local_flags=%d) "
880 "(flags=%d)\n", smb_fname_str_dbg(smb_fname),
881 nt_errstr(status),local_flags,flags));
882 return status;
885 ret = SMB_VFS_FSTAT(fsp, &smb_fname->st);
886 if (ret == -1) {
887 /* If we have an fd, this stat should succeed. */
888 DEBUG(0,("Error doing fstat on open file %s "
889 "(%s)\n",
890 smb_fname_str_dbg(smb_fname),
891 strerror(errno) ));
892 status = map_nt_error_from_unix(errno);
893 fd_close(fsp);
894 return status;
897 if (*p_file_created) {
898 /* We created this file. */
900 bool need_re_stat = false;
901 /* Do all inheritance work after we've
902 done a successful fstat call and filled
903 in the stat struct in fsp->fsp_name. */
905 /* Inherit the ACL if required */
906 if (lp_inherit_permissions(SNUM(conn))) {
907 inherit_access_posix_acl(conn, parent_dir,
908 smb_fname->base_name,
909 unx_mode);
910 need_re_stat = true;
913 /* Change the owner if required. */
914 if (lp_inherit_owner(SNUM(conn))) {
915 change_file_owner_to_parent(conn, parent_dir,
916 fsp);
917 need_re_stat = true;
920 if (need_re_stat) {
921 ret = SMB_VFS_FSTAT(fsp, &smb_fname->st);
922 /* If we have an fd, this stat should succeed. */
923 if (ret == -1) {
924 DEBUG(0,("Error doing fstat on open file %s "
925 "(%s)\n",
926 smb_fname_str_dbg(smb_fname),
927 strerror(errno) ));
931 notify_fname(conn, NOTIFY_ACTION_ADDED,
932 FILE_NOTIFY_CHANGE_FILE_NAME,
933 smb_fname->base_name);
935 } else {
936 fsp->fh->fd = -1; /* What we used to call a stat open. */
937 if (!file_existed) {
938 /* File must exist for a stat open. */
939 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
942 status = smbd_check_access_rights(conn,
943 smb_fname,
944 false,
945 access_mask);
947 if (NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND) &&
948 fsp->posix_open &&
949 S_ISLNK(smb_fname->st.st_ex_mode)) {
950 /* This is a POSIX stat open for delete
951 * or rename on a symlink that points
952 * nowhere. Allow. */
953 DEBUG(10,("open_file: allowing POSIX "
954 "open on bad symlink %s\n",
955 smb_fname_str_dbg(smb_fname)));
956 status = NT_STATUS_OK;
959 if (!NT_STATUS_IS_OK(status)) {
960 DEBUG(10,("open_file: "
961 "smbd_check_access_rights on file "
962 "%s returned %s\n",
963 smb_fname_str_dbg(smb_fname),
964 nt_errstr(status) ));
965 return status;
970 * POSIX allows read-only opens of directories. We don't
971 * want to do this (we use a different code path for this)
972 * so catch a directory open and return an EISDIR. JRA.
975 if(S_ISDIR(smb_fname->st.st_ex_mode)) {
976 fd_close(fsp);
977 errno = EISDIR;
978 return NT_STATUS_FILE_IS_A_DIRECTORY;
981 fsp->file_id = vfs_file_id_from_sbuf(conn, &smb_fname->st);
982 fsp->vuid = req ? req->vuid : UID_FIELD_INVALID;
983 fsp->file_pid = req ? req->smbpid : 0;
984 fsp->can_lock = True;
985 fsp->can_read = ((access_mask & FILE_READ_DATA) != 0);
986 fsp->can_write =
987 CAN_WRITE(conn) &&
988 ((access_mask & (FILE_WRITE_DATA | FILE_APPEND_DATA)) != 0);
989 fsp->print_file = NULL;
990 fsp->modified = False;
991 fsp->sent_oplock_break = NO_BREAK_SENT;
992 fsp->is_directory = False;
993 if (conn->aio_write_behind_list &&
994 is_in_path(smb_fname->base_name, conn->aio_write_behind_list,
995 conn->case_sensitive)) {
996 fsp->aio_write_behind = True;
999 fsp->wcp = NULL; /* Write cache pointer. */
1001 DEBUG(2,("%s opened file %s read=%s write=%s (numopen=%d)\n",
1002 conn->session_info->unix_info->unix_name,
1003 smb_fname_str_dbg(smb_fname),
1004 BOOLSTR(fsp->can_read), BOOLSTR(fsp->can_write),
1005 conn->num_files_open));
1007 errno = 0;
1008 return NT_STATUS_OK;
1011 /****************************************************************************
1012 Check if we can open a file with a share mode.
1013 Returns True if conflict, False if not.
1014 ****************************************************************************/
1016 static bool share_conflict(struct share_mode_entry *entry,
1017 uint32 access_mask,
1018 uint32 share_access)
1020 DEBUG(10,("share_conflict: entry->access_mask = 0x%x, "
1021 "entry->share_access = 0x%x, "
1022 "entry->private_options = 0x%x\n",
1023 (unsigned int)entry->access_mask,
1024 (unsigned int)entry->share_access,
1025 (unsigned int)entry->private_options));
1027 if (server_id_is_disconnected(&entry->pid)) {
1029 * note: cleanup should have been done by
1030 * delay_for_batch_oplocks()
1032 return false;
1035 DEBUG(10,("share_conflict: access_mask = 0x%x, share_access = 0x%x\n",
1036 (unsigned int)access_mask, (unsigned int)share_access));
1038 if ((entry->access_mask & (FILE_WRITE_DATA|
1039 FILE_APPEND_DATA|
1040 FILE_READ_DATA|
1041 FILE_EXECUTE|
1042 DELETE_ACCESS)) == 0) {
1043 DEBUG(10,("share_conflict: No conflict due to "
1044 "entry->access_mask = 0x%x\n",
1045 (unsigned int)entry->access_mask ));
1046 return False;
1049 if ((access_mask & (FILE_WRITE_DATA|
1050 FILE_APPEND_DATA|
1051 FILE_READ_DATA|
1052 FILE_EXECUTE|
1053 DELETE_ACCESS)) == 0) {
1054 DEBUG(10,("share_conflict: No conflict due to "
1055 "access_mask = 0x%x\n",
1056 (unsigned int)access_mask ));
1057 return False;
1060 #if 1 /* JRA TEST - Superdebug. */
1061 #define CHECK_MASK(num, am, right, sa, share) \
1062 DEBUG(10,("share_conflict: [%d] am (0x%x) & right (0x%x) = 0x%x\n", \
1063 (unsigned int)(num), (unsigned int)(am), \
1064 (unsigned int)(right), (unsigned int)(am)&(right) )); \
1065 DEBUG(10,("share_conflict: [%d] sa (0x%x) & share (0x%x) = 0x%x\n", \
1066 (unsigned int)(num), (unsigned int)(sa), \
1067 (unsigned int)(share), (unsigned int)(sa)&(share) )); \
1068 if (((am) & (right)) && !((sa) & (share))) { \
1069 DEBUG(10,("share_conflict: check %d conflict am = 0x%x, right = 0x%x, \
1070 sa = 0x%x, share = 0x%x\n", (num), (unsigned int)(am), (unsigned int)(right), (unsigned int)(sa), \
1071 (unsigned int)(share) )); \
1072 return True; \
1074 #else
1075 #define CHECK_MASK(num, am, right, sa, share) \
1076 if (((am) & (right)) && !((sa) & (share))) { \
1077 DEBUG(10,("share_conflict: check %d conflict am = 0x%x, right = 0x%x, \
1078 sa = 0x%x, share = 0x%x\n", (num), (unsigned int)(am), (unsigned int)(right), (unsigned int)(sa), \
1079 (unsigned int)(share) )); \
1080 return True; \
1082 #endif
1084 CHECK_MASK(1, entry->access_mask, FILE_WRITE_DATA | FILE_APPEND_DATA,
1085 share_access, FILE_SHARE_WRITE);
1086 CHECK_MASK(2, access_mask, FILE_WRITE_DATA | FILE_APPEND_DATA,
1087 entry->share_access, FILE_SHARE_WRITE);
1089 CHECK_MASK(3, entry->access_mask, FILE_READ_DATA | FILE_EXECUTE,
1090 share_access, FILE_SHARE_READ);
1091 CHECK_MASK(4, access_mask, FILE_READ_DATA | FILE_EXECUTE,
1092 entry->share_access, FILE_SHARE_READ);
1094 CHECK_MASK(5, entry->access_mask, DELETE_ACCESS,
1095 share_access, FILE_SHARE_DELETE);
1096 CHECK_MASK(6, access_mask, DELETE_ACCESS,
1097 entry->share_access, FILE_SHARE_DELETE);
1099 DEBUG(10,("share_conflict: No conflict.\n"));
1100 return False;
1103 #if defined(DEVELOPER)
1104 static void validate_my_share_entries(struct smbd_server_connection *sconn,
1105 int num,
1106 struct share_mode_entry *share_entry)
1108 struct server_id self = messaging_server_id(sconn->msg_ctx);
1109 files_struct *fsp;
1111 if (!serverid_equal(&self, &share_entry->pid)) {
1112 return;
1115 if (share_entry->op_mid == 0) {
1116 /* INTERNAL_OPEN_ONLY */
1117 return;
1120 if (!is_valid_share_mode_entry(share_entry)) {
1121 return;
1124 fsp = file_find_dif(sconn, share_entry->id,
1125 share_entry->share_file_id);
1126 if (!fsp) {
1127 DEBUG(0,("validate_my_share_entries: PANIC : %s\n",
1128 share_mode_str(talloc_tos(), num, share_entry) ));
1129 smb_panic("validate_my_share_entries: Cannot match a "
1130 "share entry with an open file\n");
1133 if (((uint16)fsp->oplock_type) != share_entry->op_type) {
1134 goto panic;
1137 return;
1139 panic:
1141 char *str;
1142 DEBUG(0,("validate_my_share_entries: PANIC : %s\n",
1143 share_mode_str(talloc_tos(), num, share_entry) ));
1144 str = talloc_asprintf(talloc_tos(),
1145 "validate_my_share_entries: "
1146 "file %s, oplock_type = 0x%x, op_type = 0x%x\n",
1147 fsp->fsp_name->base_name,
1148 (unsigned int)fsp->oplock_type,
1149 (unsigned int)share_entry->op_type );
1150 smb_panic(str);
1153 #endif
1155 bool is_stat_open(uint32 access_mask)
1157 const uint32_t stat_open_bits =
1158 (SYNCHRONIZE_ACCESS|
1159 FILE_READ_ATTRIBUTES|
1160 FILE_WRITE_ATTRIBUTES);
1162 return (((access_mask & stat_open_bits) != 0) &&
1163 ((access_mask & ~stat_open_bits) == 0));
1166 static bool has_delete_on_close(struct share_mode_lock *lck,
1167 uint32_t name_hash)
1169 struct share_mode_data *d = lck->data;
1170 uint32_t i;
1172 if (d->num_share_modes == 0) {
1173 return false;
1175 if (!is_delete_on_close_set(lck, name_hash)) {
1176 return false;
1178 for (i=0; i<d->num_share_modes; i++) {
1179 if (!share_mode_stale_pid(d, i)) {
1180 return true;
1183 return false;
1186 /****************************************************************************
1187 Deal with share modes
1188 Invariant: Share mode must be locked on entry and exit.
1189 Returns -1 on error, or number of share modes on success (may be zero).
1190 ****************************************************************************/
1192 static NTSTATUS open_mode_check(connection_struct *conn,
1193 struct share_mode_lock *lck,
1194 uint32 access_mask,
1195 uint32 share_access)
1197 int i;
1199 if(lck->data->num_share_modes == 0) {
1200 return NT_STATUS_OK;
1203 if (is_stat_open(access_mask)) {
1204 /* Stat open that doesn't trigger oplock breaks or share mode
1205 * checks... ! JRA. */
1206 return NT_STATUS_OK;
1210 * Check if the share modes will give us access.
1213 #if defined(DEVELOPER)
1214 for(i = 0; i < lck->data->num_share_modes; i++) {
1215 validate_my_share_entries(conn->sconn, i,
1216 &lck->data->share_modes[i]);
1218 #endif
1220 /* Now we check the share modes, after any oplock breaks. */
1221 for(i = 0; i < lck->data->num_share_modes; i++) {
1223 if (!is_valid_share_mode_entry(&lck->data->share_modes[i])) {
1224 continue;
1227 /* someone else has a share lock on it, check to see if we can
1228 * too */
1229 if (share_conflict(&lck->data->share_modes[i],
1230 access_mask, share_access)) {
1232 if (share_mode_stale_pid(lck->data, i)) {
1233 continue;
1236 return NT_STATUS_SHARING_VIOLATION;
1240 return NT_STATUS_OK;
1244 * Send a break message to the oplock holder and delay the open for
1245 * our client.
1248 NTSTATUS send_break_message(struct messaging_context *msg_ctx,
1249 const struct share_mode_entry *exclusive,
1250 uint16_t break_to)
1252 NTSTATUS status;
1253 char msg[MSG_SMB_SHARE_MODE_ENTRY_SIZE];
1255 DEBUG(10, ("Sending break request to PID %s\n",
1256 procid_str_static(&exclusive->pid)));
1258 /* Create the message. */
1259 share_mode_entry_to_message(msg, exclusive);
1261 /* Overload entry->op_type */
1263 * This is a cut from uint32 to uint16, but so far only the lower 3
1264 * bits (LEASE_WRITE/HANDLE/READ are used anyway.
1266 SSVAL(msg,OP_BREAK_MSG_OP_TYPE_OFFSET, break_to);
1268 status = messaging_send_buf(msg_ctx, exclusive->pid,
1269 MSG_SMB_BREAK_REQUEST,
1270 (uint8 *)msg, sizeof(msg));
1271 if (!NT_STATUS_IS_OK(status)) {
1272 DEBUG(3, ("Could not send oplock break message: %s\n",
1273 nt_errstr(status)));
1276 return status;
1280 * Do internal consistency checks on the share mode for a file.
1283 static bool validate_oplock_types(struct share_mode_lock *lck)
1285 struct share_mode_data *d = lck->data;
1286 bool batch = false;
1287 bool ex_or_batch = false;
1288 bool level2 = false;
1289 bool no_oplock = false;
1290 uint32_t num_non_stat_opens = 0;
1291 uint32_t i;
1293 for (i=0; i<d->num_share_modes; i++) {
1294 struct share_mode_entry *e = &d->share_modes[i];
1296 if (!is_valid_share_mode_entry(e)) {
1297 continue;
1300 if (e->op_mid == 0) {
1301 /* INTERNAL_OPEN_ONLY */
1302 continue;
1305 if (e->op_type == NO_OPLOCK && is_stat_open(e->access_mask)) {
1306 /* We ignore stat opens in the table - they
1307 always have NO_OPLOCK and never get or
1308 cause breaks. JRA. */
1309 continue;
1312 num_non_stat_opens += 1;
1314 if (BATCH_OPLOCK_TYPE(e->op_type)) {
1315 /* batch - can only be one. */
1316 if (share_mode_stale_pid(d, i)) {
1317 DEBUG(10, ("Found stale batch oplock\n"));
1318 continue;
1320 if (ex_or_batch || batch || level2 || no_oplock) {
1321 DEBUG(0, ("Bad batch oplock entry %u.",
1322 (unsigned)i));
1323 return false;
1325 batch = true;
1328 if (EXCLUSIVE_OPLOCK_TYPE(e->op_type)) {
1329 if (share_mode_stale_pid(d, i)) {
1330 DEBUG(10, ("Found stale duplicate oplock\n"));
1331 continue;
1333 /* Exclusive or batch - can only be one. */
1334 if (ex_or_batch || level2 || no_oplock) {
1335 DEBUG(0, ("Bad exclusive or batch oplock "
1336 "entry %u.", (unsigned)i));
1337 return false;
1339 ex_or_batch = true;
1342 if (LEVEL_II_OPLOCK_TYPE(e->op_type)) {
1343 if (batch || ex_or_batch) {
1344 if (share_mode_stale_pid(d, i)) {
1345 DEBUG(10, ("Found stale LevelII "
1346 "oplock\n"));
1347 continue;
1349 DEBUG(0, ("Bad levelII oplock entry %u.",
1350 (unsigned)i));
1351 return false;
1353 level2 = true;
1356 if (e->op_type == NO_OPLOCK) {
1357 if (batch || ex_or_batch) {
1358 if (share_mode_stale_pid(d, i)) {
1359 DEBUG(10, ("Found stale NO_OPLOCK "
1360 "entry\n"));
1361 continue;
1363 DEBUG(0, ("Bad no oplock entry %u.",
1364 (unsigned)i));
1365 return false;
1367 no_oplock = true;
1371 remove_stale_share_mode_entries(d);
1373 if ((batch || ex_or_batch) && (num_non_stat_opens != 1)) {
1374 DEBUG(1, ("got batch (%d) or ex (%d) non-exclusively (%d)\n",
1375 (int)batch, (int)ex_or_batch,
1376 (int)d->num_share_modes));
1377 return false;
1380 return true;
1383 static bool delay_for_oplock(files_struct *fsp,
1384 int oplock_request,
1385 const struct smb2_lease *lease,
1386 struct share_mode_lock *lck,
1387 bool have_sharing_violation,
1388 uint32_t create_disposition,
1389 bool first_open_attempt)
1391 struct share_mode_data *d = lck->data;
1392 uint32_t i;
1393 bool delay = false;
1394 bool will_overwrite;
1396 if ((oplock_request & INTERNAL_OPEN_ONLY) ||
1397 is_stat_open(fsp->access_mask)) {
1398 return false;
1401 switch (create_disposition) {
1402 case FILE_SUPERSEDE:
1403 case FILE_OVERWRITE:
1404 case FILE_OVERWRITE_IF:
1405 will_overwrite = true;
1406 break;
1407 default:
1408 will_overwrite = false;
1409 break;
1412 for (i=0; i<d->num_share_modes; i++) {
1413 struct share_mode_entry *e = &d->share_modes[i];
1414 struct share_mode_lease *l = NULL;
1415 uint32_t e_lease_type = get_lease_type(d, e);
1416 uint32_t break_to;
1417 uint32_t delay_mask = 0;
1419 if (e->op_type == LEASE_OPLOCK) {
1420 l = &d->leases[e->lease_idx];
1423 if (have_sharing_violation) {
1424 delay_mask = SMB2_LEASE_HANDLE;
1425 } else {
1426 delay_mask = SMB2_LEASE_WRITE;
1429 break_to = e_lease_type & ~delay_mask;
1431 if (will_overwrite) {
1433 * we'll decide about SMB2_LEASE_READ later.
1435 * Maybe the break will be defered
1437 break_to &= ~SMB2_LEASE_HANDLE;
1440 DEBUG(10, ("entry %u: e_lease_type %u, will_overwrite: %u\n",
1441 (unsigned)i, (unsigned)e_lease_type,
1442 (unsigned)will_overwrite));
1444 if (lease != NULL && l != NULL) {
1445 bool ign;
1447 ign = smb2_lease_equal(fsp_client_guid(fsp),
1448 &lease->lease_key,
1449 &l->client_guid,
1450 &l->lease_key);
1451 if (ign) {
1452 continue;
1456 if ((e_lease_type & ~break_to) == 0) {
1457 if (l != NULL && l->breaking) {
1458 delay = true;
1460 continue;
1463 if (share_mode_stale_pid(d, i)) {
1464 continue;
1467 if (will_overwrite) {
1469 * If we break anyway break to NONE directly.
1470 * Otherwise vfs_set_filelen() will trigger the
1471 * break.
1473 break_to &= ~(SMB2_LEASE_READ|SMB2_LEASE_WRITE);
1476 if (e->op_type != LEASE_OPLOCK) {
1478 * Oplocks only support breaking to R or NONE.
1480 break_to &= ~(SMB2_LEASE_HANDLE|SMB2_LEASE_WRITE);
1483 DEBUG(10, ("breaking from %d to %d\n",
1484 (int)e_lease_type, (int)break_to));
1485 send_break_message(fsp->conn->sconn->msg_ctx, e,
1486 break_to);
1487 if (e_lease_type & delay_mask) {
1488 delay = true;
1490 if (l != NULL && l->breaking && !first_open_attempt) {
1491 delay = true;
1493 continue;
1496 return delay;
1499 static bool file_has_brlocks(files_struct *fsp)
1501 struct byte_range_lock *br_lck;
1503 br_lck = brl_get_locks_readonly(fsp);
1504 if (!br_lck)
1505 return false;
1507 return (brl_num_locks(br_lck) > 0);
1510 int find_share_mode_lease(struct share_mode_data *d,
1511 const struct GUID *client_guid,
1512 const struct smb2_lease_key *key)
1514 uint32_t i;
1516 for (i=0; i<d->num_leases; i++) {
1517 struct share_mode_lease *l = &d->leases[i];
1519 if (smb2_lease_equal(client_guid,
1520 key,
1521 &l->client_guid,
1522 &l->lease_key)) {
1523 return i;
1527 return -1;
1530 struct fsp_lease *find_fsp_lease(struct files_struct *new_fsp,
1531 const struct smb2_lease_key *key,
1532 const struct share_mode_lease *l)
1534 struct files_struct *fsp;
1537 * TODO: Measure how expensive this loop is with thousands of open
1538 * handles...
1541 for (fsp = file_find_di_first(new_fsp->conn->sconn, new_fsp->file_id);
1542 fsp != NULL;
1543 fsp = file_find_di_next(fsp)) {
1545 if (fsp == new_fsp) {
1546 continue;
1548 if (fsp->oplock_type != LEASE_OPLOCK) {
1549 continue;
1551 if (smb2_lease_key_equal(&fsp->lease->lease.lease_key, key)) {
1552 fsp->lease->ref_count += 1;
1553 return fsp->lease;
1557 /* Not found - must be leased in another smbd. */
1558 new_fsp->lease = talloc_zero(new_fsp->conn->sconn, struct fsp_lease);
1559 if (new_fsp->lease == NULL) {
1560 return NULL;
1562 new_fsp->lease->ref_count = 1;
1563 new_fsp->lease->sconn = new_fsp->conn->sconn;
1564 new_fsp->lease->lease.lease_key = *key;
1565 new_fsp->lease->lease.lease_state = l->current_state;
1567 * We internally treat all leases as V2 and update
1568 * the epoch, but when sending breaks it matters if
1569 * the requesting lease was v1 or v2.
1571 new_fsp->lease->lease.lease_version = l->lease_version;
1572 new_fsp->lease->lease.lease_epoch = l->epoch;
1573 return new_fsp->lease;
1576 static NTSTATUS grant_fsp_lease(struct files_struct *fsp,
1577 struct share_mode_lock *lck,
1578 const struct smb2_lease *lease,
1579 uint32_t *p_lease_idx,
1580 uint32_t granted)
1582 struct share_mode_data *d = lck->data;
1583 const struct GUID *client_guid = fsp_client_guid(fsp);
1584 struct share_mode_lease *tmp;
1585 NTSTATUS status;
1586 int idx;
1588 idx = find_share_mode_lease(d, client_guid, &lease->lease_key);
1590 if (idx != -1) {
1591 struct share_mode_lease *l = &d->leases[idx];
1592 bool do_upgrade;
1593 uint32_t existing, requested;
1595 fsp->lease = find_fsp_lease(fsp, &lease->lease_key, l);
1596 if (fsp->lease == NULL) {
1597 DEBUG(1, ("Did not find existing lease for file %s\n",
1598 fsp_str_dbg(fsp)));
1599 return NT_STATUS_NO_MEMORY;
1602 *p_lease_idx = idx;
1605 * Upgrade only if the requested lease is a strict upgrade.
1607 existing = l->current_state;
1608 requested = lease->lease_state;
1611 * Tricky: This test makes sure that "requested" is a
1612 * strict bitwise superset of "existing".
1614 do_upgrade = ((existing & requested) == existing);
1617 * Upgrade only if there's a change.
1619 do_upgrade &= (granted != existing);
1622 * Upgrade only if other leases don't prevent what was asked
1623 * for.
1625 do_upgrade &= (granted == requested);
1628 * only upgrade if we are not in breaking state
1630 do_upgrade &= !l->breaking;
1632 DEBUG(10, ("existing=%"PRIu32", requested=%"PRIu32", "
1633 "granted=%"PRIu32", do_upgrade=%d\n",
1634 existing, requested, granted, (int)do_upgrade));
1636 if (do_upgrade) {
1637 l->current_state = granted;
1638 l->epoch += 1;
1641 /* Ensure we're in sync with current lease state. */
1642 fsp_lease_update(lck, fsp_client_guid(fsp), fsp->lease);
1643 return NT_STATUS_OK;
1647 * Create new lease
1650 tmp = talloc_realloc(d, d->leases, struct share_mode_lease,
1651 d->num_leases+1);
1652 if (tmp == NULL) {
1654 * See [MS-SMB2]
1656 return NT_STATUS_INSUFFICIENT_RESOURCES;
1658 d->leases = tmp;
1660 fsp->lease = talloc_zero(fsp->conn->sconn, struct fsp_lease);
1661 if (fsp->lease == NULL) {
1662 return NT_STATUS_INSUFFICIENT_RESOURCES;
1664 fsp->lease->ref_count = 1;
1665 fsp->lease->sconn = fsp->conn->sconn;
1666 fsp->lease->lease.lease_version = lease->lease_version;
1667 fsp->lease->lease.lease_key = lease->lease_key;
1668 fsp->lease->lease.lease_state = granted;
1669 fsp->lease->lease.lease_epoch = lease->lease_epoch + 1;
1671 *p_lease_idx = d->num_leases;
1673 d->leases[d->num_leases] = (struct share_mode_lease) {
1674 .client_guid = *client_guid,
1675 .lease_key = fsp->lease->lease.lease_key,
1676 .current_state = fsp->lease->lease.lease_state,
1677 .lease_version = fsp->lease->lease.lease_version,
1678 .epoch = fsp->lease->lease.lease_epoch,
1681 status = leases_db_add(client_guid,
1682 &lease->lease_key,
1683 &fsp->file_id,
1684 fsp->conn->connectpath,
1685 fsp->fsp_name->base_name,
1686 fsp->fsp_name->stream_name);
1687 if (!NT_STATUS_IS_OK(status)) {
1688 DEBUG(10, ("%s: leases_db_add failed: %s\n", __func__,
1689 nt_errstr(status)));
1690 TALLOC_FREE(fsp->lease);
1691 return NT_STATUS_INSUFFICIENT_RESOURCES;
1694 d->num_leases += 1;
1695 d->modified = true;
1697 return NT_STATUS_OK;
1700 static bool is_same_lease(const files_struct *fsp,
1701 const struct share_mode_data *d,
1702 const struct share_mode_entry *e,
1703 const struct smb2_lease *lease)
1705 if (e->op_type != LEASE_OPLOCK) {
1706 return false;
1708 if (lease == NULL) {
1709 return false;
1712 return smb2_lease_equal(fsp_client_guid(fsp),
1713 &lease->lease_key,
1714 &d->leases[e->lease_idx].client_guid,
1715 &d->leases[e->lease_idx].lease_key);
1718 static NTSTATUS grant_fsp_oplock_type(struct smb_request *req,
1719 struct files_struct *fsp,
1720 struct share_mode_lock *lck,
1721 int oplock_request,
1722 struct smb2_lease *lease)
1724 struct share_mode_data *d = lck->data;
1725 bool got_handle_lease = false;
1726 bool got_oplock = false;
1727 uint32_t i;
1728 uint32_t granted;
1729 uint32_t lease_idx = UINT32_MAX;
1730 bool ok;
1731 NTSTATUS status;
1733 if (oplock_request & INTERNAL_OPEN_ONLY) {
1734 /* No oplocks on internal open. */
1735 oplock_request = NO_OPLOCK;
1736 DEBUG(10,("grant_fsp_oplock_type: oplock type 0x%x on file %s\n",
1737 fsp->oplock_type, fsp_str_dbg(fsp)));
1740 if (oplock_request == LEASE_OPLOCK) {
1741 if (lease == NULL) {
1743 * The SMB2 layer should have checked this
1745 return NT_STATUS_INTERNAL_ERROR;
1748 granted = lease->lease_state;
1750 if (lp_kernel_oplocks(SNUM(fsp->conn))) {
1751 DEBUG(10, ("No lease granted because kernel oplocks are enabled\n"));
1752 granted = SMB2_LEASE_NONE;
1754 if ((granted & (SMB2_LEASE_READ|SMB2_LEASE_WRITE)) == 0) {
1755 DEBUG(10, ("No read or write lease requested\n"));
1756 granted = SMB2_LEASE_NONE;
1758 if (granted == SMB2_LEASE_WRITE) {
1759 DEBUG(10, ("pure write lease requested\n"));
1760 granted = SMB2_LEASE_NONE;
1762 if (granted == (SMB2_LEASE_WRITE|SMB2_LEASE_HANDLE)) {
1763 DEBUG(10, ("write and handle lease requested\n"));
1764 granted = SMB2_LEASE_NONE;
1766 } else {
1767 granted = map_oplock_to_lease_type(
1768 oplock_request & ~SAMBA_PRIVATE_OPLOCK_MASK);
1771 if (lp_locking(fsp->conn->params) && file_has_brlocks(fsp)) {
1772 DEBUG(10,("grant_fsp_oplock_type: file %s has byte range locks\n",
1773 fsp_str_dbg(fsp)));
1774 granted &= ~SMB2_LEASE_READ;
1777 for (i=0; i<d->num_share_modes; i++) {
1778 struct share_mode_entry *e = &d->share_modes[i];
1779 uint32_t e_lease_type;
1781 e_lease_type = get_lease_type(d, e);
1783 if ((granted & SMB2_LEASE_WRITE) &&
1784 !is_same_lease(fsp, d, e, lease) &&
1785 !share_mode_stale_pid(d, i)) {
1787 * Can grant only one writer
1789 granted &= ~SMB2_LEASE_WRITE;
1792 if ((e_lease_type & SMB2_LEASE_HANDLE) && !got_handle_lease &&
1793 !share_mode_stale_pid(d, i)) {
1794 got_handle_lease = true;
1797 if ((e->op_type != LEASE_OPLOCK) && !got_oplock &&
1798 !share_mode_stale_pid(d, i)) {
1799 got_oplock = true;
1803 if ((granted & SMB2_LEASE_READ) && !(granted & SMB2_LEASE_WRITE)) {
1804 bool allow_level2 =
1805 (global_client_caps & CAP_LEVEL_II_OPLOCKS) &&
1806 lp_level2_oplocks(SNUM(fsp->conn));
1808 if (!allow_level2) {
1809 granted = SMB2_LEASE_NONE;
1813 if (oplock_request == LEASE_OPLOCK) {
1814 if (got_oplock) {
1815 granted &= ~SMB2_LEASE_HANDLE;
1818 fsp->oplock_type = LEASE_OPLOCK;
1820 status = grant_fsp_lease(fsp, lck, lease, &lease_idx,
1821 granted);
1822 if (!NT_STATUS_IS_OK(status)) {
1823 return status;
1826 *lease = fsp->lease->lease;
1827 DEBUG(10, ("lease_state=%d\n", lease->lease_state));
1828 } else {
1829 if (got_handle_lease) {
1830 granted = SMB2_LEASE_NONE;
1833 switch (granted) {
1834 case SMB2_LEASE_READ|SMB2_LEASE_WRITE|SMB2_LEASE_HANDLE:
1835 fsp->oplock_type = BATCH_OPLOCK|EXCLUSIVE_OPLOCK;
1836 break;
1837 case SMB2_LEASE_READ|SMB2_LEASE_WRITE:
1838 fsp->oplock_type = EXCLUSIVE_OPLOCK;
1839 break;
1840 case SMB2_LEASE_READ|SMB2_LEASE_HANDLE:
1841 case SMB2_LEASE_READ:
1842 fsp->oplock_type = LEVEL_II_OPLOCK;
1843 break;
1844 default:
1845 fsp->oplock_type = NO_OPLOCK;
1846 break;
1849 status = set_file_oplock(fsp);
1850 if (!NT_STATUS_IS_OK(status)) {
1852 * Could not get the kernel oplock
1854 fsp->oplock_type = NO_OPLOCK;
1858 ok = set_share_mode(lck, fsp, get_current_uid(fsp->conn),
1859 req ? req->mid : 0,
1860 fsp->oplock_type,
1861 lease_idx);
1862 if (!ok) {
1863 return NT_STATUS_NO_MEMORY;
1866 ok = update_num_read_oplocks(fsp, lck);
1867 if (!ok) {
1868 del_share_mode(lck, fsp);
1869 return NT_STATUS_INTERNAL_ERROR;
1872 DEBUG(10,("grant_fsp_oplock_type: oplock type 0x%x on file %s\n",
1873 fsp->oplock_type, fsp_str_dbg(fsp)));
1875 return NT_STATUS_OK;
1878 static bool request_timed_out(struct timeval request_time,
1879 struct timeval timeout)
1881 struct timeval now, end_time;
1882 GetTimeOfDay(&now);
1883 end_time = timeval_sum(&request_time, &timeout);
1884 return (timeval_compare(&end_time, &now) < 0);
1887 struct defer_open_state {
1888 struct smbXsrv_connection *xconn;
1889 uint64_t mid;
1892 static void defer_open_done(struct tevent_req *req);
1894 /****************************************************************************
1895 Handle the 1 second delay in returning a SHARING_VIOLATION error.
1896 ****************************************************************************/
1898 static void defer_open(struct share_mode_lock *lck,
1899 struct timeval request_time,
1900 struct timeval timeout,
1901 struct smb_request *req,
1902 struct deferred_open_record *state)
1904 struct deferred_open_record *open_rec;
1906 DEBUG(10,("defer_open_sharing_error: time [%u.%06u] adding deferred "
1907 "open entry for mid %llu\n",
1908 (unsigned int)request_time.tv_sec,
1909 (unsigned int)request_time.tv_usec,
1910 (unsigned long long)req->mid));
1912 open_rec = talloc(NULL, struct deferred_open_record);
1913 if (open_rec == NULL) {
1914 TALLOC_FREE(lck);
1915 exit_server("talloc failed");
1918 *open_rec = *state;
1920 if (lck) {
1921 struct defer_open_state *watch_state;
1922 struct tevent_req *watch_req;
1923 bool ret;
1925 watch_state = talloc(open_rec, struct defer_open_state);
1926 if (watch_state == NULL) {
1927 exit_server("talloc failed");
1929 watch_state->xconn = req->xconn;
1930 watch_state->mid = req->mid;
1932 DEBUG(10, ("defering mid %llu\n",
1933 (unsigned long long)req->mid));
1935 watch_req = dbwrap_record_watch_send(
1936 watch_state, req->sconn->ev_ctx, lck->data->record,
1937 req->sconn->msg_ctx);
1938 if (watch_req == NULL) {
1939 exit_server("Could not watch share mode record");
1941 tevent_req_set_callback(watch_req, defer_open_done,
1942 watch_state);
1944 ret = tevent_req_set_endtime(
1945 watch_req, req->sconn->ev_ctx,
1946 timeval_sum(&request_time, &timeout));
1947 SMB_ASSERT(ret);
1950 if (!push_deferred_open_message_smb(req, request_time, timeout,
1951 state->id, open_rec)) {
1952 TALLOC_FREE(lck);
1953 exit_server("push_deferred_open_message_smb failed");
1957 static void defer_open_done(struct tevent_req *req)
1959 struct defer_open_state *state = tevent_req_callback_data(
1960 req, struct defer_open_state);
1961 NTSTATUS status;
1962 bool ret;
1964 status = dbwrap_record_watch_recv(req, talloc_tos(), NULL);
1965 TALLOC_FREE(req);
1966 if (!NT_STATUS_IS_OK(status)) {
1967 DEBUG(5, ("dbwrap_record_watch_recv returned %s\n",
1968 nt_errstr(status)));
1970 * Even if it failed, retry anyway. TODO: We need a way to
1971 * tell a re-scheduled open about that error.
1975 DEBUG(10, ("scheduling mid %llu\n", (unsigned long long)state->mid));
1977 ret = schedule_deferred_open_message_smb(state->xconn, state->mid);
1978 SMB_ASSERT(ret);
1979 TALLOC_FREE(state);
1983 /****************************************************************************
1984 On overwrite open ensure that the attributes match.
1985 ****************************************************************************/
1987 static bool open_match_attributes(connection_struct *conn,
1988 uint32 old_dos_attr,
1989 uint32 new_dos_attr,
1990 mode_t existing_unx_mode,
1991 mode_t new_unx_mode,
1992 mode_t *returned_unx_mode)
1994 uint32 noarch_old_dos_attr, noarch_new_dos_attr;
1996 noarch_old_dos_attr = (old_dos_attr & ~FILE_ATTRIBUTE_ARCHIVE);
1997 noarch_new_dos_attr = (new_dos_attr & ~FILE_ATTRIBUTE_ARCHIVE);
1999 if((noarch_old_dos_attr == 0 && noarch_new_dos_attr != 0) ||
2000 (noarch_old_dos_attr != 0 && ((noarch_old_dos_attr & noarch_new_dos_attr) == noarch_old_dos_attr))) {
2001 *returned_unx_mode = new_unx_mode;
2002 } else {
2003 *returned_unx_mode = (mode_t)0;
2006 DEBUG(10,("open_match_attributes: old_dos_attr = 0x%x, "
2007 "existing_unx_mode = 0%o, new_dos_attr = 0x%x "
2008 "returned_unx_mode = 0%o\n",
2009 (unsigned int)old_dos_attr,
2010 (unsigned int)existing_unx_mode,
2011 (unsigned int)new_dos_attr,
2012 (unsigned int)*returned_unx_mode ));
2014 /* If we're mapping SYSTEM and HIDDEN ensure they match. */
2015 if (lp_map_system(SNUM(conn)) || lp_store_dos_attributes(SNUM(conn))) {
2016 if ((old_dos_attr & FILE_ATTRIBUTE_SYSTEM) &&
2017 !(new_dos_attr & FILE_ATTRIBUTE_SYSTEM)) {
2018 return False;
2021 if (lp_map_hidden(SNUM(conn)) || lp_store_dos_attributes(SNUM(conn))) {
2022 if ((old_dos_attr & FILE_ATTRIBUTE_HIDDEN) &&
2023 !(new_dos_attr & FILE_ATTRIBUTE_HIDDEN)) {
2024 return False;
2027 return True;
2030 /****************************************************************************
2031 Special FCB or DOS processing in the case of a sharing violation.
2032 Try and find a duplicated file handle.
2033 ****************************************************************************/
2035 static NTSTATUS fcb_or_dos_open(struct smb_request *req,
2036 connection_struct *conn,
2037 files_struct *fsp_to_dup_into,
2038 const struct smb_filename *smb_fname,
2039 struct file_id id,
2040 uint16 file_pid,
2041 uint64_t vuid,
2042 uint32 access_mask,
2043 uint32 share_access,
2044 uint32 create_options)
2046 files_struct *fsp;
2048 DEBUG(5,("fcb_or_dos_open: attempting old open semantics for "
2049 "file %s.\n", smb_fname_str_dbg(smb_fname)));
2051 for(fsp = file_find_di_first(conn->sconn, id); fsp;
2052 fsp = file_find_di_next(fsp)) {
2054 DEBUG(10,("fcb_or_dos_open: checking file %s, fd = %d, "
2055 "vuid = %llu, file_pid = %u, private_options = 0x%x "
2056 "access_mask = 0x%x\n", fsp_str_dbg(fsp),
2057 fsp->fh->fd, (unsigned long long)fsp->vuid,
2058 (unsigned int)fsp->file_pid,
2059 (unsigned int)fsp->fh->private_options,
2060 (unsigned int)fsp->access_mask ));
2062 if (fsp != fsp_to_dup_into &&
2063 fsp->fh->fd != -1 &&
2064 fsp->vuid == vuid &&
2065 fsp->file_pid == file_pid &&
2066 (fsp->fh->private_options & (NTCREATEX_OPTIONS_PRIVATE_DENY_DOS |
2067 NTCREATEX_OPTIONS_PRIVATE_DENY_FCB)) &&
2068 (fsp->access_mask & FILE_WRITE_DATA) &&
2069 strequal(fsp->fsp_name->base_name, smb_fname->base_name) &&
2070 strequal(fsp->fsp_name->stream_name,
2071 smb_fname->stream_name)) {
2072 DEBUG(10,("fcb_or_dos_open: file match\n"));
2073 break;
2077 if (!fsp) {
2078 return NT_STATUS_NOT_FOUND;
2081 /* quite an insane set of semantics ... */
2082 if (is_executable(smb_fname->base_name) &&
2083 (fsp->fh->private_options & NTCREATEX_OPTIONS_PRIVATE_DENY_DOS)) {
2084 DEBUG(10,("fcb_or_dos_open: file fail due to is_executable.\n"));
2085 return NT_STATUS_INVALID_PARAMETER;
2088 /* We need to duplicate this fsp. */
2089 return dup_file_fsp(req, fsp, access_mask, share_access,
2090 create_options, fsp_to_dup_into);
2093 static void schedule_defer_open(struct share_mode_lock *lck,
2094 struct file_id id,
2095 struct timeval request_time,
2096 struct smb_request *req)
2098 struct deferred_open_record state;
2100 /* This is a relative time, added to the absolute
2101 request_time value to get the absolute timeout time.
2102 Note that if this is the second or greater time we enter
2103 this codepath for this particular request mid then
2104 request_time is left as the absolute time of the *first*
2105 time this request mid was processed. This is what allows
2106 the request to eventually time out. */
2108 struct timeval timeout;
2110 /* Normally the smbd we asked should respond within
2111 * OPLOCK_BREAK_TIMEOUT seconds regardless of whether
2112 * the client did, give twice the timeout as a safety
2113 * measure here in case the other smbd is stuck
2114 * somewhere else. */
2116 timeout = timeval_set(OPLOCK_BREAK_TIMEOUT*2, 0);
2118 /* Nothing actually uses state.delayed_for_oplocks
2119 but it's handy to differentiate in debug messages
2120 between a 30 second delay due to oplock break, and
2121 a 1 second delay for share mode conflicts. */
2123 state.delayed_for_oplocks = True;
2124 state.async_open = false;
2125 state.id = id;
2127 if (!request_timed_out(request_time, timeout)) {
2128 defer_open(lck, request_time, timeout, req, &state);
2132 /****************************************************************************
2133 Reschedule an open call that went asynchronous.
2134 ****************************************************************************/
2136 static void schedule_async_open(struct timeval request_time,
2137 struct smb_request *req)
2139 struct deferred_open_record state;
2140 struct timeval timeout;
2142 timeout = timeval_set(20, 0);
2144 ZERO_STRUCT(state);
2145 state.delayed_for_oplocks = false;
2146 state.async_open = true;
2148 if (!request_timed_out(request_time, timeout)) {
2149 defer_open(NULL, request_time, timeout, req, &state);
2153 /****************************************************************************
2154 Work out what access_mask to use from what the client sent us.
2155 ****************************************************************************/
2157 static NTSTATUS smbd_calculate_maximum_allowed_access(
2158 connection_struct *conn,
2159 const struct smb_filename *smb_fname,
2160 bool use_privs,
2161 uint32_t *p_access_mask)
2163 struct security_descriptor *sd;
2164 uint32_t access_granted;
2165 NTSTATUS status;
2167 if (!use_privs && (get_current_uid(conn) == (uid_t)0)) {
2168 *p_access_mask |= FILE_GENERIC_ALL;
2169 return NT_STATUS_OK;
2172 status = SMB_VFS_GET_NT_ACL(conn, smb_fname->base_name,
2173 (SECINFO_OWNER |
2174 SECINFO_GROUP |
2175 SECINFO_DACL),
2176 talloc_tos(), &sd);
2178 if (NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
2180 * File did not exist
2182 *p_access_mask = FILE_GENERIC_ALL;
2183 return NT_STATUS_OK;
2185 if (!NT_STATUS_IS_OK(status)) {
2186 DEBUG(10,("Could not get acl on file %s: %s\n",
2187 smb_fname_str_dbg(smb_fname),
2188 nt_errstr(status)));
2189 return NT_STATUS_ACCESS_DENIED;
2193 * If we can access the path to this file, by
2194 * default we have FILE_READ_ATTRIBUTES from the
2195 * containing directory. See the section:
2196 * "Algorithm to Check Access to an Existing File"
2197 * in MS-FSA.pdf.
2199 * se_file_access_check()
2200 * also takes care of owner WRITE_DAC and READ_CONTROL.
2202 status = se_file_access_check(sd,
2203 get_current_nttok(conn),
2204 use_privs,
2205 (*p_access_mask & ~FILE_READ_ATTRIBUTES),
2206 &access_granted);
2208 TALLOC_FREE(sd);
2210 if (!NT_STATUS_IS_OK(status)) {
2211 DEBUG(10, ("Access denied on file %s: "
2212 "when calculating maximum access\n",
2213 smb_fname_str_dbg(smb_fname)));
2214 return NT_STATUS_ACCESS_DENIED;
2216 *p_access_mask = (access_granted | FILE_READ_ATTRIBUTES);
2218 if (!(access_granted & DELETE_ACCESS)) {
2219 if (can_delete_file_in_directory(conn, smb_fname)) {
2220 *p_access_mask |= DELETE_ACCESS;
2224 return NT_STATUS_OK;
2227 NTSTATUS smbd_calculate_access_mask(connection_struct *conn,
2228 const struct smb_filename *smb_fname,
2229 bool use_privs,
2230 uint32_t access_mask,
2231 uint32_t *access_mask_out)
2233 NTSTATUS status;
2234 uint32_t orig_access_mask = access_mask;
2235 uint32_t rejected_share_access;
2238 * Convert GENERIC bits to specific bits.
2241 se_map_generic(&access_mask, &file_generic_mapping);
2243 /* Calculate MAXIMUM_ALLOWED_ACCESS if requested. */
2244 if (access_mask & MAXIMUM_ALLOWED_ACCESS) {
2246 status = smbd_calculate_maximum_allowed_access(
2247 conn, smb_fname, use_privs, &access_mask);
2249 if (!NT_STATUS_IS_OK(status)) {
2250 return status;
2253 access_mask &= conn->share_access;
2256 rejected_share_access = access_mask & ~(conn->share_access);
2258 if (rejected_share_access) {
2259 DEBUG(10, ("smbd_calculate_access_mask: Access denied on "
2260 "file %s: rejected by share access mask[0x%08X] "
2261 "orig[0x%08X] mapped[0x%08X] reject[0x%08X]\n",
2262 smb_fname_str_dbg(smb_fname),
2263 conn->share_access,
2264 orig_access_mask, access_mask,
2265 rejected_share_access));
2266 return NT_STATUS_ACCESS_DENIED;
2269 *access_mask_out = access_mask;
2270 return NT_STATUS_OK;
2273 /****************************************************************************
2274 Remove the deferred open entry under lock.
2275 ****************************************************************************/
2277 /****************************************************************************
2278 Return true if this is a state pointer to an asynchronous create.
2279 ****************************************************************************/
2281 bool is_deferred_open_async(const struct deferred_open_record *rec)
2283 return rec->async_open;
2286 static bool clear_ads(uint32_t create_disposition)
2288 bool ret = false;
2290 switch (create_disposition) {
2291 case FILE_SUPERSEDE:
2292 case FILE_OVERWRITE_IF:
2293 case FILE_OVERWRITE:
2294 ret = true;
2295 break;
2296 default:
2297 break;
2299 return ret;
2302 static int disposition_to_open_flags(uint32_t create_disposition)
2304 int ret = 0;
2307 * Currently we're using FILE_SUPERSEDE as the same as
2308 * FILE_OVERWRITE_IF but they really are
2309 * different. FILE_SUPERSEDE deletes an existing file
2310 * (requiring delete access) then recreates it.
2313 switch (create_disposition) {
2314 case FILE_SUPERSEDE:
2315 case FILE_OVERWRITE_IF:
2317 * If file exists replace/overwrite. If file doesn't
2318 * exist create.
2320 ret = O_CREAT|O_TRUNC;
2321 break;
2323 case FILE_OPEN:
2325 * If file exists open. If file doesn't exist error.
2327 ret = 0;
2328 break;
2330 case FILE_OVERWRITE:
2332 * If file exists overwrite. If file doesn't exist
2333 * error.
2335 ret = O_TRUNC;
2336 break;
2338 case FILE_CREATE:
2340 * If file exists error. If file doesn't exist create.
2342 ret = O_CREAT|O_EXCL;
2343 break;
2345 case FILE_OPEN_IF:
2347 * If file exists open. If file doesn't exist create.
2349 ret = O_CREAT;
2350 break;
2352 return ret;
2355 static int calculate_open_access_flags(uint32_t access_mask,
2356 int oplock_request,
2357 uint32_t private_flags)
2359 bool need_write, need_read;
2362 * Note that we ignore the append flag as append does not
2363 * mean the same thing under DOS and Unix.
2366 need_write = (access_mask & (FILE_WRITE_DATA | FILE_APPEND_DATA));
2367 if (!need_write) {
2368 return O_RDONLY;
2371 /* DENY_DOS opens are always underlying read-write on the
2372 file handle, no matter what the requested access mask
2373 says. */
2375 need_read =
2376 ((private_flags & NTCREATEX_OPTIONS_PRIVATE_DENY_DOS) ||
2377 access_mask & (FILE_READ_ATTRIBUTES|FILE_READ_DATA|
2378 FILE_READ_EA|FILE_EXECUTE));
2380 if (!need_read) {
2381 return O_WRONLY;
2383 return O_RDWR;
2386 /****************************************************************************
2387 Open a file with a share mode. Passed in an already created files_struct *.
2388 ****************************************************************************/
2390 static NTSTATUS open_file_ntcreate(connection_struct *conn,
2391 struct smb_request *req,
2392 uint32 access_mask, /* access bits (FILE_READ_DATA etc.) */
2393 uint32 share_access, /* share constants (FILE_SHARE_READ etc) */
2394 uint32 create_disposition, /* FILE_OPEN_IF etc. */
2395 uint32 create_options, /* options such as delete on close. */
2396 uint32 new_dos_attributes, /* attributes used for new file. */
2397 int oplock_request, /* internal Samba oplock codes. */
2398 struct smb2_lease *lease,
2399 /* Information (FILE_EXISTS etc.) */
2400 uint32_t private_flags, /* Samba specific flags. */
2401 int *pinfo,
2402 files_struct *fsp)
2404 struct smb_filename *smb_fname = fsp->fsp_name;
2405 int flags=0;
2406 int flags2=0;
2407 bool file_existed = VALID_STAT(smb_fname->st);
2408 bool def_acl = False;
2409 bool posix_open = False;
2410 bool new_file_created = False;
2411 bool first_open_attempt = true;
2412 NTSTATUS fsp_open = NT_STATUS_ACCESS_DENIED;
2413 mode_t new_unx_mode = (mode_t)0;
2414 mode_t unx_mode = (mode_t)0;
2415 int info;
2416 uint32 existing_dos_attributes = 0;
2417 struct timeval request_time = timeval_zero();
2418 struct share_mode_lock *lck = NULL;
2419 uint32 open_access_mask = access_mask;
2420 NTSTATUS status;
2421 char *parent_dir;
2422 SMB_STRUCT_STAT saved_stat = smb_fname->st;
2423 struct timespec old_write_time;
2424 struct file_id id;
2426 if (conn->printer) {
2428 * Printers are handled completely differently.
2429 * Most of the passed parameters are ignored.
2432 if (pinfo) {
2433 *pinfo = FILE_WAS_CREATED;
2436 DEBUG(10, ("open_file_ntcreate: printer open fname=%s\n",
2437 smb_fname_str_dbg(smb_fname)));
2439 if (!req) {
2440 DEBUG(0,("open_file_ntcreate: printer open without "
2441 "an SMB request!\n"));
2442 return NT_STATUS_INTERNAL_ERROR;
2445 return print_spool_open(fsp, smb_fname->base_name,
2446 req->vuid);
2449 if (!parent_dirname(talloc_tos(), smb_fname->base_name, &parent_dir,
2450 NULL)) {
2451 return NT_STATUS_NO_MEMORY;
2454 if (new_dos_attributes & FILE_FLAG_POSIX_SEMANTICS) {
2455 posix_open = True;
2456 unx_mode = (mode_t)(new_dos_attributes & ~FILE_FLAG_POSIX_SEMANTICS);
2457 new_dos_attributes = 0;
2458 } else {
2459 /* Windows allows a new file to be created and
2460 silently removes a FILE_ATTRIBUTE_DIRECTORY
2461 sent by the client. Do the same. */
2463 new_dos_attributes &= ~FILE_ATTRIBUTE_DIRECTORY;
2465 /* We add FILE_ATTRIBUTE_ARCHIVE to this as this mode is only used if the file is
2466 * created new. */
2467 unx_mode = unix_mode(conn, new_dos_attributes | FILE_ATTRIBUTE_ARCHIVE,
2468 smb_fname, parent_dir);
2471 DEBUG(10, ("open_file_ntcreate: fname=%s, dos_attrs=0x%x "
2472 "access_mask=0x%x share_access=0x%x "
2473 "create_disposition = 0x%x create_options=0x%x "
2474 "unix mode=0%o oplock_request=%d private_flags = 0x%x\n",
2475 smb_fname_str_dbg(smb_fname), new_dos_attributes,
2476 access_mask, share_access, create_disposition,
2477 create_options, (unsigned int)unx_mode, oplock_request,
2478 (unsigned int)private_flags));
2480 if (req == NULL) {
2481 /* Ensure req == NULL means INTERNAL_OPEN_ONLY */
2482 SMB_ASSERT(((oplock_request & INTERNAL_OPEN_ONLY) != 0));
2483 } else {
2484 /* And req != NULL means no INTERNAL_OPEN_ONLY */
2485 SMB_ASSERT(((oplock_request & INTERNAL_OPEN_ONLY) == 0));
2489 * Only non-internal opens can be deferred at all
2492 if (req) {
2493 struct deferred_open_record *open_rec;
2494 if (get_deferred_open_message_state(req,
2495 &request_time,
2496 &open_rec)) {
2497 /* Remember the absolute time of the original
2498 request with this mid. We'll use it later to
2499 see if this has timed out. */
2501 /* If it was an async create retry, the file
2502 didn't exist. */
2504 if (is_deferred_open_async(open_rec)) {
2505 SET_STAT_INVALID(smb_fname->st);
2506 file_existed = false;
2509 /* Ensure we don't reprocess this message. */
2510 remove_deferred_open_message_smb(req->xconn, req->mid);
2512 first_open_attempt = false;
2516 if (!posix_open) {
2517 new_dos_attributes &= SAMBA_ATTRIBUTES_MASK;
2518 if (file_existed) {
2519 existing_dos_attributes = dos_mode(conn, smb_fname);
2523 /* ignore any oplock requests if oplocks are disabled */
2524 if (!lp_oplocks(SNUM(conn)) ||
2525 IS_VETO_OPLOCK_PATH(conn, smb_fname->base_name)) {
2526 /* Mask off everything except the private Samba bits. */
2527 oplock_request &= SAMBA_PRIVATE_OPLOCK_MASK;
2530 /* this is for OS/2 long file names - say we don't support them */
2531 if (!lp_posix_pathnames() && strstr(smb_fname->base_name,".+,;=[].")) {
2532 /* OS/2 Workplace shell fix may be main code stream in a later
2533 * release. */
2534 DEBUG(5,("open_file_ntcreate: OS/2 long filenames are not "
2535 "supported.\n"));
2536 if (use_nt_status()) {
2537 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
2539 return NT_STATUS_DOS(ERRDOS, ERRcannotopen);
2542 switch( create_disposition ) {
2543 case FILE_OPEN:
2544 /* If file exists open. If file doesn't exist error. */
2545 if (!file_existed) {
2546 DEBUG(5,("open_file_ntcreate: FILE_OPEN "
2547 "requested for file %s and file "
2548 "doesn't exist.\n",
2549 smb_fname_str_dbg(smb_fname)));
2550 errno = ENOENT;
2551 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
2553 break;
2555 case FILE_OVERWRITE:
2556 /* If file exists overwrite. If file doesn't exist
2557 * error. */
2558 if (!file_existed) {
2559 DEBUG(5,("open_file_ntcreate: FILE_OVERWRITE "
2560 "requested for file %s and file "
2561 "doesn't exist.\n",
2562 smb_fname_str_dbg(smb_fname) ));
2563 errno = ENOENT;
2564 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
2566 break;
2568 case FILE_CREATE:
2569 /* If file exists error. If file doesn't exist
2570 * create. */
2571 if (file_existed) {
2572 DEBUG(5,("open_file_ntcreate: FILE_CREATE "
2573 "requested for file %s and file "
2574 "already exists.\n",
2575 smb_fname_str_dbg(smb_fname)));
2576 if (S_ISDIR(smb_fname->st.st_ex_mode)) {
2577 errno = EISDIR;
2578 } else {
2579 errno = EEXIST;
2581 return map_nt_error_from_unix(errno);
2583 break;
2585 case FILE_SUPERSEDE:
2586 case FILE_OVERWRITE_IF:
2587 case FILE_OPEN_IF:
2588 break;
2589 default:
2590 return NT_STATUS_INVALID_PARAMETER;
2593 flags2 = disposition_to_open_flags(create_disposition);
2595 /* We only care about matching attributes on file exists and
2596 * overwrite. */
2598 if (!posix_open && file_existed &&
2599 ((create_disposition == FILE_OVERWRITE) ||
2600 (create_disposition == FILE_OVERWRITE_IF))) {
2601 if (!open_match_attributes(conn, existing_dos_attributes,
2602 new_dos_attributes,
2603 smb_fname->st.st_ex_mode,
2604 unx_mode, &new_unx_mode)) {
2605 DEBUG(5,("open_file_ntcreate: attributes missmatch "
2606 "for file %s (%x %x) (0%o, 0%o)\n",
2607 smb_fname_str_dbg(smb_fname),
2608 existing_dos_attributes,
2609 new_dos_attributes,
2610 (unsigned int)smb_fname->st.st_ex_mode,
2611 (unsigned int)unx_mode ));
2612 errno = EACCES;
2613 return NT_STATUS_ACCESS_DENIED;
2617 status = smbd_calculate_access_mask(conn, smb_fname,
2618 false,
2619 access_mask,
2620 &access_mask);
2621 if (!NT_STATUS_IS_OK(status)) {
2622 DEBUG(10, ("open_file_ntcreate: smbd_calculate_access_mask "
2623 "on file %s returned %s\n",
2624 smb_fname_str_dbg(smb_fname), nt_errstr(status)));
2625 return status;
2628 open_access_mask = access_mask;
2630 if (flags2 & O_TRUNC) {
2631 open_access_mask |= FILE_WRITE_DATA; /* This will cause oplock breaks. */
2634 DEBUG(10, ("open_file_ntcreate: fname=%s, after mapping "
2635 "access_mask=0x%x\n", smb_fname_str_dbg(smb_fname),
2636 access_mask));
2639 * Note that we ignore the append flag as append does not
2640 * mean the same thing under DOS and Unix.
2643 flags = calculate_open_access_flags(access_mask, oplock_request,
2644 private_flags);
2647 * Currently we only look at FILE_WRITE_THROUGH for create options.
2650 #if defined(O_SYNC)
2651 if ((create_options & FILE_WRITE_THROUGH) && lp_strict_sync(SNUM(conn))) {
2652 flags2 |= O_SYNC;
2654 #endif /* O_SYNC */
2656 if (posix_open && (access_mask & FILE_APPEND_DATA)) {
2657 flags2 |= O_APPEND;
2660 if (!posix_open && !CAN_WRITE(conn)) {
2662 * We should really return a permission denied error if either
2663 * O_CREAT or O_TRUNC are set, but for compatibility with
2664 * older versions of Samba we just AND them out.
2666 flags2 &= ~(O_CREAT|O_TRUNC);
2669 if (first_open_attempt && lp_kernel_oplocks(SNUM(conn))) {
2671 * With kernel oplocks the open breaking an oplock
2672 * blocks until the oplock holder has given up the
2673 * oplock or closed the file. We prevent this by first
2674 * trying to open the file with O_NONBLOCK (see "man
2675 * fcntl" on Linux). For the second try, triggered by
2676 * an oplock break response, we do not need this
2677 * anymore.
2679 * This is true under the assumption that only Samba
2680 * requests kernel oplocks. Once someone else like
2681 * NFSv4 starts to use that API, we will have to
2682 * modify this by communicating with the NFSv4 server.
2684 flags2 |= O_NONBLOCK;
2688 * Ensure we can't write on a read-only share or file.
2691 if (flags != O_RDONLY && file_existed &&
2692 (!CAN_WRITE(conn) || IS_DOS_READONLY(existing_dos_attributes))) {
2693 DEBUG(5,("open_file_ntcreate: write access requested for "
2694 "file %s on read only %s\n",
2695 smb_fname_str_dbg(smb_fname),
2696 !CAN_WRITE(conn) ? "share" : "file" ));
2697 errno = EACCES;
2698 return NT_STATUS_ACCESS_DENIED;
2701 fsp->file_id = vfs_file_id_from_sbuf(conn, &smb_fname->st);
2702 fsp->share_access = share_access;
2703 fsp->fh->private_options = private_flags;
2704 fsp->access_mask = open_access_mask; /* We change this to the
2705 * requested access_mask after
2706 * the open is done. */
2707 fsp->posix_open = posix_open;
2709 if (timeval_is_zero(&request_time)) {
2710 request_time = fsp->open_time;
2714 * Ensure we pay attention to default ACLs on directories if required.
2717 if ((flags2 & O_CREAT) && lp_inherit_acls(SNUM(conn)) &&
2718 (def_acl = directory_has_default_acl(conn, parent_dir))) {
2719 unx_mode = (0777 & lp_create_mask(SNUM(conn)));
2722 DEBUG(4,("calling open_file with flags=0x%X flags2=0x%X mode=0%o, "
2723 "access_mask = 0x%x, open_access_mask = 0x%x\n",
2724 (unsigned int)flags, (unsigned int)flags2,
2725 (unsigned int)unx_mode, (unsigned int)access_mask,
2726 (unsigned int)open_access_mask));
2728 fsp_open = open_file(fsp, conn, req, parent_dir,
2729 flags|flags2, unx_mode, access_mask,
2730 open_access_mask, &new_file_created);
2732 if (NT_STATUS_EQUAL(fsp_open, NT_STATUS_NETWORK_BUSY)) {
2733 struct deferred_open_record state;
2736 * EWOULDBLOCK/EAGAIN maps to NETWORK_BUSY.
2738 if (file_existed && S_ISFIFO(fsp->fsp_name->st.st_ex_mode)) {
2739 DEBUG(10, ("FIFO busy\n"));
2740 return NT_STATUS_NETWORK_BUSY;
2742 if (req == NULL) {
2743 DEBUG(10, ("Internal open busy\n"));
2744 return NT_STATUS_NETWORK_BUSY;
2748 * From here on we assume this is an oplock break triggered
2751 lck = get_existing_share_mode_lock(talloc_tos(), fsp->file_id);
2752 if (lck == NULL) {
2753 state.delayed_for_oplocks = false;
2754 state.async_open = false;
2755 state.id = fsp->file_id;
2756 defer_open(NULL, request_time, timeval_set(0, 0),
2757 req, &state);
2758 DEBUG(10, ("No share mode lock found after "
2759 "EWOULDBLOCK, retrying sync\n"));
2760 return NT_STATUS_SHARING_VIOLATION;
2763 if (!validate_oplock_types(lck)) {
2764 smb_panic("validate_oplock_types failed");
2767 if (delay_for_oplock(fsp, 0, lease, lck, false,
2768 create_disposition, first_open_attempt)) {
2769 schedule_defer_open(lck, fsp->file_id, request_time,
2770 req);
2771 TALLOC_FREE(lck);
2772 DEBUG(10, ("Sent oplock break request to kernel "
2773 "oplock holder\n"));
2774 return NT_STATUS_SHARING_VIOLATION;
2778 * No oplock from Samba around. Immediately retry with
2779 * a blocking open.
2781 state.delayed_for_oplocks = false;
2782 state.async_open = false;
2783 state.id = fsp->file_id;
2784 defer_open(lck, request_time, timeval_set(0, 0), req, &state);
2785 TALLOC_FREE(lck);
2786 DEBUG(10, ("No Samba oplock around after EWOULDBLOCK. "
2787 "Retrying sync\n"));
2788 return NT_STATUS_SHARING_VIOLATION;
2791 if (!NT_STATUS_IS_OK(fsp_open)) {
2792 if (NT_STATUS_EQUAL(fsp_open, NT_STATUS_RETRY)) {
2793 schedule_async_open(request_time, req);
2795 return fsp_open;
2798 if (new_file_created) {
2800 * As we atomically create using O_CREAT|O_EXCL,
2801 * then if new_file_created is true, then
2802 * file_existed *MUST* have been false (even
2803 * if the file was previously detected as being
2804 * there).
2806 file_existed = false;
2809 if (file_existed && !check_same_dev_ino(&saved_stat, &smb_fname->st)) {
2811 * The file did exist, but some other (local or NFS)
2812 * process either renamed/unlinked and re-created the
2813 * file with different dev/ino after we walked the path,
2814 * but before we did the open. We could retry the
2815 * open but it's a rare enough case it's easier to
2816 * just fail the open to prevent creating any problems
2817 * in the open file db having the wrong dev/ino key.
2819 fd_close(fsp);
2820 DEBUG(1,("open_file_ntcreate: file %s - dev/ino mismatch. "
2821 "Old (dev=0x%llu, ino =0x%llu). "
2822 "New (dev=0x%llu, ino=0x%llu). Failing open "
2823 " with NT_STATUS_ACCESS_DENIED.\n",
2824 smb_fname_str_dbg(smb_fname),
2825 (unsigned long long)saved_stat.st_ex_dev,
2826 (unsigned long long)saved_stat.st_ex_ino,
2827 (unsigned long long)smb_fname->st.st_ex_dev,
2828 (unsigned long long)smb_fname->st.st_ex_ino));
2829 return NT_STATUS_ACCESS_DENIED;
2832 old_write_time = smb_fname->st.st_ex_mtime;
2835 * Deal with the race condition where two smbd's detect the
2836 * file doesn't exist and do the create at the same time. One
2837 * of them will win and set a share mode, the other (ie. this
2838 * one) should check if the requested share mode for this
2839 * create is allowed.
2843 * Now the file exists and fsp is successfully opened,
2844 * fsp->dev and fsp->inode are valid and should replace the
2845 * dev=0,inode=0 from a non existent file. Spotted by
2846 * Nadav Danieli <nadavd@exanet.com>. JRA.
2849 id = fsp->file_id;
2851 lck = get_share_mode_lock(talloc_tos(), id,
2852 conn->connectpath,
2853 smb_fname, &old_write_time);
2855 if (lck == NULL) {
2856 DEBUG(0, ("open_file_ntcreate: Could not get share "
2857 "mode lock for %s\n",
2858 smb_fname_str_dbg(smb_fname)));
2859 fd_close(fsp);
2860 return NT_STATUS_SHARING_VIOLATION;
2863 /* Get the types we need to examine. */
2864 if (!validate_oplock_types(lck)) {
2865 smb_panic("validate_oplock_types failed");
2868 if (has_delete_on_close(lck, fsp->name_hash)) {
2869 TALLOC_FREE(lck);
2870 fd_close(fsp);
2871 return NT_STATUS_DELETE_PENDING;
2874 status = open_mode_check(conn, lck,
2875 access_mask, share_access);
2877 if (NT_STATUS_EQUAL(status, NT_STATUS_SHARING_VIOLATION) ||
2878 (lck->data->num_share_modes > 0)) {
2880 * This comes from ancient times out of open_mode_check. I
2881 * have no clue whether this is still necessary. I can't think
2882 * of a case where this would actually matter further down in
2883 * this function. I leave it here for further investigation
2884 * :-)
2886 file_existed = true;
2889 if ((req != NULL) &&
2890 delay_for_oplock(
2891 fsp, oplock_request, lease, lck,
2892 NT_STATUS_EQUAL(status, NT_STATUS_SHARING_VIOLATION),
2893 create_disposition, first_open_attempt)) {
2894 schedule_defer_open(lck, fsp->file_id, request_time, req);
2895 TALLOC_FREE(lck);
2896 fd_close(fsp);
2897 return NT_STATUS_SHARING_VIOLATION;
2900 if (!NT_STATUS_IS_OK(status)) {
2901 uint32 can_access_mask;
2902 bool can_access = True;
2904 SMB_ASSERT(NT_STATUS_EQUAL(status, NT_STATUS_SHARING_VIOLATION));
2906 /* Check if this can be done with the deny_dos and fcb
2907 * calls. */
2908 if (private_flags &
2909 (NTCREATEX_OPTIONS_PRIVATE_DENY_DOS|
2910 NTCREATEX_OPTIONS_PRIVATE_DENY_FCB)) {
2911 if (req == NULL) {
2912 DEBUG(0, ("DOS open without an SMB "
2913 "request!\n"));
2914 TALLOC_FREE(lck);
2915 fd_close(fsp);
2916 return NT_STATUS_INTERNAL_ERROR;
2919 /* Use the client requested access mask here,
2920 * not the one we open with. */
2921 status = fcb_or_dos_open(req,
2922 conn,
2923 fsp,
2924 smb_fname,
2926 req->smbpid,
2927 req->vuid,
2928 access_mask,
2929 share_access,
2930 create_options);
2932 if (NT_STATUS_IS_OK(status)) {
2933 TALLOC_FREE(lck);
2934 if (pinfo) {
2935 *pinfo = FILE_WAS_OPENED;
2937 return NT_STATUS_OK;
2942 * This next line is a subtlety we need for
2943 * MS-Access. If a file open will fail due to share
2944 * permissions and also for security (access) reasons,
2945 * we need to return the access failed error, not the
2946 * share error. We can't open the file due to kernel
2947 * oplock deadlock (it's possible we failed above on
2948 * the open_mode_check()) so use a userspace check.
2951 if (flags & O_RDWR) {
2952 can_access_mask = FILE_READ_DATA|FILE_WRITE_DATA;
2953 } else if (flags & O_WRONLY) {
2954 can_access_mask = FILE_WRITE_DATA;
2955 } else {
2956 can_access_mask = FILE_READ_DATA;
2959 if (((can_access_mask & FILE_WRITE_DATA) &&
2960 !CAN_WRITE(conn)) ||
2961 !NT_STATUS_IS_OK(smbd_check_access_rights(conn,
2962 smb_fname,
2963 false,
2964 can_access_mask))) {
2965 can_access = False;
2969 * If we're returning a share violation, ensure we
2970 * cope with the braindead 1 second delay (SMB1 only).
2973 if (!(oplock_request & INTERNAL_OPEN_ONLY) &&
2974 !conn->sconn->using_smb2 &&
2975 lp_defer_sharing_violations()) {
2976 struct timeval timeout;
2977 struct deferred_open_record state;
2978 int timeout_usecs;
2980 /* this is a hack to speed up torture tests
2981 in 'make test' */
2982 timeout_usecs = lp_parm_int(SNUM(conn),
2983 "smbd","sharedelay",
2984 SHARING_VIOLATION_USEC_WAIT);
2986 /* This is a relative time, added to the absolute
2987 request_time value to get the absolute timeout time.
2988 Note that if this is the second or greater time we enter
2989 this codepath for this particular request mid then
2990 request_time is left as the absolute time of the *first*
2991 time this request mid was processed. This is what allows
2992 the request to eventually time out. */
2994 timeout = timeval_set(0, timeout_usecs);
2996 /* Nothing actually uses state.delayed_for_oplocks
2997 but it's handy to differentiate in debug messages
2998 between a 30 second delay due to oplock break, and
2999 a 1 second delay for share mode conflicts. */
3001 state.delayed_for_oplocks = False;
3002 state.async_open = false;
3003 state.id = id;
3005 if ((req != NULL)
3006 && !request_timed_out(request_time,
3007 timeout)) {
3008 defer_open(lck, request_time, timeout,
3009 req, &state);
3013 TALLOC_FREE(lck);
3014 fd_close(fsp);
3015 if (can_access) {
3017 * We have detected a sharing violation here
3018 * so return the correct error code
3020 status = NT_STATUS_SHARING_VIOLATION;
3021 } else {
3022 status = NT_STATUS_ACCESS_DENIED;
3024 return status;
3027 /* Should we atomically (to the client at least) truncate ? */
3028 if ((!new_file_created) &&
3029 (flags2 & O_TRUNC) &&
3030 (!S_ISFIFO(fsp->fsp_name->st.st_ex_mode))) {
3031 int ret;
3033 ret = vfs_set_filelen(fsp, 0);
3034 if (ret != 0) {
3035 status = map_nt_error_from_unix(errno);
3036 TALLOC_FREE(lck);
3037 fd_close(fsp);
3038 return status;
3043 * We have the share entry *locked*.....
3046 /* Delete streams if create_disposition requires it */
3047 if (!new_file_created && clear_ads(create_disposition) &&
3048 !is_ntfs_stream_smb_fname(smb_fname)) {
3049 status = delete_all_streams(conn, smb_fname->base_name);
3050 if (!NT_STATUS_IS_OK(status)) {
3051 TALLOC_FREE(lck);
3052 fd_close(fsp);
3053 return status;
3057 /* note that we ignore failure for the following. It is
3058 basically a hack for NFS, and NFS will never set one of
3059 these only read them. Nobody but Samba can ever set a deny
3060 mode and we have already checked our more authoritative
3061 locking database for permission to set this deny mode. If
3062 the kernel refuses the operations then the kernel is wrong.
3063 note that GPFS supports it as well - jmcd */
3065 if (fsp->fh->fd != -1 && lp_kernel_share_modes(SNUM(conn))) {
3066 int ret_flock;
3067 ret_flock = SMB_VFS_KERNEL_FLOCK(fsp, share_access, access_mask);
3068 if(ret_flock == -1 ){
3070 TALLOC_FREE(lck);
3071 fd_close(fsp);
3073 return NT_STATUS_SHARING_VIOLATION;
3078 * At this point onwards, we can guarantee that the share entry
3079 * is locked, whether we created the file or not, and that the
3080 * deny mode is compatible with all current opens.
3084 * According to Samba4, SEC_FILE_READ_ATTRIBUTE is always granted,
3085 * but we don't have to store this - just ignore it on access check.
3087 if (conn->sconn->using_smb2) {
3089 * SMB2 doesn't return it (according to Microsoft tests).
3090 * Test Case: TestSuite_ScenarioNo009GrantedAccessTestS0
3091 * File created with access = 0x7 (Read, Write, Delete)
3092 * Query Info on file returns 0x87 (Read, Write, Delete, Read Attributes)
3094 fsp->access_mask = access_mask;
3095 } else {
3096 /* But SMB1 does. */
3097 fsp->access_mask = access_mask | FILE_READ_ATTRIBUTES;
3100 if (file_existed) {
3102 * stat opens on existing files don't get oplocks.
3103 * They can get leases.
3105 * Note that we check for stat open on the *open_access_mask*,
3106 * i.e. the access mask we actually used to do the open,
3107 * not the one the client asked for (which is in
3108 * fsp->access_mask). This is due to the fact that
3109 * FILE_OVERWRITE and FILE_OVERWRITE_IF add in O_TRUNC,
3110 * which adds FILE_WRITE_DATA to open_access_mask.
3112 if (is_stat_open(open_access_mask) && lease == NULL) {
3113 oplock_request = NO_OPLOCK;
3117 if (new_file_created) {
3118 info = FILE_WAS_CREATED;
3119 } else {
3120 if (flags2 & O_TRUNC) {
3121 info = FILE_WAS_OVERWRITTEN;
3122 } else {
3123 info = FILE_WAS_OPENED;
3127 if (pinfo) {
3128 *pinfo = info;
3132 * Setup the oplock info in both the shared memory and
3133 * file structs.
3135 status = grant_fsp_oplock_type(req, fsp, lck, oplock_request, lease);
3136 if (!NT_STATUS_IS_OK(status)) {
3137 TALLOC_FREE(lck);
3138 fd_close(fsp);
3139 return status;
3142 /* Handle strange delete on close create semantics. */
3143 if (create_options & FILE_DELETE_ON_CLOSE) {
3145 status = can_set_delete_on_close(fsp, new_dos_attributes);
3147 if (!NT_STATUS_IS_OK(status)) {
3148 /* Remember to delete the mode we just added. */
3149 del_share_mode(lck, fsp);
3150 TALLOC_FREE(lck);
3151 fd_close(fsp);
3152 return status;
3154 /* Note that here we set the *inital* delete on close flag,
3155 not the regular one. The magic gets handled in close. */
3156 fsp->initial_delete_on_close = True;
3159 if (info != FILE_WAS_OPENED) {
3160 /* Files should be initially set as archive */
3161 if (lp_map_archive(SNUM(conn)) ||
3162 lp_store_dos_attributes(SNUM(conn))) {
3163 if (!posix_open) {
3164 if (file_set_dosmode(conn, smb_fname,
3165 new_dos_attributes | FILE_ATTRIBUTE_ARCHIVE,
3166 parent_dir, true) == 0) {
3167 unx_mode = smb_fname->st.st_ex_mode;
3173 /* Determine sparse flag. */
3174 if (posix_open) {
3175 /* POSIX opens are sparse by default. */
3176 fsp->is_sparse = true;
3177 } else {
3178 fsp->is_sparse = (file_existed &&
3179 (existing_dos_attributes & FILE_ATTRIBUTE_SPARSE));
3183 * Take care of inherited ACLs on created files - if default ACL not
3184 * selected.
3187 if (!posix_open && new_file_created && !def_acl) {
3189 int saved_errno = errno; /* We might get ENOSYS in the next
3190 * call.. */
3192 if (SMB_VFS_FCHMOD_ACL(fsp, unx_mode) == -1 &&
3193 errno == ENOSYS) {
3194 errno = saved_errno; /* Ignore ENOSYS */
3197 } else if (new_unx_mode) {
3199 int ret = -1;
3201 /* Attributes need changing. File already existed. */
3204 int saved_errno = errno; /* We might get ENOSYS in the
3205 * next call.. */
3206 ret = SMB_VFS_FCHMOD_ACL(fsp, new_unx_mode);
3208 if (ret == -1 && errno == ENOSYS) {
3209 errno = saved_errno; /* Ignore ENOSYS */
3210 } else {
3211 DEBUG(5, ("open_file_ntcreate: reset "
3212 "attributes of file %s to 0%o\n",
3213 smb_fname_str_dbg(smb_fname),
3214 (unsigned int)new_unx_mode));
3215 ret = 0; /* Don't do the fchmod below. */
3219 if ((ret == -1) &&
3220 (SMB_VFS_FCHMOD(fsp, new_unx_mode) == -1))
3221 DEBUG(5, ("open_file_ntcreate: failed to reset "
3222 "attributes of file %s to 0%o\n",
3223 smb_fname_str_dbg(smb_fname),
3224 (unsigned int)new_unx_mode));
3229 * Deal with other opens having a modified write time.
3231 struct timespec write_time = get_share_mode_write_time(lck);
3233 if (!null_timespec(write_time)) {
3234 update_stat_ex_mtime(&fsp->fsp_name->st, write_time);
3238 TALLOC_FREE(lck);
3240 return NT_STATUS_OK;
3243 static NTSTATUS mkdir_internal(connection_struct *conn,
3244 struct smb_filename *smb_dname,
3245 uint32 file_attributes)
3247 mode_t mode;
3248 char *parent_dir = NULL;
3249 NTSTATUS status;
3250 bool posix_open = false;
3251 bool need_re_stat = false;
3252 uint32_t access_mask = SEC_DIR_ADD_SUBDIR;
3254 if (!CAN_WRITE(conn) || (access_mask & ~(conn->share_access))) {
3255 DEBUG(5,("mkdir_internal: failing share access "
3256 "%s\n", lp_servicename(talloc_tos(), SNUM(conn))));
3257 return NT_STATUS_ACCESS_DENIED;
3260 if (!parent_dirname(talloc_tos(), smb_dname->base_name, &parent_dir,
3261 NULL)) {
3262 return NT_STATUS_NO_MEMORY;
3265 if (file_attributes & FILE_FLAG_POSIX_SEMANTICS) {
3266 posix_open = true;
3267 mode = (mode_t)(file_attributes & ~FILE_FLAG_POSIX_SEMANTICS);
3268 } else {
3269 mode = unix_mode(conn, FILE_ATTRIBUTE_DIRECTORY, smb_dname, parent_dir);
3272 status = check_parent_access(conn,
3273 smb_dname,
3274 access_mask);
3275 if(!NT_STATUS_IS_OK(status)) {
3276 DEBUG(5,("mkdir_internal: check_parent_access "
3277 "on directory %s for path %s returned %s\n",
3278 parent_dir,
3279 smb_dname->base_name,
3280 nt_errstr(status) ));
3281 return status;
3284 if (SMB_VFS_MKDIR(conn, smb_dname->base_name, mode) != 0) {
3285 return map_nt_error_from_unix(errno);
3288 /* Ensure we're checking for a symlink here.... */
3289 /* We don't want to get caught by a symlink racer. */
3291 if (SMB_VFS_LSTAT(conn, smb_dname) == -1) {
3292 DEBUG(2, ("Could not stat directory '%s' just created: %s\n",
3293 smb_fname_str_dbg(smb_dname), strerror(errno)));
3294 return map_nt_error_from_unix(errno);
3297 if (!S_ISDIR(smb_dname->st.st_ex_mode)) {
3298 DEBUG(0, ("Directory '%s' just created is not a directory !\n",
3299 smb_fname_str_dbg(smb_dname)));
3300 return NT_STATUS_NOT_A_DIRECTORY;
3303 if (lp_store_dos_attributes(SNUM(conn))) {
3304 if (!posix_open) {
3305 file_set_dosmode(conn, smb_dname,
3306 file_attributes | FILE_ATTRIBUTE_DIRECTORY,
3307 parent_dir, true);
3311 if (lp_inherit_permissions(SNUM(conn))) {
3312 inherit_access_posix_acl(conn, parent_dir,
3313 smb_dname->base_name, mode);
3314 need_re_stat = true;
3317 if (!posix_open) {
3319 * Check if high bits should have been set,
3320 * then (if bits are missing): add them.
3321 * Consider bits automagically set by UNIX, i.e. SGID bit from parent
3322 * dir.
3324 if ((mode & ~(S_IRWXU|S_IRWXG|S_IRWXO)) &&
3325 (mode & ~smb_dname->st.st_ex_mode)) {
3326 SMB_VFS_CHMOD(conn, smb_dname->base_name,
3327 (smb_dname->st.st_ex_mode |
3328 (mode & ~smb_dname->st.st_ex_mode)));
3329 need_re_stat = true;
3333 /* Change the owner if required. */
3334 if (lp_inherit_owner(SNUM(conn))) {
3335 change_dir_owner_to_parent(conn, parent_dir,
3336 smb_dname->base_name,
3337 &smb_dname->st);
3338 need_re_stat = true;
3341 if (need_re_stat) {
3342 if (SMB_VFS_LSTAT(conn, smb_dname) == -1) {
3343 DEBUG(2, ("Could not stat directory '%s' just created: %s\n",
3344 smb_fname_str_dbg(smb_dname), strerror(errno)));
3345 return map_nt_error_from_unix(errno);
3349 notify_fname(conn, NOTIFY_ACTION_ADDED, FILE_NOTIFY_CHANGE_DIR_NAME,
3350 smb_dname->base_name);
3352 return NT_STATUS_OK;
3355 /****************************************************************************
3356 Open a directory from an NT SMB call.
3357 ****************************************************************************/
3359 static NTSTATUS open_directory(connection_struct *conn,
3360 struct smb_request *req,
3361 struct smb_filename *smb_dname,
3362 uint32 access_mask,
3363 uint32 share_access,
3364 uint32 create_disposition,
3365 uint32 create_options,
3366 uint32 file_attributes,
3367 int *pinfo,
3368 files_struct **result)
3370 files_struct *fsp = NULL;
3371 bool dir_existed = VALID_STAT(smb_dname->st) ? True : False;
3372 struct share_mode_lock *lck = NULL;
3373 NTSTATUS status;
3374 struct timespec mtimespec;
3375 int info = 0;
3376 bool ok;
3378 if (is_ntfs_stream_smb_fname(smb_dname)) {
3379 DEBUG(2, ("open_directory: %s is a stream name!\n",
3380 smb_fname_str_dbg(smb_dname)));
3381 return NT_STATUS_NOT_A_DIRECTORY;
3384 if (!(file_attributes & FILE_FLAG_POSIX_SEMANTICS)) {
3385 /* Ensure we have a directory attribute. */
3386 file_attributes |= FILE_ATTRIBUTE_DIRECTORY;
3389 DEBUG(5,("open_directory: opening directory %s, access_mask = 0x%x, "
3390 "share_access = 0x%x create_options = 0x%x, "
3391 "create_disposition = 0x%x, file_attributes = 0x%x\n",
3392 smb_fname_str_dbg(smb_dname),
3393 (unsigned int)access_mask,
3394 (unsigned int)share_access,
3395 (unsigned int)create_options,
3396 (unsigned int)create_disposition,
3397 (unsigned int)file_attributes));
3399 status = smbd_calculate_access_mask(conn, smb_dname, false,
3400 access_mask, &access_mask);
3401 if (!NT_STATUS_IS_OK(status)) {
3402 DEBUG(10, ("open_directory: smbd_calculate_access_mask "
3403 "on file %s returned %s\n",
3404 smb_fname_str_dbg(smb_dname),
3405 nt_errstr(status)));
3406 return status;
3409 if ((access_mask & SEC_FLAG_SYSTEM_SECURITY) &&
3410 !security_token_has_privilege(get_current_nttok(conn),
3411 SEC_PRIV_SECURITY)) {
3412 DEBUG(10, ("open_directory: open on %s "
3413 "failed - SEC_FLAG_SYSTEM_SECURITY denied.\n",
3414 smb_fname_str_dbg(smb_dname)));
3415 return NT_STATUS_PRIVILEGE_NOT_HELD;
3418 switch( create_disposition ) {
3419 case FILE_OPEN:
3421 if (!dir_existed) {
3422 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3425 info = FILE_WAS_OPENED;
3426 break;
3428 case FILE_CREATE:
3430 /* If directory exists error. If directory doesn't
3431 * exist create. */
3433 if (dir_existed) {
3434 status = NT_STATUS_OBJECT_NAME_COLLISION;
3435 DEBUG(2, ("open_directory: unable to create "
3436 "%s. Error was %s\n",
3437 smb_fname_str_dbg(smb_dname),
3438 nt_errstr(status)));
3439 return status;
3442 status = mkdir_internal(conn, smb_dname,
3443 file_attributes);
3445 if (!NT_STATUS_IS_OK(status)) {
3446 DEBUG(2, ("open_directory: unable to create "
3447 "%s. Error was %s\n",
3448 smb_fname_str_dbg(smb_dname),
3449 nt_errstr(status)));
3450 return status;
3453 info = FILE_WAS_CREATED;
3454 break;
3456 case FILE_OPEN_IF:
3458 * If directory exists open. If directory doesn't
3459 * exist create.
3462 if (dir_existed) {
3463 status = NT_STATUS_OK;
3464 info = FILE_WAS_OPENED;
3465 } else {
3466 status = mkdir_internal(conn, smb_dname,
3467 file_attributes);
3469 if (NT_STATUS_IS_OK(status)) {
3470 info = FILE_WAS_CREATED;
3471 } else {
3472 /* Cope with create race. */
3473 if (!NT_STATUS_EQUAL(status,
3474 NT_STATUS_OBJECT_NAME_COLLISION)) {
3475 DEBUG(2, ("open_directory: unable to create "
3476 "%s. Error was %s\n",
3477 smb_fname_str_dbg(smb_dname),
3478 nt_errstr(status)));
3479 return status;
3481 info = FILE_WAS_OPENED;
3485 break;
3487 case FILE_SUPERSEDE:
3488 case FILE_OVERWRITE:
3489 case FILE_OVERWRITE_IF:
3490 default:
3491 DEBUG(5,("open_directory: invalid create_disposition "
3492 "0x%x for directory %s\n",
3493 (unsigned int)create_disposition,
3494 smb_fname_str_dbg(smb_dname)));
3495 return NT_STATUS_INVALID_PARAMETER;
3498 if(!S_ISDIR(smb_dname->st.st_ex_mode)) {
3499 DEBUG(5,("open_directory: %s is not a directory !\n",
3500 smb_fname_str_dbg(smb_dname)));
3501 return NT_STATUS_NOT_A_DIRECTORY;
3504 if (info == FILE_WAS_OPENED) {
3505 status = smbd_check_access_rights(conn,
3506 smb_dname,
3507 false,
3508 access_mask);
3509 if (!NT_STATUS_IS_OK(status)) {
3510 DEBUG(10, ("open_directory: smbd_check_access_rights on "
3511 "file %s failed with %s\n",
3512 smb_fname_str_dbg(smb_dname),
3513 nt_errstr(status)));
3514 return status;
3518 status = file_new(req, conn, &fsp);
3519 if(!NT_STATUS_IS_OK(status)) {
3520 return status;
3524 * Setup the files_struct for it.
3527 fsp->file_id = vfs_file_id_from_sbuf(conn, &smb_dname->st);
3528 fsp->vuid = req ? req->vuid : UID_FIELD_INVALID;
3529 fsp->file_pid = req ? req->smbpid : 0;
3530 fsp->can_lock = False;
3531 fsp->can_read = False;
3532 fsp->can_write = False;
3534 fsp->share_access = share_access;
3535 fsp->fh->private_options = 0;
3537 * According to Samba4, SEC_FILE_READ_ATTRIBUTE is always granted,
3539 fsp->access_mask = access_mask | FILE_READ_ATTRIBUTES;
3540 fsp->print_file = NULL;
3541 fsp->modified = False;
3542 fsp->oplock_type = NO_OPLOCK;
3543 fsp->sent_oplock_break = NO_BREAK_SENT;
3544 fsp->is_directory = True;
3545 fsp->posix_open = (file_attributes & FILE_FLAG_POSIX_SEMANTICS) ? True : False;
3546 status = fsp_set_smb_fname(fsp, smb_dname);
3547 if (!NT_STATUS_IS_OK(status)) {
3548 file_free(req, fsp);
3549 return status;
3552 /* Don't store old timestamps for directory
3553 handles in the internal database. We don't
3554 update them in there if new objects
3555 are creaded in the directory. Currently
3556 we only update timestamps on file writes.
3557 See bug #9870.
3559 ZERO_STRUCT(mtimespec);
3561 if (access_mask & (FILE_LIST_DIRECTORY|
3562 FILE_ADD_FILE|
3563 FILE_ADD_SUBDIRECTORY|
3564 FILE_TRAVERSE|
3565 DELETE_ACCESS|
3566 FILE_DELETE_CHILD)) {
3567 #ifdef O_DIRECTORY
3568 status = fd_open(conn, fsp, O_RDONLY|O_DIRECTORY, 0);
3569 #else
3570 /* POSIX allows us to open a directory with O_RDONLY. */
3571 status = fd_open(conn, fsp, O_RDONLY, 0);
3572 #endif
3573 if (!NT_STATUS_IS_OK(status)) {
3574 DEBUG(5, ("open_directory: Could not open fd for "
3575 "%s (%s)\n",
3576 smb_fname_str_dbg(smb_dname),
3577 nt_errstr(status)));
3578 file_free(req, fsp);
3579 return status;
3581 } else {
3582 fsp->fh->fd = -1;
3583 DEBUG(10, ("Not opening Directory %s\n",
3584 smb_fname_str_dbg(smb_dname)));
3587 status = vfs_stat_fsp(fsp);
3588 if (!NT_STATUS_IS_OK(status)) {
3589 fd_close(fsp);
3590 file_free(req, fsp);
3591 return status;
3594 /* Ensure there was no race condition. */
3595 if (!check_same_stat(&smb_dname->st, &fsp->fsp_name->st)) {
3596 DEBUG(5,("open_directory: stat struct differs for "
3597 "directory %s.\n",
3598 smb_fname_str_dbg(smb_dname)));
3599 fd_close(fsp);
3600 file_free(req, fsp);
3601 return NT_STATUS_ACCESS_DENIED;
3604 lck = get_share_mode_lock(talloc_tos(), fsp->file_id,
3605 conn->connectpath, smb_dname,
3606 &mtimespec);
3608 if (lck == NULL) {
3609 DEBUG(0, ("open_directory: Could not get share mode lock for "
3610 "%s\n", smb_fname_str_dbg(smb_dname)));
3611 fd_close(fsp);
3612 file_free(req, fsp);
3613 return NT_STATUS_SHARING_VIOLATION;
3616 if (has_delete_on_close(lck, fsp->name_hash)) {
3617 TALLOC_FREE(lck);
3618 fd_close(fsp);
3619 file_free(req, fsp);
3620 return NT_STATUS_DELETE_PENDING;
3623 status = open_mode_check(conn, lck,
3624 access_mask, share_access);
3626 if (!NT_STATUS_IS_OK(status)) {
3627 TALLOC_FREE(lck);
3628 fd_close(fsp);
3629 file_free(req, fsp);
3630 return status;
3633 ok = set_share_mode(lck, fsp, get_current_uid(conn),
3634 req ? req->mid : 0, NO_OPLOCK,
3635 UINT32_MAX);
3636 if (!ok) {
3637 TALLOC_FREE(lck);
3638 fd_close(fsp);
3639 file_free(req, fsp);
3640 return NT_STATUS_NO_MEMORY;
3643 /* For directories the delete on close bit at open time seems
3644 always to be honored on close... See test 19 in Samba4 BASE-DELETE. */
3645 if (create_options & FILE_DELETE_ON_CLOSE) {
3646 status = can_set_delete_on_close(fsp, 0);
3647 if (!NT_STATUS_IS_OK(status) && !NT_STATUS_EQUAL(status, NT_STATUS_DIRECTORY_NOT_EMPTY)) {
3648 del_share_mode(lck, fsp);
3649 TALLOC_FREE(lck);
3650 fd_close(fsp);
3651 file_free(req, fsp);
3652 return status;
3655 if (NT_STATUS_IS_OK(status)) {
3656 /* Note that here we set the *inital* delete on close flag,
3657 not the regular one. The magic gets handled in close. */
3658 fsp->initial_delete_on_close = True;
3664 * Deal with other opens having a modified write time. Is this
3665 * possible for directories?
3667 struct timespec write_time = get_share_mode_write_time(lck);
3669 if (!null_timespec(write_time)) {
3670 update_stat_ex_mtime(&fsp->fsp_name->st, write_time);
3674 TALLOC_FREE(lck);
3676 if (pinfo) {
3677 *pinfo = info;
3680 *result = fsp;
3681 return NT_STATUS_OK;
3684 NTSTATUS create_directory(connection_struct *conn, struct smb_request *req,
3685 struct smb_filename *smb_dname)
3687 NTSTATUS status;
3688 files_struct *fsp;
3690 status = SMB_VFS_CREATE_FILE(
3691 conn, /* conn */
3692 req, /* req */
3693 0, /* root_dir_fid */
3694 smb_dname, /* fname */
3695 FILE_READ_ATTRIBUTES, /* access_mask */
3696 FILE_SHARE_NONE, /* share_access */
3697 FILE_CREATE, /* create_disposition*/
3698 FILE_DIRECTORY_FILE, /* create_options */
3699 FILE_ATTRIBUTE_DIRECTORY, /* file_attributes */
3700 0, /* oplock_request */
3701 NULL, /* lease */
3702 0, /* allocation_size */
3703 0, /* private_flags */
3704 NULL, /* sd */
3705 NULL, /* ea_list */
3706 &fsp, /* result */
3707 NULL, /* pinfo */
3708 NULL, NULL); /* create context */
3710 if (NT_STATUS_IS_OK(status)) {
3711 close_file(req, fsp, NORMAL_CLOSE);
3714 return status;
3717 /****************************************************************************
3718 Receive notification that one of our open files has been renamed by another
3719 smbd process.
3720 ****************************************************************************/
3722 void msg_file_was_renamed(struct messaging_context *msg,
3723 void *private_data,
3724 uint32_t msg_type,
3725 struct server_id server_id,
3726 DATA_BLOB *data)
3728 files_struct *fsp;
3729 char *frm = (char *)data->data;
3730 struct file_id id;
3731 const char *sharepath;
3732 const char *base_name;
3733 const char *stream_name;
3734 struct smb_filename *smb_fname = NULL;
3735 size_t sp_len, bn_len;
3736 NTSTATUS status;
3737 struct smbd_server_connection *sconn =
3738 talloc_get_type_abort(private_data,
3739 struct smbd_server_connection);
3741 if (data->data == NULL
3742 || data->length < MSG_FILE_RENAMED_MIN_SIZE + 2) {
3743 DEBUG(0, ("msg_file_was_renamed: Got invalid msg len %d\n",
3744 (int)data->length));
3745 return;
3748 /* Unpack the message. */
3749 pull_file_id_24(frm, &id);
3750 sharepath = &frm[24];
3751 sp_len = strlen(sharepath);
3752 base_name = sharepath + sp_len + 1;
3753 bn_len = strlen(base_name);
3754 stream_name = sharepath + sp_len + 1 + bn_len + 1;
3756 /* stream_name must always be NULL if there is no stream. */
3757 if (stream_name[0] == '\0') {
3758 stream_name = NULL;
3761 smb_fname = synthetic_smb_fname(talloc_tos(), base_name,
3762 stream_name, NULL);
3763 if (smb_fname == NULL) {
3764 return;
3767 DEBUG(10,("msg_file_was_renamed: Got rename message for sharepath %s, new name %s, "
3768 "file_id %s\n",
3769 sharepath, smb_fname_str_dbg(smb_fname),
3770 file_id_string_tos(&id)));
3772 for(fsp = file_find_di_first(sconn, id); fsp;
3773 fsp = file_find_di_next(fsp)) {
3774 if (memcmp(fsp->conn->connectpath, sharepath, sp_len) == 0) {
3776 DEBUG(10,("msg_file_was_renamed: renaming file %s from %s -> %s\n",
3777 fsp_fnum_dbg(fsp), fsp_str_dbg(fsp),
3778 smb_fname_str_dbg(smb_fname)));
3779 status = fsp_set_smb_fname(fsp, smb_fname);
3780 if (!NT_STATUS_IS_OK(status)) {
3781 goto out;
3783 } else {
3784 /* TODO. JRA. */
3785 /* Now we have the complete path we can work out if this is
3786 actually within this share and adjust newname accordingly. */
3787 DEBUG(10,("msg_file_was_renamed: share mismatch (sharepath %s "
3788 "not sharepath %s) "
3789 "%s from %s -> %s\n",
3790 fsp->conn->connectpath,
3791 sharepath,
3792 fsp_fnum_dbg(fsp),
3793 fsp_str_dbg(fsp),
3794 smb_fname_str_dbg(smb_fname)));
3797 out:
3798 TALLOC_FREE(smb_fname);
3799 return;
3803 * If a main file is opened for delete, all streams need to be checked for
3804 * !FILE_SHARE_DELETE. Do this by opening with DELETE_ACCESS.
3805 * If that works, delete them all by setting the delete on close and close.
3808 NTSTATUS open_streams_for_delete(connection_struct *conn,
3809 const char *fname)
3811 struct stream_struct *stream_info = NULL;
3812 files_struct **streams = NULL;
3813 int i;
3814 unsigned int num_streams = 0;
3815 TALLOC_CTX *frame = talloc_stackframe();
3816 NTSTATUS status;
3818 status = vfs_streaminfo(conn, NULL, fname, talloc_tos(),
3819 &num_streams, &stream_info);
3821 if (NT_STATUS_EQUAL(status, NT_STATUS_NOT_IMPLEMENTED)
3822 || NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
3823 DEBUG(10, ("no streams around\n"));
3824 TALLOC_FREE(frame);
3825 return NT_STATUS_OK;
3828 if (!NT_STATUS_IS_OK(status)) {
3829 DEBUG(10, ("vfs_streaminfo failed: %s\n",
3830 nt_errstr(status)));
3831 goto fail;
3834 DEBUG(10, ("open_streams_for_delete found %d streams\n",
3835 num_streams));
3837 if (num_streams == 0) {
3838 TALLOC_FREE(frame);
3839 return NT_STATUS_OK;
3842 streams = talloc_array(talloc_tos(), files_struct *, num_streams);
3843 if (streams == NULL) {
3844 DEBUG(0, ("talloc failed\n"));
3845 status = NT_STATUS_NO_MEMORY;
3846 goto fail;
3849 for (i=0; i<num_streams; i++) {
3850 struct smb_filename *smb_fname;
3852 if (strequal(stream_info[i].name, "::$DATA")) {
3853 streams[i] = NULL;
3854 continue;
3857 smb_fname = synthetic_smb_fname(
3858 talloc_tos(), fname, stream_info[i].name, NULL);
3859 if (smb_fname == NULL) {
3860 status = NT_STATUS_NO_MEMORY;
3861 goto fail;
3864 if (SMB_VFS_STAT(conn, smb_fname) == -1) {
3865 DEBUG(10, ("Unable to stat stream: %s\n",
3866 smb_fname_str_dbg(smb_fname)));
3869 status = SMB_VFS_CREATE_FILE(
3870 conn, /* conn */
3871 NULL, /* req */
3872 0, /* root_dir_fid */
3873 smb_fname, /* fname */
3874 DELETE_ACCESS, /* access_mask */
3875 (FILE_SHARE_READ | /* share_access */
3876 FILE_SHARE_WRITE | FILE_SHARE_DELETE),
3877 FILE_OPEN, /* create_disposition*/
3878 0, /* create_options */
3879 FILE_ATTRIBUTE_NORMAL, /* file_attributes */
3880 0, /* oplock_request */
3881 NULL, /* lease */
3882 0, /* allocation_size */
3883 NTCREATEX_OPTIONS_PRIVATE_STREAM_DELETE, /* private_flags */
3884 NULL, /* sd */
3885 NULL, /* ea_list */
3886 &streams[i], /* result */
3887 NULL, /* pinfo */
3888 NULL, NULL); /* create context */
3890 if (!NT_STATUS_IS_OK(status)) {
3891 DEBUG(10, ("Could not open stream %s: %s\n",
3892 smb_fname_str_dbg(smb_fname),
3893 nt_errstr(status)));
3895 TALLOC_FREE(smb_fname);
3896 break;
3898 TALLOC_FREE(smb_fname);
3902 * don't touch the variable "status" beyond this point :-)
3905 for (i -= 1 ; i >= 0; i--) {
3906 if (streams[i] == NULL) {
3907 continue;
3910 DEBUG(10, ("Closing stream # %d, %s\n", i,
3911 fsp_str_dbg(streams[i])));
3912 close_file(NULL, streams[i], NORMAL_CLOSE);
3915 fail:
3916 TALLOC_FREE(frame);
3917 return status;
3920 /*********************************************************************
3921 Create a default ACL by inheriting from the parent. If no inheritance
3922 from the parent available, don't set anything. This will leave the actual
3923 permissions the new file or directory already got from the filesystem
3924 as the NT ACL when read.
3925 *********************************************************************/
3927 static NTSTATUS inherit_new_acl(files_struct *fsp)
3929 TALLOC_CTX *frame = talloc_stackframe();
3930 char *parent_name = NULL;
3931 struct security_descriptor *parent_desc = NULL;
3932 NTSTATUS status = NT_STATUS_OK;
3933 struct security_descriptor *psd = NULL;
3934 const struct dom_sid *owner_sid = NULL;
3935 const struct dom_sid *group_sid = NULL;
3936 uint32_t security_info_sent = (SECINFO_OWNER | SECINFO_GROUP | SECINFO_DACL);
3937 struct security_token *token = fsp->conn->session_info->security_token;
3938 bool inherit_owner = lp_inherit_owner(SNUM(fsp->conn));
3939 bool inheritable_components = false;
3940 bool try_builtin_administrators = false;
3941 const struct dom_sid *BA_U_sid = NULL;
3942 const struct dom_sid *BA_G_sid = NULL;
3943 bool try_system = false;
3944 const struct dom_sid *SY_U_sid = NULL;
3945 const struct dom_sid *SY_G_sid = NULL;
3946 size_t size = 0;
3948 if (!parent_dirname(frame, fsp->fsp_name->base_name, &parent_name, NULL)) {
3949 TALLOC_FREE(frame);
3950 return NT_STATUS_NO_MEMORY;
3953 status = SMB_VFS_GET_NT_ACL(fsp->conn,
3954 parent_name,
3955 (SECINFO_OWNER | SECINFO_GROUP | SECINFO_DACL),
3956 frame,
3957 &parent_desc);
3958 if (!NT_STATUS_IS_OK(status)) {
3959 TALLOC_FREE(frame);
3960 return status;
3963 inheritable_components = sd_has_inheritable_components(parent_desc,
3964 fsp->is_directory);
3966 if (!inheritable_components && !inherit_owner) {
3967 TALLOC_FREE(frame);
3968 /* Nothing to inherit and not setting owner. */
3969 return NT_STATUS_OK;
3972 /* Create an inherited descriptor from the parent. */
3974 if (DEBUGLEVEL >= 10) {
3975 DEBUG(10,("inherit_new_acl: parent acl for %s is:\n",
3976 fsp_str_dbg(fsp) ));
3977 NDR_PRINT_DEBUG(security_descriptor, parent_desc);
3980 /* Inherit from parent descriptor if "inherit owner" set. */
3981 if (inherit_owner) {
3982 owner_sid = parent_desc->owner_sid;
3983 group_sid = parent_desc->group_sid;
3986 if (owner_sid == NULL) {
3987 if (security_token_has_builtin_administrators(token)) {
3988 try_builtin_administrators = true;
3989 } else if (security_token_is_system(token)) {
3990 try_builtin_administrators = true;
3991 try_system = true;
3995 if (group_sid == NULL &&
3996 token->num_sids == PRIMARY_GROUP_SID_INDEX)
3998 if (security_token_is_system(token)) {
3999 try_builtin_administrators = true;
4000 try_system = true;
4004 if (try_builtin_administrators) {
4005 struct unixid ids;
4006 bool ok;
4008 ZERO_STRUCT(ids);
4009 ok = sids_to_unixids(&global_sid_Builtin_Administrators, 1, &ids);
4010 if (ok) {
4011 switch (ids.type) {
4012 case ID_TYPE_BOTH:
4013 BA_U_sid = &global_sid_Builtin_Administrators;
4014 BA_G_sid = &global_sid_Builtin_Administrators;
4015 break;
4016 case ID_TYPE_UID:
4017 BA_U_sid = &global_sid_Builtin_Administrators;
4018 break;
4019 case ID_TYPE_GID:
4020 BA_G_sid = &global_sid_Builtin_Administrators;
4021 break;
4022 default:
4023 break;
4028 if (try_system) {
4029 struct unixid ids;
4030 bool ok;
4032 ZERO_STRUCT(ids);
4033 ok = sids_to_unixids(&global_sid_System, 1, &ids);
4034 if (ok) {
4035 switch (ids.type) {
4036 case ID_TYPE_BOTH:
4037 SY_U_sid = &global_sid_System;
4038 SY_G_sid = &global_sid_System;
4039 break;
4040 case ID_TYPE_UID:
4041 SY_U_sid = &global_sid_System;
4042 break;
4043 case ID_TYPE_GID:
4044 SY_G_sid = &global_sid_System;
4045 break;
4046 default:
4047 break;
4052 if (owner_sid == NULL) {
4053 owner_sid = BA_U_sid;
4056 if (owner_sid == NULL) {
4057 owner_sid = SY_U_sid;
4060 if (group_sid == NULL) {
4061 group_sid = SY_G_sid;
4064 if (try_system && group_sid == NULL) {
4065 group_sid = BA_G_sid;
4068 if (owner_sid == NULL) {
4069 owner_sid = &token->sids[PRIMARY_USER_SID_INDEX];
4071 if (group_sid == NULL) {
4072 if (token->num_sids == PRIMARY_GROUP_SID_INDEX) {
4073 group_sid = &token->sids[PRIMARY_USER_SID_INDEX];
4074 } else {
4075 group_sid = &token->sids[PRIMARY_GROUP_SID_INDEX];
4079 status = se_create_child_secdesc(frame,
4080 &psd,
4081 &size,
4082 parent_desc,
4083 owner_sid,
4084 group_sid,
4085 fsp->is_directory);
4086 if (!NT_STATUS_IS_OK(status)) {
4087 TALLOC_FREE(frame);
4088 return status;
4091 /* If inheritable_components == false,
4092 se_create_child_secdesc()
4093 creates a security desriptor with a NULL dacl
4094 entry, but with SEC_DESC_DACL_PRESENT. We need
4095 to remove that flag. */
4097 if (!inheritable_components) {
4098 security_info_sent &= ~SECINFO_DACL;
4099 psd->type &= ~SEC_DESC_DACL_PRESENT;
4102 if (DEBUGLEVEL >= 10) {
4103 DEBUG(10,("inherit_new_acl: child acl for %s is:\n",
4104 fsp_str_dbg(fsp) ));
4105 NDR_PRINT_DEBUG(security_descriptor, psd);
4108 if (inherit_owner) {
4109 /* We need to be root to force this. */
4110 become_root();
4112 status = SMB_VFS_FSET_NT_ACL(fsp,
4113 security_info_sent,
4114 psd);
4115 if (inherit_owner) {
4116 unbecome_root();
4118 TALLOC_FREE(frame);
4119 return status;
4123 * If we already have a lease, it must match the new file id. [MS-SMB2]
4124 * 3.3.5.9.8 speaks about INVALID_PARAMETER if an already used lease key is
4125 * used for a different file name.
4128 struct lease_match_state {
4129 /* Input parameters. */
4130 TALLOC_CTX *mem_ctx;
4131 const char *servicepath;
4132 const struct smb_filename *fname;
4133 bool file_existed;
4134 struct file_id id;
4135 /* Return parameters. */
4136 uint32_t num_file_ids;
4137 struct file_id *ids;
4138 NTSTATUS match_status;
4141 /*************************************************************
4142 File doesn't exist but this lease key+guid is already in use.
4144 This is only allowable in the dynamic share case where the
4145 service path must be different.
4147 There is a small race condition here in the multi-connection
4148 case where a client sends two create calls on different connections,
4149 where the file doesn't exist and one smbd creates the leases_db
4150 entry first, but this will get fixed by the multichannel cleanup
4151 when all identical client_guids get handled by a single smbd.
4152 **************************************************************/
4154 static void lease_match_parser_new_file(
4155 uint32_t num_files,
4156 const struct leases_db_file *files,
4157 struct lease_match_state *state)
4159 uint32_t i;
4161 for (i = 0; i < num_files; i++) {
4162 const struct leases_db_file *f = &files[i];
4163 if (strequal(state->servicepath, f->servicepath)) {
4164 state->match_status = NT_STATUS_INVALID_PARAMETER;
4165 return;
4169 /* Dynamic share case. Break leases on all other files. */
4170 state->match_status = leases_db_copy_file_ids(state->mem_ctx,
4171 num_files,
4172 files,
4173 &state->ids);
4174 if (!NT_STATUS_IS_OK(state->match_status)) {
4175 return;
4178 state->num_file_ids = num_files;
4179 state->match_status = NT_STATUS_OPLOCK_NOT_GRANTED;
4180 return;
4183 static void lease_match_parser(
4184 uint32_t num_files,
4185 const struct leases_db_file *files,
4186 void *private_data)
4188 struct lease_match_state *state =
4189 (struct lease_match_state *)private_data;
4190 uint32_t i;
4192 if (!state->file_existed) {
4194 * Deal with name mismatch or
4195 * possible dynamic share case separately
4196 * to make code clearer.
4198 lease_match_parser_new_file(num_files,
4199 files,
4200 state);
4201 return;
4204 /* File existed. */
4205 state->match_status = NT_STATUS_OK;
4207 for (i = 0; i < num_files; i++) {
4208 const struct leases_db_file *f = &files[i];
4210 /* Everything should be the same. */
4211 if (!file_id_equal(&state->id, &f->id)) {
4212 /* This should catch all dynamic share cases. */
4213 state->match_status = NT_STATUS_OPLOCK_NOT_GRANTED;
4214 break;
4216 if (!strequal(f->servicepath, state->servicepath)) {
4217 state->match_status = NT_STATUS_INVALID_PARAMETER;
4218 break;
4220 if (!strequal(f->base_name, state->fname->base_name)) {
4221 state->match_status = NT_STATUS_INVALID_PARAMETER;
4222 break;
4224 if (!strequal(f->stream_name, state->fname->stream_name)) {
4225 state->match_status = NT_STATUS_INVALID_PARAMETER;
4226 break;
4230 if (NT_STATUS_IS_OK(state->match_status)) {
4232 * Common case - just opening another handle on a
4233 * file on a non-dynamic share.
4235 return;
4238 if (NT_STATUS_EQUAL(state->match_status, NT_STATUS_INVALID_PARAMETER)) {
4239 /* Mismatched path. Error back to client. */
4240 return;
4244 * File id mismatch. Dynamic share case NT_STATUS_OPLOCK_NOT_GRANTED.
4245 * Don't allow leases.
4248 state->match_status = leases_db_copy_file_ids(state->mem_ctx,
4249 num_files,
4250 files,
4251 &state->ids);
4252 if (!NT_STATUS_IS_OK(state->match_status)) {
4253 return;
4256 state->num_file_ids = num_files;
4257 state->match_status = NT_STATUS_OPLOCK_NOT_GRANTED;
4258 return;
4261 static NTSTATUS lease_match(connection_struct *conn,
4262 struct smb_request *req,
4263 struct smb2_lease_key *lease_key,
4264 const char *servicepath,
4265 const struct smb_filename *fname,
4266 uint16_t *p_version,
4267 uint16_t *p_epoch)
4269 struct smbd_server_connection *sconn = req->sconn;
4270 TALLOC_CTX *tos = talloc_tos();
4271 struct lease_match_state state = {
4272 .mem_ctx = tos,
4273 .servicepath = servicepath,
4274 .fname = fname,
4275 .match_status = NT_STATUS_OK
4277 uint32_t i;
4278 NTSTATUS status;
4280 state.file_existed = VALID_STAT(fname->st);
4281 if (state.file_existed) {
4282 state.id = vfs_file_id_from_sbuf(conn, &fname->st);
4283 } else {
4284 memset(&state.id, '\0', sizeof(state.id));
4287 status = leases_db_parse(&sconn->client->connections->smb2.client.guid,
4288 lease_key, lease_match_parser, &state);
4289 if (!NT_STATUS_IS_OK(status)) {
4291 * Not found or error means okay: We can make the lease pass
4293 return NT_STATUS_OK;
4295 if (!NT_STATUS_EQUAL(state.match_status, NT_STATUS_OPLOCK_NOT_GRANTED)) {
4297 * Anything but NT_STATUS_OPLOCK_NOT_GRANTED, let the caller
4298 * deal with it.
4300 return state.match_status;
4303 /* We have to break all existing leases. */
4304 for (i = 0; i < state.num_file_ids; i++) {
4305 struct share_mode_lock *lck;
4306 struct share_mode_data *d;
4307 uint32_t j;
4309 if (file_id_equal(&state.ids[i], &state.id)) {
4310 /* Don't need to break our own file. */
4311 continue;
4314 lck = get_existing_share_mode_lock(talloc_tos(), state.ids[i]);
4315 if (lck == NULL) {
4316 /* Race condition - file already closed. */
4317 continue;
4319 d = lck->data;
4320 for (j=0; j<d->num_share_modes; j++) {
4321 struct share_mode_entry *e = &d->share_modes[j];
4322 uint32_t e_lease_type = get_lease_type(d, e);
4323 struct share_mode_lease *l = NULL;
4325 if (share_mode_stale_pid(d, j)) {
4326 continue;
4329 if (e->op_type == LEASE_OPLOCK) {
4330 l = &lck->data->leases[e->lease_idx];
4331 if (!smb2_lease_key_equal(&l->lease_key,
4332 lease_key)) {
4333 continue;
4335 *p_epoch = l->epoch;
4336 *p_version = l->lease_version;
4339 if (e_lease_type == SMB2_LEASE_NONE) {
4340 continue;
4343 send_break_message(conn->sconn->msg_ctx, e,
4344 SMB2_LEASE_NONE);
4347 * Windows 7 and 8 lease clients
4348 * are broken in that they will not
4349 * respond to lease break requests
4350 * whilst waiting for an outstanding
4351 * open request on that lease handle
4352 * on the same TCP connection, due
4353 * to holding an internal inode lock.
4355 * This means we can't reschedule
4356 * ourselves here, but must return
4357 * from the create.
4359 * Work around:
4361 * Send the breaks and then return
4362 * SMB2_LEASE_NONE in the lease handle
4363 * to cause them to acknowledge the
4364 * lease break. Consulatation with
4365 * Microsoft engineering confirmed
4366 * this approach is safe.
4370 TALLOC_FREE(lck);
4373 * Ensure we don't grant anything more so we
4374 * never upgrade.
4376 return NT_STATUS_OPLOCK_NOT_GRANTED;
4380 * Wrapper around open_file_ntcreate and open_directory
4383 static NTSTATUS create_file_unixpath(connection_struct *conn,
4384 struct smb_request *req,
4385 struct smb_filename *smb_fname,
4386 uint32_t access_mask,
4387 uint32_t share_access,
4388 uint32_t create_disposition,
4389 uint32_t create_options,
4390 uint32_t file_attributes,
4391 uint32_t oplock_request,
4392 struct smb2_lease *lease,
4393 uint64_t allocation_size,
4394 uint32_t private_flags,
4395 struct security_descriptor *sd,
4396 struct ea_list *ea_list,
4398 files_struct **result,
4399 int *pinfo)
4401 int info = FILE_WAS_OPENED;
4402 files_struct *base_fsp = NULL;
4403 files_struct *fsp = NULL;
4404 NTSTATUS status;
4406 DEBUG(10,("create_file_unixpath: access_mask = 0x%x "
4407 "file_attributes = 0x%x, share_access = 0x%x, "
4408 "create_disposition = 0x%x create_options = 0x%x "
4409 "oplock_request = 0x%x private_flags = 0x%x "
4410 "ea_list = 0x%p, sd = 0x%p, "
4411 "fname = %s\n",
4412 (unsigned int)access_mask,
4413 (unsigned int)file_attributes,
4414 (unsigned int)share_access,
4415 (unsigned int)create_disposition,
4416 (unsigned int)create_options,
4417 (unsigned int)oplock_request,
4418 (unsigned int)private_flags,
4419 ea_list, sd, smb_fname_str_dbg(smb_fname)));
4421 if (create_options & FILE_OPEN_BY_FILE_ID) {
4422 status = NT_STATUS_NOT_SUPPORTED;
4423 goto fail;
4426 if (create_options & NTCREATEX_OPTIONS_INVALID_PARAM_MASK) {
4427 status = NT_STATUS_INVALID_PARAMETER;
4428 goto fail;
4431 if (req == NULL) {
4432 oplock_request |= INTERNAL_OPEN_ONLY;
4435 if (lease != NULL) {
4436 uint16_t epoch = lease->lease_epoch;
4437 uint16_t version = lease->lease_version;
4438 status = lease_match(conn,
4439 req,
4440 &lease->lease_key,
4441 conn->connectpath,
4442 smb_fname,
4443 &version,
4444 &epoch);
4445 if (NT_STATUS_EQUAL(status, NT_STATUS_OPLOCK_NOT_GRANTED)) {
4446 /* Dynamic share file. No leases and update epoch... */
4447 lease->lease_state = SMB2_LEASE_NONE;
4448 lease->lease_epoch = epoch;
4449 lease->lease_version = version;
4450 } else if (!NT_STATUS_IS_OK(status)) {
4451 goto fail;
4455 if ((conn->fs_capabilities & FILE_NAMED_STREAMS)
4456 && (access_mask & DELETE_ACCESS)
4457 && !is_ntfs_stream_smb_fname(smb_fname)) {
4459 * We can't open a file with DELETE access if any of the
4460 * streams is open without FILE_SHARE_DELETE
4462 status = open_streams_for_delete(conn, smb_fname->base_name);
4464 if (!NT_STATUS_IS_OK(status)) {
4465 goto fail;
4469 if ((access_mask & SEC_FLAG_SYSTEM_SECURITY) &&
4470 !security_token_has_privilege(get_current_nttok(conn),
4471 SEC_PRIV_SECURITY)) {
4472 DEBUG(10, ("create_file_unixpath: open on %s "
4473 "failed - SEC_FLAG_SYSTEM_SECURITY denied.\n",
4474 smb_fname_str_dbg(smb_fname)));
4475 status = NT_STATUS_PRIVILEGE_NOT_HELD;
4476 goto fail;
4479 if ((conn->fs_capabilities & FILE_NAMED_STREAMS)
4480 && is_ntfs_stream_smb_fname(smb_fname)
4481 && (!(private_flags & NTCREATEX_OPTIONS_PRIVATE_STREAM_DELETE))) {
4482 uint32 base_create_disposition;
4483 struct smb_filename *smb_fname_base = NULL;
4485 if (create_options & FILE_DIRECTORY_FILE) {
4486 status = NT_STATUS_NOT_A_DIRECTORY;
4487 goto fail;
4490 switch (create_disposition) {
4491 case FILE_OPEN:
4492 base_create_disposition = FILE_OPEN;
4493 break;
4494 default:
4495 base_create_disposition = FILE_OPEN_IF;
4496 break;
4499 /* Create an smb_filename with stream_name == NULL. */
4500 smb_fname_base = synthetic_smb_fname(talloc_tos(),
4501 smb_fname->base_name,
4502 NULL, NULL);
4503 if (smb_fname_base == NULL) {
4504 status = NT_STATUS_NO_MEMORY;
4505 goto fail;
4508 if (SMB_VFS_STAT(conn, smb_fname_base) == -1) {
4509 DEBUG(10, ("Unable to stat stream: %s\n",
4510 smb_fname_str_dbg(smb_fname_base)));
4511 } else {
4513 * https://bugzilla.samba.org/show_bug.cgi?id=10229
4514 * We need to check if the requested access mask
4515 * could be used to open the underlying file (if
4516 * it existed), as we're passing in zero for the
4517 * access mask to the base filename.
4519 status = check_base_file_access(conn,
4520 smb_fname_base,
4521 access_mask);
4523 if (!NT_STATUS_IS_OK(status)) {
4524 DEBUG(10, ("Permission check "
4525 "for base %s failed: "
4526 "%s\n", smb_fname->base_name,
4527 nt_errstr(status)));
4528 goto fail;
4532 /* Open the base file. */
4533 status = create_file_unixpath(conn, NULL, smb_fname_base, 0,
4534 FILE_SHARE_READ
4535 | FILE_SHARE_WRITE
4536 | FILE_SHARE_DELETE,
4537 base_create_disposition,
4538 0, 0, 0, NULL, 0, 0, NULL, NULL,
4539 &base_fsp, NULL);
4540 TALLOC_FREE(smb_fname_base);
4542 if (!NT_STATUS_IS_OK(status)) {
4543 DEBUG(10, ("create_file_unixpath for base %s failed: "
4544 "%s\n", smb_fname->base_name,
4545 nt_errstr(status)));
4546 goto fail;
4548 /* we don't need the low level fd */
4549 fd_close(base_fsp);
4553 * If it's a request for a directory open, deal with it separately.
4556 if (create_options & FILE_DIRECTORY_FILE) {
4558 if (create_options & FILE_NON_DIRECTORY_FILE) {
4559 status = NT_STATUS_INVALID_PARAMETER;
4560 goto fail;
4563 /* Can't open a temp directory. IFS kit test. */
4564 if (!(file_attributes & FILE_FLAG_POSIX_SEMANTICS) &&
4565 (file_attributes & FILE_ATTRIBUTE_TEMPORARY)) {
4566 status = NT_STATUS_INVALID_PARAMETER;
4567 goto fail;
4571 * We will get a create directory here if the Win32
4572 * app specified a security descriptor in the
4573 * CreateDirectory() call.
4576 oplock_request = 0;
4577 status = open_directory(
4578 conn, req, smb_fname, access_mask, share_access,
4579 create_disposition, create_options, file_attributes,
4580 &info, &fsp);
4581 } else {
4584 * Ordinary file case.
4587 status = file_new(req, conn, &fsp);
4588 if(!NT_STATUS_IS_OK(status)) {
4589 goto fail;
4592 status = fsp_set_smb_fname(fsp, smb_fname);
4593 if (!NT_STATUS_IS_OK(status)) {
4594 goto fail;
4597 if (base_fsp) {
4599 * We're opening the stream element of a
4600 * base_fsp we already opened. Set up the
4601 * base_fsp pointer.
4603 fsp->base_fsp = base_fsp;
4606 if (allocation_size) {
4607 fsp->initial_allocation_size = smb_roundup(fsp->conn,
4608 allocation_size);
4611 status = open_file_ntcreate(conn,
4612 req,
4613 access_mask,
4614 share_access,
4615 create_disposition,
4616 create_options,
4617 file_attributes,
4618 oplock_request,
4619 lease,
4620 private_flags,
4621 &info,
4622 fsp);
4624 if(!NT_STATUS_IS_OK(status)) {
4625 file_free(req, fsp);
4626 fsp = NULL;
4629 if (NT_STATUS_EQUAL(status, NT_STATUS_FILE_IS_A_DIRECTORY)) {
4631 /* A stream open never opens a directory */
4633 if (base_fsp) {
4634 status = NT_STATUS_FILE_IS_A_DIRECTORY;
4635 goto fail;
4639 * Fail the open if it was explicitly a non-directory
4640 * file.
4643 if (create_options & FILE_NON_DIRECTORY_FILE) {
4644 status = NT_STATUS_FILE_IS_A_DIRECTORY;
4645 goto fail;
4648 oplock_request = 0;
4649 status = open_directory(
4650 conn, req, smb_fname, access_mask,
4651 share_access, create_disposition,
4652 create_options, file_attributes,
4653 &info, &fsp);
4657 if (!NT_STATUS_IS_OK(status)) {
4658 goto fail;
4661 fsp->base_fsp = base_fsp;
4663 if ((ea_list != NULL) &&
4664 ((info == FILE_WAS_CREATED) || (info == FILE_WAS_OVERWRITTEN))) {
4665 status = set_ea(conn, fsp, fsp->fsp_name, ea_list);
4666 if (!NT_STATUS_IS_OK(status)) {
4667 goto fail;
4671 if (!fsp->is_directory && S_ISDIR(fsp->fsp_name->st.st_ex_mode)) {
4672 status = NT_STATUS_ACCESS_DENIED;
4673 goto fail;
4676 /* Save the requested allocation size. */
4677 if ((info == FILE_WAS_CREATED) || (info == FILE_WAS_OVERWRITTEN)) {
4678 if (allocation_size
4679 && (allocation_size > fsp->fsp_name->st.st_ex_size)) {
4680 fsp->initial_allocation_size = smb_roundup(
4681 fsp->conn, allocation_size);
4682 if (fsp->is_directory) {
4683 /* Can't set allocation size on a directory. */
4684 status = NT_STATUS_ACCESS_DENIED;
4685 goto fail;
4687 if (vfs_allocate_file_space(
4688 fsp, fsp->initial_allocation_size) == -1) {
4689 status = NT_STATUS_DISK_FULL;
4690 goto fail;
4692 } else {
4693 fsp->initial_allocation_size = smb_roundup(
4694 fsp->conn, (uint64_t)fsp->fsp_name->st.st_ex_size);
4696 } else {
4697 fsp->initial_allocation_size = 0;
4700 if ((info == FILE_WAS_CREATED) && lp_nt_acl_support(SNUM(conn)) &&
4701 fsp->base_fsp == NULL) {
4702 if (sd != NULL) {
4704 * According to the MS documentation, the only time the security
4705 * descriptor is applied to the opened file is iff we *created* the
4706 * file; an existing file stays the same.
4708 * Also, it seems (from observation) that you can open the file with
4709 * any access mask but you can still write the sd. We need to override
4710 * the granted access before we call set_sd
4711 * Patch for bug #2242 from Tom Lackemann <cessnatomny@yahoo.com>.
4714 uint32_t sec_info_sent;
4715 uint32_t saved_access_mask = fsp->access_mask;
4717 sec_info_sent = get_sec_info(sd);
4719 fsp->access_mask = FILE_GENERIC_ALL;
4721 if (sec_info_sent & (SECINFO_OWNER|
4722 SECINFO_GROUP|
4723 SECINFO_DACL|
4724 SECINFO_SACL)) {
4725 status = set_sd(fsp, sd, sec_info_sent);
4728 fsp->access_mask = saved_access_mask;
4730 if (!NT_STATUS_IS_OK(status)) {
4731 goto fail;
4733 } else if (lp_inherit_acls(SNUM(conn))) {
4734 /* Inherit from parent. Errors here are not fatal. */
4735 status = inherit_new_acl(fsp);
4736 if (!NT_STATUS_IS_OK(status)) {
4737 DEBUG(10,("inherit_new_acl: failed for %s with %s\n",
4738 fsp_str_dbg(fsp),
4739 nt_errstr(status) ));
4744 if ((conn->fs_capabilities & FILE_FILE_COMPRESSION)
4745 && (create_options & FILE_NO_COMPRESSION)
4746 && (info == FILE_WAS_CREATED)) {
4747 status = SMB_VFS_SET_COMPRESSION(conn, fsp, fsp,
4748 COMPRESSION_FORMAT_NONE);
4749 if (!NT_STATUS_IS_OK(status)) {
4750 DEBUG(1, ("failed to disable compression: %s\n",
4751 nt_errstr(status)));
4755 DEBUG(10, ("create_file_unixpath: info=%d\n", info));
4757 *result = fsp;
4758 if (pinfo != NULL) {
4759 *pinfo = info;
4762 smb_fname->st = fsp->fsp_name->st;
4764 return NT_STATUS_OK;
4766 fail:
4767 DEBUG(10, ("create_file_unixpath: %s\n", nt_errstr(status)));
4769 if (fsp != NULL) {
4770 if (base_fsp && fsp->base_fsp == base_fsp) {
4772 * The close_file below will close
4773 * fsp->base_fsp.
4775 base_fsp = NULL;
4777 close_file(req, fsp, ERROR_CLOSE);
4778 fsp = NULL;
4780 if (base_fsp != NULL) {
4781 close_file(req, base_fsp, ERROR_CLOSE);
4782 base_fsp = NULL;
4784 return status;
4788 * Calculate the full path name given a relative fid.
4790 NTSTATUS get_relative_fid_filename(connection_struct *conn,
4791 struct smb_request *req,
4792 uint16_t root_dir_fid,
4793 const struct smb_filename *smb_fname,
4794 struct smb_filename **smb_fname_out)
4796 files_struct *dir_fsp;
4797 char *parent_fname = NULL;
4798 char *new_base_name = NULL;
4799 NTSTATUS status;
4801 if (root_dir_fid == 0 || !smb_fname) {
4802 status = NT_STATUS_INTERNAL_ERROR;
4803 goto out;
4806 dir_fsp = file_fsp(req, root_dir_fid);
4808 if (dir_fsp == NULL) {
4809 status = NT_STATUS_INVALID_HANDLE;
4810 goto out;
4813 if (is_ntfs_stream_smb_fname(dir_fsp->fsp_name)) {
4814 status = NT_STATUS_INVALID_HANDLE;
4815 goto out;
4818 if (!dir_fsp->is_directory) {
4821 * Check to see if this is a mac fork of some kind.
4824 if ((conn->fs_capabilities & FILE_NAMED_STREAMS) &&
4825 is_ntfs_stream_smb_fname(smb_fname)) {
4826 status = NT_STATUS_OBJECT_PATH_NOT_FOUND;
4827 goto out;
4831 we need to handle the case when we get a
4832 relative open relative to a file and the
4833 pathname is blank - this is a reopen!
4834 (hint from demyn plantenberg)
4837 status = NT_STATUS_INVALID_HANDLE;
4838 goto out;
4841 if (ISDOT(dir_fsp->fsp_name->base_name)) {
4843 * We're at the toplevel dir, the final file name
4844 * must not contain ./, as this is filtered out
4845 * normally by srvstr_get_path and unix_convert
4846 * explicitly rejects paths containing ./.
4848 parent_fname = talloc_strdup(talloc_tos(), "");
4849 if (parent_fname == NULL) {
4850 status = NT_STATUS_NO_MEMORY;
4851 goto out;
4853 } else {
4854 size_t dir_name_len = strlen(dir_fsp->fsp_name->base_name);
4857 * Copy in the base directory name.
4860 parent_fname = talloc_array(talloc_tos(), char,
4861 dir_name_len+2);
4862 if (parent_fname == NULL) {
4863 status = NT_STATUS_NO_MEMORY;
4864 goto out;
4866 memcpy(parent_fname, dir_fsp->fsp_name->base_name,
4867 dir_name_len+1);
4870 * Ensure it ends in a '/'.
4871 * We used TALLOC_SIZE +2 to add space for the '/'.
4874 if(dir_name_len
4875 && (parent_fname[dir_name_len-1] != '\\')
4876 && (parent_fname[dir_name_len-1] != '/')) {
4877 parent_fname[dir_name_len] = '/';
4878 parent_fname[dir_name_len+1] = '\0';
4882 new_base_name = talloc_asprintf(talloc_tos(), "%s%s", parent_fname,
4883 smb_fname->base_name);
4884 if (new_base_name == NULL) {
4885 status = NT_STATUS_NO_MEMORY;
4886 goto out;
4889 status = filename_convert(req,
4890 conn,
4891 req->flags2 & FLAGS2_DFS_PATHNAMES,
4892 new_base_name,
4894 NULL,
4895 smb_fname_out);
4896 if (!NT_STATUS_IS_OK(status)) {
4897 goto out;
4900 out:
4901 TALLOC_FREE(parent_fname);
4902 TALLOC_FREE(new_base_name);
4903 return status;
4906 NTSTATUS create_file_default(connection_struct *conn,
4907 struct smb_request *req,
4908 uint16_t root_dir_fid,
4909 struct smb_filename *smb_fname,
4910 uint32_t access_mask,
4911 uint32_t share_access,
4912 uint32_t create_disposition,
4913 uint32_t create_options,
4914 uint32_t file_attributes,
4915 uint32_t oplock_request,
4916 struct smb2_lease *lease,
4917 uint64_t allocation_size,
4918 uint32_t private_flags,
4919 struct security_descriptor *sd,
4920 struct ea_list *ea_list,
4921 files_struct **result,
4922 int *pinfo,
4923 const struct smb2_create_blobs *in_context_blobs,
4924 struct smb2_create_blobs *out_context_blobs)
4926 int info = FILE_WAS_OPENED;
4927 files_struct *fsp = NULL;
4928 NTSTATUS status;
4929 bool stream_name = false;
4931 DEBUG(10,("create_file: access_mask = 0x%x "
4932 "file_attributes = 0x%x, share_access = 0x%x, "
4933 "create_disposition = 0x%x create_options = 0x%x "
4934 "oplock_request = 0x%x "
4935 "private_flags = 0x%x "
4936 "root_dir_fid = 0x%x, ea_list = 0x%p, sd = 0x%p, "
4937 "fname = %s\n",
4938 (unsigned int)access_mask,
4939 (unsigned int)file_attributes,
4940 (unsigned int)share_access,
4941 (unsigned int)create_disposition,
4942 (unsigned int)create_options,
4943 (unsigned int)oplock_request,
4944 (unsigned int)private_flags,
4945 (unsigned int)root_dir_fid,
4946 ea_list, sd, smb_fname_str_dbg(smb_fname)));
4949 * Calculate the filename from the root_dir_if if necessary.
4952 if (root_dir_fid != 0) {
4953 struct smb_filename *smb_fname_out = NULL;
4954 status = get_relative_fid_filename(conn, req, root_dir_fid,
4955 smb_fname, &smb_fname_out);
4956 if (!NT_STATUS_IS_OK(status)) {
4957 goto fail;
4959 smb_fname = smb_fname_out;
4963 * Check to see if this is a mac fork of some kind.
4966 stream_name = is_ntfs_stream_smb_fname(smb_fname);
4967 if (stream_name) {
4968 enum FAKE_FILE_TYPE fake_file_type;
4970 fake_file_type = is_fake_file(smb_fname);
4972 if (fake_file_type != FAKE_FILE_TYPE_NONE) {
4975 * Here we go! support for changing the disk quotas
4976 * --metze
4978 * We need to fake up to open this MAGIC QUOTA file
4979 * and return a valid FID.
4981 * w2k close this file directly after openening xp
4982 * also tries a QUERY_FILE_INFO on the file and then
4983 * close it
4985 status = open_fake_file(req, conn, req->vuid,
4986 fake_file_type, smb_fname,
4987 access_mask, &fsp);
4988 if (!NT_STATUS_IS_OK(status)) {
4989 goto fail;
4992 ZERO_STRUCT(smb_fname->st);
4993 goto done;
4996 if (!(conn->fs_capabilities & FILE_NAMED_STREAMS)) {
4997 status = NT_STATUS_OBJECT_NAME_NOT_FOUND;
4998 goto fail;
5002 if (is_ntfs_default_stream_smb_fname(smb_fname)) {
5003 int ret;
5004 smb_fname->stream_name = NULL;
5005 /* We have to handle this error here. */
5006 if (create_options & FILE_DIRECTORY_FILE) {
5007 status = NT_STATUS_NOT_A_DIRECTORY;
5008 goto fail;
5010 if (lp_posix_pathnames()) {
5011 ret = SMB_VFS_LSTAT(conn, smb_fname);
5012 } else {
5013 ret = SMB_VFS_STAT(conn, smb_fname);
5016 if (ret == 0 && VALID_STAT_OF_DIR(smb_fname->st)) {
5017 status = NT_STATUS_FILE_IS_A_DIRECTORY;
5018 goto fail;
5022 status = create_file_unixpath(
5023 conn, req, smb_fname, access_mask, share_access,
5024 create_disposition, create_options, file_attributes,
5025 oplock_request, lease, allocation_size, private_flags,
5026 sd, ea_list,
5027 &fsp, &info);
5029 if (!NT_STATUS_IS_OK(status)) {
5030 goto fail;
5033 done:
5034 DEBUG(10, ("create_file: info=%d\n", info));
5036 *result = fsp;
5037 if (pinfo != NULL) {
5038 *pinfo = info;
5040 return NT_STATUS_OK;
5042 fail:
5043 DEBUG(10, ("create_file: %s\n", nt_errstr(status)));
5045 if (fsp != NULL) {
5046 close_file(req, fsp, ERROR_CLOSE);
5047 fsp = NULL;
5049 return status;