Fix bug #10229 - No access check verification on stream files.
[Samba.git] / source3 / smbd / open.c
blob02827224bb672b74bc281c1c68486ec6cc835393
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 Ensure when opening a base file for a stream open that we have permissions
304 to do so given the access mask on the base file.
305 ****************************************************************************/
307 static NTSTATUS check_base_file_access(struct connection_struct *conn,
308 struct smb_filename *smb_fname,
309 uint32_t access_mask)
311 NTSTATUS status;
313 status = smbd_calculate_access_mask(conn, smb_fname,
314 access_mask,
315 &access_mask);
316 if (!NT_STATUS_IS_OK(status)) {
317 DEBUG(10, ("smbd_calculate_access_mask "
318 "on file %s returned %s\n",
319 smb_fname_str_dbg(smb_fname),
320 nt_errstr(status)));
321 return status;
324 if (access_mask & (FILE_WRITE_DATA|FILE_APPEND_DATA)) {
325 uint32_t dosattrs;
326 if (!CAN_WRITE(conn)) {
327 return NT_STATUS_ACCESS_DENIED;
329 dosattrs = dos_mode(conn, smb_fname);
330 if (IS_DOS_READONLY(dosattrs)) {
331 return NT_STATUS_ACCESS_DENIED;
335 return smbd_check_access_rights(conn,
336 smb_fname,
337 access_mask);
340 /****************************************************************************
341 fd support routines - attempt to do a dos_open.
342 ****************************************************************************/
344 NTSTATUS fd_open(struct connection_struct *conn,
345 files_struct *fsp,
346 int flags,
347 mode_t mode)
349 struct smb_filename *smb_fname = fsp->fsp_name;
350 NTSTATUS status = NT_STATUS_OK;
352 #ifdef O_NOFOLLOW
354 * Never follow symlinks on a POSIX client. The
355 * client should be doing this.
358 if (fsp->posix_open || !lp_symlinks(SNUM(conn))) {
359 flags |= O_NOFOLLOW;
361 #endif
363 fsp->fh->fd = SMB_VFS_OPEN(conn, smb_fname, fsp, flags, mode);
364 if (fsp->fh->fd == -1) {
365 int posix_errno = errno;
366 #ifdef O_NOFOLLOW
367 #if defined(ENOTSUP) && defined(OSF1)
368 /* handle special Tru64 errno */
369 if (errno == ENOTSUP) {
370 posix_errno = ELOOP;
372 #endif /* ENOTSUP */
373 #ifdef EFTYPE
374 /* fix broken NetBSD errno */
375 if (errno == EFTYPE) {
376 posix_errno = ELOOP;
378 #endif /* EFTYPE */
379 /* fix broken FreeBSD errno */
380 if (errno == EMLINK) {
381 posix_errno = ELOOP;
383 #endif /* O_NOFOLLOW */
384 status = map_nt_error_from_unix(posix_errno);
385 if (errno == EMFILE) {
386 static time_t last_warned = 0L;
388 if (time((time_t *) NULL) > last_warned) {
389 DEBUG(0,("Too many open files, unable "
390 "to open more! smbd's max "
391 "open files = %d\n",
392 lp_max_open_files()));
393 last_warned = time((time_t *) NULL);
399 DEBUG(10,("fd_open: name %s, flags = 0%o mode = 0%o, fd = %d. %s\n",
400 smb_fname_str_dbg(smb_fname), flags, (int)mode, fsp->fh->fd,
401 (fsp->fh->fd == -1) ? strerror(errno) : "" ));
403 return status;
406 /****************************************************************************
407 Close the file associated with a fsp.
408 ****************************************************************************/
410 NTSTATUS fd_close(files_struct *fsp)
412 int ret;
414 if (fsp->dptr) {
415 dptr_CloseDir(fsp);
417 if (fsp->fh->fd == -1) {
418 return NT_STATUS_OK; /* What we used to call a stat open. */
420 if (fsp->fh->ref_count > 1) {
421 return NT_STATUS_OK; /* Shared handle. Only close last reference. */
424 ret = SMB_VFS_CLOSE(fsp);
425 fsp->fh->fd = -1;
426 if (ret == -1) {
427 return map_nt_error_from_unix(errno);
429 return NT_STATUS_OK;
432 /****************************************************************************
433 Change the ownership of a file to that of the parent directory.
434 Do this by fd if possible.
435 ****************************************************************************/
437 void change_file_owner_to_parent(connection_struct *conn,
438 const char *inherit_from_dir,
439 files_struct *fsp)
441 struct smb_filename *smb_fname_parent = NULL;
442 NTSTATUS status;
443 int ret;
445 status = create_synthetic_smb_fname(talloc_tos(), inherit_from_dir,
446 NULL, NULL, &smb_fname_parent);
447 if (!NT_STATUS_IS_OK(status)) {
448 return;
451 ret = SMB_VFS_STAT(conn, smb_fname_parent);
452 if (ret == -1) {
453 DEBUG(0,("change_file_owner_to_parent: failed to stat parent "
454 "directory %s. Error was %s\n",
455 smb_fname_str_dbg(smb_fname_parent),
456 strerror(errno)));
457 TALLOC_FREE(smb_fname_parent);
458 return;
461 if (smb_fname_parent->st.st_ex_uid == fsp->fsp_name->st.st_ex_uid) {
462 /* Already this uid - no need to change. */
463 DEBUG(10,("change_file_owner_to_parent: file %s "
464 "is already owned by uid %d\n",
465 fsp_str_dbg(fsp),
466 (int)fsp->fsp_name->st.st_ex_uid ));
467 TALLOC_FREE(smb_fname_parent);
468 return;
471 become_root();
472 ret = SMB_VFS_FCHOWN(fsp, smb_fname_parent->st.st_ex_uid, (gid_t)-1);
473 unbecome_root();
474 if (ret == -1) {
475 DEBUG(0,("change_file_owner_to_parent: failed to fchown "
476 "file %s to parent directory uid %u. Error "
477 "was %s\n", fsp_str_dbg(fsp),
478 (unsigned int)smb_fname_parent->st.st_ex_uid,
479 strerror(errno) ));
480 } else {
481 DEBUG(10,("change_file_owner_to_parent: changed new file %s to "
482 "parent directory uid %u.\n", fsp_str_dbg(fsp),
483 (unsigned int)smb_fname_parent->st.st_ex_uid));
484 /* Ensure the uid entry is updated. */
485 fsp->fsp_name->st.st_ex_uid = smb_fname_parent->st.st_ex_uid;
488 TALLOC_FREE(smb_fname_parent);
491 NTSTATUS change_dir_owner_to_parent(connection_struct *conn,
492 const char *inherit_from_dir,
493 const char *fname,
494 SMB_STRUCT_STAT *psbuf)
496 struct smb_filename *smb_fname_parent = NULL;
497 struct smb_filename *smb_fname_cwd = NULL;
498 char *saved_dir = NULL;
499 TALLOC_CTX *ctx = talloc_tos();
500 NTSTATUS status = NT_STATUS_OK;
501 int ret;
503 status = create_synthetic_smb_fname(ctx, inherit_from_dir, NULL, NULL,
504 &smb_fname_parent);
505 if (!NT_STATUS_IS_OK(status)) {
506 return status;
509 ret = SMB_VFS_STAT(conn, smb_fname_parent);
510 if (ret == -1) {
511 status = map_nt_error_from_unix(errno);
512 DEBUG(0,("change_dir_owner_to_parent: failed to stat parent "
513 "directory %s. Error was %s\n",
514 smb_fname_str_dbg(smb_fname_parent),
515 strerror(errno)));
516 goto out;
519 /* We've already done an lstat into psbuf, and we know it's a
520 directory. If we can cd into the directory and the dev/ino
521 are the same then we can safely chown without races as
522 we're locking the directory in place by being in it. This
523 should work on any UNIX (thanks tridge :-). JRA.
526 saved_dir = vfs_GetWd(ctx,conn);
527 if (!saved_dir) {
528 status = map_nt_error_from_unix(errno);
529 DEBUG(0,("change_dir_owner_to_parent: failed to get "
530 "current working directory. Error was %s\n",
531 strerror(errno)));
532 goto out;
535 /* Chdir into the new path. */
536 if (vfs_ChDir(conn, fname) == -1) {
537 status = map_nt_error_from_unix(errno);
538 DEBUG(0,("change_dir_owner_to_parent: failed to change "
539 "current working directory to %s. Error "
540 "was %s\n", fname, strerror(errno) ));
541 goto chdir;
544 status = create_synthetic_smb_fname(ctx, ".", NULL, NULL,
545 &smb_fname_cwd);
546 if (!NT_STATUS_IS_OK(status)) {
547 return status;
550 ret = SMB_VFS_STAT(conn, smb_fname_cwd);
551 if (ret == -1) {
552 status = map_nt_error_from_unix(errno);
553 DEBUG(0,("change_dir_owner_to_parent: failed to stat "
554 "directory '.' (%s) Error was %s\n",
555 fname, strerror(errno)));
556 goto chdir;
559 /* Ensure we're pointing at the same place. */
560 if (smb_fname_cwd->st.st_ex_dev != psbuf->st_ex_dev ||
561 smb_fname_cwd->st.st_ex_ino != psbuf->st_ex_ino) {
562 DEBUG(0,("change_dir_owner_to_parent: "
563 "device/inode on directory %s changed. "
564 "Refusing to chown !\n", fname ));
565 status = NT_STATUS_ACCESS_DENIED;
566 goto chdir;
569 if (smb_fname_parent->st.st_ex_uid == smb_fname_cwd->st.st_ex_uid) {
570 /* Already this uid - no need to change. */
571 DEBUG(10,("change_dir_owner_to_parent: directory %s "
572 "is already owned by uid %d\n",
573 fname,
574 (int)smb_fname_cwd->st.st_ex_uid ));
575 status = NT_STATUS_OK;
576 goto chdir;
579 become_root();
580 ret = SMB_VFS_LCHOWN(conn, ".", smb_fname_parent->st.st_ex_uid,
581 (gid_t)-1);
582 unbecome_root();
583 if (ret == -1) {
584 status = map_nt_error_from_unix(errno);
585 DEBUG(10,("change_dir_owner_to_parent: failed to chown "
586 "directory %s to parent directory uid %u. "
587 "Error was %s\n", fname,
588 (unsigned int)smb_fname_parent->st.st_ex_uid,
589 strerror(errno) ));
590 } else {
591 DEBUG(10,("change_dir_owner_to_parent: changed ownership of new "
592 "directory %s to parent directory uid %u.\n",
593 fname, (unsigned int)smb_fname_parent->st.st_ex_uid ));
594 /* Ensure the uid entry is updated. */
595 psbuf->st_ex_uid = smb_fname_parent->st.st_ex_uid;
598 chdir:
599 vfs_ChDir(conn,saved_dir);
600 out:
601 TALLOC_FREE(smb_fname_parent);
602 TALLOC_FREE(smb_fname_cwd);
603 return status;
606 /****************************************************************************
607 Open a file - returning a guaranteed ATOMIC indication of if the
608 file was created or not.
609 ****************************************************************************/
611 static NTSTATUS fd_open_atomic(struct connection_struct *conn,
612 files_struct *fsp,
613 int flags,
614 mode_t mode,
615 bool *file_created)
617 NTSTATUS status = NT_STATUS_UNSUCCESSFUL;
618 bool file_existed = VALID_STAT(fsp->fsp_name->st);
620 *file_created = false;
622 if (!(flags & O_CREAT)) {
624 * We're not creating the file, just pass through.
626 return fd_open(conn, fsp, flags, mode);
629 if (flags & O_EXCL) {
631 * Fail if already exists, just pass through.
633 status = fd_open(conn, fsp, flags, mode);
636 * Here we've opened with O_CREAT|O_EXCL. If that went
637 * NT_STATUS_OK, we *know* we created this file.
639 *file_created = NT_STATUS_IS_OK(status);
641 return status;
645 * Now it gets tricky. We have O_CREAT, but not O_EXCL.
646 * To know absolutely if we created the file or not,
647 * we can never call O_CREAT without O_EXCL. So if
648 * we think the file existed, try without O_CREAT|O_EXCL.
649 * If we think the file didn't exist, try with
650 * O_CREAT|O_EXCL. Keep bouncing between these two
651 * requests until either the file is created, or
652 * opened. Either way, we keep going until we get
653 * a returnable result (error, or open/create).
656 while(1) {
657 int curr_flags = flags;
659 if (file_existed) {
660 /* Just try open, do not create. */
661 curr_flags &= ~(O_CREAT);
662 status = fd_open(conn, fsp, curr_flags, mode);
663 if (NT_STATUS_EQUAL(status,
664 NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
666 * Someone deleted it in the meantime.
667 * Retry with O_EXCL.
669 file_existed = false;
670 DEBUG(10,("fd_open_atomic: file %s existed. "
671 "Retry.\n",
672 smb_fname_str_dbg(fsp->fsp_name)));
673 continue;
675 } else {
676 /* Try create exclusively, fail if it exists. */
677 curr_flags |= O_EXCL;
678 status = fd_open(conn, fsp, curr_flags, mode);
679 if (NT_STATUS_EQUAL(status,
680 NT_STATUS_OBJECT_NAME_COLLISION)) {
682 * Someone created it in the meantime.
683 * Retry without O_CREAT.
685 file_existed = true;
686 DEBUG(10,("fd_open_atomic: file %s "
687 "did not exist. Retry.\n",
688 smb_fname_str_dbg(fsp->fsp_name)));
689 continue;
691 if (NT_STATUS_IS_OK(status)) {
693 * Here we've opened with O_CREAT|O_EXCL
694 * and got success. We *know* we created
695 * this file.
697 *file_created = true;
700 /* Create is done, or failed. */
701 break;
703 return status;
706 /****************************************************************************
707 Open a file.
708 ****************************************************************************/
710 static NTSTATUS open_file(files_struct *fsp,
711 connection_struct *conn,
712 struct smb_request *req,
713 const char *parent_dir,
714 int flags,
715 mode_t unx_mode,
716 uint32 access_mask, /* client requested access mask. */
717 uint32 open_access_mask, /* what we're actually using in the open. */
718 bool *p_file_created)
720 struct smb_filename *smb_fname = fsp->fsp_name;
721 NTSTATUS status = NT_STATUS_OK;
722 int accmode = (flags & O_ACCMODE);
723 int local_flags = flags;
724 bool file_existed = VALID_STAT(fsp->fsp_name->st);
726 fsp->fh->fd = -1;
727 errno = EPERM;
729 /* Check permissions */
732 * This code was changed after seeing a client open request
733 * containing the open mode of (DENY_WRITE/read-only) with
734 * the 'create if not exist' bit set. The previous code
735 * would fail to open the file read only on a read-only share
736 * as it was checking the flags parameter directly against O_RDONLY,
737 * this was failing as the flags parameter was set to O_RDONLY|O_CREAT.
738 * JRA.
741 if (!CAN_WRITE(conn)) {
742 /* It's a read-only share - fail if we wanted to write. */
743 if(accmode != O_RDONLY || (flags & O_TRUNC) || (flags & O_APPEND)) {
744 DEBUG(3,("Permission denied opening %s\n",
745 smb_fname_str_dbg(smb_fname)));
746 return NT_STATUS_ACCESS_DENIED;
747 } else if(flags & O_CREAT) {
748 /* We don't want to write - but we must make sure that
749 O_CREAT doesn't create the file if we have write
750 access into the directory.
752 flags &= ~(O_CREAT|O_EXCL);
753 local_flags &= ~(O_CREAT|O_EXCL);
758 * This little piece of insanity is inspired by the
759 * fact that an NT client can open a file for O_RDONLY,
760 * but set the create disposition to FILE_EXISTS_TRUNCATE.
761 * If the client *can* write to the file, then it expects to
762 * truncate the file, even though it is opening for readonly.
763 * Quicken uses this stupid trick in backup file creation...
764 * Thanks *greatly* to "David W. Chapman Jr." <dwcjr@inethouston.net>
765 * for helping track this one down. It didn't bite us in 2.0.x
766 * as we always opened files read-write in that release. JRA.
769 if ((accmode == O_RDONLY) && ((flags & O_TRUNC) == O_TRUNC)) {
770 DEBUG(10,("open_file: truncate requested on read-only open "
771 "for file %s\n", smb_fname_str_dbg(smb_fname)));
772 local_flags = (flags & ~O_ACCMODE)|O_RDWR;
775 if ((open_access_mask & (FILE_READ_DATA|FILE_WRITE_DATA|FILE_APPEND_DATA|FILE_EXECUTE)) ||
776 (!file_existed && (local_flags & O_CREAT)) ||
777 ((local_flags & O_TRUNC) == O_TRUNC) ) {
778 const char *wild;
779 int ret;
781 #if defined(O_NONBLOCK) && defined(S_ISFIFO)
783 * We would block on opening a FIFO with no one else on the
784 * other end. Do what we used to do and add O_NONBLOCK to the
785 * open flags. JRA.
788 if (file_existed && S_ISFIFO(smb_fname->st.st_ex_mode)) {
789 local_flags &= ~O_TRUNC; /* Can't truncate a FIFO. */
790 local_flags |= O_NONBLOCK;
792 #endif
794 /* Don't create files with Microsoft wildcard characters. */
795 if (fsp->base_fsp) {
797 * wildcard characters are allowed in stream names
798 * only test the basefilename
800 wild = fsp->base_fsp->fsp_name->base_name;
801 } else {
802 wild = smb_fname->base_name;
804 if ((local_flags & O_CREAT) && !file_existed &&
805 ms_has_wild(wild)) {
806 return NT_STATUS_OBJECT_NAME_INVALID;
809 /* Can we access this file ? */
810 if (!fsp->base_fsp) {
811 /* Only do this check on non-stream open. */
812 if (file_existed) {
813 status = smbd_check_access_rights(conn,
814 smb_fname,
815 access_mask);
816 } else if (local_flags & O_CREAT){
817 status = check_parent_access(conn,
818 smb_fname,
819 SEC_DIR_ADD_FILE);
820 } else {
821 /* File didn't exist and no O_CREAT. */
822 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
824 if (!NT_STATUS_IS_OK(status)) {
825 DEBUG(10,("open_file: "
826 "%s on file "
827 "%s returned %s\n",
828 file_existed ?
829 "smbd_check_access_rights" :
830 "check_parent_access",
831 smb_fname_str_dbg(smb_fname),
832 nt_errstr(status) ));
833 return status;
837 /* Actually do the open */
838 status = fd_open_atomic(conn, fsp, local_flags,
839 unx_mode, p_file_created);
840 if (!NT_STATUS_IS_OK(status)) {
841 DEBUG(3,("Error opening file %s (%s) (local_flags=%d) "
842 "(flags=%d)\n", smb_fname_str_dbg(smb_fname),
843 nt_errstr(status),local_flags,flags));
844 return status;
847 ret = SMB_VFS_FSTAT(fsp, &smb_fname->st);
848 if (ret == -1) {
849 /* If we have an fd, this stat should succeed. */
850 DEBUG(0,("Error doing fstat on open file %s "
851 "(%s)\n",
852 smb_fname_str_dbg(smb_fname),
853 strerror(errno) ));
854 status = map_nt_error_from_unix(errno);
855 fd_close(fsp);
856 return status;
859 if (*p_file_created) {
860 /* We created this file. */
862 bool need_re_stat = false;
863 /* Do all inheritance work after we've
864 done a successful fstat call and filled
865 in the stat struct in fsp->fsp_name. */
867 /* Inherit the ACL if required */
868 if (lp_inherit_perms(SNUM(conn))) {
869 inherit_access_posix_acl(conn, parent_dir,
870 smb_fname->base_name,
871 unx_mode);
872 need_re_stat = true;
875 /* Change the owner if required. */
876 if (lp_inherit_owner(SNUM(conn))) {
877 change_file_owner_to_parent(conn, parent_dir,
878 fsp);
879 need_re_stat = true;
882 if (need_re_stat) {
883 ret = SMB_VFS_FSTAT(fsp, &smb_fname->st);
884 /* If we have an fd, this stat should succeed. */
885 if (ret == -1) {
886 DEBUG(0,("Error doing fstat on open file %s "
887 "(%s)\n",
888 smb_fname_str_dbg(smb_fname),
889 strerror(errno) ));
893 notify_fname(conn, NOTIFY_ACTION_ADDED,
894 FILE_NOTIFY_CHANGE_FILE_NAME,
895 smb_fname->base_name);
897 } else {
898 fsp->fh->fd = -1; /* What we used to call a stat open. */
899 if (!file_existed) {
900 /* File must exist for a stat open. */
901 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
904 status = smbd_check_access_rights(conn,
905 smb_fname,
906 access_mask);
908 if (NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND) &&
909 fsp->posix_open &&
910 S_ISLNK(smb_fname->st.st_ex_mode)) {
911 /* This is a POSIX stat open for delete
912 * or rename on a symlink that points
913 * nowhere. Allow. */
914 DEBUG(10,("open_file: allowing POSIX "
915 "open on bad symlink %s\n",
916 smb_fname_str_dbg(smb_fname)));
917 status = NT_STATUS_OK;
920 if (!NT_STATUS_IS_OK(status)) {
921 DEBUG(10,("open_file: "
922 "smbd_check_access_rights on file "
923 "%s returned %s\n",
924 smb_fname_str_dbg(smb_fname),
925 nt_errstr(status) ));
926 return status;
931 * POSIX allows read-only opens of directories. We don't
932 * want to do this (we use a different code path for this)
933 * so catch a directory open and return an EISDIR. JRA.
936 if(S_ISDIR(smb_fname->st.st_ex_mode)) {
937 fd_close(fsp);
938 errno = EISDIR;
939 return NT_STATUS_FILE_IS_A_DIRECTORY;
942 fsp->file_id = vfs_file_id_from_sbuf(conn, &smb_fname->st);
943 fsp->vuid = req ? req->vuid : UID_FIELD_INVALID;
944 fsp->file_pid = req ? req->smbpid : 0;
945 fsp->can_lock = True;
946 fsp->can_read = ((access_mask & FILE_READ_DATA) != 0);
947 fsp->can_write =
948 CAN_WRITE(conn) &&
949 ((access_mask & (FILE_WRITE_DATA | FILE_APPEND_DATA)) != 0);
950 fsp->print_file = NULL;
951 fsp->modified = False;
952 fsp->sent_oplock_break = NO_BREAK_SENT;
953 fsp->is_directory = False;
954 if (conn->aio_write_behind_list &&
955 is_in_path(smb_fname->base_name, conn->aio_write_behind_list,
956 conn->case_sensitive)) {
957 fsp->aio_write_behind = True;
960 fsp->wcp = NULL; /* Write cache pointer. */
962 DEBUG(2,("%s opened file %s read=%s write=%s (numopen=%d)\n",
963 conn->session_info->unix_info->unix_name,
964 smb_fname_str_dbg(smb_fname),
965 BOOLSTR(fsp->can_read), BOOLSTR(fsp->can_write),
966 conn->num_files_open));
968 errno = 0;
969 return NT_STATUS_OK;
972 /****************************************************************************
973 Check if we can open a file with a share mode.
974 Returns True if conflict, False if not.
975 ****************************************************************************/
977 static bool share_conflict(struct share_mode_entry *entry,
978 uint32 access_mask,
979 uint32 share_access)
981 DEBUG(10,("share_conflict: entry->access_mask = 0x%x, "
982 "entry->share_access = 0x%x, "
983 "entry->private_options = 0x%x\n",
984 (unsigned int)entry->access_mask,
985 (unsigned int)entry->share_access,
986 (unsigned int)entry->private_options));
988 if (server_id_is_disconnected(&entry->pid)) {
990 * note: cleanup should have been done by
991 * delay_for_batch_oplocks()
993 return false;
996 DEBUG(10,("share_conflict: access_mask = 0x%x, share_access = 0x%x\n",
997 (unsigned int)access_mask, (unsigned int)share_access));
999 if ((entry->access_mask & (FILE_WRITE_DATA|
1000 FILE_APPEND_DATA|
1001 FILE_READ_DATA|
1002 FILE_EXECUTE|
1003 DELETE_ACCESS)) == 0) {
1004 DEBUG(10,("share_conflict: No conflict due to "
1005 "entry->access_mask = 0x%x\n",
1006 (unsigned int)entry->access_mask ));
1007 return False;
1010 if ((access_mask & (FILE_WRITE_DATA|
1011 FILE_APPEND_DATA|
1012 FILE_READ_DATA|
1013 FILE_EXECUTE|
1014 DELETE_ACCESS)) == 0) {
1015 DEBUG(10,("share_conflict: No conflict due to "
1016 "access_mask = 0x%x\n",
1017 (unsigned int)access_mask ));
1018 return False;
1021 #if 1 /* JRA TEST - Superdebug. */
1022 #define CHECK_MASK(num, am, right, sa, share) \
1023 DEBUG(10,("share_conflict: [%d] am (0x%x) & right (0x%x) = 0x%x\n", \
1024 (unsigned int)(num), (unsigned int)(am), \
1025 (unsigned int)(right), (unsigned int)(am)&(right) )); \
1026 DEBUG(10,("share_conflict: [%d] sa (0x%x) & share (0x%x) = 0x%x\n", \
1027 (unsigned int)(num), (unsigned int)(sa), \
1028 (unsigned int)(share), (unsigned int)(sa)&(share) )); \
1029 if (((am) & (right)) && !((sa) & (share))) { \
1030 DEBUG(10,("share_conflict: check %d conflict am = 0x%x, right = 0x%x, \
1031 sa = 0x%x, share = 0x%x\n", (num), (unsigned int)(am), (unsigned int)(right), (unsigned int)(sa), \
1032 (unsigned int)(share) )); \
1033 return True; \
1035 #else
1036 #define CHECK_MASK(num, am, right, sa, share) \
1037 if (((am) & (right)) && !((sa) & (share))) { \
1038 DEBUG(10,("share_conflict: check %d conflict am = 0x%x, right = 0x%x, \
1039 sa = 0x%x, share = 0x%x\n", (num), (unsigned int)(am), (unsigned int)(right), (unsigned int)(sa), \
1040 (unsigned int)(share) )); \
1041 return True; \
1043 #endif
1045 CHECK_MASK(1, entry->access_mask, FILE_WRITE_DATA | FILE_APPEND_DATA,
1046 share_access, FILE_SHARE_WRITE);
1047 CHECK_MASK(2, access_mask, FILE_WRITE_DATA | FILE_APPEND_DATA,
1048 entry->share_access, FILE_SHARE_WRITE);
1050 CHECK_MASK(3, entry->access_mask, FILE_READ_DATA | FILE_EXECUTE,
1051 share_access, FILE_SHARE_READ);
1052 CHECK_MASK(4, access_mask, FILE_READ_DATA | FILE_EXECUTE,
1053 entry->share_access, FILE_SHARE_READ);
1055 CHECK_MASK(5, entry->access_mask, DELETE_ACCESS,
1056 share_access, FILE_SHARE_DELETE);
1057 CHECK_MASK(6, access_mask, DELETE_ACCESS,
1058 entry->share_access, FILE_SHARE_DELETE);
1060 DEBUG(10,("share_conflict: No conflict.\n"));
1061 return False;
1064 #if defined(DEVELOPER)
1065 static void validate_my_share_entries(struct smbd_server_connection *sconn,
1066 int num,
1067 struct share_mode_entry *share_entry)
1069 struct server_id self = messaging_server_id(sconn->msg_ctx);
1070 files_struct *fsp;
1072 if (!serverid_equal(&self, &share_entry->pid)) {
1073 return;
1076 if (is_deferred_open_entry(share_entry) &&
1077 !open_was_deferred(sconn, share_entry->op_mid)) {
1078 char *str = talloc_asprintf(talloc_tos(),
1079 "Got a deferred entry without a request: "
1080 "PANIC: %s\n",
1081 share_mode_str(talloc_tos(), num, share_entry));
1082 smb_panic(str);
1085 if (!is_valid_share_mode_entry(share_entry)) {
1086 return;
1089 fsp = file_find_dif(sconn, share_entry->id,
1090 share_entry->share_file_id);
1091 if (!fsp) {
1092 DEBUG(0,("validate_my_share_entries: PANIC : %s\n",
1093 share_mode_str(talloc_tos(), num, share_entry) ));
1094 smb_panic("validate_my_share_entries: Cannot match a "
1095 "share entry with an open file\n");
1098 if (is_deferred_open_entry(share_entry)) {
1099 goto panic;
1102 if ((share_entry->op_type == NO_OPLOCK) &&
1103 (fsp->oplock_type == FAKE_LEVEL_II_OPLOCK)) {
1104 /* Someone has already written to it, but I haven't yet
1105 * noticed */
1106 return;
1109 if (((uint16)fsp->oplock_type) != share_entry->op_type) {
1110 goto panic;
1113 return;
1115 panic:
1117 char *str;
1118 DEBUG(0,("validate_my_share_entries: PANIC : %s\n",
1119 share_mode_str(talloc_tos(), num, share_entry) ));
1120 str = talloc_asprintf(talloc_tos(),
1121 "validate_my_share_entries: "
1122 "file %s, oplock_type = 0x%x, op_type = 0x%x\n",
1123 fsp->fsp_name->base_name,
1124 (unsigned int)fsp->oplock_type,
1125 (unsigned int)share_entry->op_type );
1126 smb_panic(str);
1129 #endif
1131 bool is_stat_open(uint32 access_mask)
1133 return (access_mask &&
1134 ((access_mask & ~(SYNCHRONIZE_ACCESS| FILE_READ_ATTRIBUTES|
1135 FILE_WRITE_ATTRIBUTES))==0) &&
1136 ((access_mask & (SYNCHRONIZE_ACCESS|FILE_READ_ATTRIBUTES|
1137 FILE_WRITE_ATTRIBUTES)) != 0));
1140 /****************************************************************************
1141 Deal with share modes
1142 Invarient: Share mode must be locked on entry and exit.
1143 Returns -1 on error, or number of share modes on success (may be zero).
1144 ****************************************************************************/
1146 static NTSTATUS open_mode_check(connection_struct *conn,
1147 struct share_mode_lock *lck,
1148 uint32_t name_hash,
1149 uint32 access_mask,
1150 uint32 share_access,
1151 uint32 create_options,
1152 bool *file_existed)
1154 int i;
1156 if(lck->data->num_share_modes == 0) {
1157 return NT_STATUS_OK;
1160 /* A delete on close prohibits everything */
1162 if (is_delete_on_close_set(lck, name_hash)) {
1164 * Check the delete on close token
1165 * is valid. It could have been left
1166 * after a server crash.
1168 for(i = 0; i < lck->data->num_share_modes; i++) {
1169 if (!share_mode_stale_pid(lck->data, i)) {
1171 *file_existed = true;
1173 return NT_STATUS_DELETE_PENDING;
1176 return NT_STATUS_OK;
1179 if (is_stat_open(access_mask)) {
1180 /* Stat open that doesn't trigger oplock breaks or share mode
1181 * checks... ! JRA. */
1182 return NT_STATUS_OK;
1186 * Check if the share modes will give us access.
1189 #if defined(DEVELOPER)
1190 for(i = 0; i < lck->data->num_share_modes; i++) {
1191 validate_my_share_entries(conn->sconn, i,
1192 &lck->data->share_modes[i]);
1194 #endif
1196 /* Now we check the share modes, after any oplock breaks. */
1197 for(i = 0; i < lck->data->num_share_modes; i++) {
1199 if (!is_valid_share_mode_entry(&lck->data->share_modes[i])) {
1200 continue;
1203 /* someone else has a share lock on it, check to see if we can
1204 * too */
1205 if (share_conflict(&lck->data->share_modes[i],
1206 access_mask, share_access)) {
1208 if (share_mode_stale_pid(lck->data, i)) {
1209 continue;
1212 *file_existed = true;
1214 return NT_STATUS_SHARING_VIOLATION;
1218 if (lck->data->num_share_modes != 0) {
1219 *file_existed = true;
1222 return NT_STATUS_OK;
1226 * Send a break message to the oplock holder and delay the open for
1227 * our client.
1230 static NTSTATUS send_break_message(files_struct *fsp,
1231 struct share_mode_entry *exclusive,
1232 uint64_t mid,
1233 int oplock_request)
1235 NTSTATUS status;
1236 char msg[MSG_SMB_SHARE_MODE_ENTRY_SIZE];
1238 DEBUG(10, ("Sending break request to PID %s\n",
1239 procid_str_static(&exclusive->pid)));
1240 exclusive->op_mid = mid;
1242 /* Create the message. */
1243 share_mode_entry_to_message(msg, exclusive);
1245 /* Add in the FORCE_OPLOCK_BREAK_TO_NONE bit in the message if set. We
1246 don't want this set in the share mode struct pointed to by lck. */
1248 if (oplock_request & FORCE_OPLOCK_BREAK_TO_NONE) {
1249 SSVAL(msg,OP_BREAK_MSG_OP_TYPE_OFFSET,
1250 exclusive->op_type | FORCE_OPLOCK_BREAK_TO_NONE);
1253 status = messaging_send_buf(fsp->conn->sconn->msg_ctx, exclusive->pid,
1254 MSG_SMB_BREAK_REQUEST,
1255 (uint8 *)msg,
1256 MSG_SMB_SHARE_MODE_ENTRY_SIZE);
1257 if (!NT_STATUS_IS_OK(status)) {
1258 DEBUG(3, ("Could not send oplock break message: %s\n",
1259 nt_errstr(status)));
1262 return status;
1266 * Return share_mode_entry pointers for :
1267 * 1). Batch oplock entry.
1268 * 2). Batch or exclusive oplock entry (may be identical to #1).
1269 * bool have_level2_oplock
1270 * bool have_no_oplock.
1271 * Do internal consistency checks on the share mode for a file.
1274 static void find_oplock_types(files_struct *fsp,
1275 int oplock_request,
1276 const struct share_mode_lock *lck,
1277 struct share_mode_entry **pp_batch,
1278 struct share_mode_entry **pp_ex_or_batch,
1279 bool *got_level2,
1280 bool *got_no_oplock)
1282 int i;
1284 *pp_batch = NULL;
1285 *pp_ex_or_batch = NULL;
1286 *got_level2 = false;
1287 *got_no_oplock = false;
1289 /* Ignore stat or internal opens, as is done in
1290 delay_for_batch_oplocks() and
1291 delay_for_exclusive_oplocks().
1293 if ((oplock_request & INTERNAL_OPEN_ONLY) || is_stat_open(fsp->access_mask)) {
1294 return;
1297 for (i=0; i<lck->data->num_share_modes; i++) {
1298 struct share_mode_entry *e = &lck->data->share_modes[i];
1300 if (!is_valid_share_mode_entry(e)) {
1301 continue;
1304 if (e->op_type == NO_OPLOCK && is_stat_open(e->access_mask)) {
1305 /* We ignore stat opens in the table - they
1306 always have NO_OPLOCK and never get or
1307 cause breaks. JRA. */
1308 continue;
1311 if (BATCH_OPLOCK_TYPE(e->op_type)) {
1312 /* batch - can only be one. */
1313 if (share_mode_stale_pid(lck->data, i)) {
1314 DEBUG(10, ("Found stale batch oplock\n"));
1315 continue;
1317 if (*pp_ex_or_batch || *pp_batch || *got_level2 || *got_no_oplock) {
1318 smb_panic("Bad batch oplock entry.");
1320 *pp_batch = e;
1323 if (EXCLUSIVE_OPLOCK_TYPE(e->op_type)) {
1324 if (share_mode_stale_pid(lck->data, i)) {
1325 DEBUG(10, ("Found stale duplicate oplock\n"));
1326 continue;
1328 /* Exclusive or batch - can only be one. */
1329 if (*pp_ex_or_batch || *got_level2 || *got_no_oplock) {
1330 smb_panic("Bad exclusive or batch oplock entry.");
1332 *pp_ex_or_batch = e;
1335 if (LEVEL_II_OPLOCK_TYPE(e->op_type)) {
1336 if (*pp_batch || *pp_ex_or_batch) {
1337 if (share_mode_stale_pid(lck->data, i)) {
1338 DEBUG(10, ("Found stale LevelII "
1339 "oplock\n"));
1340 continue;
1342 smb_panic("Bad levelII oplock entry.");
1344 *got_level2 = true;
1347 if (e->op_type == NO_OPLOCK) {
1348 if (*pp_batch || *pp_ex_or_batch) {
1349 if (share_mode_stale_pid(lck->data, i)) {
1350 DEBUG(10, ("Found stale NO_OPLOCK "
1351 "entry\n"));
1352 continue;
1354 smb_panic("Bad no oplock entry.");
1356 *got_no_oplock = true;
1361 static bool delay_for_batch_oplocks(files_struct *fsp,
1362 uint64_t mid,
1363 int oplock_request,
1364 struct share_mode_entry *batch_entry)
1366 if ((oplock_request & INTERNAL_OPEN_ONLY) || is_stat_open(fsp->access_mask)) {
1367 return false;
1369 if (batch_entry == NULL) {
1370 return false;
1373 if (server_id_is_disconnected(&batch_entry->pid)) {
1375 * TODO: clean up.
1376 * This could be achieved by sending a break message
1377 * to ourselves. Special considerations for files
1378 * with delete_on_close flag set!
1380 * For now we keep it simple and do not
1381 * allow delete on close for durable handles.
1383 return false;
1386 /* Found a batch oplock */
1387 send_break_message(fsp, batch_entry, mid, oplock_request);
1388 return true;
1391 static bool delay_for_exclusive_oplocks(files_struct *fsp,
1392 uint64_t mid,
1393 int oplock_request,
1394 struct share_mode_entry *ex_entry)
1396 if ((oplock_request & INTERNAL_OPEN_ONLY) || is_stat_open(fsp->access_mask)) {
1397 return false;
1399 if (ex_entry == NULL) {
1400 return false;
1403 if (server_id_is_disconnected(&ex_entry->pid)) {
1405 * since only durable handles can get disconnected,
1406 * and we can only get durable handles with batch oplocks,
1407 * this should actually never be reached...
1409 return false;
1412 send_break_message(fsp, ex_entry, mid, oplock_request);
1413 return true;
1416 static bool file_has_brlocks(files_struct *fsp)
1418 struct byte_range_lock *br_lck;
1420 br_lck = brl_get_locks_readonly(fsp);
1421 if (!br_lck)
1422 return false;
1424 return br_lck->num_locks > 0 ? true : false;
1427 static void grant_fsp_oplock_type(files_struct *fsp,
1428 int oplock_request,
1429 bool got_level2_oplock,
1430 bool got_a_none_oplock)
1432 bool allow_level2 = (global_client_caps & CAP_LEVEL_II_OPLOCKS) &&
1433 lp_level2_oplocks(SNUM(fsp->conn));
1435 /* Start by granting what the client asked for,
1436 but ensure no SAMBA_PRIVATE bits can be set. */
1437 fsp->oplock_type = (oplock_request & ~SAMBA_PRIVATE_OPLOCK_MASK);
1439 if (oplock_request & INTERNAL_OPEN_ONLY) {
1440 /* No oplocks on internal open. */
1441 fsp->oplock_type = NO_OPLOCK;
1442 DEBUG(10,("grant_fsp_oplock_type: oplock type 0x%x on file %s\n",
1443 fsp->oplock_type, fsp_str_dbg(fsp)));
1444 return;
1447 if (lp_locking(fsp->conn->params) && file_has_brlocks(fsp)) {
1448 DEBUG(10,("grant_fsp_oplock_type: file %s has byte range locks\n",
1449 fsp_str_dbg(fsp)));
1450 fsp->oplock_type = NO_OPLOCK;
1453 if (is_stat_open(fsp->access_mask)) {
1454 /* Leave the value already set. */
1455 DEBUG(10,("grant_fsp_oplock_type: oplock type 0x%x on file %s\n",
1456 fsp->oplock_type, fsp_str_dbg(fsp)));
1457 return;
1461 * Match what was requested (fsp->oplock_type) with
1462 * what was found in the existing share modes.
1465 if (got_a_none_oplock) {
1466 fsp->oplock_type = NO_OPLOCK;
1467 } else if (got_level2_oplock) {
1468 if (fsp->oplock_type == NO_OPLOCK ||
1469 fsp->oplock_type == FAKE_LEVEL_II_OPLOCK) {
1470 /* Store a level2 oplock, but don't tell the client */
1471 fsp->oplock_type = FAKE_LEVEL_II_OPLOCK;
1472 } else {
1473 fsp->oplock_type = LEVEL_II_OPLOCK;
1475 } else {
1476 /* All share_mode_entries are placeholders or deferred.
1477 * Silently upgrade to fake levelII if the client didn't
1478 * ask for an oplock. */
1479 if (fsp->oplock_type == NO_OPLOCK) {
1480 /* Store a level2 oplock, but don't tell the client */
1481 fsp->oplock_type = FAKE_LEVEL_II_OPLOCK;
1486 * Don't grant level2 to clients that don't want them
1487 * or if we've turned them off.
1489 if (fsp->oplock_type == LEVEL_II_OPLOCK && !allow_level2) {
1490 fsp->oplock_type = FAKE_LEVEL_II_OPLOCK;
1493 DEBUG(10,("grant_fsp_oplock_type: oplock type 0x%x on file %s\n",
1494 fsp->oplock_type, fsp_str_dbg(fsp)));
1497 static bool request_timed_out(struct timeval request_time,
1498 struct timeval timeout)
1500 struct timeval now, end_time;
1501 GetTimeOfDay(&now);
1502 end_time = timeval_sum(&request_time, &timeout);
1503 return (timeval_compare(&end_time, &now) < 0);
1506 /****************************************************************************
1507 Handle the 1 second delay in returning a SHARING_VIOLATION error.
1508 ****************************************************************************/
1510 static void defer_open(struct share_mode_lock *lck,
1511 struct timeval request_time,
1512 struct timeval timeout,
1513 struct smb_request *req,
1514 struct deferred_open_record *state)
1516 struct server_id self = messaging_server_id(req->sconn->msg_ctx);
1518 /* Paranoia check */
1520 if (lck) {
1521 int i;
1523 for (i=0; i<lck->data->num_share_modes; i++) {
1524 struct share_mode_entry *e = &lck->data->share_modes[i];
1526 if (is_deferred_open_entry(e) &&
1527 serverid_equal(&self, &e->pid) &&
1528 (e->op_mid == req->mid)) {
1529 DEBUG(0, ("Trying to defer an already deferred "
1530 "request: mid=%llu, exiting\n",
1531 (unsigned long long)req->mid));
1532 TALLOC_FREE(lck);
1533 exit_server("attempt to defer a deferred request");
1538 /* End paranoia check */
1540 DEBUG(10,("defer_open_sharing_error: time [%u.%06u] adding deferred "
1541 "open entry for mid %llu\n",
1542 (unsigned int)request_time.tv_sec,
1543 (unsigned int)request_time.tv_usec,
1544 (unsigned long long)req->mid));
1546 if (!push_deferred_open_message_smb(req, request_time, timeout,
1547 state->id, (char *)state, sizeof(*state))) {
1548 TALLOC_FREE(lck);
1549 exit_server("push_deferred_open_message_smb failed");
1551 if (lck) {
1552 add_deferred_open(lck, req->mid, request_time, self, state->id);
1557 /****************************************************************************
1558 On overwrite open ensure that the attributes match.
1559 ****************************************************************************/
1561 static bool open_match_attributes(connection_struct *conn,
1562 uint32 old_dos_attr,
1563 uint32 new_dos_attr,
1564 mode_t existing_unx_mode,
1565 mode_t new_unx_mode,
1566 mode_t *returned_unx_mode)
1568 uint32 noarch_old_dos_attr, noarch_new_dos_attr;
1570 noarch_old_dos_attr = (old_dos_attr & ~FILE_ATTRIBUTE_ARCHIVE);
1571 noarch_new_dos_attr = (new_dos_attr & ~FILE_ATTRIBUTE_ARCHIVE);
1573 if((noarch_old_dos_attr == 0 && noarch_new_dos_attr != 0) ||
1574 (noarch_old_dos_attr != 0 && ((noarch_old_dos_attr & noarch_new_dos_attr) == noarch_old_dos_attr))) {
1575 *returned_unx_mode = new_unx_mode;
1576 } else {
1577 *returned_unx_mode = (mode_t)0;
1580 DEBUG(10,("open_match_attributes: old_dos_attr = 0x%x, "
1581 "existing_unx_mode = 0%o, new_dos_attr = 0x%x "
1582 "returned_unx_mode = 0%o\n",
1583 (unsigned int)old_dos_attr,
1584 (unsigned int)existing_unx_mode,
1585 (unsigned int)new_dos_attr,
1586 (unsigned int)*returned_unx_mode ));
1588 /* If we're mapping SYSTEM and HIDDEN ensure they match. */
1589 if (lp_map_system(SNUM(conn)) || lp_store_dos_attributes(SNUM(conn))) {
1590 if ((old_dos_attr & FILE_ATTRIBUTE_SYSTEM) &&
1591 !(new_dos_attr & FILE_ATTRIBUTE_SYSTEM)) {
1592 return False;
1595 if (lp_map_hidden(SNUM(conn)) || lp_store_dos_attributes(SNUM(conn))) {
1596 if ((old_dos_attr & FILE_ATTRIBUTE_HIDDEN) &&
1597 !(new_dos_attr & FILE_ATTRIBUTE_HIDDEN)) {
1598 return False;
1601 return True;
1604 /****************************************************************************
1605 Special FCB or DOS processing in the case of a sharing violation.
1606 Try and find a duplicated file handle.
1607 ****************************************************************************/
1609 static NTSTATUS fcb_or_dos_open(struct smb_request *req,
1610 connection_struct *conn,
1611 files_struct *fsp_to_dup_into,
1612 const struct smb_filename *smb_fname,
1613 struct file_id id,
1614 uint16 file_pid,
1615 uint64_t vuid,
1616 uint32 access_mask,
1617 uint32 share_access,
1618 uint32 create_options)
1620 files_struct *fsp;
1622 DEBUG(5,("fcb_or_dos_open: attempting old open semantics for "
1623 "file %s.\n", smb_fname_str_dbg(smb_fname)));
1625 for(fsp = file_find_di_first(conn->sconn, id); fsp;
1626 fsp = file_find_di_next(fsp)) {
1628 DEBUG(10,("fcb_or_dos_open: checking file %s, fd = %d, "
1629 "vuid = %llu, file_pid = %u, private_options = 0x%x "
1630 "access_mask = 0x%x\n", fsp_str_dbg(fsp),
1631 fsp->fh->fd, (unsigned long long)fsp->vuid,
1632 (unsigned int)fsp->file_pid,
1633 (unsigned int)fsp->fh->private_options,
1634 (unsigned int)fsp->access_mask ));
1636 if (fsp->fh->fd != -1 &&
1637 fsp->vuid == vuid &&
1638 fsp->file_pid == file_pid &&
1639 (fsp->fh->private_options & (NTCREATEX_OPTIONS_PRIVATE_DENY_DOS |
1640 NTCREATEX_OPTIONS_PRIVATE_DENY_FCB)) &&
1641 (fsp->access_mask & FILE_WRITE_DATA) &&
1642 strequal(fsp->fsp_name->base_name, smb_fname->base_name) &&
1643 strequal(fsp->fsp_name->stream_name,
1644 smb_fname->stream_name)) {
1645 DEBUG(10,("fcb_or_dos_open: file match\n"));
1646 break;
1650 if (!fsp) {
1651 return NT_STATUS_NOT_FOUND;
1654 /* quite an insane set of semantics ... */
1655 if (is_executable(smb_fname->base_name) &&
1656 (fsp->fh->private_options & NTCREATEX_OPTIONS_PRIVATE_DENY_DOS)) {
1657 DEBUG(10,("fcb_or_dos_open: file fail due to is_executable.\n"));
1658 return NT_STATUS_INVALID_PARAMETER;
1661 /* We need to duplicate this fsp. */
1662 return dup_file_fsp(req, fsp, access_mask, share_access,
1663 create_options, fsp_to_dup_into);
1666 static void schedule_defer_open(struct share_mode_lock *lck,
1667 struct timeval request_time,
1668 struct smb_request *req)
1670 struct deferred_open_record state;
1672 /* This is a relative time, added to the absolute
1673 request_time value to get the absolute timeout time.
1674 Note that if this is the second or greater time we enter
1675 this codepath for this particular request mid then
1676 request_time is left as the absolute time of the *first*
1677 time this request mid was processed. This is what allows
1678 the request to eventually time out. */
1680 struct timeval timeout;
1682 /* Normally the smbd we asked should respond within
1683 * OPLOCK_BREAK_TIMEOUT seconds regardless of whether
1684 * the client did, give twice the timeout as a safety
1685 * measure here in case the other smbd is stuck
1686 * somewhere else. */
1688 timeout = timeval_set(OPLOCK_BREAK_TIMEOUT*2, 0);
1690 /* Nothing actually uses state.delayed_for_oplocks
1691 but it's handy to differentiate in debug messages
1692 between a 30 second delay due to oplock break, and
1693 a 1 second delay for share mode conflicts. */
1695 state.delayed_for_oplocks = True;
1696 state.async_open = false;
1697 state.id = lck->data->id;
1699 if (!request_timed_out(request_time, timeout)) {
1700 defer_open(lck, request_time, timeout, req, &state);
1704 /****************************************************************************
1705 Reschedule an open call that went asynchronous.
1706 ****************************************************************************/
1708 static void schedule_async_open(struct timeval request_time,
1709 struct smb_request *req)
1711 struct deferred_open_record state;
1712 struct timeval timeout;
1714 timeout = timeval_set(20, 0);
1716 ZERO_STRUCT(state);
1717 state.delayed_for_oplocks = false;
1718 state.async_open = true;
1720 if (!request_timed_out(request_time, timeout)) {
1721 defer_open(NULL, request_time, timeout, req, &state);
1725 /****************************************************************************
1726 Work out what access_mask to use from what the client sent us.
1727 ****************************************************************************/
1729 static NTSTATUS smbd_calculate_maximum_allowed_access(
1730 connection_struct *conn,
1731 const struct smb_filename *smb_fname,
1732 uint32_t *p_access_mask)
1734 struct security_descriptor *sd;
1735 uint32_t access_granted;
1736 NTSTATUS status;
1738 if (get_current_uid(conn) == (uid_t)0) {
1739 *p_access_mask |= FILE_GENERIC_ALL;
1740 return NT_STATUS_OK;
1743 status = SMB_VFS_GET_NT_ACL(conn, smb_fname->base_name,
1744 (SECINFO_OWNER |
1745 SECINFO_GROUP |
1746 SECINFO_DACL),
1747 talloc_tos(), &sd);
1749 if (NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
1751 * File did not exist
1753 *p_access_mask = FILE_GENERIC_ALL;
1754 return NT_STATUS_OK;
1756 if (!NT_STATUS_IS_OK(status)) {
1757 DEBUG(10,("smbd_calculate_access_mask: "
1758 "Could not get acl on file %s: %s\n",
1759 smb_fname_str_dbg(smb_fname),
1760 nt_errstr(status)));
1761 return NT_STATUS_ACCESS_DENIED;
1765 * If we can access the path to this file, by
1766 * default we have FILE_READ_ATTRIBUTES from the
1767 * containing directory. See the section:
1768 * "Algorithm to Check Access to an Existing File"
1769 * in MS-FSA.pdf.
1771 * se_file_access_check()
1772 * also takes care of owner WRITE_DAC and READ_CONTROL.
1774 status = se_file_access_check(sd,
1775 get_current_nttok(conn),
1776 false,
1777 (*p_access_mask & ~FILE_READ_ATTRIBUTES),
1778 &access_granted);
1780 TALLOC_FREE(sd);
1782 if (!NT_STATUS_IS_OK(status)) {
1783 DEBUG(10, ("smbd_calculate_access_mask: "
1784 "Access denied on file %s: "
1785 "when calculating maximum access\n",
1786 smb_fname_str_dbg(smb_fname)));
1787 return NT_STATUS_ACCESS_DENIED;
1789 *p_access_mask = (access_granted | FILE_READ_ATTRIBUTES);
1791 if (!(access_granted & DELETE_ACCESS)) {
1792 if (can_delete_file_in_directory(conn, smb_fname)) {
1793 *p_access_mask |= DELETE_ACCESS;
1797 return NT_STATUS_OK;
1800 NTSTATUS smbd_calculate_access_mask(connection_struct *conn,
1801 const struct smb_filename *smb_fname,
1802 uint32_t access_mask,
1803 uint32_t *access_mask_out)
1805 NTSTATUS status;
1806 uint32_t orig_access_mask = access_mask;
1807 uint32_t rejected_share_access;
1810 * Convert GENERIC bits to specific bits.
1813 se_map_generic(&access_mask, &file_generic_mapping);
1815 /* Calculate MAXIMUM_ALLOWED_ACCESS if requested. */
1816 if (access_mask & MAXIMUM_ALLOWED_ACCESS) {
1818 status = smbd_calculate_maximum_allowed_access(
1819 conn, smb_fname, &access_mask);
1821 if (!NT_STATUS_IS_OK(status)) {
1822 return status;
1825 access_mask &= conn->share_access;
1828 rejected_share_access = access_mask & ~(conn->share_access);
1830 if (rejected_share_access) {
1831 DEBUG(10, ("smbd_calculate_access_mask: Access denied on "
1832 "file %s: rejected by share access mask[0x%08X] "
1833 "orig[0x%08X] mapped[0x%08X] reject[0x%08X]\n",
1834 smb_fname_str_dbg(smb_fname),
1835 conn->share_access,
1836 orig_access_mask, access_mask,
1837 rejected_share_access));
1838 return NT_STATUS_ACCESS_DENIED;
1841 *access_mask_out = access_mask;
1842 return NT_STATUS_OK;
1845 /****************************************************************************
1846 Remove the deferred open entry under lock.
1847 ****************************************************************************/
1849 void remove_deferred_open_entry(struct file_id id, uint64_t mid,
1850 struct server_id pid)
1852 struct share_mode_lock *lck = get_existing_share_mode_lock(
1853 talloc_tos(), id);
1854 if (lck == NULL) {
1855 DEBUG(0, ("could not get share mode lock\n"));
1856 return;
1858 del_deferred_open_entry(lck, mid, pid);
1859 TALLOC_FREE(lck);
1862 /****************************************************************************
1863 Return true if this is a state pointer to an asynchronous create.
1864 ****************************************************************************/
1866 bool is_deferred_open_async(const void *ptr)
1868 const struct deferred_open_record *state = (const struct deferred_open_record *)ptr;
1870 return state->async_open;
1873 static bool clear_ads(uint32_t create_disposition)
1875 bool ret = false;
1877 switch (create_disposition) {
1878 case FILE_SUPERSEDE:
1879 case FILE_OVERWRITE_IF:
1880 case FILE_OVERWRITE:
1881 ret = true;
1882 break;
1883 default:
1884 break;
1886 return ret;
1889 static int disposition_to_open_flags(uint32_t create_disposition)
1891 int ret = 0;
1894 * Currently we're using FILE_SUPERSEDE as the same as
1895 * FILE_OVERWRITE_IF but they really are
1896 * different. FILE_SUPERSEDE deletes an existing file
1897 * (requiring delete access) then recreates it.
1900 switch (create_disposition) {
1901 case FILE_SUPERSEDE:
1902 case FILE_OVERWRITE_IF:
1904 * If file exists replace/overwrite. If file doesn't
1905 * exist create.
1907 ret = O_CREAT|O_TRUNC;
1908 break;
1910 case FILE_OPEN:
1912 * If file exists open. If file doesn't exist error.
1914 ret = 0;
1915 break;
1917 case FILE_OVERWRITE:
1919 * If file exists overwrite. If file doesn't exist
1920 * error.
1922 ret = O_TRUNC;
1923 break;
1925 case FILE_CREATE:
1927 * If file exists error. If file doesn't exist create.
1929 ret = O_CREAT|O_EXCL;
1930 break;
1932 case FILE_OPEN_IF:
1934 * If file exists open. If file doesn't exist create.
1936 ret = O_CREAT;
1937 break;
1939 return ret;
1942 /****************************************************************************
1943 Open a file with a share mode. Passed in an already created files_struct *.
1944 ****************************************************************************/
1946 static NTSTATUS open_file_ntcreate(connection_struct *conn,
1947 struct smb_request *req,
1948 uint32 access_mask, /* access bits (FILE_READ_DATA etc.) */
1949 uint32 share_access, /* share constants (FILE_SHARE_READ etc) */
1950 uint32 create_disposition, /* FILE_OPEN_IF etc. */
1951 uint32 create_options, /* options such as delete on close. */
1952 uint32 new_dos_attributes, /* attributes used for new file. */
1953 int oplock_request, /* internal Samba oplock codes. */
1954 /* Information (FILE_EXISTS etc.) */
1955 uint32_t private_flags, /* Samba specific flags. */
1956 int *pinfo,
1957 files_struct *fsp)
1959 struct smb_filename *smb_fname = fsp->fsp_name;
1960 int flags=0;
1961 int flags2=0;
1962 bool file_existed = VALID_STAT(smb_fname->st);
1963 bool def_acl = False;
1964 bool posix_open = False;
1965 bool new_file_created = False;
1966 NTSTATUS fsp_open = NT_STATUS_ACCESS_DENIED;
1967 mode_t new_unx_mode = (mode_t)0;
1968 mode_t unx_mode = (mode_t)0;
1969 int info;
1970 uint32 existing_dos_attributes = 0;
1971 struct timeval request_time = timeval_zero();
1972 struct share_mode_lock *lck = NULL;
1973 uint32 open_access_mask = access_mask;
1974 NTSTATUS status;
1975 char *parent_dir;
1976 SMB_STRUCT_STAT saved_stat = smb_fname->st;
1978 if (conn->printer) {
1980 * Printers are handled completely differently.
1981 * Most of the passed parameters are ignored.
1984 if (pinfo) {
1985 *pinfo = FILE_WAS_CREATED;
1988 DEBUG(10, ("open_file_ntcreate: printer open fname=%s\n",
1989 smb_fname_str_dbg(smb_fname)));
1991 if (!req) {
1992 DEBUG(0,("open_file_ntcreate: printer open without "
1993 "an SMB request!\n"));
1994 return NT_STATUS_INTERNAL_ERROR;
1997 return print_spool_open(fsp, smb_fname->base_name,
1998 req->vuid);
2001 if (!parent_dirname(talloc_tos(), smb_fname->base_name, &parent_dir,
2002 NULL)) {
2003 return NT_STATUS_NO_MEMORY;
2006 if (new_dos_attributes & FILE_FLAG_POSIX_SEMANTICS) {
2007 posix_open = True;
2008 unx_mode = (mode_t)(new_dos_attributes & ~FILE_FLAG_POSIX_SEMANTICS);
2009 new_dos_attributes = 0;
2010 } else {
2011 /* Windows allows a new file to be created and
2012 silently removes a FILE_ATTRIBUTE_DIRECTORY
2013 sent by the client. Do the same. */
2015 new_dos_attributes &= ~FILE_ATTRIBUTE_DIRECTORY;
2017 /* We add FILE_ATTRIBUTE_ARCHIVE to this as this mode is only used if the file is
2018 * created new. */
2019 unx_mode = unix_mode(conn, new_dos_attributes | FILE_ATTRIBUTE_ARCHIVE,
2020 smb_fname, parent_dir);
2023 DEBUG(10, ("open_file_ntcreate: fname=%s, dos_attrs=0x%x "
2024 "access_mask=0x%x share_access=0x%x "
2025 "create_disposition = 0x%x create_options=0x%x "
2026 "unix mode=0%o oplock_request=%d private_flags = 0x%x\n",
2027 smb_fname_str_dbg(smb_fname), new_dos_attributes,
2028 access_mask, share_access, create_disposition,
2029 create_options, (unsigned int)unx_mode, oplock_request,
2030 (unsigned int)private_flags));
2032 if ((req == NULL) && ((oplock_request & INTERNAL_OPEN_ONLY) == 0)) {
2033 DEBUG(0, ("No smb request but not an internal only open!\n"));
2034 return NT_STATUS_INTERNAL_ERROR;
2038 * Only non-internal opens can be deferred at all
2041 if (req) {
2042 void *ptr;
2043 if (get_deferred_open_message_state(req,
2044 &request_time,
2045 &ptr)) {
2046 /* Remember the absolute time of the original
2047 request with this mid. We'll use it later to
2048 see if this has timed out. */
2050 /* If it was an async create retry, the file
2051 didn't exist. */
2053 if (is_deferred_open_async(ptr)) {
2054 SET_STAT_INVALID(smb_fname->st);
2055 file_existed = false;
2056 } else {
2057 struct deferred_open_record *state = (struct deferred_open_record *)ptr;
2058 /* Remove the deferred open entry under lock. */
2059 remove_deferred_open_entry(
2060 state->id, req->mid,
2061 messaging_server_id(req->sconn->msg_ctx));
2064 /* Ensure we don't reprocess this message. */
2065 remove_deferred_open_message_smb(req->sconn, req->mid);
2069 if (!posix_open) {
2070 new_dos_attributes &= SAMBA_ATTRIBUTES_MASK;
2071 if (file_existed) {
2072 existing_dos_attributes = dos_mode(conn, smb_fname);
2076 /* ignore any oplock requests if oplocks are disabled */
2077 if (!lp_oplocks(SNUM(conn)) ||
2078 IS_VETO_OPLOCK_PATH(conn, smb_fname->base_name)) {
2079 /* Mask off everything except the private Samba bits. */
2080 oplock_request &= SAMBA_PRIVATE_OPLOCK_MASK;
2083 /* this is for OS/2 long file names - say we don't support them */
2084 if (!lp_posix_pathnames() && strstr(smb_fname->base_name,".+,;=[].")) {
2085 /* OS/2 Workplace shell fix may be main code stream in a later
2086 * release. */
2087 DEBUG(5,("open_file_ntcreate: OS/2 long filenames are not "
2088 "supported.\n"));
2089 if (use_nt_status()) {
2090 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
2092 return NT_STATUS_DOS(ERRDOS, ERRcannotopen);
2095 switch( create_disposition ) {
2096 case FILE_OPEN:
2097 /* If file exists open. If file doesn't exist error. */
2098 if (!file_existed) {
2099 DEBUG(5,("open_file_ntcreate: FILE_OPEN "
2100 "requested for file %s and file "
2101 "doesn't exist.\n",
2102 smb_fname_str_dbg(smb_fname)));
2103 errno = ENOENT;
2104 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
2106 break;
2108 case FILE_OVERWRITE:
2109 /* If file exists overwrite. If file doesn't exist
2110 * error. */
2111 if (!file_existed) {
2112 DEBUG(5,("open_file_ntcreate: FILE_OVERWRITE "
2113 "requested for file %s and file "
2114 "doesn't exist.\n",
2115 smb_fname_str_dbg(smb_fname) ));
2116 errno = ENOENT;
2117 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
2119 break;
2121 case FILE_CREATE:
2122 /* If file exists error. If file doesn't exist
2123 * create. */
2124 if (file_existed) {
2125 DEBUG(5,("open_file_ntcreate: FILE_CREATE "
2126 "requested for file %s and file "
2127 "already exists.\n",
2128 smb_fname_str_dbg(smb_fname)));
2129 if (S_ISDIR(smb_fname->st.st_ex_mode)) {
2130 errno = EISDIR;
2131 } else {
2132 errno = EEXIST;
2134 return map_nt_error_from_unix(errno);
2136 break;
2138 case FILE_SUPERSEDE:
2139 case FILE_OVERWRITE_IF:
2140 case FILE_OPEN_IF:
2141 break;
2142 default:
2143 return NT_STATUS_INVALID_PARAMETER;
2146 flags2 = disposition_to_open_flags(create_disposition);
2148 /* We only care about matching attributes on file exists and
2149 * overwrite. */
2151 if (!posix_open && file_existed &&
2152 ((create_disposition == FILE_OVERWRITE) ||
2153 (create_disposition == FILE_OVERWRITE_IF))) {
2154 if (!open_match_attributes(conn, existing_dos_attributes,
2155 new_dos_attributes,
2156 smb_fname->st.st_ex_mode,
2157 unx_mode, &new_unx_mode)) {
2158 DEBUG(5,("open_file_ntcreate: attributes missmatch "
2159 "for file %s (%x %x) (0%o, 0%o)\n",
2160 smb_fname_str_dbg(smb_fname),
2161 existing_dos_attributes,
2162 new_dos_attributes,
2163 (unsigned int)smb_fname->st.st_ex_mode,
2164 (unsigned int)unx_mode ));
2165 errno = EACCES;
2166 return NT_STATUS_ACCESS_DENIED;
2170 status = smbd_calculate_access_mask(conn, smb_fname,
2171 access_mask,
2172 &access_mask);
2173 if (!NT_STATUS_IS_OK(status)) {
2174 DEBUG(10, ("open_file_ntcreate: smbd_calculate_access_mask "
2175 "on file %s returned %s\n",
2176 smb_fname_str_dbg(smb_fname), nt_errstr(status)));
2177 return status;
2180 open_access_mask = access_mask;
2182 if ((flags2 & O_TRUNC) || (oplock_request & FORCE_OPLOCK_BREAK_TO_NONE)) {
2183 open_access_mask |= FILE_WRITE_DATA; /* This will cause oplock breaks. */
2186 DEBUG(10, ("open_file_ntcreate: fname=%s, after mapping "
2187 "access_mask=0x%x\n", smb_fname_str_dbg(smb_fname),
2188 access_mask));
2191 * Note that we ignore the append flag as append does not
2192 * mean the same thing under DOS and Unix.
2195 if ((access_mask & (FILE_WRITE_DATA | FILE_APPEND_DATA)) ||
2196 (oplock_request & FORCE_OPLOCK_BREAK_TO_NONE)) {
2197 /* DENY_DOS opens are always underlying read-write on the
2198 file handle, no matter what the requested access mask
2199 says. */
2200 if ((private_flags & NTCREATEX_OPTIONS_PRIVATE_DENY_DOS) ||
2201 access_mask & (FILE_READ_ATTRIBUTES|FILE_READ_DATA|FILE_READ_EA|FILE_EXECUTE)) {
2202 flags = O_RDWR;
2203 } else {
2204 flags = O_WRONLY;
2206 } else {
2207 flags = O_RDONLY;
2211 * Currently we only look at FILE_WRITE_THROUGH for create options.
2214 #if defined(O_SYNC)
2215 if ((create_options & FILE_WRITE_THROUGH) && lp_strict_sync(SNUM(conn))) {
2216 flags2 |= O_SYNC;
2218 #endif /* O_SYNC */
2220 if (posix_open && (access_mask & FILE_APPEND_DATA)) {
2221 flags2 |= O_APPEND;
2224 if (!posix_open && !CAN_WRITE(conn)) {
2226 * We should really return a permission denied error if either
2227 * O_CREAT or O_TRUNC are set, but for compatibility with
2228 * older versions of Samba we just AND them out.
2230 flags2 &= ~(O_CREAT|O_TRUNC);
2234 * Ensure we can't write on a read-only share or file.
2237 if (flags != O_RDONLY && file_existed &&
2238 (!CAN_WRITE(conn) || IS_DOS_READONLY(existing_dos_attributes))) {
2239 DEBUG(5,("open_file_ntcreate: write access requested for "
2240 "file %s on read only %s\n",
2241 smb_fname_str_dbg(smb_fname),
2242 !CAN_WRITE(conn) ? "share" : "file" ));
2243 errno = EACCES;
2244 return NT_STATUS_ACCESS_DENIED;
2247 fsp->file_id = vfs_file_id_from_sbuf(conn, &smb_fname->st);
2248 fsp->share_access = share_access;
2249 fsp->fh->private_options = private_flags;
2250 fsp->access_mask = open_access_mask; /* We change this to the
2251 * requested access_mask after
2252 * the open is done. */
2253 fsp->posix_open = posix_open;
2255 /* Ensure no SAMBA_PRIVATE bits can be set. */
2256 fsp->oplock_type = (oplock_request & ~SAMBA_PRIVATE_OPLOCK_MASK);
2258 if (timeval_is_zero(&request_time)) {
2259 request_time = fsp->open_time;
2262 if (file_existed) {
2263 struct share_mode_entry *batch_entry = NULL;
2264 struct share_mode_entry *exclusive_entry = NULL;
2265 bool got_level2_oplock = false;
2266 bool got_a_none_oplock = false;
2267 struct file_id id;
2269 struct timespec old_write_time = smb_fname->st.st_ex_mtime;
2270 id = vfs_file_id_from_sbuf(conn, &smb_fname->st);
2272 lck = get_share_mode_lock(talloc_tos(), id,
2273 conn->connectpath,
2274 smb_fname, &old_write_time);
2275 if (lck == NULL) {
2276 DEBUG(0, ("Could not get share mode lock\n"));
2277 return NT_STATUS_SHARING_VIOLATION;
2280 /* Get the types we need to examine. */
2281 find_oplock_types(fsp,
2282 oplock_request,
2283 lck,
2284 &batch_entry,
2285 &exclusive_entry,
2286 &got_level2_oplock,
2287 &got_a_none_oplock);
2289 /* First pass - send break only on batch oplocks. */
2290 if ((req != NULL) &&
2291 delay_for_batch_oplocks(fsp,
2292 req->mid,
2293 oplock_request,
2294 batch_entry)) {
2295 schedule_defer_open(lck, request_time, req);
2296 TALLOC_FREE(lck);
2297 return NT_STATUS_SHARING_VIOLATION;
2300 /* Use the client requested access mask here, not the one we
2301 * open with. */
2302 status = open_mode_check(conn, lck, fsp->name_hash,
2303 access_mask, share_access,
2304 create_options, &file_existed);
2306 if (NT_STATUS_IS_OK(status)) {
2307 /* We might be going to allow this open. Check oplock
2308 * status again. */
2309 /* Second pass - send break for both batch or
2310 * exclusive oplocks. */
2311 if ((req != NULL) &&
2312 delay_for_exclusive_oplocks(
2313 fsp,
2314 req->mid,
2315 oplock_request,
2316 exclusive_entry)) {
2317 schedule_defer_open(lck, request_time, req);
2318 TALLOC_FREE(lck);
2319 return NT_STATUS_SHARING_VIOLATION;
2323 if (NT_STATUS_EQUAL(status, NT_STATUS_DELETE_PENDING)) {
2324 /* DELETE_PENDING is not deferred for a second */
2325 TALLOC_FREE(lck);
2326 return status;
2329 grant_fsp_oplock_type(fsp,
2330 oplock_request,
2331 got_level2_oplock,
2332 got_a_none_oplock);
2334 if (!NT_STATUS_IS_OK(status)) {
2335 uint32 can_access_mask;
2336 bool can_access = True;
2338 SMB_ASSERT(NT_STATUS_EQUAL(status, NT_STATUS_SHARING_VIOLATION));
2340 /* Check if this can be done with the deny_dos and fcb
2341 * calls. */
2342 if (private_flags &
2343 (NTCREATEX_OPTIONS_PRIVATE_DENY_DOS|
2344 NTCREATEX_OPTIONS_PRIVATE_DENY_FCB)) {
2345 if (req == NULL) {
2346 DEBUG(0, ("DOS open without an SMB "
2347 "request!\n"));
2348 TALLOC_FREE(lck);
2349 return NT_STATUS_INTERNAL_ERROR;
2352 /* Use the client requested access mask here,
2353 * not the one we open with. */
2354 status = fcb_or_dos_open(req,
2355 conn,
2356 fsp,
2357 smb_fname,
2359 req->smbpid,
2360 req->vuid,
2361 access_mask,
2362 share_access,
2363 create_options);
2365 if (NT_STATUS_IS_OK(status)) {
2366 TALLOC_FREE(lck);
2367 if (pinfo) {
2368 *pinfo = FILE_WAS_OPENED;
2370 return NT_STATUS_OK;
2375 * This next line is a subtlety we need for
2376 * MS-Access. If a file open will fail due to share
2377 * permissions and also for security (access) reasons,
2378 * we need to return the access failed error, not the
2379 * share error. We can't open the file due to kernel
2380 * oplock deadlock (it's possible we failed above on
2381 * the open_mode_check()) so use a userspace check.
2384 if (flags & O_RDWR) {
2385 can_access_mask = FILE_READ_DATA|FILE_WRITE_DATA;
2386 } else if (flags & O_WRONLY) {
2387 can_access_mask = FILE_WRITE_DATA;
2388 } else {
2389 can_access_mask = FILE_READ_DATA;
2392 if (((can_access_mask & FILE_WRITE_DATA) &&
2393 !CAN_WRITE(conn)) ||
2394 !NT_STATUS_IS_OK(smbd_check_access_rights(conn,
2395 smb_fname, can_access_mask))) {
2396 can_access = False;
2400 * If we're returning a share violation, ensure we
2401 * cope with the braindead 1 second delay (SMB1 only).
2404 if (!(oplock_request & INTERNAL_OPEN_ONLY) &&
2405 !conn->sconn->using_smb2 &&
2406 lp_defer_sharing_violations()) {
2407 struct timeval timeout;
2408 struct deferred_open_record state;
2409 int timeout_usecs;
2411 /* this is a hack to speed up torture tests
2412 in 'make test' */
2413 timeout_usecs = lp_parm_int(SNUM(conn),
2414 "smbd","sharedelay",
2415 SHARING_VIOLATION_USEC_WAIT);
2417 /* This is a relative time, added to the absolute
2418 request_time value to get the absolute timeout time.
2419 Note that if this is the second or greater time we enter
2420 this codepath for this particular request mid then
2421 request_time is left as the absolute time of the *first*
2422 time this request mid was processed. This is what allows
2423 the request to eventually time out. */
2425 timeout = timeval_set(0, timeout_usecs);
2427 /* Nothing actually uses state.delayed_for_oplocks
2428 but it's handy to differentiate in debug messages
2429 between a 30 second delay due to oplock break, and
2430 a 1 second delay for share mode conflicts. */
2432 state.delayed_for_oplocks = False;
2433 state.async_open = false;
2434 state.id = id;
2436 if ((req != NULL)
2437 && !request_timed_out(request_time,
2438 timeout)) {
2439 defer_open(lck, request_time, timeout,
2440 req, &state);
2444 TALLOC_FREE(lck);
2445 if (can_access) {
2447 * We have detected a sharing violation here
2448 * so return the correct error code
2450 status = NT_STATUS_SHARING_VIOLATION;
2451 } else {
2452 status = NT_STATUS_ACCESS_DENIED;
2454 return status;
2458 * We exit this block with the share entry *locked*.....
2462 SMB_ASSERT(!file_existed || (lck != NULL));
2465 * Ensure we pay attention to default ACLs on directories if required.
2468 if ((flags2 & O_CREAT) && lp_inherit_acls(SNUM(conn)) &&
2469 (def_acl = directory_has_default_acl(conn, parent_dir))) {
2470 unx_mode = (0777 & lp_create_mask(SNUM(conn)));
2473 DEBUG(4,("calling open_file with flags=0x%X flags2=0x%X mode=0%o, "
2474 "access_mask = 0x%x, open_access_mask = 0x%x\n",
2475 (unsigned int)flags, (unsigned int)flags2,
2476 (unsigned int)unx_mode, (unsigned int)access_mask,
2477 (unsigned int)open_access_mask));
2479 fsp_open = open_file(fsp, conn, req, parent_dir,
2480 flags|flags2, unx_mode, access_mask,
2481 open_access_mask, &new_file_created);
2483 if (!NT_STATUS_IS_OK(fsp_open)) {
2484 if (NT_STATUS_EQUAL(fsp_open, NT_STATUS_RETRY)) {
2485 schedule_async_open(request_time, req);
2487 TALLOC_FREE(lck);
2488 return fsp_open;
2491 if (file_existed && !check_same_dev_ino(&saved_stat, &smb_fname->st)) {
2493 * The file did exist, but some other (local or NFS)
2494 * process either renamed/unlinked and re-created the
2495 * file with different dev/ino after we walked the path,
2496 * but before we did the open. We could retry the
2497 * open but it's a rare enough case it's easier to
2498 * just fail the open to prevent creating any problems
2499 * in the open file db having the wrong dev/ino key.
2501 TALLOC_FREE(lck);
2502 fd_close(fsp);
2503 DEBUG(1,("open_file_ntcreate: file %s - dev/ino mismatch. "
2504 "Old (dev=0x%llu, ino =0x%llu). "
2505 "New (dev=0x%llu, ino=0x%llu). Failing open "
2506 " with NT_STATUS_ACCESS_DENIED.\n",
2507 smb_fname_str_dbg(smb_fname),
2508 (unsigned long long)saved_stat.st_ex_dev,
2509 (unsigned long long)saved_stat.st_ex_ino,
2510 (unsigned long long)smb_fname->st.st_ex_dev,
2511 (unsigned long long)smb_fname->st.st_ex_ino));
2512 return NT_STATUS_ACCESS_DENIED;
2515 if (!file_existed) {
2516 struct share_mode_entry *batch_entry = NULL;
2517 struct share_mode_entry *exclusive_entry = NULL;
2518 bool got_level2_oplock = false;
2519 bool got_a_none_oplock = false;
2520 struct timespec old_write_time = smb_fname->st.st_ex_mtime;
2521 struct file_id id;
2523 * Deal with the race condition where two smbd's detect the
2524 * file doesn't exist and do the create at the same time. One
2525 * of them will win and set a share mode, the other (ie. this
2526 * one) should check if the requested share mode for this
2527 * create is allowed.
2531 * Now the file exists and fsp is successfully opened,
2532 * fsp->dev and fsp->inode are valid and should replace the
2533 * dev=0,inode=0 from a non existent file. Spotted by
2534 * Nadav Danieli <nadavd@exanet.com>. JRA.
2537 id = fsp->file_id;
2539 lck = get_share_mode_lock(talloc_tos(), id,
2540 conn->connectpath,
2541 smb_fname, &old_write_time);
2543 if (lck == NULL) {
2544 DEBUG(0, ("open_file_ntcreate: Could not get share "
2545 "mode lock for %s\n",
2546 smb_fname_str_dbg(smb_fname)));
2547 fd_close(fsp);
2548 return NT_STATUS_SHARING_VIOLATION;
2551 /* Get the types we need to examine. */
2552 find_oplock_types(fsp,
2553 oplock_request,
2554 lck,
2555 &batch_entry,
2556 &exclusive_entry,
2557 &got_level2_oplock,
2558 &got_a_none_oplock);
2560 /* First pass - send break only on batch oplocks. */
2561 if ((req != NULL) &&
2562 delay_for_batch_oplocks(fsp,
2563 req->mid,
2564 oplock_request,
2565 batch_entry)) {
2566 schedule_defer_open(lck, request_time, req);
2567 TALLOC_FREE(lck);
2568 fd_close(fsp);
2569 return NT_STATUS_SHARING_VIOLATION;
2572 status = open_mode_check(conn, lck, fsp->name_hash,
2573 access_mask, share_access,
2574 create_options, &file_existed);
2576 if (NT_STATUS_IS_OK(status)) {
2577 /* We might be going to allow this open. Check oplock
2578 * status again. */
2579 /* Second pass - send break for both batch or
2580 * exclusive oplocks. */
2581 if ((req != NULL) &&
2582 delay_for_exclusive_oplocks(
2583 fsp,
2584 req->mid,
2585 oplock_request,
2586 exclusive_entry)) {
2587 schedule_defer_open(lck, request_time, req);
2588 TALLOC_FREE(lck);
2589 fd_close(fsp);
2590 return NT_STATUS_SHARING_VIOLATION;
2594 if (!NT_STATUS_IS_OK(status)) {
2595 struct deferred_open_record state;
2597 state.delayed_for_oplocks = False;
2598 state.async_open = false;
2599 state.id = id;
2601 /* Do it all over again immediately. In the second
2602 * round we will find that the file existed and handle
2603 * the DELETE_PENDING and FCB cases correctly. No need
2604 * to duplicate the code here. Essentially this is a
2605 * "goto top of this function", but don't tell
2606 * anybody... */
2608 if (req != NULL) {
2609 defer_open(lck, request_time, timeval_zero(),
2610 req, &state);
2612 TALLOC_FREE(lck);
2613 fd_close(fsp);
2614 return status;
2617 grant_fsp_oplock_type(fsp,
2618 oplock_request,
2619 got_level2_oplock,
2620 got_a_none_oplock);
2623 * We exit this block with the share entry *locked*.....
2628 SMB_ASSERT(lck != NULL);
2630 /* Delete streams if create_disposition requires it */
2631 if (!new_file_created && clear_ads(create_disposition) &&
2632 !is_ntfs_stream_smb_fname(smb_fname)) {
2633 status = delete_all_streams(conn, smb_fname->base_name);
2634 if (!NT_STATUS_IS_OK(status)) {
2635 TALLOC_FREE(lck);
2636 fd_close(fsp);
2637 return status;
2641 /* note that we ignore failure for the following. It is
2642 basically a hack for NFS, and NFS will never set one of
2643 these only read them. Nobody but Samba can ever set a deny
2644 mode and we have already checked our more authoritative
2645 locking database for permission to set this deny mode. If
2646 the kernel refuses the operations then the kernel is wrong.
2647 note that GPFS supports it as well - jmcd */
2649 if (fsp->fh->fd != -1 && lp_kernel_share_modes(SNUM(conn))) {
2650 int ret_flock;
2651 ret_flock = SMB_VFS_KERNEL_FLOCK(fsp, share_access, access_mask);
2652 if(ret_flock == -1 ){
2654 TALLOC_FREE(lck);
2655 fd_close(fsp);
2657 return NT_STATUS_SHARING_VIOLATION;
2662 * At this point onwards, we can guarentee that the share entry
2663 * is locked, whether we created the file or not, and that the
2664 * deny mode is compatible with all current opens.
2668 * According to Samba4, SEC_FILE_READ_ATTRIBUTE is always granted,
2669 * but we don't have to store this - just ignore it on access check.
2671 if (conn->sconn->using_smb2) {
2673 * SMB2 doesn't return it (according to Microsoft tests).
2674 * Test Case: TestSuite_ScenarioNo009GrantedAccessTestS0
2675 * File created with access = 0x7 (Read, Write, Delete)
2676 * Query Info on file returns 0x87 (Read, Write, Delete, Read Attributes)
2678 fsp->access_mask = access_mask;
2679 } else {
2680 /* But SMB1 does. */
2681 fsp->access_mask = access_mask | FILE_READ_ATTRIBUTES;
2684 if (file_existed) {
2685 /* stat opens on existing files don't get oplocks. */
2686 if (is_stat_open(open_access_mask)) {
2687 fsp->oplock_type = NO_OPLOCK;
2691 if (new_file_created) {
2692 info = FILE_WAS_CREATED;
2693 } else {
2694 if (flags2 & O_TRUNC) {
2695 info = FILE_WAS_OVERWRITTEN;
2696 } else {
2697 info = FILE_WAS_OPENED;
2701 if (pinfo) {
2702 *pinfo = info;
2706 * Setup the oplock info in both the shared memory and
2707 * file structs.
2710 status = set_file_oplock(fsp, fsp->oplock_type);
2711 if (!NT_STATUS_IS_OK(status)) {
2713 * Could not get the kernel oplock or there are byte-range
2714 * locks on the file.
2716 fsp->oplock_type = NO_OPLOCK;
2719 set_share_mode(lck, fsp, get_current_uid(conn),
2720 req ? req->mid : 0,
2721 fsp->oplock_type);
2723 /* Handle strange delete on close create semantics. */
2724 if (create_options & FILE_DELETE_ON_CLOSE) {
2726 status = can_set_delete_on_close(fsp, new_dos_attributes);
2728 if (!NT_STATUS_IS_OK(status)) {
2729 /* Remember to delete the mode we just added. */
2730 del_share_mode(lck, fsp);
2731 TALLOC_FREE(lck);
2732 fd_close(fsp);
2733 return status;
2735 /* Note that here we set the *inital* delete on close flag,
2736 not the regular one. The magic gets handled in close. */
2737 fsp->initial_delete_on_close = True;
2740 if (info != FILE_WAS_OPENED) {
2741 /* Files should be initially set as archive */
2742 if (lp_map_archive(SNUM(conn)) ||
2743 lp_store_dos_attributes(SNUM(conn))) {
2744 if (!posix_open) {
2745 if (file_set_dosmode(conn, smb_fname,
2746 new_dos_attributes | FILE_ATTRIBUTE_ARCHIVE,
2747 parent_dir, true) == 0) {
2748 unx_mode = smb_fname->st.st_ex_mode;
2754 /* Determine sparse flag. */
2755 if (posix_open) {
2756 /* POSIX opens are sparse by default. */
2757 fsp->is_sparse = true;
2758 } else {
2759 fsp->is_sparse = (file_existed &&
2760 (existing_dos_attributes & FILE_ATTRIBUTE_SPARSE));
2764 * Take care of inherited ACLs on created files - if default ACL not
2765 * selected.
2768 if (!posix_open && new_file_created && !def_acl) {
2770 int saved_errno = errno; /* We might get ENOSYS in the next
2771 * call.. */
2773 if (SMB_VFS_FCHMOD_ACL(fsp, unx_mode) == -1 &&
2774 errno == ENOSYS) {
2775 errno = saved_errno; /* Ignore ENOSYS */
2778 } else if (new_unx_mode) {
2780 int ret = -1;
2782 /* Attributes need changing. File already existed. */
2785 int saved_errno = errno; /* We might get ENOSYS in the
2786 * next call.. */
2787 ret = SMB_VFS_FCHMOD_ACL(fsp, new_unx_mode);
2789 if (ret == -1 && errno == ENOSYS) {
2790 errno = saved_errno; /* Ignore ENOSYS */
2791 } else {
2792 DEBUG(5, ("open_file_ntcreate: reset "
2793 "attributes of file %s to 0%o\n",
2794 smb_fname_str_dbg(smb_fname),
2795 (unsigned int)new_unx_mode));
2796 ret = 0; /* Don't do the fchmod below. */
2800 if ((ret == -1) &&
2801 (SMB_VFS_FCHMOD(fsp, new_unx_mode) == -1))
2802 DEBUG(5, ("open_file_ntcreate: failed to reset "
2803 "attributes of file %s to 0%o\n",
2804 smb_fname_str_dbg(smb_fname),
2805 (unsigned int)new_unx_mode));
2808 /* If this is a successful open, we must remove any deferred open
2809 * records. */
2810 if (req != NULL) {
2811 del_deferred_open_entry(lck, req->mid,
2812 messaging_server_id(req->sconn->msg_ctx));
2814 TALLOC_FREE(lck);
2816 return NT_STATUS_OK;
2820 /****************************************************************************
2821 Open a file for for write to ensure that we can fchmod it.
2822 ****************************************************************************/
2824 NTSTATUS open_file_fchmod(connection_struct *conn,
2825 struct smb_filename *smb_fname,
2826 files_struct **result)
2828 if (!VALID_STAT(smb_fname->st)) {
2829 return NT_STATUS_INVALID_PARAMETER;
2832 return SMB_VFS_CREATE_FILE(
2833 conn, /* conn */
2834 NULL, /* req */
2835 0, /* root_dir_fid */
2836 smb_fname, /* fname */
2837 FILE_WRITE_DATA, /* access_mask */
2838 (FILE_SHARE_READ | FILE_SHARE_WRITE | /* share_access */
2839 FILE_SHARE_DELETE),
2840 FILE_OPEN, /* create_disposition*/
2841 0, /* create_options */
2842 0, /* file_attributes */
2843 INTERNAL_OPEN_ONLY, /* oplock_request */
2844 0, /* allocation_size */
2845 0, /* private_flags */
2846 NULL, /* sd */
2847 NULL, /* ea_list */
2848 result, /* result */
2849 NULL); /* pinfo */
2852 static NTSTATUS mkdir_internal(connection_struct *conn,
2853 struct smb_filename *smb_dname,
2854 uint32 file_attributes)
2856 mode_t mode;
2857 char *parent_dir = NULL;
2858 NTSTATUS status;
2859 bool posix_open = false;
2860 bool need_re_stat = false;
2861 uint32_t access_mask = SEC_DIR_ADD_SUBDIR;
2863 if (!CAN_WRITE(conn) || (access_mask & ~(conn->share_access))) {
2864 DEBUG(5,("mkdir_internal: failing share access "
2865 "%s\n", lp_servicename(talloc_tos(), SNUM(conn))));
2866 return NT_STATUS_ACCESS_DENIED;
2869 if (!parent_dirname(talloc_tos(), smb_dname->base_name, &parent_dir,
2870 NULL)) {
2871 return NT_STATUS_NO_MEMORY;
2874 if (file_attributes & FILE_FLAG_POSIX_SEMANTICS) {
2875 posix_open = true;
2876 mode = (mode_t)(file_attributes & ~FILE_FLAG_POSIX_SEMANTICS);
2877 } else {
2878 mode = unix_mode(conn, FILE_ATTRIBUTE_DIRECTORY, smb_dname, parent_dir);
2881 status = check_parent_access(conn,
2882 smb_dname,
2883 access_mask);
2884 if(!NT_STATUS_IS_OK(status)) {
2885 DEBUG(5,("mkdir_internal: check_parent_access "
2886 "on directory %s for path %s returned %s\n",
2887 parent_dir,
2888 smb_dname->base_name,
2889 nt_errstr(status) ));
2890 return status;
2893 if (SMB_VFS_MKDIR(conn, smb_dname->base_name, mode) != 0) {
2894 return map_nt_error_from_unix(errno);
2897 /* Ensure we're checking for a symlink here.... */
2898 /* We don't want to get caught by a symlink racer. */
2900 if (SMB_VFS_LSTAT(conn, smb_dname) == -1) {
2901 DEBUG(2, ("Could not stat directory '%s' just created: %s\n",
2902 smb_fname_str_dbg(smb_dname), strerror(errno)));
2903 return map_nt_error_from_unix(errno);
2906 if (!S_ISDIR(smb_dname->st.st_ex_mode)) {
2907 DEBUG(0, ("Directory '%s' just created is not a directory !\n",
2908 smb_fname_str_dbg(smb_dname)));
2909 return NT_STATUS_NOT_A_DIRECTORY;
2912 if (lp_store_dos_attributes(SNUM(conn))) {
2913 if (!posix_open) {
2914 file_set_dosmode(conn, smb_dname,
2915 file_attributes | FILE_ATTRIBUTE_DIRECTORY,
2916 parent_dir, true);
2920 if (lp_inherit_perms(SNUM(conn))) {
2921 inherit_access_posix_acl(conn, parent_dir,
2922 smb_dname->base_name, mode);
2923 need_re_stat = true;
2926 if (!posix_open) {
2928 * Check if high bits should have been set,
2929 * then (if bits are missing): add them.
2930 * Consider bits automagically set by UNIX, i.e. SGID bit from parent
2931 * dir.
2933 if ((mode & ~(S_IRWXU|S_IRWXG|S_IRWXO)) &&
2934 (mode & ~smb_dname->st.st_ex_mode)) {
2935 SMB_VFS_CHMOD(conn, smb_dname->base_name,
2936 (smb_dname->st.st_ex_mode |
2937 (mode & ~smb_dname->st.st_ex_mode)));
2938 need_re_stat = true;
2942 /* Change the owner if required. */
2943 if (lp_inherit_owner(SNUM(conn))) {
2944 change_dir_owner_to_parent(conn, parent_dir,
2945 smb_dname->base_name,
2946 &smb_dname->st);
2947 need_re_stat = true;
2950 if (need_re_stat) {
2951 if (SMB_VFS_LSTAT(conn, smb_dname) == -1) {
2952 DEBUG(2, ("Could not stat directory '%s' just created: %s\n",
2953 smb_fname_str_dbg(smb_dname), strerror(errno)));
2954 return map_nt_error_from_unix(errno);
2958 notify_fname(conn, NOTIFY_ACTION_ADDED, FILE_NOTIFY_CHANGE_DIR_NAME,
2959 smb_dname->base_name);
2961 return NT_STATUS_OK;
2964 /****************************************************************************
2965 Open a directory from an NT SMB call.
2966 ****************************************************************************/
2968 static NTSTATUS open_directory(connection_struct *conn,
2969 struct smb_request *req,
2970 struct smb_filename *smb_dname,
2971 uint32 access_mask,
2972 uint32 share_access,
2973 uint32 create_disposition,
2974 uint32 create_options,
2975 uint32 file_attributes,
2976 int *pinfo,
2977 files_struct **result)
2979 files_struct *fsp = NULL;
2980 bool dir_existed = VALID_STAT(smb_dname->st) ? True : False;
2981 struct share_mode_lock *lck = NULL;
2982 NTSTATUS status;
2983 struct timespec mtimespec;
2984 int info = 0;
2986 if (is_ntfs_stream_smb_fname(smb_dname)) {
2987 DEBUG(2, ("open_directory: %s is a stream name!\n",
2988 smb_fname_str_dbg(smb_dname)));
2989 return NT_STATUS_NOT_A_DIRECTORY;
2992 if (!(file_attributes & FILE_FLAG_POSIX_SEMANTICS)) {
2993 /* Ensure we have a directory attribute. */
2994 file_attributes |= FILE_ATTRIBUTE_DIRECTORY;
2997 DEBUG(5,("open_directory: opening directory %s, access_mask = 0x%x, "
2998 "share_access = 0x%x create_options = 0x%x, "
2999 "create_disposition = 0x%x, file_attributes = 0x%x\n",
3000 smb_fname_str_dbg(smb_dname),
3001 (unsigned int)access_mask,
3002 (unsigned int)share_access,
3003 (unsigned int)create_options,
3004 (unsigned int)create_disposition,
3005 (unsigned int)file_attributes));
3007 status = smbd_calculate_access_mask(conn, smb_dname,
3008 access_mask, &access_mask);
3009 if (!NT_STATUS_IS_OK(status)) {
3010 DEBUG(10, ("open_directory: smbd_calculate_access_mask "
3011 "on file %s returned %s\n",
3012 smb_fname_str_dbg(smb_dname),
3013 nt_errstr(status)));
3014 return status;
3017 if ((access_mask & SEC_FLAG_SYSTEM_SECURITY) &&
3018 !security_token_has_privilege(get_current_nttok(conn),
3019 SEC_PRIV_SECURITY)) {
3020 DEBUG(10, ("open_directory: open on %s "
3021 "failed - SEC_FLAG_SYSTEM_SECURITY denied.\n",
3022 smb_fname_str_dbg(smb_dname)));
3023 return NT_STATUS_PRIVILEGE_NOT_HELD;
3026 switch( create_disposition ) {
3027 case FILE_OPEN:
3029 if (!dir_existed) {
3030 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3033 info = FILE_WAS_OPENED;
3034 break;
3036 case FILE_CREATE:
3038 /* If directory exists error. If directory doesn't
3039 * exist create. */
3041 if (dir_existed) {
3042 status = NT_STATUS_OBJECT_NAME_COLLISION;
3043 DEBUG(2, ("open_directory: unable to create "
3044 "%s. Error was %s\n",
3045 smb_fname_str_dbg(smb_dname),
3046 nt_errstr(status)));
3047 return status;
3050 status = mkdir_internal(conn, smb_dname,
3051 file_attributes);
3053 if (!NT_STATUS_IS_OK(status)) {
3054 DEBUG(2, ("open_directory: unable to create "
3055 "%s. Error was %s\n",
3056 smb_fname_str_dbg(smb_dname),
3057 nt_errstr(status)));
3058 return status;
3061 info = FILE_WAS_CREATED;
3062 break;
3064 case FILE_OPEN_IF:
3066 * If directory exists open. If directory doesn't
3067 * exist create.
3070 if (dir_existed) {
3071 status = NT_STATUS_OK;
3072 info = FILE_WAS_OPENED;
3073 } else {
3074 status = mkdir_internal(conn, smb_dname,
3075 file_attributes);
3077 if (NT_STATUS_IS_OK(status)) {
3078 info = FILE_WAS_CREATED;
3079 } else {
3080 /* Cope with create race. */
3081 if (!NT_STATUS_EQUAL(status,
3082 NT_STATUS_OBJECT_NAME_COLLISION)) {
3083 DEBUG(2, ("open_directory: unable to create "
3084 "%s. Error was %s\n",
3085 smb_fname_str_dbg(smb_dname),
3086 nt_errstr(status)));
3087 return status;
3089 info = FILE_WAS_OPENED;
3093 break;
3095 case FILE_SUPERSEDE:
3096 case FILE_OVERWRITE:
3097 case FILE_OVERWRITE_IF:
3098 default:
3099 DEBUG(5,("open_directory: invalid create_disposition "
3100 "0x%x for directory %s\n",
3101 (unsigned int)create_disposition,
3102 smb_fname_str_dbg(smb_dname)));
3103 return NT_STATUS_INVALID_PARAMETER;
3106 if(!S_ISDIR(smb_dname->st.st_ex_mode)) {
3107 DEBUG(5,("open_directory: %s is not a directory !\n",
3108 smb_fname_str_dbg(smb_dname)));
3109 return NT_STATUS_NOT_A_DIRECTORY;
3112 if (info == FILE_WAS_OPENED) {
3113 status = smbd_check_access_rights(conn, smb_dname, access_mask);
3114 if (!NT_STATUS_IS_OK(status)) {
3115 DEBUG(10, ("open_directory: smbd_check_access_rights on "
3116 "file %s failed with %s\n",
3117 smb_fname_str_dbg(smb_dname),
3118 nt_errstr(status)));
3119 return status;
3123 status = file_new(req, conn, &fsp);
3124 if(!NT_STATUS_IS_OK(status)) {
3125 return status;
3129 * Setup the files_struct for it.
3132 fsp->file_id = vfs_file_id_from_sbuf(conn, &smb_dname->st);
3133 fsp->vuid = req ? req->vuid : UID_FIELD_INVALID;
3134 fsp->file_pid = req ? req->smbpid : 0;
3135 fsp->can_lock = False;
3136 fsp->can_read = False;
3137 fsp->can_write = False;
3139 fsp->share_access = share_access;
3140 fsp->fh->private_options = 0;
3142 * According to Samba4, SEC_FILE_READ_ATTRIBUTE is always granted,
3144 fsp->access_mask = access_mask | FILE_READ_ATTRIBUTES;
3145 fsp->print_file = NULL;
3146 fsp->modified = False;
3147 fsp->oplock_type = NO_OPLOCK;
3148 fsp->sent_oplock_break = NO_BREAK_SENT;
3149 fsp->is_directory = True;
3150 fsp->posix_open = (file_attributes & FILE_FLAG_POSIX_SEMANTICS) ? True : False;
3151 status = fsp_set_smb_fname(fsp, smb_dname);
3152 if (!NT_STATUS_IS_OK(status)) {
3153 file_free(req, fsp);
3154 return status;
3157 mtimespec = smb_dname->st.st_ex_mtime;
3159 #ifdef O_DIRECTORY
3160 status = fd_open(conn, fsp, O_RDONLY|O_DIRECTORY, 0);
3161 #else
3162 /* POSIX allows us to open a directory with O_RDONLY. */
3163 status = fd_open(conn, fsp, O_RDONLY, 0);
3164 #endif
3165 if (!NT_STATUS_IS_OK(status)) {
3166 DEBUG(5, ("open_directory: Could not open fd for "
3167 "%s (%s)\n",
3168 smb_fname_str_dbg(smb_dname),
3169 nt_errstr(status)));
3170 file_free(req, fsp);
3171 return status;
3174 status = vfs_stat_fsp(fsp);
3175 if (!NT_STATUS_IS_OK(status)) {
3176 fd_close(fsp);
3177 file_free(req, fsp);
3178 return status;
3181 /* Ensure there was no race condition. */
3182 if (!check_same_stat(&smb_dname->st, &fsp->fsp_name->st)) {
3183 DEBUG(5,("open_directory: stat struct differs for "
3184 "directory %s.\n",
3185 smb_fname_str_dbg(smb_dname)));
3186 fd_close(fsp);
3187 file_free(req, fsp);
3188 return NT_STATUS_ACCESS_DENIED;
3191 lck = get_share_mode_lock(talloc_tos(), fsp->file_id,
3192 conn->connectpath, smb_dname,
3193 &mtimespec);
3195 if (lck == NULL) {
3196 DEBUG(0, ("open_directory: Could not get share mode lock for "
3197 "%s\n", smb_fname_str_dbg(smb_dname)));
3198 fd_close(fsp);
3199 file_free(req, fsp);
3200 return NT_STATUS_SHARING_VIOLATION;
3203 status = open_mode_check(conn, lck, fsp->name_hash,
3204 access_mask, share_access,
3205 create_options, &dir_existed);
3207 if (!NT_STATUS_IS_OK(status)) {
3208 TALLOC_FREE(lck);
3209 fd_close(fsp);
3210 file_free(req, fsp);
3211 return status;
3214 set_share_mode(lck, fsp, get_current_uid(conn),
3215 req ? req->mid : 0, NO_OPLOCK);
3217 /* For directories the delete on close bit at open time seems
3218 always to be honored on close... See test 19 in Samba4 BASE-DELETE. */
3219 if (create_options & FILE_DELETE_ON_CLOSE) {
3220 status = can_set_delete_on_close(fsp, 0);
3221 if (!NT_STATUS_IS_OK(status) && !NT_STATUS_EQUAL(status, NT_STATUS_DIRECTORY_NOT_EMPTY)) {
3222 TALLOC_FREE(lck);
3223 fd_close(fsp);
3224 file_free(req, fsp);
3225 return status;
3228 if (NT_STATUS_IS_OK(status)) {
3229 /* Note that here we set the *inital* delete on close flag,
3230 not the regular one. The magic gets handled in close. */
3231 fsp->initial_delete_on_close = True;
3235 TALLOC_FREE(lck);
3237 if (pinfo) {
3238 *pinfo = info;
3241 *result = fsp;
3242 return NT_STATUS_OK;
3245 NTSTATUS create_directory(connection_struct *conn, struct smb_request *req,
3246 struct smb_filename *smb_dname)
3248 NTSTATUS status;
3249 files_struct *fsp;
3251 status = SMB_VFS_CREATE_FILE(
3252 conn, /* conn */
3253 req, /* req */
3254 0, /* root_dir_fid */
3255 smb_dname, /* fname */
3256 FILE_READ_ATTRIBUTES, /* access_mask */
3257 FILE_SHARE_NONE, /* share_access */
3258 FILE_CREATE, /* create_disposition*/
3259 FILE_DIRECTORY_FILE, /* create_options */
3260 FILE_ATTRIBUTE_DIRECTORY, /* file_attributes */
3261 0, /* oplock_request */
3262 0, /* allocation_size */
3263 0, /* private_flags */
3264 NULL, /* sd */
3265 NULL, /* ea_list */
3266 &fsp, /* result */
3267 NULL); /* pinfo */
3269 if (NT_STATUS_IS_OK(status)) {
3270 close_file(req, fsp, NORMAL_CLOSE);
3273 return status;
3276 /****************************************************************************
3277 Receive notification that one of our open files has been renamed by another
3278 smbd process.
3279 ****************************************************************************/
3281 void msg_file_was_renamed(struct messaging_context *msg,
3282 void *private_data,
3283 uint32_t msg_type,
3284 struct server_id server_id,
3285 DATA_BLOB *data)
3287 files_struct *fsp;
3288 char *frm = (char *)data->data;
3289 struct file_id id;
3290 const char *sharepath;
3291 const char *base_name;
3292 const char *stream_name;
3293 struct smb_filename *smb_fname = NULL;
3294 size_t sp_len, bn_len;
3295 NTSTATUS status;
3296 struct smbd_server_connection *sconn =
3297 talloc_get_type_abort(private_data,
3298 struct smbd_server_connection);
3300 if (data->data == NULL
3301 || data->length < MSG_FILE_RENAMED_MIN_SIZE + 2) {
3302 DEBUG(0, ("msg_file_was_renamed: Got invalid msg len %d\n",
3303 (int)data->length));
3304 return;
3307 /* Unpack the message. */
3308 pull_file_id_24(frm, &id);
3309 sharepath = &frm[24];
3310 sp_len = strlen(sharepath);
3311 base_name = sharepath + sp_len + 1;
3312 bn_len = strlen(base_name);
3313 stream_name = sharepath + sp_len + 1 + bn_len + 1;
3315 /* stream_name must always be NULL if there is no stream. */
3316 if (stream_name[0] == '\0') {
3317 stream_name = NULL;
3320 status = create_synthetic_smb_fname(talloc_tos(), base_name,
3321 stream_name, NULL, &smb_fname);
3322 if (!NT_STATUS_IS_OK(status)) {
3323 return;
3326 DEBUG(10,("msg_file_was_renamed: Got rename message for sharepath %s, new name %s, "
3327 "file_id %s\n",
3328 sharepath, smb_fname_str_dbg(smb_fname),
3329 file_id_string_tos(&id)));
3331 for(fsp = file_find_di_first(sconn, id); fsp;
3332 fsp = file_find_di_next(fsp)) {
3333 if (memcmp(fsp->conn->connectpath, sharepath, sp_len) == 0) {
3335 DEBUG(10,("msg_file_was_renamed: renaming file %s from %s -> %s\n",
3336 fsp_fnum_dbg(fsp), fsp_str_dbg(fsp),
3337 smb_fname_str_dbg(smb_fname)));
3338 status = fsp_set_smb_fname(fsp, smb_fname);
3339 if (!NT_STATUS_IS_OK(status)) {
3340 goto out;
3342 } else {
3343 /* TODO. JRA. */
3344 /* Now we have the complete path we can work out if this is
3345 actually within this share and adjust newname accordingly. */
3346 DEBUG(10,("msg_file_was_renamed: share mismatch (sharepath %s "
3347 "not sharepath %s) "
3348 "%s from %s -> %s\n",
3349 fsp->conn->connectpath,
3350 sharepath,
3351 fsp_fnum_dbg(fsp),
3352 fsp_str_dbg(fsp),
3353 smb_fname_str_dbg(smb_fname)));
3356 out:
3357 TALLOC_FREE(smb_fname);
3358 return;
3362 * If a main file is opened for delete, all streams need to be checked for
3363 * !FILE_SHARE_DELETE. Do this by opening with DELETE_ACCESS.
3364 * If that works, delete them all by setting the delete on close and close.
3367 NTSTATUS open_streams_for_delete(connection_struct *conn,
3368 const char *fname)
3370 struct stream_struct *stream_info = NULL;
3371 files_struct **streams = NULL;
3372 int i;
3373 unsigned int num_streams = 0;
3374 TALLOC_CTX *frame = talloc_stackframe();
3375 NTSTATUS status;
3377 status = vfs_streaminfo(conn, NULL, fname, talloc_tos(),
3378 &num_streams, &stream_info);
3380 if (NT_STATUS_EQUAL(status, NT_STATUS_NOT_IMPLEMENTED)
3381 || NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
3382 DEBUG(10, ("no streams around\n"));
3383 TALLOC_FREE(frame);
3384 return NT_STATUS_OK;
3387 if (!NT_STATUS_IS_OK(status)) {
3388 DEBUG(10, ("vfs_streaminfo failed: %s\n",
3389 nt_errstr(status)));
3390 goto fail;
3393 DEBUG(10, ("open_streams_for_delete found %d streams\n",
3394 num_streams));
3396 if (num_streams == 0) {
3397 TALLOC_FREE(frame);
3398 return NT_STATUS_OK;
3401 streams = talloc_array(talloc_tos(), files_struct *, num_streams);
3402 if (streams == NULL) {
3403 DEBUG(0, ("talloc failed\n"));
3404 status = NT_STATUS_NO_MEMORY;
3405 goto fail;
3408 for (i=0; i<num_streams; i++) {
3409 struct smb_filename *smb_fname = NULL;
3411 if (strequal(stream_info[i].name, "::$DATA")) {
3412 streams[i] = NULL;
3413 continue;
3416 status = create_synthetic_smb_fname(talloc_tos(), fname,
3417 stream_info[i].name,
3418 NULL, &smb_fname);
3419 if (!NT_STATUS_IS_OK(status)) {
3420 goto fail;
3423 if (SMB_VFS_STAT(conn, smb_fname) == -1) {
3424 DEBUG(10, ("Unable to stat stream: %s\n",
3425 smb_fname_str_dbg(smb_fname)));
3428 status = SMB_VFS_CREATE_FILE(
3429 conn, /* conn */
3430 NULL, /* req */
3431 0, /* root_dir_fid */
3432 smb_fname, /* fname */
3433 DELETE_ACCESS, /* access_mask */
3434 (FILE_SHARE_READ | /* share_access */
3435 FILE_SHARE_WRITE | FILE_SHARE_DELETE),
3436 FILE_OPEN, /* create_disposition*/
3437 0, /* create_options */
3438 FILE_ATTRIBUTE_NORMAL, /* file_attributes */
3439 0, /* oplock_request */
3440 0, /* allocation_size */
3441 NTCREATEX_OPTIONS_PRIVATE_STREAM_DELETE, /* private_flags */
3442 NULL, /* sd */
3443 NULL, /* ea_list */
3444 &streams[i], /* result */
3445 NULL); /* pinfo */
3447 if (!NT_STATUS_IS_OK(status)) {
3448 DEBUG(10, ("Could not open stream %s: %s\n",
3449 smb_fname_str_dbg(smb_fname),
3450 nt_errstr(status)));
3452 TALLOC_FREE(smb_fname);
3453 break;
3455 TALLOC_FREE(smb_fname);
3459 * don't touch the variable "status" beyond this point :-)
3462 for (i -= 1 ; i >= 0; i--) {
3463 if (streams[i] == NULL) {
3464 continue;
3467 DEBUG(10, ("Closing stream # %d, %s\n", i,
3468 fsp_str_dbg(streams[i])));
3469 close_file(NULL, streams[i], NORMAL_CLOSE);
3472 fail:
3473 TALLOC_FREE(frame);
3474 return status;
3477 /*********************************************************************
3478 Create a default ACL by inheriting from the parent. If no inheritance
3479 from the parent available, don't set anything. This will leave the actual
3480 permissions the new file or directory already got from the filesystem
3481 as the NT ACL when read.
3482 *********************************************************************/
3484 static NTSTATUS inherit_new_acl(files_struct *fsp)
3486 TALLOC_CTX *frame = talloc_stackframe();
3487 char *parent_name = NULL;
3488 struct security_descriptor *parent_desc = NULL;
3489 NTSTATUS status = NT_STATUS_OK;
3490 struct security_descriptor *psd = NULL;
3491 const struct dom_sid *owner_sid = NULL;
3492 const struct dom_sid *group_sid = NULL;
3493 uint32_t security_info_sent = (SECINFO_OWNER | SECINFO_GROUP | SECINFO_DACL);
3494 struct security_token *token = fsp->conn->session_info->security_token;
3495 bool inherit_owner = lp_inherit_owner(SNUM(fsp->conn));
3496 bool inheritable_components = false;
3497 bool try_builtin_administrators = false;
3498 const struct dom_sid *BA_U_sid = NULL;
3499 const struct dom_sid *BA_G_sid = NULL;
3500 bool try_system = false;
3501 const struct dom_sid *SY_U_sid = NULL;
3502 const struct dom_sid *SY_G_sid = NULL;
3503 size_t size = 0;
3505 if (!parent_dirname(frame, fsp->fsp_name->base_name, &parent_name, NULL)) {
3506 TALLOC_FREE(frame);
3507 return NT_STATUS_NO_MEMORY;
3510 status = SMB_VFS_GET_NT_ACL(fsp->conn,
3511 parent_name,
3512 (SECINFO_OWNER | SECINFO_GROUP | SECINFO_DACL),
3513 frame,
3514 &parent_desc);
3515 if (!NT_STATUS_IS_OK(status)) {
3516 TALLOC_FREE(frame);
3517 return status;
3520 inheritable_components = sd_has_inheritable_components(parent_desc,
3521 fsp->is_directory);
3523 if (!inheritable_components && !inherit_owner) {
3524 TALLOC_FREE(frame);
3525 /* Nothing to inherit and not setting owner. */
3526 return NT_STATUS_OK;
3529 /* Create an inherited descriptor from the parent. */
3531 if (DEBUGLEVEL >= 10) {
3532 DEBUG(10,("inherit_new_acl: parent acl for %s is:\n",
3533 fsp_str_dbg(fsp) ));
3534 NDR_PRINT_DEBUG(security_descriptor, parent_desc);
3537 /* Inherit from parent descriptor if "inherit owner" set. */
3538 if (inherit_owner) {
3539 owner_sid = parent_desc->owner_sid;
3540 group_sid = parent_desc->group_sid;
3543 if (owner_sid == NULL) {
3544 if (security_token_has_builtin_administrators(token)) {
3545 try_builtin_administrators = true;
3546 } else if (security_token_is_system(token)) {
3547 try_builtin_administrators = true;
3548 try_system = true;
3552 if (group_sid == NULL &&
3553 token->num_sids == PRIMARY_GROUP_SID_INDEX)
3555 if (security_token_is_system(token)) {
3556 try_builtin_administrators = true;
3557 try_system = true;
3561 if (try_builtin_administrators) {
3562 struct unixid ids;
3563 bool ok;
3565 ZERO_STRUCT(ids);
3566 ok = sids_to_unixids(&global_sid_Builtin_Administrators, 1, &ids);
3567 if (ok) {
3568 switch (ids.type) {
3569 case ID_TYPE_BOTH:
3570 BA_U_sid = &global_sid_Builtin_Administrators;
3571 BA_G_sid = &global_sid_Builtin_Administrators;
3572 break;
3573 case ID_TYPE_UID:
3574 BA_U_sid = &global_sid_Builtin_Administrators;
3575 break;
3576 case ID_TYPE_GID:
3577 BA_G_sid = &global_sid_Builtin_Administrators;
3578 break;
3579 default:
3580 break;
3585 if (try_system) {
3586 struct unixid ids;
3587 bool ok;
3589 ZERO_STRUCT(ids);
3590 ok = sids_to_unixids(&global_sid_System, 1, &ids);
3591 if (ok) {
3592 switch (ids.type) {
3593 case ID_TYPE_BOTH:
3594 SY_U_sid = &global_sid_System;
3595 SY_G_sid = &global_sid_System;
3596 break;
3597 case ID_TYPE_UID:
3598 SY_U_sid = &global_sid_System;
3599 break;
3600 case ID_TYPE_GID:
3601 SY_G_sid = &global_sid_System;
3602 break;
3603 default:
3604 break;
3609 if (owner_sid == NULL) {
3610 owner_sid = BA_U_sid;
3613 if (owner_sid == NULL) {
3614 owner_sid = SY_U_sid;
3617 if (group_sid == NULL) {
3618 group_sid = SY_G_sid;
3621 if (try_system && group_sid == NULL) {
3622 group_sid = BA_G_sid;
3625 if (owner_sid == NULL) {
3626 owner_sid = &token->sids[PRIMARY_USER_SID_INDEX];
3628 if (group_sid == NULL) {
3629 if (token->num_sids == PRIMARY_GROUP_SID_INDEX) {
3630 group_sid = &token->sids[PRIMARY_USER_SID_INDEX];
3631 } else {
3632 group_sid = &token->sids[PRIMARY_GROUP_SID_INDEX];
3636 status = se_create_child_secdesc(frame,
3637 &psd,
3638 &size,
3639 parent_desc,
3640 owner_sid,
3641 group_sid,
3642 fsp->is_directory);
3643 if (!NT_STATUS_IS_OK(status)) {
3644 TALLOC_FREE(frame);
3645 return status;
3648 /* If inheritable_components == false,
3649 se_create_child_secdesc()
3650 creates a security desriptor with a NULL dacl
3651 entry, but with SEC_DESC_DACL_PRESENT. We need
3652 to remove that flag. */
3654 if (!inheritable_components) {
3655 security_info_sent &= ~SECINFO_DACL;
3656 psd->type &= ~SEC_DESC_DACL_PRESENT;
3659 if (DEBUGLEVEL >= 10) {
3660 DEBUG(10,("inherit_new_acl: child acl for %s is:\n",
3661 fsp_str_dbg(fsp) ));
3662 NDR_PRINT_DEBUG(security_descriptor, psd);
3665 if (inherit_owner) {
3666 /* We need to be root to force this. */
3667 become_root();
3669 status = SMB_VFS_FSET_NT_ACL(fsp,
3670 security_info_sent,
3671 psd);
3672 if (inherit_owner) {
3673 unbecome_root();
3675 TALLOC_FREE(frame);
3676 return status;
3680 * Wrapper around open_file_ntcreate and open_directory
3683 static NTSTATUS create_file_unixpath(connection_struct *conn,
3684 struct smb_request *req,
3685 struct smb_filename *smb_fname,
3686 uint32_t access_mask,
3687 uint32_t share_access,
3688 uint32_t create_disposition,
3689 uint32_t create_options,
3690 uint32_t file_attributes,
3691 uint32_t oplock_request,
3692 uint64_t allocation_size,
3693 uint32_t private_flags,
3694 struct security_descriptor *sd,
3695 struct ea_list *ea_list,
3697 files_struct **result,
3698 int *pinfo)
3700 int info = FILE_WAS_OPENED;
3701 files_struct *base_fsp = NULL;
3702 files_struct *fsp = NULL;
3703 NTSTATUS status;
3705 DEBUG(10,("create_file_unixpath: access_mask = 0x%x "
3706 "file_attributes = 0x%x, share_access = 0x%x, "
3707 "create_disposition = 0x%x create_options = 0x%x "
3708 "oplock_request = 0x%x private_flags = 0x%x "
3709 "ea_list = 0x%p, sd = 0x%p, "
3710 "fname = %s\n",
3711 (unsigned int)access_mask,
3712 (unsigned int)file_attributes,
3713 (unsigned int)share_access,
3714 (unsigned int)create_disposition,
3715 (unsigned int)create_options,
3716 (unsigned int)oplock_request,
3717 (unsigned int)private_flags,
3718 ea_list, sd, smb_fname_str_dbg(smb_fname)));
3720 if (create_options & FILE_OPEN_BY_FILE_ID) {
3721 status = NT_STATUS_NOT_SUPPORTED;
3722 goto fail;
3725 if (create_options & NTCREATEX_OPTIONS_INVALID_PARAM_MASK) {
3726 status = NT_STATUS_INVALID_PARAMETER;
3727 goto fail;
3730 if (req == NULL) {
3731 oplock_request |= INTERNAL_OPEN_ONLY;
3734 if ((conn->fs_capabilities & FILE_NAMED_STREAMS)
3735 && (access_mask & DELETE_ACCESS)
3736 && !is_ntfs_stream_smb_fname(smb_fname)) {
3738 * We can't open a file with DELETE access if any of the
3739 * streams is open without FILE_SHARE_DELETE
3741 status = open_streams_for_delete(conn, smb_fname->base_name);
3743 if (!NT_STATUS_IS_OK(status)) {
3744 goto fail;
3748 if ((access_mask & SEC_FLAG_SYSTEM_SECURITY) &&
3749 !security_token_has_privilege(get_current_nttok(conn),
3750 SEC_PRIV_SECURITY)) {
3751 DEBUG(10, ("create_file_unixpath: open on %s "
3752 "failed - SEC_FLAG_SYSTEM_SECURITY denied.\n",
3753 smb_fname_str_dbg(smb_fname)));
3754 status = NT_STATUS_PRIVILEGE_NOT_HELD;
3755 goto fail;
3758 if ((conn->fs_capabilities & FILE_NAMED_STREAMS)
3759 && is_ntfs_stream_smb_fname(smb_fname)
3760 && (!(private_flags & NTCREATEX_OPTIONS_PRIVATE_STREAM_DELETE))) {
3761 uint32 base_create_disposition;
3762 struct smb_filename *smb_fname_base = NULL;
3764 if (create_options & FILE_DIRECTORY_FILE) {
3765 status = NT_STATUS_NOT_A_DIRECTORY;
3766 goto fail;
3769 switch (create_disposition) {
3770 case FILE_OPEN:
3771 base_create_disposition = FILE_OPEN;
3772 break;
3773 default:
3774 base_create_disposition = FILE_OPEN_IF;
3775 break;
3778 /* Create an smb_filename with stream_name == NULL. */
3779 status = create_synthetic_smb_fname(talloc_tos(),
3780 smb_fname->base_name,
3781 NULL, NULL,
3782 &smb_fname_base);
3783 if (!NT_STATUS_IS_OK(status)) {
3784 goto fail;
3787 if (SMB_VFS_STAT(conn, smb_fname_base) == -1) {
3788 DEBUG(10, ("Unable to stat stream: %s\n",
3789 smb_fname_str_dbg(smb_fname_base)));
3790 } else {
3792 * https://bugzilla.samba.org/show_bug.cgi?id=10229
3793 * We need to check if the requested access mask
3794 * could be used to open the underlying file (if
3795 * it existed), as we're passing in zero for the
3796 * access mask to the base filename.
3798 status = check_base_file_access(conn,
3799 smb_fname_base,
3800 access_mask);
3802 if (!NT_STATUS_IS_OK(status)) {
3803 DEBUG(10, ("Permission check "
3804 "for base %s failed: "
3805 "%s\n", smb_fname->base_name,
3806 nt_errstr(status)));
3807 goto fail;
3811 /* Open the base file. */
3812 status = create_file_unixpath(conn, NULL, smb_fname_base, 0,
3813 FILE_SHARE_READ
3814 | FILE_SHARE_WRITE
3815 | FILE_SHARE_DELETE,
3816 base_create_disposition,
3817 0, 0, 0, 0, 0, NULL, NULL,
3818 &base_fsp, NULL);
3819 TALLOC_FREE(smb_fname_base);
3821 if (!NT_STATUS_IS_OK(status)) {
3822 DEBUG(10, ("create_file_unixpath for base %s failed: "
3823 "%s\n", smb_fname->base_name,
3824 nt_errstr(status)));
3825 goto fail;
3827 /* we don't need to low level fd */
3828 fd_close(base_fsp);
3832 * If it's a request for a directory open, deal with it separately.
3835 if (create_options & FILE_DIRECTORY_FILE) {
3837 if (create_options & FILE_NON_DIRECTORY_FILE) {
3838 status = NT_STATUS_INVALID_PARAMETER;
3839 goto fail;
3842 /* Can't open a temp directory. IFS kit test. */
3843 if (!(file_attributes & FILE_FLAG_POSIX_SEMANTICS) &&
3844 (file_attributes & FILE_ATTRIBUTE_TEMPORARY)) {
3845 status = NT_STATUS_INVALID_PARAMETER;
3846 goto fail;
3850 * We will get a create directory here if the Win32
3851 * app specified a security descriptor in the
3852 * CreateDirectory() call.
3855 oplock_request = 0;
3856 status = open_directory(
3857 conn, req, smb_fname, access_mask, share_access,
3858 create_disposition, create_options, file_attributes,
3859 &info, &fsp);
3860 } else {
3863 * Ordinary file case.
3866 status = file_new(req, conn, &fsp);
3867 if(!NT_STATUS_IS_OK(status)) {
3868 goto fail;
3871 status = fsp_set_smb_fname(fsp, smb_fname);
3872 if (!NT_STATUS_IS_OK(status)) {
3873 goto fail;
3876 if (base_fsp) {
3878 * We're opening the stream element of a
3879 * base_fsp we already opened. Set up the
3880 * base_fsp pointer.
3882 fsp->base_fsp = base_fsp;
3885 if (allocation_size) {
3886 fsp->initial_allocation_size = smb_roundup(fsp->conn,
3887 allocation_size);
3890 status = open_file_ntcreate(conn,
3891 req,
3892 access_mask,
3893 share_access,
3894 create_disposition,
3895 create_options,
3896 file_attributes,
3897 oplock_request,
3898 private_flags,
3899 &info,
3900 fsp);
3902 if(!NT_STATUS_IS_OK(status)) {
3903 file_free(req, fsp);
3904 fsp = NULL;
3907 if (NT_STATUS_EQUAL(status, NT_STATUS_FILE_IS_A_DIRECTORY)) {
3909 /* A stream open never opens a directory */
3911 if (base_fsp) {
3912 status = NT_STATUS_FILE_IS_A_DIRECTORY;
3913 goto fail;
3917 * Fail the open if it was explicitly a non-directory
3918 * file.
3921 if (create_options & FILE_NON_DIRECTORY_FILE) {
3922 status = NT_STATUS_FILE_IS_A_DIRECTORY;
3923 goto fail;
3926 oplock_request = 0;
3927 status = open_directory(
3928 conn, req, smb_fname, access_mask,
3929 share_access, create_disposition,
3930 create_options, file_attributes,
3931 &info, &fsp);
3935 if (!NT_STATUS_IS_OK(status)) {
3936 goto fail;
3939 fsp->base_fsp = base_fsp;
3941 if ((ea_list != NULL) &&
3942 ((info == FILE_WAS_CREATED) || (info == FILE_WAS_OVERWRITTEN))) {
3943 status = set_ea(conn, fsp, fsp->fsp_name, ea_list);
3944 if (!NT_STATUS_IS_OK(status)) {
3945 goto fail;
3949 if (!fsp->is_directory && S_ISDIR(fsp->fsp_name->st.st_ex_mode)) {
3950 status = NT_STATUS_ACCESS_DENIED;
3951 goto fail;
3954 /* Save the requested allocation size. */
3955 if ((info == FILE_WAS_CREATED) || (info == FILE_WAS_OVERWRITTEN)) {
3956 if (allocation_size
3957 && (allocation_size > fsp->fsp_name->st.st_ex_size)) {
3958 fsp->initial_allocation_size = smb_roundup(
3959 fsp->conn, allocation_size);
3960 if (fsp->is_directory) {
3961 /* Can't set allocation size on a directory. */
3962 status = NT_STATUS_ACCESS_DENIED;
3963 goto fail;
3965 if (vfs_allocate_file_space(
3966 fsp, fsp->initial_allocation_size) == -1) {
3967 status = NT_STATUS_DISK_FULL;
3968 goto fail;
3970 } else {
3971 fsp->initial_allocation_size = smb_roundup(
3972 fsp->conn, (uint64_t)fsp->fsp_name->st.st_ex_size);
3974 } else {
3975 fsp->initial_allocation_size = 0;
3978 if ((info == FILE_WAS_CREATED) && lp_nt_acl_support(SNUM(conn)) &&
3979 fsp->base_fsp == NULL) {
3980 if (sd != NULL) {
3982 * According to the MS documentation, the only time the security
3983 * descriptor is applied to the opened file is iff we *created* the
3984 * file; an existing file stays the same.
3986 * Also, it seems (from observation) that you can open the file with
3987 * any access mask but you can still write the sd. We need to override
3988 * the granted access before we call set_sd
3989 * Patch for bug #2242 from Tom Lackemann <cessnatomny@yahoo.com>.
3992 uint32_t sec_info_sent;
3993 uint32_t saved_access_mask = fsp->access_mask;
3995 sec_info_sent = get_sec_info(sd);
3997 fsp->access_mask = FILE_GENERIC_ALL;
3999 if (sec_info_sent & (SECINFO_OWNER|
4000 SECINFO_GROUP|
4001 SECINFO_DACL|
4002 SECINFO_SACL)) {
4003 status = set_sd(fsp, sd, sec_info_sent);
4006 fsp->access_mask = saved_access_mask;
4008 if (!NT_STATUS_IS_OK(status)) {
4009 goto fail;
4011 } else if (lp_inherit_acls(SNUM(conn))) {
4012 /* Inherit from parent. Errors here are not fatal. */
4013 status = inherit_new_acl(fsp);
4014 if (!NT_STATUS_IS_OK(status)) {
4015 DEBUG(10,("inherit_new_acl: failed for %s with %s\n",
4016 fsp_str_dbg(fsp),
4017 nt_errstr(status) ));
4022 DEBUG(10, ("create_file_unixpath: info=%d\n", info));
4024 *result = fsp;
4025 if (pinfo != NULL) {
4026 *pinfo = info;
4029 smb_fname->st = fsp->fsp_name->st;
4031 return NT_STATUS_OK;
4033 fail:
4034 DEBUG(10, ("create_file_unixpath: %s\n", nt_errstr(status)));
4036 if (fsp != NULL) {
4037 if (base_fsp && fsp->base_fsp == base_fsp) {
4039 * The close_file below will close
4040 * fsp->base_fsp.
4042 base_fsp = NULL;
4044 close_file(req, fsp, ERROR_CLOSE);
4045 fsp = NULL;
4047 if (base_fsp != NULL) {
4048 close_file(req, base_fsp, ERROR_CLOSE);
4049 base_fsp = NULL;
4051 return status;
4055 * Calculate the full path name given a relative fid.
4057 NTSTATUS get_relative_fid_filename(connection_struct *conn,
4058 struct smb_request *req,
4059 uint16_t root_dir_fid,
4060 const struct smb_filename *smb_fname,
4061 struct smb_filename **smb_fname_out)
4063 files_struct *dir_fsp;
4064 char *parent_fname = NULL;
4065 char *new_base_name = NULL;
4066 NTSTATUS status;
4068 if (root_dir_fid == 0 || !smb_fname) {
4069 status = NT_STATUS_INTERNAL_ERROR;
4070 goto out;
4073 dir_fsp = file_fsp(req, root_dir_fid);
4075 if (dir_fsp == NULL) {
4076 status = NT_STATUS_INVALID_HANDLE;
4077 goto out;
4080 if (is_ntfs_stream_smb_fname(dir_fsp->fsp_name)) {
4081 status = NT_STATUS_INVALID_HANDLE;
4082 goto out;
4085 if (!dir_fsp->is_directory) {
4088 * Check to see if this is a mac fork of some kind.
4091 if ((conn->fs_capabilities & FILE_NAMED_STREAMS) &&
4092 is_ntfs_stream_smb_fname(smb_fname)) {
4093 status = NT_STATUS_OBJECT_PATH_NOT_FOUND;
4094 goto out;
4098 we need to handle the case when we get a
4099 relative open relative to a file and the
4100 pathname is blank - this is a reopen!
4101 (hint from demyn plantenberg)
4104 status = NT_STATUS_INVALID_HANDLE;
4105 goto out;
4108 if (ISDOT(dir_fsp->fsp_name->base_name)) {
4110 * We're at the toplevel dir, the final file name
4111 * must not contain ./, as this is filtered out
4112 * normally by srvstr_get_path and unix_convert
4113 * explicitly rejects paths containing ./.
4115 parent_fname = talloc_strdup(talloc_tos(), "");
4116 if (parent_fname == NULL) {
4117 status = NT_STATUS_NO_MEMORY;
4118 goto out;
4120 } else {
4121 size_t dir_name_len = strlen(dir_fsp->fsp_name->base_name);
4124 * Copy in the base directory name.
4127 parent_fname = talloc_array(talloc_tos(), char,
4128 dir_name_len+2);
4129 if (parent_fname == NULL) {
4130 status = NT_STATUS_NO_MEMORY;
4131 goto out;
4133 memcpy(parent_fname, dir_fsp->fsp_name->base_name,
4134 dir_name_len+1);
4137 * Ensure it ends in a '/'.
4138 * We used TALLOC_SIZE +2 to add space for the '/'.
4141 if(dir_name_len
4142 && (parent_fname[dir_name_len-1] != '\\')
4143 && (parent_fname[dir_name_len-1] != '/')) {
4144 parent_fname[dir_name_len] = '/';
4145 parent_fname[dir_name_len+1] = '\0';
4149 new_base_name = talloc_asprintf(talloc_tos(), "%s%s", parent_fname,
4150 smb_fname->base_name);
4151 if (new_base_name == NULL) {
4152 status = NT_STATUS_NO_MEMORY;
4153 goto out;
4156 status = filename_convert(req,
4157 conn,
4158 req->flags2 & FLAGS2_DFS_PATHNAMES,
4159 new_base_name,
4161 NULL,
4162 smb_fname_out);
4163 if (!NT_STATUS_IS_OK(status)) {
4164 goto out;
4167 out:
4168 TALLOC_FREE(parent_fname);
4169 TALLOC_FREE(new_base_name);
4170 return status;
4173 NTSTATUS create_file_default(connection_struct *conn,
4174 struct smb_request *req,
4175 uint16_t root_dir_fid,
4176 struct smb_filename *smb_fname,
4177 uint32_t access_mask,
4178 uint32_t share_access,
4179 uint32_t create_disposition,
4180 uint32_t create_options,
4181 uint32_t file_attributes,
4182 uint32_t oplock_request,
4183 uint64_t allocation_size,
4184 uint32_t private_flags,
4185 struct security_descriptor *sd,
4186 struct ea_list *ea_list,
4187 files_struct **result,
4188 int *pinfo)
4190 int info = FILE_WAS_OPENED;
4191 files_struct *fsp = NULL;
4192 NTSTATUS status;
4193 bool stream_name = false;
4195 DEBUG(10,("create_file: access_mask = 0x%x "
4196 "file_attributes = 0x%x, share_access = 0x%x, "
4197 "create_disposition = 0x%x create_options = 0x%x "
4198 "oplock_request = 0x%x "
4199 "private_flags = 0x%x "
4200 "root_dir_fid = 0x%x, ea_list = 0x%p, sd = 0x%p, "
4201 "fname = %s\n",
4202 (unsigned int)access_mask,
4203 (unsigned int)file_attributes,
4204 (unsigned int)share_access,
4205 (unsigned int)create_disposition,
4206 (unsigned int)create_options,
4207 (unsigned int)oplock_request,
4208 (unsigned int)private_flags,
4209 (unsigned int)root_dir_fid,
4210 ea_list, sd, smb_fname_str_dbg(smb_fname)));
4213 * Calculate the filename from the root_dir_if if necessary.
4216 if (root_dir_fid != 0) {
4217 struct smb_filename *smb_fname_out = NULL;
4218 status = get_relative_fid_filename(conn, req, root_dir_fid,
4219 smb_fname, &smb_fname_out);
4220 if (!NT_STATUS_IS_OK(status)) {
4221 goto fail;
4223 smb_fname = smb_fname_out;
4227 * Check to see if this is a mac fork of some kind.
4230 stream_name = is_ntfs_stream_smb_fname(smb_fname);
4231 if (stream_name) {
4232 enum FAKE_FILE_TYPE fake_file_type;
4234 fake_file_type = is_fake_file(smb_fname);
4236 if (fake_file_type != FAKE_FILE_TYPE_NONE) {
4239 * Here we go! support for changing the disk quotas
4240 * --metze
4242 * We need to fake up to open this MAGIC QUOTA file
4243 * and return a valid FID.
4245 * w2k close this file directly after openening xp
4246 * also tries a QUERY_FILE_INFO on the file and then
4247 * close it
4249 status = open_fake_file(req, conn, req->vuid,
4250 fake_file_type, smb_fname,
4251 access_mask, &fsp);
4252 if (!NT_STATUS_IS_OK(status)) {
4253 goto fail;
4256 ZERO_STRUCT(smb_fname->st);
4257 goto done;
4260 if (!(conn->fs_capabilities & FILE_NAMED_STREAMS)) {
4261 status = NT_STATUS_OBJECT_NAME_NOT_FOUND;
4262 goto fail;
4266 if (is_ntfs_default_stream_smb_fname(smb_fname)) {
4267 int ret;
4268 smb_fname->stream_name = NULL;
4269 /* We have to handle this error here. */
4270 if (create_options & FILE_DIRECTORY_FILE) {
4271 status = NT_STATUS_NOT_A_DIRECTORY;
4272 goto fail;
4274 if (lp_posix_pathnames()) {
4275 ret = SMB_VFS_LSTAT(conn, smb_fname);
4276 } else {
4277 ret = SMB_VFS_STAT(conn, smb_fname);
4280 if (ret == 0 && VALID_STAT_OF_DIR(smb_fname->st)) {
4281 status = NT_STATUS_FILE_IS_A_DIRECTORY;
4282 goto fail;
4286 status = create_file_unixpath(
4287 conn, req, smb_fname, access_mask, share_access,
4288 create_disposition, create_options, file_attributes,
4289 oplock_request, allocation_size, private_flags,
4290 sd, ea_list,
4291 &fsp, &info);
4293 if (!NT_STATUS_IS_OK(status)) {
4294 goto fail;
4297 done:
4298 DEBUG(10, ("create_file: info=%d\n", info));
4300 *result = fsp;
4301 if (pinfo != NULL) {
4302 *pinfo = info;
4304 return NT_STATUS_OK;
4306 fail:
4307 DEBUG(10, ("create_file: %s\n", nt_errstr(status)));
4309 if (fsp != NULL) {
4310 close_file(req, fsp, ERROR_CLOSE);
4311 fsp = NULL;
4313 return status;