smbd: Simplify find_oplock_types
[Samba.git] / source3 / smbd / open.c
bloba1b4e43df764669a271277329ffc8b4b2be5025a
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 "passdb/lookup_sid.h"
33 #include "auth.h"
34 #include "serverid.h"
35 #include "messages.h"
37 extern const struct generic_mapping file_generic_mapping;
39 struct deferred_open_record {
40 bool delayed_for_oplocks;
41 bool async_open;
42 struct file_id id;
45 /****************************************************************************
46 If the requester wanted DELETE_ACCESS and was rejected because
47 the file ACL didn't include DELETE_ACCESS, see if the parent ACL
48 overrides this.
49 ****************************************************************************/
51 static bool parent_override_delete(connection_struct *conn,
52 const struct smb_filename *smb_fname,
53 uint32_t access_mask,
54 uint32_t rejected_mask)
56 if ((access_mask & DELETE_ACCESS) &&
57 (rejected_mask & DELETE_ACCESS) &&
58 can_delete_file_in_directory(conn, smb_fname)) {
59 return true;
61 return false;
64 /****************************************************************************
65 Check if we have open rights.
66 ****************************************************************************/
68 NTSTATUS smbd_check_access_rights(struct connection_struct *conn,
69 const struct smb_filename *smb_fname,
70 uint32_t access_mask)
72 /* Check if we have rights to open. */
73 NTSTATUS status;
74 struct security_descriptor *sd = NULL;
75 uint32_t rejected_share_access;
76 uint32_t rejected_mask = access_mask;
77 uint32_t do_not_check_mask = 0;
79 rejected_share_access = access_mask & ~(conn->share_access);
81 if (rejected_share_access) {
82 DEBUG(10, ("smbd_check_access_rights: rejected share access 0x%x "
83 "on %s (0x%x)\n",
84 (unsigned int)access_mask,
85 smb_fname_str_dbg(smb_fname),
86 (unsigned int)rejected_share_access ));
87 return NT_STATUS_ACCESS_DENIED;
90 if (get_current_uid(conn) == (uid_t)0) {
91 /* I'm sorry sir, I didn't know you were root... */
92 DEBUG(10,("smbd_check_access_rights: root override "
93 "on %s. Granting 0x%x\n",
94 smb_fname_str_dbg(smb_fname),
95 (unsigned int)access_mask ));
96 return NT_STATUS_OK;
99 if ((access_mask & DELETE_ACCESS) && !lp_acl_check_permissions(SNUM(conn))) {
100 DEBUG(10,("smbd_check_access_rights: not checking ACL "
101 "on DELETE_ACCESS on file %s. Granting 0x%x\n",
102 smb_fname_str_dbg(smb_fname),
103 (unsigned int)access_mask ));
104 return NT_STATUS_OK;
107 if (access_mask == DELETE_ACCESS &&
108 VALID_STAT(smb_fname->st) &&
109 S_ISLNK(smb_fname->st.st_ex_mode)) {
110 /* We can always delete a symlink. */
111 DEBUG(10,("smbd_check_access_rights: not checking ACL "
112 "on DELETE_ACCESS on symlink %s.\n",
113 smb_fname_str_dbg(smb_fname) ));
114 return NT_STATUS_OK;
117 status = SMB_VFS_GET_NT_ACL(conn, smb_fname->base_name,
118 (SECINFO_OWNER |
119 SECINFO_GROUP |
120 SECINFO_DACL), talloc_tos(), &sd);
122 if (!NT_STATUS_IS_OK(status)) {
123 DEBUG(10, ("smbd_check_access_rights: Could not get acl "
124 "on %s: %s\n",
125 smb_fname_str_dbg(smb_fname),
126 nt_errstr(status)));
128 if (NT_STATUS_EQUAL(status, NT_STATUS_ACCESS_DENIED)) {
129 goto access_denied;
132 return status;
136 * If we can access the path to this file, by
137 * default we have FILE_READ_ATTRIBUTES from the
138 * containing directory. See the section:
139 * "Algorithm to Check Access to an Existing File"
140 * in MS-FSA.pdf.
142 * se_file_access_check() also takes care of
143 * owner WRITE_DAC and READ_CONTROL.
145 do_not_check_mask = FILE_READ_ATTRIBUTES;
148 * Samba 3.6 and earlier granted execute access even
149 * if the ACL did not contain execute rights.
150 * Samba 4.0 is more correct and checks it.
151 * The compatibilty mode allows to skip this check
152 * to smoothen upgrades.
154 if (lp_acl_allow_execute_always(SNUM(conn))) {
155 do_not_check_mask |= FILE_EXECUTE;
158 status = se_file_access_check(sd,
159 get_current_nttok(conn),
160 false,
161 (access_mask & ~do_not_check_mask),
162 &rejected_mask);
164 DEBUG(10,("smbd_check_access_rights: file %s requesting "
165 "0x%x returning 0x%x (%s)\n",
166 smb_fname_str_dbg(smb_fname),
167 (unsigned int)access_mask,
168 (unsigned int)rejected_mask,
169 nt_errstr(status) ));
171 if (!NT_STATUS_IS_OK(status)) {
172 if (DEBUGLEVEL >= 10) {
173 DEBUG(10,("smbd_check_access_rights: acl for %s is:\n",
174 smb_fname_str_dbg(smb_fname) ));
175 NDR_PRINT_DEBUG(security_descriptor, sd);
179 TALLOC_FREE(sd);
181 if (NT_STATUS_IS_OK(status) ||
182 !NT_STATUS_EQUAL(status, NT_STATUS_ACCESS_DENIED)) {
183 return status;
186 /* Here we know status == NT_STATUS_ACCESS_DENIED. */
188 access_denied:
190 if ((access_mask & FILE_WRITE_ATTRIBUTES) &&
191 (rejected_mask & FILE_WRITE_ATTRIBUTES) &&
192 !lp_store_dos_attributes(SNUM(conn)) &&
193 (lp_map_readonly(SNUM(conn)) ||
194 lp_map_archive(SNUM(conn)) ||
195 lp_map_hidden(SNUM(conn)) ||
196 lp_map_system(SNUM(conn)))) {
197 rejected_mask &= ~FILE_WRITE_ATTRIBUTES;
199 DEBUG(10,("smbd_check_access_rights: "
200 "overrode "
201 "FILE_WRITE_ATTRIBUTES "
202 "on file %s\n",
203 smb_fname_str_dbg(smb_fname)));
206 if (parent_override_delete(conn,
207 smb_fname,
208 access_mask,
209 rejected_mask)) {
210 /* Were we trying to do an open
211 * for delete and didn't get DELETE
212 * access (only) ? Check if the
213 * directory allows DELETE_CHILD.
214 * See here:
215 * http://blogs.msdn.com/oldnewthing/archive/2004/06/04/148426.aspx
216 * for details. */
218 rejected_mask &= ~DELETE_ACCESS;
220 DEBUG(10,("smbd_check_access_rights: "
221 "overrode "
222 "DELETE_ACCESS on "
223 "file %s\n",
224 smb_fname_str_dbg(smb_fname)));
227 if (rejected_mask != 0) {
228 return NT_STATUS_ACCESS_DENIED;
230 return NT_STATUS_OK;
233 static NTSTATUS check_parent_access(struct connection_struct *conn,
234 struct smb_filename *smb_fname,
235 uint32_t access_mask)
237 NTSTATUS status;
238 char *parent_dir = NULL;
239 struct security_descriptor *parent_sd = NULL;
240 uint32_t access_granted = 0;
242 if (!parent_dirname(talloc_tos(),
243 smb_fname->base_name,
244 &parent_dir,
245 NULL)) {
246 return NT_STATUS_NO_MEMORY;
249 if (get_current_uid(conn) == (uid_t)0) {
250 /* I'm sorry sir, I didn't know you were root... */
251 DEBUG(10,("check_parent_access: root override "
252 "on %s. Granting 0x%x\n",
253 smb_fname_str_dbg(smb_fname),
254 (unsigned int)access_mask ));
255 return NT_STATUS_OK;
258 status = SMB_VFS_GET_NT_ACL(conn,
259 parent_dir,
260 SECINFO_DACL,
261 talloc_tos(),
262 &parent_sd);
264 if (!NT_STATUS_IS_OK(status)) {
265 DEBUG(5,("check_parent_access: SMB_VFS_GET_NT_ACL failed for "
266 "%s with error %s\n",
267 parent_dir,
268 nt_errstr(status)));
269 return status;
273 * If we can access the path to this file, by
274 * default we have FILE_READ_ATTRIBUTES from the
275 * containing directory. See the section:
276 * "Algorithm to Check Access to an Existing File"
277 * in MS-FSA.pdf.
279 * se_file_access_check() also takes care of
280 * owner WRITE_DAC and READ_CONTROL.
282 status = se_file_access_check(parent_sd,
283 get_current_nttok(conn),
284 false,
285 (access_mask & ~FILE_READ_ATTRIBUTES),
286 &access_granted);
287 if(!NT_STATUS_IS_OK(status)) {
288 DEBUG(5,("check_parent_access: access check "
289 "on directory %s for "
290 "path %s for mask 0x%x returned (0x%x) %s\n",
291 parent_dir,
292 smb_fname->base_name,
293 access_mask,
294 access_granted,
295 nt_errstr(status) ));
296 return status;
299 return NT_STATUS_OK;
302 /****************************************************************************
303 fd support routines - attempt to do a dos_open.
304 ****************************************************************************/
306 NTSTATUS fd_open(struct connection_struct *conn,
307 files_struct *fsp,
308 int flags,
309 mode_t mode)
311 struct smb_filename *smb_fname = fsp->fsp_name;
312 NTSTATUS status = NT_STATUS_OK;
314 #ifdef O_NOFOLLOW
316 * Never follow symlinks on a POSIX client. The
317 * client should be doing this.
320 if (fsp->posix_open || !lp_symlinks(SNUM(conn))) {
321 flags |= O_NOFOLLOW;
323 #endif
325 fsp->fh->fd = SMB_VFS_OPEN(conn, smb_fname, fsp, flags, mode);
326 if (fsp->fh->fd == -1) {
327 int posix_errno = errno;
328 #ifdef O_NOFOLLOW
329 #if defined(ENOTSUP) && defined(OSF1)
330 /* handle special Tru64 errno */
331 if (errno == ENOTSUP) {
332 posix_errno = ELOOP;
334 #endif /* ENOTSUP */
335 #ifdef EFTYPE
336 /* fix broken NetBSD errno */
337 if (errno == EFTYPE) {
338 posix_errno = ELOOP;
340 #endif /* EFTYPE */
341 /* fix broken FreeBSD errno */
342 if (errno == EMLINK) {
343 posix_errno = ELOOP;
345 #endif /* O_NOFOLLOW */
346 status = map_nt_error_from_unix(posix_errno);
347 if (errno == EMFILE) {
348 static time_t last_warned = 0L;
350 if (time((time_t *) NULL) > last_warned) {
351 DEBUG(0,("Too many open files, unable "
352 "to open more! smbd's max "
353 "open files = %d\n",
354 lp_max_open_files()));
355 last_warned = time((time_t *) NULL);
361 DEBUG(10,("fd_open: name %s, flags = 0%o mode = 0%o, fd = %d. %s\n",
362 smb_fname_str_dbg(smb_fname), flags, (int)mode, fsp->fh->fd,
363 (fsp->fh->fd == -1) ? strerror(errno) : "" ));
365 return status;
368 /****************************************************************************
369 Close the file associated with a fsp.
370 ****************************************************************************/
372 NTSTATUS fd_close(files_struct *fsp)
374 int ret;
376 if (fsp->dptr) {
377 dptr_CloseDir(fsp);
379 if (fsp->fh->fd == -1) {
380 return NT_STATUS_OK; /* What we used to call a stat open. */
382 if (fsp->fh->ref_count > 1) {
383 return NT_STATUS_OK; /* Shared handle. Only close last reference. */
386 ret = SMB_VFS_CLOSE(fsp);
387 fsp->fh->fd = -1;
388 if (ret == -1) {
389 return map_nt_error_from_unix(errno);
391 return NT_STATUS_OK;
394 /****************************************************************************
395 Change the ownership of a file to that of the parent directory.
396 Do this by fd if possible.
397 ****************************************************************************/
399 void change_file_owner_to_parent(connection_struct *conn,
400 const char *inherit_from_dir,
401 files_struct *fsp)
403 struct smb_filename *smb_fname_parent = NULL;
404 NTSTATUS status;
405 int ret;
407 status = create_synthetic_smb_fname(talloc_tos(), inherit_from_dir,
408 NULL, NULL, &smb_fname_parent);
409 if (!NT_STATUS_IS_OK(status)) {
410 return;
413 ret = SMB_VFS_STAT(conn, smb_fname_parent);
414 if (ret == -1) {
415 DEBUG(0,("change_file_owner_to_parent: failed to stat parent "
416 "directory %s. Error was %s\n",
417 smb_fname_str_dbg(smb_fname_parent),
418 strerror(errno)));
419 TALLOC_FREE(smb_fname_parent);
420 return;
423 if (smb_fname_parent->st.st_ex_uid == fsp->fsp_name->st.st_ex_uid) {
424 /* Already this uid - no need to change. */
425 DEBUG(10,("change_file_owner_to_parent: file %s "
426 "is already owned by uid %d\n",
427 fsp_str_dbg(fsp),
428 (int)fsp->fsp_name->st.st_ex_uid ));
429 TALLOC_FREE(smb_fname_parent);
430 return;
433 become_root();
434 ret = SMB_VFS_FCHOWN(fsp, smb_fname_parent->st.st_ex_uid, (gid_t)-1);
435 unbecome_root();
436 if (ret == -1) {
437 DEBUG(0,("change_file_owner_to_parent: failed to fchown "
438 "file %s to parent directory uid %u. Error "
439 "was %s\n", fsp_str_dbg(fsp),
440 (unsigned int)smb_fname_parent->st.st_ex_uid,
441 strerror(errno) ));
442 } else {
443 DEBUG(10,("change_file_owner_to_parent: changed new file %s to "
444 "parent directory uid %u.\n", fsp_str_dbg(fsp),
445 (unsigned int)smb_fname_parent->st.st_ex_uid));
446 /* Ensure the uid entry is updated. */
447 fsp->fsp_name->st.st_ex_uid = smb_fname_parent->st.st_ex_uid;
450 TALLOC_FREE(smb_fname_parent);
453 NTSTATUS change_dir_owner_to_parent(connection_struct *conn,
454 const char *inherit_from_dir,
455 const char *fname,
456 SMB_STRUCT_STAT *psbuf)
458 struct smb_filename *smb_fname_parent = NULL;
459 struct smb_filename *smb_fname_cwd = NULL;
460 char *saved_dir = NULL;
461 TALLOC_CTX *ctx = talloc_tos();
462 NTSTATUS status = NT_STATUS_OK;
463 int ret;
465 status = create_synthetic_smb_fname(ctx, inherit_from_dir, NULL, NULL,
466 &smb_fname_parent);
467 if (!NT_STATUS_IS_OK(status)) {
468 return status;
471 ret = SMB_VFS_STAT(conn, smb_fname_parent);
472 if (ret == -1) {
473 status = map_nt_error_from_unix(errno);
474 DEBUG(0,("change_dir_owner_to_parent: failed to stat parent "
475 "directory %s. Error was %s\n",
476 smb_fname_str_dbg(smb_fname_parent),
477 strerror(errno)));
478 goto out;
481 /* We've already done an lstat into psbuf, and we know it's a
482 directory. If we can cd into the directory and the dev/ino
483 are the same then we can safely chown without races as
484 we're locking the directory in place by being in it. This
485 should work on any UNIX (thanks tridge :-). JRA.
488 saved_dir = vfs_GetWd(ctx,conn);
489 if (!saved_dir) {
490 status = map_nt_error_from_unix(errno);
491 DEBUG(0,("change_dir_owner_to_parent: failed to get "
492 "current working directory. Error was %s\n",
493 strerror(errno)));
494 goto out;
497 /* Chdir into the new path. */
498 if (vfs_ChDir(conn, fname) == -1) {
499 status = map_nt_error_from_unix(errno);
500 DEBUG(0,("change_dir_owner_to_parent: failed to change "
501 "current working directory to %s. Error "
502 "was %s\n", fname, strerror(errno) ));
503 goto chdir;
506 status = create_synthetic_smb_fname(ctx, ".", NULL, NULL,
507 &smb_fname_cwd);
508 if (!NT_STATUS_IS_OK(status)) {
509 return status;
512 ret = SMB_VFS_STAT(conn, smb_fname_cwd);
513 if (ret == -1) {
514 status = map_nt_error_from_unix(errno);
515 DEBUG(0,("change_dir_owner_to_parent: failed to stat "
516 "directory '.' (%s) Error was %s\n",
517 fname, strerror(errno)));
518 goto chdir;
521 /* Ensure we're pointing at the same place. */
522 if (smb_fname_cwd->st.st_ex_dev != psbuf->st_ex_dev ||
523 smb_fname_cwd->st.st_ex_ino != psbuf->st_ex_ino) {
524 DEBUG(0,("change_dir_owner_to_parent: "
525 "device/inode on directory %s changed. "
526 "Refusing to chown !\n", fname ));
527 status = NT_STATUS_ACCESS_DENIED;
528 goto chdir;
531 if (smb_fname_parent->st.st_ex_uid == smb_fname_cwd->st.st_ex_uid) {
532 /* Already this uid - no need to change. */
533 DEBUG(10,("change_dir_owner_to_parent: directory %s "
534 "is already owned by uid %d\n",
535 fname,
536 (int)smb_fname_cwd->st.st_ex_uid ));
537 status = NT_STATUS_OK;
538 goto chdir;
541 become_root();
542 ret = SMB_VFS_LCHOWN(conn, ".", smb_fname_parent->st.st_ex_uid,
543 (gid_t)-1);
544 unbecome_root();
545 if (ret == -1) {
546 status = map_nt_error_from_unix(errno);
547 DEBUG(10,("change_dir_owner_to_parent: failed to chown "
548 "directory %s to parent directory uid %u. "
549 "Error was %s\n", fname,
550 (unsigned int)smb_fname_parent->st.st_ex_uid,
551 strerror(errno) ));
552 } else {
553 DEBUG(10,("change_dir_owner_to_parent: changed ownership of new "
554 "directory %s to parent directory uid %u.\n",
555 fname, (unsigned int)smb_fname_parent->st.st_ex_uid ));
556 /* Ensure the uid entry is updated. */
557 psbuf->st_ex_uid = smb_fname_parent->st.st_ex_uid;
560 chdir:
561 vfs_ChDir(conn,saved_dir);
562 out:
563 TALLOC_FREE(smb_fname_parent);
564 TALLOC_FREE(smb_fname_cwd);
565 return status;
568 /****************************************************************************
569 Open a file - returning a guaranteed ATOMIC indication of if the
570 file was created or not.
571 ****************************************************************************/
573 static NTSTATUS fd_open_atomic(struct connection_struct *conn,
574 files_struct *fsp,
575 int flags,
576 mode_t mode,
577 bool *file_created)
579 NTSTATUS status = NT_STATUS_UNSUCCESSFUL;
580 bool file_existed = VALID_STAT(fsp->fsp_name->st);
582 *file_created = false;
584 if (!(flags & O_CREAT)) {
586 * We're not creating the file, just pass through.
588 return fd_open(conn, fsp, flags, mode);
591 if (flags & O_EXCL) {
593 * Fail if already exists, just pass through.
595 status = fd_open(conn, fsp, flags, mode);
598 * Here we've opened with O_CREAT|O_EXCL. If that went
599 * NT_STATUS_OK, we *know* we created this file.
601 *file_created = NT_STATUS_IS_OK(status);
603 return status;
607 * Now it gets tricky. We have O_CREAT, but not O_EXCL.
608 * To know absolutely if we created the file or not,
609 * we can never call O_CREAT without O_EXCL. So if
610 * we think the file existed, try without O_CREAT|O_EXCL.
611 * If we think the file didn't exist, try with
612 * O_CREAT|O_EXCL. Keep bouncing between these two
613 * requests until either the file is created, or
614 * opened. Either way, we keep going until we get
615 * a returnable result (error, or open/create).
618 while(1) {
619 int curr_flags = flags;
621 if (file_existed) {
622 /* Just try open, do not create. */
623 curr_flags &= ~(O_CREAT);
624 status = fd_open(conn, fsp, curr_flags, mode);
625 if (NT_STATUS_EQUAL(status,
626 NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
628 * Someone deleted it in the meantime.
629 * Retry with O_EXCL.
631 file_existed = false;
632 DEBUG(10,("fd_open_atomic: file %s existed. "
633 "Retry.\n",
634 smb_fname_str_dbg(fsp->fsp_name)));
635 continue;
637 } else {
638 /* Try create exclusively, fail if it exists. */
639 curr_flags |= O_EXCL;
640 status = fd_open(conn, fsp, curr_flags, mode);
641 if (NT_STATUS_EQUAL(status,
642 NT_STATUS_OBJECT_NAME_COLLISION)) {
644 * Someone created it in the meantime.
645 * Retry without O_CREAT.
647 file_existed = true;
648 DEBUG(10,("fd_open_atomic: file %s "
649 "did not exist. Retry.\n",
650 smb_fname_str_dbg(fsp->fsp_name)));
651 continue;
653 if (NT_STATUS_IS_OK(status)) {
655 * Here we've opened with O_CREAT|O_EXCL
656 * and got success. We *know* we created
657 * this file.
659 *file_created = true;
662 /* Create is done, or failed. */
663 break;
665 return status;
668 /****************************************************************************
669 Open a file.
670 ****************************************************************************/
672 static NTSTATUS open_file(files_struct *fsp,
673 connection_struct *conn,
674 struct smb_request *req,
675 const char *parent_dir,
676 int flags,
677 mode_t unx_mode,
678 uint32 access_mask, /* client requested access mask. */
679 uint32 open_access_mask, /* what we're actually using in the open. */
680 bool *p_file_created)
682 struct smb_filename *smb_fname = fsp->fsp_name;
683 NTSTATUS status = NT_STATUS_OK;
684 int accmode = (flags & O_ACCMODE);
685 int local_flags = flags;
686 bool file_existed = VALID_STAT(fsp->fsp_name->st);
688 fsp->fh->fd = -1;
689 errno = EPERM;
691 /* Check permissions */
694 * This code was changed after seeing a client open request
695 * containing the open mode of (DENY_WRITE/read-only) with
696 * the 'create if not exist' bit set. The previous code
697 * would fail to open the file read only on a read-only share
698 * as it was checking the flags parameter directly against O_RDONLY,
699 * this was failing as the flags parameter was set to O_RDONLY|O_CREAT.
700 * JRA.
703 if (!CAN_WRITE(conn)) {
704 /* It's a read-only share - fail if we wanted to write. */
705 if(accmode != O_RDONLY || (flags & O_TRUNC) || (flags & O_APPEND)) {
706 DEBUG(3,("Permission denied opening %s\n",
707 smb_fname_str_dbg(smb_fname)));
708 return NT_STATUS_ACCESS_DENIED;
709 } else if(flags & O_CREAT) {
710 /* We don't want to write - but we must make sure that
711 O_CREAT doesn't create the file if we have write
712 access into the directory.
714 flags &= ~(O_CREAT|O_EXCL);
715 local_flags &= ~(O_CREAT|O_EXCL);
720 * This little piece of insanity is inspired by the
721 * fact that an NT client can open a file for O_RDONLY,
722 * but set the create disposition to FILE_EXISTS_TRUNCATE.
723 * If the client *can* write to the file, then it expects to
724 * truncate the file, even though it is opening for readonly.
725 * Quicken uses this stupid trick in backup file creation...
726 * Thanks *greatly* to "David W. Chapman Jr." <dwcjr@inethouston.net>
727 * for helping track this one down. It didn't bite us in 2.0.x
728 * as we always opened files read-write in that release. JRA.
731 if ((accmode == O_RDONLY) && ((flags & O_TRUNC) == O_TRUNC)) {
732 DEBUG(10,("open_file: truncate requested on read-only open "
733 "for file %s\n", smb_fname_str_dbg(smb_fname)));
734 local_flags = (flags & ~O_ACCMODE)|O_RDWR;
737 if ((open_access_mask & (FILE_READ_DATA|FILE_WRITE_DATA|FILE_APPEND_DATA|FILE_EXECUTE)) ||
738 (!file_existed && (local_flags & O_CREAT)) ||
739 ((local_flags & O_TRUNC) == O_TRUNC) ) {
740 const char *wild;
741 int ret;
743 #if defined(O_NONBLOCK) && defined(S_ISFIFO)
745 * We would block on opening a FIFO with no one else on the
746 * other end. Do what we used to do and add O_NONBLOCK to the
747 * open flags. JRA.
750 if (file_existed && S_ISFIFO(smb_fname->st.st_ex_mode)) {
751 local_flags &= ~O_TRUNC; /* Can't truncate a FIFO. */
752 local_flags |= O_NONBLOCK;
754 #endif
756 /* Don't create files with Microsoft wildcard characters. */
757 if (fsp->base_fsp) {
759 * wildcard characters are allowed in stream names
760 * only test the basefilename
762 wild = fsp->base_fsp->fsp_name->base_name;
763 } else {
764 wild = smb_fname->base_name;
766 if ((local_flags & O_CREAT) && !file_existed &&
767 ms_has_wild(wild)) {
768 return NT_STATUS_OBJECT_NAME_INVALID;
771 /* Can we access this file ? */
772 if (!fsp->base_fsp) {
773 /* Only do this check on non-stream open. */
774 if (file_existed) {
775 status = smbd_check_access_rights(conn,
776 smb_fname,
777 access_mask);
778 } else if (local_flags & O_CREAT){
779 status = check_parent_access(conn,
780 smb_fname,
781 SEC_DIR_ADD_FILE);
782 } else {
783 /* File didn't exist and no O_CREAT. */
784 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
786 if (!NT_STATUS_IS_OK(status)) {
787 DEBUG(10,("open_file: "
788 "%s on file "
789 "%s returned %s\n",
790 file_existed ?
791 "smbd_check_access_rights" :
792 "check_parent_access",
793 smb_fname_str_dbg(smb_fname),
794 nt_errstr(status) ));
795 return status;
799 /* Actually do the open */
800 status = fd_open_atomic(conn, fsp, local_flags,
801 unx_mode, p_file_created);
802 if (!NT_STATUS_IS_OK(status)) {
803 DEBUG(3,("Error opening file %s (%s) (local_flags=%d) "
804 "(flags=%d)\n", smb_fname_str_dbg(smb_fname),
805 nt_errstr(status),local_flags,flags));
806 return status;
809 ret = SMB_VFS_FSTAT(fsp, &smb_fname->st);
810 if (ret == -1) {
811 /* If we have an fd, this stat should succeed. */
812 DEBUG(0,("Error doing fstat on open file %s "
813 "(%s)\n",
814 smb_fname_str_dbg(smb_fname),
815 strerror(errno) ));
816 status = map_nt_error_from_unix(errno);
817 fd_close(fsp);
818 return status;
821 if (*p_file_created) {
822 /* We created this file. */
824 bool need_re_stat = false;
825 /* Do all inheritance work after we've
826 done a successful fstat call and filled
827 in the stat struct in fsp->fsp_name. */
829 /* Inherit the ACL if required */
830 if (lp_inherit_perms(SNUM(conn))) {
831 inherit_access_posix_acl(conn, parent_dir,
832 smb_fname->base_name,
833 unx_mode);
834 need_re_stat = true;
837 /* Change the owner if required. */
838 if (lp_inherit_owner(SNUM(conn))) {
839 change_file_owner_to_parent(conn, parent_dir,
840 fsp);
841 need_re_stat = true;
844 if (need_re_stat) {
845 ret = SMB_VFS_FSTAT(fsp, &smb_fname->st);
846 /* If we have an fd, this stat should succeed. */
847 if (ret == -1) {
848 DEBUG(0,("Error doing fstat on open file %s "
849 "(%s)\n",
850 smb_fname_str_dbg(smb_fname),
851 strerror(errno) ));
855 notify_fname(conn, NOTIFY_ACTION_ADDED,
856 FILE_NOTIFY_CHANGE_FILE_NAME,
857 smb_fname->base_name);
859 } else {
860 fsp->fh->fd = -1; /* What we used to call a stat open. */
861 if (!file_existed) {
862 /* File must exist for a stat open. */
863 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
866 status = smbd_check_access_rights(conn,
867 smb_fname,
868 access_mask);
870 if (NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND) &&
871 fsp->posix_open &&
872 S_ISLNK(smb_fname->st.st_ex_mode)) {
873 /* This is a POSIX stat open for delete
874 * or rename on a symlink that points
875 * nowhere. Allow. */
876 DEBUG(10,("open_file: allowing POSIX "
877 "open on bad symlink %s\n",
878 smb_fname_str_dbg(smb_fname)));
879 status = NT_STATUS_OK;
882 if (!NT_STATUS_IS_OK(status)) {
883 DEBUG(10,("open_file: "
884 "smbd_check_access_rights on file "
885 "%s returned %s\n",
886 smb_fname_str_dbg(smb_fname),
887 nt_errstr(status) ));
888 return status;
893 * POSIX allows read-only opens of directories. We don't
894 * want to do this (we use a different code path for this)
895 * so catch a directory open and return an EISDIR. JRA.
898 if(S_ISDIR(smb_fname->st.st_ex_mode)) {
899 fd_close(fsp);
900 errno = EISDIR;
901 return NT_STATUS_FILE_IS_A_DIRECTORY;
904 fsp->file_id = vfs_file_id_from_sbuf(conn, &smb_fname->st);
905 fsp->vuid = req ? req->vuid : UID_FIELD_INVALID;
906 fsp->file_pid = req ? req->smbpid : 0;
907 fsp->can_lock = True;
908 fsp->can_read = ((access_mask & FILE_READ_DATA) != 0);
909 fsp->can_write =
910 CAN_WRITE(conn) &&
911 ((access_mask & (FILE_WRITE_DATA | FILE_APPEND_DATA)) != 0);
912 fsp->print_file = NULL;
913 fsp->modified = False;
914 fsp->sent_oplock_break = NO_BREAK_SENT;
915 fsp->is_directory = False;
916 if (conn->aio_write_behind_list &&
917 is_in_path(smb_fname->base_name, conn->aio_write_behind_list,
918 conn->case_sensitive)) {
919 fsp->aio_write_behind = True;
922 fsp->wcp = NULL; /* Write cache pointer. */
924 DEBUG(2,("%s opened file %s read=%s write=%s (numopen=%d)\n",
925 conn->session_info->unix_info->unix_name,
926 smb_fname_str_dbg(smb_fname),
927 BOOLSTR(fsp->can_read), BOOLSTR(fsp->can_write),
928 conn->num_files_open));
930 errno = 0;
931 return NT_STATUS_OK;
934 /****************************************************************************
935 Check if we can open a file with a share mode.
936 Returns True if conflict, False if not.
937 ****************************************************************************/
939 static bool share_conflict(struct share_mode_entry *entry,
940 uint32 access_mask,
941 uint32 share_access)
943 DEBUG(10,("share_conflict: entry->access_mask = 0x%x, "
944 "entry->share_access = 0x%x, "
945 "entry->private_options = 0x%x\n",
946 (unsigned int)entry->access_mask,
947 (unsigned int)entry->share_access,
948 (unsigned int)entry->private_options));
950 if (server_id_is_disconnected(&entry->pid)) {
952 * note: cleanup should have been done by
953 * delay_for_batch_oplocks()
955 return false;
958 DEBUG(10,("share_conflict: access_mask = 0x%x, share_access = 0x%x\n",
959 (unsigned int)access_mask, (unsigned int)share_access));
961 if ((entry->access_mask & (FILE_WRITE_DATA|
962 FILE_APPEND_DATA|
963 FILE_READ_DATA|
964 FILE_EXECUTE|
965 DELETE_ACCESS)) == 0) {
966 DEBUG(10,("share_conflict: No conflict due to "
967 "entry->access_mask = 0x%x\n",
968 (unsigned int)entry->access_mask ));
969 return False;
972 if ((access_mask & (FILE_WRITE_DATA|
973 FILE_APPEND_DATA|
974 FILE_READ_DATA|
975 FILE_EXECUTE|
976 DELETE_ACCESS)) == 0) {
977 DEBUG(10,("share_conflict: No conflict due to "
978 "access_mask = 0x%x\n",
979 (unsigned int)access_mask ));
980 return False;
983 #if 1 /* JRA TEST - Superdebug. */
984 #define CHECK_MASK(num, am, right, sa, share) \
985 DEBUG(10,("share_conflict: [%d] am (0x%x) & right (0x%x) = 0x%x\n", \
986 (unsigned int)(num), (unsigned int)(am), \
987 (unsigned int)(right), (unsigned int)(am)&(right) )); \
988 DEBUG(10,("share_conflict: [%d] sa (0x%x) & share (0x%x) = 0x%x\n", \
989 (unsigned int)(num), (unsigned int)(sa), \
990 (unsigned int)(share), (unsigned int)(sa)&(share) )); \
991 if (((am) & (right)) && !((sa) & (share))) { \
992 DEBUG(10,("share_conflict: check %d conflict am = 0x%x, right = 0x%x, \
993 sa = 0x%x, share = 0x%x\n", (num), (unsigned int)(am), (unsigned int)(right), (unsigned int)(sa), \
994 (unsigned int)(share) )); \
995 return True; \
997 #else
998 #define CHECK_MASK(num, am, right, sa, share) \
999 if (((am) & (right)) && !((sa) & (share))) { \
1000 DEBUG(10,("share_conflict: check %d conflict am = 0x%x, right = 0x%x, \
1001 sa = 0x%x, share = 0x%x\n", (num), (unsigned int)(am), (unsigned int)(right), (unsigned int)(sa), \
1002 (unsigned int)(share) )); \
1003 return True; \
1005 #endif
1007 CHECK_MASK(1, entry->access_mask, FILE_WRITE_DATA | FILE_APPEND_DATA,
1008 share_access, FILE_SHARE_WRITE);
1009 CHECK_MASK(2, access_mask, FILE_WRITE_DATA | FILE_APPEND_DATA,
1010 entry->share_access, FILE_SHARE_WRITE);
1012 CHECK_MASK(3, entry->access_mask, FILE_READ_DATA | FILE_EXECUTE,
1013 share_access, FILE_SHARE_READ);
1014 CHECK_MASK(4, access_mask, FILE_READ_DATA | FILE_EXECUTE,
1015 entry->share_access, FILE_SHARE_READ);
1017 CHECK_MASK(5, entry->access_mask, DELETE_ACCESS,
1018 share_access, FILE_SHARE_DELETE);
1019 CHECK_MASK(6, access_mask, DELETE_ACCESS,
1020 entry->share_access, FILE_SHARE_DELETE);
1022 DEBUG(10,("share_conflict: No conflict.\n"));
1023 return False;
1026 #if defined(DEVELOPER)
1027 static void validate_my_share_entries(struct smbd_server_connection *sconn,
1028 int num,
1029 struct share_mode_entry *share_entry)
1031 struct server_id self = messaging_server_id(sconn->msg_ctx);
1032 files_struct *fsp;
1034 if (!serverid_equal(&self, &share_entry->pid)) {
1035 return;
1038 if (is_deferred_open_entry(share_entry) &&
1039 !open_was_deferred(sconn, share_entry->op_mid)) {
1040 char *str = talloc_asprintf(talloc_tos(),
1041 "Got a deferred entry without a request: "
1042 "PANIC: %s\n",
1043 share_mode_str(talloc_tos(), num, share_entry));
1044 smb_panic(str);
1047 if (!is_valid_share_mode_entry(share_entry)) {
1048 return;
1051 fsp = file_find_dif(sconn, share_entry->id,
1052 share_entry->share_file_id);
1053 if (!fsp) {
1054 DEBUG(0,("validate_my_share_entries: PANIC : %s\n",
1055 share_mode_str(talloc_tos(), num, share_entry) ));
1056 smb_panic("validate_my_share_entries: Cannot match a "
1057 "share entry with an open file\n");
1060 if (is_deferred_open_entry(share_entry)) {
1061 goto panic;
1064 if ((share_entry->op_type == NO_OPLOCK) &&
1065 (fsp->oplock_type == FAKE_LEVEL_II_OPLOCK)) {
1066 /* Someone has already written to it, but I haven't yet
1067 * noticed */
1068 return;
1071 if (((uint16)fsp->oplock_type) != share_entry->op_type) {
1072 goto panic;
1075 return;
1077 panic:
1079 char *str;
1080 DEBUG(0,("validate_my_share_entries: PANIC : %s\n",
1081 share_mode_str(talloc_tos(), num, share_entry) ));
1082 str = talloc_asprintf(talloc_tos(),
1083 "validate_my_share_entries: "
1084 "file %s, oplock_type = 0x%x, op_type = 0x%x\n",
1085 fsp->fsp_name->base_name,
1086 (unsigned int)fsp->oplock_type,
1087 (unsigned int)share_entry->op_type );
1088 smb_panic(str);
1091 #endif
1093 bool is_stat_open(uint32 access_mask)
1095 return (access_mask &&
1096 ((access_mask & ~(SYNCHRONIZE_ACCESS| FILE_READ_ATTRIBUTES|
1097 FILE_WRITE_ATTRIBUTES))==0) &&
1098 ((access_mask & (SYNCHRONIZE_ACCESS|FILE_READ_ATTRIBUTES|
1099 FILE_WRITE_ATTRIBUTES)) != 0));
1102 /****************************************************************************
1103 Deal with share modes
1104 Invarient: Share mode must be locked on entry and exit.
1105 Returns -1 on error, or number of share modes on success (may be zero).
1106 ****************************************************************************/
1108 static NTSTATUS open_mode_check(connection_struct *conn,
1109 struct share_mode_lock *lck,
1110 uint32_t name_hash,
1111 uint32 access_mask,
1112 uint32 share_access,
1113 uint32 create_options,
1114 bool *file_existed)
1116 int i;
1118 if(lck->data->num_share_modes == 0) {
1119 return NT_STATUS_OK;
1122 /* A delete on close prohibits everything */
1124 if (is_delete_on_close_set(lck, name_hash)) {
1126 * Check the delete on close token
1127 * is valid. It could have been left
1128 * after a server crash.
1130 for(i = 0; i < lck->data->num_share_modes; i++) {
1131 if (!share_mode_stale_pid(lck->data, i)) {
1133 *file_existed = true;
1135 return NT_STATUS_DELETE_PENDING;
1138 return NT_STATUS_OK;
1141 if (is_stat_open(access_mask)) {
1142 /* Stat open that doesn't trigger oplock breaks or share mode
1143 * checks... ! JRA. */
1144 return NT_STATUS_OK;
1148 * Check if the share modes will give us access.
1151 #if defined(DEVELOPER)
1152 for(i = 0; i < lck->data->num_share_modes; i++) {
1153 validate_my_share_entries(conn->sconn, i,
1154 &lck->data->share_modes[i]);
1156 #endif
1158 /* Now we check the share modes, after any oplock breaks. */
1159 for(i = 0; i < lck->data->num_share_modes; i++) {
1161 if (!is_valid_share_mode_entry(&lck->data->share_modes[i])) {
1162 continue;
1165 /* someone else has a share lock on it, check to see if we can
1166 * too */
1167 if (share_conflict(&lck->data->share_modes[i],
1168 access_mask, share_access)) {
1170 if (share_mode_stale_pid(lck->data, i)) {
1171 continue;
1174 *file_existed = true;
1176 return NT_STATUS_SHARING_VIOLATION;
1180 if (lck->data->num_share_modes != 0) {
1181 *file_existed = true;
1184 return NT_STATUS_OK;
1188 * Send a break message to the oplock holder and delay the open for
1189 * our client.
1192 static NTSTATUS send_break_message(files_struct *fsp,
1193 struct share_mode_entry *exclusive,
1194 uint64_t mid,
1195 int oplock_request)
1197 NTSTATUS status;
1198 char msg[MSG_SMB_SHARE_MODE_ENTRY_SIZE];
1200 DEBUG(10, ("Sending break request to PID %s\n",
1201 procid_str_static(&exclusive->pid)));
1202 exclusive->op_mid = mid;
1204 /* Create the message. */
1205 share_mode_entry_to_message(msg, exclusive);
1207 /* Add in the FORCE_OPLOCK_BREAK_TO_NONE bit in the message if set. We
1208 don't want this set in the share mode struct pointed to by lck. */
1210 if (oplock_request & FORCE_OPLOCK_BREAK_TO_NONE) {
1211 SSVAL(msg,OP_BREAK_MSG_OP_TYPE_OFFSET,
1212 exclusive->op_type | FORCE_OPLOCK_BREAK_TO_NONE);
1215 status = messaging_send_buf(fsp->conn->sconn->msg_ctx, exclusive->pid,
1216 MSG_SMB_BREAK_REQUEST,
1217 (uint8 *)msg,
1218 MSG_SMB_SHARE_MODE_ENTRY_SIZE);
1219 if (!NT_STATUS_IS_OK(status)) {
1220 DEBUG(3, ("Could not send oplock break message: %s\n",
1221 nt_errstr(status)));
1224 return status;
1228 * Return share_mode_entry pointers for :
1229 * 1). Batch oplock entry.
1230 * 2). Batch or exclusive oplock entry (may be identical to #1).
1231 * bool have_level2_oplock
1232 * bool have_no_oplock.
1233 * Do internal consistency checks on the share mode for a file.
1236 static void find_oplock_types(files_struct *fsp,
1237 int oplock_request,
1238 const struct share_mode_lock *lck,
1239 struct share_mode_entry **pp_batch,
1240 struct share_mode_entry **pp_ex_or_batch,
1241 bool *got_level2,
1242 bool *got_no_oplock)
1244 int i;
1246 *pp_batch = NULL;
1247 *pp_ex_or_batch = NULL;
1248 *got_level2 = false;
1249 *got_no_oplock = false;
1251 /* Ignore stat or internal opens, as is done in
1252 delay_for_batch_oplocks() and
1253 delay_for_exclusive_oplocks().
1255 if ((oplock_request & INTERNAL_OPEN_ONLY) || is_stat_open(fsp->access_mask)) {
1256 return;
1259 for (i=0; i<lck->data->num_share_modes; i++) {
1260 struct share_mode_entry *e = &lck->data->share_modes[i];
1262 if (!is_valid_share_mode_entry(e)) {
1263 continue;
1266 if (e->op_type == NO_OPLOCK && is_stat_open(e->access_mask)) {
1267 /* We ignore stat opens in the table - they
1268 always have NO_OPLOCK and never get or
1269 cause breaks. JRA. */
1270 continue;
1273 if (BATCH_OPLOCK_TYPE(e->op_type)) {
1274 /* batch - can only be one. */
1275 if (share_mode_stale_pid(lck->data, i)) {
1276 DEBUG(10, ("Found stale batch oplock\n"));
1277 continue;
1279 if (*pp_ex_or_batch || *pp_batch || *got_level2 || *got_no_oplock) {
1280 smb_panic("Bad batch oplock entry.");
1282 *pp_batch = e;
1285 if (EXCLUSIVE_OPLOCK_TYPE(e->op_type)) {
1286 if (share_mode_stale_pid(lck->data, i)) {
1287 DEBUG(10, ("Found stale duplicate oplock\n"));
1288 continue;
1290 /* Exclusive or batch - can only be one. */
1291 if (*pp_ex_or_batch || *got_level2 || *got_no_oplock) {
1292 smb_panic("Bad exclusive or batch oplock entry.");
1294 *pp_ex_or_batch = e;
1297 if (LEVEL_II_OPLOCK_TYPE(e->op_type)) {
1298 if (*pp_batch || *pp_ex_or_batch) {
1299 if (share_mode_stale_pid(lck->data, i)) {
1300 DEBUG(10, ("Found stale LevelII "
1301 "oplock\n"));
1302 continue;
1304 smb_panic("Bad levelII oplock entry.");
1306 *got_level2 = true;
1309 if (e->op_type == NO_OPLOCK) {
1310 if (*pp_batch || *pp_ex_or_batch) {
1311 if (share_mode_stale_pid(lck->data, i)) {
1312 DEBUG(10, ("Found stale NO_OPLOCK "
1313 "entry\n"));
1314 continue;
1316 smb_panic("Bad no oplock entry.");
1318 *got_no_oplock = true;
1323 static bool delay_for_batch_oplocks(files_struct *fsp,
1324 uint64_t mid,
1325 int oplock_request,
1326 struct share_mode_entry *batch_entry)
1328 if ((oplock_request & INTERNAL_OPEN_ONLY) || is_stat_open(fsp->access_mask)) {
1329 return false;
1331 if (batch_entry == NULL) {
1332 return false;
1335 if (server_id_is_disconnected(&batch_entry->pid)) {
1337 * TODO: clean up.
1338 * This could be achieved by sending a break message
1339 * to ourselves. Special considerations for files
1340 * with delete_on_close flag set!
1342 * For now we keep it simple and do not
1343 * allow delete on close for durable handles.
1345 return false;
1348 /* Found a batch oplock */
1349 send_break_message(fsp, batch_entry, mid, oplock_request);
1350 return true;
1353 static bool delay_for_exclusive_oplocks(files_struct *fsp,
1354 uint64_t mid,
1355 int oplock_request,
1356 struct share_mode_entry *ex_entry)
1358 if ((oplock_request & INTERNAL_OPEN_ONLY) || is_stat_open(fsp->access_mask)) {
1359 return false;
1361 if (ex_entry == NULL) {
1362 return false;
1365 if (server_id_is_disconnected(&ex_entry->pid)) {
1367 * since only durable handles can get disconnected,
1368 * and we can only get durable handles with batch oplocks,
1369 * this should actually never be reached...
1371 return false;
1374 send_break_message(fsp, ex_entry, mid, oplock_request);
1375 return true;
1378 static bool file_has_brlocks(files_struct *fsp)
1380 struct byte_range_lock *br_lck;
1382 br_lck = brl_get_locks_readonly(fsp);
1383 if (!br_lck)
1384 return false;
1386 return br_lck->num_locks > 0 ? true : false;
1389 static void grant_fsp_oplock_type(files_struct *fsp,
1390 int oplock_request,
1391 bool got_level2_oplock,
1392 bool got_a_none_oplock)
1394 bool allow_level2 = (global_client_caps & CAP_LEVEL_II_OPLOCKS) &&
1395 lp_level2_oplocks(SNUM(fsp->conn));
1397 /* Start by granting what the client asked for,
1398 but ensure no SAMBA_PRIVATE bits can be set. */
1399 fsp->oplock_type = (oplock_request & ~SAMBA_PRIVATE_OPLOCK_MASK);
1401 if (oplock_request & INTERNAL_OPEN_ONLY) {
1402 /* No oplocks on internal open. */
1403 fsp->oplock_type = NO_OPLOCK;
1404 DEBUG(10,("grant_fsp_oplock_type: oplock type 0x%x on file %s\n",
1405 fsp->oplock_type, fsp_str_dbg(fsp)));
1406 return;
1409 if (lp_locking(fsp->conn->params) && file_has_brlocks(fsp)) {
1410 DEBUG(10,("grant_fsp_oplock_type: file %s has byte range locks\n",
1411 fsp_str_dbg(fsp)));
1412 fsp->oplock_type = NO_OPLOCK;
1415 if (is_stat_open(fsp->access_mask)) {
1416 /* Leave the value already set. */
1417 DEBUG(10,("grant_fsp_oplock_type: oplock type 0x%x on file %s\n",
1418 fsp->oplock_type, fsp_str_dbg(fsp)));
1419 return;
1423 * Match what was requested (fsp->oplock_type) with
1424 * what was found in the existing share modes.
1427 if (got_a_none_oplock) {
1428 fsp->oplock_type = NO_OPLOCK;
1429 } else if (got_level2_oplock) {
1430 if (fsp->oplock_type == NO_OPLOCK ||
1431 fsp->oplock_type == FAKE_LEVEL_II_OPLOCK) {
1432 /* Store a level2 oplock, but don't tell the client */
1433 fsp->oplock_type = FAKE_LEVEL_II_OPLOCK;
1434 } else {
1435 fsp->oplock_type = LEVEL_II_OPLOCK;
1437 } else {
1438 /* All share_mode_entries are placeholders or deferred.
1439 * Silently upgrade to fake levelII if the client didn't
1440 * ask for an oplock. */
1441 if (fsp->oplock_type == NO_OPLOCK) {
1442 /* Store a level2 oplock, but don't tell the client */
1443 fsp->oplock_type = FAKE_LEVEL_II_OPLOCK;
1448 * Don't grant level2 to clients that don't want them
1449 * or if we've turned them off.
1451 if (fsp->oplock_type == LEVEL_II_OPLOCK && !allow_level2) {
1452 fsp->oplock_type = FAKE_LEVEL_II_OPLOCK;
1455 DEBUG(10,("grant_fsp_oplock_type: oplock type 0x%x on file %s\n",
1456 fsp->oplock_type, fsp_str_dbg(fsp)));
1459 static bool request_timed_out(struct timeval request_time,
1460 struct timeval timeout)
1462 struct timeval now, end_time;
1463 GetTimeOfDay(&now);
1464 end_time = timeval_sum(&request_time, &timeout);
1465 return (timeval_compare(&end_time, &now) < 0);
1468 /****************************************************************************
1469 Handle the 1 second delay in returning a SHARING_VIOLATION error.
1470 ****************************************************************************/
1472 static void defer_open(struct share_mode_lock *lck,
1473 struct timeval request_time,
1474 struct timeval timeout,
1475 struct smb_request *req,
1476 struct deferred_open_record *state)
1478 struct server_id self = messaging_server_id(req->sconn->msg_ctx);
1480 /* Paranoia check */
1482 if (lck) {
1483 int i;
1485 for (i=0; i<lck->data->num_share_modes; i++) {
1486 struct share_mode_entry *e = &lck->data->share_modes[i];
1488 if (is_deferred_open_entry(e) &&
1489 serverid_equal(&self, &e->pid) &&
1490 (e->op_mid == req->mid)) {
1491 DEBUG(0, ("Trying to defer an already deferred "
1492 "request: mid=%llu, exiting\n",
1493 (unsigned long long)req->mid));
1494 TALLOC_FREE(lck);
1495 exit_server("attempt to defer a deferred request");
1500 /* End paranoia check */
1502 DEBUG(10,("defer_open_sharing_error: time [%u.%06u] adding deferred "
1503 "open entry for mid %llu\n",
1504 (unsigned int)request_time.tv_sec,
1505 (unsigned int)request_time.tv_usec,
1506 (unsigned long long)req->mid));
1508 if (!push_deferred_open_message_smb(req, request_time, timeout,
1509 state->id, (char *)state, sizeof(*state))) {
1510 TALLOC_FREE(lck);
1511 exit_server("push_deferred_open_message_smb failed");
1513 if (lck) {
1514 add_deferred_open(lck, req->mid, request_time, self, state->id);
1519 /****************************************************************************
1520 On overwrite open ensure that the attributes match.
1521 ****************************************************************************/
1523 static bool open_match_attributes(connection_struct *conn,
1524 uint32 old_dos_attr,
1525 uint32 new_dos_attr,
1526 mode_t existing_unx_mode,
1527 mode_t new_unx_mode,
1528 mode_t *returned_unx_mode)
1530 uint32 noarch_old_dos_attr, noarch_new_dos_attr;
1532 noarch_old_dos_attr = (old_dos_attr & ~FILE_ATTRIBUTE_ARCHIVE);
1533 noarch_new_dos_attr = (new_dos_attr & ~FILE_ATTRIBUTE_ARCHIVE);
1535 if((noarch_old_dos_attr == 0 && noarch_new_dos_attr != 0) ||
1536 (noarch_old_dos_attr != 0 && ((noarch_old_dos_attr & noarch_new_dos_attr) == noarch_old_dos_attr))) {
1537 *returned_unx_mode = new_unx_mode;
1538 } else {
1539 *returned_unx_mode = (mode_t)0;
1542 DEBUG(10,("open_match_attributes: old_dos_attr = 0x%x, "
1543 "existing_unx_mode = 0%o, new_dos_attr = 0x%x "
1544 "returned_unx_mode = 0%o\n",
1545 (unsigned int)old_dos_attr,
1546 (unsigned int)existing_unx_mode,
1547 (unsigned int)new_dos_attr,
1548 (unsigned int)*returned_unx_mode ));
1550 /* If we're mapping SYSTEM and HIDDEN ensure they match. */
1551 if (lp_map_system(SNUM(conn)) || lp_store_dos_attributes(SNUM(conn))) {
1552 if ((old_dos_attr & FILE_ATTRIBUTE_SYSTEM) &&
1553 !(new_dos_attr & FILE_ATTRIBUTE_SYSTEM)) {
1554 return False;
1557 if (lp_map_hidden(SNUM(conn)) || lp_store_dos_attributes(SNUM(conn))) {
1558 if ((old_dos_attr & FILE_ATTRIBUTE_HIDDEN) &&
1559 !(new_dos_attr & FILE_ATTRIBUTE_HIDDEN)) {
1560 return False;
1563 return True;
1566 /****************************************************************************
1567 Special FCB or DOS processing in the case of a sharing violation.
1568 Try and find a duplicated file handle.
1569 ****************************************************************************/
1571 static NTSTATUS fcb_or_dos_open(struct smb_request *req,
1572 connection_struct *conn,
1573 files_struct *fsp_to_dup_into,
1574 const struct smb_filename *smb_fname,
1575 struct file_id id,
1576 uint16 file_pid,
1577 uint64_t vuid,
1578 uint32 access_mask,
1579 uint32 share_access,
1580 uint32 create_options)
1582 files_struct *fsp;
1584 DEBUG(5,("fcb_or_dos_open: attempting old open semantics for "
1585 "file %s.\n", smb_fname_str_dbg(smb_fname)));
1587 for(fsp = file_find_di_first(conn->sconn, id); fsp;
1588 fsp = file_find_di_next(fsp)) {
1590 DEBUG(10,("fcb_or_dos_open: checking file %s, fd = %d, "
1591 "vuid = %llu, file_pid = %u, private_options = 0x%x "
1592 "access_mask = 0x%x\n", fsp_str_dbg(fsp),
1593 fsp->fh->fd, (unsigned long long)fsp->vuid,
1594 (unsigned int)fsp->file_pid,
1595 (unsigned int)fsp->fh->private_options,
1596 (unsigned int)fsp->access_mask ));
1598 if (fsp->fh->fd != -1 &&
1599 fsp->vuid == vuid &&
1600 fsp->file_pid == file_pid &&
1601 (fsp->fh->private_options & (NTCREATEX_OPTIONS_PRIVATE_DENY_DOS |
1602 NTCREATEX_OPTIONS_PRIVATE_DENY_FCB)) &&
1603 (fsp->access_mask & FILE_WRITE_DATA) &&
1604 strequal(fsp->fsp_name->base_name, smb_fname->base_name) &&
1605 strequal(fsp->fsp_name->stream_name,
1606 smb_fname->stream_name)) {
1607 DEBUG(10,("fcb_or_dos_open: file match\n"));
1608 break;
1612 if (!fsp) {
1613 return NT_STATUS_NOT_FOUND;
1616 /* quite an insane set of semantics ... */
1617 if (is_executable(smb_fname->base_name) &&
1618 (fsp->fh->private_options & NTCREATEX_OPTIONS_PRIVATE_DENY_DOS)) {
1619 DEBUG(10,("fcb_or_dos_open: file fail due to is_executable.\n"));
1620 return NT_STATUS_INVALID_PARAMETER;
1623 /* We need to duplicate this fsp. */
1624 return dup_file_fsp(req, fsp, access_mask, share_access,
1625 create_options, fsp_to_dup_into);
1628 static void schedule_defer_open(struct share_mode_lock *lck,
1629 struct timeval request_time,
1630 struct smb_request *req)
1632 struct deferred_open_record state;
1634 /* This is a relative time, added to the absolute
1635 request_time value to get the absolute timeout time.
1636 Note that if this is the second or greater time we enter
1637 this codepath for this particular request mid then
1638 request_time is left as the absolute time of the *first*
1639 time this request mid was processed. This is what allows
1640 the request to eventually time out. */
1642 struct timeval timeout;
1644 /* Normally the smbd we asked should respond within
1645 * OPLOCK_BREAK_TIMEOUT seconds regardless of whether
1646 * the client did, give twice the timeout as a safety
1647 * measure here in case the other smbd is stuck
1648 * somewhere else. */
1650 timeout = timeval_set(OPLOCK_BREAK_TIMEOUT*2, 0);
1652 /* Nothing actually uses state.delayed_for_oplocks
1653 but it's handy to differentiate in debug messages
1654 between a 30 second delay due to oplock break, and
1655 a 1 second delay for share mode conflicts. */
1657 state.delayed_for_oplocks = True;
1658 state.async_open = false;
1659 state.id = lck->data->id;
1661 if (!request_timed_out(request_time, timeout)) {
1662 defer_open(lck, request_time, timeout, req, &state);
1666 /****************************************************************************
1667 Reschedule an open call that went asynchronous.
1668 ****************************************************************************/
1670 static void schedule_async_open(struct timeval request_time,
1671 struct smb_request *req)
1673 struct deferred_open_record state;
1674 struct timeval timeout;
1676 timeout = timeval_set(20, 0);
1678 ZERO_STRUCT(state);
1679 state.delayed_for_oplocks = false;
1680 state.async_open = true;
1682 if (!request_timed_out(request_time, timeout)) {
1683 defer_open(NULL, request_time, timeout, req, &state);
1687 /****************************************************************************
1688 Work out what access_mask to use from what the client sent us.
1689 ****************************************************************************/
1691 static NTSTATUS smbd_calculate_maximum_allowed_access(
1692 connection_struct *conn,
1693 const struct smb_filename *smb_fname,
1694 uint32_t *p_access_mask)
1696 struct security_descriptor *sd;
1697 uint32_t access_granted;
1698 NTSTATUS status;
1700 if (get_current_uid(conn) == (uid_t)0) {
1701 *p_access_mask |= FILE_GENERIC_ALL;
1702 return NT_STATUS_OK;
1705 status = SMB_VFS_GET_NT_ACL(conn, smb_fname->base_name,
1706 (SECINFO_OWNER |
1707 SECINFO_GROUP |
1708 SECINFO_DACL),
1709 talloc_tos(), &sd);
1711 if (NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
1713 * File did not exist
1715 *p_access_mask = FILE_GENERIC_ALL;
1716 return NT_STATUS_OK;
1718 if (!NT_STATUS_IS_OK(status)) {
1719 DEBUG(10,("smbd_calculate_access_mask: "
1720 "Could not get acl on file %s: %s\n",
1721 smb_fname_str_dbg(smb_fname),
1722 nt_errstr(status)));
1723 return NT_STATUS_ACCESS_DENIED;
1727 * If we can access the path to this file, by
1728 * default we have FILE_READ_ATTRIBUTES from the
1729 * containing directory. See the section:
1730 * "Algorithm to Check Access to an Existing File"
1731 * in MS-FSA.pdf.
1733 * se_file_access_check()
1734 * also takes care of owner WRITE_DAC and READ_CONTROL.
1736 status = se_file_access_check(sd,
1737 get_current_nttok(conn),
1738 false,
1739 (*p_access_mask & ~FILE_READ_ATTRIBUTES),
1740 &access_granted);
1742 TALLOC_FREE(sd);
1744 if (!NT_STATUS_IS_OK(status)) {
1745 DEBUG(10, ("smbd_calculate_access_mask: "
1746 "Access denied on file %s: "
1747 "when calculating maximum access\n",
1748 smb_fname_str_dbg(smb_fname)));
1749 return NT_STATUS_ACCESS_DENIED;
1751 *p_access_mask = (access_granted | FILE_READ_ATTRIBUTES);
1753 if (!(access_granted & DELETE_ACCESS)) {
1754 if (can_delete_file_in_directory(conn, smb_fname)) {
1755 *p_access_mask |= DELETE_ACCESS;
1759 return NT_STATUS_OK;
1762 NTSTATUS smbd_calculate_access_mask(connection_struct *conn,
1763 const struct smb_filename *smb_fname,
1764 uint32_t access_mask,
1765 uint32_t *access_mask_out)
1767 NTSTATUS status;
1768 uint32_t orig_access_mask = access_mask;
1769 uint32_t rejected_share_access;
1772 * Convert GENERIC bits to specific bits.
1775 se_map_generic(&access_mask, &file_generic_mapping);
1777 /* Calculate MAXIMUM_ALLOWED_ACCESS if requested. */
1778 if (access_mask & MAXIMUM_ALLOWED_ACCESS) {
1780 status = smbd_calculate_maximum_allowed_access(
1781 conn, smb_fname, &access_mask);
1783 if (!NT_STATUS_IS_OK(status)) {
1784 return status;
1787 access_mask &= conn->share_access;
1790 rejected_share_access = access_mask & ~(conn->share_access);
1792 if (rejected_share_access) {
1793 DEBUG(10, ("smbd_calculate_access_mask: Access denied on "
1794 "file %s: rejected by share access mask[0x%08X] "
1795 "orig[0x%08X] mapped[0x%08X] reject[0x%08X]\n",
1796 smb_fname_str_dbg(smb_fname),
1797 conn->share_access,
1798 orig_access_mask, access_mask,
1799 rejected_share_access));
1800 return NT_STATUS_ACCESS_DENIED;
1803 *access_mask_out = access_mask;
1804 return NT_STATUS_OK;
1807 /****************************************************************************
1808 Remove the deferred open entry under lock.
1809 ****************************************************************************/
1811 void remove_deferred_open_entry(struct file_id id, uint64_t mid,
1812 struct server_id pid)
1814 struct share_mode_lock *lck = get_existing_share_mode_lock(
1815 talloc_tos(), id);
1816 if (lck == NULL) {
1817 DEBUG(0, ("could not get share mode lock\n"));
1818 return;
1820 del_deferred_open_entry(lck, mid, pid);
1821 TALLOC_FREE(lck);
1824 /****************************************************************************
1825 Return true if this is a state pointer to an asynchronous create.
1826 ****************************************************************************/
1828 bool is_deferred_open_async(const void *ptr)
1830 const struct deferred_open_record *state = (const struct deferred_open_record *)ptr;
1832 return state->async_open;
1835 static bool clear_ads(uint32_t create_disposition)
1837 bool ret = false;
1839 switch (create_disposition) {
1840 case FILE_SUPERSEDE:
1841 case FILE_OVERWRITE_IF:
1842 case FILE_OVERWRITE:
1843 ret = true;
1844 break;
1845 default:
1846 break;
1848 return ret;
1851 static int disposition_to_open_flags(uint32_t create_disposition)
1853 int ret = 0;
1856 * Currently we're using FILE_SUPERSEDE as the same as
1857 * FILE_OVERWRITE_IF but they really are
1858 * different. FILE_SUPERSEDE deletes an existing file
1859 * (requiring delete access) then recreates it.
1862 switch (create_disposition) {
1863 case FILE_SUPERSEDE:
1864 case FILE_OVERWRITE_IF:
1866 * If file exists replace/overwrite. If file doesn't
1867 * exist create.
1869 ret = O_CREAT|O_TRUNC;
1870 break;
1872 case FILE_OPEN:
1874 * If file exists open. If file doesn't exist error.
1876 ret = 0;
1877 break;
1879 case FILE_OVERWRITE:
1881 * If file exists overwrite. If file doesn't exist
1882 * error.
1884 ret = O_TRUNC;
1885 break;
1887 case FILE_CREATE:
1889 * If file exists error. If file doesn't exist create.
1891 ret = O_CREAT|O_EXCL;
1892 break;
1894 case FILE_OPEN_IF:
1896 * If file exists open. If file doesn't exist create.
1898 ret = O_CREAT;
1899 break;
1901 return ret;
1904 /****************************************************************************
1905 Open a file with a share mode. Passed in an already created files_struct *.
1906 ****************************************************************************/
1908 static NTSTATUS open_file_ntcreate(connection_struct *conn,
1909 struct smb_request *req,
1910 uint32 access_mask, /* access bits (FILE_READ_DATA etc.) */
1911 uint32 share_access, /* share constants (FILE_SHARE_READ etc) */
1912 uint32 create_disposition, /* FILE_OPEN_IF etc. */
1913 uint32 create_options, /* options such as delete on close. */
1914 uint32 new_dos_attributes, /* attributes used for new file. */
1915 int oplock_request, /* internal Samba oplock codes. */
1916 /* Information (FILE_EXISTS etc.) */
1917 uint32_t private_flags, /* Samba specific flags. */
1918 int *pinfo,
1919 files_struct *fsp)
1921 struct smb_filename *smb_fname = fsp->fsp_name;
1922 int flags=0;
1923 int flags2=0;
1924 bool file_existed = VALID_STAT(smb_fname->st);
1925 bool def_acl = False;
1926 bool posix_open = False;
1927 bool new_file_created = False;
1928 NTSTATUS fsp_open = NT_STATUS_ACCESS_DENIED;
1929 mode_t new_unx_mode = (mode_t)0;
1930 mode_t unx_mode = (mode_t)0;
1931 int info;
1932 uint32 existing_dos_attributes = 0;
1933 struct timeval request_time = timeval_zero();
1934 struct share_mode_lock *lck = NULL;
1935 uint32 open_access_mask = access_mask;
1936 NTSTATUS status;
1937 char *parent_dir;
1938 SMB_STRUCT_STAT saved_stat = smb_fname->st;
1940 if (conn->printer) {
1942 * Printers are handled completely differently.
1943 * Most of the passed parameters are ignored.
1946 if (pinfo) {
1947 *pinfo = FILE_WAS_CREATED;
1950 DEBUG(10, ("open_file_ntcreate: printer open fname=%s\n",
1951 smb_fname_str_dbg(smb_fname)));
1953 if (!req) {
1954 DEBUG(0,("open_file_ntcreate: printer open without "
1955 "an SMB request!\n"));
1956 return NT_STATUS_INTERNAL_ERROR;
1959 return print_spool_open(fsp, smb_fname->base_name,
1960 req->vuid);
1963 if (!parent_dirname(talloc_tos(), smb_fname->base_name, &parent_dir,
1964 NULL)) {
1965 return NT_STATUS_NO_MEMORY;
1968 if (new_dos_attributes & FILE_FLAG_POSIX_SEMANTICS) {
1969 posix_open = True;
1970 unx_mode = (mode_t)(new_dos_attributes & ~FILE_FLAG_POSIX_SEMANTICS);
1971 new_dos_attributes = 0;
1972 } else {
1973 /* Windows allows a new file to be created and
1974 silently removes a FILE_ATTRIBUTE_DIRECTORY
1975 sent by the client. Do the same. */
1977 new_dos_attributes &= ~FILE_ATTRIBUTE_DIRECTORY;
1979 /* We add FILE_ATTRIBUTE_ARCHIVE to this as this mode is only used if the file is
1980 * created new. */
1981 unx_mode = unix_mode(conn, new_dos_attributes | FILE_ATTRIBUTE_ARCHIVE,
1982 smb_fname, parent_dir);
1985 DEBUG(10, ("open_file_ntcreate: fname=%s, dos_attrs=0x%x "
1986 "access_mask=0x%x share_access=0x%x "
1987 "create_disposition = 0x%x create_options=0x%x "
1988 "unix mode=0%o oplock_request=%d private_flags = 0x%x\n",
1989 smb_fname_str_dbg(smb_fname), new_dos_attributes,
1990 access_mask, share_access, create_disposition,
1991 create_options, (unsigned int)unx_mode, oplock_request,
1992 (unsigned int)private_flags));
1994 if ((req == NULL) && ((oplock_request & INTERNAL_OPEN_ONLY) == 0)) {
1995 DEBUG(0, ("No smb request but not an internal only open!\n"));
1996 return NT_STATUS_INTERNAL_ERROR;
2000 * Only non-internal opens can be deferred at all
2003 if (req) {
2004 void *ptr;
2005 if (get_deferred_open_message_state(req,
2006 &request_time,
2007 &ptr)) {
2008 /* Remember the absolute time of the original
2009 request with this mid. We'll use it later to
2010 see if this has timed out. */
2012 /* If it was an async create retry, the file
2013 didn't exist. */
2015 if (is_deferred_open_async(ptr)) {
2016 SET_STAT_INVALID(smb_fname->st);
2017 file_existed = false;
2018 } else {
2019 struct deferred_open_record *state = (struct deferred_open_record *)ptr;
2020 /* Remove the deferred open entry under lock. */
2021 remove_deferred_open_entry(
2022 state->id, req->mid,
2023 messaging_server_id(req->sconn->msg_ctx));
2026 /* Ensure we don't reprocess this message. */
2027 remove_deferred_open_message_smb(req->sconn, req->mid);
2031 if (!posix_open) {
2032 new_dos_attributes &= SAMBA_ATTRIBUTES_MASK;
2033 if (file_existed) {
2034 existing_dos_attributes = dos_mode(conn, smb_fname);
2038 /* ignore any oplock requests if oplocks are disabled */
2039 if (!lp_oplocks(SNUM(conn)) ||
2040 IS_VETO_OPLOCK_PATH(conn, smb_fname->base_name)) {
2041 /* Mask off everything except the private Samba bits. */
2042 oplock_request &= SAMBA_PRIVATE_OPLOCK_MASK;
2045 /* this is for OS/2 long file names - say we don't support them */
2046 if (!lp_posix_pathnames() && strstr(smb_fname->base_name,".+,;=[].")) {
2047 /* OS/2 Workplace shell fix may be main code stream in a later
2048 * release. */
2049 DEBUG(5,("open_file_ntcreate: OS/2 long filenames are not "
2050 "supported.\n"));
2051 if (use_nt_status()) {
2052 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
2054 return NT_STATUS_DOS(ERRDOS, ERRcannotopen);
2057 switch( create_disposition ) {
2058 case FILE_OPEN:
2059 /* If file exists open. If file doesn't exist error. */
2060 if (!file_existed) {
2061 DEBUG(5,("open_file_ntcreate: FILE_OPEN "
2062 "requested for file %s and file "
2063 "doesn't exist.\n",
2064 smb_fname_str_dbg(smb_fname)));
2065 errno = ENOENT;
2066 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
2068 break;
2070 case FILE_OVERWRITE:
2071 /* If file exists overwrite. If file doesn't exist
2072 * error. */
2073 if (!file_existed) {
2074 DEBUG(5,("open_file_ntcreate: FILE_OVERWRITE "
2075 "requested for file %s and file "
2076 "doesn't exist.\n",
2077 smb_fname_str_dbg(smb_fname) ));
2078 errno = ENOENT;
2079 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
2081 break;
2083 case FILE_CREATE:
2084 /* If file exists error. If file doesn't exist
2085 * create. */
2086 if (file_existed) {
2087 DEBUG(5,("open_file_ntcreate: FILE_CREATE "
2088 "requested for file %s and file "
2089 "already exists.\n",
2090 smb_fname_str_dbg(smb_fname)));
2091 if (S_ISDIR(smb_fname->st.st_ex_mode)) {
2092 errno = EISDIR;
2093 } else {
2094 errno = EEXIST;
2096 return map_nt_error_from_unix(errno);
2098 break;
2100 case FILE_SUPERSEDE:
2101 case FILE_OVERWRITE_IF:
2102 case FILE_OPEN_IF:
2103 break;
2104 default:
2105 return NT_STATUS_INVALID_PARAMETER;
2108 flags2 = disposition_to_open_flags(create_disposition);
2110 /* We only care about matching attributes on file exists and
2111 * overwrite. */
2113 if (!posix_open && file_existed &&
2114 ((create_disposition == FILE_OVERWRITE) ||
2115 (create_disposition == FILE_OVERWRITE_IF))) {
2116 if (!open_match_attributes(conn, existing_dos_attributes,
2117 new_dos_attributes,
2118 smb_fname->st.st_ex_mode,
2119 unx_mode, &new_unx_mode)) {
2120 DEBUG(5,("open_file_ntcreate: attributes missmatch "
2121 "for file %s (%x %x) (0%o, 0%o)\n",
2122 smb_fname_str_dbg(smb_fname),
2123 existing_dos_attributes,
2124 new_dos_attributes,
2125 (unsigned int)smb_fname->st.st_ex_mode,
2126 (unsigned int)unx_mode ));
2127 errno = EACCES;
2128 return NT_STATUS_ACCESS_DENIED;
2132 status = smbd_calculate_access_mask(conn, smb_fname,
2133 access_mask,
2134 &access_mask);
2135 if (!NT_STATUS_IS_OK(status)) {
2136 DEBUG(10, ("open_file_ntcreate: smbd_calculate_access_mask "
2137 "on file %s returned %s\n",
2138 smb_fname_str_dbg(smb_fname), nt_errstr(status)));
2139 return status;
2142 open_access_mask = access_mask;
2144 if ((flags2 & O_TRUNC) || (oplock_request & FORCE_OPLOCK_BREAK_TO_NONE)) {
2145 open_access_mask |= FILE_WRITE_DATA; /* This will cause oplock breaks. */
2148 DEBUG(10, ("open_file_ntcreate: fname=%s, after mapping "
2149 "access_mask=0x%x\n", smb_fname_str_dbg(smb_fname),
2150 access_mask));
2153 * Note that we ignore the append flag as append does not
2154 * mean the same thing under DOS and Unix.
2157 if ((access_mask & (FILE_WRITE_DATA | FILE_APPEND_DATA)) ||
2158 (oplock_request & FORCE_OPLOCK_BREAK_TO_NONE)) {
2159 /* DENY_DOS opens are always underlying read-write on the
2160 file handle, no matter what the requested access mask
2161 says. */
2162 if ((private_flags & NTCREATEX_OPTIONS_PRIVATE_DENY_DOS) ||
2163 access_mask & (FILE_READ_ATTRIBUTES|FILE_READ_DATA|FILE_READ_EA|FILE_EXECUTE)) {
2164 flags = O_RDWR;
2165 } else {
2166 flags = O_WRONLY;
2168 } else {
2169 flags = O_RDONLY;
2173 * Currently we only look at FILE_WRITE_THROUGH for create options.
2176 #if defined(O_SYNC)
2177 if ((create_options & FILE_WRITE_THROUGH) && lp_strict_sync(SNUM(conn))) {
2178 flags2 |= O_SYNC;
2180 #endif /* O_SYNC */
2182 if (posix_open && (access_mask & FILE_APPEND_DATA)) {
2183 flags2 |= O_APPEND;
2186 if (!posix_open && !CAN_WRITE(conn)) {
2188 * We should really return a permission denied error if either
2189 * O_CREAT or O_TRUNC are set, but for compatibility with
2190 * older versions of Samba we just AND them out.
2192 flags2 &= ~(O_CREAT|O_TRUNC);
2196 * Ensure we can't write on a read-only share or file.
2199 if (flags != O_RDONLY && file_existed &&
2200 (!CAN_WRITE(conn) || IS_DOS_READONLY(existing_dos_attributes))) {
2201 DEBUG(5,("open_file_ntcreate: write access requested for "
2202 "file %s on read only %s\n",
2203 smb_fname_str_dbg(smb_fname),
2204 !CAN_WRITE(conn) ? "share" : "file" ));
2205 errno = EACCES;
2206 return NT_STATUS_ACCESS_DENIED;
2209 fsp->file_id = vfs_file_id_from_sbuf(conn, &smb_fname->st);
2210 fsp->share_access = share_access;
2211 fsp->fh->private_options = private_flags;
2212 fsp->access_mask = open_access_mask; /* We change this to the
2213 * requested access_mask after
2214 * the open is done. */
2215 fsp->posix_open = posix_open;
2217 /* Ensure no SAMBA_PRIVATE bits can be set. */
2218 fsp->oplock_type = (oplock_request & ~SAMBA_PRIVATE_OPLOCK_MASK);
2220 if (timeval_is_zero(&request_time)) {
2221 request_time = fsp->open_time;
2224 if (file_existed) {
2225 struct share_mode_entry *batch_entry = NULL;
2226 struct share_mode_entry *exclusive_entry = NULL;
2227 bool got_level2_oplock = false;
2228 bool got_a_none_oplock = false;
2229 struct file_id id;
2231 struct timespec old_write_time = smb_fname->st.st_ex_mtime;
2232 id = vfs_file_id_from_sbuf(conn, &smb_fname->st);
2234 lck = get_share_mode_lock(talloc_tos(), id,
2235 conn->connectpath,
2236 smb_fname, &old_write_time);
2237 if (lck == NULL) {
2238 DEBUG(0, ("Could not get share mode lock\n"));
2239 return NT_STATUS_SHARING_VIOLATION;
2242 /* Get the types we need to examine. */
2243 find_oplock_types(fsp,
2244 oplock_request,
2245 lck,
2246 &batch_entry,
2247 &exclusive_entry,
2248 &got_level2_oplock,
2249 &got_a_none_oplock);
2251 /* First pass - send break only on batch oplocks. */
2252 if ((req != NULL) &&
2253 delay_for_batch_oplocks(fsp,
2254 req->mid,
2255 oplock_request,
2256 batch_entry)) {
2257 schedule_defer_open(lck, request_time, req);
2258 TALLOC_FREE(lck);
2259 return NT_STATUS_SHARING_VIOLATION;
2262 /* Use the client requested access mask here, not the one we
2263 * open with. */
2264 status = open_mode_check(conn, lck, fsp->name_hash,
2265 access_mask, share_access,
2266 create_options, &file_existed);
2268 if (NT_STATUS_IS_OK(status)) {
2269 /* We might be going to allow this open. Check oplock
2270 * status again. */
2271 /* Second pass - send break for both batch or
2272 * exclusive oplocks. */
2273 if ((req != NULL) &&
2274 delay_for_exclusive_oplocks(
2275 fsp,
2276 req->mid,
2277 oplock_request,
2278 exclusive_entry)) {
2279 schedule_defer_open(lck, request_time, req);
2280 TALLOC_FREE(lck);
2281 return NT_STATUS_SHARING_VIOLATION;
2285 if (NT_STATUS_EQUAL(status, NT_STATUS_DELETE_PENDING)) {
2286 /* DELETE_PENDING is not deferred for a second */
2287 TALLOC_FREE(lck);
2288 return status;
2291 grant_fsp_oplock_type(fsp,
2292 oplock_request,
2293 got_level2_oplock,
2294 got_a_none_oplock);
2296 if (!NT_STATUS_IS_OK(status)) {
2297 uint32 can_access_mask;
2298 bool can_access = True;
2300 SMB_ASSERT(NT_STATUS_EQUAL(status, NT_STATUS_SHARING_VIOLATION));
2302 /* Check if this can be done with the deny_dos and fcb
2303 * calls. */
2304 if (private_flags &
2305 (NTCREATEX_OPTIONS_PRIVATE_DENY_DOS|
2306 NTCREATEX_OPTIONS_PRIVATE_DENY_FCB)) {
2307 if (req == NULL) {
2308 DEBUG(0, ("DOS open without an SMB "
2309 "request!\n"));
2310 TALLOC_FREE(lck);
2311 return NT_STATUS_INTERNAL_ERROR;
2314 /* Use the client requested access mask here,
2315 * not the one we open with. */
2316 status = fcb_or_dos_open(req,
2317 conn,
2318 fsp,
2319 smb_fname,
2321 req->smbpid,
2322 req->vuid,
2323 access_mask,
2324 share_access,
2325 create_options);
2327 if (NT_STATUS_IS_OK(status)) {
2328 TALLOC_FREE(lck);
2329 if (pinfo) {
2330 *pinfo = FILE_WAS_OPENED;
2332 return NT_STATUS_OK;
2337 * This next line is a subtlety we need for
2338 * MS-Access. If a file open will fail due to share
2339 * permissions and also for security (access) reasons,
2340 * we need to return the access failed error, not the
2341 * share error. We can't open the file due to kernel
2342 * oplock deadlock (it's possible we failed above on
2343 * the open_mode_check()) so use a userspace check.
2346 if (flags & O_RDWR) {
2347 can_access_mask = FILE_READ_DATA|FILE_WRITE_DATA;
2348 } else if (flags & O_WRONLY) {
2349 can_access_mask = FILE_WRITE_DATA;
2350 } else {
2351 can_access_mask = FILE_READ_DATA;
2354 if (((can_access_mask & FILE_WRITE_DATA) &&
2355 !CAN_WRITE(conn)) ||
2356 !NT_STATUS_IS_OK(smbd_check_access_rights(conn,
2357 smb_fname, can_access_mask))) {
2358 can_access = False;
2362 * If we're returning a share violation, ensure we
2363 * cope with the braindead 1 second delay (SMB1 only).
2366 if (!(oplock_request & INTERNAL_OPEN_ONLY) &&
2367 !conn->sconn->using_smb2 &&
2368 lp_defer_sharing_violations()) {
2369 struct timeval timeout;
2370 struct deferred_open_record state;
2371 int timeout_usecs;
2373 /* this is a hack to speed up torture tests
2374 in 'make test' */
2375 timeout_usecs = lp_parm_int(SNUM(conn),
2376 "smbd","sharedelay",
2377 SHARING_VIOLATION_USEC_WAIT);
2379 /* This is a relative time, added to the absolute
2380 request_time value to get the absolute timeout time.
2381 Note that if this is the second or greater time we enter
2382 this codepath for this particular request mid then
2383 request_time is left as the absolute time of the *first*
2384 time this request mid was processed. This is what allows
2385 the request to eventually time out. */
2387 timeout = timeval_set(0, timeout_usecs);
2389 /* Nothing actually uses state.delayed_for_oplocks
2390 but it's handy to differentiate in debug messages
2391 between a 30 second delay due to oplock break, and
2392 a 1 second delay for share mode conflicts. */
2394 state.delayed_for_oplocks = False;
2395 state.async_open = false;
2396 state.id = id;
2398 if ((req != NULL)
2399 && !request_timed_out(request_time,
2400 timeout)) {
2401 defer_open(lck, request_time, timeout,
2402 req, &state);
2406 TALLOC_FREE(lck);
2407 if (can_access) {
2409 * We have detected a sharing violation here
2410 * so return the correct error code
2412 status = NT_STATUS_SHARING_VIOLATION;
2413 } else {
2414 status = NT_STATUS_ACCESS_DENIED;
2416 return status;
2420 * We exit this block with the share entry *locked*.....
2424 SMB_ASSERT(!file_existed || (lck != NULL));
2427 * Ensure we pay attention to default ACLs on directories if required.
2430 if ((flags2 & O_CREAT) && lp_inherit_acls(SNUM(conn)) &&
2431 (def_acl = directory_has_default_acl(conn, parent_dir))) {
2432 unx_mode = (0777 & lp_create_mask(SNUM(conn)));
2435 DEBUG(4,("calling open_file with flags=0x%X flags2=0x%X mode=0%o, "
2436 "access_mask = 0x%x, open_access_mask = 0x%x\n",
2437 (unsigned int)flags, (unsigned int)flags2,
2438 (unsigned int)unx_mode, (unsigned int)access_mask,
2439 (unsigned int)open_access_mask));
2441 fsp_open = open_file(fsp, conn, req, parent_dir,
2442 flags|flags2, unx_mode, access_mask,
2443 open_access_mask, &new_file_created);
2445 if (!NT_STATUS_IS_OK(fsp_open)) {
2446 if (NT_STATUS_EQUAL(fsp_open, NT_STATUS_RETRY)) {
2447 schedule_async_open(request_time, req);
2449 TALLOC_FREE(lck);
2450 return fsp_open;
2453 if (file_existed && !check_same_dev_ino(&saved_stat, &smb_fname->st)) {
2455 * The file did exist, but some other (local or NFS)
2456 * process either renamed/unlinked and re-created the
2457 * file with different dev/ino after we walked the path,
2458 * but before we did the open. We could retry the
2459 * open but it's a rare enough case it's easier to
2460 * just fail the open to prevent creating any problems
2461 * in the open file db having the wrong dev/ino key.
2463 TALLOC_FREE(lck);
2464 fd_close(fsp);
2465 DEBUG(1,("open_file_ntcreate: file %s - dev/ino mismatch. "
2466 "Old (dev=0x%llu, ino =0x%llu). "
2467 "New (dev=0x%llu, ino=0x%llu). Failing open "
2468 " with NT_STATUS_ACCESS_DENIED.\n",
2469 smb_fname_str_dbg(smb_fname),
2470 (unsigned long long)saved_stat.st_ex_dev,
2471 (unsigned long long)saved_stat.st_ex_ino,
2472 (unsigned long long)smb_fname->st.st_ex_dev,
2473 (unsigned long long)smb_fname->st.st_ex_ino));
2474 return NT_STATUS_ACCESS_DENIED;
2477 if (!file_existed) {
2478 struct share_mode_entry *batch_entry = NULL;
2479 struct share_mode_entry *exclusive_entry = NULL;
2480 bool got_level2_oplock = false;
2481 bool got_a_none_oplock = false;
2482 struct timespec old_write_time = smb_fname->st.st_ex_mtime;
2483 struct file_id id;
2485 * Deal with the race condition where two smbd's detect the
2486 * file doesn't exist and do the create at the same time. One
2487 * of them will win and set a share mode, the other (ie. this
2488 * one) should check if the requested share mode for this
2489 * create is allowed.
2493 * Now the file exists and fsp is successfully opened,
2494 * fsp->dev and fsp->inode are valid and should replace the
2495 * dev=0,inode=0 from a non existent file. Spotted by
2496 * Nadav Danieli <nadavd@exanet.com>. JRA.
2499 id = fsp->file_id;
2501 lck = get_share_mode_lock(talloc_tos(), id,
2502 conn->connectpath,
2503 smb_fname, &old_write_time);
2505 if (lck == NULL) {
2506 DEBUG(0, ("open_file_ntcreate: Could not get share "
2507 "mode lock for %s\n",
2508 smb_fname_str_dbg(smb_fname)));
2509 fd_close(fsp);
2510 return NT_STATUS_SHARING_VIOLATION;
2513 /* Get the types we need to examine. */
2514 find_oplock_types(fsp,
2515 oplock_request,
2516 lck,
2517 &batch_entry,
2518 &exclusive_entry,
2519 &got_level2_oplock,
2520 &got_a_none_oplock);
2522 /* First pass - send break only on batch oplocks. */
2523 if ((req != NULL) &&
2524 delay_for_batch_oplocks(fsp,
2525 req->mid,
2526 oplock_request,
2527 batch_entry)) {
2528 schedule_defer_open(lck, request_time, req);
2529 TALLOC_FREE(lck);
2530 fd_close(fsp);
2531 return NT_STATUS_SHARING_VIOLATION;
2534 status = open_mode_check(conn, lck, fsp->name_hash,
2535 access_mask, share_access,
2536 create_options, &file_existed);
2538 if (NT_STATUS_IS_OK(status)) {
2539 /* We might be going to allow this open. Check oplock
2540 * status again. */
2541 /* Second pass - send break for both batch or
2542 * exclusive oplocks. */
2543 if ((req != NULL) &&
2544 delay_for_exclusive_oplocks(
2545 fsp,
2546 req->mid,
2547 oplock_request,
2548 exclusive_entry)) {
2549 schedule_defer_open(lck, request_time, req);
2550 TALLOC_FREE(lck);
2551 fd_close(fsp);
2552 return NT_STATUS_SHARING_VIOLATION;
2556 if (!NT_STATUS_IS_OK(status)) {
2557 struct deferred_open_record state;
2559 state.delayed_for_oplocks = False;
2560 state.async_open = false;
2561 state.id = id;
2563 /* Do it all over again immediately. In the second
2564 * round we will find that the file existed and handle
2565 * the DELETE_PENDING and FCB cases correctly. No need
2566 * to duplicate the code here. Essentially this is a
2567 * "goto top of this function", but don't tell
2568 * anybody... */
2570 if (req != NULL) {
2571 defer_open(lck, request_time, timeval_zero(),
2572 req, &state);
2574 TALLOC_FREE(lck);
2575 fd_close(fsp);
2576 return status;
2579 grant_fsp_oplock_type(fsp,
2580 oplock_request,
2581 got_level2_oplock,
2582 got_a_none_oplock);
2585 * We exit this block with the share entry *locked*.....
2590 SMB_ASSERT(lck != NULL);
2592 /* Delete streams if create_disposition requires it */
2593 if (!new_file_created && clear_ads(create_disposition) &&
2594 !is_ntfs_stream_smb_fname(smb_fname)) {
2595 status = delete_all_streams(conn, smb_fname->base_name);
2596 if (!NT_STATUS_IS_OK(status)) {
2597 TALLOC_FREE(lck);
2598 fd_close(fsp);
2599 return status;
2603 /* note that we ignore failure for the following. It is
2604 basically a hack for NFS, and NFS will never set one of
2605 these only read them. Nobody but Samba can ever set a deny
2606 mode and we have already checked our more authoritative
2607 locking database for permission to set this deny mode. If
2608 the kernel refuses the operations then the kernel is wrong.
2609 note that GPFS supports it as well - jmcd */
2611 if (fsp->fh->fd != -1 && lp_kernel_share_modes(SNUM(conn))) {
2612 int ret_flock;
2613 ret_flock = SMB_VFS_KERNEL_FLOCK(fsp, share_access, access_mask);
2614 if(ret_flock == -1 ){
2616 TALLOC_FREE(lck);
2617 fd_close(fsp);
2619 return NT_STATUS_SHARING_VIOLATION;
2624 * At this point onwards, we can guarentee that the share entry
2625 * is locked, whether we created the file or not, and that the
2626 * deny mode is compatible with all current opens.
2630 * According to Samba4, SEC_FILE_READ_ATTRIBUTE is always granted,
2631 * but we don't have to store this - just ignore it on access check.
2633 if (conn->sconn->using_smb2) {
2635 * SMB2 doesn't return it (according to Microsoft tests).
2636 * Test Case: TestSuite_ScenarioNo009GrantedAccessTestS0
2637 * File created with access = 0x7 (Read, Write, Delete)
2638 * Query Info on file returns 0x87 (Read, Write, Delete, Read Attributes)
2640 fsp->access_mask = access_mask;
2641 } else {
2642 /* But SMB1 does. */
2643 fsp->access_mask = access_mask | FILE_READ_ATTRIBUTES;
2646 if (file_existed) {
2647 /* stat opens on existing files don't get oplocks. */
2648 if (is_stat_open(open_access_mask)) {
2649 fsp->oplock_type = NO_OPLOCK;
2653 if (new_file_created) {
2654 info = FILE_WAS_CREATED;
2655 } else {
2656 if (flags2 & O_TRUNC) {
2657 info = FILE_WAS_OVERWRITTEN;
2658 } else {
2659 info = FILE_WAS_OPENED;
2663 if (pinfo) {
2664 *pinfo = info;
2668 * Setup the oplock info in both the shared memory and
2669 * file structs.
2672 status = set_file_oplock(fsp, fsp->oplock_type);
2673 if (!NT_STATUS_IS_OK(status)) {
2675 * Could not get the kernel oplock or there are byte-range
2676 * locks on the file.
2678 fsp->oplock_type = NO_OPLOCK;
2681 set_share_mode(lck, fsp, get_current_uid(conn),
2682 req ? req->mid : 0,
2683 fsp->oplock_type);
2685 /* Handle strange delete on close create semantics. */
2686 if (create_options & FILE_DELETE_ON_CLOSE) {
2688 status = can_set_delete_on_close(fsp, new_dos_attributes);
2690 if (!NT_STATUS_IS_OK(status)) {
2691 /* Remember to delete the mode we just added. */
2692 del_share_mode(lck, fsp);
2693 TALLOC_FREE(lck);
2694 fd_close(fsp);
2695 return status;
2697 /* Note that here we set the *inital* delete on close flag,
2698 not the regular one. The magic gets handled in close. */
2699 fsp->initial_delete_on_close = True;
2702 if (info != FILE_WAS_OPENED) {
2703 /* Files should be initially set as archive */
2704 if (lp_map_archive(SNUM(conn)) ||
2705 lp_store_dos_attributes(SNUM(conn))) {
2706 if (!posix_open) {
2707 if (file_set_dosmode(conn, smb_fname,
2708 new_dos_attributes | FILE_ATTRIBUTE_ARCHIVE,
2709 parent_dir, true) == 0) {
2710 unx_mode = smb_fname->st.st_ex_mode;
2716 /* Determine sparse flag. */
2717 if (posix_open) {
2718 /* POSIX opens are sparse by default. */
2719 fsp->is_sparse = true;
2720 } else {
2721 fsp->is_sparse = (file_existed &&
2722 (existing_dos_attributes & FILE_ATTRIBUTE_SPARSE));
2726 * Take care of inherited ACLs on created files - if default ACL not
2727 * selected.
2730 if (!posix_open && new_file_created && !def_acl) {
2732 int saved_errno = errno; /* We might get ENOSYS in the next
2733 * call.. */
2735 if (SMB_VFS_FCHMOD_ACL(fsp, unx_mode) == -1 &&
2736 errno == ENOSYS) {
2737 errno = saved_errno; /* Ignore ENOSYS */
2740 } else if (new_unx_mode) {
2742 int ret = -1;
2744 /* Attributes need changing. File already existed. */
2747 int saved_errno = errno; /* We might get ENOSYS in the
2748 * next call.. */
2749 ret = SMB_VFS_FCHMOD_ACL(fsp, new_unx_mode);
2751 if (ret == -1 && errno == ENOSYS) {
2752 errno = saved_errno; /* Ignore ENOSYS */
2753 } else {
2754 DEBUG(5, ("open_file_ntcreate: reset "
2755 "attributes of file %s to 0%o\n",
2756 smb_fname_str_dbg(smb_fname),
2757 (unsigned int)new_unx_mode));
2758 ret = 0; /* Don't do the fchmod below. */
2762 if ((ret == -1) &&
2763 (SMB_VFS_FCHMOD(fsp, new_unx_mode) == -1))
2764 DEBUG(5, ("open_file_ntcreate: failed to reset "
2765 "attributes of file %s to 0%o\n",
2766 smb_fname_str_dbg(smb_fname),
2767 (unsigned int)new_unx_mode));
2770 /* If this is a successful open, we must remove any deferred open
2771 * records. */
2772 if (req != NULL) {
2773 del_deferred_open_entry(lck, req->mid,
2774 messaging_server_id(req->sconn->msg_ctx));
2776 TALLOC_FREE(lck);
2778 return NT_STATUS_OK;
2782 /****************************************************************************
2783 Open a file for for write to ensure that we can fchmod it.
2784 ****************************************************************************/
2786 NTSTATUS open_file_fchmod(connection_struct *conn,
2787 struct smb_filename *smb_fname,
2788 files_struct **result)
2790 if (!VALID_STAT(smb_fname->st)) {
2791 return NT_STATUS_INVALID_PARAMETER;
2794 return SMB_VFS_CREATE_FILE(
2795 conn, /* conn */
2796 NULL, /* req */
2797 0, /* root_dir_fid */
2798 smb_fname, /* fname */
2799 FILE_WRITE_DATA, /* access_mask */
2800 (FILE_SHARE_READ | FILE_SHARE_WRITE | /* share_access */
2801 FILE_SHARE_DELETE),
2802 FILE_OPEN, /* create_disposition*/
2803 0, /* create_options */
2804 0, /* file_attributes */
2805 INTERNAL_OPEN_ONLY, /* oplock_request */
2806 0, /* allocation_size */
2807 0, /* private_flags */
2808 NULL, /* sd */
2809 NULL, /* ea_list */
2810 result, /* result */
2811 NULL); /* pinfo */
2814 static NTSTATUS mkdir_internal(connection_struct *conn,
2815 struct smb_filename *smb_dname,
2816 uint32 file_attributes)
2818 mode_t mode;
2819 char *parent_dir = NULL;
2820 NTSTATUS status;
2821 bool posix_open = false;
2822 bool need_re_stat = false;
2823 uint32_t access_mask = SEC_DIR_ADD_SUBDIR;
2825 if (!CAN_WRITE(conn) || (access_mask & ~(conn->share_access))) {
2826 DEBUG(5,("mkdir_internal: failing share access "
2827 "%s\n", lp_servicename(talloc_tos(), SNUM(conn))));
2828 return NT_STATUS_ACCESS_DENIED;
2831 if (!parent_dirname(talloc_tos(), smb_dname->base_name, &parent_dir,
2832 NULL)) {
2833 return NT_STATUS_NO_MEMORY;
2836 if (file_attributes & FILE_FLAG_POSIX_SEMANTICS) {
2837 posix_open = true;
2838 mode = (mode_t)(file_attributes & ~FILE_FLAG_POSIX_SEMANTICS);
2839 } else {
2840 mode = unix_mode(conn, FILE_ATTRIBUTE_DIRECTORY, smb_dname, parent_dir);
2843 status = check_parent_access(conn,
2844 smb_dname,
2845 access_mask);
2846 if(!NT_STATUS_IS_OK(status)) {
2847 DEBUG(5,("mkdir_internal: check_parent_access "
2848 "on directory %s for path %s returned %s\n",
2849 parent_dir,
2850 smb_dname->base_name,
2851 nt_errstr(status) ));
2852 return status;
2855 if (SMB_VFS_MKDIR(conn, smb_dname->base_name, mode) != 0) {
2856 return map_nt_error_from_unix(errno);
2859 /* Ensure we're checking for a symlink here.... */
2860 /* We don't want to get caught by a symlink racer. */
2862 if (SMB_VFS_LSTAT(conn, smb_dname) == -1) {
2863 DEBUG(2, ("Could not stat directory '%s' just created: %s\n",
2864 smb_fname_str_dbg(smb_dname), strerror(errno)));
2865 return map_nt_error_from_unix(errno);
2868 if (!S_ISDIR(smb_dname->st.st_ex_mode)) {
2869 DEBUG(0, ("Directory '%s' just created is not a directory !\n",
2870 smb_fname_str_dbg(smb_dname)));
2871 return NT_STATUS_NOT_A_DIRECTORY;
2874 if (lp_store_dos_attributes(SNUM(conn))) {
2875 if (!posix_open) {
2876 file_set_dosmode(conn, smb_dname,
2877 file_attributes | FILE_ATTRIBUTE_DIRECTORY,
2878 parent_dir, true);
2882 if (lp_inherit_perms(SNUM(conn))) {
2883 inherit_access_posix_acl(conn, parent_dir,
2884 smb_dname->base_name, mode);
2885 need_re_stat = true;
2888 if (!posix_open) {
2890 * Check if high bits should have been set,
2891 * then (if bits are missing): add them.
2892 * Consider bits automagically set by UNIX, i.e. SGID bit from parent
2893 * dir.
2895 if ((mode & ~(S_IRWXU|S_IRWXG|S_IRWXO)) &&
2896 (mode & ~smb_dname->st.st_ex_mode)) {
2897 SMB_VFS_CHMOD(conn, smb_dname->base_name,
2898 (smb_dname->st.st_ex_mode |
2899 (mode & ~smb_dname->st.st_ex_mode)));
2900 need_re_stat = true;
2904 /* Change the owner if required. */
2905 if (lp_inherit_owner(SNUM(conn))) {
2906 change_dir_owner_to_parent(conn, parent_dir,
2907 smb_dname->base_name,
2908 &smb_dname->st);
2909 need_re_stat = true;
2912 if (need_re_stat) {
2913 if (SMB_VFS_LSTAT(conn, smb_dname) == -1) {
2914 DEBUG(2, ("Could not stat directory '%s' just created: %s\n",
2915 smb_fname_str_dbg(smb_dname), strerror(errno)));
2916 return map_nt_error_from_unix(errno);
2920 notify_fname(conn, NOTIFY_ACTION_ADDED, FILE_NOTIFY_CHANGE_DIR_NAME,
2921 smb_dname->base_name);
2923 return NT_STATUS_OK;
2926 /****************************************************************************
2927 Open a directory from an NT SMB call.
2928 ****************************************************************************/
2930 static NTSTATUS open_directory(connection_struct *conn,
2931 struct smb_request *req,
2932 struct smb_filename *smb_dname,
2933 uint32 access_mask,
2934 uint32 share_access,
2935 uint32 create_disposition,
2936 uint32 create_options,
2937 uint32 file_attributes,
2938 int *pinfo,
2939 files_struct **result)
2941 files_struct *fsp = NULL;
2942 bool dir_existed = VALID_STAT(smb_dname->st) ? True : False;
2943 struct share_mode_lock *lck = NULL;
2944 NTSTATUS status;
2945 struct timespec mtimespec;
2946 int info = 0;
2948 if (is_ntfs_stream_smb_fname(smb_dname)) {
2949 DEBUG(2, ("open_directory: %s is a stream name!\n",
2950 smb_fname_str_dbg(smb_dname)));
2951 return NT_STATUS_NOT_A_DIRECTORY;
2954 if (!(file_attributes & FILE_FLAG_POSIX_SEMANTICS)) {
2955 /* Ensure we have a directory attribute. */
2956 file_attributes |= FILE_ATTRIBUTE_DIRECTORY;
2959 DEBUG(5,("open_directory: opening directory %s, access_mask = 0x%x, "
2960 "share_access = 0x%x create_options = 0x%x, "
2961 "create_disposition = 0x%x, file_attributes = 0x%x\n",
2962 smb_fname_str_dbg(smb_dname),
2963 (unsigned int)access_mask,
2964 (unsigned int)share_access,
2965 (unsigned int)create_options,
2966 (unsigned int)create_disposition,
2967 (unsigned int)file_attributes));
2969 status = smbd_calculate_access_mask(conn, smb_dname,
2970 access_mask, &access_mask);
2971 if (!NT_STATUS_IS_OK(status)) {
2972 DEBUG(10, ("open_directory: smbd_calculate_access_mask "
2973 "on file %s returned %s\n",
2974 smb_fname_str_dbg(smb_dname),
2975 nt_errstr(status)));
2976 return status;
2979 if ((access_mask & SEC_FLAG_SYSTEM_SECURITY) &&
2980 !security_token_has_privilege(get_current_nttok(conn),
2981 SEC_PRIV_SECURITY)) {
2982 DEBUG(10, ("open_directory: open on %s "
2983 "failed - SEC_FLAG_SYSTEM_SECURITY denied.\n",
2984 smb_fname_str_dbg(smb_dname)));
2985 return NT_STATUS_PRIVILEGE_NOT_HELD;
2988 switch( create_disposition ) {
2989 case FILE_OPEN:
2991 if (!dir_existed) {
2992 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
2995 info = FILE_WAS_OPENED;
2996 break;
2998 case FILE_CREATE:
3000 /* If directory exists error. If directory doesn't
3001 * exist create. */
3003 if (dir_existed) {
3004 status = NT_STATUS_OBJECT_NAME_COLLISION;
3005 DEBUG(2, ("open_directory: unable to create "
3006 "%s. Error was %s\n",
3007 smb_fname_str_dbg(smb_dname),
3008 nt_errstr(status)));
3009 return status;
3012 status = mkdir_internal(conn, smb_dname,
3013 file_attributes);
3015 if (!NT_STATUS_IS_OK(status)) {
3016 DEBUG(2, ("open_directory: unable to create "
3017 "%s. Error was %s\n",
3018 smb_fname_str_dbg(smb_dname),
3019 nt_errstr(status)));
3020 return status;
3023 info = FILE_WAS_CREATED;
3024 break;
3026 case FILE_OPEN_IF:
3028 * If directory exists open. If directory doesn't
3029 * exist create.
3032 if (dir_existed) {
3033 status = NT_STATUS_OK;
3034 info = FILE_WAS_OPENED;
3035 } else {
3036 status = mkdir_internal(conn, smb_dname,
3037 file_attributes);
3039 if (NT_STATUS_IS_OK(status)) {
3040 info = FILE_WAS_CREATED;
3041 } else {
3042 /* Cope with create race. */
3043 if (!NT_STATUS_EQUAL(status,
3044 NT_STATUS_OBJECT_NAME_COLLISION)) {
3045 DEBUG(2, ("open_directory: unable to create "
3046 "%s. Error was %s\n",
3047 smb_fname_str_dbg(smb_dname),
3048 nt_errstr(status)));
3049 return status;
3051 info = FILE_WAS_OPENED;
3055 break;
3057 case FILE_SUPERSEDE:
3058 case FILE_OVERWRITE:
3059 case FILE_OVERWRITE_IF:
3060 default:
3061 DEBUG(5,("open_directory: invalid create_disposition "
3062 "0x%x for directory %s\n",
3063 (unsigned int)create_disposition,
3064 smb_fname_str_dbg(smb_dname)));
3065 return NT_STATUS_INVALID_PARAMETER;
3068 if(!S_ISDIR(smb_dname->st.st_ex_mode)) {
3069 DEBUG(5,("open_directory: %s is not a directory !\n",
3070 smb_fname_str_dbg(smb_dname)));
3071 return NT_STATUS_NOT_A_DIRECTORY;
3074 if (info == FILE_WAS_OPENED) {
3075 status = smbd_check_access_rights(conn, smb_dname, access_mask);
3076 if (!NT_STATUS_IS_OK(status)) {
3077 DEBUG(10, ("open_directory: smbd_check_access_rights on "
3078 "file %s failed with %s\n",
3079 smb_fname_str_dbg(smb_dname),
3080 nt_errstr(status)));
3081 return status;
3085 status = file_new(req, conn, &fsp);
3086 if(!NT_STATUS_IS_OK(status)) {
3087 return status;
3091 * Setup the files_struct for it.
3094 fsp->file_id = vfs_file_id_from_sbuf(conn, &smb_dname->st);
3095 fsp->vuid = req ? req->vuid : UID_FIELD_INVALID;
3096 fsp->file_pid = req ? req->smbpid : 0;
3097 fsp->can_lock = False;
3098 fsp->can_read = False;
3099 fsp->can_write = False;
3101 fsp->share_access = share_access;
3102 fsp->fh->private_options = 0;
3104 * According to Samba4, SEC_FILE_READ_ATTRIBUTE is always granted,
3106 fsp->access_mask = access_mask | FILE_READ_ATTRIBUTES;
3107 fsp->print_file = NULL;
3108 fsp->modified = False;
3109 fsp->oplock_type = NO_OPLOCK;
3110 fsp->sent_oplock_break = NO_BREAK_SENT;
3111 fsp->is_directory = True;
3112 fsp->posix_open = (file_attributes & FILE_FLAG_POSIX_SEMANTICS) ? True : False;
3113 status = fsp_set_smb_fname(fsp, smb_dname);
3114 if (!NT_STATUS_IS_OK(status)) {
3115 file_free(req, fsp);
3116 return status;
3119 mtimespec = smb_dname->st.st_ex_mtime;
3121 #ifdef O_DIRECTORY
3122 status = fd_open(conn, fsp, O_RDONLY|O_DIRECTORY, 0);
3123 #else
3124 /* POSIX allows us to open a directory with O_RDONLY. */
3125 status = fd_open(conn, fsp, O_RDONLY, 0);
3126 #endif
3127 if (!NT_STATUS_IS_OK(status)) {
3128 DEBUG(5, ("open_directory: Could not open fd for "
3129 "%s (%s)\n",
3130 smb_fname_str_dbg(smb_dname),
3131 nt_errstr(status)));
3132 file_free(req, fsp);
3133 return status;
3136 status = vfs_stat_fsp(fsp);
3137 if (!NT_STATUS_IS_OK(status)) {
3138 fd_close(fsp);
3139 file_free(req, fsp);
3140 return status;
3143 /* Ensure there was no race condition. */
3144 if (!check_same_stat(&smb_dname->st, &fsp->fsp_name->st)) {
3145 DEBUG(5,("open_directory: stat struct differs for "
3146 "directory %s.\n",
3147 smb_fname_str_dbg(smb_dname)));
3148 fd_close(fsp);
3149 file_free(req, fsp);
3150 return NT_STATUS_ACCESS_DENIED;
3153 lck = get_share_mode_lock(talloc_tos(), fsp->file_id,
3154 conn->connectpath, smb_dname,
3155 &mtimespec);
3157 if (lck == NULL) {
3158 DEBUG(0, ("open_directory: Could not get share mode lock for "
3159 "%s\n", smb_fname_str_dbg(smb_dname)));
3160 fd_close(fsp);
3161 file_free(req, fsp);
3162 return NT_STATUS_SHARING_VIOLATION;
3165 status = open_mode_check(conn, lck, fsp->name_hash,
3166 access_mask, share_access,
3167 create_options, &dir_existed);
3169 if (!NT_STATUS_IS_OK(status)) {
3170 TALLOC_FREE(lck);
3171 fd_close(fsp);
3172 file_free(req, fsp);
3173 return status;
3176 set_share_mode(lck, fsp, get_current_uid(conn),
3177 req ? req->mid : 0, NO_OPLOCK);
3179 /* For directories the delete on close bit at open time seems
3180 always to be honored on close... See test 19 in Samba4 BASE-DELETE. */
3181 if (create_options & FILE_DELETE_ON_CLOSE) {
3182 status = can_set_delete_on_close(fsp, 0);
3183 if (!NT_STATUS_IS_OK(status) && !NT_STATUS_EQUAL(status, NT_STATUS_DIRECTORY_NOT_EMPTY)) {
3184 TALLOC_FREE(lck);
3185 fd_close(fsp);
3186 file_free(req, fsp);
3187 return status;
3190 if (NT_STATUS_IS_OK(status)) {
3191 /* Note that here we set the *inital* delete on close flag,
3192 not the regular one. The magic gets handled in close. */
3193 fsp->initial_delete_on_close = True;
3197 TALLOC_FREE(lck);
3199 if (pinfo) {
3200 *pinfo = info;
3203 *result = fsp;
3204 return NT_STATUS_OK;
3207 NTSTATUS create_directory(connection_struct *conn, struct smb_request *req,
3208 struct smb_filename *smb_dname)
3210 NTSTATUS status;
3211 files_struct *fsp;
3213 status = SMB_VFS_CREATE_FILE(
3214 conn, /* conn */
3215 req, /* req */
3216 0, /* root_dir_fid */
3217 smb_dname, /* fname */
3218 FILE_READ_ATTRIBUTES, /* access_mask */
3219 FILE_SHARE_NONE, /* share_access */
3220 FILE_CREATE, /* create_disposition*/
3221 FILE_DIRECTORY_FILE, /* create_options */
3222 FILE_ATTRIBUTE_DIRECTORY, /* file_attributes */
3223 0, /* oplock_request */
3224 0, /* allocation_size */
3225 0, /* private_flags */
3226 NULL, /* sd */
3227 NULL, /* ea_list */
3228 &fsp, /* result */
3229 NULL); /* pinfo */
3231 if (NT_STATUS_IS_OK(status)) {
3232 close_file(req, fsp, NORMAL_CLOSE);
3235 return status;
3238 /****************************************************************************
3239 Receive notification that one of our open files has been renamed by another
3240 smbd process.
3241 ****************************************************************************/
3243 void msg_file_was_renamed(struct messaging_context *msg,
3244 void *private_data,
3245 uint32_t msg_type,
3246 struct server_id server_id,
3247 DATA_BLOB *data)
3249 files_struct *fsp;
3250 char *frm = (char *)data->data;
3251 struct file_id id;
3252 const char *sharepath;
3253 const char *base_name;
3254 const char *stream_name;
3255 struct smb_filename *smb_fname = NULL;
3256 size_t sp_len, bn_len;
3257 NTSTATUS status;
3258 struct smbd_server_connection *sconn =
3259 talloc_get_type_abort(private_data,
3260 struct smbd_server_connection);
3262 if (data->data == NULL
3263 || data->length < MSG_FILE_RENAMED_MIN_SIZE + 2) {
3264 DEBUG(0, ("msg_file_was_renamed: Got invalid msg len %d\n",
3265 (int)data->length));
3266 return;
3269 /* Unpack the message. */
3270 pull_file_id_24(frm, &id);
3271 sharepath = &frm[24];
3272 sp_len = strlen(sharepath);
3273 base_name = sharepath + sp_len + 1;
3274 bn_len = strlen(base_name);
3275 stream_name = sharepath + sp_len + 1 + bn_len + 1;
3277 /* stream_name must always be NULL if there is no stream. */
3278 if (stream_name[0] == '\0') {
3279 stream_name = NULL;
3282 status = create_synthetic_smb_fname(talloc_tos(), base_name,
3283 stream_name, NULL, &smb_fname);
3284 if (!NT_STATUS_IS_OK(status)) {
3285 return;
3288 DEBUG(10,("msg_file_was_renamed: Got rename message for sharepath %s, new name %s, "
3289 "file_id %s\n",
3290 sharepath, smb_fname_str_dbg(smb_fname),
3291 file_id_string_tos(&id)));
3293 for(fsp = file_find_di_first(sconn, id); fsp;
3294 fsp = file_find_di_next(fsp)) {
3295 if (memcmp(fsp->conn->connectpath, sharepath, sp_len) == 0) {
3297 DEBUG(10,("msg_file_was_renamed: renaming file %s from %s -> %s\n",
3298 fsp_fnum_dbg(fsp), fsp_str_dbg(fsp),
3299 smb_fname_str_dbg(smb_fname)));
3300 status = fsp_set_smb_fname(fsp, smb_fname);
3301 if (!NT_STATUS_IS_OK(status)) {
3302 goto out;
3304 } else {
3305 /* TODO. JRA. */
3306 /* Now we have the complete path we can work out if this is
3307 actually within this share and adjust newname accordingly. */
3308 DEBUG(10,("msg_file_was_renamed: share mismatch (sharepath %s "
3309 "not sharepath %s) "
3310 "%s from %s -> %s\n",
3311 fsp->conn->connectpath,
3312 sharepath,
3313 fsp_fnum_dbg(fsp),
3314 fsp_str_dbg(fsp),
3315 smb_fname_str_dbg(smb_fname)));
3318 out:
3319 TALLOC_FREE(smb_fname);
3320 return;
3324 * If a main file is opened for delete, all streams need to be checked for
3325 * !FILE_SHARE_DELETE. Do this by opening with DELETE_ACCESS.
3326 * If that works, delete them all by setting the delete on close and close.
3329 NTSTATUS open_streams_for_delete(connection_struct *conn,
3330 const char *fname)
3332 struct stream_struct *stream_info = NULL;
3333 files_struct **streams = NULL;
3334 int i;
3335 unsigned int num_streams = 0;
3336 TALLOC_CTX *frame = talloc_stackframe();
3337 NTSTATUS status;
3339 status = vfs_streaminfo(conn, NULL, fname, talloc_tos(),
3340 &num_streams, &stream_info);
3342 if (NT_STATUS_EQUAL(status, NT_STATUS_NOT_IMPLEMENTED)
3343 || NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
3344 DEBUG(10, ("no streams around\n"));
3345 TALLOC_FREE(frame);
3346 return NT_STATUS_OK;
3349 if (!NT_STATUS_IS_OK(status)) {
3350 DEBUG(10, ("vfs_streaminfo failed: %s\n",
3351 nt_errstr(status)));
3352 goto fail;
3355 DEBUG(10, ("open_streams_for_delete found %d streams\n",
3356 num_streams));
3358 if (num_streams == 0) {
3359 TALLOC_FREE(frame);
3360 return NT_STATUS_OK;
3363 streams = talloc_array(talloc_tos(), files_struct *, num_streams);
3364 if (streams == NULL) {
3365 DEBUG(0, ("talloc failed\n"));
3366 status = NT_STATUS_NO_MEMORY;
3367 goto fail;
3370 for (i=0; i<num_streams; i++) {
3371 struct smb_filename *smb_fname = NULL;
3373 if (strequal(stream_info[i].name, "::$DATA")) {
3374 streams[i] = NULL;
3375 continue;
3378 status = create_synthetic_smb_fname(talloc_tos(), fname,
3379 stream_info[i].name,
3380 NULL, &smb_fname);
3381 if (!NT_STATUS_IS_OK(status)) {
3382 goto fail;
3385 if (SMB_VFS_STAT(conn, smb_fname) == -1) {
3386 DEBUG(10, ("Unable to stat stream: %s\n",
3387 smb_fname_str_dbg(smb_fname)));
3390 status = SMB_VFS_CREATE_FILE(
3391 conn, /* conn */
3392 NULL, /* req */
3393 0, /* root_dir_fid */
3394 smb_fname, /* fname */
3395 DELETE_ACCESS, /* access_mask */
3396 (FILE_SHARE_READ | /* share_access */
3397 FILE_SHARE_WRITE | FILE_SHARE_DELETE),
3398 FILE_OPEN, /* create_disposition*/
3399 0, /* create_options */
3400 FILE_ATTRIBUTE_NORMAL, /* file_attributes */
3401 0, /* oplock_request */
3402 0, /* allocation_size */
3403 NTCREATEX_OPTIONS_PRIVATE_STREAM_DELETE, /* private_flags */
3404 NULL, /* sd */
3405 NULL, /* ea_list */
3406 &streams[i], /* result */
3407 NULL); /* pinfo */
3409 if (!NT_STATUS_IS_OK(status)) {
3410 DEBUG(10, ("Could not open stream %s: %s\n",
3411 smb_fname_str_dbg(smb_fname),
3412 nt_errstr(status)));
3414 TALLOC_FREE(smb_fname);
3415 break;
3417 TALLOC_FREE(smb_fname);
3421 * don't touch the variable "status" beyond this point :-)
3424 for (i -= 1 ; i >= 0; i--) {
3425 if (streams[i] == NULL) {
3426 continue;
3429 DEBUG(10, ("Closing stream # %d, %s\n", i,
3430 fsp_str_dbg(streams[i])));
3431 close_file(NULL, streams[i], NORMAL_CLOSE);
3434 fail:
3435 TALLOC_FREE(frame);
3436 return status;
3439 /*********************************************************************
3440 Create a default ACL by inheriting from the parent. If no inheritance
3441 from the parent available, don't set anything. This will leave the actual
3442 permissions the new file or directory already got from the filesystem
3443 as the NT ACL when read.
3444 *********************************************************************/
3446 static NTSTATUS inherit_new_acl(files_struct *fsp)
3448 TALLOC_CTX *frame = talloc_stackframe();
3449 char *parent_name = NULL;
3450 struct security_descriptor *parent_desc = NULL;
3451 NTSTATUS status = NT_STATUS_OK;
3452 struct security_descriptor *psd = NULL;
3453 const struct dom_sid *owner_sid = NULL;
3454 const struct dom_sid *group_sid = NULL;
3455 uint32_t security_info_sent = (SECINFO_OWNER | SECINFO_GROUP | SECINFO_DACL);
3456 struct security_token *token = fsp->conn->session_info->security_token;
3457 bool inherit_owner = lp_inherit_owner(SNUM(fsp->conn));
3458 bool inheritable_components = false;
3459 bool try_builtin_administrators = false;
3460 const struct dom_sid *BA_U_sid = NULL;
3461 const struct dom_sid *BA_G_sid = NULL;
3462 bool try_system = false;
3463 const struct dom_sid *SY_U_sid = NULL;
3464 const struct dom_sid *SY_G_sid = NULL;
3465 size_t size = 0;
3467 if (!parent_dirname(frame, fsp->fsp_name->base_name, &parent_name, NULL)) {
3468 TALLOC_FREE(frame);
3469 return NT_STATUS_NO_MEMORY;
3472 status = SMB_VFS_GET_NT_ACL(fsp->conn,
3473 parent_name,
3474 (SECINFO_OWNER | SECINFO_GROUP | SECINFO_DACL),
3475 frame,
3476 &parent_desc);
3477 if (!NT_STATUS_IS_OK(status)) {
3478 TALLOC_FREE(frame);
3479 return status;
3482 inheritable_components = sd_has_inheritable_components(parent_desc,
3483 fsp->is_directory);
3485 if (!inheritable_components && !inherit_owner) {
3486 TALLOC_FREE(frame);
3487 /* Nothing to inherit and not setting owner. */
3488 return NT_STATUS_OK;
3491 /* Create an inherited descriptor from the parent. */
3493 if (DEBUGLEVEL >= 10) {
3494 DEBUG(10,("inherit_new_acl: parent acl for %s is:\n",
3495 fsp_str_dbg(fsp) ));
3496 NDR_PRINT_DEBUG(security_descriptor, parent_desc);
3499 /* Inherit from parent descriptor if "inherit owner" set. */
3500 if (inherit_owner) {
3501 owner_sid = parent_desc->owner_sid;
3502 group_sid = parent_desc->group_sid;
3505 if (owner_sid == NULL) {
3506 if (security_token_has_builtin_administrators(token)) {
3507 try_builtin_administrators = true;
3508 } else if (security_token_is_system(token)) {
3509 try_builtin_administrators = true;
3510 try_system = true;
3514 if (group_sid == NULL &&
3515 token->num_sids == PRIMARY_GROUP_SID_INDEX)
3517 if (security_token_is_system(token)) {
3518 try_builtin_administrators = true;
3519 try_system = true;
3523 if (try_builtin_administrators) {
3524 struct unixid ids;
3525 bool ok;
3527 ZERO_STRUCT(ids);
3528 ok = sids_to_unixids(&global_sid_Builtin_Administrators, 1, &ids);
3529 if (ok) {
3530 switch (ids.type) {
3531 case ID_TYPE_BOTH:
3532 BA_U_sid = &global_sid_Builtin_Administrators;
3533 BA_G_sid = &global_sid_Builtin_Administrators;
3534 break;
3535 case ID_TYPE_UID:
3536 BA_U_sid = &global_sid_Builtin_Administrators;
3537 break;
3538 case ID_TYPE_GID:
3539 BA_G_sid = &global_sid_Builtin_Administrators;
3540 break;
3541 default:
3542 break;
3547 if (try_system) {
3548 struct unixid ids;
3549 bool ok;
3551 ZERO_STRUCT(ids);
3552 ok = sids_to_unixids(&global_sid_System, 1, &ids);
3553 if (ok) {
3554 switch (ids.type) {
3555 case ID_TYPE_BOTH:
3556 SY_U_sid = &global_sid_System;
3557 SY_G_sid = &global_sid_System;
3558 break;
3559 case ID_TYPE_UID:
3560 SY_U_sid = &global_sid_System;
3561 break;
3562 case ID_TYPE_GID:
3563 SY_G_sid = &global_sid_System;
3564 break;
3565 default:
3566 break;
3571 if (owner_sid == NULL) {
3572 owner_sid = BA_U_sid;
3575 if (owner_sid == NULL) {
3576 owner_sid = SY_U_sid;
3579 if (group_sid == NULL) {
3580 group_sid = SY_G_sid;
3583 if (try_system && group_sid == NULL) {
3584 group_sid = BA_G_sid;
3587 if (owner_sid == NULL) {
3588 owner_sid = &token->sids[PRIMARY_USER_SID_INDEX];
3590 if (group_sid == NULL) {
3591 if (token->num_sids == PRIMARY_GROUP_SID_INDEX) {
3592 group_sid = &token->sids[PRIMARY_USER_SID_INDEX];
3593 } else {
3594 group_sid = &token->sids[PRIMARY_GROUP_SID_INDEX];
3598 status = se_create_child_secdesc(frame,
3599 &psd,
3600 &size,
3601 parent_desc,
3602 owner_sid,
3603 group_sid,
3604 fsp->is_directory);
3605 if (!NT_STATUS_IS_OK(status)) {
3606 TALLOC_FREE(frame);
3607 return status;
3610 /* If inheritable_components == false,
3611 se_create_child_secdesc()
3612 creates a security desriptor with a NULL dacl
3613 entry, but with SEC_DESC_DACL_PRESENT. We need
3614 to remove that flag. */
3616 if (!inheritable_components) {
3617 security_info_sent &= ~SECINFO_DACL;
3618 psd->type &= ~SEC_DESC_DACL_PRESENT;
3621 if (DEBUGLEVEL >= 10) {
3622 DEBUG(10,("inherit_new_acl: child acl for %s is:\n",
3623 fsp_str_dbg(fsp) ));
3624 NDR_PRINT_DEBUG(security_descriptor, psd);
3627 if (inherit_owner) {
3628 /* We need to be root to force this. */
3629 become_root();
3631 status = SMB_VFS_FSET_NT_ACL(fsp,
3632 security_info_sent,
3633 psd);
3634 if (inherit_owner) {
3635 unbecome_root();
3637 TALLOC_FREE(frame);
3638 return status;
3642 * Wrapper around open_file_ntcreate and open_directory
3645 static NTSTATUS create_file_unixpath(connection_struct *conn,
3646 struct smb_request *req,
3647 struct smb_filename *smb_fname,
3648 uint32_t access_mask,
3649 uint32_t share_access,
3650 uint32_t create_disposition,
3651 uint32_t create_options,
3652 uint32_t file_attributes,
3653 uint32_t oplock_request,
3654 uint64_t allocation_size,
3655 uint32_t private_flags,
3656 struct security_descriptor *sd,
3657 struct ea_list *ea_list,
3659 files_struct **result,
3660 int *pinfo)
3662 int info = FILE_WAS_OPENED;
3663 files_struct *base_fsp = NULL;
3664 files_struct *fsp = NULL;
3665 NTSTATUS status;
3667 DEBUG(10,("create_file_unixpath: access_mask = 0x%x "
3668 "file_attributes = 0x%x, share_access = 0x%x, "
3669 "create_disposition = 0x%x create_options = 0x%x "
3670 "oplock_request = 0x%x private_flags = 0x%x "
3671 "ea_list = 0x%p, sd = 0x%p, "
3672 "fname = %s\n",
3673 (unsigned int)access_mask,
3674 (unsigned int)file_attributes,
3675 (unsigned int)share_access,
3676 (unsigned int)create_disposition,
3677 (unsigned int)create_options,
3678 (unsigned int)oplock_request,
3679 (unsigned int)private_flags,
3680 ea_list, sd, smb_fname_str_dbg(smb_fname)));
3682 if (create_options & FILE_OPEN_BY_FILE_ID) {
3683 status = NT_STATUS_NOT_SUPPORTED;
3684 goto fail;
3687 if (create_options & NTCREATEX_OPTIONS_INVALID_PARAM_MASK) {
3688 status = NT_STATUS_INVALID_PARAMETER;
3689 goto fail;
3692 if (req == NULL) {
3693 oplock_request |= INTERNAL_OPEN_ONLY;
3696 if ((conn->fs_capabilities & FILE_NAMED_STREAMS)
3697 && (access_mask & DELETE_ACCESS)
3698 && !is_ntfs_stream_smb_fname(smb_fname)) {
3700 * We can't open a file with DELETE access if any of the
3701 * streams is open without FILE_SHARE_DELETE
3703 status = open_streams_for_delete(conn, smb_fname->base_name);
3705 if (!NT_STATUS_IS_OK(status)) {
3706 goto fail;
3710 if ((access_mask & SEC_FLAG_SYSTEM_SECURITY) &&
3711 !security_token_has_privilege(get_current_nttok(conn),
3712 SEC_PRIV_SECURITY)) {
3713 DEBUG(10, ("create_file_unixpath: open on %s "
3714 "failed - SEC_FLAG_SYSTEM_SECURITY denied.\n",
3715 smb_fname_str_dbg(smb_fname)));
3716 status = NT_STATUS_PRIVILEGE_NOT_HELD;
3717 goto fail;
3720 if ((conn->fs_capabilities & FILE_NAMED_STREAMS)
3721 && is_ntfs_stream_smb_fname(smb_fname)
3722 && (!(private_flags & NTCREATEX_OPTIONS_PRIVATE_STREAM_DELETE))) {
3723 uint32 base_create_disposition;
3724 struct smb_filename *smb_fname_base = NULL;
3726 if (create_options & FILE_DIRECTORY_FILE) {
3727 status = NT_STATUS_NOT_A_DIRECTORY;
3728 goto fail;
3731 switch (create_disposition) {
3732 case FILE_OPEN:
3733 base_create_disposition = FILE_OPEN;
3734 break;
3735 default:
3736 base_create_disposition = FILE_OPEN_IF;
3737 break;
3740 /* Create an smb_filename with stream_name == NULL. */
3741 status = create_synthetic_smb_fname(talloc_tos(),
3742 smb_fname->base_name,
3743 NULL, NULL,
3744 &smb_fname_base);
3745 if (!NT_STATUS_IS_OK(status)) {
3746 goto fail;
3749 if (SMB_VFS_STAT(conn, smb_fname_base) == -1) {
3750 DEBUG(10, ("Unable to stat stream: %s\n",
3751 smb_fname_str_dbg(smb_fname_base)));
3754 /* Open the base file. */
3755 status = create_file_unixpath(conn, NULL, smb_fname_base, 0,
3756 FILE_SHARE_READ
3757 | FILE_SHARE_WRITE
3758 | FILE_SHARE_DELETE,
3759 base_create_disposition,
3760 0, 0, 0, 0, 0, NULL, NULL,
3761 &base_fsp, NULL);
3762 TALLOC_FREE(smb_fname_base);
3764 if (!NT_STATUS_IS_OK(status)) {
3765 DEBUG(10, ("create_file_unixpath for base %s failed: "
3766 "%s\n", smb_fname->base_name,
3767 nt_errstr(status)));
3768 goto fail;
3770 /* we don't need to low level fd */
3771 fd_close(base_fsp);
3775 * If it's a request for a directory open, deal with it separately.
3778 if (create_options & FILE_DIRECTORY_FILE) {
3780 if (create_options & FILE_NON_DIRECTORY_FILE) {
3781 status = NT_STATUS_INVALID_PARAMETER;
3782 goto fail;
3785 /* Can't open a temp directory. IFS kit test. */
3786 if (!(file_attributes & FILE_FLAG_POSIX_SEMANTICS) &&
3787 (file_attributes & FILE_ATTRIBUTE_TEMPORARY)) {
3788 status = NT_STATUS_INVALID_PARAMETER;
3789 goto fail;
3793 * We will get a create directory here if the Win32
3794 * app specified a security descriptor in the
3795 * CreateDirectory() call.
3798 oplock_request = 0;
3799 status = open_directory(
3800 conn, req, smb_fname, access_mask, share_access,
3801 create_disposition, create_options, file_attributes,
3802 &info, &fsp);
3803 } else {
3806 * Ordinary file case.
3809 status = file_new(req, conn, &fsp);
3810 if(!NT_STATUS_IS_OK(status)) {
3811 goto fail;
3814 status = fsp_set_smb_fname(fsp, smb_fname);
3815 if (!NT_STATUS_IS_OK(status)) {
3816 goto fail;
3819 if (base_fsp) {
3821 * We're opening the stream element of a
3822 * base_fsp we already opened. Set up the
3823 * base_fsp pointer.
3825 fsp->base_fsp = base_fsp;
3828 if (allocation_size) {
3829 fsp->initial_allocation_size = smb_roundup(fsp->conn,
3830 allocation_size);
3833 status = open_file_ntcreate(conn,
3834 req,
3835 access_mask,
3836 share_access,
3837 create_disposition,
3838 create_options,
3839 file_attributes,
3840 oplock_request,
3841 private_flags,
3842 &info,
3843 fsp);
3845 if(!NT_STATUS_IS_OK(status)) {
3846 file_free(req, fsp);
3847 fsp = NULL;
3850 if (NT_STATUS_EQUAL(status, NT_STATUS_FILE_IS_A_DIRECTORY)) {
3852 /* A stream open never opens a directory */
3854 if (base_fsp) {
3855 status = NT_STATUS_FILE_IS_A_DIRECTORY;
3856 goto fail;
3860 * Fail the open if it was explicitly a non-directory
3861 * file.
3864 if (create_options & FILE_NON_DIRECTORY_FILE) {
3865 status = NT_STATUS_FILE_IS_A_DIRECTORY;
3866 goto fail;
3869 oplock_request = 0;
3870 status = open_directory(
3871 conn, req, smb_fname, access_mask,
3872 share_access, create_disposition,
3873 create_options, file_attributes,
3874 &info, &fsp);
3878 if (!NT_STATUS_IS_OK(status)) {
3879 goto fail;
3882 fsp->base_fsp = base_fsp;
3884 if ((ea_list != NULL) &&
3885 ((info == FILE_WAS_CREATED) || (info == FILE_WAS_OVERWRITTEN))) {
3886 status = set_ea(conn, fsp, fsp->fsp_name, ea_list);
3887 if (!NT_STATUS_IS_OK(status)) {
3888 goto fail;
3892 if (!fsp->is_directory && S_ISDIR(fsp->fsp_name->st.st_ex_mode)) {
3893 status = NT_STATUS_ACCESS_DENIED;
3894 goto fail;
3897 /* Save the requested allocation size. */
3898 if ((info == FILE_WAS_CREATED) || (info == FILE_WAS_OVERWRITTEN)) {
3899 if (allocation_size
3900 && (allocation_size > fsp->fsp_name->st.st_ex_size)) {
3901 fsp->initial_allocation_size = smb_roundup(
3902 fsp->conn, allocation_size);
3903 if (fsp->is_directory) {
3904 /* Can't set allocation size on a directory. */
3905 status = NT_STATUS_ACCESS_DENIED;
3906 goto fail;
3908 if (vfs_allocate_file_space(
3909 fsp, fsp->initial_allocation_size) == -1) {
3910 status = NT_STATUS_DISK_FULL;
3911 goto fail;
3913 } else {
3914 fsp->initial_allocation_size = smb_roundup(
3915 fsp->conn, (uint64_t)fsp->fsp_name->st.st_ex_size);
3917 } else {
3918 fsp->initial_allocation_size = 0;
3921 if ((info == FILE_WAS_CREATED) && lp_nt_acl_support(SNUM(conn)) &&
3922 fsp->base_fsp == NULL) {
3923 if (sd != NULL) {
3925 * According to the MS documentation, the only time the security
3926 * descriptor is applied to the opened file is iff we *created* the
3927 * file; an existing file stays the same.
3929 * Also, it seems (from observation) that you can open the file with
3930 * any access mask but you can still write the sd. We need to override
3931 * the granted access before we call set_sd
3932 * Patch for bug #2242 from Tom Lackemann <cessnatomny@yahoo.com>.
3935 uint32_t sec_info_sent;
3936 uint32_t saved_access_mask = fsp->access_mask;
3938 sec_info_sent = get_sec_info(sd);
3940 fsp->access_mask = FILE_GENERIC_ALL;
3942 if (sec_info_sent & (SECINFO_OWNER|
3943 SECINFO_GROUP|
3944 SECINFO_DACL|
3945 SECINFO_SACL)) {
3946 status = set_sd(fsp, sd, sec_info_sent);
3949 fsp->access_mask = saved_access_mask;
3951 if (!NT_STATUS_IS_OK(status)) {
3952 goto fail;
3954 } else if (lp_inherit_acls(SNUM(conn))) {
3955 /* Inherit from parent. Errors here are not fatal. */
3956 status = inherit_new_acl(fsp);
3957 if (!NT_STATUS_IS_OK(status)) {
3958 DEBUG(10,("inherit_new_acl: failed for %s with %s\n",
3959 fsp_str_dbg(fsp),
3960 nt_errstr(status) ));
3965 DEBUG(10, ("create_file_unixpath: info=%d\n", info));
3967 *result = fsp;
3968 if (pinfo != NULL) {
3969 *pinfo = info;
3972 smb_fname->st = fsp->fsp_name->st;
3974 return NT_STATUS_OK;
3976 fail:
3977 DEBUG(10, ("create_file_unixpath: %s\n", nt_errstr(status)));
3979 if (fsp != NULL) {
3980 if (base_fsp && fsp->base_fsp == base_fsp) {
3982 * The close_file below will close
3983 * fsp->base_fsp.
3985 base_fsp = NULL;
3987 close_file(req, fsp, ERROR_CLOSE);
3988 fsp = NULL;
3990 if (base_fsp != NULL) {
3991 close_file(req, base_fsp, ERROR_CLOSE);
3992 base_fsp = NULL;
3994 return status;
3998 * Calculate the full path name given a relative fid.
4000 NTSTATUS get_relative_fid_filename(connection_struct *conn,
4001 struct smb_request *req,
4002 uint16_t root_dir_fid,
4003 const struct smb_filename *smb_fname,
4004 struct smb_filename **smb_fname_out)
4006 files_struct *dir_fsp;
4007 char *parent_fname = NULL;
4008 char *new_base_name = NULL;
4009 NTSTATUS status;
4011 if (root_dir_fid == 0 || !smb_fname) {
4012 status = NT_STATUS_INTERNAL_ERROR;
4013 goto out;
4016 dir_fsp = file_fsp(req, root_dir_fid);
4018 if (dir_fsp == NULL) {
4019 status = NT_STATUS_INVALID_HANDLE;
4020 goto out;
4023 if (is_ntfs_stream_smb_fname(dir_fsp->fsp_name)) {
4024 status = NT_STATUS_INVALID_HANDLE;
4025 goto out;
4028 if (!dir_fsp->is_directory) {
4031 * Check to see if this is a mac fork of some kind.
4034 if ((conn->fs_capabilities & FILE_NAMED_STREAMS) &&
4035 is_ntfs_stream_smb_fname(smb_fname)) {
4036 status = NT_STATUS_OBJECT_PATH_NOT_FOUND;
4037 goto out;
4041 we need to handle the case when we get a
4042 relative open relative to a file and the
4043 pathname is blank - this is a reopen!
4044 (hint from demyn plantenberg)
4047 status = NT_STATUS_INVALID_HANDLE;
4048 goto out;
4051 if (ISDOT(dir_fsp->fsp_name->base_name)) {
4053 * We're at the toplevel dir, the final file name
4054 * must not contain ./, as this is filtered out
4055 * normally by srvstr_get_path and unix_convert
4056 * explicitly rejects paths containing ./.
4058 parent_fname = talloc_strdup(talloc_tos(), "");
4059 if (parent_fname == NULL) {
4060 status = NT_STATUS_NO_MEMORY;
4061 goto out;
4063 } else {
4064 size_t dir_name_len = strlen(dir_fsp->fsp_name->base_name);
4067 * Copy in the base directory name.
4070 parent_fname = talloc_array(talloc_tos(), char,
4071 dir_name_len+2);
4072 if (parent_fname == NULL) {
4073 status = NT_STATUS_NO_MEMORY;
4074 goto out;
4076 memcpy(parent_fname, dir_fsp->fsp_name->base_name,
4077 dir_name_len+1);
4080 * Ensure it ends in a '/'.
4081 * We used TALLOC_SIZE +2 to add space for the '/'.
4084 if(dir_name_len
4085 && (parent_fname[dir_name_len-1] != '\\')
4086 && (parent_fname[dir_name_len-1] != '/')) {
4087 parent_fname[dir_name_len] = '/';
4088 parent_fname[dir_name_len+1] = '\0';
4092 new_base_name = talloc_asprintf(talloc_tos(), "%s%s", parent_fname,
4093 smb_fname->base_name);
4094 if (new_base_name == NULL) {
4095 status = NT_STATUS_NO_MEMORY;
4096 goto out;
4099 status = filename_convert(req,
4100 conn,
4101 req->flags2 & FLAGS2_DFS_PATHNAMES,
4102 new_base_name,
4104 NULL,
4105 smb_fname_out);
4106 if (!NT_STATUS_IS_OK(status)) {
4107 goto out;
4110 out:
4111 TALLOC_FREE(parent_fname);
4112 TALLOC_FREE(new_base_name);
4113 return status;
4116 NTSTATUS create_file_default(connection_struct *conn,
4117 struct smb_request *req,
4118 uint16_t root_dir_fid,
4119 struct smb_filename *smb_fname,
4120 uint32_t access_mask,
4121 uint32_t share_access,
4122 uint32_t create_disposition,
4123 uint32_t create_options,
4124 uint32_t file_attributes,
4125 uint32_t oplock_request,
4126 uint64_t allocation_size,
4127 uint32_t private_flags,
4128 struct security_descriptor *sd,
4129 struct ea_list *ea_list,
4130 files_struct **result,
4131 int *pinfo)
4133 int info = FILE_WAS_OPENED;
4134 files_struct *fsp = NULL;
4135 NTSTATUS status;
4136 bool stream_name = false;
4138 DEBUG(10,("create_file: access_mask = 0x%x "
4139 "file_attributes = 0x%x, share_access = 0x%x, "
4140 "create_disposition = 0x%x create_options = 0x%x "
4141 "oplock_request = 0x%x "
4142 "private_flags = 0x%x "
4143 "root_dir_fid = 0x%x, ea_list = 0x%p, sd = 0x%p, "
4144 "fname = %s\n",
4145 (unsigned int)access_mask,
4146 (unsigned int)file_attributes,
4147 (unsigned int)share_access,
4148 (unsigned int)create_disposition,
4149 (unsigned int)create_options,
4150 (unsigned int)oplock_request,
4151 (unsigned int)private_flags,
4152 (unsigned int)root_dir_fid,
4153 ea_list, sd, smb_fname_str_dbg(smb_fname)));
4156 * Calculate the filename from the root_dir_if if necessary.
4159 if (root_dir_fid != 0) {
4160 struct smb_filename *smb_fname_out = NULL;
4161 status = get_relative_fid_filename(conn, req, root_dir_fid,
4162 smb_fname, &smb_fname_out);
4163 if (!NT_STATUS_IS_OK(status)) {
4164 goto fail;
4166 smb_fname = smb_fname_out;
4170 * Check to see if this is a mac fork of some kind.
4173 stream_name = is_ntfs_stream_smb_fname(smb_fname);
4174 if (stream_name) {
4175 enum FAKE_FILE_TYPE fake_file_type;
4177 fake_file_type = is_fake_file(smb_fname);
4179 if (fake_file_type != FAKE_FILE_TYPE_NONE) {
4182 * Here we go! support for changing the disk quotas
4183 * --metze
4185 * We need to fake up to open this MAGIC QUOTA file
4186 * and return a valid FID.
4188 * w2k close this file directly after openening xp
4189 * also tries a QUERY_FILE_INFO on the file and then
4190 * close it
4192 status = open_fake_file(req, conn, req->vuid,
4193 fake_file_type, smb_fname,
4194 access_mask, &fsp);
4195 if (!NT_STATUS_IS_OK(status)) {
4196 goto fail;
4199 ZERO_STRUCT(smb_fname->st);
4200 goto done;
4203 if (!(conn->fs_capabilities & FILE_NAMED_STREAMS)) {
4204 status = NT_STATUS_OBJECT_NAME_NOT_FOUND;
4205 goto fail;
4209 if (is_ntfs_default_stream_smb_fname(smb_fname)) {
4210 int ret;
4211 smb_fname->stream_name = NULL;
4212 /* We have to handle this error here. */
4213 if (create_options & FILE_DIRECTORY_FILE) {
4214 status = NT_STATUS_NOT_A_DIRECTORY;
4215 goto fail;
4217 if (lp_posix_pathnames()) {
4218 ret = SMB_VFS_LSTAT(conn, smb_fname);
4219 } else {
4220 ret = SMB_VFS_STAT(conn, smb_fname);
4223 if (ret == 0 && VALID_STAT_OF_DIR(smb_fname->st)) {
4224 status = NT_STATUS_FILE_IS_A_DIRECTORY;
4225 goto fail;
4229 status = create_file_unixpath(
4230 conn, req, smb_fname, access_mask, share_access,
4231 create_disposition, create_options, file_attributes,
4232 oplock_request, allocation_size, private_flags,
4233 sd, ea_list,
4234 &fsp, &info);
4236 if (!NT_STATUS_IS_OK(status)) {
4237 goto fail;
4240 done:
4241 DEBUG(10, ("create_file: info=%d\n", info));
4243 *result = fsp;
4244 if (pinfo != NULL) {
4245 *pinfo = info;
4247 return NT_STATUS_OK;
4249 fail:
4250 DEBUG(10, ("create_file: %s\n", nt_errstr(status)));
4252 if (fsp != NULL) {
4253 close_file(req, fsp, ERROR_CLOSE);
4254 fsp = NULL;
4256 return status;