s3: smbd - Prevent file truncation on an open that fails with share mode violation.
[Samba.git] / source3 / smbd / open.c
blob72b8b598310310b962b6e69bf52f8042641b0e98
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;
843 * Actually do the open - if O_TRUNC is needed handle it
844 * below under the share mode lock.
846 status = fd_open_atomic(conn, fsp, local_flags & ~O_TRUNC,
847 unx_mode, p_file_created);
848 if (!NT_STATUS_IS_OK(status)) {
849 DEBUG(3,("Error opening file %s (%s) (local_flags=%d) "
850 "(flags=%d)\n", smb_fname_str_dbg(smb_fname),
851 nt_errstr(status),local_flags,flags));
852 return status;
855 ret = SMB_VFS_FSTAT(fsp, &smb_fname->st);
856 if (ret == -1) {
857 /* If we have an fd, this stat should succeed. */
858 DEBUG(0,("Error doing fstat on open file %s "
859 "(%s)\n",
860 smb_fname_str_dbg(smb_fname),
861 strerror(errno) ));
862 status = map_nt_error_from_unix(errno);
863 fd_close(fsp);
864 return status;
867 if (*p_file_created) {
868 /* We created this file. */
870 bool need_re_stat = false;
871 /* Do all inheritance work after we've
872 done a successful fstat call and filled
873 in the stat struct in fsp->fsp_name. */
875 /* Inherit the ACL if required */
876 if (lp_inherit_perms(SNUM(conn))) {
877 inherit_access_posix_acl(conn, parent_dir,
878 smb_fname->base_name,
879 unx_mode);
880 need_re_stat = true;
883 /* Change the owner if required. */
884 if (lp_inherit_owner(SNUM(conn))) {
885 change_file_owner_to_parent(conn, parent_dir,
886 fsp);
887 need_re_stat = true;
890 if (need_re_stat) {
891 ret = SMB_VFS_FSTAT(fsp, &smb_fname->st);
892 /* If we have an fd, this stat should succeed. */
893 if (ret == -1) {
894 DEBUG(0,("Error doing fstat on open file %s "
895 "(%s)\n",
896 smb_fname_str_dbg(smb_fname),
897 strerror(errno) ));
901 notify_fname(conn, NOTIFY_ACTION_ADDED,
902 FILE_NOTIFY_CHANGE_FILE_NAME,
903 smb_fname->base_name);
905 } else {
906 fsp->fh->fd = -1; /* What we used to call a stat open. */
907 if (!file_existed) {
908 /* File must exist for a stat open. */
909 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
912 status = smbd_check_access_rights(conn,
913 smb_fname,
914 false,
915 access_mask);
917 if (NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND) &&
918 fsp->posix_open &&
919 S_ISLNK(smb_fname->st.st_ex_mode)) {
920 /* This is a POSIX stat open for delete
921 * or rename on a symlink that points
922 * nowhere. Allow. */
923 DEBUG(10,("open_file: allowing POSIX "
924 "open on bad symlink %s\n",
925 smb_fname_str_dbg(smb_fname)));
926 status = NT_STATUS_OK;
929 if (!NT_STATUS_IS_OK(status)) {
930 DEBUG(10,("open_file: "
931 "smbd_check_access_rights on file "
932 "%s returned %s\n",
933 smb_fname_str_dbg(smb_fname),
934 nt_errstr(status) ));
935 return status;
940 * POSIX allows read-only opens of directories. We don't
941 * want to do this (we use a different code path for this)
942 * so catch a directory open and return an EISDIR. JRA.
945 if(S_ISDIR(smb_fname->st.st_ex_mode)) {
946 fd_close(fsp);
947 errno = EISDIR;
948 return NT_STATUS_FILE_IS_A_DIRECTORY;
951 fsp->file_id = vfs_file_id_from_sbuf(conn, &smb_fname->st);
952 fsp->vuid = req ? req->vuid : UID_FIELD_INVALID;
953 fsp->file_pid = req ? req->smbpid : 0;
954 fsp->can_lock = True;
955 fsp->can_read = ((access_mask & FILE_READ_DATA) != 0);
956 fsp->can_write =
957 CAN_WRITE(conn) &&
958 ((access_mask & (FILE_WRITE_DATA | FILE_APPEND_DATA)) != 0);
959 fsp->print_file = NULL;
960 fsp->modified = False;
961 fsp->sent_oplock_break = NO_BREAK_SENT;
962 fsp->is_directory = False;
963 if (conn->aio_write_behind_list &&
964 is_in_path(smb_fname->base_name, conn->aio_write_behind_list,
965 conn->case_sensitive)) {
966 fsp->aio_write_behind = True;
969 fsp->wcp = NULL; /* Write cache pointer. */
971 DEBUG(2,("%s opened file %s read=%s write=%s (numopen=%d)\n",
972 conn->session_info->unix_info->unix_name,
973 smb_fname_str_dbg(smb_fname),
974 BOOLSTR(fsp->can_read), BOOLSTR(fsp->can_write),
975 conn->num_files_open));
977 errno = 0;
978 return NT_STATUS_OK;
981 /****************************************************************************
982 Check if we can open a file with a share mode.
983 Returns True if conflict, False if not.
984 ****************************************************************************/
986 static bool share_conflict(struct share_mode_entry *entry,
987 uint32 access_mask,
988 uint32 share_access)
990 DEBUG(10,("share_conflict: entry->access_mask = 0x%x, "
991 "entry->share_access = 0x%x, "
992 "entry->private_options = 0x%x\n",
993 (unsigned int)entry->access_mask,
994 (unsigned int)entry->share_access,
995 (unsigned int)entry->private_options));
997 if (server_id_is_disconnected(&entry->pid)) {
999 * note: cleanup should have been done by
1000 * delay_for_batch_oplocks()
1002 return false;
1005 DEBUG(10,("share_conflict: access_mask = 0x%x, share_access = 0x%x\n",
1006 (unsigned int)access_mask, (unsigned int)share_access));
1008 if ((entry->access_mask & (FILE_WRITE_DATA|
1009 FILE_APPEND_DATA|
1010 FILE_READ_DATA|
1011 FILE_EXECUTE|
1012 DELETE_ACCESS)) == 0) {
1013 DEBUG(10,("share_conflict: No conflict due to "
1014 "entry->access_mask = 0x%x\n",
1015 (unsigned int)entry->access_mask ));
1016 return False;
1019 if ((access_mask & (FILE_WRITE_DATA|
1020 FILE_APPEND_DATA|
1021 FILE_READ_DATA|
1022 FILE_EXECUTE|
1023 DELETE_ACCESS)) == 0) {
1024 DEBUG(10,("share_conflict: No conflict due to "
1025 "access_mask = 0x%x\n",
1026 (unsigned int)access_mask ));
1027 return False;
1030 #if 1 /* JRA TEST - Superdebug. */
1031 #define CHECK_MASK(num, am, right, sa, share) \
1032 DEBUG(10,("share_conflict: [%d] am (0x%x) & right (0x%x) = 0x%x\n", \
1033 (unsigned int)(num), (unsigned int)(am), \
1034 (unsigned int)(right), (unsigned int)(am)&(right) )); \
1035 DEBUG(10,("share_conflict: [%d] sa (0x%x) & share (0x%x) = 0x%x\n", \
1036 (unsigned int)(num), (unsigned int)(sa), \
1037 (unsigned int)(share), (unsigned int)(sa)&(share) )); \
1038 if (((am) & (right)) && !((sa) & (share))) { \
1039 DEBUG(10,("share_conflict: check %d conflict am = 0x%x, right = 0x%x, \
1040 sa = 0x%x, share = 0x%x\n", (num), (unsigned int)(am), (unsigned int)(right), (unsigned int)(sa), \
1041 (unsigned int)(share) )); \
1042 return True; \
1044 #else
1045 #define CHECK_MASK(num, am, right, sa, share) \
1046 if (((am) & (right)) && !((sa) & (share))) { \
1047 DEBUG(10,("share_conflict: check %d conflict am = 0x%x, right = 0x%x, \
1048 sa = 0x%x, share = 0x%x\n", (num), (unsigned int)(am), (unsigned int)(right), (unsigned int)(sa), \
1049 (unsigned int)(share) )); \
1050 return True; \
1052 #endif
1054 CHECK_MASK(1, entry->access_mask, FILE_WRITE_DATA | FILE_APPEND_DATA,
1055 share_access, FILE_SHARE_WRITE);
1056 CHECK_MASK(2, access_mask, FILE_WRITE_DATA | FILE_APPEND_DATA,
1057 entry->share_access, FILE_SHARE_WRITE);
1059 CHECK_MASK(3, entry->access_mask, FILE_READ_DATA | FILE_EXECUTE,
1060 share_access, FILE_SHARE_READ);
1061 CHECK_MASK(4, access_mask, FILE_READ_DATA | FILE_EXECUTE,
1062 entry->share_access, FILE_SHARE_READ);
1064 CHECK_MASK(5, entry->access_mask, DELETE_ACCESS,
1065 share_access, FILE_SHARE_DELETE);
1066 CHECK_MASK(6, access_mask, DELETE_ACCESS,
1067 entry->share_access, FILE_SHARE_DELETE);
1069 DEBUG(10,("share_conflict: No conflict.\n"));
1070 return False;
1073 #if defined(DEVELOPER)
1074 static void validate_my_share_entries(struct smbd_server_connection *sconn,
1075 int num,
1076 struct share_mode_entry *share_entry)
1078 struct server_id self = messaging_server_id(sconn->msg_ctx);
1079 files_struct *fsp;
1081 if (!serverid_equal(&self, &share_entry->pid)) {
1082 return;
1085 if (share_entry->share_file_id == 0) {
1086 /* INTERNAL_OPEN_ONLY */
1087 return;
1090 if (!is_valid_share_mode_entry(share_entry)) {
1091 return;
1094 fsp = file_find_dif(sconn, share_entry->id,
1095 share_entry->share_file_id);
1096 if (!fsp) {
1097 DEBUG(0,("validate_my_share_entries: PANIC : %s\n",
1098 share_mode_str(talloc_tos(), num, share_entry) ));
1099 smb_panic("validate_my_share_entries: Cannot match a "
1100 "share entry with an open file\n");
1103 if ((share_entry->op_type == NO_OPLOCK) &&
1104 (fsp->oplock_type == FAKE_LEVEL_II_OPLOCK))
1106 /* Someone has already written to it, but I haven't yet
1107 * noticed */
1108 return;
1111 if (((uint16)fsp->oplock_type) != share_entry->op_type) {
1112 goto panic;
1115 return;
1117 panic:
1119 char *str;
1120 DEBUG(0,("validate_my_share_entries: PANIC : %s\n",
1121 share_mode_str(talloc_tos(), num, share_entry) ));
1122 str = talloc_asprintf(talloc_tos(),
1123 "validate_my_share_entries: "
1124 "file %s, oplock_type = 0x%x, op_type = 0x%x\n",
1125 fsp->fsp_name->base_name,
1126 (unsigned int)fsp->oplock_type,
1127 (unsigned int)share_entry->op_type );
1128 smb_panic(str);
1131 #endif
1133 bool is_stat_open(uint32 access_mask)
1135 const uint32_t stat_open_bits =
1136 (SYNCHRONIZE_ACCESS|
1137 FILE_READ_ATTRIBUTES|
1138 FILE_WRITE_ATTRIBUTES);
1140 return (((access_mask & stat_open_bits) != 0) &&
1141 ((access_mask & ~stat_open_bits) == 0));
1144 /****************************************************************************
1145 Deal with share modes
1146 Invarient: Share mode must be locked on entry and exit.
1147 Returns -1 on error, or number of share modes on success (may be zero).
1148 ****************************************************************************/
1150 static NTSTATUS open_mode_check(connection_struct *conn,
1151 struct share_mode_lock *lck,
1152 uint32_t name_hash,
1153 uint32 access_mask,
1154 uint32 share_access,
1155 uint32 create_options,
1156 bool *file_existed)
1158 int i;
1160 if(lck->data->num_share_modes == 0) {
1161 return NT_STATUS_OK;
1164 /* A delete on close prohibits everything */
1166 if (is_delete_on_close_set(lck, name_hash)) {
1168 * Check the delete on close token
1169 * is valid. It could have been left
1170 * after a server crash.
1172 for(i = 0; i < lck->data->num_share_modes; i++) {
1173 if (!share_mode_stale_pid(lck->data, i)) {
1175 *file_existed = true;
1177 return NT_STATUS_DELETE_PENDING;
1180 return NT_STATUS_OK;
1183 if (is_stat_open(access_mask)) {
1184 /* Stat open that doesn't trigger oplock breaks or share mode
1185 * checks... ! JRA. */
1186 return NT_STATUS_OK;
1190 * Check if the share modes will give us access.
1193 #if defined(DEVELOPER)
1194 for(i = 0; i < lck->data->num_share_modes; i++) {
1195 validate_my_share_entries(conn->sconn, i,
1196 &lck->data->share_modes[i]);
1198 #endif
1200 /* Now we check the share modes, after any oplock breaks. */
1201 for(i = 0; i < lck->data->num_share_modes; i++) {
1203 if (!is_valid_share_mode_entry(&lck->data->share_modes[i])) {
1204 continue;
1207 /* someone else has a share lock on it, check to see if we can
1208 * too */
1209 if (share_conflict(&lck->data->share_modes[i],
1210 access_mask, share_access)) {
1212 if (share_mode_stale_pid(lck->data, i)) {
1213 continue;
1216 *file_existed = true;
1218 return NT_STATUS_SHARING_VIOLATION;
1222 if (lck->data->num_share_modes != 0) {
1223 *file_existed = true;
1226 return NT_STATUS_OK;
1230 * Send a break message to the oplock holder and delay the open for
1231 * our client.
1234 static NTSTATUS send_break_message(files_struct *fsp,
1235 struct share_mode_entry *exclusive,
1236 uint64_t mid,
1237 int oplock_request)
1239 NTSTATUS status;
1240 char msg[MSG_SMB_SHARE_MODE_ENTRY_SIZE];
1242 DEBUG(10, ("Sending break request to PID %s\n",
1243 procid_str_static(&exclusive->pid)));
1244 exclusive->op_mid = mid;
1246 /* Create the message. */
1247 share_mode_entry_to_message(msg, exclusive);
1249 /* Add in the FORCE_OPLOCK_BREAK_TO_NONE bit in the message if set. We
1250 don't want this set in the share mode struct pointed to by lck. */
1252 if (oplock_request & FORCE_OPLOCK_BREAK_TO_NONE) {
1253 SSVAL(msg,OP_BREAK_MSG_OP_TYPE_OFFSET,
1254 exclusive->op_type | FORCE_OPLOCK_BREAK_TO_NONE);
1257 status = messaging_send_buf(fsp->conn->sconn->msg_ctx, exclusive->pid,
1258 MSG_SMB_BREAK_REQUEST,
1259 (uint8 *)msg,
1260 MSG_SMB_SHARE_MODE_ENTRY_SIZE);
1261 if (!NT_STATUS_IS_OK(status)) {
1262 DEBUG(3, ("Could not send oplock break message: %s\n",
1263 nt_errstr(status)));
1266 return status;
1270 * Return share_mode_entry pointers for :
1271 * 1). Batch oplock entry.
1272 * 2). Batch or exclusive oplock entry (may be identical to #1).
1273 * bool have_level2_oplock
1274 * bool have_no_oplock.
1275 * Do internal consistency checks on the share mode for a file.
1278 static void find_oplock_types(files_struct *fsp,
1279 int oplock_request,
1280 const struct share_mode_lock *lck,
1281 struct share_mode_entry **pp_batch,
1282 struct share_mode_entry **pp_ex_or_batch,
1283 bool *got_level2,
1284 bool *got_no_oplock)
1286 int i;
1288 *pp_batch = NULL;
1289 *pp_ex_or_batch = NULL;
1290 *got_level2 = false;
1291 *got_no_oplock = false;
1293 /* Ignore stat or internal opens, as is done in
1294 delay_for_batch_oplocks() and
1295 delay_for_exclusive_oplocks().
1297 if ((oplock_request & INTERNAL_OPEN_ONLY) || is_stat_open(fsp->access_mask)) {
1298 return;
1301 for (i=0; i<lck->data->num_share_modes; i++) {
1302 struct share_mode_entry *e = &lck->data->share_modes[i];
1304 if (!is_valid_share_mode_entry(e)) {
1305 continue;
1308 if (e->op_type == NO_OPLOCK && is_stat_open(e->access_mask)) {
1309 /* We ignore stat opens in the table - they
1310 always have NO_OPLOCK and never get or
1311 cause breaks. JRA. */
1312 continue;
1315 if (BATCH_OPLOCK_TYPE(e->op_type)) {
1316 /* batch - can only be one. */
1317 if (share_mode_stale_pid(lck->data, i)) {
1318 DEBUG(10, ("Found stale batch oplock\n"));
1319 continue;
1321 if (*pp_ex_or_batch || *pp_batch || *got_level2 || *got_no_oplock) {
1322 smb_panic("Bad batch oplock entry.");
1324 *pp_batch = e;
1327 if (EXCLUSIVE_OPLOCK_TYPE(e->op_type)) {
1328 if (share_mode_stale_pid(lck->data, i)) {
1329 DEBUG(10, ("Found stale duplicate oplock\n"));
1330 continue;
1332 /* Exclusive or batch - can only be one. */
1333 if (*pp_ex_or_batch || *got_level2 || *got_no_oplock) {
1334 smb_panic("Bad exclusive or batch oplock entry.");
1336 *pp_ex_or_batch = e;
1339 if (LEVEL_II_OPLOCK_TYPE(e->op_type)) {
1340 if (*pp_batch || *pp_ex_or_batch) {
1341 if (share_mode_stale_pid(lck->data, i)) {
1342 DEBUG(10, ("Found stale LevelII "
1343 "oplock\n"));
1344 continue;
1346 smb_panic("Bad levelII oplock entry.");
1348 *got_level2 = true;
1351 if (e->op_type == NO_OPLOCK) {
1352 if (*pp_batch || *pp_ex_or_batch) {
1353 if (share_mode_stale_pid(lck->data, i)) {
1354 DEBUG(10, ("Found stale NO_OPLOCK "
1355 "entry\n"));
1356 continue;
1358 smb_panic("Bad no oplock entry.");
1360 *got_no_oplock = true;
1365 static bool delay_for_batch_oplocks(files_struct *fsp,
1366 uint64_t mid,
1367 int oplock_request,
1368 struct share_mode_entry *batch_entry)
1370 if ((oplock_request & INTERNAL_OPEN_ONLY) || is_stat_open(fsp->access_mask)) {
1371 return false;
1373 if (batch_entry == NULL) {
1374 return false;
1377 if (server_id_is_disconnected(&batch_entry->pid)) {
1379 * TODO: clean up.
1380 * This could be achieved by sending a break message
1381 * to ourselves. Special considerations for files
1382 * with delete_on_close flag set!
1384 * For now we keep it simple and do not
1385 * allow delete on close for durable handles.
1387 return false;
1390 /* Found a batch oplock */
1391 send_break_message(fsp, batch_entry, mid, oplock_request);
1392 return true;
1395 static bool delay_for_exclusive_oplocks(files_struct *fsp,
1396 uint64_t mid,
1397 int oplock_request,
1398 struct share_mode_entry *ex_entry)
1400 if ((oplock_request & INTERNAL_OPEN_ONLY) || is_stat_open(fsp->access_mask)) {
1401 return false;
1403 if (ex_entry == NULL) {
1404 return false;
1407 if (server_id_is_disconnected(&ex_entry->pid)) {
1409 * since only durable handles can get disconnected,
1410 * and we can only get durable handles with batch oplocks,
1411 * this should actually never be reached...
1413 return false;
1416 send_break_message(fsp, ex_entry, mid, oplock_request);
1417 return true;
1420 static bool file_has_brlocks(files_struct *fsp)
1422 struct byte_range_lock *br_lck;
1424 br_lck = brl_get_locks_readonly(fsp);
1425 if (!br_lck)
1426 return false;
1428 return br_lck->num_locks > 0 ? true : false;
1431 static void grant_fsp_oplock_type(files_struct *fsp,
1432 int oplock_request,
1433 bool got_level2_oplock,
1434 bool got_a_none_oplock)
1436 bool allow_level2 = (global_client_caps & CAP_LEVEL_II_OPLOCKS) &&
1437 lp_level2_oplocks(SNUM(fsp->conn));
1439 /* Start by granting what the client asked for,
1440 but ensure no SAMBA_PRIVATE bits can be set. */
1441 fsp->oplock_type = (oplock_request & ~SAMBA_PRIVATE_OPLOCK_MASK);
1443 if (oplock_request & INTERNAL_OPEN_ONLY) {
1444 /* No oplocks on internal open. */
1445 fsp->oplock_type = NO_OPLOCK;
1446 DEBUG(10,("grant_fsp_oplock_type: oplock type 0x%x on file %s\n",
1447 fsp->oplock_type, fsp_str_dbg(fsp)));
1448 return;
1451 if (lp_locking(fsp->conn->params) && file_has_brlocks(fsp)) {
1452 DEBUG(10,("grant_fsp_oplock_type: file %s has byte range locks\n",
1453 fsp_str_dbg(fsp)));
1454 fsp->oplock_type = NO_OPLOCK;
1457 if (is_stat_open(fsp->access_mask)) {
1458 /* Leave the value already set. */
1459 DEBUG(10,("grant_fsp_oplock_type: oplock type 0x%x on file %s\n",
1460 fsp->oplock_type, fsp_str_dbg(fsp)));
1461 return;
1465 * Match what was requested (fsp->oplock_type) with
1466 * what was found in the existing share modes.
1469 if (got_a_none_oplock) {
1470 fsp->oplock_type = NO_OPLOCK;
1471 } else if (got_level2_oplock) {
1472 if (fsp->oplock_type == NO_OPLOCK ||
1473 fsp->oplock_type == FAKE_LEVEL_II_OPLOCK) {
1474 /* Store a level2 oplock, but don't tell the client */
1475 fsp->oplock_type = FAKE_LEVEL_II_OPLOCK;
1476 } else {
1477 fsp->oplock_type = LEVEL_II_OPLOCK;
1479 } else {
1480 /* All share_mode_entries are placeholders or deferred.
1481 * Silently upgrade to fake levelII if the client didn't
1482 * ask for an oplock. */
1483 if (fsp->oplock_type == NO_OPLOCK) {
1484 /* Store a level2 oplock, but don't tell the client */
1485 fsp->oplock_type = FAKE_LEVEL_II_OPLOCK;
1490 * Don't grant level2 to clients that don't want them
1491 * or if we've turned them off.
1493 if (fsp->oplock_type == LEVEL_II_OPLOCK && !allow_level2) {
1494 fsp->oplock_type = FAKE_LEVEL_II_OPLOCK;
1497 DEBUG(10,("grant_fsp_oplock_type: oplock type 0x%x on file %s\n",
1498 fsp->oplock_type, fsp_str_dbg(fsp)));
1501 static bool request_timed_out(struct timeval request_time,
1502 struct timeval timeout)
1504 struct timeval now, end_time;
1505 GetTimeOfDay(&now);
1506 end_time = timeval_sum(&request_time, &timeout);
1507 return (timeval_compare(&end_time, &now) < 0);
1510 struct defer_open_state {
1511 struct smbd_server_connection *sconn;
1512 uint64_t mid;
1515 static void defer_open_done(struct tevent_req *req);
1517 /****************************************************************************
1518 Handle the 1 second delay in returning a SHARING_VIOLATION error.
1519 ****************************************************************************/
1521 static void defer_open(struct share_mode_lock *lck,
1522 struct timeval request_time,
1523 struct timeval timeout,
1524 struct smb_request *req,
1525 struct deferred_open_record *state)
1527 DEBUG(10,("defer_open_sharing_error: time [%u.%06u] adding deferred "
1528 "open entry for mid %llu\n",
1529 (unsigned int)request_time.tv_sec,
1530 (unsigned int)request_time.tv_usec,
1531 (unsigned long long)req->mid));
1533 if (!push_deferred_open_message_smb(req, request_time, timeout,
1534 state->id, (char *)state, sizeof(*state))) {
1535 TALLOC_FREE(lck);
1536 exit_server("push_deferred_open_message_smb failed");
1538 if (lck) {
1539 struct defer_open_state *watch_state;
1540 struct tevent_req *watch_req;
1541 bool ret;
1543 watch_state = talloc(req->sconn, struct defer_open_state);
1544 if (watch_state == NULL) {
1545 exit_server("talloc failed");
1547 watch_state->sconn = req->sconn;
1548 watch_state->mid = req->mid;
1550 DEBUG(10, ("defering mid %llu\n",
1551 (unsigned long long)req->mid));
1553 watch_req = dbwrap_record_watch_send(
1554 watch_state, req->sconn->ev_ctx, lck->data->record,
1555 req->sconn->msg_ctx);
1556 if (watch_req == NULL) {
1557 exit_server("Could not watch share mode record");
1559 tevent_req_set_callback(watch_req, defer_open_done,
1560 watch_state);
1562 ret = tevent_req_set_endtime(
1563 watch_req, req->sconn->ev_ctx,
1564 timeval_sum(&request_time, &timeout));
1565 SMB_ASSERT(ret);
1569 static void defer_open_done(struct tevent_req *req)
1571 struct defer_open_state *state = tevent_req_callback_data(
1572 req, struct defer_open_state);
1573 NTSTATUS status;
1574 bool ret;
1576 status = dbwrap_record_watch_recv(req, talloc_tos(), NULL);
1577 TALLOC_FREE(req);
1578 if (!NT_STATUS_IS_OK(status)) {
1579 DEBUG(5, ("dbwrap_record_watch_recv returned %s\n",
1580 nt_errstr(status)));
1582 * Even if it failed, retry anyway. TODO: We need a way to
1583 * tell a re-scheduled open about that error.
1587 DEBUG(10, ("scheduling mid %llu\n", (unsigned long long)state->mid));
1589 ret = schedule_deferred_open_message_smb(state->sconn, state->mid);
1590 SMB_ASSERT(ret);
1591 TALLOC_FREE(state);
1595 /****************************************************************************
1596 On overwrite open ensure that the attributes match.
1597 ****************************************************************************/
1599 static bool open_match_attributes(connection_struct *conn,
1600 uint32 old_dos_attr,
1601 uint32 new_dos_attr,
1602 mode_t existing_unx_mode,
1603 mode_t new_unx_mode,
1604 mode_t *returned_unx_mode)
1606 uint32 noarch_old_dos_attr, noarch_new_dos_attr;
1608 noarch_old_dos_attr = (old_dos_attr & ~FILE_ATTRIBUTE_ARCHIVE);
1609 noarch_new_dos_attr = (new_dos_attr & ~FILE_ATTRIBUTE_ARCHIVE);
1611 if((noarch_old_dos_attr == 0 && noarch_new_dos_attr != 0) ||
1612 (noarch_old_dos_attr != 0 && ((noarch_old_dos_attr & noarch_new_dos_attr) == noarch_old_dos_attr))) {
1613 *returned_unx_mode = new_unx_mode;
1614 } else {
1615 *returned_unx_mode = (mode_t)0;
1618 DEBUG(10,("open_match_attributes: old_dos_attr = 0x%x, "
1619 "existing_unx_mode = 0%o, new_dos_attr = 0x%x "
1620 "returned_unx_mode = 0%o\n",
1621 (unsigned int)old_dos_attr,
1622 (unsigned int)existing_unx_mode,
1623 (unsigned int)new_dos_attr,
1624 (unsigned int)*returned_unx_mode ));
1626 /* If we're mapping SYSTEM and HIDDEN ensure they match. */
1627 if (lp_map_system(SNUM(conn)) || lp_store_dos_attributes(SNUM(conn))) {
1628 if ((old_dos_attr & FILE_ATTRIBUTE_SYSTEM) &&
1629 !(new_dos_attr & FILE_ATTRIBUTE_SYSTEM)) {
1630 return False;
1633 if (lp_map_hidden(SNUM(conn)) || lp_store_dos_attributes(SNUM(conn))) {
1634 if ((old_dos_attr & FILE_ATTRIBUTE_HIDDEN) &&
1635 !(new_dos_attr & FILE_ATTRIBUTE_HIDDEN)) {
1636 return False;
1639 return True;
1642 /****************************************************************************
1643 Special FCB or DOS processing in the case of a sharing violation.
1644 Try and find a duplicated file handle.
1645 ****************************************************************************/
1647 static NTSTATUS fcb_or_dos_open(struct smb_request *req,
1648 connection_struct *conn,
1649 files_struct *fsp_to_dup_into,
1650 const struct smb_filename *smb_fname,
1651 struct file_id id,
1652 uint16 file_pid,
1653 uint64_t vuid,
1654 uint32 access_mask,
1655 uint32 share_access,
1656 uint32 create_options)
1658 files_struct *fsp;
1660 DEBUG(5,("fcb_or_dos_open: attempting old open semantics for "
1661 "file %s.\n", smb_fname_str_dbg(smb_fname)));
1663 for(fsp = file_find_di_first(conn->sconn, id); fsp;
1664 fsp = file_find_di_next(fsp)) {
1666 DEBUG(10,("fcb_or_dos_open: checking file %s, fd = %d, "
1667 "vuid = %llu, file_pid = %u, private_options = 0x%x "
1668 "access_mask = 0x%x\n", fsp_str_dbg(fsp),
1669 fsp->fh->fd, (unsigned long long)fsp->vuid,
1670 (unsigned int)fsp->file_pid,
1671 (unsigned int)fsp->fh->private_options,
1672 (unsigned int)fsp->access_mask ));
1674 if (fsp != fsp_to_dup_into &&
1675 fsp->fh->fd != -1 &&
1676 fsp->vuid == vuid &&
1677 fsp->file_pid == file_pid &&
1678 (fsp->fh->private_options & (NTCREATEX_OPTIONS_PRIVATE_DENY_DOS |
1679 NTCREATEX_OPTIONS_PRIVATE_DENY_FCB)) &&
1680 (fsp->access_mask & FILE_WRITE_DATA) &&
1681 strequal(fsp->fsp_name->base_name, smb_fname->base_name) &&
1682 strequal(fsp->fsp_name->stream_name,
1683 smb_fname->stream_name)) {
1684 DEBUG(10,("fcb_or_dos_open: file match\n"));
1685 break;
1689 if (!fsp) {
1690 return NT_STATUS_NOT_FOUND;
1693 /* quite an insane set of semantics ... */
1694 if (is_executable(smb_fname->base_name) &&
1695 (fsp->fh->private_options & NTCREATEX_OPTIONS_PRIVATE_DENY_DOS)) {
1696 DEBUG(10,("fcb_or_dos_open: file fail due to is_executable.\n"));
1697 return NT_STATUS_INVALID_PARAMETER;
1700 /* We need to duplicate this fsp. */
1701 return dup_file_fsp(req, fsp, access_mask, share_access,
1702 create_options, fsp_to_dup_into);
1705 static void schedule_defer_open(struct share_mode_lock *lck,
1706 struct timeval request_time,
1707 struct smb_request *req)
1709 struct deferred_open_record state;
1711 /* This is a relative time, added to the absolute
1712 request_time value to get the absolute timeout time.
1713 Note that if this is the second or greater time we enter
1714 this codepath for this particular request mid then
1715 request_time is left as the absolute time of the *first*
1716 time this request mid was processed. This is what allows
1717 the request to eventually time out. */
1719 struct timeval timeout;
1721 /* Normally the smbd we asked should respond within
1722 * OPLOCK_BREAK_TIMEOUT seconds regardless of whether
1723 * the client did, give twice the timeout as a safety
1724 * measure here in case the other smbd is stuck
1725 * somewhere else. */
1727 timeout = timeval_set(OPLOCK_BREAK_TIMEOUT*2, 0);
1729 /* Nothing actually uses state.delayed_for_oplocks
1730 but it's handy to differentiate in debug messages
1731 between a 30 second delay due to oplock break, and
1732 a 1 second delay for share mode conflicts. */
1734 state.delayed_for_oplocks = True;
1735 state.async_open = false;
1736 state.id = lck->data->id;
1738 if (!request_timed_out(request_time, timeout)) {
1739 defer_open(lck, request_time, timeout, req, &state);
1743 /****************************************************************************
1744 Reschedule an open call that went asynchronous.
1745 ****************************************************************************/
1747 static void schedule_async_open(struct timeval request_time,
1748 struct smb_request *req)
1750 struct deferred_open_record state;
1751 struct timeval timeout;
1753 timeout = timeval_set(20, 0);
1755 ZERO_STRUCT(state);
1756 state.delayed_for_oplocks = false;
1757 state.async_open = true;
1759 if (!request_timed_out(request_time, timeout)) {
1760 defer_open(NULL, request_time, timeout, req, &state);
1764 /****************************************************************************
1765 Work out what access_mask to use from what the client sent us.
1766 ****************************************************************************/
1768 static NTSTATUS smbd_calculate_maximum_allowed_access(
1769 connection_struct *conn,
1770 const struct smb_filename *smb_fname,
1771 bool use_privs,
1772 uint32_t *p_access_mask)
1774 struct security_descriptor *sd;
1775 uint32_t access_granted;
1776 NTSTATUS status;
1778 if (!use_privs && (get_current_uid(conn) == (uid_t)0)) {
1779 *p_access_mask |= FILE_GENERIC_ALL;
1780 return NT_STATUS_OK;
1783 status = SMB_VFS_GET_NT_ACL(conn, smb_fname->base_name,
1784 (SECINFO_OWNER |
1785 SECINFO_GROUP |
1786 SECINFO_DACL),
1787 talloc_tos(), &sd);
1789 if (NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
1791 * File did not exist
1793 *p_access_mask = FILE_GENERIC_ALL;
1794 return NT_STATUS_OK;
1796 if (!NT_STATUS_IS_OK(status)) {
1797 DEBUG(10,("Could not get acl on file %s: %s\n",
1798 smb_fname_str_dbg(smb_fname),
1799 nt_errstr(status)));
1800 return NT_STATUS_ACCESS_DENIED;
1804 * If we can access the path to this file, by
1805 * default we have FILE_READ_ATTRIBUTES from the
1806 * containing directory. See the section:
1807 * "Algorithm to Check Access to an Existing File"
1808 * in MS-FSA.pdf.
1810 * se_file_access_check()
1811 * also takes care of owner WRITE_DAC and READ_CONTROL.
1813 status = se_file_access_check(sd,
1814 get_current_nttok(conn),
1815 use_privs,
1816 (*p_access_mask & ~FILE_READ_ATTRIBUTES),
1817 &access_granted);
1819 TALLOC_FREE(sd);
1821 if (!NT_STATUS_IS_OK(status)) {
1822 DEBUG(10, ("Access denied on file %s: "
1823 "when calculating maximum access\n",
1824 smb_fname_str_dbg(smb_fname)));
1825 return NT_STATUS_ACCESS_DENIED;
1827 *p_access_mask = (access_granted | FILE_READ_ATTRIBUTES);
1829 if (!(access_granted & DELETE_ACCESS)) {
1830 if (can_delete_file_in_directory(conn, smb_fname)) {
1831 *p_access_mask |= DELETE_ACCESS;
1835 return NT_STATUS_OK;
1838 NTSTATUS smbd_calculate_access_mask(connection_struct *conn,
1839 const struct smb_filename *smb_fname,
1840 bool use_privs,
1841 uint32_t access_mask,
1842 uint32_t *access_mask_out)
1844 NTSTATUS status;
1845 uint32_t orig_access_mask = access_mask;
1846 uint32_t rejected_share_access;
1849 * Convert GENERIC bits to specific bits.
1852 se_map_generic(&access_mask, &file_generic_mapping);
1854 /* Calculate MAXIMUM_ALLOWED_ACCESS if requested. */
1855 if (access_mask & MAXIMUM_ALLOWED_ACCESS) {
1857 status = smbd_calculate_maximum_allowed_access(
1858 conn, smb_fname, use_privs, &access_mask);
1860 if (!NT_STATUS_IS_OK(status)) {
1861 return status;
1864 access_mask &= conn->share_access;
1867 rejected_share_access = access_mask & ~(conn->share_access);
1869 if (rejected_share_access) {
1870 DEBUG(10, ("smbd_calculate_access_mask: Access denied on "
1871 "file %s: rejected by share access mask[0x%08X] "
1872 "orig[0x%08X] mapped[0x%08X] reject[0x%08X]\n",
1873 smb_fname_str_dbg(smb_fname),
1874 conn->share_access,
1875 orig_access_mask, access_mask,
1876 rejected_share_access));
1877 return NT_STATUS_ACCESS_DENIED;
1880 *access_mask_out = access_mask;
1881 return NT_STATUS_OK;
1884 /****************************************************************************
1885 Remove the deferred open entry under lock.
1886 ****************************************************************************/
1888 /****************************************************************************
1889 Return true if this is a state pointer to an asynchronous create.
1890 ****************************************************************************/
1892 bool is_deferred_open_async(const void *ptr)
1894 const struct deferred_open_record *state = (const struct deferred_open_record *)ptr;
1896 return state->async_open;
1899 static bool clear_ads(uint32_t create_disposition)
1901 bool ret = false;
1903 switch (create_disposition) {
1904 case FILE_SUPERSEDE:
1905 case FILE_OVERWRITE_IF:
1906 case FILE_OVERWRITE:
1907 ret = true;
1908 break;
1909 default:
1910 break;
1912 return ret;
1915 static int disposition_to_open_flags(uint32_t create_disposition)
1917 int ret = 0;
1920 * Currently we're using FILE_SUPERSEDE as the same as
1921 * FILE_OVERWRITE_IF but they really are
1922 * different. FILE_SUPERSEDE deletes an existing file
1923 * (requiring delete access) then recreates it.
1926 switch (create_disposition) {
1927 case FILE_SUPERSEDE:
1928 case FILE_OVERWRITE_IF:
1930 * If file exists replace/overwrite. If file doesn't
1931 * exist create.
1933 ret = O_CREAT|O_TRUNC;
1934 break;
1936 case FILE_OPEN:
1938 * If file exists open. If file doesn't exist error.
1940 ret = 0;
1941 break;
1943 case FILE_OVERWRITE:
1945 * If file exists overwrite. If file doesn't exist
1946 * error.
1948 ret = O_TRUNC;
1949 break;
1951 case FILE_CREATE:
1953 * If file exists error. If file doesn't exist create.
1955 ret = O_CREAT|O_EXCL;
1956 break;
1958 case FILE_OPEN_IF:
1960 * If file exists open. If file doesn't exist create.
1962 ret = O_CREAT;
1963 break;
1965 return ret;
1968 static int calculate_open_access_flags(uint32_t access_mask,
1969 int oplock_request,
1970 uint32_t private_flags)
1972 bool need_write, need_read;
1975 * Note that we ignore the append flag as append does not
1976 * mean the same thing under DOS and Unix.
1979 need_write =
1980 ((access_mask & (FILE_WRITE_DATA | FILE_APPEND_DATA)) ||
1981 (oplock_request & FORCE_OPLOCK_BREAK_TO_NONE));
1983 if (!need_write) {
1984 return O_RDONLY;
1987 /* DENY_DOS opens are always underlying read-write on the
1988 file handle, no matter what the requested access mask
1989 says. */
1991 need_read =
1992 ((private_flags & NTCREATEX_OPTIONS_PRIVATE_DENY_DOS) ||
1993 access_mask & (FILE_READ_ATTRIBUTES|FILE_READ_DATA|
1994 FILE_READ_EA|FILE_EXECUTE));
1996 if (!need_read) {
1997 return O_WRONLY;
1999 return O_RDWR;
2002 /****************************************************************************
2003 Open a file with a share mode. Passed in an already created files_struct *.
2004 ****************************************************************************/
2006 static NTSTATUS open_file_ntcreate(connection_struct *conn,
2007 struct smb_request *req,
2008 uint32 access_mask, /* access bits (FILE_READ_DATA etc.) */
2009 uint32 share_access, /* share constants (FILE_SHARE_READ etc) */
2010 uint32 create_disposition, /* FILE_OPEN_IF etc. */
2011 uint32 create_options, /* options such as delete on close. */
2012 uint32 new_dos_attributes, /* attributes used for new file. */
2013 int oplock_request, /* internal Samba oplock codes. */
2014 /* Information (FILE_EXISTS etc.) */
2015 uint32_t private_flags, /* Samba specific flags. */
2016 int *pinfo,
2017 files_struct *fsp)
2019 struct smb_filename *smb_fname = fsp->fsp_name;
2020 int flags=0;
2021 int flags2=0;
2022 bool file_existed = VALID_STAT(smb_fname->st);
2023 bool def_acl = False;
2024 bool posix_open = False;
2025 bool new_file_created = False;
2026 bool first_open_attempt = true;
2027 NTSTATUS fsp_open = NT_STATUS_ACCESS_DENIED;
2028 mode_t new_unx_mode = (mode_t)0;
2029 mode_t unx_mode = (mode_t)0;
2030 int info;
2031 uint32 existing_dos_attributes = 0;
2032 struct timeval request_time = timeval_zero();
2033 struct share_mode_lock *lck = NULL;
2034 uint32 open_access_mask = access_mask;
2035 NTSTATUS status;
2036 char *parent_dir;
2037 SMB_STRUCT_STAT saved_stat = smb_fname->st;
2038 struct share_mode_entry *batch_entry = NULL;
2039 struct share_mode_entry *exclusive_entry = NULL;
2040 bool got_level2_oplock = false;
2041 bool got_a_none_oplock = false;
2042 struct timespec old_write_time;
2043 struct file_id id;
2045 if (conn->printer) {
2047 * Printers are handled completely differently.
2048 * Most of the passed parameters are ignored.
2051 if (pinfo) {
2052 *pinfo = FILE_WAS_CREATED;
2055 DEBUG(10, ("open_file_ntcreate: printer open fname=%s\n",
2056 smb_fname_str_dbg(smb_fname)));
2058 if (!req) {
2059 DEBUG(0,("open_file_ntcreate: printer open without "
2060 "an SMB request!\n"));
2061 return NT_STATUS_INTERNAL_ERROR;
2064 return print_spool_open(fsp, smb_fname->base_name,
2065 req->vuid);
2068 if (!parent_dirname(talloc_tos(), smb_fname->base_name, &parent_dir,
2069 NULL)) {
2070 return NT_STATUS_NO_MEMORY;
2073 if (new_dos_attributes & FILE_FLAG_POSIX_SEMANTICS) {
2074 posix_open = True;
2075 unx_mode = (mode_t)(new_dos_attributes & ~FILE_FLAG_POSIX_SEMANTICS);
2076 new_dos_attributes = 0;
2077 } else {
2078 /* Windows allows a new file to be created and
2079 silently removes a FILE_ATTRIBUTE_DIRECTORY
2080 sent by the client. Do the same. */
2082 new_dos_attributes &= ~FILE_ATTRIBUTE_DIRECTORY;
2084 /* We add FILE_ATTRIBUTE_ARCHIVE to this as this mode is only used if the file is
2085 * created new. */
2086 unx_mode = unix_mode(conn, new_dos_attributes | FILE_ATTRIBUTE_ARCHIVE,
2087 smb_fname, parent_dir);
2090 DEBUG(10, ("open_file_ntcreate: fname=%s, dos_attrs=0x%x "
2091 "access_mask=0x%x share_access=0x%x "
2092 "create_disposition = 0x%x create_options=0x%x "
2093 "unix mode=0%o oplock_request=%d private_flags = 0x%x\n",
2094 smb_fname_str_dbg(smb_fname), new_dos_attributes,
2095 access_mask, share_access, create_disposition,
2096 create_options, (unsigned int)unx_mode, oplock_request,
2097 (unsigned int)private_flags));
2099 if (req == NULL) {
2100 /* Ensure req == NULL means INTERNAL_OPEN_ONLY */
2101 SMB_ASSERT(((oplock_request & INTERNAL_OPEN_ONLY) != 0));
2102 } else {
2103 /* And req != NULL means no INTERNAL_OPEN_ONLY */
2104 SMB_ASSERT(((oplock_request & INTERNAL_OPEN_ONLY) == 0));
2108 * Only non-internal opens can be deferred at all
2111 if (req) {
2112 void *ptr;
2113 if (get_deferred_open_message_state(req,
2114 &request_time,
2115 &ptr)) {
2116 /* Remember the absolute time of the original
2117 request with this mid. We'll use it later to
2118 see if this has timed out. */
2120 /* If it was an async create retry, the file
2121 didn't exist. */
2123 if (is_deferred_open_async(ptr)) {
2124 SET_STAT_INVALID(smb_fname->st);
2125 file_existed = false;
2128 /* Ensure we don't reprocess this message. */
2129 remove_deferred_open_message_smb(req->sconn, req->mid);
2131 first_open_attempt = false;
2135 if (!posix_open) {
2136 new_dos_attributes &= SAMBA_ATTRIBUTES_MASK;
2137 if (file_existed) {
2138 existing_dos_attributes = dos_mode(conn, smb_fname);
2142 /* ignore any oplock requests if oplocks are disabled */
2143 if (!lp_oplocks(SNUM(conn)) ||
2144 IS_VETO_OPLOCK_PATH(conn, smb_fname->base_name)) {
2145 /* Mask off everything except the private Samba bits. */
2146 oplock_request &= SAMBA_PRIVATE_OPLOCK_MASK;
2149 /* this is for OS/2 long file names - say we don't support them */
2150 if (!lp_posix_pathnames() && strstr(smb_fname->base_name,".+,;=[].")) {
2151 /* OS/2 Workplace shell fix may be main code stream in a later
2152 * release. */
2153 DEBUG(5,("open_file_ntcreate: OS/2 long filenames are not "
2154 "supported.\n"));
2155 if (use_nt_status()) {
2156 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
2158 return NT_STATUS_DOS(ERRDOS, ERRcannotopen);
2161 switch( create_disposition ) {
2162 case FILE_OPEN:
2163 /* If file exists open. If file doesn't exist error. */
2164 if (!file_existed) {
2165 DEBUG(5,("open_file_ntcreate: FILE_OPEN "
2166 "requested for file %s and file "
2167 "doesn't exist.\n",
2168 smb_fname_str_dbg(smb_fname)));
2169 errno = ENOENT;
2170 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
2172 break;
2174 case FILE_OVERWRITE:
2175 /* If file exists overwrite. If file doesn't exist
2176 * error. */
2177 if (!file_existed) {
2178 DEBUG(5,("open_file_ntcreate: FILE_OVERWRITE "
2179 "requested for file %s and file "
2180 "doesn't exist.\n",
2181 smb_fname_str_dbg(smb_fname) ));
2182 errno = ENOENT;
2183 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
2185 break;
2187 case FILE_CREATE:
2188 /* If file exists error. If file doesn't exist
2189 * create. */
2190 if (file_existed) {
2191 DEBUG(5,("open_file_ntcreate: FILE_CREATE "
2192 "requested for file %s and file "
2193 "already exists.\n",
2194 smb_fname_str_dbg(smb_fname)));
2195 if (S_ISDIR(smb_fname->st.st_ex_mode)) {
2196 errno = EISDIR;
2197 } else {
2198 errno = EEXIST;
2200 return map_nt_error_from_unix(errno);
2202 break;
2204 case FILE_SUPERSEDE:
2205 case FILE_OVERWRITE_IF:
2206 case FILE_OPEN_IF:
2207 break;
2208 default:
2209 return NT_STATUS_INVALID_PARAMETER;
2212 flags2 = disposition_to_open_flags(create_disposition);
2214 /* We only care about matching attributes on file exists and
2215 * overwrite. */
2217 if (!posix_open && file_existed &&
2218 ((create_disposition == FILE_OVERWRITE) ||
2219 (create_disposition == FILE_OVERWRITE_IF))) {
2220 if (!open_match_attributes(conn, existing_dos_attributes,
2221 new_dos_attributes,
2222 smb_fname->st.st_ex_mode,
2223 unx_mode, &new_unx_mode)) {
2224 DEBUG(5,("open_file_ntcreate: attributes missmatch "
2225 "for file %s (%x %x) (0%o, 0%o)\n",
2226 smb_fname_str_dbg(smb_fname),
2227 existing_dos_attributes,
2228 new_dos_attributes,
2229 (unsigned int)smb_fname->st.st_ex_mode,
2230 (unsigned int)unx_mode ));
2231 errno = EACCES;
2232 return NT_STATUS_ACCESS_DENIED;
2236 status = smbd_calculate_access_mask(conn, smb_fname,
2237 false,
2238 access_mask,
2239 &access_mask);
2240 if (!NT_STATUS_IS_OK(status)) {
2241 DEBUG(10, ("open_file_ntcreate: smbd_calculate_access_mask "
2242 "on file %s returned %s\n",
2243 smb_fname_str_dbg(smb_fname), nt_errstr(status)));
2244 return status;
2247 open_access_mask = access_mask;
2249 if ((flags2 & O_TRUNC) || (oplock_request & FORCE_OPLOCK_BREAK_TO_NONE)) {
2250 open_access_mask |= FILE_WRITE_DATA; /* This will cause oplock breaks. */
2253 DEBUG(10, ("open_file_ntcreate: fname=%s, after mapping "
2254 "access_mask=0x%x\n", smb_fname_str_dbg(smb_fname),
2255 access_mask));
2258 * Note that we ignore the append flag as append does not
2259 * mean the same thing under DOS and Unix.
2262 flags = calculate_open_access_flags(access_mask, oplock_request,
2263 private_flags);
2266 * Currently we only look at FILE_WRITE_THROUGH for create options.
2269 #if defined(O_SYNC)
2270 if ((create_options & FILE_WRITE_THROUGH) && lp_strict_sync(SNUM(conn))) {
2271 flags2 |= O_SYNC;
2273 #endif /* O_SYNC */
2275 if (posix_open && (access_mask & FILE_APPEND_DATA)) {
2276 flags2 |= O_APPEND;
2279 if (!posix_open && !CAN_WRITE(conn)) {
2281 * We should really return a permission denied error if either
2282 * O_CREAT or O_TRUNC are set, but for compatibility with
2283 * older versions of Samba we just AND them out.
2285 flags2 &= ~(O_CREAT|O_TRUNC);
2288 if (first_open_attempt && lp_kernel_oplocks(SNUM(conn))) {
2290 * With kernel oplocks the open breaking an oplock
2291 * blocks until the oplock holder has given up the
2292 * oplock or closed the file. We prevent this by first
2293 * trying to open the file with O_NONBLOCK (see "man
2294 * fcntl" on Linux). For the second try, triggered by
2295 * an oplock break response, we do not need this
2296 * anymore.
2298 * This is true under the assumption that only Samba
2299 * requests kernel oplocks. Once someone else like
2300 * NFSv4 starts to use that API, we will have to
2301 * modify this by communicating with the NFSv4 server.
2303 flags2 |= O_NONBLOCK;
2307 * Ensure we can't write on a read-only share or file.
2310 if (flags != O_RDONLY && file_existed &&
2311 (!CAN_WRITE(conn) || IS_DOS_READONLY(existing_dos_attributes))) {
2312 DEBUG(5,("open_file_ntcreate: write access requested for "
2313 "file %s on read only %s\n",
2314 smb_fname_str_dbg(smb_fname),
2315 !CAN_WRITE(conn) ? "share" : "file" ));
2316 errno = EACCES;
2317 return NT_STATUS_ACCESS_DENIED;
2320 fsp->file_id = vfs_file_id_from_sbuf(conn, &smb_fname->st);
2321 fsp->share_access = share_access;
2322 fsp->fh->private_options = private_flags;
2323 fsp->access_mask = open_access_mask; /* We change this to the
2324 * requested access_mask after
2325 * the open is done. */
2326 fsp->posix_open = posix_open;
2328 /* Ensure no SAMBA_PRIVATE bits can be set. */
2329 fsp->oplock_type = (oplock_request & ~SAMBA_PRIVATE_OPLOCK_MASK);
2331 if (timeval_is_zero(&request_time)) {
2332 request_time = fsp->open_time;
2336 * Ensure we pay attention to default ACLs on directories if required.
2339 if ((flags2 & O_CREAT) && lp_inherit_acls(SNUM(conn)) &&
2340 (def_acl = directory_has_default_acl(conn, parent_dir))) {
2341 unx_mode = (0777 & lp_create_mask(SNUM(conn)));
2344 DEBUG(4,("calling open_file with flags=0x%X flags2=0x%X mode=0%o, "
2345 "access_mask = 0x%x, open_access_mask = 0x%x\n",
2346 (unsigned int)flags, (unsigned int)flags2,
2347 (unsigned int)unx_mode, (unsigned int)access_mask,
2348 (unsigned int)open_access_mask));
2350 fsp_open = open_file(fsp, conn, req, parent_dir,
2351 flags|flags2, unx_mode, access_mask,
2352 open_access_mask, &new_file_created);
2354 if (NT_STATUS_EQUAL(fsp_open, NT_STATUS_NETWORK_BUSY)) {
2355 struct deferred_open_record state;
2358 * EWOULDBLOCK/EAGAIN maps to NETWORK_BUSY.
2360 if (file_existed && S_ISFIFO(fsp->fsp_name->st.st_ex_mode)) {
2361 DEBUG(10, ("FIFO busy\n"));
2362 return NT_STATUS_NETWORK_BUSY;
2364 if (req == NULL) {
2365 DEBUG(10, ("Internal open busy\n"));
2366 return NT_STATUS_NETWORK_BUSY;
2370 * From here on we assume this is an oplock break triggered
2373 lck = get_existing_share_mode_lock(talloc_tos(), fsp->file_id);
2374 if (lck == NULL) {
2375 state.delayed_for_oplocks = false;
2376 state.async_open = false;
2377 state.id = fsp->file_id;
2378 defer_open(NULL, request_time, timeval_set(0, 0),
2379 req, &state);
2380 DEBUG(10, ("No share mode lock found after "
2381 "EWOULDBLOCK, retrying sync\n"));
2382 return NT_STATUS_SHARING_VIOLATION;
2385 find_oplock_types(fsp, 0, lck, &batch_entry, &exclusive_entry,
2386 &got_level2_oplock, &got_a_none_oplock);
2388 if (delay_for_batch_oplocks(fsp, req->mid, 0, batch_entry) ||
2389 delay_for_exclusive_oplocks(fsp, req->mid, 0,
2390 exclusive_entry)) {
2391 schedule_defer_open(lck, request_time, req);
2392 TALLOC_FREE(lck);
2393 DEBUG(10, ("Sent oplock break request to kernel "
2394 "oplock holder\n"));
2395 return NT_STATUS_SHARING_VIOLATION;
2399 * No oplock from Samba around. Immediately retry with
2400 * a blocking open.
2402 state.delayed_for_oplocks = false;
2403 state.async_open = false;
2404 state.id = lck->data->id;
2405 defer_open(lck, request_time, timeval_set(0, 0), req, &state);
2406 TALLOC_FREE(lck);
2407 DEBUG(10, ("No Samba oplock around after EWOULDBLOCK. "
2408 "Retrying sync\n"));
2409 return NT_STATUS_SHARING_VIOLATION;
2412 if (!NT_STATUS_IS_OK(fsp_open)) {
2413 if (NT_STATUS_EQUAL(fsp_open, NT_STATUS_RETRY)) {
2414 schedule_async_open(request_time, req);
2416 TALLOC_FREE(lck);
2417 return fsp_open;
2420 if (file_existed && !check_same_dev_ino(&saved_stat, &smb_fname->st)) {
2422 * The file did exist, but some other (local or NFS)
2423 * process either renamed/unlinked and re-created the
2424 * file with different dev/ino after we walked the path,
2425 * but before we did the open. We could retry the
2426 * open but it's a rare enough case it's easier to
2427 * just fail the open to prevent creating any problems
2428 * in the open file db having the wrong dev/ino key.
2430 TALLOC_FREE(lck);
2431 fd_close(fsp);
2432 DEBUG(1,("open_file_ntcreate: file %s - dev/ino mismatch. "
2433 "Old (dev=0x%llu, ino =0x%llu). "
2434 "New (dev=0x%llu, ino=0x%llu). Failing open "
2435 " with NT_STATUS_ACCESS_DENIED.\n",
2436 smb_fname_str_dbg(smb_fname),
2437 (unsigned long long)saved_stat.st_ex_dev,
2438 (unsigned long long)saved_stat.st_ex_ino,
2439 (unsigned long long)smb_fname->st.st_ex_dev,
2440 (unsigned long long)smb_fname->st.st_ex_ino));
2441 return NT_STATUS_ACCESS_DENIED;
2444 old_write_time = smb_fname->st.st_ex_mtime;
2447 * Deal with the race condition where two smbd's detect the
2448 * file doesn't exist and do the create at the same time. One
2449 * of them will win and set a share mode, the other (ie. this
2450 * one) should check if the requested share mode for this
2451 * create is allowed.
2455 * Now the file exists and fsp is successfully opened,
2456 * fsp->dev and fsp->inode are valid and should replace the
2457 * dev=0,inode=0 from a non existent file. Spotted by
2458 * Nadav Danieli <nadavd@exanet.com>. JRA.
2461 id = fsp->file_id;
2463 lck = get_share_mode_lock(talloc_tos(), id,
2464 conn->connectpath,
2465 smb_fname, &old_write_time);
2467 if (lck == NULL) {
2468 DEBUG(0, ("open_file_ntcreate: Could not get share "
2469 "mode lock for %s\n",
2470 smb_fname_str_dbg(smb_fname)));
2471 fd_close(fsp);
2472 return NT_STATUS_SHARING_VIOLATION;
2475 /* Get the types we need to examine. */
2476 find_oplock_types(fsp,
2477 oplock_request,
2478 lck,
2479 &batch_entry,
2480 &exclusive_entry,
2481 &got_level2_oplock,
2482 &got_a_none_oplock);
2484 /* First pass - send break only on batch oplocks. */
2485 if ((req != NULL) &&
2486 delay_for_batch_oplocks(fsp,
2487 req->mid,
2488 oplock_request,
2489 batch_entry)) {
2490 schedule_defer_open(lck, request_time, req);
2491 TALLOC_FREE(lck);
2492 fd_close(fsp);
2493 return NT_STATUS_SHARING_VIOLATION;
2496 status = open_mode_check(conn, lck, fsp->name_hash,
2497 access_mask, share_access,
2498 create_options, &file_existed);
2500 if (NT_STATUS_IS_OK(status)) {
2501 /* We might be going to allow this open. Check oplock
2502 * status again. */
2503 /* Second pass - send break for both batch or
2504 * exclusive oplocks. */
2505 if ((req != NULL) &&
2506 delay_for_exclusive_oplocks(
2507 fsp,
2508 req->mid,
2509 oplock_request,
2510 exclusive_entry)) {
2511 schedule_defer_open(lck, request_time, req);
2512 TALLOC_FREE(lck);
2513 fd_close(fsp);
2514 return NT_STATUS_SHARING_VIOLATION;
2518 if (NT_STATUS_EQUAL(status, NT_STATUS_DELETE_PENDING)) {
2519 /* DELETE_PENDING is not deferred for a second */
2520 TALLOC_FREE(lck);
2521 fd_close(fsp);
2522 return status;
2525 if (!NT_STATUS_IS_OK(status)) {
2526 uint32 can_access_mask;
2527 bool can_access = True;
2529 SMB_ASSERT(NT_STATUS_EQUAL(status, NT_STATUS_SHARING_VIOLATION));
2531 /* Check if this can be done with the deny_dos and fcb
2532 * calls. */
2533 if (private_flags &
2534 (NTCREATEX_OPTIONS_PRIVATE_DENY_DOS|
2535 NTCREATEX_OPTIONS_PRIVATE_DENY_FCB)) {
2536 if (req == NULL) {
2537 DEBUG(0, ("DOS open without an SMB "
2538 "request!\n"));
2539 TALLOC_FREE(lck);
2540 fd_close(fsp);
2541 return NT_STATUS_INTERNAL_ERROR;
2544 /* Use the client requested access mask here,
2545 * not the one we open with. */
2546 status = fcb_or_dos_open(req,
2547 conn,
2548 fsp,
2549 smb_fname,
2551 req->smbpid,
2552 req->vuid,
2553 access_mask,
2554 share_access,
2555 create_options);
2557 if (NT_STATUS_IS_OK(status)) {
2558 TALLOC_FREE(lck);
2559 if (pinfo) {
2560 *pinfo = FILE_WAS_OPENED;
2562 return NT_STATUS_OK;
2567 * This next line is a subtlety we need for
2568 * MS-Access. If a file open will fail due to share
2569 * permissions and also for security (access) reasons,
2570 * we need to return the access failed error, not the
2571 * share error. We can't open the file due to kernel
2572 * oplock deadlock (it's possible we failed above on
2573 * the open_mode_check()) so use a userspace check.
2576 if (flags & O_RDWR) {
2577 can_access_mask = FILE_READ_DATA|FILE_WRITE_DATA;
2578 } else if (flags & O_WRONLY) {
2579 can_access_mask = FILE_WRITE_DATA;
2580 } else {
2581 can_access_mask = FILE_READ_DATA;
2584 if (((can_access_mask & FILE_WRITE_DATA) &&
2585 !CAN_WRITE(conn)) ||
2586 !NT_STATUS_IS_OK(smbd_check_access_rights(conn,
2587 smb_fname,
2588 false,
2589 can_access_mask))) {
2590 can_access = False;
2594 * If we're returning a share violation, ensure we
2595 * cope with the braindead 1 second delay (SMB1 only).
2598 if (!(oplock_request & INTERNAL_OPEN_ONLY) &&
2599 !conn->sconn->using_smb2 &&
2600 lp_defer_sharing_violations()) {
2601 struct timeval timeout;
2602 struct deferred_open_record state;
2603 int timeout_usecs;
2605 /* this is a hack to speed up torture tests
2606 in 'make test' */
2607 timeout_usecs = lp_parm_int(SNUM(conn),
2608 "smbd","sharedelay",
2609 SHARING_VIOLATION_USEC_WAIT);
2611 /* This is a relative time, added to the absolute
2612 request_time value to get the absolute timeout time.
2613 Note that if this is the second or greater time we enter
2614 this codepath for this particular request mid then
2615 request_time is left as the absolute time of the *first*
2616 time this request mid was processed. This is what allows
2617 the request to eventually time out. */
2619 timeout = timeval_set(0, timeout_usecs);
2621 /* Nothing actually uses state.delayed_for_oplocks
2622 but it's handy to differentiate in debug messages
2623 between a 30 second delay due to oplock break, and
2624 a 1 second delay for share mode conflicts. */
2626 state.delayed_for_oplocks = False;
2627 state.async_open = false;
2628 state.id = id;
2630 if ((req != NULL)
2631 && !request_timed_out(request_time,
2632 timeout)) {
2633 defer_open(lck, request_time, timeout,
2634 req, &state);
2638 TALLOC_FREE(lck);
2639 fd_close(fsp);
2640 if (can_access) {
2642 * We have detected a sharing violation here
2643 * so return the correct error code
2645 status = NT_STATUS_SHARING_VIOLATION;
2646 } else {
2647 status = NT_STATUS_ACCESS_DENIED;
2649 return status;
2652 /* Should we atomically (to the client at least) truncate ? */
2653 if (!new_file_created) {
2654 if (flags2 & O_TRUNC) {
2655 if (!S_ISFIFO(fsp->fsp_name->st.st_ex_mode)) {
2656 int ret = vfs_set_filelen(fsp, 0);
2657 if (ret != 0) {
2658 status = map_nt_error_from_unix(errno);
2659 TALLOC_FREE(lck);
2660 fd_close(fsp);
2661 return status;
2667 grant_fsp_oplock_type(fsp,
2668 oplock_request,
2669 got_level2_oplock,
2670 got_a_none_oplock);
2673 * We have the share entry *locked*.....
2676 /* Delete streams if create_disposition requires it */
2677 if (!new_file_created && clear_ads(create_disposition) &&
2678 !is_ntfs_stream_smb_fname(smb_fname)) {
2679 status = delete_all_streams(conn, smb_fname->base_name);
2680 if (!NT_STATUS_IS_OK(status)) {
2681 TALLOC_FREE(lck);
2682 fd_close(fsp);
2683 return status;
2687 /* note that we ignore failure for the following. It is
2688 basically a hack for NFS, and NFS will never set one of
2689 these only read them. Nobody but Samba can ever set a deny
2690 mode and we have already checked our more authoritative
2691 locking database for permission to set this deny mode. If
2692 the kernel refuses the operations then the kernel is wrong.
2693 note that GPFS supports it as well - jmcd */
2695 if (fsp->fh->fd != -1 && lp_kernel_share_modes(SNUM(conn))) {
2696 int ret_flock;
2697 ret_flock = SMB_VFS_KERNEL_FLOCK(fsp, share_access, access_mask);
2698 if(ret_flock == -1 ){
2700 TALLOC_FREE(lck);
2701 fd_close(fsp);
2703 return NT_STATUS_SHARING_VIOLATION;
2708 * At this point onwards, we can guarantee that the share entry
2709 * is locked, whether we created the file or not, and that the
2710 * deny mode is compatible with all current opens.
2714 * According to Samba4, SEC_FILE_READ_ATTRIBUTE is always granted,
2715 * but we don't have to store this - just ignore it on access check.
2717 if (conn->sconn->using_smb2) {
2719 * SMB2 doesn't return it (according to Microsoft tests).
2720 * Test Case: TestSuite_ScenarioNo009GrantedAccessTestS0
2721 * File created with access = 0x7 (Read, Write, Delete)
2722 * Query Info on file returns 0x87 (Read, Write, Delete, Read Attributes)
2724 fsp->access_mask = access_mask;
2725 } else {
2726 /* But SMB1 does. */
2727 fsp->access_mask = access_mask | FILE_READ_ATTRIBUTES;
2730 if (file_existed) {
2731 /* stat opens on existing files don't get oplocks. */
2732 if (is_stat_open(open_access_mask)) {
2733 fsp->oplock_type = NO_OPLOCK;
2737 if (new_file_created) {
2738 info = FILE_WAS_CREATED;
2739 } else {
2740 if (flags2 & O_TRUNC) {
2741 info = FILE_WAS_OVERWRITTEN;
2742 } else {
2743 info = FILE_WAS_OPENED;
2747 if (pinfo) {
2748 *pinfo = info;
2752 * Setup the oplock info in both the shared memory and
2753 * file structs.
2756 status = set_file_oplock(fsp, fsp->oplock_type);
2757 if (!NT_STATUS_IS_OK(status)) {
2759 * Could not get the kernel oplock or there are byte-range
2760 * locks on the file.
2762 fsp->oplock_type = NO_OPLOCK;
2765 set_share_mode(lck, fsp, get_current_uid(conn),
2766 req ? req->mid : 0,
2767 fsp->oplock_type);
2769 /* Handle strange delete on close create semantics. */
2770 if (create_options & FILE_DELETE_ON_CLOSE) {
2772 status = can_set_delete_on_close(fsp, new_dos_attributes);
2774 if (!NT_STATUS_IS_OK(status)) {
2775 /* Remember to delete the mode we just added. */
2776 del_share_mode(lck, fsp);
2777 TALLOC_FREE(lck);
2778 fd_close(fsp);
2779 return status;
2781 /* Note that here we set the *inital* delete on close flag,
2782 not the regular one. The magic gets handled in close. */
2783 fsp->initial_delete_on_close = True;
2786 if (info != FILE_WAS_OPENED) {
2787 /* Files should be initially set as archive */
2788 if (lp_map_archive(SNUM(conn)) ||
2789 lp_store_dos_attributes(SNUM(conn))) {
2790 if (!posix_open) {
2791 if (file_set_dosmode(conn, smb_fname,
2792 new_dos_attributes | FILE_ATTRIBUTE_ARCHIVE,
2793 parent_dir, true) == 0) {
2794 unx_mode = smb_fname->st.st_ex_mode;
2800 /* Determine sparse flag. */
2801 if (posix_open) {
2802 /* POSIX opens are sparse by default. */
2803 fsp->is_sparse = true;
2804 } else {
2805 fsp->is_sparse = (file_existed &&
2806 (existing_dos_attributes & FILE_ATTRIBUTE_SPARSE));
2810 * Take care of inherited ACLs on created files - if default ACL not
2811 * selected.
2814 if (!posix_open && new_file_created && !def_acl) {
2816 int saved_errno = errno; /* We might get ENOSYS in the next
2817 * call.. */
2819 if (SMB_VFS_FCHMOD_ACL(fsp, unx_mode) == -1 &&
2820 errno == ENOSYS) {
2821 errno = saved_errno; /* Ignore ENOSYS */
2824 } else if (new_unx_mode) {
2826 int ret = -1;
2828 /* Attributes need changing. File already existed. */
2831 int saved_errno = errno; /* We might get ENOSYS in the
2832 * next call.. */
2833 ret = SMB_VFS_FCHMOD_ACL(fsp, new_unx_mode);
2835 if (ret == -1 && errno == ENOSYS) {
2836 errno = saved_errno; /* Ignore ENOSYS */
2837 } else {
2838 DEBUG(5, ("open_file_ntcreate: reset "
2839 "attributes of file %s to 0%o\n",
2840 smb_fname_str_dbg(smb_fname),
2841 (unsigned int)new_unx_mode));
2842 ret = 0; /* Don't do the fchmod below. */
2846 if ((ret == -1) &&
2847 (SMB_VFS_FCHMOD(fsp, new_unx_mode) == -1))
2848 DEBUG(5, ("open_file_ntcreate: failed to reset "
2849 "attributes of file %s to 0%o\n",
2850 smb_fname_str_dbg(smb_fname),
2851 (unsigned int)new_unx_mode));
2854 TALLOC_FREE(lck);
2856 return NT_STATUS_OK;
2859 static NTSTATUS mkdir_internal(connection_struct *conn,
2860 struct smb_filename *smb_dname,
2861 uint32 file_attributes)
2863 mode_t mode;
2864 char *parent_dir = NULL;
2865 NTSTATUS status;
2866 bool posix_open = false;
2867 bool need_re_stat = false;
2868 uint32_t access_mask = SEC_DIR_ADD_SUBDIR;
2870 if (!CAN_WRITE(conn) || (access_mask & ~(conn->share_access))) {
2871 DEBUG(5,("mkdir_internal: failing share access "
2872 "%s\n", lp_servicename(talloc_tos(), SNUM(conn))));
2873 return NT_STATUS_ACCESS_DENIED;
2876 if (!parent_dirname(talloc_tos(), smb_dname->base_name, &parent_dir,
2877 NULL)) {
2878 return NT_STATUS_NO_MEMORY;
2881 if (file_attributes & FILE_FLAG_POSIX_SEMANTICS) {
2882 posix_open = true;
2883 mode = (mode_t)(file_attributes & ~FILE_FLAG_POSIX_SEMANTICS);
2884 } else {
2885 mode = unix_mode(conn, FILE_ATTRIBUTE_DIRECTORY, smb_dname, parent_dir);
2888 status = check_parent_access(conn,
2889 smb_dname,
2890 access_mask);
2891 if(!NT_STATUS_IS_OK(status)) {
2892 DEBUG(5,("mkdir_internal: check_parent_access "
2893 "on directory %s for path %s returned %s\n",
2894 parent_dir,
2895 smb_dname->base_name,
2896 nt_errstr(status) ));
2897 return status;
2900 if (SMB_VFS_MKDIR(conn, smb_dname->base_name, mode) != 0) {
2901 return map_nt_error_from_unix(errno);
2904 /* Ensure we're checking for a symlink here.... */
2905 /* We don't want to get caught by a symlink racer. */
2907 if (SMB_VFS_LSTAT(conn, smb_dname) == -1) {
2908 DEBUG(2, ("Could not stat directory '%s' just created: %s\n",
2909 smb_fname_str_dbg(smb_dname), strerror(errno)));
2910 return map_nt_error_from_unix(errno);
2913 if (!S_ISDIR(smb_dname->st.st_ex_mode)) {
2914 DEBUG(0, ("Directory '%s' just created is not a directory !\n",
2915 smb_fname_str_dbg(smb_dname)));
2916 return NT_STATUS_NOT_A_DIRECTORY;
2919 if (lp_store_dos_attributes(SNUM(conn))) {
2920 if (!posix_open) {
2921 file_set_dosmode(conn, smb_dname,
2922 file_attributes | FILE_ATTRIBUTE_DIRECTORY,
2923 parent_dir, true);
2927 if (lp_inherit_perms(SNUM(conn))) {
2928 inherit_access_posix_acl(conn, parent_dir,
2929 smb_dname->base_name, mode);
2930 need_re_stat = true;
2933 if (!posix_open) {
2935 * Check if high bits should have been set,
2936 * then (if bits are missing): add them.
2937 * Consider bits automagically set by UNIX, i.e. SGID bit from parent
2938 * dir.
2940 if ((mode & ~(S_IRWXU|S_IRWXG|S_IRWXO)) &&
2941 (mode & ~smb_dname->st.st_ex_mode)) {
2942 SMB_VFS_CHMOD(conn, smb_dname->base_name,
2943 (smb_dname->st.st_ex_mode |
2944 (mode & ~smb_dname->st.st_ex_mode)));
2945 need_re_stat = true;
2949 /* Change the owner if required. */
2950 if (lp_inherit_owner(SNUM(conn))) {
2951 change_dir_owner_to_parent(conn, parent_dir,
2952 smb_dname->base_name,
2953 &smb_dname->st);
2954 need_re_stat = true;
2957 if (need_re_stat) {
2958 if (SMB_VFS_LSTAT(conn, smb_dname) == -1) {
2959 DEBUG(2, ("Could not stat directory '%s' just created: %s\n",
2960 smb_fname_str_dbg(smb_dname), strerror(errno)));
2961 return map_nt_error_from_unix(errno);
2965 notify_fname(conn, NOTIFY_ACTION_ADDED, FILE_NOTIFY_CHANGE_DIR_NAME,
2966 smb_dname->base_name);
2968 return NT_STATUS_OK;
2971 /****************************************************************************
2972 Open a directory from an NT SMB call.
2973 ****************************************************************************/
2975 static NTSTATUS open_directory(connection_struct *conn,
2976 struct smb_request *req,
2977 struct smb_filename *smb_dname,
2978 uint32 access_mask,
2979 uint32 share_access,
2980 uint32 create_disposition,
2981 uint32 create_options,
2982 uint32 file_attributes,
2983 int *pinfo,
2984 files_struct **result)
2986 files_struct *fsp = NULL;
2987 bool dir_existed = VALID_STAT(smb_dname->st) ? True : False;
2988 struct share_mode_lock *lck = NULL;
2989 NTSTATUS status;
2990 struct timespec mtimespec;
2991 int info = 0;
2993 if (is_ntfs_stream_smb_fname(smb_dname)) {
2994 DEBUG(2, ("open_directory: %s is a stream name!\n",
2995 smb_fname_str_dbg(smb_dname)));
2996 return NT_STATUS_NOT_A_DIRECTORY;
2999 if (!(file_attributes & FILE_FLAG_POSIX_SEMANTICS)) {
3000 /* Ensure we have a directory attribute. */
3001 file_attributes |= FILE_ATTRIBUTE_DIRECTORY;
3004 DEBUG(5,("open_directory: opening directory %s, access_mask = 0x%x, "
3005 "share_access = 0x%x create_options = 0x%x, "
3006 "create_disposition = 0x%x, file_attributes = 0x%x\n",
3007 smb_fname_str_dbg(smb_dname),
3008 (unsigned int)access_mask,
3009 (unsigned int)share_access,
3010 (unsigned int)create_options,
3011 (unsigned int)create_disposition,
3012 (unsigned int)file_attributes));
3014 status = smbd_calculate_access_mask(conn, smb_dname, false,
3015 access_mask, &access_mask);
3016 if (!NT_STATUS_IS_OK(status)) {
3017 DEBUG(10, ("open_directory: smbd_calculate_access_mask "
3018 "on file %s returned %s\n",
3019 smb_fname_str_dbg(smb_dname),
3020 nt_errstr(status)));
3021 return status;
3024 if ((access_mask & SEC_FLAG_SYSTEM_SECURITY) &&
3025 !security_token_has_privilege(get_current_nttok(conn),
3026 SEC_PRIV_SECURITY)) {
3027 DEBUG(10, ("open_directory: open on %s "
3028 "failed - SEC_FLAG_SYSTEM_SECURITY denied.\n",
3029 smb_fname_str_dbg(smb_dname)));
3030 return NT_STATUS_PRIVILEGE_NOT_HELD;
3033 switch( create_disposition ) {
3034 case FILE_OPEN:
3036 if (!dir_existed) {
3037 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3040 info = FILE_WAS_OPENED;
3041 break;
3043 case FILE_CREATE:
3045 /* If directory exists error. If directory doesn't
3046 * exist create. */
3048 if (dir_existed) {
3049 status = NT_STATUS_OBJECT_NAME_COLLISION;
3050 DEBUG(2, ("open_directory: unable to create "
3051 "%s. Error was %s\n",
3052 smb_fname_str_dbg(smb_dname),
3053 nt_errstr(status)));
3054 return status;
3057 status = mkdir_internal(conn, smb_dname,
3058 file_attributes);
3060 if (!NT_STATUS_IS_OK(status)) {
3061 DEBUG(2, ("open_directory: unable to create "
3062 "%s. Error was %s\n",
3063 smb_fname_str_dbg(smb_dname),
3064 nt_errstr(status)));
3065 return status;
3068 info = FILE_WAS_CREATED;
3069 break;
3071 case FILE_OPEN_IF:
3073 * If directory exists open. If directory doesn't
3074 * exist create.
3077 if (dir_existed) {
3078 status = NT_STATUS_OK;
3079 info = FILE_WAS_OPENED;
3080 } else {
3081 status = mkdir_internal(conn, smb_dname,
3082 file_attributes);
3084 if (NT_STATUS_IS_OK(status)) {
3085 info = FILE_WAS_CREATED;
3086 } else {
3087 /* Cope with create race. */
3088 if (!NT_STATUS_EQUAL(status,
3089 NT_STATUS_OBJECT_NAME_COLLISION)) {
3090 DEBUG(2, ("open_directory: unable to create "
3091 "%s. Error was %s\n",
3092 smb_fname_str_dbg(smb_dname),
3093 nt_errstr(status)));
3094 return status;
3096 info = FILE_WAS_OPENED;
3100 break;
3102 case FILE_SUPERSEDE:
3103 case FILE_OVERWRITE:
3104 case FILE_OVERWRITE_IF:
3105 default:
3106 DEBUG(5,("open_directory: invalid create_disposition "
3107 "0x%x for directory %s\n",
3108 (unsigned int)create_disposition,
3109 smb_fname_str_dbg(smb_dname)));
3110 return NT_STATUS_INVALID_PARAMETER;
3113 if(!S_ISDIR(smb_dname->st.st_ex_mode)) {
3114 DEBUG(5,("open_directory: %s is not a directory !\n",
3115 smb_fname_str_dbg(smb_dname)));
3116 return NT_STATUS_NOT_A_DIRECTORY;
3119 if (info == FILE_WAS_OPENED) {
3120 status = smbd_check_access_rights(conn,
3121 smb_dname,
3122 false,
3123 access_mask);
3124 if (!NT_STATUS_IS_OK(status)) {
3125 DEBUG(10, ("open_directory: smbd_check_access_rights on "
3126 "file %s failed with %s\n",
3127 smb_fname_str_dbg(smb_dname),
3128 nt_errstr(status)));
3129 return status;
3133 status = file_new(req, conn, &fsp);
3134 if(!NT_STATUS_IS_OK(status)) {
3135 return status;
3139 * Setup the files_struct for it.
3142 fsp->file_id = vfs_file_id_from_sbuf(conn, &smb_dname->st);
3143 fsp->vuid = req ? req->vuid : UID_FIELD_INVALID;
3144 fsp->file_pid = req ? req->smbpid : 0;
3145 fsp->can_lock = False;
3146 fsp->can_read = False;
3147 fsp->can_write = False;
3149 fsp->share_access = share_access;
3150 fsp->fh->private_options = 0;
3152 * According to Samba4, SEC_FILE_READ_ATTRIBUTE is always granted,
3154 fsp->access_mask = access_mask | FILE_READ_ATTRIBUTES;
3155 fsp->print_file = NULL;
3156 fsp->modified = False;
3157 fsp->oplock_type = NO_OPLOCK;
3158 fsp->sent_oplock_break = NO_BREAK_SENT;
3159 fsp->is_directory = True;
3160 fsp->posix_open = (file_attributes & FILE_FLAG_POSIX_SEMANTICS) ? True : False;
3161 status = fsp_set_smb_fname(fsp, smb_dname);
3162 if (!NT_STATUS_IS_OK(status)) {
3163 file_free(req, fsp);
3164 return status;
3167 /* Don't store old timestamps for directory
3168 handles in the internal database. We don't
3169 update them in there if new objects
3170 are creaded in the directory. Currently
3171 we only update timestamps on file writes.
3172 See bug #9870.
3174 ZERO_STRUCT(mtimespec);
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;