s3: smbd: Remove open_file_fchmod().
[Samba.git] / source3 / smbd / open.c
blob5f7bff9a8d3c96b533aab3097868600e9a40aa0d
1 /*
2 Unix SMB/CIFS implementation.
3 file opening and share modes
4 Copyright (C) Andrew Tridgell 1992-1998
5 Copyright (C) Jeremy Allison 2001-2004
6 Copyright (C) Volker Lendecke 2005
8 This program is free software; you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation; either version 3 of the License, or
11 (at your option) any later version.
13 This program is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with this program. If not, see <http://www.gnu.org/licenses/>.
22 #include "includes.h"
23 #include "system/filesys.h"
24 #include "printing.h"
25 #include "smbd/smbd.h"
26 #include "smbd/globals.h"
27 #include "fake_file.h"
28 #include "../libcli/security/security.h"
29 #include "../librpc/gen_ndr/ndr_security.h"
30 #include "../librpc/gen_ndr/open_files.h"
31 #include "../librpc/gen_ndr/idmap.h"
32 #include "passdb/lookup_sid.h"
33 #include "auth.h"
34 #include "serverid.h"
35 #include "messages.h"
36 #include "source3/lib/dbwrap/dbwrap_watch.h"
38 extern const struct generic_mapping file_generic_mapping;
40 struct deferred_open_record {
41 bool delayed_for_oplocks;
42 bool async_open;
43 struct file_id id;
46 /****************************************************************************
47 If the requester wanted DELETE_ACCESS and was rejected because
48 the file ACL didn't include DELETE_ACCESS, see if the parent ACL
49 overrides this.
50 ****************************************************************************/
52 static bool parent_override_delete(connection_struct *conn,
53 const struct smb_filename *smb_fname,
54 uint32_t access_mask,
55 uint32_t rejected_mask)
57 if ((access_mask & DELETE_ACCESS) &&
58 (rejected_mask & DELETE_ACCESS) &&
59 can_delete_file_in_directory(conn, smb_fname)) {
60 return true;
62 return false;
65 /****************************************************************************
66 Check if we have open rights.
67 ****************************************************************************/
69 NTSTATUS smbd_check_access_rights(struct connection_struct *conn,
70 const struct smb_filename *smb_fname,
71 bool use_privs,
72 uint32_t access_mask)
74 /* Check if we have rights to open. */
75 NTSTATUS status;
76 struct security_descriptor *sd = NULL;
77 uint32_t rejected_share_access;
78 uint32_t rejected_mask = access_mask;
79 uint32_t do_not_check_mask = 0;
81 rejected_share_access = access_mask & ~(conn->share_access);
83 if (rejected_share_access) {
84 DEBUG(10, ("smbd_check_access_rights: rejected share access 0x%x "
85 "on %s (0x%x)\n",
86 (unsigned int)access_mask,
87 smb_fname_str_dbg(smb_fname),
88 (unsigned int)rejected_share_access ));
89 return NT_STATUS_ACCESS_DENIED;
92 if (!use_privs && get_current_uid(conn) == (uid_t)0) {
93 /* I'm sorry sir, I didn't know you were root... */
94 DEBUG(10,("smbd_check_access_rights: root override "
95 "on %s. Granting 0x%x\n",
96 smb_fname_str_dbg(smb_fname),
97 (unsigned int)access_mask ));
98 return NT_STATUS_OK;
101 if ((access_mask & DELETE_ACCESS) && !lp_acl_check_permissions(SNUM(conn))) {
102 DEBUG(10,("smbd_check_access_rights: not checking ACL "
103 "on DELETE_ACCESS on file %s. Granting 0x%x\n",
104 smb_fname_str_dbg(smb_fname),
105 (unsigned int)access_mask ));
106 return NT_STATUS_OK;
109 if (access_mask == DELETE_ACCESS &&
110 VALID_STAT(smb_fname->st) &&
111 S_ISLNK(smb_fname->st.st_ex_mode)) {
112 /* We can always delete a symlink. */
113 DEBUG(10,("smbd_check_access_rights: not checking ACL "
114 "on DELETE_ACCESS on symlink %s.\n",
115 smb_fname_str_dbg(smb_fname) ));
116 return NT_STATUS_OK;
119 status = SMB_VFS_GET_NT_ACL(conn, smb_fname->base_name,
120 (SECINFO_OWNER |
121 SECINFO_GROUP |
122 SECINFO_DACL), talloc_tos(), &sd);
124 if (!NT_STATUS_IS_OK(status)) {
125 DEBUG(10, ("smbd_check_access_rights: Could not get acl "
126 "on %s: %s\n",
127 smb_fname_str_dbg(smb_fname),
128 nt_errstr(status)));
130 if (NT_STATUS_EQUAL(status, NT_STATUS_ACCESS_DENIED)) {
131 goto access_denied;
134 return status;
138 * If we can access the path to this file, by
139 * default we have FILE_READ_ATTRIBUTES from the
140 * containing directory. See the section:
141 * "Algorithm to Check Access to an Existing File"
142 * in MS-FSA.pdf.
144 * se_file_access_check() also takes care of
145 * owner WRITE_DAC and READ_CONTROL.
147 do_not_check_mask = FILE_READ_ATTRIBUTES;
150 * Samba 3.6 and earlier granted execute access even
151 * if the ACL did not contain execute rights.
152 * Samba 4.0 is more correct and checks it.
153 * The compatibilty mode allows to skip this check
154 * to smoothen upgrades.
156 if (lp_acl_allow_execute_always(SNUM(conn))) {
157 do_not_check_mask |= FILE_EXECUTE;
160 status = se_file_access_check(sd,
161 get_current_nttok(conn),
162 use_privs,
163 (access_mask & ~do_not_check_mask),
164 &rejected_mask);
166 DEBUG(10,("smbd_check_access_rights: file %s requesting "
167 "0x%x returning 0x%x (%s)\n",
168 smb_fname_str_dbg(smb_fname),
169 (unsigned int)access_mask,
170 (unsigned int)rejected_mask,
171 nt_errstr(status) ));
173 if (!NT_STATUS_IS_OK(status)) {
174 if (DEBUGLEVEL >= 10) {
175 DEBUG(10,("smbd_check_access_rights: acl for %s is:\n",
176 smb_fname_str_dbg(smb_fname) ));
177 NDR_PRINT_DEBUG(security_descriptor, sd);
181 TALLOC_FREE(sd);
183 if (NT_STATUS_IS_OK(status) ||
184 !NT_STATUS_EQUAL(status, NT_STATUS_ACCESS_DENIED)) {
185 return status;
188 /* Here we know status == NT_STATUS_ACCESS_DENIED. */
190 access_denied:
192 if ((access_mask & FILE_WRITE_ATTRIBUTES) &&
193 (rejected_mask & FILE_WRITE_ATTRIBUTES) &&
194 !lp_store_dos_attributes(SNUM(conn)) &&
195 (lp_map_readonly(SNUM(conn)) ||
196 lp_map_archive(SNUM(conn)) ||
197 lp_map_hidden(SNUM(conn)) ||
198 lp_map_system(SNUM(conn)))) {
199 rejected_mask &= ~FILE_WRITE_ATTRIBUTES;
201 DEBUG(10,("smbd_check_access_rights: "
202 "overrode "
203 "FILE_WRITE_ATTRIBUTES "
204 "on file %s\n",
205 smb_fname_str_dbg(smb_fname)));
208 if (parent_override_delete(conn,
209 smb_fname,
210 access_mask,
211 rejected_mask)) {
212 /* Were we trying to do an open
213 * for delete and didn't get DELETE
214 * access (only) ? Check if the
215 * directory allows DELETE_CHILD.
216 * See here:
217 * http://blogs.msdn.com/oldnewthing/archive/2004/06/04/148426.aspx
218 * for details. */
220 rejected_mask &= ~DELETE_ACCESS;
222 DEBUG(10,("smbd_check_access_rights: "
223 "overrode "
224 "DELETE_ACCESS on "
225 "file %s\n",
226 smb_fname_str_dbg(smb_fname)));
229 if (rejected_mask != 0) {
230 return NT_STATUS_ACCESS_DENIED;
232 return NT_STATUS_OK;
235 static NTSTATUS check_parent_access(struct connection_struct *conn,
236 struct smb_filename *smb_fname,
237 uint32_t access_mask)
239 NTSTATUS status;
240 char *parent_dir = NULL;
241 struct security_descriptor *parent_sd = NULL;
242 uint32_t access_granted = 0;
244 if (!parent_dirname(talloc_tos(),
245 smb_fname->base_name,
246 &parent_dir,
247 NULL)) {
248 return NT_STATUS_NO_MEMORY;
251 if (get_current_uid(conn) == (uid_t)0) {
252 /* I'm sorry sir, I didn't know you were root... */
253 DEBUG(10,("check_parent_access: root override "
254 "on %s. Granting 0x%x\n",
255 smb_fname_str_dbg(smb_fname),
256 (unsigned int)access_mask ));
257 return NT_STATUS_OK;
260 status = SMB_VFS_GET_NT_ACL(conn,
261 parent_dir,
262 SECINFO_DACL,
263 talloc_tos(),
264 &parent_sd);
266 if (!NT_STATUS_IS_OK(status)) {
267 DEBUG(5,("check_parent_access: SMB_VFS_GET_NT_ACL failed for "
268 "%s with error %s\n",
269 parent_dir,
270 nt_errstr(status)));
271 return status;
275 * If we can access the path to this file, by
276 * default we have FILE_READ_ATTRIBUTES from the
277 * containing directory. See the section:
278 * "Algorithm to Check Access to an Existing File"
279 * in MS-FSA.pdf.
281 * se_file_access_check() also takes care of
282 * owner WRITE_DAC and READ_CONTROL.
284 status = se_file_access_check(parent_sd,
285 get_current_nttok(conn),
286 false,
287 (access_mask & ~FILE_READ_ATTRIBUTES),
288 &access_granted);
289 if(!NT_STATUS_IS_OK(status)) {
290 DEBUG(5,("check_parent_access: access check "
291 "on directory %s for "
292 "path %s for mask 0x%x returned (0x%x) %s\n",
293 parent_dir,
294 smb_fname->base_name,
295 access_mask,
296 access_granted,
297 nt_errstr(status) ));
298 return status;
301 return NT_STATUS_OK;
304 /****************************************************************************
305 Ensure when opening a base file for a stream open that we have permissions
306 to do so given the access mask on the base file.
307 ****************************************************************************/
309 static NTSTATUS check_base_file_access(struct connection_struct *conn,
310 struct smb_filename *smb_fname,
311 uint32_t access_mask)
313 NTSTATUS status;
315 status = smbd_calculate_access_mask(conn, smb_fname,
316 false,
317 access_mask,
318 &access_mask);
319 if (!NT_STATUS_IS_OK(status)) {
320 DEBUG(10, ("smbd_calculate_access_mask "
321 "on file %s returned %s\n",
322 smb_fname_str_dbg(smb_fname),
323 nt_errstr(status)));
324 return status;
327 if (access_mask & (FILE_WRITE_DATA|FILE_APPEND_DATA)) {
328 uint32_t dosattrs;
329 if (!CAN_WRITE(conn)) {
330 return NT_STATUS_ACCESS_DENIED;
332 dosattrs = dos_mode(conn, smb_fname);
333 if (IS_DOS_READONLY(dosattrs)) {
334 return NT_STATUS_ACCESS_DENIED;
338 return smbd_check_access_rights(conn,
339 smb_fname,
340 false,
341 access_mask);
344 /****************************************************************************
345 fd support routines - attempt to do a dos_open.
346 ****************************************************************************/
348 NTSTATUS fd_open(struct connection_struct *conn,
349 files_struct *fsp,
350 int flags,
351 mode_t mode)
353 struct smb_filename *smb_fname = fsp->fsp_name;
354 NTSTATUS status = NT_STATUS_OK;
356 #ifdef O_NOFOLLOW
358 * Never follow symlinks on a POSIX client. The
359 * client should be doing this.
362 if (fsp->posix_open || !lp_symlinks(SNUM(conn))) {
363 flags |= O_NOFOLLOW;
365 #endif
367 fsp->fh->fd = SMB_VFS_OPEN(conn, smb_fname, fsp, flags, mode);
368 if (fsp->fh->fd == -1) {
369 int posix_errno = errno;
370 #ifdef O_NOFOLLOW
371 #if defined(ENOTSUP) && defined(OSF1)
372 /* handle special Tru64 errno */
373 if (errno == ENOTSUP) {
374 posix_errno = ELOOP;
376 #endif /* ENOTSUP */
377 #ifdef EFTYPE
378 /* fix broken NetBSD errno */
379 if (errno == EFTYPE) {
380 posix_errno = ELOOP;
382 #endif /* EFTYPE */
383 /* fix broken FreeBSD errno */
384 if (errno == EMLINK) {
385 posix_errno = ELOOP;
387 #endif /* O_NOFOLLOW */
388 status = map_nt_error_from_unix(posix_errno);
389 if (errno == EMFILE) {
390 static time_t last_warned = 0L;
392 if (time((time_t *) NULL) > last_warned) {
393 DEBUG(0,("Too many open files, unable "
394 "to open more! smbd's max "
395 "open files = %d\n",
396 lp_max_open_files()));
397 last_warned = time((time_t *) NULL);
403 DEBUG(10,("fd_open: name %s, flags = 0%o mode = 0%o, fd = %d. %s\n",
404 smb_fname_str_dbg(smb_fname), flags, (int)mode, fsp->fh->fd,
405 (fsp->fh->fd == -1) ? strerror(errno) : "" ));
407 return status;
410 /****************************************************************************
411 Close the file associated with a fsp.
412 ****************************************************************************/
414 NTSTATUS fd_close(files_struct *fsp)
416 int ret;
418 if (fsp->dptr) {
419 dptr_CloseDir(fsp);
421 if (fsp->fh->fd == -1) {
422 return NT_STATUS_OK; /* What we used to call a stat open. */
424 if (fsp->fh->ref_count > 1) {
425 return NT_STATUS_OK; /* Shared handle. Only close last reference. */
428 ret = SMB_VFS_CLOSE(fsp);
429 fsp->fh->fd = -1;
430 if (ret == -1) {
431 return map_nt_error_from_unix(errno);
433 return NT_STATUS_OK;
436 /****************************************************************************
437 Change the ownership of a file to that of the parent directory.
438 Do this by fd if possible.
439 ****************************************************************************/
441 void change_file_owner_to_parent(connection_struct *conn,
442 const char *inherit_from_dir,
443 files_struct *fsp)
445 struct smb_filename *smb_fname_parent;
446 int ret;
448 smb_fname_parent = synthetic_smb_fname(talloc_tos(), inherit_from_dir,
449 NULL, NULL);
450 if (smb_fname_parent == NULL) {
451 return;
454 ret = SMB_VFS_STAT(conn, smb_fname_parent);
455 if (ret == -1) {
456 DEBUG(0,("change_file_owner_to_parent: failed to stat parent "
457 "directory %s. Error was %s\n",
458 smb_fname_str_dbg(smb_fname_parent),
459 strerror(errno)));
460 TALLOC_FREE(smb_fname_parent);
461 return;
464 if (smb_fname_parent->st.st_ex_uid == fsp->fsp_name->st.st_ex_uid) {
465 /* Already this uid - no need to change. */
466 DEBUG(10,("change_file_owner_to_parent: file %s "
467 "is already owned by uid %d\n",
468 fsp_str_dbg(fsp),
469 (int)fsp->fsp_name->st.st_ex_uid ));
470 TALLOC_FREE(smb_fname_parent);
471 return;
474 become_root();
475 ret = SMB_VFS_FCHOWN(fsp, smb_fname_parent->st.st_ex_uid, (gid_t)-1);
476 unbecome_root();
477 if (ret == -1) {
478 DEBUG(0,("change_file_owner_to_parent: failed to fchown "
479 "file %s to parent directory uid %u. Error "
480 "was %s\n", fsp_str_dbg(fsp),
481 (unsigned int)smb_fname_parent->st.st_ex_uid,
482 strerror(errno) ));
483 } else {
484 DEBUG(10,("change_file_owner_to_parent: changed new file %s to "
485 "parent directory uid %u.\n", fsp_str_dbg(fsp),
486 (unsigned int)smb_fname_parent->st.st_ex_uid));
487 /* Ensure the uid entry is updated. */
488 fsp->fsp_name->st.st_ex_uid = smb_fname_parent->st.st_ex_uid;
491 TALLOC_FREE(smb_fname_parent);
494 NTSTATUS change_dir_owner_to_parent(connection_struct *conn,
495 const char *inherit_from_dir,
496 const char *fname,
497 SMB_STRUCT_STAT *psbuf)
499 struct smb_filename *smb_fname_parent;
500 struct smb_filename *smb_fname_cwd = NULL;
501 char *saved_dir = NULL;
502 TALLOC_CTX *ctx = talloc_tos();
503 NTSTATUS status = NT_STATUS_OK;
504 int ret;
506 smb_fname_parent = synthetic_smb_fname(ctx, inherit_from_dir,
507 NULL, NULL);
508 if (smb_fname_parent == NULL) {
509 return NT_STATUS_NO_MEMORY;
512 ret = SMB_VFS_STAT(conn, smb_fname_parent);
513 if (ret == -1) {
514 status = map_nt_error_from_unix(errno);
515 DEBUG(0,("change_dir_owner_to_parent: failed to stat parent "
516 "directory %s. Error was %s\n",
517 smb_fname_str_dbg(smb_fname_parent),
518 strerror(errno)));
519 goto out;
522 /* We've already done an lstat into psbuf, and we know it's a
523 directory. If we can cd into the directory and the dev/ino
524 are the same then we can safely chown without races as
525 we're locking the directory in place by being in it. This
526 should work on any UNIX (thanks tridge :-). JRA.
529 saved_dir = vfs_GetWd(ctx,conn);
530 if (!saved_dir) {
531 status = map_nt_error_from_unix(errno);
532 DEBUG(0,("change_dir_owner_to_parent: failed to get "
533 "current working directory. Error was %s\n",
534 strerror(errno)));
535 goto out;
538 /* Chdir into the new path. */
539 if (vfs_ChDir(conn, fname) == -1) {
540 status = map_nt_error_from_unix(errno);
541 DEBUG(0,("change_dir_owner_to_parent: failed to change "
542 "current working directory to %s. Error "
543 "was %s\n", fname, strerror(errno) ));
544 goto chdir;
547 smb_fname_cwd = synthetic_smb_fname(ctx, ".", NULL, NULL);
548 if (smb_fname_cwd == NULL) {
549 status = NT_STATUS_NO_MEMORY;
550 goto chdir;
553 ret = SMB_VFS_STAT(conn, smb_fname_cwd);
554 if (ret == -1) {
555 status = map_nt_error_from_unix(errno);
556 DEBUG(0,("change_dir_owner_to_parent: failed to stat "
557 "directory '.' (%s) Error was %s\n",
558 fname, strerror(errno)));
559 goto chdir;
562 /* Ensure we're pointing at the same place. */
563 if (smb_fname_cwd->st.st_ex_dev != psbuf->st_ex_dev ||
564 smb_fname_cwd->st.st_ex_ino != psbuf->st_ex_ino) {
565 DEBUG(0,("change_dir_owner_to_parent: "
566 "device/inode on directory %s changed. "
567 "Refusing to chown !\n", fname ));
568 status = NT_STATUS_ACCESS_DENIED;
569 goto chdir;
572 if (smb_fname_parent->st.st_ex_uid == smb_fname_cwd->st.st_ex_uid) {
573 /* Already this uid - no need to change. */
574 DEBUG(10,("change_dir_owner_to_parent: directory %s "
575 "is already owned by uid %d\n",
576 fname,
577 (int)smb_fname_cwd->st.st_ex_uid ));
578 status = NT_STATUS_OK;
579 goto chdir;
582 become_root();
583 ret = SMB_VFS_LCHOWN(conn, ".", smb_fname_parent->st.st_ex_uid,
584 (gid_t)-1);
585 unbecome_root();
586 if (ret == -1) {
587 status = map_nt_error_from_unix(errno);
588 DEBUG(10,("change_dir_owner_to_parent: failed to chown "
589 "directory %s to parent directory uid %u. "
590 "Error was %s\n", fname,
591 (unsigned int)smb_fname_parent->st.st_ex_uid,
592 strerror(errno) ));
593 } else {
594 DEBUG(10,("change_dir_owner_to_parent: changed ownership of new "
595 "directory %s to parent directory uid %u.\n",
596 fname, (unsigned int)smb_fname_parent->st.st_ex_uid ));
597 /* Ensure the uid entry is updated. */
598 psbuf->st_ex_uid = smb_fname_parent->st.st_ex_uid;
601 chdir:
602 vfs_ChDir(conn,saved_dir);
603 out:
604 TALLOC_FREE(smb_fname_parent);
605 TALLOC_FREE(smb_fname_cwd);
606 return status;
609 /****************************************************************************
610 Open a file - returning a guaranteed ATOMIC indication of if the
611 file was created or not.
612 ****************************************************************************/
614 static NTSTATUS fd_open_atomic(struct connection_struct *conn,
615 files_struct *fsp,
616 int flags,
617 mode_t mode,
618 bool *file_created)
620 NTSTATUS status = NT_STATUS_UNSUCCESSFUL;
621 bool file_existed = VALID_STAT(fsp->fsp_name->st);
623 *file_created = false;
625 if (!(flags & O_CREAT)) {
627 * We're not creating the file, just pass through.
629 return fd_open(conn, fsp, flags, mode);
632 if (flags & O_EXCL) {
634 * Fail if already exists, just pass through.
636 status = fd_open(conn, fsp, flags, mode);
639 * Here we've opened with O_CREAT|O_EXCL. If that went
640 * NT_STATUS_OK, we *know* we created this file.
642 *file_created = NT_STATUS_IS_OK(status);
644 return status;
648 * Now it gets tricky. We have O_CREAT, but not O_EXCL.
649 * To know absolutely if we created the file or not,
650 * we can never call O_CREAT without O_EXCL. So if
651 * we think the file existed, try without O_CREAT|O_EXCL.
652 * If we think the file didn't exist, try with
653 * O_CREAT|O_EXCL. Keep bouncing between these two
654 * requests until either the file is created, or
655 * opened. Either way, we keep going until we get
656 * a returnable result (error, or open/create).
659 while(1) {
660 int curr_flags = flags;
662 if (file_existed) {
663 /* Just try open, do not create. */
664 curr_flags &= ~(O_CREAT);
665 status = fd_open(conn, fsp, curr_flags, mode);
666 if (NT_STATUS_EQUAL(status,
667 NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
669 * Someone deleted it in the meantime.
670 * Retry with O_EXCL.
672 file_existed = false;
673 DEBUG(10,("fd_open_atomic: file %s existed. "
674 "Retry.\n",
675 smb_fname_str_dbg(fsp->fsp_name)));
676 continue;
678 } else {
679 /* Try create exclusively, fail if it exists. */
680 curr_flags |= O_EXCL;
681 status = fd_open(conn, fsp, curr_flags, mode);
682 if (NT_STATUS_EQUAL(status,
683 NT_STATUS_OBJECT_NAME_COLLISION)) {
685 * Someone created it in the meantime.
686 * Retry without O_CREAT.
688 file_existed = true;
689 DEBUG(10,("fd_open_atomic: file %s "
690 "did not exist. Retry.\n",
691 smb_fname_str_dbg(fsp->fsp_name)));
692 continue;
694 if (NT_STATUS_IS_OK(status)) {
696 * Here we've opened with O_CREAT|O_EXCL
697 * and got success. We *know* we created
698 * this file.
700 *file_created = true;
703 /* Create is done, or failed. */
704 break;
706 return status;
709 /****************************************************************************
710 Open a file.
711 ****************************************************************************/
713 static NTSTATUS open_file(files_struct *fsp,
714 connection_struct *conn,
715 struct smb_request *req,
716 const char *parent_dir,
717 int flags,
718 mode_t unx_mode,
719 uint32 access_mask, /* client requested access mask. */
720 uint32 open_access_mask, /* what we're actually using in the open. */
721 bool *p_file_created)
723 struct smb_filename *smb_fname = fsp->fsp_name;
724 NTSTATUS status = NT_STATUS_OK;
725 int accmode = (flags & O_ACCMODE);
726 int local_flags = flags;
727 bool file_existed = VALID_STAT(fsp->fsp_name->st);
729 fsp->fh->fd = -1;
730 errno = EPERM;
732 /* Check permissions */
735 * This code was changed after seeing a client open request
736 * containing the open mode of (DENY_WRITE/read-only) with
737 * the 'create if not exist' bit set. The previous code
738 * would fail to open the file read only on a read-only share
739 * as it was checking the flags parameter directly against O_RDONLY,
740 * this was failing as the flags parameter was set to O_RDONLY|O_CREAT.
741 * JRA.
744 if (!CAN_WRITE(conn)) {
745 /* It's a read-only share - fail if we wanted to write. */
746 if(accmode != O_RDONLY || (flags & O_TRUNC) || (flags & O_APPEND)) {
747 DEBUG(3,("Permission denied opening %s\n",
748 smb_fname_str_dbg(smb_fname)));
749 return NT_STATUS_ACCESS_DENIED;
751 if (flags & O_CREAT) {
752 /* We don't want to write - but we must make sure that
753 O_CREAT doesn't create the file if we have write
754 access into the directory.
756 flags &= ~(O_CREAT|O_EXCL);
757 local_flags &= ~(O_CREAT|O_EXCL);
762 * This little piece of insanity is inspired by the
763 * fact that an NT client can open a file for O_RDONLY,
764 * but set the create disposition to FILE_EXISTS_TRUNCATE.
765 * If the client *can* write to the file, then it expects to
766 * truncate the file, even though it is opening for readonly.
767 * Quicken uses this stupid trick in backup file creation...
768 * Thanks *greatly* to "David W. Chapman Jr." <dwcjr@inethouston.net>
769 * for helping track this one down. It didn't bite us in 2.0.x
770 * as we always opened files read-write in that release. JRA.
773 if ((accmode == O_RDONLY) && ((flags & O_TRUNC) == O_TRUNC)) {
774 DEBUG(10,("open_file: truncate requested on read-only open "
775 "for file %s\n", smb_fname_str_dbg(smb_fname)));
776 local_flags = (flags & ~O_ACCMODE)|O_RDWR;
779 if ((open_access_mask & (FILE_READ_DATA|FILE_WRITE_DATA|FILE_APPEND_DATA|FILE_EXECUTE)) ||
780 (!file_existed && (local_flags & O_CREAT)) ||
781 ((local_flags & O_TRUNC) == O_TRUNC) ) {
782 const char *wild;
783 int ret;
785 #if defined(O_NONBLOCK) && defined(S_ISFIFO)
787 * We would block on opening a FIFO with no one else on the
788 * other end. Do what we used to do and add O_NONBLOCK to the
789 * open flags. JRA.
792 if (file_existed && S_ISFIFO(smb_fname->st.st_ex_mode)) {
793 local_flags &= ~O_TRUNC; /* Can't truncate a FIFO. */
794 local_flags |= O_NONBLOCK;
796 #endif
798 /* Don't create files with Microsoft wildcard characters. */
799 if (fsp->base_fsp) {
801 * wildcard characters are allowed in stream names
802 * only test the basefilename
804 wild = fsp->base_fsp->fsp_name->base_name;
805 } else {
806 wild = smb_fname->base_name;
808 if ((local_flags & O_CREAT) && !file_existed &&
809 ms_has_wild(wild)) {
810 return NT_STATUS_OBJECT_NAME_INVALID;
813 /* Can we access this file ? */
814 if (!fsp->base_fsp) {
815 /* Only do this check on non-stream open. */
816 if (file_existed) {
817 status = smbd_check_access_rights(conn,
818 smb_fname,
819 false,
820 access_mask);
821 } else if (local_flags & O_CREAT){
822 status = check_parent_access(conn,
823 smb_fname,
824 SEC_DIR_ADD_FILE);
825 } else {
826 /* File didn't exist and no O_CREAT. */
827 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
829 if (!NT_STATUS_IS_OK(status)) {
830 DEBUG(10,("open_file: "
831 "%s on file "
832 "%s returned %s\n",
833 file_existed ?
834 "smbd_check_access_rights" :
835 "check_parent_access",
836 smb_fname_str_dbg(smb_fname),
837 nt_errstr(status) ));
838 return status;
842 /* Actually do the open */
843 status = fd_open_atomic(conn, fsp, local_flags,
844 unx_mode, p_file_created);
845 if (!NT_STATUS_IS_OK(status)) {
846 DEBUG(3,("Error opening file %s (%s) (local_flags=%d) "
847 "(flags=%d)\n", smb_fname_str_dbg(smb_fname),
848 nt_errstr(status),local_flags,flags));
849 return status;
852 ret = SMB_VFS_FSTAT(fsp, &smb_fname->st);
853 if (ret == -1) {
854 /* If we have an fd, this stat should succeed. */
855 DEBUG(0,("Error doing fstat on open file %s "
856 "(%s)\n",
857 smb_fname_str_dbg(smb_fname),
858 strerror(errno) ));
859 status = map_nt_error_from_unix(errno);
860 fd_close(fsp);
861 return status;
864 if (*p_file_created) {
865 /* We created this file. */
867 bool need_re_stat = false;
868 /* Do all inheritance work after we've
869 done a successful fstat call and filled
870 in the stat struct in fsp->fsp_name. */
872 /* Inherit the ACL if required */
873 if (lp_inherit_perms(SNUM(conn))) {
874 inherit_access_posix_acl(conn, parent_dir,
875 smb_fname->base_name,
876 unx_mode);
877 need_re_stat = true;
880 /* Change the owner if required. */
881 if (lp_inherit_owner(SNUM(conn))) {
882 change_file_owner_to_parent(conn, parent_dir,
883 fsp);
884 need_re_stat = true;
887 if (need_re_stat) {
888 ret = SMB_VFS_FSTAT(fsp, &smb_fname->st);
889 /* If we have an fd, this stat should succeed. */
890 if (ret == -1) {
891 DEBUG(0,("Error doing fstat on open file %s "
892 "(%s)\n",
893 smb_fname_str_dbg(smb_fname),
894 strerror(errno) ));
898 notify_fname(conn, NOTIFY_ACTION_ADDED,
899 FILE_NOTIFY_CHANGE_FILE_NAME,
900 smb_fname->base_name);
902 } else {
903 fsp->fh->fd = -1; /* What we used to call a stat open. */
904 if (!file_existed) {
905 /* File must exist for a stat open. */
906 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
909 status = smbd_check_access_rights(conn,
910 smb_fname,
911 false,
912 access_mask);
914 if (NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND) &&
915 fsp->posix_open &&
916 S_ISLNK(smb_fname->st.st_ex_mode)) {
917 /* This is a POSIX stat open for delete
918 * or rename on a symlink that points
919 * nowhere. Allow. */
920 DEBUG(10,("open_file: allowing POSIX "
921 "open on bad symlink %s\n",
922 smb_fname_str_dbg(smb_fname)));
923 status = NT_STATUS_OK;
926 if (!NT_STATUS_IS_OK(status)) {
927 DEBUG(10,("open_file: "
928 "smbd_check_access_rights on file "
929 "%s returned %s\n",
930 smb_fname_str_dbg(smb_fname),
931 nt_errstr(status) ));
932 return status;
937 * POSIX allows read-only opens of directories. We don't
938 * want to do this (we use a different code path for this)
939 * so catch a directory open and return an EISDIR. JRA.
942 if(S_ISDIR(smb_fname->st.st_ex_mode)) {
943 fd_close(fsp);
944 errno = EISDIR;
945 return NT_STATUS_FILE_IS_A_DIRECTORY;
948 fsp->file_id = vfs_file_id_from_sbuf(conn, &smb_fname->st);
949 fsp->vuid = req ? req->vuid : UID_FIELD_INVALID;
950 fsp->file_pid = req ? req->smbpid : 0;
951 fsp->can_lock = True;
952 fsp->can_read = ((access_mask & FILE_READ_DATA) != 0);
953 fsp->can_write =
954 CAN_WRITE(conn) &&
955 ((access_mask & (FILE_WRITE_DATA | FILE_APPEND_DATA)) != 0);
956 fsp->print_file = NULL;
957 fsp->modified = False;
958 fsp->sent_oplock_break = NO_BREAK_SENT;
959 fsp->is_directory = False;
960 if (conn->aio_write_behind_list &&
961 is_in_path(smb_fname->base_name, conn->aio_write_behind_list,
962 conn->case_sensitive)) {
963 fsp->aio_write_behind = True;
966 fsp->wcp = NULL; /* Write cache pointer. */
968 DEBUG(2,("%s opened file %s read=%s write=%s (numopen=%d)\n",
969 conn->session_info->unix_info->unix_name,
970 smb_fname_str_dbg(smb_fname),
971 BOOLSTR(fsp->can_read), BOOLSTR(fsp->can_write),
972 conn->num_files_open));
974 errno = 0;
975 return NT_STATUS_OK;
978 /****************************************************************************
979 Check if we can open a file with a share mode.
980 Returns True if conflict, False if not.
981 ****************************************************************************/
983 static bool share_conflict(struct share_mode_entry *entry,
984 uint32 access_mask,
985 uint32 share_access)
987 DEBUG(10,("share_conflict: entry->access_mask = 0x%x, "
988 "entry->share_access = 0x%x, "
989 "entry->private_options = 0x%x\n",
990 (unsigned int)entry->access_mask,
991 (unsigned int)entry->share_access,
992 (unsigned int)entry->private_options));
994 if (server_id_is_disconnected(&entry->pid)) {
996 * note: cleanup should have been done by
997 * delay_for_batch_oplocks()
999 return false;
1002 DEBUG(10,("share_conflict: access_mask = 0x%x, share_access = 0x%x\n",
1003 (unsigned int)access_mask, (unsigned int)share_access));
1005 if ((entry->access_mask & (FILE_WRITE_DATA|
1006 FILE_APPEND_DATA|
1007 FILE_READ_DATA|
1008 FILE_EXECUTE|
1009 DELETE_ACCESS)) == 0) {
1010 DEBUG(10,("share_conflict: No conflict due to "
1011 "entry->access_mask = 0x%x\n",
1012 (unsigned int)entry->access_mask ));
1013 return False;
1016 if ((access_mask & (FILE_WRITE_DATA|
1017 FILE_APPEND_DATA|
1018 FILE_READ_DATA|
1019 FILE_EXECUTE|
1020 DELETE_ACCESS)) == 0) {
1021 DEBUG(10,("share_conflict: No conflict due to "
1022 "access_mask = 0x%x\n",
1023 (unsigned int)access_mask ));
1024 return False;
1027 #if 1 /* JRA TEST - Superdebug. */
1028 #define CHECK_MASK(num, am, right, sa, share) \
1029 DEBUG(10,("share_conflict: [%d] am (0x%x) & right (0x%x) = 0x%x\n", \
1030 (unsigned int)(num), (unsigned int)(am), \
1031 (unsigned int)(right), (unsigned int)(am)&(right) )); \
1032 DEBUG(10,("share_conflict: [%d] sa (0x%x) & share (0x%x) = 0x%x\n", \
1033 (unsigned int)(num), (unsigned int)(sa), \
1034 (unsigned int)(share), (unsigned int)(sa)&(share) )); \
1035 if (((am) & (right)) && !((sa) & (share))) { \
1036 DEBUG(10,("share_conflict: check %d conflict am = 0x%x, right = 0x%x, \
1037 sa = 0x%x, share = 0x%x\n", (num), (unsigned int)(am), (unsigned int)(right), (unsigned int)(sa), \
1038 (unsigned int)(share) )); \
1039 return True; \
1041 #else
1042 #define CHECK_MASK(num, am, right, sa, share) \
1043 if (((am) & (right)) && !((sa) & (share))) { \
1044 DEBUG(10,("share_conflict: check %d conflict am = 0x%x, right = 0x%x, \
1045 sa = 0x%x, share = 0x%x\n", (num), (unsigned int)(am), (unsigned int)(right), (unsigned int)(sa), \
1046 (unsigned int)(share) )); \
1047 return True; \
1049 #endif
1051 CHECK_MASK(1, entry->access_mask, FILE_WRITE_DATA | FILE_APPEND_DATA,
1052 share_access, FILE_SHARE_WRITE);
1053 CHECK_MASK(2, access_mask, FILE_WRITE_DATA | FILE_APPEND_DATA,
1054 entry->share_access, FILE_SHARE_WRITE);
1056 CHECK_MASK(3, entry->access_mask, FILE_READ_DATA | FILE_EXECUTE,
1057 share_access, FILE_SHARE_READ);
1058 CHECK_MASK(4, access_mask, FILE_READ_DATA | FILE_EXECUTE,
1059 entry->share_access, FILE_SHARE_READ);
1061 CHECK_MASK(5, entry->access_mask, DELETE_ACCESS,
1062 share_access, FILE_SHARE_DELETE);
1063 CHECK_MASK(6, access_mask, DELETE_ACCESS,
1064 entry->share_access, FILE_SHARE_DELETE);
1066 DEBUG(10,("share_conflict: No conflict.\n"));
1067 return False;
1070 #if defined(DEVELOPER)
1071 static void validate_my_share_entries(struct smbd_server_connection *sconn,
1072 int num,
1073 struct share_mode_entry *share_entry)
1075 struct server_id self = messaging_server_id(sconn->msg_ctx);
1076 files_struct *fsp;
1078 if (!serverid_equal(&self, &share_entry->pid)) {
1079 return;
1082 if (share_entry->share_file_id == 0) {
1083 /* INTERNAL_OPEN_ONLY */
1084 return;
1087 if (!is_valid_share_mode_entry(share_entry)) {
1088 return;
1091 fsp = file_find_dif(sconn, share_entry->id,
1092 share_entry->share_file_id);
1093 if (!fsp) {
1094 DEBUG(0,("validate_my_share_entries: PANIC : %s\n",
1095 share_mode_str(talloc_tos(), num, share_entry) ));
1096 smb_panic("validate_my_share_entries: Cannot match a "
1097 "share entry with an open file\n");
1100 if ((share_entry->op_type == NO_OPLOCK) &&
1101 (fsp->oplock_type == FAKE_LEVEL_II_OPLOCK))
1103 /* Someone has already written to it, but I haven't yet
1104 * noticed */
1105 return;
1108 if (((uint16)fsp->oplock_type) != share_entry->op_type) {
1109 goto panic;
1112 return;
1114 panic:
1116 char *str;
1117 DEBUG(0,("validate_my_share_entries: PANIC : %s\n",
1118 share_mode_str(talloc_tos(), num, share_entry) ));
1119 str = talloc_asprintf(talloc_tos(),
1120 "validate_my_share_entries: "
1121 "file %s, oplock_type = 0x%x, op_type = 0x%x\n",
1122 fsp->fsp_name->base_name,
1123 (unsigned int)fsp->oplock_type,
1124 (unsigned int)share_entry->op_type );
1125 smb_panic(str);
1128 #endif
1130 bool is_stat_open(uint32 access_mask)
1132 const uint32_t stat_open_bits =
1133 (SYNCHRONIZE_ACCESS|
1134 FILE_READ_ATTRIBUTES|
1135 FILE_WRITE_ATTRIBUTES);
1137 return (((access_mask & stat_open_bits) != 0) &&
1138 ((access_mask & ~stat_open_bits) == 0));
1141 /****************************************************************************
1142 Deal with share modes
1143 Invarient: Share mode must be locked on entry and exit.
1144 Returns -1 on error, or number of share modes on success (may be zero).
1145 ****************************************************************************/
1147 static NTSTATUS open_mode_check(connection_struct *conn,
1148 struct share_mode_lock *lck,
1149 uint32_t name_hash,
1150 uint32 access_mask,
1151 uint32 share_access,
1152 uint32 create_options,
1153 bool *file_existed)
1155 int i;
1157 if(lck->data->num_share_modes == 0) {
1158 return NT_STATUS_OK;
1161 /* A delete on close prohibits everything */
1163 if (is_delete_on_close_set(lck, name_hash)) {
1165 * Check the delete on close token
1166 * is valid. It could have been left
1167 * after a server crash.
1169 for(i = 0; i < lck->data->num_share_modes; i++) {
1170 if (!share_mode_stale_pid(lck->data, i)) {
1172 *file_existed = true;
1174 return NT_STATUS_DELETE_PENDING;
1177 return NT_STATUS_OK;
1180 if (is_stat_open(access_mask)) {
1181 /* Stat open that doesn't trigger oplock breaks or share mode
1182 * checks... ! JRA. */
1183 return NT_STATUS_OK;
1187 * Check if the share modes will give us access.
1190 #if defined(DEVELOPER)
1191 for(i = 0; i < lck->data->num_share_modes; i++) {
1192 validate_my_share_entries(conn->sconn, i,
1193 &lck->data->share_modes[i]);
1195 #endif
1197 /* Now we check the share modes, after any oplock breaks. */
1198 for(i = 0; i < lck->data->num_share_modes; i++) {
1200 if (!is_valid_share_mode_entry(&lck->data->share_modes[i])) {
1201 continue;
1204 /* someone else has a share lock on it, check to see if we can
1205 * too */
1206 if (share_conflict(&lck->data->share_modes[i],
1207 access_mask, share_access)) {
1209 if (share_mode_stale_pid(lck->data, i)) {
1210 continue;
1213 *file_existed = true;
1215 return NT_STATUS_SHARING_VIOLATION;
1219 if (lck->data->num_share_modes != 0) {
1220 *file_existed = true;
1223 return NT_STATUS_OK;
1227 * Send a break message to the oplock holder and delay the open for
1228 * our client.
1231 static NTSTATUS send_break_message(files_struct *fsp,
1232 struct share_mode_entry *exclusive,
1233 uint64_t mid,
1234 int oplock_request)
1236 NTSTATUS status;
1237 char msg[MSG_SMB_SHARE_MODE_ENTRY_SIZE];
1239 DEBUG(10, ("Sending break request to PID %s\n",
1240 procid_str_static(&exclusive->pid)));
1241 exclusive->op_mid = mid;
1243 /* Create the message. */
1244 share_mode_entry_to_message(msg, exclusive);
1246 /* Add in the FORCE_OPLOCK_BREAK_TO_NONE bit in the message if set. We
1247 don't want this set in the share mode struct pointed to by lck. */
1249 if (oplock_request & FORCE_OPLOCK_BREAK_TO_NONE) {
1250 SSVAL(msg,OP_BREAK_MSG_OP_TYPE_OFFSET,
1251 exclusive->op_type | FORCE_OPLOCK_BREAK_TO_NONE);
1254 status = messaging_send_buf(fsp->conn->sconn->msg_ctx, exclusive->pid,
1255 MSG_SMB_BREAK_REQUEST,
1256 (uint8 *)msg,
1257 MSG_SMB_SHARE_MODE_ENTRY_SIZE);
1258 if (!NT_STATUS_IS_OK(status)) {
1259 DEBUG(3, ("Could not send oplock break message: %s\n",
1260 nt_errstr(status)));
1263 return status;
1267 * Return share_mode_entry pointers for :
1268 * 1). Batch oplock entry.
1269 * 2). Batch or exclusive oplock entry (may be identical to #1).
1270 * bool have_level2_oplock
1271 * bool have_no_oplock.
1272 * Do internal consistency checks on the share mode for a file.
1275 static void find_oplock_types(files_struct *fsp,
1276 int oplock_request,
1277 const struct share_mode_lock *lck,
1278 struct share_mode_entry **pp_batch,
1279 struct share_mode_entry **pp_ex_or_batch,
1280 bool *got_level2,
1281 bool *got_no_oplock)
1283 int i;
1285 *pp_batch = NULL;
1286 *pp_ex_or_batch = NULL;
1287 *got_level2 = false;
1288 *got_no_oplock = false;
1290 /* Ignore stat or internal opens, as is done in
1291 delay_for_batch_oplocks() and
1292 delay_for_exclusive_oplocks().
1294 if ((oplock_request & INTERNAL_OPEN_ONLY) || is_stat_open(fsp->access_mask)) {
1295 return;
1298 for (i=0; i<lck->data->num_share_modes; i++) {
1299 struct share_mode_entry *e = &lck->data->share_modes[i];
1301 if (!is_valid_share_mode_entry(e)) {
1302 continue;
1305 if (e->op_type == NO_OPLOCK && is_stat_open(e->access_mask)) {
1306 /* We ignore stat opens in the table - they
1307 always have NO_OPLOCK and never get or
1308 cause breaks. JRA. */
1309 continue;
1312 if (BATCH_OPLOCK_TYPE(e->op_type)) {
1313 /* batch - can only be one. */
1314 if (share_mode_stale_pid(lck->data, i)) {
1315 DEBUG(10, ("Found stale batch oplock\n"));
1316 continue;
1318 if (*pp_ex_or_batch || *pp_batch || *got_level2 || *got_no_oplock) {
1319 smb_panic("Bad batch oplock entry.");
1321 *pp_batch = e;
1324 if (EXCLUSIVE_OPLOCK_TYPE(e->op_type)) {
1325 if (share_mode_stale_pid(lck->data, i)) {
1326 DEBUG(10, ("Found stale duplicate oplock\n"));
1327 continue;
1329 /* Exclusive or batch - can only be one. */
1330 if (*pp_ex_or_batch || *got_level2 || *got_no_oplock) {
1331 smb_panic("Bad exclusive or batch oplock entry.");
1333 *pp_ex_or_batch = e;
1336 if (LEVEL_II_OPLOCK_TYPE(e->op_type)) {
1337 if (*pp_batch || *pp_ex_or_batch) {
1338 if (share_mode_stale_pid(lck->data, i)) {
1339 DEBUG(10, ("Found stale LevelII "
1340 "oplock\n"));
1341 continue;
1343 smb_panic("Bad levelII oplock entry.");
1345 *got_level2 = true;
1348 if (e->op_type == NO_OPLOCK) {
1349 if (*pp_batch || *pp_ex_or_batch) {
1350 if (share_mode_stale_pid(lck->data, i)) {
1351 DEBUG(10, ("Found stale NO_OPLOCK "
1352 "entry\n"));
1353 continue;
1355 smb_panic("Bad no oplock entry.");
1357 *got_no_oplock = true;
1362 static bool delay_for_batch_oplocks(files_struct *fsp,
1363 uint64_t mid,
1364 int oplock_request,
1365 struct share_mode_entry *batch_entry)
1367 if ((oplock_request & INTERNAL_OPEN_ONLY) || is_stat_open(fsp->access_mask)) {
1368 return false;
1370 if (batch_entry == NULL) {
1371 return false;
1374 if (server_id_is_disconnected(&batch_entry->pid)) {
1376 * TODO: clean up.
1377 * This could be achieved by sending a break message
1378 * to ourselves. Special considerations for files
1379 * with delete_on_close flag set!
1381 * For now we keep it simple and do not
1382 * allow delete on close for durable handles.
1384 return false;
1387 /* Found a batch oplock */
1388 send_break_message(fsp, batch_entry, mid, oplock_request);
1389 return true;
1392 static bool delay_for_exclusive_oplocks(files_struct *fsp,
1393 uint64_t mid,
1394 int oplock_request,
1395 struct share_mode_entry *ex_entry)
1397 if ((oplock_request & INTERNAL_OPEN_ONLY) || is_stat_open(fsp->access_mask)) {
1398 return false;
1400 if (ex_entry == NULL) {
1401 return false;
1404 if (server_id_is_disconnected(&ex_entry->pid)) {
1406 * since only durable handles can get disconnected,
1407 * and we can only get durable handles with batch oplocks,
1408 * this should actually never be reached...
1410 return false;
1413 send_break_message(fsp, ex_entry, mid, oplock_request);
1414 return true;
1417 static bool file_has_brlocks(files_struct *fsp)
1419 struct byte_range_lock *br_lck;
1421 br_lck = brl_get_locks_readonly(fsp);
1422 if (!br_lck)
1423 return false;
1425 return br_lck->num_locks > 0 ? true : false;
1428 static void grant_fsp_oplock_type(files_struct *fsp,
1429 int oplock_request,
1430 bool got_level2_oplock,
1431 bool got_a_none_oplock)
1433 bool allow_level2 = (global_client_caps & CAP_LEVEL_II_OPLOCKS) &&
1434 lp_level2_oplocks(SNUM(fsp->conn));
1436 /* Start by granting what the client asked for,
1437 but ensure no SAMBA_PRIVATE bits can be set. */
1438 fsp->oplock_type = (oplock_request & ~SAMBA_PRIVATE_OPLOCK_MASK);
1440 if (oplock_request & INTERNAL_OPEN_ONLY) {
1441 /* No oplocks on internal open. */
1442 fsp->oplock_type = NO_OPLOCK;
1443 DEBUG(10,("grant_fsp_oplock_type: oplock type 0x%x on file %s\n",
1444 fsp->oplock_type, fsp_str_dbg(fsp)));
1445 return;
1448 if (lp_locking(fsp->conn->params) && file_has_brlocks(fsp)) {
1449 DEBUG(10,("grant_fsp_oplock_type: file %s has byte range locks\n",
1450 fsp_str_dbg(fsp)));
1451 fsp->oplock_type = NO_OPLOCK;
1454 if (is_stat_open(fsp->access_mask)) {
1455 /* Leave the value already set. */
1456 DEBUG(10,("grant_fsp_oplock_type: oplock type 0x%x on file %s\n",
1457 fsp->oplock_type, fsp_str_dbg(fsp)));
1458 return;
1462 * Match what was requested (fsp->oplock_type) with
1463 * what was found in the existing share modes.
1466 if (got_a_none_oplock) {
1467 fsp->oplock_type = NO_OPLOCK;
1468 } else if (got_level2_oplock) {
1469 if (fsp->oplock_type == NO_OPLOCK ||
1470 fsp->oplock_type == FAKE_LEVEL_II_OPLOCK) {
1471 /* Store a level2 oplock, but don't tell the client */
1472 fsp->oplock_type = FAKE_LEVEL_II_OPLOCK;
1473 } else {
1474 fsp->oplock_type = LEVEL_II_OPLOCK;
1476 } else {
1477 /* All share_mode_entries are placeholders or deferred.
1478 * Silently upgrade to fake levelII if the client didn't
1479 * ask for an oplock. */
1480 if (fsp->oplock_type == NO_OPLOCK) {
1481 /* Store a level2 oplock, but don't tell the client */
1482 fsp->oplock_type = FAKE_LEVEL_II_OPLOCK;
1487 * Don't grant level2 to clients that don't want them
1488 * or if we've turned them off.
1490 if (fsp->oplock_type == LEVEL_II_OPLOCK && !allow_level2) {
1491 fsp->oplock_type = FAKE_LEVEL_II_OPLOCK;
1494 DEBUG(10,("grant_fsp_oplock_type: oplock type 0x%x on file %s\n",
1495 fsp->oplock_type, fsp_str_dbg(fsp)));
1498 static bool request_timed_out(struct timeval request_time,
1499 struct timeval timeout)
1501 struct timeval now, end_time;
1502 GetTimeOfDay(&now);
1503 end_time = timeval_sum(&request_time, &timeout);
1504 return (timeval_compare(&end_time, &now) < 0);
1507 struct defer_open_state {
1508 struct smbd_server_connection *sconn;
1509 uint64_t mid;
1512 static void defer_open_done(struct tevent_req *req);
1514 /****************************************************************************
1515 Handle the 1 second delay in returning a SHARING_VIOLATION error.
1516 ****************************************************************************/
1518 static void defer_open(struct share_mode_lock *lck,
1519 struct timeval request_time,
1520 struct timeval timeout,
1521 struct smb_request *req,
1522 struct deferred_open_record *state)
1524 DEBUG(10,("defer_open_sharing_error: time [%u.%06u] adding deferred "
1525 "open entry for mid %llu\n",
1526 (unsigned int)request_time.tv_sec,
1527 (unsigned int)request_time.tv_usec,
1528 (unsigned long long)req->mid));
1530 if (!push_deferred_open_message_smb(req, request_time, timeout,
1531 state->id, (char *)state, sizeof(*state))) {
1532 TALLOC_FREE(lck);
1533 exit_server("push_deferred_open_message_smb failed");
1535 if (lck) {
1536 struct defer_open_state *watch_state;
1537 struct tevent_req *watch_req;
1538 bool ret;
1540 watch_state = talloc(req->sconn, struct defer_open_state);
1541 if (watch_state == NULL) {
1542 exit_server("talloc failed");
1544 watch_state->sconn = req->sconn;
1545 watch_state->mid = req->mid;
1547 DEBUG(10, ("defering mid %llu\n",
1548 (unsigned long long)req->mid));
1550 watch_req = dbwrap_record_watch_send(
1551 watch_state, req->sconn->ev_ctx, lck->data->record,
1552 req->sconn->msg_ctx);
1553 if (watch_req == NULL) {
1554 exit_server("Could not watch share mode record");
1556 tevent_req_set_callback(watch_req, defer_open_done,
1557 watch_state);
1559 ret = tevent_req_set_endtime(
1560 watch_req, req->sconn->ev_ctx,
1561 timeval_sum(&request_time, &timeout));
1562 SMB_ASSERT(ret);
1566 static void defer_open_done(struct tevent_req *req)
1568 struct defer_open_state *state = tevent_req_callback_data(
1569 req, struct defer_open_state);
1570 NTSTATUS status;
1571 bool ret;
1573 status = dbwrap_record_watch_recv(req, talloc_tos(), NULL);
1574 TALLOC_FREE(req);
1575 if (!NT_STATUS_IS_OK(status)) {
1576 DEBUG(5, ("dbwrap_record_watch_recv returned %s\n",
1577 nt_errstr(status)));
1579 * Even if it failed, retry anyway. TODO: We need a way to
1580 * tell a re-scheduled open about that error.
1584 DEBUG(10, ("scheduling mid %llu\n", (unsigned long long)state->mid));
1586 ret = schedule_deferred_open_message_smb(state->sconn, state->mid);
1587 SMB_ASSERT(ret);
1588 TALLOC_FREE(state);
1592 /****************************************************************************
1593 On overwrite open ensure that the attributes match.
1594 ****************************************************************************/
1596 static bool open_match_attributes(connection_struct *conn,
1597 uint32 old_dos_attr,
1598 uint32 new_dos_attr,
1599 mode_t existing_unx_mode,
1600 mode_t new_unx_mode,
1601 mode_t *returned_unx_mode)
1603 uint32 noarch_old_dos_attr, noarch_new_dos_attr;
1605 noarch_old_dos_attr = (old_dos_attr & ~FILE_ATTRIBUTE_ARCHIVE);
1606 noarch_new_dos_attr = (new_dos_attr & ~FILE_ATTRIBUTE_ARCHIVE);
1608 if((noarch_old_dos_attr == 0 && noarch_new_dos_attr != 0) ||
1609 (noarch_old_dos_attr != 0 && ((noarch_old_dos_attr & noarch_new_dos_attr) == noarch_old_dos_attr))) {
1610 *returned_unx_mode = new_unx_mode;
1611 } else {
1612 *returned_unx_mode = (mode_t)0;
1615 DEBUG(10,("open_match_attributes: old_dos_attr = 0x%x, "
1616 "existing_unx_mode = 0%o, new_dos_attr = 0x%x "
1617 "returned_unx_mode = 0%o\n",
1618 (unsigned int)old_dos_attr,
1619 (unsigned int)existing_unx_mode,
1620 (unsigned int)new_dos_attr,
1621 (unsigned int)*returned_unx_mode ));
1623 /* If we're mapping SYSTEM and HIDDEN ensure they match. */
1624 if (lp_map_system(SNUM(conn)) || lp_store_dos_attributes(SNUM(conn))) {
1625 if ((old_dos_attr & FILE_ATTRIBUTE_SYSTEM) &&
1626 !(new_dos_attr & FILE_ATTRIBUTE_SYSTEM)) {
1627 return False;
1630 if (lp_map_hidden(SNUM(conn)) || lp_store_dos_attributes(SNUM(conn))) {
1631 if ((old_dos_attr & FILE_ATTRIBUTE_HIDDEN) &&
1632 !(new_dos_attr & FILE_ATTRIBUTE_HIDDEN)) {
1633 return False;
1636 return True;
1639 /****************************************************************************
1640 Special FCB or DOS processing in the case of a sharing violation.
1641 Try and find a duplicated file handle.
1642 ****************************************************************************/
1644 static NTSTATUS fcb_or_dos_open(struct smb_request *req,
1645 connection_struct *conn,
1646 files_struct *fsp_to_dup_into,
1647 const struct smb_filename *smb_fname,
1648 struct file_id id,
1649 uint16 file_pid,
1650 uint64_t vuid,
1651 uint32 access_mask,
1652 uint32 share_access,
1653 uint32 create_options)
1655 files_struct *fsp;
1657 DEBUG(5,("fcb_or_dos_open: attempting old open semantics for "
1658 "file %s.\n", smb_fname_str_dbg(smb_fname)));
1660 for(fsp = file_find_di_first(conn->sconn, id); fsp;
1661 fsp = file_find_di_next(fsp)) {
1663 DEBUG(10,("fcb_or_dos_open: checking file %s, fd = %d, "
1664 "vuid = %llu, file_pid = %u, private_options = 0x%x "
1665 "access_mask = 0x%x\n", fsp_str_dbg(fsp),
1666 fsp->fh->fd, (unsigned long long)fsp->vuid,
1667 (unsigned int)fsp->file_pid,
1668 (unsigned int)fsp->fh->private_options,
1669 (unsigned int)fsp->access_mask ));
1671 if (fsp != fsp_to_dup_into &&
1672 fsp->fh->fd != -1 &&
1673 fsp->vuid == vuid &&
1674 fsp->file_pid == file_pid &&
1675 (fsp->fh->private_options & (NTCREATEX_OPTIONS_PRIVATE_DENY_DOS |
1676 NTCREATEX_OPTIONS_PRIVATE_DENY_FCB)) &&
1677 (fsp->access_mask & FILE_WRITE_DATA) &&
1678 strequal(fsp->fsp_name->base_name, smb_fname->base_name) &&
1679 strequal(fsp->fsp_name->stream_name,
1680 smb_fname->stream_name)) {
1681 DEBUG(10,("fcb_or_dos_open: file match\n"));
1682 break;
1686 if (!fsp) {
1687 return NT_STATUS_NOT_FOUND;
1690 /* quite an insane set of semantics ... */
1691 if (is_executable(smb_fname->base_name) &&
1692 (fsp->fh->private_options & NTCREATEX_OPTIONS_PRIVATE_DENY_DOS)) {
1693 DEBUG(10,("fcb_or_dos_open: file fail due to is_executable.\n"));
1694 return NT_STATUS_INVALID_PARAMETER;
1697 /* We need to duplicate this fsp. */
1698 return dup_file_fsp(req, fsp, access_mask, share_access,
1699 create_options, fsp_to_dup_into);
1702 static void schedule_defer_open(struct share_mode_lock *lck,
1703 struct timeval request_time,
1704 struct smb_request *req)
1706 struct deferred_open_record state;
1708 /* This is a relative time, added to the absolute
1709 request_time value to get the absolute timeout time.
1710 Note that if this is the second or greater time we enter
1711 this codepath for this particular request mid then
1712 request_time is left as the absolute time of the *first*
1713 time this request mid was processed. This is what allows
1714 the request to eventually time out. */
1716 struct timeval timeout;
1718 /* Normally the smbd we asked should respond within
1719 * OPLOCK_BREAK_TIMEOUT seconds regardless of whether
1720 * the client did, give twice the timeout as a safety
1721 * measure here in case the other smbd is stuck
1722 * somewhere else. */
1724 timeout = timeval_set(OPLOCK_BREAK_TIMEOUT*2, 0);
1726 /* Nothing actually uses state.delayed_for_oplocks
1727 but it's handy to differentiate in debug messages
1728 between a 30 second delay due to oplock break, and
1729 a 1 second delay for share mode conflicts. */
1731 state.delayed_for_oplocks = True;
1732 state.async_open = false;
1733 state.id = lck->data->id;
1735 if (!request_timed_out(request_time, timeout)) {
1736 defer_open(lck, request_time, timeout, req, &state);
1740 /****************************************************************************
1741 Reschedule an open call that went asynchronous.
1742 ****************************************************************************/
1744 static void schedule_async_open(struct timeval request_time,
1745 struct smb_request *req)
1747 struct deferred_open_record state;
1748 struct timeval timeout;
1750 timeout = timeval_set(20, 0);
1752 ZERO_STRUCT(state);
1753 state.delayed_for_oplocks = false;
1754 state.async_open = true;
1756 if (!request_timed_out(request_time, timeout)) {
1757 defer_open(NULL, request_time, timeout, req, &state);
1761 /****************************************************************************
1762 Work out what access_mask to use from what the client sent us.
1763 ****************************************************************************/
1765 static NTSTATUS smbd_calculate_maximum_allowed_access(
1766 connection_struct *conn,
1767 const struct smb_filename *smb_fname,
1768 bool use_privs,
1769 uint32_t *p_access_mask)
1771 struct security_descriptor *sd;
1772 uint32_t access_granted;
1773 NTSTATUS status;
1775 if (!use_privs && (get_current_uid(conn) == (uid_t)0)) {
1776 *p_access_mask |= FILE_GENERIC_ALL;
1777 return NT_STATUS_OK;
1780 status = SMB_VFS_GET_NT_ACL(conn, smb_fname->base_name,
1781 (SECINFO_OWNER |
1782 SECINFO_GROUP |
1783 SECINFO_DACL),
1784 talloc_tos(), &sd);
1786 if (NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
1788 * File did not exist
1790 *p_access_mask = FILE_GENERIC_ALL;
1791 return NT_STATUS_OK;
1793 if (!NT_STATUS_IS_OK(status)) {
1794 DEBUG(10,("Could not get acl on file %s: %s\n",
1795 smb_fname_str_dbg(smb_fname),
1796 nt_errstr(status)));
1797 return NT_STATUS_ACCESS_DENIED;
1801 * If we can access the path to this file, by
1802 * default we have FILE_READ_ATTRIBUTES from the
1803 * containing directory. See the section:
1804 * "Algorithm to Check Access to an Existing File"
1805 * in MS-FSA.pdf.
1807 * se_file_access_check()
1808 * also takes care of owner WRITE_DAC and READ_CONTROL.
1810 status = se_file_access_check(sd,
1811 get_current_nttok(conn),
1812 use_privs,
1813 (*p_access_mask & ~FILE_READ_ATTRIBUTES),
1814 &access_granted);
1816 TALLOC_FREE(sd);
1818 if (!NT_STATUS_IS_OK(status)) {
1819 DEBUG(10, ("Access denied on file %s: "
1820 "when calculating maximum access\n",
1821 smb_fname_str_dbg(smb_fname)));
1822 return NT_STATUS_ACCESS_DENIED;
1824 *p_access_mask = (access_granted | FILE_READ_ATTRIBUTES);
1826 if (!(access_granted & DELETE_ACCESS)) {
1827 if (can_delete_file_in_directory(conn, smb_fname)) {
1828 *p_access_mask |= DELETE_ACCESS;
1832 return NT_STATUS_OK;
1835 NTSTATUS smbd_calculate_access_mask(connection_struct *conn,
1836 const struct smb_filename *smb_fname,
1837 bool use_privs,
1838 uint32_t access_mask,
1839 uint32_t *access_mask_out)
1841 NTSTATUS status;
1842 uint32_t orig_access_mask = access_mask;
1843 uint32_t rejected_share_access;
1846 * Convert GENERIC bits to specific bits.
1849 se_map_generic(&access_mask, &file_generic_mapping);
1851 /* Calculate MAXIMUM_ALLOWED_ACCESS if requested. */
1852 if (access_mask & MAXIMUM_ALLOWED_ACCESS) {
1854 status = smbd_calculate_maximum_allowed_access(
1855 conn, smb_fname, use_privs, &access_mask);
1857 if (!NT_STATUS_IS_OK(status)) {
1858 return status;
1861 access_mask &= conn->share_access;
1864 rejected_share_access = access_mask & ~(conn->share_access);
1866 if (rejected_share_access) {
1867 DEBUG(10, ("smbd_calculate_access_mask: Access denied on "
1868 "file %s: rejected by share access mask[0x%08X] "
1869 "orig[0x%08X] mapped[0x%08X] reject[0x%08X]\n",
1870 smb_fname_str_dbg(smb_fname),
1871 conn->share_access,
1872 orig_access_mask, access_mask,
1873 rejected_share_access));
1874 return NT_STATUS_ACCESS_DENIED;
1877 *access_mask_out = access_mask;
1878 return NT_STATUS_OK;
1881 /****************************************************************************
1882 Remove the deferred open entry under lock.
1883 ****************************************************************************/
1885 /****************************************************************************
1886 Return true if this is a state pointer to an asynchronous create.
1887 ****************************************************************************/
1889 bool is_deferred_open_async(const void *ptr)
1891 const struct deferred_open_record *state = (const struct deferred_open_record *)ptr;
1893 return state->async_open;
1896 static bool clear_ads(uint32_t create_disposition)
1898 bool ret = false;
1900 switch (create_disposition) {
1901 case FILE_SUPERSEDE:
1902 case FILE_OVERWRITE_IF:
1903 case FILE_OVERWRITE:
1904 ret = true;
1905 break;
1906 default:
1907 break;
1909 return ret;
1912 static int disposition_to_open_flags(uint32_t create_disposition)
1914 int ret = 0;
1917 * Currently we're using FILE_SUPERSEDE as the same as
1918 * FILE_OVERWRITE_IF but they really are
1919 * different. FILE_SUPERSEDE deletes an existing file
1920 * (requiring delete access) then recreates it.
1923 switch (create_disposition) {
1924 case FILE_SUPERSEDE:
1925 case FILE_OVERWRITE_IF:
1927 * If file exists replace/overwrite. If file doesn't
1928 * exist create.
1930 ret = O_CREAT|O_TRUNC;
1931 break;
1933 case FILE_OPEN:
1935 * If file exists open. If file doesn't exist error.
1937 ret = 0;
1938 break;
1940 case FILE_OVERWRITE:
1942 * If file exists overwrite. If file doesn't exist
1943 * error.
1945 ret = O_TRUNC;
1946 break;
1948 case FILE_CREATE:
1950 * If file exists error. If file doesn't exist create.
1952 ret = O_CREAT|O_EXCL;
1953 break;
1955 case FILE_OPEN_IF:
1957 * If file exists open. If file doesn't exist create.
1959 ret = O_CREAT;
1960 break;
1962 return ret;
1965 static int calculate_open_access_flags(uint32_t access_mask,
1966 int oplock_request,
1967 uint32_t private_flags)
1969 bool need_write, need_read;
1972 * Note that we ignore the append flag as append does not
1973 * mean the same thing under DOS and Unix.
1976 need_write =
1977 ((access_mask & (FILE_WRITE_DATA | FILE_APPEND_DATA)) ||
1978 (oplock_request & FORCE_OPLOCK_BREAK_TO_NONE));
1980 if (!need_write) {
1981 return O_RDONLY;
1984 /* DENY_DOS opens are always underlying read-write on the
1985 file handle, no matter what the requested access mask
1986 says. */
1988 need_read =
1989 ((private_flags & NTCREATEX_OPTIONS_PRIVATE_DENY_DOS) ||
1990 access_mask & (FILE_READ_ATTRIBUTES|FILE_READ_DATA|
1991 FILE_READ_EA|FILE_EXECUTE));
1993 if (!need_read) {
1994 return O_WRONLY;
1996 return O_RDWR;
1999 /****************************************************************************
2000 Open a file with a share mode. Passed in an already created files_struct *.
2001 ****************************************************************************/
2003 static NTSTATUS open_file_ntcreate(connection_struct *conn,
2004 struct smb_request *req,
2005 uint32 access_mask, /* access bits (FILE_READ_DATA etc.) */
2006 uint32 share_access, /* share constants (FILE_SHARE_READ etc) */
2007 uint32 create_disposition, /* FILE_OPEN_IF etc. */
2008 uint32 create_options, /* options such as delete on close. */
2009 uint32 new_dos_attributes, /* attributes used for new file. */
2010 int oplock_request, /* internal Samba oplock codes. */
2011 /* Information (FILE_EXISTS etc.) */
2012 uint32_t private_flags, /* Samba specific flags. */
2013 int *pinfo,
2014 files_struct *fsp)
2016 struct smb_filename *smb_fname = fsp->fsp_name;
2017 int flags=0;
2018 int flags2=0;
2019 bool file_existed = VALID_STAT(smb_fname->st);
2020 bool def_acl = False;
2021 bool posix_open = False;
2022 bool new_file_created = False;
2023 bool first_open_attempt = true;
2024 NTSTATUS fsp_open = NT_STATUS_ACCESS_DENIED;
2025 mode_t new_unx_mode = (mode_t)0;
2026 mode_t unx_mode = (mode_t)0;
2027 int info;
2028 uint32 existing_dos_attributes = 0;
2029 struct timeval request_time = timeval_zero();
2030 struct share_mode_lock *lck = NULL;
2031 uint32 open_access_mask = access_mask;
2032 NTSTATUS status;
2033 char *parent_dir;
2034 SMB_STRUCT_STAT saved_stat = smb_fname->st;
2035 struct share_mode_entry *batch_entry = NULL;
2036 struct share_mode_entry *exclusive_entry = NULL;
2037 bool got_level2_oplock = false;
2038 bool got_a_none_oplock = false;
2039 struct timespec old_write_time;
2040 struct file_id id;
2042 if (conn->printer) {
2044 * Printers are handled completely differently.
2045 * Most of the passed parameters are ignored.
2048 if (pinfo) {
2049 *pinfo = FILE_WAS_CREATED;
2052 DEBUG(10, ("open_file_ntcreate: printer open fname=%s\n",
2053 smb_fname_str_dbg(smb_fname)));
2055 if (!req) {
2056 DEBUG(0,("open_file_ntcreate: printer open without "
2057 "an SMB request!\n"));
2058 return NT_STATUS_INTERNAL_ERROR;
2061 return print_spool_open(fsp, smb_fname->base_name,
2062 req->vuid);
2065 if (!parent_dirname(talloc_tos(), smb_fname->base_name, &parent_dir,
2066 NULL)) {
2067 return NT_STATUS_NO_MEMORY;
2070 if (new_dos_attributes & FILE_FLAG_POSIX_SEMANTICS) {
2071 posix_open = True;
2072 unx_mode = (mode_t)(new_dos_attributes & ~FILE_FLAG_POSIX_SEMANTICS);
2073 new_dos_attributes = 0;
2074 } else {
2075 /* Windows allows a new file to be created and
2076 silently removes a FILE_ATTRIBUTE_DIRECTORY
2077 sent by the client. Do the same. */
2079 new_dos_attributes &= ~FILE_ATTRIBUTE_DIRECTORY;
2081 /* We add FILE_ATTRIBUTE_ARCHIVE to this as this mode is only used if the file is
2082 * created new. */
2083 unx_mode = unix_mode(conn, new_dos_attributes | FILE_ATTRIBUTE_ARCHIVE,
2084 smb_fname, parent_dir);
2087 DEBUG(10, ("open_file_ntcreate: fname=%s, dos_attrs=0x%x "
2088 "access_mask=0x%x share_access=0x%x "
2089 "create_disposition = 0x%x create_options=0x%x "
2090 "unix mode=0%o oplock_request=%d private_flags = 0x%x\n",
2091 smb_fname_str_dbg(smb_fname), new_dos_attributes,
2092 access_mask, share_access, create_disposition,
2093 create_options, (unsigned int)unx_mode, oplock_request,
2094 (unsigned int)private_flags));
2096 if (req == NULL) {
2097 /* Ensure req == NULL means INTERNAL_OPEN_ONLY */
2098 SMB_ASSERT(((oplock_request & INTERNAL_OPEN_ONLY) != 0));
2099 } else {
2100 /* And req != NULL means no INTERNAL_OPEN_ONLY */
2101 SMB_ASSERT(((oplock_request & INTERNAL_OPEN_ONLY) == 0));
2105 * Only non-internal opens can be deferred at all
2108 if (req) {
2109 void *ptr;
2110 if (get_deferred_open_message_state(req,
2111 &request_time,
2112 &ptr)) {
2113 /* Remember the absolute time of the original
2114 request with this mid. We'll use it later to
2115 see if this has timed out. */
2117 /* If it was an async create retry, the file
2118 didn't exist. */
2120 if (is_deferred_open_async(ptr)) {
2121 SET_STAT_INVALID(smb_fname->st);
2122 file_existed = false;
2125 /* Ensure we don't reprocess this message. */
2126 remove_deferred_open_message_smb(req->sconn, req->mid);
2128 first_open_attempt = false;
2132 if (!posix_open) {
2133 new_dos_attributes &= SAMBA_ATTRIBUTES_MASK;
2134 if (file_existed) {
2135 existing_dos_attributes = dos_mode(conn, smb_fname);
2139 /* ignore any oplock requests if oplocks are disabled */
2140 if (!lp_oplocks(SNUM(conn)) ||
2141 IS_VETO_OPLOCK_PATH(conn, smb_fname->base_name)) {
2142 /* Mask off everything except the private Samba bits. */
2143 oplock_request &= SAMBA_PRIVATE_OPLOCK_MASK;
2146 /* this is for OS/2 long file names - say we don't support them */
2147 if (!lp_posix_pathnames() && strstr(smb_fname->base_name,".+,;=[].")) {
2148 /* OS/2 Workplace shell fix may be main code stream in a later
2149 * release. */
2150 DEBUG(5,("open_file_ntcreate: OS/2 long filenames are not "
2151 "supported.\n"));
2152 if (use_nt_status()) {
2153 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
2155 return NT_STATUS_DOS(ERRDOS, ERRcannotopen);
2158 switch( create_disposition ) {
2159 case FILE_OPEN:
2160 /* If file exists open. If file doesn't exist error. */
2161 if (!file_existed) {
2162 DEBUG(5,("open_file_ntcreate: FILE_OPEN "
2163 "requested for file %s and file "
2164 "doesn't exist.\n",
2165 smb_fname_str_dbg(smb_fname)));
2166 errno = ENOENT;
2167 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
2169 break;
2171 case FILE_OVERWRITE:
2172 /* If file exists overwrite. If file doesn't exist
2173 * error. */
2174 if (!file_existed) {
2175 DEBUG(5,("open_file_ntcreate: FILE_OVERWRITE "
2176 "requested for file %s and file "
2177 "doesn't exist.\n",
2178 smb_fname_str_dbg(smb_fname) ));
2179 errno = ENOENT;
2180 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
2182 break;
2184 case FILE_CREATE:
2185 /* If file exists error. If file doesn't exist
2186 * create. */
2187 if (file_existed) {
2188 DEBUG(5,("open_file_ntcreate: FILE_CREATE "
2189 "requested for file %s and file "
2190 "already exists.\n",
2191 smb_fname_str_dbg(smb_fname)));
2192 if (S_ISDIR(smb_fname->st.st_ex_mode)) {
2193 errno = EISDIR;
2194 } else {
2195 errno = EEXIST;
2197 return map_nt_error_from_unix(errno);
2199 break;
2201 case FILE_SUPERSEDE:
2202 case FILE_OVERWRITE_IF:
2203 case FILE_OPEN_IF:
2204 break;
2205 default:
2206 return NT_STATUS_INVALID_PARAMETER;
2209 flags2 = disposition_to_open_flags(create_disposition);
2211 /* We only care about matching attributes on file exists and
2212 * overwrite. */
2214 if (!posix_open && file_existed &&
2215 ((create_disposition == FILE_OVERWRITE) ||
2216 (create_disposition == FILE_OVERWRITE_IF))) {
2217 if (!open_match_attributes(conn, existing_dos_attributes,
2218 new_dos_attributes,
2219 smb_fname->st.st_ex_mode,
2220 unx_mode, &new_unx_mode)) {
2221 DEBUG(5,("open_file_ntcreate: attributes missmatch "
2222 "for file %s (%x %x) (0%o, 0%o)\n",
2223 smb_fname_str_dbg(smb_fname),
2224 existing_dos_attributes,
2225 new_dos_attributes,
2226 (unsigned int)smb_fname->st.st_ex_mode,
2227 (unsigned int)unx_mode ));
2228 errno = EACCES;
2229 return NT_STATUS_ACCESS_DENIED;
2233 status = smbd_calculate_access_mask(conn, smb_fname,
2234 false,
2235 access_mask,
2236 &access_mask);
2237 if (!NT_STATUS_IS_OK(status)) {
2238 DEBUG(10, ("open_file_ntcreate: smbd_calculate_access_mask "
2239 "on file %s returned %s\n",
2240 smb_fname_str_dbg(smb_fname), nt_errstr(status)));
2241 return status;
2244 open_access_mask = access_mask;
2246 if ((flags2 & O_TRUNC) || (oplock_request & FORCE_OPLOCK_BREAK_TO_NONE)) {
2247 open_access_mask |= FILE_WRITE_DATA; /* This will cause oplock breaks. */
2250 DEBUG(10, ("open_file_ntcreate: fname=%s, after mapping "
2251 "access_mask=0x%x\n", smb_fname_str_dbg(smb_fname),
2252 access_mask));
2255 * Note that we ignore the append flag as append does not
2256 * mean the same thing under DOS and Unix.
2259 flags = calculate_open_access_flags(access_mask, oplock_request,
2260 private_flags);
2263 * Currently we only look at FILE_WRITE_THROUGH for create options.
2266 #if defined(O_SYNC)
2267 if ((create_options & FILE_WRITE_THROUGH) && lp_strict_sync(SNUM(conn))) {
2268 flags2 |= O_SYNC;
2270 #endif /* O_SYNC */
2272 if (posix_open && (access_mask & FILE_APPEND_DATA)) {
2273 flags2 |= O_APPEND;
2276 if (!posix_open && !CAN_WRITE(conn)) {
2278 * We should really return a permission denied error if either
2279 * O_CREAT or O_TRUNC are set, but for compatibility with
2280 * older versions of Samba we just AND them out.
2282 flags2 &= ~(O_CREAT|O_TRUNC);
2285 if (first_open_attempt && lp_kernel_oplocks(SNUM(conn))) {
2287 * With kernel oplocks the open breaking an oplock
2288 * blocks until the oplock holder has given up the
2289 * oplock or closed the file. We prevent this by first
2290 * trying to open the file with O_NONBLOCK (see "man
2291 * fcntl" on Linux). For the second try, triggered by
2292 * an oplock break response, we do not need this
2293 * anymore.
2295 * This is true under the assumption that only Samba
2296 * requests kernel oplocks. Once someone else like
2297 * NFSv4 starts to use that API, we will have to
2298 * modify this by communicating with the NFSv4 server.
2300 flags2 |= O_NONBLOCK;
2304 * Ensure we can't write on a read-only share or file.
2307 if (flags != O_RDONLY && file_existed &&
2308 (!CAN_WRITE(conn) || IS_DOS_READONLY(existing_dos_attributes))) {
2309 DEBUG(5,("open_file_ntcreate: write access requested for "
2310 "file %s on read only %s\n",
2311 smb_fname_str_dbg(smb_fname),
2312 !CAN_WRITE(conn) ? "share" : "file" ));
2313 errno = EACCES;
2314 return NT_STATUS_ACCESS_DENIED;
2317 fsp->file_id = vfs_file_id_from_sbuf(conn, &smb_fname->st);
2318 fsp->share_access = share_access;
2319 fsp->fh->private_options = private_flags;
2320 fsp->access_mask = open_access_mask; /* We change this to the
2321 * requested access_mask after
2322 * the open is done. */
2323 fsp->posix_open = posix_open;
2325 /* Ensure no SAMBA_PRIVATE bits can be set. */
2326 fsp->oplock_type = (oplock_request & ~SAMBA_PRIVATE_OPLOCK_MASK);
2328 if (timeval_is_zero(&request_time)) {
2329 request_time = fsp->open_time;
2333 * Ensure we pay attention to default ACLs on directories if required.
2336 if ((flags2 & O_CREAT) && lp_inherit_acls(SNUM(conn)) &&
2337 (def_acl = directory_has_default_acl(conn, parent_dir))) {
2338 unx_mode = (0777 & lp_create_mask(SNUM(conn)));
2341 DEBUG(4,("calling open_file with flags=0x%X flags2=0x%X mode=0%o, "
2342 "access_mask = 0x%x, open_access_mask = 0x%x\n",
2343 (unsigned int)flags, (unsigned int)flags2,
2344 (unsigned int)unx_mode, (unsigned int)access_mask,
2345 (unsigned int)open_access_mask));
2347 fsp_open = open_file(fsp, conn, req, parent_dir,
2348 flags|flags2, unx_mode, access_mask,
2349 open_access_mask, &new_file_created);
2351 if (NT_STATUS_EQUAL(fsp_open, NT_STATUS_NETWORK_BUSY)) {
2352 struct deferred_open_record state;
2355 * EWOULDBLOCK/EAGAIN maps to NETWORK_BUSY.
2357 if (file_existed && S_ISFIFO(fsp->fsp_name->st.st_ex_mode)) {
2358 DEBUG(10, ("FIFO busy\n"));
2359 return NT_STATUS_NETWORK_BUSY;
2361 if (req == NULL) {
2362 DEBUG(10, ("Internal open busy\n"));
2363 return NT_STATUS_NETWORK_BUSY;
2367 * From here on we assume this is an oplock break triggered
2370 lck = get_existing_share_mode_lock(talloc_tos(), fsp->file_id);
2371 if (lck == NULL) {
2372 state.delayed_for_oplocks = false;
2373 state.async_open = false;
2374 state.id = fsp->file_id;
2375 defer_open(NULL, request_time, timeval_set(0, 0),
2376 req, &state);
2377 DEBUG(10, ("No share mode lock found after "
2378 "EWOULDBLOCK, retrying sync\n"));
2379 return NT_STATUS_SHARING_VIOLATION;
2382 find_oplock_types(fsp, 0, lck, &batch_entry, &exclusive_entry,
2383 &got_level2_oplock, &got_a_none_oplock);
2385 if (delay_for_batch_oplocks(fsp, req->mid, 0, batch_entry) ||
2386 delay_for_exclusive_oplocks(fsp, req->mid, 0,
2387 exclusive_entry)) {
2388 schedule_defer_open(lck, request_time, req);
2389 TALLOC_FREE(lck);
2390 DEBUG(10, ("Sent oplock break request to kernel "
2391 "oplock holder\n"));
2392 return NT_STATUS_SHARING_VIOLATION;
2396 * No oplock from Samba around. Immediately retry with
2397 * a blocking open.
2399 state.delayed_for_oplocks = false;
2400 state.async_open = false;
2401 state.id = lck->data->id;
2402 defer_open(lck, request_time, timeval_set(0, 0), req, &state);
2403 TALLOC_FREE(lck);
2404 DEBUG(10, ("No Samba oplock around after EWOULDBLOCK. "
2405 "Retrying sync\n"));
2406 return NT_STATUS_SHARING_VIOLATION;
2409 if (!NT_STATUS_IS_OK(fsp_open)) {
2410 if (NT_STATUS_EQUAL(fsp_open, NT_STATUS_RETRY)) {
2411 schedule_async_open(request_time, req);
2413 TALLOC_FREE(lck);
2414 return fsp_open;
2417 if (file_existed && !check_same_dev_ino(&saved_stat, &smb_fname->st)) {
2419 * The file did exist, but some other (local or NFS)
2420 * process either renamed/unlinked and re-created the
2421 * file with different dev/ino after we walked the path,
2422 * but before we did the open. We could retry the
2423 * open but it's a rare enough case it's easier to
2424 * just fail the open to prevent creating any problems
2425 * in the open file db having the wrong dev/ino key.
2427 TALLOC_FREE(lck);
2428 fd_close(fsp);
2429 DEBUG(1,("open_file_ntcreate: file %s - dev/ino mismatch. "
2430 "Old (dev=0x%llu, ino =0x%llu). "
2431 "New (dev=0x%llu, ino=0x%llu). Failing open "
2432 " with NT_STATUS_ACCESS_DENIED.\n",
2433 smb_fname_str_dbg(smb_fname),
2434 (unsigned long long)saved_stat.st_ex_dev,
2435 (unsigned long long)saved_stat.st_ex_ino,
2436 (unsigned long long)smb_fname->st.st_ex_dev,
2437 (unsigned long long)smb_fname->st.st_ex_ino));
2438 return NT_STATUS_ACCESS_DENIED;
2441 old_write_time = smb_fname->st.st_ex_mtime;
2444 * Deal with the race condition where two smbd's detect the
2445 * file doesn't exist and do the create at the same time. One
2446 * of them will win and set a share mode, the other (ie. this
2447 * one) should check if the requested share mode for this
2448 * create is allowed.
2452 * Now the file exists and fsp is successfully opened,
2453 * fsp->dev and fsp->inode are valid and should replace the
2454 * dev=0,inode=0 from a non existent file. Spotted by
2455 * Nadav Danieli <nadavd@exanet.com>. JRA.
2458 id = fsp->file_id;
2460 lck = get_share_mode_lock(talloc_tos(), id,
2461 conn->connectpath,
2462 smb_fname, &old_write_time);
2464 if (lck == NULL) {
2465 DEBUG(0, ("open_file_ntcreate: Could not get share "
2466 "mode lock for %s\n",
2467 smb_fname_str_dbg(smb_fname)));
2468 fd_close(fsp);
2469 return NT_STATUS_SHARING_VIOLATION;
2472 /* Get the types we need to examine. */
2473 find_oplock_types(fsp,
2474 oplock_request,
2475 lck,
2476 &batch_entry,
2477 &exclusive_entry,
2478 &got_level2_oplock,
2479 &got_a_none_oplock);
2481 /* First pass - send break only on batch oplocks. */
2482 if ((req != NULL) &&
2483 delay_for_batch_oplocks(fsp,
2484 req->mid,
2485 oplock_request,
2486 batch_entry)) {
2487 schedule_defer_open(lck, request_time, req);
2488 TALLOC_FREE(lck);
2489 fd_close(fsp);
2490 return NT_STATUS_SHARING_VIOLATION;
2493 status = open_mode_check(conn, lck, fsp->name_hash,
2494 access_mask, share_access,
2495 create_options, &file_existed);
2497 if (NT_STATUS_IS_OK(status)) {
2498 /* We might be going to allow this open. Check oplock
2499 * status again. */
2500 /* Second pass - send break for both batch or
2501 * exclusive oplocks. */
2502 if ((req != NULL) &&
2503 delay_for_exclusive_oplocks(
2504 fsp,
2505 req->mid,
2506 oplock_request,
2507 exclusive_entry)) {
2508 schedule_defer_open(lck, request_time, req);
2509 TALLOC_FREE(lck);
2510 fd_close(fsp);
2511 return NT_STATUS_SHARING_VIOLATION;
2515 if (NT_STATUS_EQUAL(status, NT_STATUS_DELETE_PENDING)) {
2516 /* DELETE_PENDING is not deferred for a second */
2517 TALLOC_FREE(lck);
2518 fd_close(fsp);
2519 return status;
2522 if (!NT_STATUS_IS_OK(status)) {
2523 uint32 can_access_mask;
2524 bool can_access = True;
2526 SMB_ASSERT(NT_STATUS_EQUAL(status, NT_STATUS_SHARING_VIOLATION));
2528 /* Check if this can be done with the deny_dos and fcb
2529 * calls. */
2530 if (private_flags &
2531 (NTCREATEX_OPTIONS_PRIVATE_DENY_DOS|
2532 NTCREATEX_OPTIONS_PRIVATE_DENY_FCB)) {
2533 if (req == NULL) {
2534 DEBUG(0, ("DOS open without an SMB "
2535 "request!\n"));
2536 TALLOC_FREE(lck);
2537 fd_close(fsp);
2538 return NT_STATUS_INTERNAL_ERROR;
2541 /* Use the client requested access mask here,
2542 * not the one we open with. */
2543 status = fcb_or_dos_open(req,
2544 conn,
2545 fsp,
2546 smb_fname,
2548 req->smbpid,
2549 req->vuid,
2550 access_mask,
2551 share_access,
2552 create_options);
2554 if (NT_STATUS_IS_OK(status)) {
2555 TALLOC_FREE(lck);
2556 if (pinfo) {
2557 *pinfo = FILE_WAS_OPENED;
2559 return NT_STATUS_OK;
2564 * This next line is a subtlety we need for
2565 * MS-Access. If a file open will fail due to share
2566 * permissions and also for security (access) reasons,
2567 * we need to return the access failed error, not the
2568 * share error. We can't open the file due to kernel
2569 * oplock deadlock (it's possible we failed above on
2570 * the open_mode_check()) so use a userspace check.
2573 if (flags & O_RDWR) {
2574 can_access_mask = FILE_READ_DATA|FILE_WRITE_DATA;
2575 } else if (flags & O_WRONLY) {
2576 can_access_mask = FILE_WRITE_DATA;
2577 } else {
2578 can_access_mask = FILE_READ_DATA;
2581 if (((can_access_mask & FILE_WRITE_DATA) &&
2582 !CAN_WRITE(conn)) ||
2583 !NT_STATUS_IS_OK(smbd_check_access_rights(conn,
2584 smb_fname,
2585 false,
2586 can_access_mask))) {
2587 can_access = False;
2591 * If we're returning a share violation, ensure we
2592 * cope with the braindead 1 second delay (SMB1 only).
2595 if (!(oplock_request & INTERNAL_OPEN_ONLY) &&
2596 !conn->sconn->using_smb2 &&
2597 lp_defer_sharing_violations()) {
2598 struct timeval timeout;
2599 struct deferred_open_record state;
2600 int timeout_usecs;
2602 /* this is a hack to speed up torture tests
2603 in 'make test' */
2604 timeout_usecs = lp_parm_int(SNUM(conn),
2605 "smbd","sharedelay",
2606 SHARING_VIOLATION_USEC_WAIT);
2608 /* This is a relative time, added to the absolute
2609 request_time value to get the absolute timeout time.
2610 Note that if this is the second or greater time we enter
2611 this codepath for this particular request mid then
2612 request_time is left as the absolute time of the *first*
2613 time this request mid was processed. This is what allows
2614 the request to eventually time out. */
2616 timeout = timeval_set(0, timeout_usecs);
2618 /* Nothing actually uses state.delayed_for_oplocks
2619 but it's handy to differentiate in debug messages
2620 between a 30 second delay due to oplock break, and
2621 a 1 second delay for share mode conflicts. */
2623 state.delayed_for_oplocks = False;
2624 state.async_open = false;
2625 state.id = id;
2627 if ((req != NULL)
2628 && !request_timed_out(request_time,
2629 timeout)) {
2630 defer_open(lck, request_time, timeout,
2631 req, &state);
2635 TALLOC_FREE(lck);
2636 fd_close(fsp);
2637 if (can_access) {
2639 * We have detected a sharing violation here
2640 * so return the correct error code
2642 status = NT_STATUS_SHARING_VIOLATION;
2643 } else {
2644 status = NT_STATUS_ACCESS_DENIED;
2646 return status;
2649 grant_fsp_oplock_type(fsp,
2650 oplock_request,
2651 got_level2_oplock,
2652 got_a_none_oplock);
2655 * We have the share entry *locked*.....
2658 /* Delete streams if create_disposition requires it */
2659 if (!new_file_created && clear_ads(create_disposition) &&
2660 !is_ntfs_stream_smb_fname(smb_fname)) {
2661 status = delete_all_streams(conn, smb_fname->base_name);
2662 if (!NT_STATUS_IS_OK(status)) {
2663 TALLOC_FREE(lck);
2664 fd_close(fsp);
2665 return status;
2669 /* note that we ignore failure for the following. It is
2670 basically a hack for NFS, and NFS will never set one of
2671 these only read them. Nobody but Samba can ever set a deny
2672 mode and we have already checked our more authoritative
2673 locking database for permission to set this deny mode. If
2674 the kernel refuses the operations then the kernel is wrong.
2675 note that GPFS supports it as well - jmcd */
2677 if (fsp->fh->fd != -1 && lp_kernel_share_modes(SNUM(conn))) {
2678 int ret_flock;
2679 ret_flock = SMB_VFS_KERNEL_FLOCK(fsp, share_access, access_mask);
2680 if(ret_flock == -1 ){
2682 TALLOC_FREE(lck);
2683 fd_close(fsp);
2685 return NT_STATUS_SHARING_VIOLATION;
2690 * At this point onwards, we can guarantee that the share entry
2691 * is locked, whether we created the file or not, and that the
2692 * deny mode is compatible with all current opens.
2696 * According to Samba4, SEC_FILE_READ_ATTRIBUTE is always granted,
2697 * but we don't have to store this - just ignore it on access check.
2699 if (conn->sconn->using_smb2) {
2701 * SMB2 doesn't return it (according to Microsoft tests).
2702 * Test Case: TestSuite_ScenarioNo009GrantedAccessTestS0
2703 * File created with access = 0x7 (Read, Write, Delete)
2704 * Query Info on file returns 0x87 (Read, Write, Delete, Read Attributes)
2706 fsp->access_mask = access_mask;
2707 } else {
2708 /* But SMB1 does. */
2709 fsp->access_mask = access_mask | FILE_READ_ATTRIBUTES;
2712 if (file_existed) {
2713 /* stat opens on existing files don't get oplocks. */
2714 if (is_stat_open(open_access_mask)) {
2715 fsp->oplock_type = NO_OPLOCK;
2719 if (new_file_created) {
2720 info = FILE_WAS_CREATED;
2721 } else {
2722 if (flags2 & O_TRUNC) {
2723 info = FILE_WAS_OVERWRITTEN;
2724 } else {
2725 info = FILE_WAS_OPENED;
2729 if (pinfo) {
2730 *pinfo = info;
2734 * Setup the oplock info in both the shared memory and
2735 * file structs.
2738 status = set_file_oplock(fsp, fsp->oplock_type);
2739 if (!NT_STATUS_IS_OK(status)) {
2741 * Could not get the kernel oplock or there are byte-range
2742 * locks on the file.
2744 fsp->oplock_type = NO_OPLOCK;
2747 set_share_mode(lck, fsp, get_current_uid(conn),
2748 req ? req->mid : 0,
2749 fsp->oplock_type);
2751 /* Handle strange delete on close create semantics. */
2752 if (create_options & FILE_DELETE_ON_CLOSE) {
2754 status = can_set_delete_on_close(fsp, new_dos_attributes);
2756 if (!NT_STATUS_IS_OK(status)) {
2757 /* Remember to delete the mode we just added. */
2758 del_share_mode(lck, fsp);
2759 TALLOC_FREE(lck);
2760 fd_close(fsp);
2761 return status;
2763 /* Note that here we set the *inital* delete on close flag,
2764 not the regular one. The magic gets handled in close. */
2765 fsp->initial_delete_on_close = True;
2768 if (info != FILE_WAS_OPENED) {
2769 /* Files should be initially set as archive */
2770 if (lp_map_archive(SNUM(conn)) ||
2771 lp_store_dos_attributes(SNUM(conn))) {
2772 if (!posix_open) {
2773 if (file_set_dosmode(conn, smb_fname,
2774 new_dos_attributes | FILE_ATTRIBUTE_ARCHIVE,
2775 parent_dir, true) == 0) {
2776 unx_mode = smb_fname->st.st_ex_mode;
2782 /* Determine sparse flag. */
2783 if (posix_open) {
2784 /* POSIX opens are sparse by default. */
2785 fsp->is_sparse = true;
2786 } else {
2787 fsp->is_sparse = (file_existed &&
2788 (existing_dos_attributes & FILE_ATTRIBUTE_SPARSE));
2792 * Take care of inherited ACLs on created files - if default ACL not
2793 * selected.
2796 if (!posix_open && new_file_created && !def_acl) {
2798 int saved_errno = errno; /* We might get ENOSYS in the next
2799 * call.. */
2801 if (SMB_VFS_FCHMOD_ACL(fsp, unx_mode) == -1 &&
2802 errno == ENOSYS) {
2803 errno = saved_errno; /* Ignore ENOSYS */
2806 } else if (new_unx_mode) {
2808 int ret = -1;
2810 /* Attributes need changing. File already existed. */
2813 int saved_errno = errno; /* We might get ENOSYS in the
2814 * next call.. */
2815 ret = SMB_VFS_FCHMOD_ACL(fsp, new_unx_mode);
2817 if (ret == -1 && errno == ENOSYS) {
2818 errno = saved_errno; /* Ignore ENOSYS */
2819 } else {
2820 DEBUG(5, ("open_file_ntcreate: reset "
2821 "attributes of file %s to 0%o\n",
2822 smb_fname_str_dbg(smb_fname),
2823 (unsigned int)new_unx_mode));
2824 ret = 0; /* Don't do the fchmod below. */
2828 if ((ret == -1) &&
2829 (SMB_VFS_FCHMOD(fsp, new_unx_mode) == -1))
2830 DEBUG(5, ("open_file_ntcreate: failed to reset "
2831 "attributes of file %s to 0%o\n",
2832 smb_fname_str_dbg(smb_fname),
2833 (unsigned int)new_unx_mode));
2836 TALLOC_FREE(lck);
2838 return NT_STATUS_OK;
2841 static NTSTATUS mkdir_internal(connection_struct *conn,
2842 struct smb_filename *smb_dname,
2843 uint32 file_attributes)
2845 mode_t mode;
2846 char *parent_dir = NULL;
2847 NTSTATUS status;
2848 bool posix_open = false;
2849 bool need_re_stat = false;
2850 uint32_t access_mask = SEC_DIR_ADD_SUBDIR;
2852 if (!CAN_WRITE(conn) || (access_mask & ~(conn->share_access))) {
2853 DEBUG(5,("mkdir_internal: failing share access "
2854 "%s\n", lp_servicename(talloc_tos(), SNUM(conn))));
2855 return NT_STATUS_ACCESS_DENIED;
2858 if (!parent_dirname(talloc_tos(), smb_dname->base_name, &parent_dir,
2859 NULL)) {
2860 return NT_STATUS_NO_MEMORY;
2863 if (file_attributes & FILE_FLAG_POSIX_SEMANTICS) {
2864 posix_open = true;
2865 mode = (mode_t)(file_attributes & ~FILE_FLAG_POSIX_SEMANTICS);
2866 } else {
2867 mode = unix_mode(conn, FILE_ATTRIBUTE_DIRECTORY, smb_dname, parent_dir);
2870 status = check_parent_access(conn,
2871 smb_dname,
2872 access_mask);
2873 if(!NT_STATUS_IS_OK(status)) {
2874 DEBUG(5,("mkdir_internal: check_parent_access "
2875 "on directory %s for path %s returned %s\n",
2876 parent_dir,
2877 smb_dname->base_name,
2878 nt_errstr(status) ));
2879 return status;
2882 if (SMB_VFS_MKDIR(conn, smb_dname->base_name, mode) != 0) {
2883 return map_nt_error_from_unix(errno);
2886 /* Ensure we're checking for a symlink here.... */
2887 /* We don't want to get caught by a symlink racer. */
2889 if (SMB_VFS_LSTAT(conn, smb_dname) == -1) {
2890 DEBUG(2, ("Could not stat directory '%s' just created: %s\n",
2891 smb_fname_str_dbg(smb_dname), strerror(errno)));
2892 return map_nt_error_from_unix(errno);
2895 if (!S_ISDIR(smb_dname->st.st_ex_mode)) {
2896 DEBUG(0, ("Directory '%s' just created is not a directory !\n",
2897 smb_fname_str_dbg(smb_dname)));
2898 return NT_STATUS_NOT_A_DIRECTORY;
2901 if (lp_store_dos_attributes(SNUM(conn))) {
2902 if (!posix_open) {
2903 file_set_dosmode(conn, smb_dname,
2904 file_attributes | FILE_ATTRIBUTE_DIRECTORY,
2905 parent_dir, true);
2909 if (lp_inherit_perms(SNUM(conn))) {
2910 inherit_access_posix_acl(conn, parent_dir,
2911 smb_dname->base_name, mode);
2912 need_re_stat = true;
2915 if (!posix_open) {
2917 * Check if high bits should have been set,
2918 * then (if bits are missing): add them.
2919 * Consider bits automagically set by UNIX, i.e. SGID bit from parent
2920 * dir.
2922 if ((mode & ~(S_IRWXU|S_IRWXG|S_IRWXO)) &&
2923 (mode & ~smb_dname->st.st_ex_mode)) {
2924 SMB_VFS_CHMOD(conn, smb_dname->base_name,
2925 (smb_dname->st.st_ex_mode |
2926 (mode & ~smb_dname->st.st_ex_mode)));
2927 need_re_stat = true;
2931 /* Change the owner if required. */
2932 if (lp_inherit_owner(SNUM(conn))) {
2933 change_dir_owner_to_parent(conn, parent_dir,
2934 smb_dname->base_name,
2935 &smb_dname->st);
2936 need_re_stat = true;
2939 if (need_re_stat) {
2940 if (SMB_VFS_LSTAT(conn, smb_dname) == -1) {
2941 DEBUG(2, ("Could not stat directory '%s' just created: %s\n",
2942 smb_fname_str_dbg(smb_dname), strerror(errno)));
2943 return map_nt_error_from_unix(errno);
2947 notify_fname(conn, NOTIFY_ACTION_ADDED, FILE_NOTIFY_CHANGE_DIR_NAME,
2948 smb_dname->base_name);
2950 return NT_STATUS_OK;
2953 /****************************************************************************
2954 Open a directory from an NT SMB call.
2955 ****************************************************************************/
2957 static NTSTATUS open_directory(connection_struct *conn,
2958 struct smb_request *req,
2959 struct smb_filename *smb_dname,
2960 uint32 access_mask,
2961 uint32 share_access,
2962 uint32 create_disposition,
2963 uint32 create_options,
2964 uint32 file_attributes,
2965 int *pinfo,
2966 files_struct **result)
2968 files_struct *fsp = NULL;
2969 bool dir_existed = VALID_STAT(smb_dname->st) ? True : False;
2970 struct share_mode_lock *lck = NULL;
2971 NTSTATUS status;
2972 struct timespec mtimespec;
2973 int info = 0;
2975 if (is_ntfs_stream_smb_fname(smb_dname)) {
2976 DEBUG(2, ("open_directory: %s is a stream name!\n",
2977 smb_fname_str_dbg(smb_dname)));
2978 return NT_STATUS_NOT_A_DIRECTORY;
2981 if (!(file_attributes & FILE_FLAG_POSIX_SEMANTICS)) {
2982 /* Ensure we have a directory attribute. */
2983 file_attributes |= FILE_ATTRIBUTE_DIRECTORY;
2986 DEBUG(5,("open_directory: opening directory %s, access_mask = 0x%x, "
2987 "share_access = 0x%x create_options = 0x%x, "
2988 "create_disposition = 0x%x, file_attributes = 0x%x\n",
2989 smb_fname_str_dbg(smb_dname),
2990 (unsigned int)access_mask,
2991 (unsigned int)share_access,
2992 (unsigned int)create_options,
2993 (unsigned int)create_disposition,
2994 (unsigned int)file_attributes));
2996 status = smbd_calculate_access_mask(conn, smb_dname, false,
2997 access_mask, &access_mask);
2998 if (!NT_STATUS_IS_OK(status)) {
2999 DEBUG(10, ("open_directory: smbd_calculate_access_mask "
3000 "on file %s returned %s\n",
3001 smb_fname_str_dbg(smb_dname),
3002 nt_errstr(status)));
3003 return status;
3006 if ((access_mask & SEC_FLAG_SYSTEM_SECURITY) &&
3007 !security_token_has_privilege(get_current_nttok(conn),
3008 SEC_PRIV_SECURITY)) {
3009 DEBUG(10, ("open_directory: open on %s "
3010 "failed - SEC_FLAG_SYSTEM_SECURITY denied.\n",
3011 smb_fname_str_dbg(smb_dname)));
3012 return NT_STATUS_PRIVILEGE_NOT_HELD;
3015 switch( create_disposition ) {
3016 case FILE_OPEN:
3018 if (!dir_existed) {
3019 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3022 info = FILE_WAS_OPENED;
3023 break;
3025 case FILE_CREATE:
3027 /* If directory exists error. If directory doesn't
3028 * exist create. */
3030 if (dir_existed) {
3031 status = NT_STATUS_OBJECT_NAME_COLLISION;
3032 DEBUG(2, ("open_directory: unable to create "
3033 "%s. Error was %s\n",
3034 smb_fname_str_dbg(smb_dname),
3035 nt_errstr(status)));
3036 return status;
3039 status = mkdir_internal(conn, smb_dname,
3040 file_attributes);
3042 if (!NT_STATUS_IS_OK(status)) {
3043 DEBUG(2, ("open_directory: unable to create "
3044 "%s. Error was %s\n",
3045 smb_fname_str_dbg(smb_dname),
3046 nt_errstr(status)));
3047 return status;
3050 info = FILE_WAS_CREATED;
3051 break;
3053 case FILE_OPEN_IF:
3055 * If directory exists open. If directory doesn't
3056 * exist create.
3059 if (dir_existed) {
3060 status = NT_STATUS_OK;
3061 info = FILE_WAS_OPENED;
3062 } else {
3063 status = mkdir_internal(conn, smb_dname,
3064 file_attributes);
3066 if (NT_STATUS_IS_OK(status)) {
3067 info = FILE_WAS_CREATED;
3068 } else {
3069 /* Cope with create race. */
3070 if (!NT_STATUS_EQUAL(status,
3071 NT_STATUS_OBJECT_NAME_COLLISION)) {
3072 DEBUG(2, ("open_directory: unable to create "
3073 "%s. Error was %s\n",
3074 smb_fname_str_dbg(smb_dname),
3075 nt_errstr(status)));
3076 return status;
3078 info = FILE_WAS_OPENED;
3082 break;
3084 case FILE_SUPERSEDE:
3085 case FILE_OVERWRITE:
3086 case FILE_OVERWRITE_IF:
3087 default:
3088 DEBUG(5,("open_directory: invalid create_disposition "
3089 "0x%x for directory %s\n",
3090 (unsigned int)create_disposition,
3091 smb_fname_str_dbg(smb_dname)));
3092 return NT_STATUS_INVALID_PARAMETER;
3095 if(!S_ISDIR(smb_dname->st.st_ex_mode)) {
3096 DEBUG(5,("open_directory: %s is not a directory !\n",
3097 smb_fname_str_dbg(smb_dname)));
3098 return NT_STATUS_NOT_A_DIRECTORY;
3101 if (info == FILE_WAS_OPENED) {
3102 status = smbd_check_access_rights(conn,
3103 smb_dname,
3104 false,
3105 access_mask);
3106 if (!NT_STATUS_IS_OK(status)) {
3107 DEBUG(10, ("open_directory: smbd_check_access_rights on "
3108 "file %s failed with %s\n",
3109 smb_fname_str_dbg(smb_dname),
3110 nt_errstr(status)));
3111 return status;
3115 status = file_new(req, conn, &fsp);
3116 if(!NT_STATUS_IS_OK(status)) {
3117 return status;
3121 * Setup the files_struct for it.
3124 fsp->file_id = vfs_file_id_from_sbuf(conn, &smb_dname->st);
3125 fsp->vuid = req ? req->vuid : UID_FIELD_INVALID;
3126 fsp->file_pid = req ? req->smbpid : 0;
3127 fsp->can_lock = False;
3128 fsp->can_read = False;
3129 fsp->can_write = False;
3131 fsp->share_access = share_access;
3132 fsp->fh->private_options = 0;
3134 * According to Samba4, SEC_FILE_READ_ATTRIBUTE is always granted,
3136 fsp->access_mask = access_mask | FILE_READ_ATTRIBUTES;
3137 fsp->print_file = NULL;
3138 fsp->modified = False;
3139 fsp->oplock_type = NO_OPLOCK;
3140 fsp->sent_oplock_break = NO_BREAK_SENT;
3141 fsp->is_directory = True;
3142 fsp->posix_open = (file_attributes & FILE_FLAG_POSIX_SEMANTICS) ? True : False;
3143 status = fsp_set_smb_fname(fsp, smb_dname);
3144 if (!NT_STATUS_IS_OK(status)) {
3145 file_free(req, fsp);
3146 return status;
3149 /* Don't store old timestamps for directory
3150 handles in the internal database. We don't
3151 update them in there if new objects
3152 are creaded in the directory. Currently
3153 we only update timestamps on file writes.
3154 See bug #9870.
3156 ZERO_STRUCT(mtimespec);
3158 #ifdef O_DIRECTORY
3159 status = fd_open(conn, fsp, O_RDONLY|O_DIRECTORY, 0);
3160 #else
3161 /* POSIX allows us to open a directory with O_RDONLY. */
3162 status = fd_open(conn, fsp, O_RDONLY, 0);
3163 #endif
3164 if (!NT_STATUS_IS_OK(status)) {
3165 DEBUG(5, ("open_directory: Could not open fd for "
3166 "%s (%s)\n",
3167 smb_fname_str_dbg(smb_dname),
3168 nt_errstr(status)));
3169 file_free(req, fsp);
3170 return status;
3173 status = vfs_stat_fsp(fsp);
3174 if (!NT_STATUS_IS_OK(status)) {
3175 fd_close(fsp);
3176 file_free(req, fsp);
3177 return status;
3180 /* Ensure there was no race condition. */
3181 if (!check_same_stat(&smb_dname->st, &fsp->fsp_name->st)) {
3182 DEBUG(5,("open_directory: stat struct differs for "
3183 "directory %s.\n",
3184 smb_fname_str_dbg(smb_dname)));
3185 fd_close(fsp);
3186 file_free(req, fsp);
3187 return NT_STATUS_ACCESS_DENIED;
3190 lck = get_share_mode_lock(talloc_tos(), fsp->file_id,
3191 conn->connectpath, smb_dname,
3192 &mtimespec);
3194 if (lck == NULL) {
3195 DEBUG(0, ("open_directory: Could not get share mode lock for "
3196 "%s\n", smb_fname_str_dbg(smb_dname)));
3197 fd_close(fsp);
3198 file_free(req, fsp);
3199 return NT_STATUS_SHARING_VIOLATION;
3202 status = open_mode_check(conn, lck, fsp->name_hash,
3203 access_mask, share_access,
3204 create_options, &dir_existed);
3206 if (!NT_STATUS_IS_OK(status)) {
3207 TALLOC_FREE(lck);
3208 fd_close(fsp);
3209 file_free(req, fsp);
3210 return status;
3213 set_share_mode(lck, fsp, get_current_uid(conn),
3214 req ? req->mid : 0, NO_OPLOCK);
3216 /* For directories the delete on close bit at open time seems
3217 always to be honored on close... See test 19 in Samba4 BASE-DELETE. */
3218 if (create_options & FILE_DELETE_ON_CLOSE) {
3219 status = can_set_delete_on_close(fsp, 0);
3220 if (!NT_STATUS_IS_OK(status) && !NT_STATUS_EQUAL(status, NT_STATUS_DIRECTORY_NOT_EMPTY)) {
3221 TALLOC_FREE(lck);
3222 fd_close(fsp);
3223 file_free(req, fsp);
3224 return status;
3227 if (NT_STATUS_IS_OK(status)) {
3228 /* Note that here we set the *inital* delete on close flag,
3229 not the regular one. The magic gets handled in close. */
3230 fsp->initial_delete_on_close = True;
3234 TALLOC_FREE(lck);
3236 if (pinfo) {
3237 *pinfo = info;
3240 *result = fsp;
3241 return NT_STATUS_OK;
3244 NTSTATUS create_directory(connection_struct *conn, struct smb_request *req,
3245 struct smb_filename *smb_dname)
3247 NTSTATUS status;
3248 files_struct *fsp;
3250 status = SMB_VFS_CREATE_FILE(
3251 conn, /* conn */
3252 req, /* req */
3253 0, /* root_dir_fid */
3254 smb_dname, /* fname */
3255 FILE_READ_ATTRIBUTES, /* access_mask */
3256 FILE_SHARE_NONE, /* share_access */
3257 FILE_CREATE, /* create_disposition*/
3258 FILE_DIRECTORY_FILE, /* create_options */
3259 FILE_ATTRIBUTE_DIRECTORY, /* file_attributes */
3260 0, /* oplock_request */
3261 0, /* allocation_size */
3262 0, /* private_flags */
3263 NULL, /* sd */
3264 NULL, /* ea_list */
3265 &fsp, /* result */
3266 NULL); /* pinfo */
3268 if (NT_STATUS_IS_OK(status)) {
3269 close_file(req, fsp, NORMAL_CLOSE);
3272 return status;
3275 /****************************************************************************
3276 Receive notification that one of our open files has been renamed by another
3277 smbd process.
3278 ****************************************************************************/
3280 void msg_file_was_renamed(struct messaging_context *msg,
3281 void *private_data,
3282 uint32_t msg_type,
3283 struct server_id server_id,
3284 DATA_BLOB *data)
3286 files_struct *fsp;
3287 char *frm = (char *)data->data;
3288 struct file_id id;
3289 const char *sharepath;
3290 const char *base_name;
3291 const char *stream_name;
3292 struct smb_filename *smb_fname = NULL;
3293 size_t sp_len, bn_len;
3294 NTSTATUS status;
3295 struct smbd_server_connection *sconn =
3296 talloc_get_type_abort(private_data,
3297 struct smbd_server_connection);
3299 if (data->data == NULL
3300 || data->length < MSG_FILE_RENAMED_MIN_SIZE + 2) {
3301 DEBUG(0, ("msg_file_was_renamed: Got invalid msg len %d\n",
3302 (int)data->length));
3303 return;
3306 /* Unpack the message. */
3307 pull_file_id_24(frm, &id);
3308 sharepath = &frm[24];
3309 sp_len = strlen(sharepath);
3310 base_name = sharepath + sp_len + 1;
3311 bn_len = strlen(base_name);
3312 stream_name = sharepath + sp_len + 1 + bn_len + 1;
3314 /* stream_name must always be NULL if there is no stream. */
3315 if (stream_name[0] == '\0') {
3316 stream_name = NULL;
3319 smb_fname = synthetic_smb_fname(talloc_tos(), base_name,
3320 stream_name, NULL);
3321 if (smb_fname == NULL) {
3322 return;
3325 DEBUG(10,("msg_file_was_renamed: Got rename message for sharepath %s, new name %s, "
3326 "file_id %s\n",
3327 sharepath, smb_fname_str_dbg(smb_fname),
3328 file_id_string_tos(&id)));
3330 for(fsp = file_find_di_first(sconn, id); fsp;
3331 fsp = file_find_di_next(fsp)) {
3332 if (memcmp(fsp->conn->connectpath, sharepath, sp_len) == 0) {
3334 DEBUG(10,("msg_file_was_renamed: renaming file %s from %s -> %s\n",
3335 fsp_fnum_dbg(fsp), fsp_str_dbg(fsp),
3336 smb_fname_str_dbg(smb_fname)));
3337 status = fsp_set_smb_fname(fsp, smb_fname);
3338 if (!NT_STATUS_IS_OK(status)) {
3339 goto out;
3341 } else {
3342 /* TODO. JRA. */
3343 /* Now we have the complete path we can work out if this is
3344 actually within this share and adjust newname accordingly. */
3345 DEBUG(10,("msg_file_was_renamed: share mismatch (sharepath %s "
3346 "not sharepath %s) "
3347 "%s from %s -> %s\n",
3348 fsp->conn->connectpath,
3349 sharepath,
3350 fsp_fnum_dbg(fsp),
3351 fsp_str_dbg(fsp),
3352 smb_fname_str_dbg(smb_fname)));
3355 out:
3356 TALLOC_FREE(smb_fname);
3357 return;
3361 * If a main file is opened for delete, all streams need to be checked for
3362 * !FILE_SHARE_DELETE. Do this by opening with DELETE_ACCESS.
3363 * If that works, delete them all by setting the delete on close and close.
3366 NTSTATUS open_streams_for_delete(connection_struct *conn,
3367 const char *fname)
3369 struct stream_struct *stream_info = NULL;
3370 files_struct **streams = NULL;
3371 int i;
3372 unsigned int num_streams = 0;
3373 TALLOC_CTX *frame = talloc_stackframe();
3374 NTSTATUS status;
3376 status = vfs_streaminfo(conn, NULL, fname, talloc_tos(),
3377 &num_streams, &stream_info);
3379 if (NT_STATUS_EQUAL(status, NT_STATUS_NOT_IMPLEMENTED)
3380 || NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
3381 DEBUG(10, ("no streams around\n"));
3382 TALLOC_FREE(frame);
3383 return NT_STATUS_OK;
3386 if (!NT_STATUS_IS_OK(status)) {
3387 DEBUG(10, ("vfs_streaminfo failed: %s\n",
3388 nt_errstr(status)));
3389 goto fail;
3392 DEBUG(10, ("open_streams_for_delete found %d streams\n",
3393 num_streams));
3395 if (num_streams == 0) {
3396 TALLOC_FREE(frame);
3397 return NT_STATUS_OK;
3400 streams = talloc_array(talloc_tos(), files_struct *, num_streams);
3401 if (streams == NULL) {
3402 DEBUG(0, ("talloc failed\n"));
3403 status = NT_STATUS_NO_MEMORY;
3404 goto fail;
3407 for (i=0; i<num_streams; i++) {
3408 struct smb_filename *smb_fname;
3410 if (strequal(stream_info[i].name, "::$DATA")) {
3411 streams[i] = NULL;
3412 continue;
3415 smb_fname = synthetic_smb_fname(
3416 talloc_tos(), fname, stream_info[i].name, NULL);
3417 if (smb_fname == NULL) {
3418 status = NT_STATUS_NO_MEMORY;
3419 goto fail;
3422 if (SMB_VFS_STAT(conn, smb_fname) == -1) {
3423 DEBUG(10, ("Unable to stat stream: %s\n",
3424 smb_fname_str_dbg(smb_fname)));
3427 status = SMB_VFS_CREATE_FILE(
3428 conn, /* conn */
3429 NULL, /* req */
3430 0, /* root_dir_fid */
3431 smb_fname, /* fname */
3432 DELETE_ACCESS, /* access_mask */
3433 (FILE_SHARE_READ | /* share_access */
3434 FILE_SHARE_WRITE | FILE_SHARE_DELETE),
3435 FILE_OPEN, /* create_disposition*/
3436 0, /* create_options */
3437 FILE_ATTRIBUTE_NORMAL, /* file_attributes */
3438 0, /* oplock_request */
3439 0, /* allocation_size */
3440 NTCREATEX_OPTIONS_PRIVATE_STREAM_DELETE, /* private_flags */
3441 NULL, /* sd */
3442 NULL, /* ea_list */
3443 &streams[i], /* result */
3444 NULL); /* pinfo */
3446 if (!NT_STATUS_IS_OK(status)) {
3447 DEBUG(10, ("Could not open stream %s: %s\n",
3448 smb_fname_str_dbg(smb_fname),
3449 nt_errstr(status)));
3451 TALLOC_FREE(smb_fname);
3452 break;
3454 TALLOC_FREE(smb_fname);
3458 * don't touch the variable "status" beyond this point :-)
3461 for (i -= 1 ; i >= 0; i--) {
3462 if (streams[i] == NULL) {
3463 continue;
3466 DEBUG(10, ("Closing stream # %d, %s\n", i,
3467 fsp_str_dbg(streams[i])));
3468 close_file(NULL, streams[i], NORMAL_CLOSE);
3471 fail:
3472 TALLOC_FREE(frame);
3473 return status;
3476 /*********************************************************************
3477 Create a default ACL by inheriting from the parent. If no inheritance
3478 from the parent available, don't set anything. This will leave the actual
3479 permissions the new file or directory already got from the filesystem
3480 as the NT ACL when read.
3481 *********************************************************************/
3483 static NTSTATUS inherit_new_acl(files_struct *fsp)
3485 TALLOC_CTX *frame = talloc_stackframe();
3486 char *parent_name = NULL;
3487 struct security_descriptor *parent_desc = NULL;
3488 NTSTATUS status = NT_STATUS_OK;
3489 struct security_descriptor *psd = NULL;
3490 const struct dom_sid *owner_sid = NULL;
3491 const struct dom_sid *group_sid = NULL;
3492 uint32_t security_info_sent = (SECINFO_OWNER | SECINFO_GROUP | SECINFO_DACL);
3493 struct security_token *token = fsp->conn->session_info->security_token;
3494 bool inherit_owner = lp_inherit_owner(SNUM(fsp->conn));
3495 bool inheritable_components = false;
3496 bool try_builtin_administrators = false;
3497 const struct dom_sid *BA_U_sid = NULL;
3498 const struct dom_sid *BA_G_sid = NULL;
3499 bool try_system = false;
3500 const struct dom_sid *SY_U_sid = NULL;
3501 const struct dom_sid *SY_G_sid = NULL;
3502 size_t size = 0;
3504 if (!parent_dirname(frame, fsp->fsp_name->base_name, &parent_name, NULL)) {
3505 TALLOC_FREE(frame);
3506 return NT_STATUS_NO_MEMORY;
3509 status = SMB_VFS_GET_NT_ACL(fsp->conn,
3510 parent_name,
3511 (SECINFO_OWNER | SECINFO_GROUP | SECINFO_DACL),
3512 frame,
3513 &parent_desc);
3514 if (!NT_STATUS_IS_OK(status)) {
3515 TALLOC_FREE(frame);
3516 return status;
3519 inheritable_components = sd_has_inheritable_components(parent_desc,
3520 fsp->is_directory);
3522 if (!inheritable_components && !inherit_owner) {
3523 TALLOC_FREE(frame);
3524 /* Nothing to inherit and not setting owner. */
3525 return NT_STATUS_OK;
3528 /* Create an inherited descriptor from the parent. */
3530 if (DEBUGLEVEL >= 10) {
3531 DEBUG(10,("inherit_new_acl: parent acl for %s is:\n",
3532 fsp_str_dbg(fsp) ));
3533 NDR_PRINT_DEBUG(security_descriptor, parent_desc);
3536 /* Inherit from parent descriptor if "inherit owner" set. */
3537 if (inherit_owner) {
3538 owner_sid = parent_desc->owner_sid;
3539 group_sid = parent_desc->group_sid;
3542 if (owner_sid == NULL) {
3543 if (security_token_has_builtin_administrators(token)) {
3544 try_builtin_administrators = true;
3545 } else if (security_token_is_system(token)) {
3546 try_builtin_administrators = true;
3547 try_system = true;
3551 if (group_sid == NULL &&
3552 token->num_sids == PRIMARY_GROUP_SID_INDEX)
3554 if (security_token_is_system(token)) {
3555 try_builtin_administrators = true;
3556 try_system = true;
3560 if (try_builtin_administrators) {
3561 struct unixid ids;
3562 bool ok;
3564 ZERO_STRUCT(ids);
3565 ok = sids_to_unixids(&global_sid_Builtin_Administrators, 1, &ids);
3566 if (ok) {
3567 switch (ids.type) {
3568 case ID_TYPE_BOTH:
3569 BA_U_sid = &global_sid_Builtin_Administrators;
3570 BA_G_sid = &global_sid_Builtin_Administrators;
3571 break;
3572 case ID_TYPE_UID:
3573 BA_U_sid = &global_sid_Builtin_Administrators;
3574 break;
3575 case ID_TYPE_GID:
3576 BA_G_sid = &global_sid_Builtin_Administrators;
3577 break;
3578 default:
3579 break;
3584 if (try_system) {
3585 struct unixid ids;
3586 bool ok;
3588 ZERO_STRUCT(ids);
3589 ok = sids_to_unixids(&global_sid_System, 1, &ids);
3590 if (ok) {
3591 switch (ids.type) {
3592 case ID_TYPE_BOTH:
3593 SY_U_sid = &global_sid_System;
3594 SY_G_sid = &global_sid_System;
3595 break;
3596 case ID_TYPE_UID:
3597 SY_U_sid = &global_sid_System;
3598 break;
3599 case ID_TYPE_GID:
3600 SY_G_sid = &global_sid_System;
3601 break;
3602 default:
3603 break;
3608 if (owner_sid == NULL) {
3609 owner_sid = BA_U_sid;
3612 if (owner_sid == NULL) {
3613 owner_sid = SY_U_sid;
3616 if (group_sid == NULL) {
3617 group_sid = SY_G_sid;
3620 if (try_system && group_sid == NULL) {
3621 group_sid = BA_G_sid;
3624 if (owner_sid == NULL) {
3625 owner_sid = &token->sids[PRIMARY_USER_SID_INDEX];
3627 if (group_sid == NULL) {
3628 if (token->num_sids == PRIMARY_GROUP_SID_INDEX) {
3629 group_sid = &token->sids[PRIMARY_USER_SID_INDEX];
3630 } else {
3631 group_sid = &token->sids[PRIMARY_GROUP_SID_INDEX];
3635 status = se_create_child_secdesc(frame,
3636 &psd,
3637 &size,
3638 parent_desc,
3639 owner_sid,
3640 group_sid,
3641 fsp->is_directory);
3642 if (!NT_STATUS_IS_OK(status)) {
3643 TALLOC_FREE(frame);
3644 return status;
3647 /* If inheritable_components == false,
3648 se_create_child_secdesc()
3649 creates a security desriptor with a NULL dacl
3650 entry, but with SEC_DESC_DACL_PRESENT. We need
3651 to remove that flag. */
3653 if (!inheritable_components) {
3654 security_info_sent &= ~SECINFO_DACL;
3655 psd->type &= ~SEC_DESC_DACL_PRESENT;
3658 if (DEBUGLEVEL >= 10) {
3659 DEBUG(10,("inherit_new_acl: child acl for %s is:\n",
3660 fsp_str_dbg(fsp) ));
3661 NDR_PRINT_DEBUG(security_descriptor, psd);
3664 if (inherit_owner) {
3665 /* We need to be root to force this. */
3666 become_root();
3668 status = SMB_VFS_FSET_NT_ACL(fsp,
3669 security_info_sent,
3670 psd);
3671 if (inherit_owner) {
3672 unbecome_root();
3674 TALLOC_FREE(frame);
3675 return status;
3679 * Wrapper around open_file_ntcreate and open_directory
3682 static NTSTATUS create_file_unixpath(connection_struct *conn,
3683 struct smb_request *req,
3684 struct smb_filename *smb_fname,
3685 uint32_t access_mask,
3686 uint32_t share_access,
3687 uint32_t create_disposition,
3688 uint32_t create_options,
3689 uint32_t file_attributes,
3690 uint32_t oplock_request,
3691 uint64_t allocation_size,
3692 uint32_t private_flags,
3693 struct security_descriptor *sd,
3694 struct ea_list *ea_list,
3696 files_struct **result,
3697 int *pinfo)
3699 int info = FILE_WAS_OPENED;
3700 files_struct *base_fsp = NULL;
3701 files_struct *fsp = NULL;
3702 NTSTATUS status;
3704 DEBUG(10,("create_file_unixpath: access_mask = 0x%x "
3705 "file_attributes = 0x%x, share_access = 0x%x, "
3706 "create_disposition = 0x%x create_options = 0x%x "
3707 "oplock_request = 0x%x private_flags = 0x%x "
3708 "ea_list = 0x%p, sd = 0x%p, "
3709 "fname = %s\n",
3710 (unsigned int)access_mask,
3711 (unsigned int)file_attributes,
3712 (unsigned int)share_access,
3713 (unsigned int)create_disposition,
3714 (unsigned int)create_options,
3715 (unsigned int)oplock_request,
3716 (unsigned int)private_flags,
3717 ea_list, sd, smb_fname_str_dbg(smb_fname)));
3719 if (create_options & FILE_OPEN_BY_FILE_ID) {
3720 status = NT_STATUS_NOT_SUPPORTED;
3721 goto fail;
3724 if (create_options & NTCREATEX_OPTIONS_INVALID_PARAM_MASK) {
3725 status = NT_STATUS_INVALID_PARAMETER;
3726 goto fail;
3729 if (req == NULL) {
3730 oplock_request |= INTERNAL_OPEN_ONLY;
3733 if ((conn->fs_capabilities & FILE_NAMED_STREAMS)
3734 && (access_mask & DELETE_ACCESS)
3735 && !is_ntfs_stream_smb_fname(smb_fname)) {
3737 * We can't open a file with DELETE access if any of the
3738 * streams is open without FILE_SHARE_DELETE
3740 status = open_streams_for_delete(conn, smb_fname->base_name);
3742 if (!NT_STATUS_IS_OK(status)) {
3743 goto fail;
3747 if ((access_mask & SEC_FLAG_SYSTEM_SECURITY) &&
3748 !security_token_has_privilege(get_current_nttok(conn),
3749 SEC_PRIV_SECURITY)) {
3750 DEBUG(10, ("create_file_unixpath: open on %s "
3751 "failed - SEC_FLAG_SYSTEM_SECURITY denied.\n",
3752 smb_fname_str_dbg(smb_fname)));
3753 status = NT_STATUS_PRIVILEGE_NOT_HELD;
3754 goto fail;
3757 if ((conn->fs_capabilities & FILE_NAMED_STREAMS)
3758 && is_ntfs_stream_smb_fname(smb_fname)
3759 && (!(private_flags & NTCREATEX_OPTIONS_PRIVATE_STREAM_DELETE))) {
3760 uint32 base_create_disposition;
3761 struct smb_filename *smb_fname_base = NULL;
3763 if (create_options & FILE_DIRECTORY_FILE) {
3764 status = NT_STATUS_NOT_A_DIRECTORY;
3765 goto fail;
3768 switch (create_disposition) {
3769 case FILE_OPEN:
3770 base_create_disposition = FILE_OPEN;
3771 break;
3772 default:
3773 base_create_disposition = FILE_OPEN_IF;
3774 break;
3777 /* Create an smb_filename with stream_name == NULL. */
3778 smb_fname_base = synthetic_smb_fname(talloc_tos(),
3779 smb_fname->base_name,
3780 NULL, NULL);
3781 if (smb_fname_base == NULL) {
3782 status = NT_STATUS_NO_MEMORY;
3783 goto fail;
3786 if (SMB_VFS_STAT(conn, smb_fname_base) == -1) {
3787 DEBUG(10, ("Unable to stat stream: %s\n",
3788 smb_fname_str_dbg(smb_fname_base)));
3789 } else {
3791 * https://bugzilla.samba.org/show_bug.cgi?id=10229
3792 * We need to check if the requested access mask
3793 * could be used to open the underlying file (if
3794 * it existed), as we're passing in zero for the
3795 * access mask to the base filename.
3797 status = check_base_file_access(conn,
3798 smb_fname_base,
3799 access_mask);
3801 if (!NT_STATUS_IS_OK(status)) {
3802 DEBUG(10, ("Permission check "
3803 "for base %s failed: "
3804 "%s\n", smb_fname->base_name,
3805 nt_errstr(status)));
3806 goto fail;
3810 /* Open the base file. */
3811 status = create_file_unixpath(conn, NULL, smb_fname_base, 0,
3812 FILE_SHARE_READ
3813 | FILE_SHARE_WRITE
3814 | FILE_SHARE_DELETE,
3815 base_create_disposition,
3816 0, 0, 0, 0, 0, NULL, NULL,
3817 &base_fsp, NULL);
3818 TALLOC_FREE(smb_fname_base);
3820 if (!NT_STATUS_IS_OK(status)) {
3821 DEBUG(10, ("create_file_unixpath for base %s failed: "
3822 "%s\n", smb_fname->base_name,
3823 nt_errstr(status)));
3824 goto fail;
3826 /* we don't need to low level fd */
3827 fd_close(base_fsp);
3831 * If it's a request for a directory open, deal with it separately.
3834 if (create_options & FILE_DIRECTORY_FILE) {
3836 if (create_options & FILE_NON_DIRECTORY_FILE) {
3837 status = NT_STATUS_INVALID_PARAMETER;
3838 goto fail;
3841 /* Can't open a temp directory. IFS kit test. */
3842 if (!(file_attributes & FILE_FLAG_POSIX_SEMANTICS) &&
3843 (file_attributes & FILE_ATTRIBUTE_TEMPORARY)) {
3844 status = NT_STATUS_INVALID_PARAMETER;
3845 goto fail;
3849 * We will get a create directory here if the Win32
3850 * app specified a security descriptor in the
3851 * CreateDirectory() call.
3854 oplock_request = 0;
3855 status = open_directory(
3856 conn, req, smb_fname, access_mask, share_access,
3857 create_disposition, create_options, file_attributes,
3858 &info, &fsp);
3859 } else {
3862 * Ordinary file case.
3865 status = file_new(req, conn, &fsp);
3866 if(!NT_STATUS_IS_OK(status)) {
3867 goto fail;
3870 status = fsp_set_smb_fname(fsp, smb_fname);
3871 if (!NT_STATUS_IS_OK(status)) {
3872 goto fail;
3875 if (base_fsp) {
3877 * We're opening the stream element of a
3878 * base_fsp we already opened. Set up the
3879 * base_fsp pointer.
3881 fsp->base_fsp = base_fsp;
3884 if (allocation_size) {
3885 fsp->initial_allocation_size = smb_roundup(fsp->conn,
3886 allocation_size);
3889 status = open_file_ntcreate(conn,
3890 req,
3891 access_mask,
3892 share_access,
3893 create_disposition,
3894 create_options,
3895 file_attributes,
3896 oplock_request,
3897 private_flags,
3898 &info,
3899 fsp);
3901 if(!NT_STATUS_IS_OK(status)) {
3902 file_free(req, fsp);
3903 fsp = NULL;
3906 if (NT_STATUS_EQUAL(status, NT_STATUS_FILE_IS_A_DIRECTORY)) {
3908 /* A stream open never opens a directory */
3910 if (base_fsp) {
3911 status = NT_STATUS_FILE_IS_A_DIRECTORY;
3912 goto fail;
3916 * Fail the open if it was explicitly a non-directory
3917 * file.
3920 if (create_options & FILE_NON_DIRECTORY_FILE) {
3921 status = NT_STATUS_FILE_IS_A_DIRECTORY;
3922 goto fail;
3925 oplock_request = 0;
3926 status = open_directory(
3927 conn, req, smb_fname, access_mask,
3928 share_access, create_disposition,
3929 create_options, file_attributes,
3930 &info, &fsp);
3934 if (!NT_STATUS_IS_OK(status)) {
3935 goto fail;
3938 fsp->base_fsp = base_fsp;
3940 if ((ea_list != NULL) &&
3941 ((info == FILE_WAS_CREATED) || (info == FILE_WAS_OVERWRITTEN))) {
3942 status = set_ea(conn, fsp, fsp->fsp_name, ea_list);
3943 if (!NT_STATUS_IS_OK(status)) {
3944 goto fail;
3948 if (!fsp->is_directory && S_ISDIR(fsp->fsp_name->st.st_ex_mode)) {
3949 status = NT_STATUS_ACCESS_DENIED;
3950 goto fail;
3953 /* Save the requested allocation size. */
3954 if ((info == FILE_WAS_CREATED) || (info == FILE_WAS_OVERWRITTEN)) {
3955 if (allocation_size
3956 && (allocation_size > fsp->fsp_name->st.st_ex_size)) {
3957 fsp->initial_allocation_size = smb_roundup(
3958 fsp->conn, allocation_size);
3959 if (fsp->is_directory) {
3960 /* Can't set allocation size on a directory. */
3961 status = NT_STATUS_ACCESS_DENIED;
3962 goto fail;
3964 if (vfs_allocate_file_space(
3965 fsp, fsp->initial_allocation_size) == -1) {
3966 status = NT_STATUS_DISK_FULL;
3967 goto fail;
3969 } else {
3970 fsp->initial_allocation_size = smb_roundup(
3971 fsp->conn, (uint64_t)fsp->fsp_name->st.st_ex_size);
3973 } else {
3974 fsp->initial_allocation_size = 0;
3977 if ((info == FILE_WAS_CREATED) && lp_nt_acl_support(SNUM(conn)) &&
3978 fsp->base_fsp == NULL) {
3979 if (sd != NULL) {
3981 * According to the MS documentation, the only time the security
3982 * descriptor is applied to the opened file is iff we *created* the
3983 * file; an existing file stays the same.
3985 * Also, it seems (from observation) that you can open the file with
3986 * any access mask but you can still write the sd. We need to override
3987 * the granted access before we call set_sd
3988 * Patch for bug #2242 from Tom Lackemann <cessnatomny@yahoo.com>.
3991 uint32_t sec_info_sent;
3992 uint32_t saved_access_mask = fsp->access_mask;
3994 sec_info_sent = get_sec_info(sd);
3996 fsp->access_mask = FILE_GENERIC_ALL;
3998 if (sec_info_sent & (SECINFO_OWNER|
3999 SECINFO_GROUP|
4000 SECINFO_DACL|
4001 SECINFO_SACL)) {
4002 status = set_sd(fsp, sd, sec_info_sent);
4005 fsp->access_mask = saved_access_mask;
4007 if (!NT_STATUS_IS_OK(status)) {
4008 goto fail;
4010 } else if (lp_inherit_acls(SNUM(conn))) {
4011 /* Inherit from parent. Errors here are not fatal. */
4012 status = inherit_new_acl(fsp);
4013 if (!NT_STATUS_IS_OK(status)) {
4014 DEBUG(10,("inherit_new_acl: failed for %s with %s\n",
4015 fsp_str_dbg(fsp),
4016 nt_errstr(status) ));
4021 DEBUG(10, ("create_file_unixpath: info=%d\n", info));
4023 *result = fsp;
4024 if (pinfo != NULL) {
4025 *pinfo = info;
4028 smb_fname->st = fsp->fsp_name->st;
4030 return NT_STATUS_OK;
4032 fail:
4033 DEBUG(10, ("create_file_unixpath: %s\n", nt_errstr(status)));
4035 if (fsp != NULL) {
4036 if (base_fsp && fsp->base_fsp == base_fsp) {
4038 * The close_file below will close
4039 * fsp->base_fsp.
4041 base_fsp = NULL;
4043 close_file(req, fsp, ERROR_CLOSE);
4044 fsp = NULL;
4046 if (base_fsp != NULL) {
4047 close_file(req, base_fsp, ERROR_CLOSE);
4048 base_fsp = NULL;
4050 return status;
4054 * Calculate the full path name given a relative fid.
4056 NTSTATUS get_relative_fid_filename(connection_struct *conn,
4057 struct smb_request *req,
4058 uint16_t root_dir_fid,
4059 const struct smb_filename *smb_fname,
4060 struct smb_filename **smb_fname_out)
4062 files_struct *dir_fsp;
4063 char *parent_fname = NULL;
4064 char *new_base_name = NULL;
4065 NTSTATUS status;
4067 if (root_dir_fid == 0 || !smb_fname) {
4068 status = NT_STATUS_INTERNAL_ERROR;
4069 goto out;
4072 dir_fsp = file_fsp(req, root_dir_fid);
4074 if (dir_fsp == NULL) {
4075 status = NT_STATUS_INVALID_HANDLE;
4076 goto out;
4079 if (is_ntfs_stream_smb_fname(dir_fsp->fsp_name)) {
4080 status = NT_STATUS_INVALID_HANDLE;
4081 goto out;
4084 if (!dir_fsp->is_directory) {
4087 * Check to see if this is a mac fork of some kind.
4090 if ((conn->fs_capabilities & FILE_NAMED_STREAMS) &&
4091 is_ntfs_stream_smb_fname(smb_fname)) {
4092 status = NT_STATUS_OBJECT_PATH_NOT_FOUND;
4093 goto out;
4097 we need to handle the case when we get a
4098 relative open relative to a file and the
4099 pathname is blank - this is a reopen!
4100 (hint from demyn plantenberg)
4103 status = NT_STATUS_INVALID_HANDLE;
4104 goto out;
4107 if (ISDOT(dir_fsp->fsp_name->base_name)) {
4109 * We're at the toplevel dir, the final file name
4110 * must not contain ./, as this is filtered out
4111 * normally by srvstr_get_path and unix_convert
4112 * explicitly rejects paths containing ./.
4114 parent_fname = talloc_strdup(talloc_tos(), "");
4115 if (parent_fname == NULL) {
4116 status = NT_STATUS_NO_MEMORY;
4117 goto out;
4119 } else {
4120 size_t dir_name_len = strlen(dir_fsp->fsp_name->base_name);
4123 * Copy in the base directory name.
4126 parent_fname = talloc_array(talloc_tos(), char,
4127 dir_name_len+2);
4128 if (parent_fname == NULL) {
4129 status = NT_STATUS_NO_MEMORY;
4130 goto out;
4132 memcpy(parent_fname, dir_fsp->fsp_name->base_name,
4133 dir_name_len+1);
4136 * Ensure it ends in a '/'.
4137 * We used TALLOC_SIZE +2 to add space for the '/'.
4140 if(dir_name_len
4141 && (parent_fname[dir_name_len-1] != '\\')
4142 && (parent_fname[dir_name_len-1] != '/')) {
4143 parent_fname[dir_name_len] = '/';
4144 parent_fname[dir_name_len+1] = '\0';
4148 new_base_name = talloc_asprintf(talloc_tos(), "%s%s", parent_fname,
4149 smb_fname->base_name);
4150 if (new_base_name == NULL) {
4151 status = NT_STATUS_NO_MEMORY;
4152 goto out;
4155 status = filename_convert(req,
4156 conn,
4157 req->flags2 & FLAGS2_DFS_PATHNAMES,
4158 new_base_name,
4160 NULL,
4161 smb_fname_out);
4162 if (!NT_STATUS_IS_OK(status)) {
4163 goto out;
4166 out:
4167 TALLOC_FREE(parent_fname);
4168 TALLOC_FREE(new_base_name);
4169 return status;
4172 NTSTATUS create_file_default(connection_struct *conn,
4173 struct smb_request *req,
4174 uint16_t root_dir_fid,
4175 struct smb_filename *smb_fname,
4176 uint32_t access_mask,
4177 uint32_t share_access,
4178 uint32_t create_disposition,
4179 uint32_t create_options,
4180 uint32_t file_attributes,
4181 uint32_t oplock_request,
4182 uint64_t allocation_size,
4183 uint32_t private_flags,
4184 struct security_descriptor *sd,
4185 struct ea_list *ea_list,
4186 files_struct **result,
4187 int *pinfo)
4189 int info = FILE_WAS_OPENED;
4190 files_struct *fsp = NULL;
4191 NTSTATUS status;
4192 bool stream_name = false;
4194 DEBUG(10,("create_file: access_mask = 0x%x "
4195 "file_attributes = 0x%x, share_access = 0x%x, "
4196 "create_disposition = 0x%x create_options = 0x%x "
4197 "oplock_request = 0x%x "
4198 "private_flags = 0x%x "
4199 "root_dir_fid = 0x%x, ea_list = 0x%p, sd = 0x%p, "
4200 "fname = %s\n",
4201 (unsigned int)access_mask,
4202 (unsigned int)file_attributes,
4203 (unsigned int)share_access,
4204 (unsigned int)create_disposition,
4205 (unsigned int)create_options,
4206 (unsigned int)oplock_request,
4207 (unsigned int)private_flags,
4208 (unsigned int)root_dir_fid,
4209 ea_list, sd, smb_fname_str_dbg(smb_fname)));
4212 * Calculate the filename from the root_dir_if if necessary.
4215 if (root_dir_fid != 0) {
4216 struct smb_filename *smb_fname_out = NULL;
4217 status = get_relative_fid_filename(conn, req, root_dir_fid,
4218 smb_fname, &smb_fname_out);
4219 if (!NT_STATUS_IS_OK(status)) {
4220 goto fail;
4222 smb_fname = smb_fname_out;
4226 * Check to see if this is a mac fork of some kind.
4229 stream_name = is_ntfs_stream_smb_fname(smb_fname);
4230 if (stream_name) {
4231 enum FAKE_FILE_TYPE fake_file_type;
4233 fake_file_type = is_fake_file(smb_fname);
4235 if (fake_file_type != FAKE_FILE_TYPE_NONE) {
4238 * Here we go! support for changing the disk quotas
4239 * --metze
4241 * We need to fake up to open this MAGIC QUOTA file
4242 * and return a valid FID.
4244 * w2k close this file directly after openening xp
4245 * also tries a QUERY_FILE_INFO on the file and then
4246 * close it
4248 status = open_fake_file(req, conn, req->vuid,
4249 fake_file_type, smb_fname,
4250 access_mask, &fsp);
4251 if (!NT_STATUS_IS_OK(status)) {
4252 goto fail;
4255 ZERO_STRUCT(smb_fname->st);
4256 goto done;
4259 if (!(conn->fs_capabilities & FILE_NAMED_STREAMS)) {
4260 status = NT_STATUS_OBJECT_NAME_NOT_FOUND;
4261 goto fail;
4265 if (is_ntfs_default_stream_smb_fname(smb_fname)) {
4266 int ret;
4267 smb_fname->stream_name = NULL;
4268 /* We have to handle this error here. */
4269 if (create_options & FILE_DIRECTORY_FILE) {
4270 status = NT_STATUS_NOT_A_DIRECTORY;
4271 goto fail;
4273 if (lp_posix_pathnames()) {
4274 ret = SMB_VFS_LSTAT(conn, smb_fname);
4275 } else {
4276 ret = SMB_VFS_STAT(conn, smb_fname);
4279 if (ret == 0 && VALID_STAT_OF_DIR(smb_fname->st)) {
4280 status = NT_STATUS_FILE_IS_A_DIRECTORY;
4281 goto fail;
4285 status = create_file_unixpath(
4286 conn, req, smb_fname, access_mask, share_access,
4287 create_disposition, create_options, file_attributes,
4288 oplock_request, allocation_size, private_flags,
4289 sd, ea_list,
4290 &fsp, &info);
4292 if (!NT_STATUS_IS_OK(status)) {
4293 goto fail;
4296 done:
4297 DEBUG(10, ("create_file: info=%d\n", info));
4299 *result = fsp;
4300 if (pinfo != NULL) {
4301 *pinfo = info;
4303 return NT_STATUS_OK;
4305 fail:
4306 DEBUG(10, ("create_file: %s\n", nt_errstr(status)));
4308 if (fsp != NULL) {
4309 close_file(req, fsp, ERROR_CLOSE);
4310 fsp = NULL;
4312 return status;