docs: mention --update and --encrypt in smbget manpage.
[Samba.git] / source3 / smbd / open.c
blobcd1bb7230549033ca466c585d840ea5a5d306aa7
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"
36 #include "source3/lib/dbwrap/dbwrap_watch.h"
38 extern const struct generic_mapping file_generic_mapping;
40 struct deferred_open_record {
41 bool delayed_for_oplocks;
42 bool async_open;
43 struct file_id id;
46 /****************************************************************************
47 If the requester wanted DELETE_ACCESS and was rejected because
48 the file ACL didn't include DELETE_ACCESS, see if the parent ACL
49 overrides this.
50 ****************************************************************************/
52 static bool parent_override_delete(connection_struct *conn,
53 const struct smb_filename *smb_fname,
54 uint32_t access_mask,
55 uint32_t rejected_mask)
57 if ((access_mask & DELETE_ACCESS) &&
58 (rejected_mask & DELETE_ACCESS) &&
59 can_delete_file_in_directory(conn, smb_fname)) {
60 return true;
62 return false;
65 /****************************************************************************
66 Check if we have open rights.
67 ****************************************************************************/
69 NTSTATUS smbd_check_access_rights(struct connection_struct *conn,
70 const struct smb_filename *smb_fname,
71 bool use_privs,
72 uint32_t access_mask)
74 /* Check if we have rights to open. */
75 NTSTATUS status;
76 struct security_descriptor *sd = NULL;
77 uint32_t rejected_share_access;
78 uint32_t rejected_mask = access_mask;
79 uint32_t do_not_check_mask = 0;
81 rejected_share_access = access_mask & ~(conn->share_access);
83 if (rejected_share_access) {
84 DEBUG(10, ("smbd_check_access_rights: rejected share access 0x%x "
85 "on %s (0x%x)\n",
86 (unsigned int)access_mask,
87 smb_fname_str_dbg(smb_fname),
88 (unsigned int)rejected_share_access ));
89 return NT_STATUS_ACCESS_DENIED;
92 if (!use_privs && get_current_uid(conn) == (uid_t)0) {
93 /* I'm sorry sir, I didn't know you were root... */
94 DEBUG(10,("smbd_check_access_rights: root override "
95 "on %s. Granting 0x%x\n",
96 smb_fname_str_dbg(smb_fname),
97 (unsigned int)access_mask ));
98 return NT_STATUS_OK;
101 if ((access_mask & DELETE_ACCESS) && !lp_acl_check_permissions(SNUM(conn))) {
102 DEBUG(10,("smbd_check_access_rights: not checking ACL "
103 "on DELETE_ACCESS on file %s. Granting 0x%x\n",
104 smb_fname_str_dbg(smb_fname),
105 (unsigned int)access_mask ));
106 return NT_STATUS_OK;
109 if (access_mask == DELETE_ACCESS &&
110 VALID_STAT(smb_fname->st) &&
111 S_ISLNK(smb_fname->st.st_ex_mode)) {
112 /* We can always delete a symlink. */
113 DEBUG(10,("smbd_check_access_rights: not checking ACL "
114 "on DELETE_ACCESS on symlink %s.\n",
115 smb_fname_str_dbg(smb_fname) ));
116 return NT_STATUS_OK;
119 status = SMB_VFS_GET_NT_ACL(conn, smb_fname->base_name,
120 (SECINFO_OWNER |
121 SECINFO_GROUP |
122 SECINFO_DACL), talloc_tos(), &sd);
124 if (!NT_STATUS_IS_OK(status)) {
125 DEBUG(10, ("smbd_check_access_rights: Could not get acl "
126 "on %s: %s\n",
127 smb_fname_str_dbg(smb_fname),
128 nt_errstr(status)));
130 if (NT_STATUS_EQUAL(status, NT_STATUS_ACCESS_DENIED)) {
131 goto access_denied;
134 return status;
138 * If we can access the path to this file, by
139 * default we have FILE_READ_ATTRIBUTES from the
140 * containing directory. See the section:
141 * "Algorithm to Check Access to an Existing File"
142 * in MS-FSA.pdf.
144 * se_file_access_check() also takes care of
145 * owner WRITE_DAC and READ_CONTROL.
147 do_not_check_mask = FILE_READ_ATTRIBUTES;
150 * Samba 3.6 and earlier granted execute access even
151 * if the ACL did not contain execute rights.
152 * Samba 4.0 is more correct and checks it.
153 * The compatibilty mode allows to skip this check
154 * to smoothen upgrades.
156 if (lp_acl_allow_execute_always(SNUM(conn))) {
157 do_not_check_mask |= FILE_EXECUTE;
160 status = se_file_access_check(sd,
161 get_current_nttok(conn),
162 use_privs,
163 (access_mask & ~do_not_check_mask),
164 &rejected_mask);
166 DEBUG(10,("smbd_check_access_rights: file %s requesting "
167 "0x%x returning 0x%x (%s)\n",
168 smb_fname_str_dbg(smb_fname),
169 (unsigned int)access_mask,
170 (unsigned int)rejected_mask,
171 nt_errstr(status) ));
173 if (!NT_STATUS_IS_OK(status)) {
174 if (DEBUGLEVEL >= 10) {
175 DEBUG(10,("smbd_check_access_rights: acl for %s is:\n",
176 smb_fname_str_dbg(smb_fname) ));
177 NDR_PRINT_DEBUG(security_descriptor, sd);
181 TALLOC_FREE(sd);
183 if (NT_STATUS_IS_OK(status) ||
184 !NT_STATUS_EQUAL(status, NT_STATUS_ACCESS_DENIED)) {
185 return status;
188 /* Here we know status == NT_STATUS_ACCESS_DENIED. */
190 access_denied:
192 if ((access_mask & FILE_WRITE_ATTRIBUTES) &&
193 (rejected_mask & FILE_WRITE_ATTRIBUTES) &&
194 !lp_store_dos_attributes(SNUM(conn)) &&
195 (lp_map_readonly(SNUM(conn)) ||
196 lp_map_archive(SNUM(conn)) ||
197 lp_map_hidden(SNUM(conn)) ||
198 lp_map_system(SNUM(conn)))) {
199 rejected_mask &= ~FILE_WRITE_ATTRIBUTES;
201 DEBUG(10,("smbd_check_access_rights: "
202 "overrode "
203 "FILE_WRITE_ATTRIBUTES "
204 "on file %s\n",
205 smb_fname_str_dbg(smb_fname)));
208 if (parent_override_delete(conn,
209 smb_fname,
210 access_mask,
211 rejected_mask)) {
212 /* Were we trying to do an open
213 * for delete and didn't get DELETE
214 * access (only) ? Check if the
215 * directory allows DELETE_CHILD.
216 * See here:
217 * http://blogs.msdn.com/oldnewthing/archive/2004/06/04/148426.aspx
218 * for details. */
220 rejected_mask &= ~DELETE_ACCESS;
222 DEBUG(10,("smbd_check_access_rights: "
223 "overrode "
224 "DELETE_ACCESS on "
225 "file %s\n",
226 smb_fname_str_dbg(smb_fname)));
229 if (rejected_mask != 0) {
230 return NT_STATUS_ACCESS_DENIED;
232 return NT_STATUS_OK;
235 static NTSTATUS check_parent_access(struct connection_struct *conn,
236 struct smb_filename *smb_fname,
237 uint32_t access_mask)
239 NTSTATUS status;
240 char *parent_dir = NULL;
241 struct security_descriptor *parent_sd = NULL;
242 uint32_t access_granted = 0;
244 if (!parent_dirname(talloc_tos(),
245 smb_fname->base_name,
246 &parent_dir,
247 NULL)) {
248 return NT_STATUS_NO_MEMORY;
251 if (get_current_uid(conn) == (uid_t)0) {
252 /* I'm sorry sir, I didn't know you were root... */
253 DEBUG(10,("check_parent_access: root override "
254 "on %s. Granting 0x%x\n",
255 smb_fname_str_dbg(smb_fname),
256 (unsigned int)access_mask ));
257 return NT_STATUS_OK;
260 status = SMB_VFS_GET_NT_ACL(conn,
261 parent_dir,
262 SECINFO_DACL,
263 talloc_tos(),
264 &parent_sd);
266 if (!NT_STATUS_IS_OK(status)) {
267 DEBUG(5,("check_parent_access: SMB_VFS_GET_NT_ACL failed for "
268 "%s with error %s\n",
269 parent_dir,
270 nt_errstr(status)));
271 return status;
275 * If we can access the path to this file, by
276 * default we have FILE_READ_ATTRIBUTES from the
277 * containing directory. See the section:
278 * "Algorithm to Check Access to an Existing File"
279 * in MS-FSA.pdf.
281 * se_file_access_check() also takes care of
282 * owner WRITE_DAC and READ_CONTROL.
284 status = se_file_access_check(parent_sd,
285 get_current_nttok(conn),
286 false,
287 (access_mask & ~FILE_READ_ATTRIBUTES),
288 &access_granted);
289 if(!NT_STATUS_IS_OK(status)) {
290 DEBUG(5,("check_parent_access: access check "
291 "on directory %s for "
292 "path %s for mask 0x%x returned (0x%x) %s\n",
293 parent_dir,
294 smb_fname->base_name,
295 access_mask,
296 access_granted,
297 nt_errstr(status) ));
298 return status;
301 return NT_STATUS_OK;
304 /****************************************************************************
305 Ensure when opening a base file for a stream open that we have permissions
306 to do so given the access mask on the base file.
307 ****************************************************************************/
309 static NTSTATUS check_base_file_access(struct connection_struct *conn,
310 struct smb_filename *smb_fname,
311 uint32_t access_mask)
313 NTSTATUS status;
315 status = smbd_calculate_access_mask(conn, smb_fname,
316 false,
317 access_mask,
318 &access_mask);
319 if (!NT_STATUS_IS_OK(status)) {
320 DEBUG(10, ("smbd_calculate_access_mask "
321 "on file %s returned %s\n",
322 smb_fname_str_dbg(smb_fname),
323 nt_errstr(status)));
324 return status;
327 if (access_mask & (FILE_WRITE_DATA|FILE_APPEND_DATA)) {
328 uint32_t dosattrs;
329 if (!CAN_WRITE(conn)) {
330 return NT_STATUS_ACCESS_DENIED;
332 dosattrs = dos_mode(conn, smb_fname);
333 if (IS_DOS_READONLY(dosattrs)) {
334 return NT_STATUS_ACCESS_DENIED;
338 return smbd_check_access_rights(conn,
339 smb_fname,
340 false,
341 access_mask);
344 /****************************************************************************
345 fd support routines - attempt to do a dos_open.
346 ****************************************************************************/
348 NTSTATUS fd_open(struct connection_struct *conn,
349 files_struct *fsp,
350 int flags,
351 mode_t mode)
353 struct smb_filename *smb_fname = fsp->fsp_name;
354 NTSTATUS status = NT_STATUS_OK;
356 #ifdef O_NOFOLLOW
358 * Never follow symlinks on a POSIX client. The
359 * client should be doing this.
362 if (fsp->posix_open || !lp_symlinks(SNUM(conn))) {
363 flags |= O_NOFOLLOW;
365 #endif
367 fsp->fh->fd = SMB_VFS_OPEN(conn, smb_fname, fsp, flags, mode);
368 if (fsp->fh->fd == -1) {
369 int posix_errno = errno;
370 #ifdef O_NOFOLLOW
371 #if defined(ENOTSUP) && defined(OSF1)
372 /* handle special Tru64 errno */
373 if (errno == ENOTSUP) {
374 posix_errno = ELOOP;
376 #endif /* ENOTSUP */
377 #ifdef EFTYPE
378 /* fix broken NetBSD errno */
379 if (errno == EFTYPE) {
380 posix_errno = ELOOP;
382 #endif /* EFTYPE */
383 /* fix broken FreeBSD errno */
384 if (errno == EMLINK) {
385 posix_errno = ELOOP;
387 #endif /* O_NOFOLLOW */
388 status = map_nt_error_from_unix(posix_errno);
389 if (errno == EMFILE) {
390 static time_t last_warned = 0L;
392 if (time((time_t *) NULL) > last_warned) {
393 DEBUG(0,("Too many open files, unable "
394 "to open more! smbd's max "
395 "open files = %d\n",
396 lp_max_open_files()));
397 last_warned = time((time_t *) NULL);
403 DEBUG(10,("fd_open: name %s, flags = 0%o mode = 0%o, fd = %d. %s\n",
404 smb_fname_str_dbg(smb_fname), flags, (int)mode, fsp->fh->fd,
405 (fsp->fh->fd == -1) ? strerror(errno) : "" ));
407 return status;
410 /****************************************************************************
411 Close the file associated with a fsp.
412 ****************************************************************************/
414 NTSTATUS fd_close(files_struct *fsp)
416 int ret;
418 if (fsp->dptr) {
419 dptr_CloseDir(fsp);
421 if (fsp->fh->fd == -1) {
422 return NT_STATUS_OK; /* What we used to call a stat open. */
424 if (fsp->fh->ref_count > 1) {
425 return NT_STATUS_OK; /* Shared handle. Only close last reference. */
428 ret = SMB_VFS_CLOSE(fsp);
429 fsp->fh->fd = -1;
430 if (ret == -1) {
431 return map_nt_error_from_unix(errno);
433 return NT_STATUS_OK;
436 /****************************************************************************
437 Change the ownership of a file to that of the parent directory.
438 Do this by fd if possible.
439 ****************************************************************************/
441 void change_file_owner_to_parent(connection_struct *conn,
442 const char *inherit_from_dir,
443 files_struct *fsp)
445 struct smb_filename *smb_fname_parent;
446 int ret;
448 smb_fname_parent = synthetic_smb_fname(talloc_tos(), inherit_from_dir,
449 NULL, NULL);
450 if (smb_fname_parent == NULL) {
451 return;
454 ret = SMB_VFS_STAT(conn, smb_fname_parent);
455 if (ret == -1) {
456 DEBUG(0,("change_file_owner_to_parent: failed to stat parent "
457 "directory %s. Error was %s\n",
458 smb_fname_str_dbg(smb_fname_parent),
459 strerror(errno)));
460 TALLOC_FREE(smb_fname_parent);
461 return;
464 if (smb_fname_parent->st.st_ex_uid == fsp->fsp_name->st.st_ex_uid) {
465 /* Already this uid - no need to change. */
466 DEBUG(10,("change_file_owner_to_parent: file %s "
467 "is already owned by uid %d\n",
468 fsp_str_dbg(fsp),
469 (int)fsp->fsp_name->st.st_ex_uid ));
470 TALLOC_FREE(smb_fname_parent);
471 return;
474 become_root();
475 ret = SMB_VFS_FCHOWN(fsp, smb_fname_parent->st.st_ex_uid, (gid_t)-1);
476 unbecome_root();
477 if (ret == -1) {
478 DEBUG(0,("change_file_owner_to_parent: failed to fchown "
479 "file %s to parent directory uid %u. Error "
480 "was %s\n", fsp_str_dbg(fsp),
481 (unsigned int)smb_fname_parent->st.st_ex_uid,
482 strerror(errno) ));
483 } else {
484 DEBUG(10,("change_file_owner_to_parent: changed new file %s to "
485 "parent directory uid %u.\n", fsp_str_dbg(fsp),
486 (unsigned int)smb_fname_parent->st.st_ex_uid));
487 /* Ensure the uid entry is updated. */
488 fsp->fsp_name->st.st_ex_uid = smb_fname_parent->st.st_ex_uid;
491 TALLOC_FREE(smb_fname_parent);
494 NTSTATUS change_dir_owner_to_parent(connection_struct *conn,
495 const char *inherit_from_dir,
496 const char *fname,
497 SMB_STRUCT_STAT *psbuf)
499 struct smb_filename *smb_fname_parent;
500 struct smb_filename *smb_fname_cwd = NULL;
501 char *saved_dir = NULL;
502 TALLOC_CTX *ctx = talloc_tos();
503 NTSTATUS status = NT_STATUS_OK;
504 int ret;
506 smb_fname_parent = synthetic_smb_fname(ctx, inherit_from_dir,
507 NULL, NULL);
508 if (smb_fname_parent == NULL) {
509 return NT_STATUS_NO_MEMORY;
512 ret = SMB_VFS_STAT(conn, smb_fname_parent);
513 if (ret == -1) {
514 status = map_nt_error_from_unix(errno);
515 DEBUG(0,("change_dir_owner_to_parent: failed to stat parent "
516 "directory %s. Error was %s\n",
517 smb_fname_str_dbg(smb_fname_parent),
518 strerror(errno)));
519 goto out;
522 /* We've already done an lstat into psbuf, and we know it's a
523 directory. If we can cd into the directory and the dev/ino
524 are the same then we can safely chown without races as
525 we're locking the directory in place by being in it. This
526 should work on any UNIX (thanks tridge :-). JRA.
529 saved_dir = vfs_GetWd(ctx,conn);
530 if (!saved_dir) {
531 status = map_nt_error_from_unix(errno);
532 DEBUG(0,("change_dir_owner_to_parent: failed to get "
533 "current working directory. Error was %s\n",
534 strerror(errno)));
535 goto out;
538 /* Chdir into the new path. */
539 if (vfs_ChDir(conn, fname) == -1) {
540 status = map_nt_error_from_unix(errno);
541 DEBUG(0,("change_dir_owner_to_parent: failed to change "
542 "current working directory to %s. Error "
543 "was %s\n", fname, strerror(errno) ));
544 goto chdir;
547 smb_fname_cwd = synthetic_smb_fname(ctx, ".", NULL, NULL);
548 if (smb_fname_cwd == NULL) {
549 status = NT_STATUS_NO_MEMORY;
550 goto chdir;
553 ret = SMB_VFS_STAT(conn, smb_fname_cwd);
554 if (ret == -1) {
555 status = map_nt_error_from_unix(errno);
556 DEBUG(0,("change_dir_owner_to_parent: failed to stat "
557 "directory '.' (%s) Error was %s\n",
558 fname, strerror(errno)));
559 goto chdir;
562 /* Ensure we're pointing at the same place. */
563 if (smb_fname_cwd->st.st_ex_dev != psbuf->st_ex_dev ||
564 smb_fname_cwd->st.st_ex_ino != psbuf->st_ex_ino) {
565 DEBUG(0,("change_dir_owner_to_parent: "
566 "device/inode on directory %s changed. "
567 "Refusing to chown !\n", fname ));
568 status = NT_STATUS_ACCESS_DENIED;
569 goto chdir;
572 if (smb_fname_parent->st.st_ex_uid == smb_fname_cwd->st.st_ex_uid) {
573 /* Already this uid - no need to change. */
574 DEBUG(10,("change_dir_owner_to_parent: directory %s "
575 "is already owned by uid %d\n",
576 fname,
577 (int)smb_fname_cwd->st.st_ex_uid ));
578 status = NT_STATUS_OK;
579 goto chdir;
582 become_root();
583 ret = SMB_VFS_LCHOWN(conn, ".", smb_fname_parent->st.st_ex_uid,
584 (gid_t)-1);
585 unbecome_root();
586 if (ret == -1) {
587 status = map_nt_error_from_unix(errno);
588 DEBUG(10,("change_dir_owner_to_parent: failed to chown "
589 "directory %s to parent directory uid %u. "
590 "Error was %s\n", fname,
591 (unsigned int)smb_fname_parent->st.st_ex_uid,
592 strerror(errno) ));
593 } else {
594 DEBUG(10,("change_dir_owner_to_parent: changed ownership of new "
595 "directory %s to parent directory uid %u.\n",
596 fname, (unsigned int)smb_fname_parent->st.st_ex_uid ));
597 /* Ensure the uid entry is updated. */
598 psbuf->st_ex_uid = smb_fname_parent->st.st_ex_uid;
601 chdir:
602 vfs_ChDir(conn,saved_dir);
603 out:
604 TALLOC_FREE(smb_fname_parent);
605 TALLOC_FREE(smb_fname_cwd);
606 return status;
609 /****************************************************************************
610 Open a file - returning a guaranteed ATOMIC indication of if the
611 file was created or not.
612 ****************************************************************************/
614 static NTSTATUS fd_open_atomic(struct connection_struct *conn,
615 files_struct *fsp,
616 int flags,
617 mode_t mode,
618 bool *file_created)
620 NTSTATUS status = NT_STATUS_UNSUCCESSFUL;
621 bool file_existed = VALID_STAT(fsp->fsp_name->st);
623 *file_created = false;
625 if (!(flags & O_CREAT)) {
627 * We're not creating the file, just pass through.
629 return fd_open(conn, fsp, flags, mode);
632 if (flags & O_EXCL) {
634 * Fail if already exists, just pass through.
636 status = fd_open(conn, fsp, flags, mode);
639 * Here we've opened with O_CREAT|O_EXCL. If that went
640 * NT_STATUS_OK, we *know* we created this file.
642 *file_created = NT_STATUS_IS_OK(status);
644 return status;
648 * Now it gets tricky. We have O_CREAT, but not O_EXCL.
649 * To know absolutely if we created the file or not,
650 * we can never call O_CREAT without O_EXCL. So if
651 * we think the file existed, try without O_CREAT|O_EXCL.
652 * If we think the file didn't exist, try with
653 * O_CREAT|O_EXCL. Keep bouncing between these two
654 * requests until either the file is created, or
655 * opened. Either way, we keep going until we get
656 * a returnable result (error, or open/create).
659 while(1) {
660 int curr_flags = flags;
662 if (file_existed) {
663 /* Just try open, do not create. */
664 curr_flags &= ~(O_CREAT);
665 status = fd_open(conn, fsp, curr_flags, mode);
666 if (NT_STATUS_EQUAL(status,
667 NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
669 * Someone deleted it in the meantime.
670 * Retry with O_EXCL.
672 file_existed = false;
673 DEBUG(10,("fd_open_atomic: file %s existed. "
674 "Retry.\n",
675 smb_fname_str_dbg(fsp->fsp_name)));
676 continue;
678 } else {
679 /* Try create exclusively, fail if it exists. */
680 curr_flags |= O_EXCL;
681 status = fd_open(conn, fsp, curr_flags, mode);
682 if (NT_STATUS_EQUAL(status,
683 NT_STATUS_OBJECT_NAME_COLLISION)) {
685 * Someone created it in the meantime.
686 * Retry without O_CREAT.
688 file_existed = true;
689 DEBUG(10,("fd_open_atomic: file %s "
690 "did not exist. Retry.\n",
691 smb_fname_str_dbg(fsp->fsp_name)));
692 continue;
694 if (NT_STATUS_IS_OK(status)) {
696 * Here we've opened with O_CREAT|O_EXCL
697 * and got success. We *know* we created
698 * this file.
700 *file_created = true;
703 /* Create is done, or failed. */
704 break;
706 return status;
709 /****************************************************************************
710 Open a file.
711 ****************************************************************************/
713 static NTSTATUS open_file(files_struct *fsp,
714 connection_struct *conn,
715 struct smb_request *req,
716 const char *parent_dir,
717 int flags,
718 mode_t unx_mode,
719 uint32 access_mask, /* client requested access mask. */
720 uint32 open_access_mask, /* what we're actually using in the open. */
721 bool *p_file_created)
723 struct smb_filename *smb_fname = fsp->fsp_name;
724 NTSTATUS status = NT_STATUS_OK;
725 int accmode = (flags & O_ACCMODE);
726 int local_flags = flags;
727 bool file_existed = VALID_STAT(fsp->fsp_name->st);
729 fsp->fh->fd = -1;
730 errno = EPERM;
732 /* Check permissions */
735 * This code was changed after seeing a client open request
736 * containing the open mode of (DENY_WRITE/read-only) with
737 * the 'create if not exist' bit set. The previous code
738 * would fail to open the file read only on a read-only share
739 * as it was checking the flags parameter directly against O_RDONLY,
740 * this was failing as the flags parameter was set to O_RDONLY|O_CREAT.
741 * JRA.
744 if (!CAN_WRITE(conn)) {
745 /* It's a read-only share - fail if we wanted to write. */
746 if(accmode != O_RDONLY || (flags & O_TRUNC) || (flags & O_APPEND)) {
747 DEBUG(3,("Permission denied opening %s\n",
748 smb_fname_str_dbg(smb_fname)));
749 return NT_STATUS_ACCESS_DENIED;
751 if (flags & O_CREAT) {
752 /* We don't want to write - but we must make sure that
753 O_CREAT doesn't create the file if we have write
754 access into the directory.
756 flags &= ~(O_CREAT|O_EXCL);
757 local_flags &= ~(O_CREAT|O_EXCL);
762 * This little piece of insanity is inspired by the
763 * fact that an NT client can open a file for O_RDONLY,
764 * but set the create disposition to FILE_EXISTS_TRUNCATE.
765 * If the client *can* write to the file, then it expects to
766 * truncate the file, even though it is opening for readonly.
767 * Quicken uses this stupid trick in backup file creation...
768 * Thanks *greatly* to "David W. Chapman Jr." <dwcjr@inethouston.net>
769 * for helping track this one down. It didn't bite us in 2.0.x
770 * as we always opened files read-write in that release. JRA.
773 if ((accmode == O_RDONLY) && ((flags & O_TRUNC) == O_TRUNC)) {
774 DEBUG(10,("open_file: truncate requested on read-only open "
775 "for file %s\n", smb_fname_str_dbg(smb_fname)));
776 local_flags = (flags & ~O_ACCMODE)|O_RDWR;
779 if ((open_access_mask & (FILE_READ_DATA|FILE_WRITE_DATA|FILE_APPEND_DATA|FILE_EXECUTE)) ||
780 (!file_existed && (local_flags & O_CREAT)) ||
781 ((local_flags & O_TRUNC) == O_TRUNC) ) {
782 const char *wild;
783 int ret;
785 #if defined(O_NONBLOCK) && defined(S_ISFIFO)
787 * We would block on opening a FIFO with no one else on the
788 * other end. Do what we used to do and add O_NONBLOCK to the
789 * open flags. JRA.
792 if (file_existed && S_ISFIFO(smb_fname->st.st_ex_mode)) {
793 local_flags &= ~O_TRUNC; /* Can't truncate a FIFO. */
794 local_flags |= O_NONBLOCK;
796 #endif
798 /* Don't create files with Microsoft wildcard characters. */
799 if (fsp->base_fsp) {
801 * wildcard characters are allowed in stream names
802 * only test the basefilename
804 wild = fsp->base_fsp->fsp_name->base_name;
805 } else {
806 wild = smb_fname->base_name;
808 if ((local_flags & O_CREAT) && !file_existed &&
809 ms_has_wild(wild)) {
810 return NT_STATUS_OBJECT_NAME_INVALID;
813 /* Can we access this file ? */
814 if (!fsp->base_fsp) {
815 /* Only do this check on non-stream open. */
816 if (file_existed) {
817 status = smbd_check_access_rights(conn,
818 smb_fname,
819 false,
820 access_mask);
821 } else if (local_flags & O_CREAT){
822 status = check_parent_access(conn,
823 smb_fname,
824 SEC_DIR_ADD_FILE);
825 } else {
826 /* File didn't exist and no O_CREAT. */
827 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
829 if (!NT_STATUS_IS_OK(status)) {
830 DEBUG(10,("open_file: "
831 "%s on file "
832 "%s returned %s\n",
833 file_existed ?
834 "smbd_check_access_rights" :
835 "check_parent_access",
836 smb_fname_str_dbg(smb_fname),
837 nt_errstr(status) ));
838 return status;
842 /* Actually do the open */
843 status = fd_open_atomic(conn, fsp, local_flags,
844 unx_mode, p_file_created);
845 if (!NT_STATUS_IS_OK(status)) {
846 DEBUG(3,("Error opening file %s (%s) (local_flags=%d) "
847 "(flags=%d)\n", smb_fname_str_dbg(smb_fname),
848 nt_errstr(status),local_flags,flags));
849 return status;
852 ret = SMB_VFS_FSTAT(fsp, &smb_fname->st);
853 if (ret == -1) {
854 /* If we have an fd, this stat should succeed. */
855 DEBUG(0,("Error doing fstat on open file %s "
856 "(%s)\n",
857 smb_fname_str_dbg(smb_fname),
858 strerror(errno) ));
859 status = map_nt_error_from_unix(errno);
860 fd_close(fsp);
861 return status;
864 if (*p_file_created) {
865 /* We created this file. */
867 bool need_re_stat = false;
868 /* Do all inheritance work after we've
869 done a successful fstat call and filled
870 in the stat struct in fsp->fsp_name. */
872 /* Inherit the ACL if required */
873 if (lp_inherit_perms(SNUM(conn))) {
874 inherit_access_posix_acl(conn, parent_dir,
875 smb_fname->base_name,
876 unx_mode);
877 need_re_stat = true;
880 /* Change the owner if required. */
881 if (lp_inherit_owner(SNUM(conn))) {
882 change_file_owner_to_parent(conn, parent_dir,
883 fsp);
884 need_re_stat = true;
887 if (need_re_stat) {
888 ret = SMB_VFS_FSTAT(fsp, &smb_fname->st);
889 /* If we have an fd, this stat should succeed. */
890 if (ret == -1) {
891 DEBUG(0,("Error doing fstat on open file %s "
892 "(%s)\n",
893 smb_fname_str_dbg(smb_fname),
894 strerror(errno) ));
898 notify_fname(conn, NOTIFY_ACTION_ADDED,
899 FILE_NOTIFY_CHANGE_FILE_NAME,
900 smb_fname->base_name);
902 } else {
903 fsp->fh->fd = -1; /* What we used to call a stat open. */
904 if (!file_existed) {
905 /* File must exist for a stat open. */
906 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
909 status = smbd_check_access_rights(conn,
910 smb_fname,
911 false,
912 access_mask);
914 if (NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND) &&
915 fsp->posix_open &&
916 S_ISLNK(smb_fname->st.st_ex_mode)) {
917 /* This is a POSIX stat open for delete
918 * or rename on a symlink that points
919 * nowhere. Allow. */
920 DEBUG(10,("open_file: allowing POSIX "
921 "open on bad symlink %s\n",
922 smb_fname_str_dbg(smb_fname)));
923 status = NT_STATUS_OK;
926 if (!NT_STATUS_IS_OK(status)) {
927 DEBUG(10,("open_file: "
928 "smbd_check_access_rights on file "
929 "%s returned %s\n",
930 smb_fname_str_dbg(smb_fname),
931 nt_errstr(status) ));
932 return status;
937 * POSIX allows read-only opens of directories. We don't
938 * want to do this (we use a different code path for this)
939 * so catch a directory open and return an EISDIR. JRA.
942 if(S_ISDIR(smb_fname->st.st_ex_mode)) {
943 fd_close(fsp);
944 errno = EISDIR;
945 return NT_STATUS_FILE_IS_A_DIRECTORY;
948 fsp->file_id = vfs_file_id_from_sbuf(conn, &smb_fname->st);
949 fsp->vuid = req ? req->vuid : UID_FIELD_INVALID;
950 fsp->file_pid = req ? req->smbpid : 0;
951 fsp->can_lock = True;
952 fsp->can_read = ((access_mask & FILE_READ_DATA) != 0);
953 fsp->can_write =
954 CAN_WRITE(conn) &&
955 ((access_mask & (FILE_WRITE_DATA | FILE_APPEND_DATA)) != 0);
956 fsp->print_file = NULL;
957 fsp->modified = False;
958 fsp->sent_oplock_break = NO_BREAK_SENT;
959 fsp->is_directory = False;
960 if (conn->aio_write_behind_list &&
961 is_in_path(smb_fname->base_name, conn->aio_write_behind_list,
962 conn->case_sensitive)) {
963 fsp->aio_write_behind = True;
966 fsp->wcp = NULL; /* Write cache pointer. */
968 DEBUG(2,("%s opened file %s read=%s write=%s (numopen=%d)\n",
969 conn->session_info->unix_info->unix_name,
970 smb_fname_str_dbg(smb_fname),
971 BOOLSTR(fsp->can_read), BOOLSTR(fsp->can_write),
972 conn->num_files_open));
974 errno = 0;
975 return NT_STATUS_OK;
978 /****************************************************************************
979 Check if we can open a file with a share mode.
980 Returns True if conflict, False if not.
981 ****************************************************************************/
983 static bool share_conflict(struct share_mode_entry *entry,
984 uint32 access_mask,
985 uint32 share_access)
987 DEBUG(10,("share_conflict: entry->access_mask = 0x%x, "
988 "entry->share_access = 0x%x, "
989 "entry->private_options = 0x%x\n",
990 (unsigned int)entry->access_mask,
991 (unsigned int)entry->share_access,
992 (unsigned int)entry->private_options));
994 if (server_id_is_disconnected(&entry->pid)) {
996 * note: cleanup should have been done by
997 * delay_for_batch_oplocks()
999 return false;
1002 DEBUG(10,("share_conflict: access_mask = 0x%x, share_access = 0x%x\n",
1003 (unsigned int)access_mask, (unsigned int)share_access));
1005 if ((entry->access_mask & (FILE_WRITE_DATA|
1006 FILE_APPEND_DATA|
1007 FILE_READ_DATA|
1008 FILE_EXECUTE|
1009 DELETE_ACCESS)) == 0) {
1010 DEBUG(10,("share_conflict: No conflict due to "
1011 "entry->access_mask = 0x%x\n",
1012 (unsigned int)entry->access_mask ));
1013 return False;
1016 if ((access_mask & (FILE_WRITE_DATA|
1017 FILE_APPEND_DATA|
1018 FILE_READ_DATA|
1019 FILE_EXECUTE|
1020 DELETE_ACCESS)) == 0) {
1021 DEBUG(10,("share_conflict: No conflict due to "
1022 "access_mask = 0x%x\n",
1023 (unsigned int)access_mask ));
1024 return False;
1027 #if 1 /* JRA TEST - Superdebug. */
1028 #define CHECK_MASK(num, am, right, sa, share) \
1029 DEBUG(10,("share_conflict: [%d] am (0x%x) & right (0x%x) = 0x%x\n", \
1030 (unsigned int)(num), (unsigned int)(am), \
1031 (unsigned int)(right), (unsigned int)(am)&(right) )); \
1032 DEBUG(10,("share_conflict: [%d] sa (0x%x) & share (0x%x) = 0x%x\n", \
1033 (unsigned int)(num), (unsigned int)(sa), \
1034 (unsigned int)(share), (unsigned int)(sa)&(share) )); \
1035 if (((am) & (right)) && !((sa) & (share))) { \
1036 DEBUG(10,("share_conflict: check %d conflict am = 0x%x, right = 0x%x, \
1037 sa = 0x%x, share = 0x%x\n", (num), (unsigned int)(am), (unsigned int)(right), (unsigned int)(sa), \
1038 (unsigned int)(share) )); \
1039 return True; \
1041 #else
1042 #define CHECK_MASK(num, am, right, sa, share) \
1043 if (((am) & (right)) && !((sa) & (share))) { \
1044 DEBUG(10,("share_conflict: check %d conflict am = 0x%x, right = 0x%x, \
1045 sa = 0x%x, share = 0x%x\n", (num), (unsigned int)(am), (unsigned int)(right), (unsigned int)(sa), \
1046 (unsigned int)(share) )); \
1047 return True; \
1049 #endif
1051 CHECK_MASK(1, entry->access_mask, FILE_WRITE_DATA | FILE_APPEND_DATA,
1052 share_access, FILE_SHARE_WRITE);
1053 CHECK_MASK(2, access_mask, FILE_WRITE_DATA | FILE_APPEND_DATA,
1054 entry->share_access, FILE_SHARE_WRITE);
1056 CHECK_MASK(3, entry->access_mask, FILE_READ_DATA | FILE_EXECUTE,
1057 share_access, FILE_SHARE_READ);
1058 CHECK_MASK(4, access_mask, FILE_READ_DATA | FILE_EXECUTE,
1059 entry->share_access, FILE_SHARE_READ);
1061 CHECK_MASK(5, entry->access_mask, DELETE_ACCESS,
1062 share_access, FILE_SHARE_DELETE);
1063 CHECK_MASK(6, access_mask, DELETE_ACCESS,
1064 entry->share_access, FILE_SHARE_DELETE);
1066 DEBUG(10,("share_conflict: No conflict.\n"));
1067 return False;
1070 #if defined(DEVELOPER)
1071 static void validate_my_share_entries(struct smbd_server_connection *sconn,
1072 int num,
1073 struct share_mode_entry *share_entry)
1075 struct server_id self = messaging_server_id(sconn->msg_ctx);
1076 files_struct *fsp;
1078 if (!serverid_equal(&self, &share_entry->pid)) {
1079 return;
1082 if (!is_valid_share_mode_entry(share_entry)) {
1083 return;
1086 fsp = file_find_dif(sconn, share_entry->id,
1087 share_entry->share_file_id);
1088 if (!fsp) {
1089 DEBUG(0,("validate_my_share_entries: PANIC : %s\n",
1090 share_mode_str(talloc_tos(), num, share_entry) ));
1091 smb_panic("validate_my_share_entries: Cannot match a "
1092 "share entry with an open file\n");
1095 if ((share_entry->op_type == NO_OPLOCK) &&
1096 (fsp->oplock_type == FAKE_LEVEL_II_OPLOCK))
1098 /* Someone has already written to it, but I haven't yet
1099 * noticed */
1100 return;
1103 if (((uint16)fsp->oplock_type) != share_entry->op_type) {
1104 goto panic;
1107 return;
1109 panic:
1111 char *str;
1112 DEBUG(0,("validate_my_share_entries: PANIC : %s\n",
1113 share_mode_str(talloc_tos(), num, share_entry) ));
1114 str = talloc_asprintf(talloc_tos(),
1115 "validate_my_share_entries: "
1116 "file %s, oplock_type = 0x%x, op_type = 0x%x\n",
1117 fsp->fsp_name->base_name,
1118 (unsigned int)fsp->oplock_type,
1119 (unsigned int)share_entry->op_type );
1120 smb_panic(str);
1123 #endif
1125 bool is_stat_open(uint32 access_mask)
1127 const uint32_t stat_open_bits =
1128 (SYNCHRONIZE_ACCESS|
1129 FILE_READ_ATTRIBUTES|
1130 FILE_WRITE_ATTRIBUTES);
1132 return (((access_mask & stat_open_bits) != 0) &&
1133 ((access_mask & ~stat_open_bits) == 0));
1136 /****************************************************************************
1137 Deal with share modes
1138 Invarient: Share mode must be locked on entry and exit.
1139 Returns -1 on error, or number of share modes on success (may be zero).
1140 ****************************************************************************/
1142 static NTSTATUS open_mode_check(connection_struct *conn,
1143 struct share_mode_lock *lck,
1144 uint32_t name_hash,
1145 uint32 access_mask,
1146 uint32 share_access,
1147 uint32 create_options,
1148 bool *file_existed)
1150 int i;
1152 if(lck->data->num_share_modes == 0) {
1153 return NT_STATUS_OK;
1156 /* A delete on close prohibits everything */
1158 if (is_delete_on_close_set(lck, name_hash)) {
1160 * Check the delete on close token
1161 * is valid. It could have been left
1162 * after a server crash.
1164 for(i = 0; i < lck->data->num_share_modes; i++) {
1165 if (!share_mode_stale_pid(lck->data, i)) {
1167 *file_existed = true;
1169 return NT_STATUS_DELETE_PENDING;
1172 return NT_STATUS_OK;
1175 if (is_stat_open(access_mask)) {
1176 /* Stat open that doesn't trigger oplock breaks or share mode
1177 * checks... ! JRA. */
1178 return NT_STATUS_OK;
1182 * Check if the share modes will give us access.
1185 #if defined(DEVELOPER)
1186 for(i = 0; i < lck->data->num_share_modes; i++) {
1187 validate_my_share_entries(conn->sconn, i,
1188 &lck->data->share_modes[i]);
1190 #endif
1192 /* Now we check the share modes, after any oplock breaks. */
1193 for(i = 0; i < lck->data->num_share_modes; i++) {
1195 if (!is_valid_share_mode_entry(&lck->data->share_modes[i])) {
1196 continue;
1199 /* someone else has a share lock on it, check to see if we can
1200 * too */
1201 if (share_conflict(&lck->data->share_modes[i],
1202 access_mask, share_access)) {
1204 if (share_mode_stale_pid(lck->data, i)) {
1205 continue;
1208 *file_existed = true;
1210 return NT_STATUS_SHARING_VIOLATION;
1214 if (lck->data->num_share_modes != 0) {
1215 *file_existed = true;
1218 return NT_STATUS_OK;
1222 * Send a break message to the oplock holder and delay the open for
1223 * our client.
1226 static NTSTATUS send_break_message(files_struct *fsp,
1227 struct share_mode_entry *exclusive,
1228 uint64_t mid,
1229 int oplock_request)
1231 NTSTATUS status;
1232 char msg[MSG_SMB_SHARE_MODE_ENTRY_SIZE];
1234 DEBUG(10, ("Sending break request to PID %s\n",
1235 procid_str_static(&exclusive->pid)));
1236 exclusive->op_mid = mid;
1238 /* Create the message. */
1239 share_mode_entry_to_message(msg, exclusive);
1241 /* Add in the FORCE_OPLOCK_BREAK_TO_NONE bit in the message if set. We
1242 don't want this set in the share mode struct pointed to by lck. */
1244 if (oplock_request & FORCE_OPLOCK_BREAK_TO_NONE) {
1245 SSVAL(msg,OP_BREAK_MSG_OP_TYPE_OFFSET,
1246 exclusive->op_type | FORCE_OPLOCK_BREAK_TO_NONE);
1249 status = messaging_send_buf(fsp->conn->sconn->msg_ctx, exclusive->pid,
1250 MSG_SMB_BREAK_REQUEST,
1251 (uint8 *)msg,
1252 MSG_SMB_SHARE_MODE_ENTRY_SIZE);
1253 if (!NT_STATUS_IS_OK(status)) {
1254 DEBUG(3, ("Could not send oplock break message: %s\n",
1255 nt_errstr(status)));
1258 return status;
1262 * Return share_mode_entry pointers for :
1263 * 1). Batch oplock entry.
1264 * 2). Batch or exclusive oplock entry (may be identical to #1).
1265 * bool have_level2_oplock
1266 * bool have_no_oplock.
1267 * Do internal consistency checks on the share mode for a file.
1270 static void find_oplock_types(files_struct *fsp,
1271 int oplock_request,
1272 const struct share_mode_lock *lck,
1273 struct share_mode_entry **pp_batch,
1274 struct share_mode_entry **pp_ex_or_batch,
1275 bool *got_level2,
1276 bool *got_no_oplock)
1278 int i;
1280 *pp_batch = NULL;
1281 *pp_ex_or_batch = NULL;
1282 *got_level2 = false;
1283 *got_no_oplock = false;
1285 /* Ignore stat or internal opens, as is done in
1286 delay_for_batch_oplocks() and
1287 delay_for_exclusive_oplocks().
1289 if ((oplock_request & INTERNAL_OPEN_ONLY) || is_stat_open(fsp->access_mask)) {
1290 return;
1293 for (i=0; i<lck->data->num_share_modes; i++) {
1294 struct share_mode_entry *e = &lck->data->share_modes[i];
1296 if (!is_valid_share_mode_entry(e)) {
1297 continue;
1300 if (e->op_type == NO_OPLOCK && is_stat_open(e->access_mask)) {
1301 /* We ignore stat opens in the table - they
1302 always have NO_OPLOCK and never get or
1303 cause breaks. JRA. */
1304 continue;
1307 if (BATCH_OPLOCK_TYPE(e->op_type)) {
1308 /* batch - can only be one. */
1309 if (share_mode_stale_pid(lck->data, i)) {
1310 DEBUG(10, ("Found stale batch oplock\n"));
1311 continue;
1313 if (*pp_ex_or_batch || *pp_batch || *got_level2 || *got_no_oplock) {
1314 smb_panic("Bad batch oplock entry.");
1316 *pp_batch = e;
1319 if (EXCLUSIVE_OPLOCK_TYPE(e->op_type)) {
1320 if (share_mode_stale_pid(lck->data, i)) {
1321 DEBUG(10, ("Found stale duplicate oplock\n"));
1322 continue;
1324 /* Exclusive or batch - can only be one. */
1325 if (*pp_ex_or_batch || *got_level2 || *got_no_oplock) {
1326 smb_panic("Bad exclusive or batch oplock entry.");
1328 *pp_ex_or_batch = e;
1331 if (LEVEL_II_OPLOCK_TYPE(e->op_type)) {
1332 if (*pp_batch || *pp_ex_or_batch) {
1333 if (share_mode_stale_pid(lck->data, i)) {
1334 DEBUG(10, ("Found stale LevelII "
1335 "oplock\n"));
1336 continue;
1338 smb_panic("Bad levelII oplock entry.");
1340 *got_level2 = true;
1343 if (e->op_type == NO_OPLOCK) {
1344 if (*pp_batch || *pp_ex_or_batch) {
1345 if (share_mode_stale_pid(lck->data, i)) {
1346 DEBUG(10, ("Found stale NO_OPLOCK "
1347 "entry\n"));
1348 continue;
1350 smb_panic("Bad no oplock entry.");
1352 *got_no_oplock = true;
1357 static bool delay_for_batch_oplocks(files_struct *fsp,
1358 uint64_t mid,
1359 int oplock_request,
1360 struct share_mode_entry *batch_entry)
1362 if ((oplock_request & INTERNAL_OPEN_ONLY) || is_stat_open(fsp->access_mask)) {
1363 return false;
1365 if (batch_entry == NULL) {
1366 return false;
1369 if (server_id_is_disconnected(&batch_entry->pid)) {
1371 * TODO: clean up.
1372 * This could be achieved by sending a break message
1373 * to ourselves. Special considerations for files
1374 * with delete_on_close flag set!
1376 * For now we keep it simple and do not
1377 * allow delete on close for durable handles.
1379 return false;
1382 /* Found a batch oplock */
1383 send_break_message(fsp, batch_entry, mid, oplock_request);
1384 return true;
1387 static bool delay_for_exclusive_oplocks(files_struct *fsp,
1388 uint64_t mid,
1389 int oplock_request,
1390 struct share_mode_entry *ex_entry)
1392 if ((oplock_request & INTERNAL_OPEN_ONLY) || is_stat_open(fsp->access_mask)) {
1393 return false;
1395 if (ex_entry == NULL) {
1396 return false;
1399 if (server_id_is_disconnected(&ex_entry->pid)) {
1401 * since only durable handles can get disconnected,
1402 * and we can only get durable handles with batch oplocks,
1403 * this should actually never be reached...
1405 return false;
1408 send_break_message(fsp, ex_entry, mid, oplock_request);
1409 return true;
1412 static bool file_has_brlocks(files_struct *fsp)
1414 struct byte_range_lock *br_lck;
1416 br_lck = brl_get_locks_readonly(fsp);
1417 if (!br_lck)
1418 return false;
1420 return br_lck->num_locks > 0 ? true : false;
1423 static void grant_fsp_oplock_type(files_struct *fsp,
1424 int oplock_request,
1425 bool got_level2_oplock,
1426 bool got_a_none_oplock)
1428 bool allow_level2 = (global_client_caps & CAP_LEVEL_II_OPLOCKS) &&
1429 lp_level2_oplocks(SNUM(fsp->conn));
1431 /* Start by granting what the client asked for,
1432 but ensure no SAMBA_PRIVATE bits can be set. */
1433 fsp->oplock_type = (oplock_request & ~SAMBA_PRIVATE_OPLOCK_MASK);
1435 if (oplock_request & INTERNAL_OPEN_ONLY) {
1436 /* No oplocks on internal open. */
1437 fsp->oplock_type = NO_OPLOCK;
1438 DEBUG(10,("grant_fsp_oplock_type: oplock type 0x%x on file %s\n",
1439 fsp->oplock_type, fsp_str_dbg(fsp)));
1440 return;
1443 if (lp_locking(fsp->conn->params) && file_has_brlocks(fsp)) {
1444 DEBUG(10,("grant_fsp_oplock_type: file %s has byte range locks\n",
1445 fsp_str_dbg(fsp)));
1446 fsp->oplock_type = NO_OPLOCK;
1449 if (is_stat_open(fsp->access_mask)) {
1450 /* Leave the value already set. */
1451 DEBUG(10,("grant_fsp_oplock_type: oplock type 0x%x on file %s\n",
1452 fsp->oplock_type, fsp_str_dbg(fsp)));
1453 return;
1457 * Match what was requested (fsp->oplock_type) with
1458 * what was found in the existing share modes.
1461 if (got_a_none_oplock) {
1462 fsp->oplock_type = NO_OPLOCK;
1463 } else if (got_level2_oplock) {
1464 if (fsp->oplock_type == NO_OPLOCK ||
1465 fsp->oplock_type == FAKE_LEVEL_II_OPLOCK) {
1466 /* Store a level2 oplock, but don't tell the client */
1467 fsp->oplock_type = FAKE_LEVEL_II_OPLOCK;
1468 } else {
1469 fsp->oplock_type = LEVEL_II_OPLOCK;
1471 } else {
1472 /* All share_mode_entries are placeholders or deferred.
1473 * Silently upgrade to fake levelII if the client didn't
1474 * ask for an oplock. */
1475 if (fsp->oplock_type == NO_OPLOCK) {
1476 /* Store a level2 oplock, but don't tell the client */
1477 fsp->oplock_type = FAKE_LEVEL_II_OPLOCK;
1482 * Don't grant level2 to clients that don't want them
1483 * or if we've turned them off.
1485 if (fsp->oplock_type == LEVEL_II_OPLOCK && !allow_level2) {
1486 fsp->oplock_type = FAKE_LEVEL_II_OPLOCK;
1489 DEBUG(10,("grant_fsp_oplock_type: oplock type 0x%x on file %s\n",
1490 fsp->oplock_type, fsp_str_dbg(fsp)));
1493 static bool request_timed_out(struct timeval request_time,
1494 struct timeval timeout)
1496 struct timeval now, end_time;
1497 GetTimeOfDay(&now);
1498 end_time = timeval_sum(&request_time, &timeout);
1499 return (timeval_compare(&end_time, &now) < 0);
1502 struct defer_open_state {
1503 struct smbd_server_connection *sconn;
1504 uint64_t mid;
1507 static void defer_open_done(struct tevent_req *req);
1509 /****************************************************************************
1510 Handle the 1 second delay in returning a SHARING_VIOLATION error.
1511 ****************************************************************************/
1513 static void defer_open(struct share_mode_lock *lck,
1514 struct timeval request_time,
1515 struct timeval timeout,
1516 struct smb_request *req,
1517 struct deferred_open_record *state)
1519 DEBUG(10,("defer_open_sharing_error: time [%u.%06u] adding deferred "
1520 "open entry for mid %llu\n",
1521 (unsigned int)request_time.tv_sec,
1522 (unsigned int)request_time.tv_usec,
1523 (unsigned long long)req->mid));
1525 if (!push_deferred_open_message_smb(req, request_time, timeout,
1526 state->id, (char *)state, sizeof(*state))) {
1527 TALLOC_FREE(lck);
1528 exit_server("push_deferred_open_message_smb failed");
1530 if (lck) {
1531 struct defer_open_state *watch_state;
1532 struct tevent_req *watch_req;
1533 bool ret;
1535 watch_state = talloc(req->sconn, struct defer_open_state);
1536 if (watch_state == NULL) {
1537 exit_server("talloc failed");
1539 watch_state->sconn = req->sconn;
1540 watch_state->mid = req->mid;
1542 DEBUG(10, ("defering mid %llu\n",
1543 (unsigned long long)req->mid));
1545 watch_req = dbwrap_record_watch_send(
1546 watch_state, req->sconn->ev_ctx, lck->data->record,
1547 req->sconn->msg_ctx);
1548 if (watch_req == NULL) {
1549 exit_server("Could not watch share mode record");
1551 tevent_req_set_callback(watch_req, defer_open_done,
1552 watch_state);
1554 ret = tevent_req_set_endtime(
1555 watch_req, req->sconn->ev_ctx,
1556 timeval_sum(&request_time, &timeout));
1557 SMB_ASSERT(ret);
1561 static void defer_open_done(struct tevent_req *req)
1563 struct defer_open_state *state = tevent_req_callback_data(
1564 req, struct defer_open_state);
1565 NTSTATUS status;
1566 bool ret;
1568 status = dbwrap_record_watch_recv(req, talloc_tos(), NULL);
1569 TALLOC_FREE(req);
1570 if (!NT_STATUS_IS_OK(status)) {
1571 DEBUG(5, ("dbwrap_record_watch_recv returned %s\n",
1572 nt_errstr(status)));
1574 * Even if it failed, retry anyway. TODO: We need a way to
1575 * tell a re-scheduled open about that error.
1579 DEBUG(10, ("scheduling mid %llu\n", (unsigned long long)state->mid));
1581 ret = schedule_deferred_open_message_smb(state->sconn, state->mid);
1582 SMB_ASSERT(ret);
1583 TALLOC_FREE(state);
1587 /****************************************************************************
1588 On overwrite open ensure that the attributes match.
1589 ****************************************************************************/
1591 static bool open_match_attributes(connection_struct *conn,
1592 uint32 old_dos_attr,
1593 uint32 new_dos_attr,
1594 mode_t existing_unx_mode,
1595 mode_t new_unx_mode,
1596 mode_t *returned_unx_mode)
1598 uint32 noarch_old_dos_attr, noarch_new_dos_attr;
1600 noarch_old_dos_attr = (old_dos_attr & ~FILE_ATTRIBUTE_ARCHIVE);
1601 noarch_new_dos_attr = (new_dos_attr & ~FILE_ATTRIBUTE_ARCHIVE);
1603 if((noarch_old_dos_attr == 0 && noarch_new_dos_attr != 0) ||
1604 (noarch_old_dos_attr != 0 && ((noarch_old_dos_attr & noarch_new_dos_attr) == noarch_old_dos_attr))) {
1605 *returned_unx_mode = new_unx_mode;
1606 } else {
1607 *returned_unx_mode = (mode_t)0;
1610 DEBUG(10,("open_match_attributes: old_dos_attr = 0x%x, "
1611 "existing_unx_mode = 0%o, new_dos_attr = 0x%x "
1612 "returned_unx_mode = 0%o\n",
1613 (unsigned int)old_dos_attr,
1614 (unsigned int)existing_unx_mode,
1615 (unsigned int)new_dos_attr,
1616 (unsigned int)*returned_unx_mode ));
1618 /* If we're mapping SYSTEM and HIDDEN ensure they match. */
1619 if (lp_map_system(SNUM(conn)) || lp_store_dos_attributes(SNUM(conn))) {
1620 if ((old_dos_attr & FILE_ATTRIBUTE_SYSTEM) &&
1621 !(new_dos_attr & FILE_ATTRIBUTE_SYSTEM)) {
1622 return False;
1625 if (lp_map_hidden(SNUM(conn)) || lp_store_dos_attributes(SNUM(conn))) {
1626 if ((old_dos_attr & FILE_ATTRIBUTE_HIDDEN) &&
1627 !(new_dos_attr & FILE_ATTRIBUTE_HIDDEN)) {
1628 return False;
1631 return True;
1634 /****************************************************************************
1635 Special FCB or DOS processing in the case of a sharing violation.
1636 Try and find a duplicated file handle.
1637 ****************************************************************************/
1639 static NTSTATUS fcb_or_dos_open(struct smb_request *req,
1640 connection_struct *conn,
1641 files_struct *fsp_to_dup_into,
1642 const struct smb_filename *smb_fname,
1643 struct file_id id,
1644 uint16 file_pid,
1645 uint64_t vuid,
1646 uint32 access_mask,
1647 uint32 share_access,
1648 uint32 create_options)
1650 files_struct *fsp;
1652 DEBUG(5,("fcb_or_dos_open: attempting old open semantics for "
1653 "file %s.\n", smb_fname_str_dbg(smb_fname)));
1655 for(fsp = file_find_di_first(conn->sconn, id); fsp;
1656 fsp = file_find_di_next(fsp)) {
1658 DEBUG(10,("fcb_or_dos_open: checking file %s, fd = %d, "
1659 "vuid = %llu, file_pid = %u, private_options = 0x%x "
1660 "access_mask = 0x%x\n", fsp_str_dbg(fsp),
1661 fsp->fh->fd, (unsigned long long)fsp->vuid,
1662 (unsigned int)fsp->file_pid,
1663 (unsigned int)fsp->fh->private_options,
1664 (unsigned int)fsp->access_mask ));
1666 if (fsp != fsp_to_dup_into &&
1667 fsp->fh->fd != -1 &&
1668 fsp->vuid == vuid &&
1669 fsp->file_pid == file_pid &&
1670 (fsp->fh->private_options & (NTCREATEX_OPTIONS_PRIVATE_DENY_DOS |
1671 NTCREATEX_OPTIONS_PRIVATE_DENY_FCB)) &&
1672 (fsp->access_mask & FILE_WRITE_DATA) &&
1673 strequal(fsp->fsp_name->base_name, smb_fname->base_name) &&
1674 strequal(fsp->fsp_name->stream_name,
1675 smb_fname->stream_name)) {
1676 DEBUG(10,("fcb_or_dos_open: file match\n"));
1677 break;
1681 if (!fsp) {
1682 return NT_STATUS_NOT_FOUND;
1685 /* quite an insane set of semantics ... */
1686 if (is_executable(smb_fname->base_name) &&
1687 (fsp->fh->private_options & NTCREATEX_OPTIONS_PRIVATE_DENY_DOS)) {
1688 DEBUG(10,("fcb_or_dos_open: file fail due to is_executable.\n"));
1689 return NT_STATUS_INVALID_PARAMETER;
1692 /* We need to duplicate this fsp. */
1693 return dup_file_fsp(req, fsp, access_mask, share_access,
1694 create_options, fsp_to_dup_into);
1697 static void schedule_defer_open(struct share_mode_lock *lck,
1698 struct timeval request_time,
1699 struct smb_request *req)
1701 struct deferred_open_record state;
1703 /* This is a relative time, added to the absolute
1704 request_time value to get the absolute timeout time.
1705 Note that if this is the second or greater time we enter
1706 this codepath for this particular request mid then
1707 request_time is left as the absolute time of the *first*
1708 time this request mid was processed. This is what allows
1709 the request to eventually time out. */
1711 struct timeval timeout;
1713 /* Normally the smbd we asked should respond within
1714 * OPLOCK_BREAK_TIMEOUT seconds regardless of whether
1715 * the client did, give twice the timeout as a safety
1716 * measure here in case the other smbd is stuck
1717 * somewhere else. */
1719 timeout = timeval_set(OPLOCK_BREAK_TIMEOUT*2, 0);
1721 /* Nothing actually uses state.delayed_for_oplocks
1722 but it's handy to differentiate in debug messages
1723 between a 30 second delay due to oplock break, and
1724 a 1 second delay for share mode conflicts. */
1726 state.delayed_for_oplocks = True;
1727 state.async_open = false;
1728 state.id = lck->data->id;
1730 if (!request_timed_out(request_time, timeout)) {
1731 defer_open(lck, request_time, timeout, req, &state);
1735 /****************************************************************************
1736 Reschedule an open call that went asynchronous.
1737 ****************************************************************************/
1739 static void schedule_async_open(struct timeval request_time,
1740 struct smb_request *req)
1742 struct deferred_open_record state;
1743 struct timeval timeout;
1745 timeout = timeval_set(20, 0);
1747 ZERO_STRUCT(state);
1748 state.delayed_for_oplocks = false;
1749 state.async_open = true;
1751 if (!request_timed_out(request_time, timeout)) {
1752 defer_open(NULL, request_time, timeout, req, &state);
1756 /****************************************************************************
1757 Work out what access_mask to use from what the client sent us.
1758 ****************************************************************************/
1760 static NTSTATUS smbd_calculate_maximum_allowed_access(
1761 connection_struct *conn,
1762 const struct smb_filename *smb_fname,
1763 bool use_privs,
1764 uint32_t *p_access_mask)
1766 struct security_descriptor *sd;
1767 uint32_t access_granted;
1768 NTSTATUS status;
1770 if (!use_privs && (get_current_uid(conn) == (uid_t)0)) {
1771 *p_access_mask |= FILE_GENERIC_ALL;
1772 return NT_STATUS_OK;
1775 status = SMB_VFS_GET_NT_ACL(conn, smb_fname->base_name,
1776 (SECINFO_OWNER |
1777 SECINFO_GROUP |
1778 SECINFO_DACL),
1779 talloc_tos(), &sd);
1781 if (NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
1783 * File did not exist
1785 *p_access_mask = FILE_GENERIC_ALL;
1786 return NT_STATUS_OK;
1788 if (!NT_STATUS_IS_OK(status)) {
1789 DEBUG(10,("Could not get acl on file %s: %s\n",
1790 smb_fname_str_dbg(smb_fname),
1791 nt_errstr(status)));
1792 return NT_STATUS_ACCESS_DENIED;
1796 * If we can access the path to this file, by
1797 * default we have FILE_READ_ATTRIBUTES from the
1798 * containing directory. See the section:
1799 * "Algorithm to Check Access to an Existing File"
1800 * in MS-FSA.pdf.
1802 * se_file_access_check()
1803 * also takes care of owner WRITE_DAC and READ_CONTROL.
1805 status = se_file_access_check(sd,
1806 get_current_nttok(conn),
1807 use_privs,
1808 (*p_access_mask & ~FILE_READ_ATTRIBUTES),
1809 &access_granted);
1811 TALLOC_FREE(sd);
1813 if (!NT_STATUS_IS_OK(status)) {
1814 DEBUG(10, ("Access denied on file %s: "
1815 "when calculating maximum access\n",
1816 smb_fname_str_dbg(smb_fname)));
1817 return NT_STATUS_ACCESS_DENIED;
1819 *p_access_mask = (access_granted | FILE_READ_ATTRIBUTES);
1821 if (!(access_granted & DELETE_ACCESS)) {
1822 if (can_delete_file_in_directory(conn, smb_fname)) {
1823 *p_access_mask |= DELETE_ACCESS;
1827 return NT_STATUS_OK;
1830 NTSTATUS smbd_calculate_access_mask(connection_struct *conn,
1831 const struct smb_filename *smb_fname,
1832 bool use_privs,
1833 uint32_t access_mask,
1834 uint32_t *access_mask_out)
1836 NTSTATUS status;
1837 uint32_t orig_access_mask = access_mask;
1838 uint32_t rejected_share_access;
1841 * Convert GENERIC bits to specific bits.
1844 se_map_generic(&access_mask, &file_generic_mapping);
1846 /* Calculate MAXIMUM_ALLOWED_ACCESS if requested. */
1847 if (access_mask & MAXIMUM_ALLOWED_ACCESS) {
1849 status = smbd_calculate_maximum_allowed_access(
1850 conn, smb_fname, use_privs, &access_mask);
1852 if (!NT_STATUS_IS_OK(status)) {
1853 return status;
1856 access_mask &= conn->share_access;
1859 rejected_share_access = access_mask & ~(conn->share_access);
1861 if (rejected_share_access) {
1862 DEBUG(10, ("smbd_calculate_access_mask: Access denied on "
1863 "file %s: rejected by share access mask[0x%08X] "
1864 "orig[0x%08X] mapped[0x%08X] reject[0x%08X]\n",
1865 smb_fname_str_dbg(smb_fname),
1866 conn->share_access,
1867 orig_access_mask, access_mask,
1868 rejected_share_access));
1869 return NT_STATUS_ACCESS_DENIED;
1872 *access_mask_out = access_mask;
1873 return NT_STATUS_OK;
1876 /****************************************************************************
1877 Remove the deferred open entry under lock.
1878 ****************************************************************************/
1880 /****************************************************************************
1881 Return true if this is a state pointer to an asynchronous create.
1882 ****************************************************************************/
1884 bool is_deferred_open_async(const void *ptr)
1886 const struct deferred_open_record *state = (const struct deferred_open_record *)ptr;
1888 return state->async_open;
1891 static bool clear_ads(uint32_t create_disposition)
1893 bool ret = false;
1895 switch (create_disposition) {
1896 case FILE_SUPERSEDE:
1897 case FILE_OVERWRITE_IF:
1898 case FILE_OVERWRITE:
1899 ret = true;
1900 break;
1901 default:
1902 break;
1904 return ret;
1907 static int disposition_to_open_flags(uint32_t create_disposition)
1909 int ret = 0;
1912 * Currently we're using FILE_SUPERSEDE as the same as
1913 * FILE_OVERWRITE_IF but they really are
1914 * different. FILE_SUPERSEDE deletes an existing file
1915 * (requiring delete access) then recreates it.
1918 switch (create_disposition) {
1919 case FILE_SUPERSEDE:
1920 case FILE_OVERWRITE_IF:
1922 * If file exists replace/overwrite. If file doesn't
1923 * exist create.
1925 ret = O_CREAT|O_TRUNC;
1926 break;
1928 case FILE_OPEN:
1930 * If file exists open. If file doesn't exist error.
1932 ret = 0;
1933 break;
1935 case FILE_OVERWRITE:
1937 * If file exists overwrite. If file doesn't exist
1938 * error.
1940 ret = O_TRUNC;
1941 break;
1943 case FILE_CREATE:
1945 * If file exists error. If file doesn't exist create.
1947 ret = O_CREAT|O_EXCL;
1948 break;
1950 case FILE_OPEN_IF:
1952 * If file exists open. If file doesn't exist create.
1954 ret = O_CREAT;
1955 break;
1957 return ret;
1960 static int calculate_open_access_flags(uint32_t access_mask,
1961 int oplock_request,
1962 uint32_t private_flags)
1964 bool need_write, need_read;
1967 * Note that we ignore the append flag as append does not
1968 * mean the same thing under DOS and Unix.
1971 need_write =
1972 ((access_mask & (FILE_WRITE_DATA | FILE_APPEND_DATA)) ||
1973 (oplock_request & FORCE_OPLOCK_BREAK_TO_NONE));
1975 if (!need_write) {
1976 return O_RDONLY;
1979 /* DENY_DOS opens are always underlying read-write on the
1980 file handle, no matter what the requested access mask
1981 says. */
1983 need_read =
1984 ((private_flags & NTCREATEX_OPTIONS_PRIVATE_DENY_DOS) ||
1985 access_mask & (FILE_READ_ATTRIBUTES|FILE_READ_DATA|
1986 FILE_READ_EA|FILE_EXECUTE));
1988 if (!need_read) {
1989 return O_WRONLY;
1991 return O_RDWR;
1994 /****************************************************************************
1995 Open a file with a share mode. Passed in an already created files_struct *.
1996 ****************************************************************************/
1998 static NTSTATUS open_file_ntcreate(connection_struct *conn,
1999 struct smb_request *req,
2000 uint32 access_mask, /* access bits (FILE_READ_DATA etc.) */
2001 uint32 share_access, /* share constants (FILE_SHARE_READ etc) */
2002 uint32 create_disposition, /* FILE_OPEN_IF etc. */
2003 uint32 create_options, /* options such as delete on close. */
2004 uint32 new_dos_attributes, /* attributes used for new file. */
2005 int oplock_request, /* internal Samba oplock codes. */
2006 /* Information (FILE_EXISTS etc.) */
2007 uint32_t private_flags, /* Samba specific flags. */
2008 int *pinfo,
2009 files_struct *fsp)
2011 struct smb_filename *smb_fname = fsp->fsp_name;
2012 int flags=0;
2013 int flags2=0;
2014 bool file_existed = VALID_STAT(smb_fname->st);
2015 bool def_acl = False;
2016 bool posix_open = False;
2017 bool new_file_created = False;
2018 bool first_open_attempt = true;
2019 NTSTATUS fsp_open = NT_STATUS_ACCESS_DENIED;
2020 mode_t new_unx_mode = (mode_t)0;
2021 mode_t unx_mode = (mode_t)0;
2022 int info;
2023 uint32 existing_dos_attributes = 0;
2024 struct timeval request_time = timeval_zero();
2025 struct share_mode_lock *lck = NULL;
2026 uint32 open_access_mask = access_mask;
2027 NTSTATUS status;
2028 char *parent_dir;
2029 SMB_STRUCT_STAT saved_stat = smb_fname->st;
2030 struct share_mode_entry *batch_entry = NULL;
2031 struct share_mode_entry *exclusive_entry = NULL;
2032 bool got_level2_oplock = false;
2033 bool got_a_none_oplock = false;
2034 struct timespec old_write_time;
2035 struct file_id id;
2037 if (conn->printer) {
2039 * Printers are handled completely differently.
2040 * Most of the passed parameters are ignored.
2043 if (pinfo) {
2044 *pinfo = FILE_WAS_CREATED;
2047 DEBUG(10, ("open_file_ntcreate: printer open fname=%s\n",
2048 smb_fname_str_dbg(smb_fname)));
2050 if (!req) {
2051 DEBUG(0,("open_file_ntcreate: printer open without "
2052 "an SMB request!\n"));
2053 return NT_STATUS_INTERNAL_ERROR;
2056 return print_spool_open(fsp, smb_fname->base_name,
2057 req->vuid);
2060 if (!parent_dirname(talloc_tos(), smb_fname->base_name, &parent_dir,
2061 NULL)) {
2062 return NT_STATUS_NO_MEMORY;
2065 if (new_dos_attributes & FILE_FLAG_POSIX_SEMANTICS) {
2066 posix_open = True;
2067 unx_mode = (mode_t)(new_dos_attributes & ~FILE_FLAG_POSIX_SEMANTICS);
2068 new_dos_attributes = 0;
2069 } else {
2070 /* Windows allows a new file to be created and
2071 silently removes a FILE_ATTRIBUTE_DIRECTORY
2072 sent by the client. Do the same. */
2074 new_dos_attributes &= ~FILE_ATTRIBUTE_DIRECTORY;
2076 /* We add FILE_ATTRIBUTE_ARCHIVE to this as this mode is only used if the file is
2077 * created new. */
2078 unx_mode = unix_mode(conn, new_dos_attributes | FILE_ATTRIBUTE_ARCHIVE,
2079 smb_fname, parent_dir);
2082 DEBUG(10, ("open_file_ntcreate: fname=%s, dos_attrs=0x%x "
2083 "access_mask=0x%x share_access=0x%x "
2084 "create_disposition = 0x%x create_options=0x%x "
2085 "unix mode=0%o oplock_request=%d private_flags = 0x%x\n",
2086 smb_fname_str_dbg(smb_fname), new_dos_attributes,
2087 access_mask, share_access, create_disposition,
2088 create_options, (unsigned int)unx_mode, oplock_request,
2089 (unsigned int)private_flags));
2091 if ((req == NULL) && ((oplock_request & INTERNAL_OPEN_ONLY) == 0)) {
2092 DEBUG(0, ("No smb request but not an internal only open!\n"));
2093 return NT_STATUS_INTERNAL_ERROR;
2097 * Only non-internal opens can be deferred at all
2100 if (req) {
2101 void *ptr;
2102 if (get_deferred_open_message_state(req,
2103 &request_time,
2104 &ptr)) {
2105 /* Remember the absolute time of the original
2106 request with this mid. We'll use it later to
2107 see if this has timed out. */
2109 /* If it was an async create retry, the file
2110 didn't exist. */
2112 if (is_deferred_open_async(ptr)) {
2113 SET_STAT_INVALID(smb_fname->st);
2114 file_existed = false;
2117 /* Ensure we don't reprocess this message. */
2118 remove_deferred_open_message_smb(req->sconn, req->mid);
2120 first_open_attempt = false;
2124 if (!posix_open) {
2125 new_dos_attributes &= SAMBA_ATTRIBUTES_MASK;
2126 if (file_existed) {
2127 existing_dos_attributes = dos_mode(conn, smb_fname);
2131 /* ignore any oplock requests if oplocks are disabled */
2132 if (!lp_oplocks(SNUM(conn)) ||
2133 IS_VETO_OPLOCK_PATH(conn, smb_fname->base_name)) {
2134 /* Mask off everything except the private Samba bits. */
2135 oplock_request &= SAMBA_PRIVATE_OPLOCK_MASK;
2138 /* this is for OS/2 long file names - say we don't support them */
2139 if (!lp_posix_pathnames() && strstr(smb_fname->base_name,".+,;=[].")) {
2140 /* OS/2 Workplace shell fix may be main code stream in a later
2141 * release. */
2142 DEBUG(5,("open_file_ntcreate: OS/2 long filenames are not "
2143 "supported.\n"));
2144 if (use_nt_status()) {
2145 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
2147 return NT_STATUS_DOS(ERRDOS, ERRcannotopen);
2150 switch( create_disposition ) {
2151 case FILE_OPEN:
2152 /* If file exists open. If file doesn't exist error. */
2153 if (!file_existed) {
2154 DEBUG(5,("open_file_ntcreate: FILE_OPEN "
2155 "requested for file %s and file "
2156 "doesn't exist.\n",
2157 smb_fname_str_dbg(smb_fname)));
2158 errno = ENOENT;
2159 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
2161 break;
2163 case FILE_OVERWRITE:
2164 /* If file exists overwrite. If file doesn't exist
2165 * error. */
2166 if (!file_existed) {
2167 DEBUG(5,("open_file_ntcreate: FILE_OVERWRITE "
2168 "requested for file %s and file "
2169 "doesn't exist.\n",
2170 smb_fname_str_dbg(smb_fname) ));
2171 errno = ENOENT;
2172 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
2174 break;
2176 case FILE_CREATE:
2177 /* If file exists error. If file doesn't exist
2178 * create. */
2179 if (file_existed) {
2180 DEBUG(5,("open_file_ntcreate: FILE_CREATE "
2181 "requested for file %s and file "
2182 "already exists.\n",
2183 smb_fname_str_dbg(smb_fname)));
2184 if (S_ISDIR(smb_fname->st.st_ex_mode)) {
2185 errno = EISDIR;
2186 } else {
2187 errno = EEXIST;
2189 return map_nt_error_from_unix(errno);
2191 break;
2193 case FILE_SUPERSEDE:
2194 case FILE_OVERWRITE_IF:
2195 case FILE_OPEN_IF:
2196 break;
2197 default:
2198 return NT_STATUS_INVALID_PARAMETER;
2201 flags2 = disposition_to_open_flags(create_disposition);
2203 /* We only care about matching attributes on file exists and
2204 * overwrite. */
2206 if (!posix_open && file_existed &&
2207 ((create_disposition == FILE_OVERWRITE) ||
2208 (create_disposition == FILE_OVERWRITE_IF))) {
2209 if (!open_match_attributes(conn, existing_dos_attributes,
2210 new_dos_attributes,
2211 smb_fname->st.st_ex_mode,
2212 unx_mode, &new_unx_mode)) {
2213 DEBUG(5,("open_file_ntcreate: attributes missmatch "
2214 "for file %s (%x %x) (0%o, 0%o)\n",
2215 smb_fname_str_dbg(smb_fname),
2216 existing_dos_attributes,
2217 new_dos_attributes,
2218 (unsigned int)smb_fname->st.st_ex_mode,
2219 (unsigned int)unx_mode ));
2220 errno = EACCES;
2221 return NT_STATUS_ACCESS_DENIED;
2225 status = smbd_calculate_access_mask(conn, smb_fname,
2226 false,
2227 access_mask,
2228 &access_mask);
2229 if (!NT_STATUS_IS_OK(status)) {
2230 DEBUG(10, ("open_file_ntcreate: smbd_calculate_access_mask "
2231 "on file %s returned %s\n",
2232 smb_fname_str_dbg(smb_fname), nt_errstr(status)));
2233 return status;
2236 open_access_mask = access_mask;
2238 if ((flags2 & O_TRUNC) || (oplock_request & FORCE_OPLOCK_BREAK_TO_NONE)) {
2239 open_access_mask |= FILE_WRITE_DATA; /* This will cause oplock breaks. */
2242 DEBUG(10, ("open_file_ntcreate: fname=%s, after mapping "
2243 "access_mask=0x%x\n", smb_fname_str_dbg(smb_fname),
2244 access_mask));
2247 * Note that we ignore the append flag as append does not
2248 * mean the same thing under DOS and Unix.
2251 flags = calculate_open_access_flags(access_mask, oplock_request,
2252 private_flags);
2255 * Currently we only look at FILE_WRITE_THROUGH for create options.
2258 #if defined(O_SYNC)
2259 if ((create_options & FILE_WRITE_THROUGH) && lp_strict_sync(SNUM(conn))) {
2260 flags2 |= O_SYNC;
2262 #endif /* O_SYNC */
2264 if (posix_open && (access_mask & FILE_APPEND_DATA)) {
2265 flags2 |= O_APPEND;
2268 if (!posix_open && !CAN_WRITE(conn)) {
2270 * We should really return a permission denied error if either
2271 * O_CREAT or O_TRUNC are set, but for compatibility with
2272 * older versions of Samba we just AND them out.
2274 flags2 &= ~(O_CREAT|O_TRUNC);
2277 if (first_open_attempt && lp_kernel_oplocks(SNUM(conn))) {
2279 * With kernel oplocks the open breaking an oplock
2280 * blocks until the oplock holder has given up the
2281 * oplock or closed the file. We prevent this by first
2282 * trying to open the file with O_NONBLOCK (see "man
2283 * fcntl" on Linux). For the second try, triggered by
2284 * an oplock break response, we do not need this
2285 * anymore.
2287 * This is true under the assumption that only Samba
2288 * requests kernel oplocks. Once someone else like
2289 * NFSv4 starts to use that API, we will have to
2290 * modify this by communicating with the NFSv4 server.
2292 flags2 |= O_NONBLOCK;
2296 * Ensure we can't write on a read-only share or file.
2299 if (flags != O_RDONLY && file_existed &&
2300 (!CAN_WRITE(conn) || IS_DOS_READONLY(existing_dos_attributes))) {
2301 DEBUG(5,("open_file_ntcreate: write access requested for "
2302 "file %s on read only %s\n",
2303 smb_fname_str_dbg(smb_fname),
2304 !CAN_WRITE(conn) ? "share" : "file" ));
2305 errno = EACCES;
2306 return NT_STATUS_ACCESS_DENIED;
2309 fsp->file_id = vfs_file_id_from_sbuf(conn, &smb_fname->st);
2310 fsp->share_access = share_access;
2311 fsp->fh->private_options = private_flags;
2312 fsp->access_mask = open_access_mask; /* We change this to the
2313 * requested access_mask after
2314 * the open is done. */
2315 fsp->posix_open = posix_open;
2317 /* Ensure no SAMBA_PRIVATE bits can be set. */
2318 fsp->oplock_type = (oplock_request & ~SAMBA_PRIVATE_OPLOCK_MASK);
2320 if (timeval_is_zero(&request_time)) {
2321 request_time = fsp->open_time;
2325 * Ensure we pay attention to default ACLs on directories if required.
2328 if ((flags2 & O_CREAT) && lp_inherit_acls(SNUM(conn)) &&
2329 (def_acl = directory_has_default_acl(conn, parent_dir))) {
2330 unx_mode = (0777 & lp_create_mask(SNUM(conn)));
2333 DEBUG(4,("calling open_file with flags=0x%X flags2=0x%X mode=0%o, "
2334 "access_mask = 0x%x, open_access_mask = 0x%x\n",
2335 (unsigned int)flags, (unsigned int)flags2,
2336 (unsigned int)unx_mode, (unsigned int)access_mask,
2337 (unsigned int)open_access_mask));
2339 fsp_open = open_file(fsp, conn, req, parent_dir,
2340 flags|flags2, unx_mode, access_mask,
2341 open_access_mask, &new_file_created);
2343 if (NT_STATUS_EQUAL(fsp_open, NT_STATUS_NETWORK_BUSY)) {
2344 struct deferred_open_record state;
2347 * EWOULDBLOCK/EAGAIN maps to NETWORK_BUSY.
2349 if (file_existed && S_ISFIFO(fsp->fsp_name->st.st_ex_mode)) {
2350 DEBUG(10, ("FIFO busy\n"));
2351 return NT_STATUS_NETWORK_BUSY;
2353 if (req == NULL) {
2354 DEBUG(10, ("Internal open busy\n"));
2355 return NT_STATUS_NETWORK_BUSY;
2359 * From here on we assume this is an oplock break triggered
2362 lck = get_existing_share_mode_lock(talloc_tos(), fsp->file_id);
2363 if (lck == NULL) {
2364 state.delayed_for_oplocks = false;
2365 state.async_open = false;
2366 state.id = fsp->file_id;
2367 defer_open(NULL, request_time, timeval_set(0, 0),
2368 req, &state);
2369 DEBUG(10, ("No share mode lock found after "
2370 "EWOULDBLOCK, retrying sync\n"));
2371 return NT_STATUS_SHARING_VIOLATION;
2374 find_oplock_types(fsp, 0, lck, &batch_entry, &exclusive_entry,
2375 &got_level2_oplock, &got_a_none_oplock);
2377 if (delay_for_batch_oplocks(fsp, req->mid, 0, batch_entry) ||
2378 delay_for_exclusive_oplocks(fsp, req->mid, 0,
2379 exclusive_entry)) {
2380 schedule_defer_open(lck, request_time, req);
2381 TALLOC_FREE(lck);
2382 DEBUG(10, ("Sent oplock break request to kernel "
2383 "oplock holder\n"));
2384 return NT_STATUS_SHARING_VIOLATION;
2388 * No oplock from Samba around. Immediately retry with
2389 * a blocking open.
2391 state.delayed_for_oplocks = false;
2392 state.async_open = false;
2393 state.id = lck->data->id;
2394 defer_open(lck, request_time, timeval_set(0, 0), req, &state);
2395 TALLOC_FREE(lck);
2396 DEBUG(10, ("No Samba oplock around after EWOULDBLOCK. "
2397 "Retrying sync\n"));
2398 return NT_STATUS_SHARING_VIOLATION;
2401 if (!NT_STATUS_IS_OK(fsp_open)) {
2402 if (NT_STATUS_EQUAL(fsp_open, NT_STATUS_RETRY)) {
2403 schedule_async_open(request_time, req);
2405 TALLOC_FREE(lck);
2406 return fsp_open;
2409 if (file_existed && !check_same_dev_ino(&saved_stat, &smb_fname->st)) {
2411 * The file did exist, but some other (local or NFS)
2412 * process either renamed/unlinked and re-created the
2413 * file with different dev/ino after we walked the path,
2414 * but before we did the open. We could retry the
2415 * open but it's a rare enough case it's easier to
2416 * just fail the open to prevent creating any problems
2417 * in the open file db having the wrong dev/ino key.
2419 TALLOC_FREE(lck);
2420 fd_close(fsp);
2421 DEBUG(1,("open_file_ntcreate: file %s - dev/ino mismatch. "
2422 "Old (dev=0x%llu, ino =0x%llu). "
2423 "New (dev=0x%llu, ino=0x%llu). Failing open "
2424 " with NT_STATUS_ACCESS_DENIED.\n",
2425 smb_fname_str_dbg(smb_fname),
2426 (unsigned long long)saved_stat.st_ex_dev,
2427 (unsigned long long)saved_stat.st_ex_ino,
2428 (unsigned long long)smb_fname->st.st_ex_dev,
2429 (unsigned long long)smb_fname->st.st_ex_ino));
2430 return NT_STATUS_ACCESS_DENIED;
2433 old_write_time = smb_fname->st.st_ex_mtime;
2436 * Deal with the race condition where two smbd's detect the
2437 * file doesn't exist and do the create at the same time. One
2438 * of them will win and set a share mode, the other (ie. this
2439 * one) should check if the requested share mode for this
2440 * create is allowed.
2444 * Now the file exists and fsp is successfully opened,
2445 * fsp->dev and fsp->inode are valid and should replace the
2446 * dev=0,inode=0 from a non existent file. Spotted by
2447 * Nadav Danieli <nadavd@exanet.com>. JRA.
2450 id = fsp->file_id;
2452 lck = get_share_mode_lock(talloc_tos(), id,
2453 conn->connectpath,
2454 smb_fname, &old_write_time);
2456 if (lck == NULL) {
2457 DEBUG(0, ("open_file_ntcreate: Could not get share "
2458 "mode lock for %s\n",
2459 smb_fname_str_dbg(smb_fname)));
2460 fd_close(fsp);
2461 return NT_STATUS_SHARING_VIOLATION;
2464 /* Get the types we need to examine. */
2465 find_oplock_types(fsp,
2466 oplock_request,
2467 lck,
2468 &batch_entry,
2469 &exclusive_entry,
2470 &got_level2_oplock,
2471 &got_a_none_oplock);
2473 /* First pass - send break only on batch oplocks. */
2474 if ((req != NULL) &&
2475 delay_for_batch_oplocks(fsp,
2476 req->mid,
2477 oplock_request,
2478 batch_entry)) {
2479 schedule_defer_open(lck, request_time, req);
2480 TALLOC_FREE(lck);
2481 fd_close(fsp);
2482 return NT_STATUS_SHARING_VIOLATION;
2485 status = open_mode_check(conn, lck, fsp->name_hash,
2486 access_mask, share_access,
2487 create_options, &file_existed);
2489 if (NT_STATUS_IS_OK(status)) {
2490 /* We might be going to allow this open. Check oplock
2491 * status again. */
2492 /* Second pass - send break for both batch or
2493 * exclusive oplocks. */
2494 if ((req != NULL) &&
2495 delay_for_exclusive_oplocks(
2496 fsp,
2497 req->mid,
2498 oplock_request,
2499 exclusive_entry)) {
2500 schedule_defer_open(lck, request_time, req);
2501 TALLOC_FREE(lck);
2502 fd_close(fsp);
2503 return NT_STATUS_SHARING_VIOLATION;
2507 if (NT_STATUS_EQUAL(status, NT_STATUS_DELETE_PENDING)) {
2508 /* DELETE_PENDING is not deferred for a second */
2509 TALLOC_FREE(lck);
2510 fd_close(fsp);
2511 return status;
2514 if (!NT_STATUS_IS_OK(status)) {
2515 uint32 can_access_mask;
2516 bool can_access = True;
2518 SMB_ASSERT(NT_STATUS_EQUAL(status, NT_STATUS_SHARING_VIOLATION));
2520 /* Check if this can be done with the deny_dos and fcb
2521 * calls. */
2522 if (private_flags &
2523 (NTCREATEX_OPTIONS_PRIVATE_DENY_DOS|
2524 NTCREATEX_OPTIONS_PRIVATE_DENY_FCB)) {
2525 if (req == NULL) {
2526 DEBUG(0, ("DOS open without an SMB "
2527 "request!\n"));
2528 TALLOC_FREE(lck);
2529 fd_close(fsp);
2530 return NT_STATUS_INTERNAL_ERROR;
2533 /* Use the client requested access mask here,
2534 * not the one we open with. */
2535 status = fcb_or_dos_open(req,
2536 conn,
2537 fsp,
2538 smb_fname,
2540 req->smbpid,
2541 req->vuid,
2542 access_mask,
2543 share_access,
2544 create_options);
2546 if (NT_STATUS_IS_OK(status)) {
2547 TALLOC_FREE(lck);
2548 if (pinfo) {
2549 *pinfo = FILE_WAS_OPENED;
2551 return NT_STATUS_OK;
2556 * This next line is a subtlety we need for
2557 * MS-Access. If a file open will fail due to share
2558 * permissions and also for security (access) reasons,
2559 * we need to return the access failed error, not the
2560 * share error. We can't open the file due to kernel
2561 * oplock deadlock (it's possible we failed above on
2562 * the open_mode_check()) so use a userspace check.
2565 if (flags & O_RDWR) {
2566 can_access_mask = FILE_READ_DATA|FILE_WRITE_DATA;
2567 } else if (flags & O_WRONLY) {
2568 can_access_mask = FILE_WRITE_DATA;
2569 } else {
2570 can_access_mask = FILE_READ_DATA;
2573 if (((can_access_mask & FILE_WRITE_DATA) &&
2574 !CAN_WRITE(conn)) ||
2575 !NT_STATUS_IS_OK(smbd_check_access_rights(conn,
2576 smb_fname,
2577 false,
2578 can_access_mask))) {
2579 can_access = False;
2583 * If we're returning a share violation, ensure we
2584 * cope with the braindead 1 second delay (SMB1 only).
2587 if (!(oplock_request & INTERNAL_OPEN_ONLY) &&
2588 !conn->sconn->using_smb2 &&
2589 lp_defer_sharing_violations()) {
2590 struct timeval timeout;
2591 struct deferred_open_record state;
2592 int timeout_usecs;
2594 /* this is a hack to speed up torture tests
2595 in 'make test' */
2596 timeout_usecs = lp_parm_int(SNUM(conn),
2597 "smbd","sharedelay",
2598 SHARING_VIOLATION_USEC_WAIT);
2600 /* This is a relative time, added to the absolute
2601 request_time value to get the absolute timeout time.
2602 Note that if this is the second or greater time we enter
2603 this codepath for this particular request mid then
2604 request_time is left as the absolute time of the *first*
2605 time this request mid was processed. This is what allows
2606 the request to eventually time out. */
2608 timeout = timeval_set(0, timeout_usecs);
2610 /* Nothing actually uses state.delayed_for_oplocks
2611 but it's handy to differentiate in debug messages
2612 between a 30 second delay due to oplock break, and
2613 a 1 second delay for share mode conflicts. */
2615 state.delayed_for_oplocks = False;
2616 state.async_open = false;
2617 state.id = id;
2619 if ((req != NULL)
2620 && !request_timed_out(request_time,
2621 timeout)) {
2622 defer_open(lck, request_time, timeout,
2623 req, &state);
2627 TALLOC_FREE(lck);
2628 fd_close(fsp);
2629 if (can_access) {
2631 * We have detected a sharing violation here
2632 * so return the correct error code
2634 status = NT_STATUS_SHARING_VIOLATION;
2635 } else {
2636 status = NT_STATUS_ACCESS_DENIED;
2638 return status;
2641 grant_fsp_oplock_type(fsp,
2642 oplock_request,
2643 got_level2_oplock,
2644 got_a_none_oplock);
2647 * We have the share entry *locked*.....
2650 /* Delete streams if create_disposition requires it */
2651 if (!new_file_created && clear_ads(create_disposition) &&
2652 !is_ntfs_stream_smb_fname(smb_fname)) {
2653 status = delete_all_streams(conn, smb_fname->base_name);
2654 if (!NT_STATUS_IS_OK(status)) {
2655 TALLOC_FREE(lck);
2656 fd_close(fsp);
2657 return status;
2661 /* note that we ignore failure for the following. It is
2662 basically a hack for NFS, and NFS will never set one of
2663 these only read them. Nobody but Samba can ever set a deny
2664 mode and we have already checked our more authoritative
2665 locking database for permission to set this deny mode. If
2666 the kernel refuses the operations then the kernel is wrong.
2667 note that GPFS supports it as well - jmcd */
2669 if (fsp->fh->fd != -1 && lp_kernel_share_modes(SNUM(conn))) {
2670 int ret_flock;
2671 ret_flock = SMB_VFS_KERNEL_FLOCK(fsp, share_access, access_mask);
2672 if(ret_flock == -1 ){
2674 TALLOC_FREE(lck);
2675 fd_close(fsp);
2677 return NT_STATUS_SHARING_VIOLATION;
2682 * At this point onwards, we can guarantee that the share entry
2683 * is locked, whether we created the file or not, and that the
2684 * deny mode is compatible with all current opens.
2688 * According to Samba4, SEC_FILE_READ_ATTRIBUTE is always granted,
2689 * but we don't have to store this - just ignore it on access check.
2691 if (conn->sconn->using_smb2) {
2693 * SMB2 doesn't return it (according to Microsoft tests).
2694 * Test Case: TestSuite_ScenarioNo009GrantedAccessTestS0
2695 * File created with access = 0x7 (Read, Write, Delete)
2696 * Query Info on file returns 0x87 (Read, Write, Delete, Read Attributes)
2698 fsp->access_mask = access_mask;
2699 } else {
2700 /* But SMB1 does. */
2701 fsp->access_mask = access_mask | FILE_READ_ATTRIBUTES;
2704 if (file_existed) {
2705 /* stat opens on existing files don't get oplocks. */
2706 if (is_stat_open(open_access_mask)) {
2707 fsp->oplock_type = NO_OPLOCK;
2711 if (new_file_created) {
2712 info = FILE_WAS_CREATED;
2713 } else {
2714 if (flags2 & O_TRUNC) {
2715 info = FILE_WAS_OVERWRITTEN;
2716 } else {
2717 info = FILE_WAS_OPENED;
2721 if (pinfo) {
2722 *pinfo = info;
2726 * Setup the oplock info in both the shared memory and
2727 * file structs.
2730 status = set_file_oplock(fsp, fsp->oplock_type);
2731 if (!NT_STATUS_IS_OK(status)) {
2733 * Could not get the kernel oplock or there are byte-range
2734 * locks on the file.
2736 fsp->oplock_type = NO_OPLOCK;
2739 set_share_mode(lck, fsp, get_current_uid(conn),
2740 req ? req->mid : 0,
2741 fsp->oplock_type);
2743 /* Handle strange delete on close create semantics. */
2744 if (create_options & FILE_DELETE_ON_CLOSE) {
2746 status = can_set_delete_on_close(fsp, new_dos_attributes);
2748 if (!NT_STATUS_IS_OK(status)) {
2749 /* Remember to delete the mode we just added. */
2750 del_share_mode(lck, fsp);
2751 TALLOC_FREE(lck);
2752 fd_close(fsp);
2753 return status;
2755 /* Note that here we set the *inital* delete on close flag,
2756 not the regular one. The magic gets handled in close. */
2757 fsp->initial_delete_on_close = True;
2760 if (info != FILE_WAS_OPENED) {
2761 /* Files should be initially set as archive */
2762 if (lp_map_archive(SNUM(conn)) ||
2763 lp_store_dos_attributes(SNUM(conn))) {
2764 if (!posix_open) {
2765 if (file_set_dosmode(conn, smb_fname,
2766 new_dos_attributes | FILE_ATTRIBUTE_ARCHIVE,
2767 parent_dir, true) == 0) {
2768 unx_mode = smb_fname->st.st_ex_mode;
2774 /* Determine sparse flag. */
2775 if (posix_open) {
2776 /* POSIX opens are sparse by default. */
2777 fsp->is_sparse = true;
2778 } else {
2779 fsp->is_sparse = (file_existed &&
2780 (existing_dos_attributes & FILE_ATTRIBUTE_SPARSE));
2784 * Take care of inherited ACLs on created files - if default ACL not
2785 * selected.
2788 if (!posix_open && new_file_created && !def_acl) {
2790 int saved_errno = errno; /* We might get ENOSYS in the next
2791 * call.. */
2793 if (SMB_VFS_FCHMOD_ACL(fsp, unx_mode) == -1 &&
2794 errno == ENOSYS) {
2795 errno = saved_errno; /* Ignore ENOSYS */
2798 } else if (new_unx_mode) {
2800 int ret = -1;
2802 /* Attributes need changing. File already existed. */
2805 int saved_errno = errno; /* We might get ENOSYS in the
2806 * next call.. */
2807 ret = SMB_VFS_FCHMOD_ACL(fsp, new_unx_mode);
2809 if (ret == -1 && errno == ENOSYS) {
2810 errno = saved_errno; /* Ignore ENOSYS */
2811 } else {
2812 DEBUG(5, ("open_file_ntcreate: reset "
2813 "attributes of file %s to 0%o\n",
2814 smb_fname_str_dbg(smb_fname),
2815 (unsigned int)new_unx_mode));
2816 ret = 0; /* Don't do the fchmod below. */
2820 if ((ret == -1) &&
2821 (SMB_VFS_FCHMOD(fsp, new_unx_mode) == -1))
2822 DEBUG(5, ("open_file_ntcreate: failed to reset "
2823 "attributes of file %s to 0%o\n",
2824 smb_fname_str_dbg(smb_fname),
2825 (unsigned int)new_unx_mode));
2828 TALLOC_FREE(lck);
2830 return NT_STATUS_OK;
2834 /****************************************************************************
2835 Open a file for for write to ensure that we can fchmod it.
2836 ****************************************************************************/
2838 NTSTATUS open_file_fchmod(connection_struct *conn,
2839 struct smb_filename *smb_fname,
2840 files_struct **result)
2842 if (!VALID_STAT(smb_fname->st)) {
2843 return NT_STATUS_INVALID_PARAMETER;
2846 return SMB_VFS_CREATE_FILE(
2847 conn, /* conn */
2848 NULL, /* req */
2849 0, /* root_dir_fid */
2850 smb_fname, /* fname */
2851 FILE_WRITE_DATA, /* access_mask */
2852 (FILE_SHARE_READ | FILE_SHARE_WRITE | /* share_access */
2853 FILE_SHARE_DELETE),
2854 FILE_OPEN, /* create_disposition*/
2855 0, /* create_options */
2856 0, /* file_attributes */
2857 INTERNAL_OPEN_ONLY, /* oplock_request */
2858 0, /* allocation_size */
2859 0, /* private_flags */
2860 NULL, /* sd */
2861 NULL, /* ea_list */
2862 result, /* result */
2863 NULL); /* pinfo */
2866 static NTSTATUS mkdir_internal(connection_struct *conn,
2867 struct smb_filename *smb_dname,
2868 uint32 file_attributes)
2870 mode_t mode;
2871 char *parent_dir = NULL;
2872 NTSTATUS status;
2873 bool posix_open = false;
2874 bool need_re_stat = false;
2875 uint32_t access_mask = SEC_DIR_ADD_SUBDIR;
2877 if (!CAN_WRITE(conn) || (access_mask & ~(conn->share_access))) {
2878 DEBUG(5,("mkdir_internal: failing share access "
2879 "%s\n", lp_servicename(talloc_tos(), SNUM(conn))));
2880 return NT_STATUS_ACCESS_DENIED;
2883 if (!parent_dirname(talloc_tos(), smb_dname->base_name, &parent_dir,
2884 NULL)) {
2885 return NT_STATUS_NO_MEMORY;
2888 if (file_attributes & FILE_FLAG_POSIX_SEMANTICS) {
2889 posix_open = true;
2890 mode = (mode_t)(file_attributes & ~FILE_FLAG_POSIX_SEMANTICS);
2891 } else {
2892 mode = unix_mode(conn, FILE_ATTRIBUTE_DIRECTORY, smb_dname, parent_dir);
2895 status = check_parent_access(conn,
2896 smb_dname,
2897 access_mask);
2898 if(!NT_STATUS_IS_OK(status)) {
2899 DEBUG(5,("mkdir_internal: check_parent_access "
2900 "on directory %s for path %s returned %s\n",
2901 parent_dir,
2902 smb_dname->base_name,
2903 nt_errstr(status) ));
2904 return status;
2907 if (SMB_VFS_MKDIR(conn, smb_dname->base_name, mode) != 0) {
2908 return map_nt_error_from_unix(errno);
2911 /* Ensure we're checking for a symlink here.... */
2912 /* We don't want to get caught by a symlink racer. */
2914 if (SMB_VFS_LSTAT(conn, smb_dname) == -1) {
2915 DEBUG(2, ("Could not stat directory '%s' just created: %s\n",
2916 smb_fname_str_dbg(smb_dname), strerror(errno)));
2917 return map_nt_error_from_unix(errno);
2920 if (!S_ISDIR(smb_dname->st.st_ex_mode)) {
2921 DEBUG(0, ("Directory '%s' just created is not a directory !\n",
2922 smb_fname_str_dbg(smb_dname)));
2923 return NT_STATUS_NOT_A_DIRECTORY;
2926 if (lp_store_dos_attributes(SNUM(conn))) {
2927 if (!posix_open) {
2928 file_set_dosmode(conn, smb_dname,
2929 file_attributes | FILE_ATTRIBUTE_DIRECTORY,
2930 parent_dir, true);
2934 if (lp_inherit_perms(SNUM(conn))) {
2935 inherit_access_posix_acl(conn, parent_dir,
2936 smb_dname->base_name, mode);
2937 need_re_stat = true;
2940 if (!posix_open) {
2942 * Check if high bits should have been set,
2943 * then (if bits are missing): add them.
2944 * Consider bits automagically set by UNIX, i.e. SGID bit from parent
2945 * dir.
2947 if ((mode & ~(S_IRWXU|S_IRWXG|S_IRWXO)) &&
2948 (mode & ~smb_dname->st.st_ex_mode)) {
2949 SMB_VFS_CHMOD(conn, smb_dname->base_name,
2950 (smb_dname->st.st_ex_mode |
2951 (mode & ~smb_dname->st.st_ex_mode)));
2952 need_re_stat = true;
2956 /* Change the owner if required. */
2957 if (lp_inherit_owner(SNUM(conn))) {
2958 change_dir_owner_to_parent(conn, parent_dir,
2959 smb_dname->base_name,
2960 &smb_dname->st);
2961 need_re_stat = true;
2964 if (need_re_stat) {
2965 if (SMB_VFS_LSTAT(conn, smb_dname) == -1) {
2966 DEBUG(2, ("Could not stat directory '%s' just created: %s\n",
2967 smb_fname_str_dbg(smb_dname), strerror(errno)));
2968 return map_nt_error_from_unix(errno);
2972 notify_fname(conn, NOTIFY_ACTION_ADDED, FILE_NOTIFY_CHANGE_DIR_NAME,
2973 smb_dname->base_name);
2975 return NT_STATUS_OK;
2978 /****************************************************************************
2979 Open a directory from an NT SMB call.
2980 ****************************************************************************/
2982 static NTSTATUS open_directory(connection_struct *conn,
2983 struct smb_request *req,
2984 struct smb_filename *smb_dname,
2985 uint32 access_mask,
2986 uint32 share_access,
2987 uint32 create_disposition,
2988 uint32 create_options,
2989 uint32 file_attributes,
2990 int *pinfo,
2991 files_struct **result)
2993 files_struct *fsp = NULL;
2994 bool dir_existed = VALID_STAT(smb_dname->st) ? True : False;
2995 struct share_mode_lock *lck = NULL;
2996 NTSTATUS status;
2997 struct timespec mtimespec;
2998 int info = 0;
3000 if (is_ntfs_stream_smb_fname(smb_dname)) {
3001 DEBUG(2, ("open_directory: %s is a stream name!\n",
3002 smb_fname_str_dbg(smb_dname)));
3003 return NT_STATUS_NOT_A_DIRECTORY;
3006 if (!(file_attributes & FILE_FLAG_POSIX_SEMANTICS)) {
3007 /* Ensure we have a directory attribute. */
3008 file_attributes |= FILE_ATTRIBUTE_DIRECTORY;
3011 DEBUG(5,("open_directory: opening directory %s, access_mask = 0x%x, "
3012 "share_access = 0x%x create_options = 0x%x, "
3013 "create_disposition = 0x%x, file_attributes = 0x%x\n",
3014 smb_fname_str_dbg(smb_dname),
3015 (unsigned int)access_mask,
3016 (unsigned int)share_access,
3017 (unsigned int)create_options,
3018 (unsigned int)create_disposition,
3019 (unsigned int)file_attributes));
3021 status = smbd_calculate_access_mask(conn, smb_dname, false,
3022 access_mask, &access_mask);
3023 if (!NT_STATUS_IS_OK(status)) {
3024 DEBUG(10, ("open_directory: smbd_calculate_access_mask "
3025 "on file %s returned %s\n",
3026 smb_fname_str_dbg(smb_dname),
3027 nt_errstr(status)));
3028 return status;
3031 if ((access_mask & SEC_FLAG_SYSTEM_SECURITY) &&
3032 !security_token_has_privilege(get_current_nttok(conn),
3033 SEC_PRIV_SECURITY)) {
3034 DEBUG(10, ("open_directory: open on %s "
3035 "failed - SEC_FLAG_SYSTEM_SECURITY denied.\n",
3036 smb_fname_str_dbg(smb_dname)));
3037 return NT_STATUS_PRIVILEGE_NOT_HELD;
3040 switch( create_disposition ) {
3041 case FILE_OPEN:
3043 if (!dir_existed) {
3044 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3047 info = FILE_WAS_OPENED;
3048 break;
3050 case FILE_CREATE:
3052 /* If directory exists error. If directory doesn't
3053 * exist create. */
3055 if (dir_existed) {
3056 status = NT_STATUS_OBJECT_NAME_COLLISION;
3057 DEBUG(2, ("open_directory: unable to create "
3058 "%s. Error was %s\n",
3059 smb_fname_str_dbg(smb_dname),
3060 nt_errstr(status)));
3061 return status;
3064 status = mkdir_internal(conn, smb_dname,
3065 file_attributes);
3067 if (!NT_STATUS_IS_OK(status)) {
3068 DEBUG(2, ("open_directory: unable to create "
3069 "%s. Error was %s\n",
3070 smb_fname_str_dbg(smb_dname),
3071 nt_errstr(status)));
3072 return status;
3075 info = FILE_WAS_CREATED;
3076 break;
3078 case FILE_OPEN_IF:
3080 * If directory exists open. If directory doesn't
3081 * exist create.
3084 if (dir_existed) {
3085 status = NT_STATUS_OK;
3086 info = FILE_WAS_OPENED;
3087 } else {
3088 status = mkdir_internal(conn, smb_dname,
3089 file_attributes);
3091 if (NT_STATUS_IS_OK(status)) {
3092 info = FILE_WAS_CREATED;
3093 } else {
3094 /* Cope with create race. */
3095 if (!NT_STATUS_EQUAL(status,
3096 NT_STATUS_OBJECT_NAME_COLLISION)) {
3097 DEBUG(2, ("open_directory: unable to create "
3098 "%s. Error was %s\n",
3099 smb_fname_str_dbg(smb_dname),
3100 nt_errstr(status)));
3101 return status;
3103 info = FILE_WAS_OPENED;
3107 break;
3109 case FILE_SUPERSEDE:
3110 case FILE_OVERWRITE:
3111 case FILE_OVERWRITE_IF:
3112 default:
3113 DEBUG(5,("open_directory: invalid create_disposition "
3114 "0x%x for directory %s\n",
3115 (unsigned int)create_disposition,
3116 smb_fname_str_dbg(smb_dname)));
3117 return NT_STATUS_INVALID_PARAMETER;
3120 if(!S_ISDIR(smb_dname->st.st_ex_mode)) {
3121 DEBUG(5,("open_directory: %s is not a directory !\n",
3122 smb_fname_str_dbg(smb_dname)));
3123 return NT_STATUS_NOT_A_DIRECTORY;
3126 if (info == FILE_WAS_OPENED) {
3127 status = smbd_check_access_rights(conn,
3128 smb_dname,
3129 false,
3130 access_mask);
3131 if (!NT_STATUS_IS_OK(status)) {
3132 DEBUG(10, ("open_directory: smbd_check_access_rights on "
3133 "file %s failed with %s\n",
3134 smb_fname_str_dbg(smb_dname),
3135 nt_errstr(status)));
3136 return status;
3140 status = file_new(req, conn, &fsp);
3141 if(!NT_STATUS_IS_OK(status)) {
3142 return status;
3146 * Setup the files_struct for it.
3149 fsp->file_id = vfs_file_id_from_sbuf(conn, &smb_dname->st);
3150 fsp->vuid = req ? req->vuid : UID_FIELD_INVALID;
3151 fsp->file_pid = req ? req->smbpid : 0;
3152 fsp->can_lock = False;
3153 fsp->can_read = False;
3154 fsp->can_write = False;
3156 fsp->share_access = share_access;
3157 fsp->fh->private_options = 0;
3159 * According to Samba4, SEC_FILE_READ_ATTRIBUTE is always granted,
3161 fsp->access_mask = access_mask | FILE_READ_ATTRIBUTES;
3162 fsp->print_file = NULL;
3163 fsp->modified = False;
3164 fsp->oplock_type = NO_OPLOCK;
3165 fsp->sent_oplock_break = NO_BREAK_SENT;
3166 fsp->is_directory = True;
3167 fsp->posix_open = (file_attributes & FILE_FLAG_POSIX_SEMANTICS) ? True : False;
3168 status = fsp_set_smb_fname(fsp, smb_dname);
3169 if (!NT_STATUS_IS_OK(status)) {
3170 file_free(req, fsp);
3171 return status;
3174 mtimespec = smb_dname->st.st_ex_mtime;
3176 #ifdef O_DIRECTORY
3177 status = fd_open(conn, fsp, O_RDONLY|O_DIRECTORY, 0);
3178 #else
3179 /* POSIX allows us to open a directory with O_RDONLY. */
3180 status = fd_open(conn, fsp, O_RDONLY, 0);
3181 #endif
3182 if (!NT_STATUS_IS_OK(status)) {
3183 DEBUG(5, ("open_directory: Could not open fd for "
3184 "%s (%s)\n",
3185 smb_fname_str_dbg(smb_dname),
3186 nt_errstr(status)));
3187 file_free(req, fsp);
3188 return status;
3191 status = vfs_stat_fsp(fsp);
3192 if (!NT_STATUS_IS_OK(status)) {
3193 fd_close(fsp);
3194 file_free(req, fsp);
3195 return status;
3198 /* Ensure there was no race condition. */
3199 if (!check_same_stat(&smb_dname->st, &fsp->fsp_name->st)) {
3200 DEBUG(5,("open_directory: stat struct differs for "
3201 "directory %s.\n",
3202 smb_fname_str_dbg(smb_dname)));
3203 fd_close(fsp);
3204 file_free(req, fsp);
3205 return NT_STATUS_ACCESS_DENIED;
3208 lck = get_share_mode_lock(talloc_tos(), fsp->file_id,
3209 conn->connectpath, smb_dname,
3210 &mtimespec);
3212 if (lck == NULL) {
3213 DEBUG(0, ("open_directory: Could not get share mode lock for "
3214 "%s\n", smb_fname_str_dbg(smb_dname)));
3215 fd_close(fsp);
3216 file_free(req, fsp);
3217 return NT_STATUS_SHARING_VIOLATION;
3220 status = open_mode_check(conn, lck, fsp->name_hash,
3221 access_mask, share_access,
3222 create_options, &dir_existed);
3224 if (!NT_STATUS_IS_OK(status)) {
3225 TALLOC_FREE(lck);
3226 fd_close(fsp);
3227 file_free(req, fsp);
3228 return status;
3231 set_share_mode(lck, fsp, get_current_uid(conn),
3232 req ? req->mid : 0, NO_OPLOCK);
3234 /* For directories the delete on close bit at open time seems
3235 always to be honored on close... See test 19 in Samba4 BASE-DELETE. */
3236 if (create_options & FILE_DELETE_ON_CLOSE) {
3237 status = can_set_delete_on_close(fsp, 0);
3238 if (!NT_STATUS_IS_OK(status) && !NT_STATUS_EQUAL(status, NT_STATUS_DIRECTORY_NOT_EMPTY)) {
3239 TALLOC_FREE(lck);
3240 fd_close(fsp);
3241 file_free(req, fsp);
3242 return status;
3245 if (NT_STATUS_IS_OK(status)) {
3246 /* Note that here we set the *inital* delete on close flag,
3247 not the regular one. The magic gets handled in close. */
3248 fsp->initial_delete_on_close = True;
3252 TALLOC_FREE(lck);
3254 if (pinfo) {
3255 *pinfo = info;
3258 *result = fsp;
3259 return NT_STATUS_OK;
3262 NTSTATUS create_directory(connection_struct *conn, struct smb_request *req,
3263 struct smb_filename *smb_dname)
3265 NTSTATUS status;
3266 files_struct *fsp;
3268 status = SMB_VFS_CREATE_FILE(
3269 conn, /* conn */
3270 req, /* req */
3271 0, /* root_dir_fid */
3272 smb_dname, /* fname */
3273 FILE_READ_ATTRIBUTES, /* access_mask */
3274 FILE_SHARE_NONE, /* share_access */
3275 FILE_CREATE, /* create_disposition*/
3276 FILE_DIRECTORY_FILE, /* create_options */
3277 FILE_ATTRIBUTE_DIRECTORY, /* file_attributes */
3278 0, /* oplock_request */
3279 0, /* allocation_size */
3280 0, /* private_flags */
3281 NULL, /* sd */
3282 NULL, /* ea_list */
3283 &fsp, /* result */
3284 NULL); /* pinfo */
3286 if (NT_STATUS_IS_OK(status)) {
3287 close_file(req, fsp, NORMAL_CLOSE);
3290 return status;
3293 /****************************************************************************
3294 Receive notification that one of our open files has been renamed by another
3295 smbd process.
3296 ****************************************************************************/
3298 void msg_file_was_renamed(struct messaging_context *msg,
3299 void *private_data,
3300 uint32_t msg_type,
3301 struct server_id server_id,
3302 DATA_BLOB *data)
3304 files_struct *fsp;
3305 char *frm = (char *)data->data;
3306 struct file_id id;
3307 const char *sharepath;
3308 const char *base_name;
3309 const char *stream_name;
3310 struct smb_filename *smb_fname = NULL;
3311 size_t sp_len, bn_len;
3312 NTSTATUS status;
3313 struct smbd_server_connection *sconn =
3314 talloc_get_type_abort(private_data,
3315 struct smbd_server_connection);
3317 if (data->data == NULL
3318 || data->length < MSG_FILE_RENAMED_MIN_SIZE + 2) {
3319 DEBUG(0, ("msg_file_was_renamed: Got invalid msg len %d\n",
3320 (int)data->length));
3321 return;
3324 /* Unpack the message. */
3325 pull_file_id_24(frm, &id);
3326 sharepath = &frm[24];
3327 sp_len = strlen(sharepath);
3328 base_name = sharepath + sp_len + 1;
3329 bn_len = strlen(base_name);
3330 stream_name = sharepath + sp_len + 1 + bn_len + 1;
3332 /* stream_name must always be NULL if there is no stream. */
3333 if (stream_name[0] == '\0') {
3334 stream_name = NULL;
3337 smb_fname = synthetic_smb_fname(talloc_tos(), base_name,
3338 stream_name, NULL);
3339 if (smb_fname == NULL) {
3340 return;
3343 DEBUG(10,("msg_file_was_renamed: Got rename message for sharepath %s, new name %s, "
3344 "file_id %s\n",
3345 sharepath, smb_fname_str_dbg(smb_fname),
3346 file_id_string_tos(&id)));
3348 for(fsp = file_find_di_first(sconn, id); fsp;
3349 fsp = file_find_di_next(fsp)) {
3350 if (memcmp(fsp->conn->connectpath, sharepath, sp_len) == 0) {
3352 DEBUG(10,("msg_file_was_renamed: renaming file %s from %s -> %s\n",
3353 fsp_fnum_dbg(fsp), fsp_str_dbg(fsp),
3354 smb_fname_str_dbg(smb_fname)));
3355 status = fsp_set_smb_fname(fsp, smb_fname);
3356 if (!NT_STATUS_IS_OK(status)) {
3357 goto out;
3359 } else {
3360 /* TODO. JRA. */
3361 /* Now we have the complete path we can work out if this is
3362 actually within this share and adjust newname accordingly. */
3363 DEBUG(10,("msg_file_was_renamed: share mismatch (sharepath %s "
3364 "not sharepath %s) "
3365 "%s from %s -> %s\n",
3366 fsp->conn->connectpath,
3367 sharepath,
3368 fsp_fnum_dbg(fsp),
3369 fsp_str_dbg(fsp),
3370 smb_fname_str_dbg(smb_fname)));
3373 out:
3374 TALLOC_FREE(smb_fname);
3375 return;
3379 * If a main file is opened for delete, all streams need to be checked for
3380 * !FILE_SHARE_DELETE. Do this by opening with DELETE_ACCESS.
3381 * If that works, delete them all by setting the delete on close and close.
3384 NTSTATUS open_streams_for_delete(connection_struct *conn,
3385 const char *fname)
3387 struct stream_struct *stream_info = NULL;
3388 files_struct **streams = NULL;
3389 int i;
3390 unsigned int num_streams = 0;
3391 TALLOC_CTX *frame = talloc_stackframe();
3392 NTSTATUS status;
3394 status = vfs_streaminfo(conn, NULL, fname, talloc_tos(),
3395 &num_streams, &stream_info);
3397 if (NT_STATUS_EQUAL(status, NT_STATUS_NOT_IMPLEMENTED)
3398 || NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
3399 DEBUG(10, ("no streams around\n"));
3400 TALLOC_FREE(frame);
3401 return NT_STATUS_OK;
3404 if (!NT_STATUS_IS_OK(status)) {
3405 DEBUG(10, ("vfs_streaminfo failed: %s\n",
3406 nt_errstr(status)));
3407 goto fail;
3410 DEBUG(10, ("open_streams_for_delete found %d streams\n",
3411 num_streams));
3413 if (num_streams == 0) {
3414 TALLOC_FREE(frame);
3415 return NT_STATUS_OK;
3418 streams = talloc_array(talloc_tos(), files_struct *, num_streams);
3419 if (streams == NULL) {
3420 DEBUG(0, ("talloc failed\n"));
3421 status = NT_STATUS_NO_MEMORY;
3422 goto fail;
3425 for (i=0; i<num_streams; i++) {
3426 struct smb_filename *smb_fname;
3428 if (strequal(stream_info[i].name, "::$DATA")) {
3429 streams[i] = NULL;
3430 continue;
3433 smb_fname = synthetic_smb_fname(
3434 talloc_tos(), fname, stream_info[i].name, NULL);
3435 if (smb_fname == NULL) {
3436 status = NT_STATUS_NO_MEMORY;
3437 goto fail;
3440 if (SMB_VFS_STAT(conn, smb_fname) == -1) {
3441 DEBUG(10, ("Unable to stat stream: %s\n",
3442 smb_fname_str_dbg(smb_fname)));
3445 status = SMB_VFS_CREATE_FILE(
3446 conn, /* conn */
3447 NULL, /* req */
3448 0, /* root_dir_fid */
3449 smb_fname, /* fname */
3450 DELETE_ACCESS, /* access_mask */
3451 (FILE_SHARE_READ | /* share_access */
3452 FILE_SHARE_WRITE | FILE_SHARE_DELETE),
3453 FILE_OPEN, /* create_disposition*/
3454 0, /* create_options */
3455 FILE_ATTRIBUTE_NORMAL, /* file_attributes */
3456 0, /* oplock_request */
3457 0, /* allocation_size */
3458 NTCREATEX_OPTIONS_PRIVATE_STREAM_DELETE, /* private_flags */
3459 NULL, /* sd */
3460 NULL, /* ea_list */
3461 &streams[i], /* result */
3462 NULL); /* pinfo */
3464 if (!NT_STATUS_IS_OK(status)) {
3465 DEBUG(10, ("Could not open stream %s: %s\n",
3466 smb_fname_str_dbg(smb_fname),
3467 nt_errstr(status)));
3469 TALLOC_FREE(smb_fname);
3470 break;
3472 TALLOC_FREE(smb_fname);
3476 * don't touch the variable "status" beyond this point :-)
3479 for (i -= 1 ; i >= 0; i--) {
3480 if (streams[i] == NULL) {
3481 continue;
3484 DEBUG(10, ("Closing stream # %d, %s\n", i,
3485 fsp_str_dbg(streams[i])));
3486 close_file(NULL, streams[i], NORMAL_CLOSE);
3489 fail:
3490 TALLOC_FREE(frame);
3491 return status;
3494 /*********************************************************************
3495 Create a default ACL by inheriting from the parent. If no inheritance
3496 from the parent available, don't set anything. This will leave the actual
3497 permissions the new file or directory already got from the filesystem
3498 as the NT ACL when read.
3499 *********************************************************************/
3501 static NTSTATUS inherit_new_acl(files_struct *fsp)
3503 TALLOC_CTX *frame = talloc_stackframe();
3504 char *parent_name = NULL;
3505 struct security_descriptor *parent_desc = NULL;
3506 NTSTATUS status = NT_STATUS_OK;
3507 struct security_descriptor *psd = NULL;
3508 const struct dom_sid *owner_sid = NULL;
3509 const struct dom_sid *group_sid = NULL;
3510 uint32_t security_info_sent = (SECINFO_OWNER | SECINFO_GROUP | SECINFO_DACL);
3511 struct security_token *token = fsp->conn->session_info->security_token;
3512 bool inherit_owner = lp_inherit_owner(SNUM(fsp->conn));
3513 bool inheritable_components = false;
3514 bool try_builtin_administrators = false;
3515 const struct dom_sid *BA_U_sid = NULL;
3516 const struct dom_sid *BA_G_sid = NULL;
3517 bool try_system = false;
3518 const struct dom_sid *SY_U_sid = NULL;
3519 const struct dom_sid *SY_G_sid = NULL;
3520 size_t size = 0;
3522 if (!parent_dirname(frame, fsp->fsp_name->base_name, &parent_name, NULL)) {
3523 TALLOC_FREE(frame);
3524 return NT_STATUS_NO_MEMORY;
3527 status = SMB_VFS_GET_NT_ACL(fsp->conn,
3528 parent_name,
3529 (SECINFO_OWNER | SECINFO_GROUP | SECINFO_DACL),
3530 frame,
3531 &parent_desc);
3532 if (!NT_STATUS_IS_OK(status)) {
3533 TALLOC_FREE(frame);
3534 return status;
3537 inheritable_components = sd_has_inheritable_components(parent_desc,
3538 fsp->is_directory);
3540 if (!inheritable_components && !inherit_owner) {
3541 TALLOC_FREE(frame);
3542 /* Nothing to inherit and not setting owner. */
3543 return NT_STATUS_OK;
3546 /* Create an inherited descriptor from the parent. */
3548 if (DEBUGLEVEL >= 10) {
3549 DEBUG(10,("inherit_new_acl: parent acl for %s is:\n",
3550 fsp_str_dbg(fsp) ));
3551 NDR_PRINT_DEBUG(security_descriptor, parent_desc);
3554 /* Inherit from parent descriptor if "inherit owner" set. */
3555 if (inherit_owner) {
3556 owner_sid = parent_desc->owner_sid;
3557 group_sid = parent_desc->group_sid;
3560 if (owner_sid == NULL) {
3561 if (security_token_has_builtin_administrators(token)) {
3562 try_builtin_administrators = true;
3563 } else if (security_token_is_system(token)) {
3564 try_builtin_administrators = true;
3565 try_system = true;
3569 if (group_sid == NULL &&
3570 token->num_sids == PRIMARY_GROUP_SID_INDEX)
3572 if (security_token_is_system(token)) {
3573 try_builtin_administrators = true;
3574 try_system = true;
3578 if (try_builtin_administrators) {
3579 struct unixid ids;
3580 bool ok;
3582 ZERO_STRUCT(ids);
3583 ok = sids_to_unixids(&global_sid_Builtin_Administrators, 1, &ids);
3584 if (ok) {
3585 switch (ids.type) {
3586 case ID_TYPE_BOTH:
3587 BA_U_sid = &global_sid_Builtin_Administrators;
3588 BA_G_sid = &global_sid_Builtin_Administrators;
3589 break;
3590 case ID_TYPE_UID:
3591 BA_U_sid = &global_sid_Builtin_Administrators;
3592 break;
3593 case ID_TYPE_GID:
3594 BA_G_sid = &global_sid_Builtin_Administrators;
3595 break;
3596 default:
3597 break;
3602 if (try_system) {
3603 struct unixid ids;
3604 bool ok;
3606 ZERO_STRUCT(ids);
3607 ok = sids_to_unixids(&global_sid_System, 1, &ids);
3608 if (ok) {
3609 switch (ids.type) {
3610 case ID_TYPE_BOTH:
3611 SY_U_sid = &global_sid_System;
3612 SY_G_sid = &global_sid_System;
3613 break;
3614 case ID_TYPE_UID:
3615 SY_U_sid = &global_sid_System;
3616 break;
3617 case ID_TYPE_GID:
3618 SY_G_sid = &global_sid_System;
3619 break;
3620 default:
3621 break;
3626 if (owner_sid == NULL) {
3627 owner_sid = BA_U_sid;
3630 if (owner_sid == NULL) {
3631 owner_sid = SY_U_sid;
3634 if (group_sid == NULL) {
3635 group_sid = SY_G_sid;
3638 if (try_system && group_sid == NULL) {
3639 group_sid = BA_G_sid;
3642 if (owner_sid == NULL) {
3643 owner_sid = &token->sids[PRIMARY_USER_SID_INDEX];
3645 if (group_sid == NULL) {
3646 if (token->num_sids == PRIMARY_GROUP_SID_INDEX) {
3647 group_sid = &token->sids[PRIMARY_USER_SID_INDEX];
3648 } else {
3649 group_sid = &token->sids[PRIMARY_GROUP_SID_INDEX];
3653 status = se_create_child_secdesc(frame,
3654 &psd,
3655 &size,
3656 parent_desc,
3657 owner_sid,
3658 group_sid,
3659 fsp->is_directory);
3660 if (!NT_STATUS_IS_OK(status)) {
3661 TALLOC_FREE(frame);
3662 return status;
3665 /* If inheritable_components == false,
3666 se_create_child_secdesc()
3667 creates a security desriptor with a NULL dacl
3668 entry, but with SEC_DESC_DACL_PRESENT. We need
3669 to remove that flag. */
3671 if (!inheritable_components) {
3672 security_info_sent &= ~SECINFO_DACL;
3673 psd->type &= ~SEC_DESC_DACL_PRESENT;
3676 if (DEBUGLEVEL >= 10) {
3677 DEBUG(10,("inherit_new_acl: child acl for %s is:\n",
3678 fsp_str_dbg(fsp) ));
3679 NDR_PRINT_DEBUG(security_descriptor, psd);
3682 if (inherit_owner) {
3683 /* We need to be root to force this. */
3684 become_root();
3686 status = SMB_VFS_FSET_NT_ACL(fsp,
3687 security_info_sent,
3688 psd);
3689 if (inherit_owner) {
3690 unbecome_root();
3692 TALLOC_FREE(frame);
3693 return status;
3697 * Wrapper around open_file_ntcreate and open_directory
3700 static NTSTATUS create_file_unixpath(connection_struct *conn,
3701 struct smb_request *req,
3702 struct smb_filename *smb_fname,
3703 uint32_t access_mask,
3704 uint32_t share_access,
3705 uint32_t create_disposition,
3706 uint32_t create_options,
3707 uint32_t file_attributes,
3708 uint32_t oplock_request,
3709 uint64_t allocation_size,
3710 uint32_t private_flags,
3711 struct security_descriptor *sd,
3712 struct ea_list *ea_list,
3714 files_struct **result,
3715 int *pinfo)
3717 int info = FILE_WAS_OPENED;
3718 files_struct *base_fsp = NULL;
3719 files_struct *fsp = NULL;
3720 NTSTATUS status;
3722 DEBUG(10,("create_file_unixpath: access_mask = 0x%x "
3723 "file_attributes = 0x%x, share_access = 0x%x, "
3724 "create_disposition = 0x%x create_options = 0x%x "
3725 "oplock_request = 0x%x private_flags = 0x%x "
3726 "ea_list = 0x%p, sd = 0x%p, "
3727 "fname = %s\n",
3728 (unsigned int)access_mask,
3729 (unsigned int)file_attributes,
3730 (unsigned int)share_access,
3731 (unsigned int)create_disposition,
3732 (unsigned int)create_options,
3733 (unsigned int)oplock_request,
3734 (unsigned int)private_flags,
3735 ea_list, sd, smb_fname_str_dbg(smb_fname)));
3737 if (create_options & FILE_OPEN_BY_FILE_ID) {
3738 status = NT_STATUS_NOT_SUPPORTED;
3739 goto fail;
3742 if (create_options & NTCREATEX_OPTIONS_INVALID_PARAM_MASK) {
3743 status = NT_STATUS_INVALID_PARAMETER;
3744 goto fail;
3747 if (req == NULL) {
3748 oplock_request |= INTERNAL_OPEN_ONLY;
3751 if ((conn->fs_capabilities & FILE_NAMED_STREAMS)
3752 && (access_mask & DELETE_ACCESS)
3753 && !is_ntfs_stream_smb_fname(smb_fname)) {
3755 * We can't open a file with DELETE access if any of the
3756 * streams is open without FILE_SHARE_DELETE
3758 status = open_streams_for_delete(conn, smb_fname->base_name);
3760 if (!NT_STATUS_IS_OK(status)) {
3761 goto fail;
3765 if ((access_mask & SEC_FLAG_SYSTEM_SECURITY) &&
3766 !security_token_has_privilege(get_current_nttok(conn),
3767 SEC_PRIV_SECURITY)) {
3768 DEBUG(10, ("create_file_unixpath: open on %s "
3769 "failed - SEC_FLAG_SYSTEM_SECURITY denied.\n",
3770 smb_fname_str_dbg(smb_fname)));
3771 status = NT_STATUS_PRIVILEGE_NOT_HELD;
3772 goto fail;
3775 if ((conn->fs_capabilities & FILE_NAMED_STREAMS)
3776 && is_ntfs_stream_smb_fname(smb_fname)
3777 && (!(private_flags & NTCREATEX_OPTIONS_PRIVATE_STREAM_DELETE))) {
3778 uint32 base_create_disposition;
3779 struct smb_filename *smb_fname_base = NULL;
3781 if (create_options & FILE_DIRECTORY_FILE) {
3782 status = NT_STATUS_NOT_A_DIRECTORY;
3783 goto fail;
3786 switch (create_disposition) {
3787 case FILE_OPEN:
3788 base_create_disposition = FILE_OPEN;
3789 break;
3790 default:
3791 base_create_disposition = FILE_OPEN_IF;
3792 break;
3795 /* Create an smb_filename with stream_name == NULL. */
3796 smb_fname_base = synthetic_smb_fname(talloc_tos(),
3797 smb_fname->base_name,
3798 NULL, NULL);
3799 if (smb_fname_base == NULL) {
3800 status = NT_STATUS_NO_MEMORY;
3801 goto fail;
3804 if (SMB_VFS_STAT(conn, smb_fname_base) == -1) {
3805 DEBUG(10, ("Unable to stat stream: %s\n",
3806 smb_fname_str_dbg(smb_fname_base)));
3807 } else {
3809 * https://bugzilla.samba.org/show_bug.cgi?id=10229
3810 * We need to check if the requested access mask
3811 * could be used to open the underlying file (if
3812 * it existed), as we're passing in zero for the
3813 * access mask to the base filename.
3815 status = check_base_file_access(conn,
3816 smb_fname_base,
3817 access_mask);
3819 if (!NT_STATUS_IS_OK(status)) {
3820 DEBUG(10, ("Permission check "
3821 "for base %s failed: "
3822 "%s\n", smb_fname->base_name,
3823 nt_errstr(status)));
3824 goto fail;
3828 /* Open the base file. */
3829 status = create_file_unixpath(conn, NULL, smb_fname_base, 0,
3830 FILE_SHARE_READ
3831 | FILE_SHARE_WRITE
3832 | FILE_SHARE_DELETE,
3833 base_create_disposition,
3834 0, 0, 0, 0, 0, NULL, NULL,
3835 &base_fsp, NULL);
3836 TALLOC_FREE(smb_fname_base);
3838 if (!NT_STATUS_IS_OK(status)) {
3839 DEBUG(10, ("create_file_unixpath for base %s failed: "
3840 "%s\n", smb_fname->base_name,
3841 nt_errstr(status)));
3842 goto fail;
3844 /* we don't need to low level fd */
3845 fd_close(base_fsp);
3849 * If it's a request for a directory open, deal with it separately.
3852 if (create_options & FILE_DIRECTORY_FILE) {
3854 if (create_options & FILE_NON_DIRECTORY_FILE) {
3855 status = NT_STATUS_INVALID_PARAMETER;
3856 goto fail;
3859 /* Can't open a temp directory. IFS kit test. */
3860 if (!(file_attributes & FILE_FLAG_POSIX_SEMANTICS) &&
3861 (file_attributes & FILE_ATTRIBUTE_TEMPORARY)) {
3862 status = NT_STATUS_INVALID_PARAMETER;
3863 goto fail;
3867 * We will get a create directory here if the Win32
3868 * app specified a security descriptor in the
3869 * CreateDirectory() call.
3872 oplock_request = 0;
3873 status = open_directory(
3874 conn, req, smb_fname, access_mask, share_access,
3875 create_disposition, create_options, file_attributes,
3876 &info, &fsp);
3877 } else {
3880 * Ordinary file case.
3883 status = file_new(req, conn, &fsp);
3884 if(!NT_STATUS_IS_OK(status)) {
3885 goto fail;
3888 status = fsp_set_smb_fname(fsp, smb_fname);
3889 if (!NT_STATUS_IS_OK(status)) {
3890 goto fail;
3893 if (base_fsp) {
3895 * We're opening the stream element of a
3896 * base_fsp we already opened. Set up the
3897 * base_fsp pointer.
3899 fsp->base_fsp = base_fsp;
3902 if (allocation_size) {
3903 fsp->initial_allocation_size = smb_roundup(fsp->conn,
3904 allocation_size);
3907 status = open_file_ntcreate(conn,
3908 req,
3909 access_mask,
3910 share_access,
3911 create_disposition,
3912 create_options,
3913 file_attributes,
3914 oplock_request,
3915 private_flags,
3916 &info,
3917 fsp);
3919 if(!NT_STATUS_IS_OK(status)) {
3920 file_free(req, fsp);
3921 fsp = NULL;
3924 if (NT_STATUS_EQUAL(status, NT_STATUS_FILE_IS_A_DIRECTORY)) {
3926 /* A stream open never opens a directory */
3928 if (base_fsp) {
3929 status = NT_STATUS_FILE_IS_A_DIRECTORY;
3930 goto fail;
3934 * Fail the open if it was explicitly a non-directory
3935 * file.
3938 if (create_options & FILE_NON_DIRECTORY_FILE) {
3939 status = NT_STATUS_FILE_IS_A_DIRECTORY;
3940 goto fail;
3943 oplock_request = 0;
3944 status = open_directory(
3945 conn, req, smb_fname, access_mask,
3946 share_access, create_disposition,
3947 create_options, file_attributes,
3948 &info, &fsp);
3952 if (!NT_STATUS_IS_OK(status)) {
3953 goto fail;
3956 fsp->base_fsp = base_fsp;
3958 if ((ea_list != NULL) &&
3959 ((info == FILE_WAS_CREATED) || (info == FILE_WAS_OVERWRITTEN))) {
3960 status = set_ea(conn, fsp, fsp->fsp_name, ea_list);
3961 if (!NT_STATUS_IS_OK(status)) {
3962 goto fail;
3966 if (!fsp->is_directory && S_ISDIR(fsp->fsp_name->st.st_ex_mode)) {
3967 status = NT_STATUS_ACCESS_DENIED;
3968 goto fail;
3971 /* Save the requested allocation size. */
3972 if ((info == FILE_WAS_CREATED) || (info == FILE_WAS_OVERWRITTEN)) {
3973 if (allocation_size
3974 && (allocation_size > fsp->fsp_name->st.st_ex_size)) {
3975 fsp->initial_allocation_size = smb_roundup(
3976 fsp->conn, allocation_size);
3977 if (fsp->is_directory) {
3978 /* Can't set allocation size on a directory. */
3979 status = NT_STATUS_ACCESS_DENIED;
3980 goto fail;
3982 if (vfs_allocate_file_space(
3983 fsp, fsp->initial_allocation_size) == -1) {
3984 status = NT_STATUS_DISK_FULL;
3985 goto fail;
3987 } else {
3988 fsp->initial_allocation_size = smb_roundup(
3989 fsp->conn, (uint64_t)fsp->fsp_name->st.st_ex_size);
3991 } else {
3992 fsp->initial_allocation_size = 0;
3995 if ((info == FILE_WAS_CREATED) && lp_nt_acl_support(SNUM(conn)) &&
3996 fsp->base_fsp == NULL) {
3997 if (sd != NULL) {
3999 * According to the MS documentation, the only time the security
4000 * descriptor is applied to the opened file is iff we *created* the
4001 * file; an existing file stays the same.
4003 * Also, it seems (from observation) that you can open the file with
4004 * any access mask but you can still write the sd. We need to override
4005 * the granted access before we call set_sd
4006 * Patch for bug #2242 from Tom Lackemann <cessnatomny@yahoo.com>.
4009 uint32_t sec_info_sent;
4010 uint32_t saved_access_mask = fsp->access_mask;
4012 sec_info_sent = get_sec_info(sd);
4014 fsp->access_mask = FILE_GENERIC_ALL;
4016 if (sec_info_sent & (SECINFO_OWNER|
4017 SECINFO_GROUP|
4018 SECINFO_DACL|
4019 SECINFO_SACL)) {
4020 status = set_sd(fsp, sd, sec_info_sent);
4023 fsp->access_mask = saved_access_mask;
4025 if (!NT_STATUS_IS_OK(status)) {
4026 goto fail;
4028 } else if (lp_inherit_acls(SNUM(conn))) {
4029 /* Inherit from parent. Errors here are not fatal. */
4030 status = inherit_new_acl(fsp);
4031 if (!NT_STATUS_IS_OK(status)) {
4032 DEBUG(10,("inherit_new_acl: failed for %s with %s\n",
4033 fsp_str_dbg(fsp),
4034 nt_errstr(status) ));
4039 DEBUG(10, ("create_file_unixpath: info=%d\n", info));
4041 *result = fsp;
4042 if (pinfo != NULL) {
4043 *pinfo = info;
4046 smb_fname->st = fsp->fsp_name->st;
4048 return NT_STATUS_OK;
4050 fail:
4051 DEBUG(10, ("create_file_unixpath: %s\n", nt_errstr(status)));
4053 if (fsp != NULL) {
4054 if (base_fsp && fsp->base_fsp == base_fsp) {
4056 * The close_file below will close
4057 * fsp->base_fsp.
4059 base_fsp = NULL;
4061 close_file(req, fsp, ERROR_CLOSE);
4062 fsp = NULL;
4064 if (base_fsp != NULL) {
4065 close_file(req, base_fsp, ERROR_CLOSE);
4066 base_fsp = NULL;
4068 return status;
4072 * Calculate the full path name given a relative fid.
4074 NTSTATUS get_relative_fid_filename(connection_struct *conn,
4075 struct smb_request *req,
4076 uint16_t root_dir_fid,
4077 const struct smb_filename *smb_fname,
4078 struct smb_filename **smb_fname_out)
4080 files_struct *dir_fsp;
4081 char *parent_fname = NULL;
4082 char *new_base_name = NULL;
4083 NTSTATUS status;
4085 if (root_dir_fid == 0 || !smb_fname) {
4086 status = NT_STATUS_INTERNAL_ERROR;
4087 goto out;
4090 dir_fsp = file_fsp(req, root_dir_fid);
4092 if (dir_fsp == NULL) {
4093 status = NT_STATUS_INVALID_HANDLE;
4094 goto out;
4097 if (is_ntfs_stream_smb_fname(dir_fsp->fsp_name)) {
4098 status = NT_STATUS_INVALID_HANDLE;
4099 goto out;
4102 if (!dir_fsp->is_directory) {
4105 * Check to see if this is a mac fork of some kind.
4108 if ((conn->fs_capabilities & FILE_NAMED_STREAMS) &&
4109 is_ntfs_stream_smb_fname(smb_fname)) {
4110 status = NT_STATUS_OBJECT_PATH_NOT_FOUND;
4111 goto out;
4115 we need to handle the case when we get a
4116 relative open relative to a file and the
4117 pathname is blank - this is a reopen!
4118 (hint from demyn plantenberg)
4121 status = NT_STATUS_INVALID_HANDLE;
4122 goto out;
4125 if (ISDOT(dir_fsp->fsp_name->base_name)) {
4127 * We're at the toplevel dir, the final file name
4128 * must not contain ./, as this is filtered out
4129 * normally by srvstr_get_path and unix_convert
4130 * explicitly rejects paths containing ./.
4132 parent_fname = talloc_strdup(talloc_tos(), "");
4133 if (parent_fname == NULL) {
4134 status = NT_STATUS_NO_MEMORY;
4135 goto out;
4137 } else {
4138 size_t dir_name_len = strlen(dir_fsp->fsp_name->base_name);
4141 * Copy in the base directory name.
4144 parent_fname = talloc_array(talloc_tos(), char,
4145 dir_name_len+2);
4146 if (parent_fname == NULL) {
4147 status = NT_STATUS_NO_MEMORY;
4148 goto out;
4150 memcpy(parent_fname, dir_fsp->fsp_name->base_name,
4151 dir_name_len+1);
4154 * Ensure it ends in a '/'.
4155 * We used TALLOC_SIZE +2 to add space for the '/'.
4158 if(dir_name_len
4159 && (parent_fname[dir_name_len-1] != '\\')
4160 && (parent_fname[dir_name_len-1] != '/')) {
4161 parent_fname[dir_name_len] = '/';
4162 parent_fname[dir_name_len+1] = '\0';
4166 new_base_name = talloc_asprintf(talloc_tos(), "%s%s", parent_fname,
4167 smb_fname->base_name);
4168 if (new_base_name == NULL) {
4169 status = NT_STATUS_NO_MEMORY;
4170 goto out;
4173 status = filename_convert(req,
4174 conn,
4175 req->flags2 & FLAGS2_DFS_PATHNAMES,
4176 new_base_name,
4178 NULL,
4179 smb_fname_out);
4180 if (!NT_STATUS_IS_OK(status)) {
4181 goto out;
4184 out:
4185 TALLOC_FREE(parent_fname);
4186 TALLOC_FREE(new_base_name);
4187 return status;
4190 NTSTATUS create_file_default(connection_struct *conn,
4191 struct smb_request *req,
4192 uint16_t root_dir_fid,
4193 struct smb_filename *smb_fname,
4194 uint32_t access_mask,
4195 uint32_t share_access,
4196 uint32_t create_disposition,
4197 uint32_t create_options,
4198 uint32_t file_attributes,
4199 uint32_t oplock_request,
4200 uint64_t allocation_size,
4201 uint32_t private_flags,
4202 struct security_descriptor *sd,
4203 struct ea_list *ea_list,
4204 files_struct **result,
4205 int *pinfo)
4207 int info = FILE_WAS_OPENED;
4208 files_struct *fsp = NULL;
4209 NTSTATUS status;
4210 bool stream_name = false;
4212 DEBUG(10,("create_file: access_mask = 0x%x "
4213 "file_attributes = 0x%x, share_access = 0x%x, "
4214 "create_disposition = 0x%x create_options = 0x%x "
4215 "oplock_request = 0x%x "
4216 "private_flags = 0x%x "
4217 "root_dir_fid = 0x%x, ea_list = 0x%p, sd = 0x%p, "
4218 "fname = %s\n",
4219 (unsigned int)access_mask,
4220 (unsigned int)file_attributes,
4221 (unsigned int)share_access,
4222 (unsigned int)create_disposition,
4223 (unsigned int)create_options,
4224 (unsigned int)oplock_request,
4225 (unsigned int)private_flags,
4226 (unsigned int)root_dir_fid,
4227 ea_list, sd, smb_fname_str_dbg(smb_fname)));
4230 * Calculate the filename from the root_dir_if if necessary.
4233 if (root_dir_fid != 0) {
4234 struct smb_filename *smb_fname_out = NULL;
4235 status = get_relative_fid_filename(conn, req, root_dir_fid,
4236 smb_fname, &smb_fname_out);
4237 if (!NT_STATUS_IS_OK(status)) {
4238 goto fail;
4240 smb_fname = smb_fname_out;
4244 * Check to see if this is a mac fork of some kind.
4247 stream_name = is_ntfs_stream_smb_fname(smb_fname);
4248 if (stream_name) {
4249 enum FAKE_FILE_TYPE fake_file_type;
4251 fake_file_type = is_fake_file(smb_fname);
4253 if (fake_file_type != FAKE_FILE_TYPE_NONE) {
4256 * Here we go! support for changing the disk quotas
4257 * --metze
4259 * We need to fake up to open this MAGIC QUOTA file
4260 * and return a valid FID.
4262 * w2k close this file directly after openening xp
4263 * also tries a QUERY_FILE_INFO on the file and then
4264 * close it
4266 status = open_fake_file(req, conn, req->vuid,
4267 fake_file_type, smb_fname,
4268 access_mask, &fsp);
4269 if (!NT_STATUS_IS_OK(status)) {
4270 goto fail;
4273 ZERO_STRUCT(smb_fname->st);
4274 goto done;
4277 if (!(conn->fs_capabilities & FILE_NAMED_STREAMS)) {
4278 status = NT_STATUS_OBJECT_NAME_NOT_FOUND;
4279 goto fail;
4283 if (is_ntfs_default_stream_smb_fname(smb_fname)) {
4284 int ret;
4285 smb_fname->stream_name = NULL;
4286 /* We have to handle this error here. */
4287 if (create_options & FILE_DIRECTORY_FILE) {
4288 status = NT_STATUS_NOT_A_DIRECTORY;
4289 goto fail;
4291 if (lp_posix_pathnames()) {
4292 ret = SMB_VFS_LSTAT(conn, smb_fname);
4293 } else {
4294 ret = SMB_VFS_STAT(conn, smb_fname);
4297 if (ret == 0 && VALID_STAT_OF_DIR(smb_fname->st)) {
4298 status = NT_STATUS_FILE_IS_A_DIRECTORY;
4299 goto fail;
4303 status = create_file_unixpath(
4304 conn, req, smb_fname, access_mask, share_access,
4305 create_disposition, create_options, file_attributes,
4306 oplock_request, allocation_size, private_flags,
4307 sd, ea_list,
4308 &fsp, &info);
4310 if (!NT_STATUS_IS_OK(status)) {
4311 goto fail;
4314 done:
4315 DEBUG(10, ("create_file: info=%d\n", info));
4317 *result = fsp;
4318 if (pinfo != NULL) {
4319 *pinfo = info;
4321 return NT_STATUS_OK;
4323 fail:
4324 DEBUG(10, ("create_file: %s\n", nt_errstr(status)));
4326 if (fsp != NULL) {
4327 close_file(req, fsp, ERROR_CLOSE);
4328 fsp = NULL;
4330 return status;