VERSION: Disable git snapshots for the 4.1.0rc4 release.
[Samba.git] / source3 / smbd / open.c
blob10b04e7f9e51fdb3ecef1f4f7035af02a87b4ddd
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 fd support routines - attempt to do a dos_open.
306 ****************************************************************************/
308 NTSTATUS fd_open(struct connection_struct *conn,
309 files_struct *fsp,
310 int flags,
311 mode_t mode)
313 struct smb_filename *smb_fname = fsp->fsp_name;
314 NTSTATUS status = NT_STATUS_OK;
316 #ifdef O_NOFOLLOW
318 * Never follow symlinks on a POSIX client. The
319 * client should be doing this.
322 if (fsp->posix_open || !lp_symlinks(SNUM(conn))) {
323 flags |= O_NOFOLLOW;
325 #endif
327 fsp->fh->fd = SMB_VFS_OPEN(conn, smb_fname, fsp, flags, mode);
328 if (fsp->fh->fd == -1) {
329 int posix_errno = errno;
330 #ifdef O_NOFOLLOW
331 #if defined(ENOTSUP) && defined(OSF1)
332 /* handle special Tru64 errno */
333 if (errno == ENOTSUP) {
334 posix_errno = ELOOP;
336 #endif /* ENOTSUP */
337 #ifdef EFTYPE
338 /* fix broken NetBSD errno */
339 if (errno == EFTYPE) {
340 posix_errno = ELOOP;
342 #endif /* EFTYPE */
343 /* fix broken FreeBSD errno */
344 if (errno == EMLINK) {
345 posix_errno = ELOOP;
347 #endif /* O_NOFOLLOW */
348 status = map_nt_error_from_unix(posix_errno);
349 if (errno == EMFILE) {
350 static time_t last_warned = 0L;
352 if (time((time_t *) NULL) > last_warned) {
353 DEBUG(0,("Too many open files, unable "
354 "to open more! smbd's max "
355 "open files = %d\n",
356 lp_max_open_files()));
357 last_warned = time((time_t *) NULL);
363 DEBUG(10,("fd_open: name %s, flags = 0%o mode = 0%o, fd = %d. %s\n",
364 smb_fname_str_dbg(smb_fname), flags, (int)mode, fsp->fh->fd,
365 (fsp->fh->fd == -1) ? strerror(errno) : "" ));
367 return status;
370 /****************************************************************************
371 Close the file associated with a fsp.
372 ****************************************************************************/
374 NTSTATUS fd_close(files_struct *fsp)
376 int ret;
378 if (fsp->dptr) {
379 dptr_CloseDir(fsp);
381 if (fsp->fh->fd == -1) {
382 return NT_STATUS_OK; /* What we used to call a stat open. */
384 if (fsp->fh->ref_count > 1) {
385 return NT_STATUS_OK; /* Shared handle. Only close last reference. */
388 ret = SMB_VFS_CLOSE(fsp);
389 fsp->fh->fd = -1;
390 if (ret == -1) {
391 return map_nt_error_from_unix(errno);
393 return NT_STATUS_OK;
396 /****************************************************************************
397 Change the ownership of a file to that of the parent directory.
398 Do this by fd if possible.
399 ****************************************************************************/
401 void change_file_owner_to_parent(connection_struct *conn,
402 const char *inherit_from_dir,
403 files_struct *fsp)
405 struct smb_filename *smb_fname_parent;
406 int ret;
408 smb_fname_parent = synthetic_smb_fname(talloc_tos(), inherit_from_dir,
409 NULL, NULL);
410 if (smb_fname_parent == NULL) {
411 return;
414 ret = SMB_VFS_STAT(conn, smb_fname_parent);
415 if (ret == -1) {
416 DEBUG(0,("change_file_owner_to_parent: failed to stat parent "
417 "directory %s. Error was %s\n",
418 smb_fname_str_dbg(smb_fname_parent),
419 strerror(errno)));
420 TALLOC_FREE(smb_fname_parent);
421 return;
424 if (smb_fname_parent->st.st_ex_uid == fsp->fsp_name->st.st_ex_uid) {
425 /* Already this uid - no need to change. */
426 DEBUG(10,("change_file_owner_to_parent: file %s "
427 "is already owned by uid %d\n",
428 fsp_str_dbg(fsp),
429 (int)fsp->fsp_name->st.st_ex_uid ));
430 TALLOC_FREE(smb_fname_parent);
431 return;
434 become_root();
435 ret = SMB_VFS_FCHOWN(fsp, smb_fname_parent->st.st_ex_uid, (gid_t)-1);
436 unbecome_root();
437 if (ret == -1) {
438 DEBUG(0,("change_file_owner_to_parent: failed to fchown "
439 "file %s to parent directory uid %u. Error "
440 "was %s\n", fsp_str_dbg(fsp),
441 (unsigned int)smb_fname_parent->st.st_ex_uid,
442 strerror(errno) ));
443 } else {
444 DEBUG(10,("change_file_owner_to_parent: changed new file %s to "
445 "parent directory uid %u.\n", fsp_str_dbg(fsp),
446 (unsigned int)smb_fname_parent->st.st_ex_uid));
447 /* Ensure the uid entry is updated. */
448 fsp->fsp_name->st.st_ex_uid = smb_fname_parent->st.st_ex_uid;
451 TALLOC_FREE(smb_fname_parent);
454 NTSTATUS change_dir_owner_to_parent(connection_struct *conn,
455 const char *inherit_from_dir,
456 const char *fname,
457 SMB_STRUCT_STAT *psbuf)
459 struct smb_filename *smb_fname_parent;
460 struct smb_filename *smb_fname_cwd = NULL;
461 char *saved_dir = NULL;
462 TALLOC_CTX *ctx = talloc_tos();
463 NTSTATUS status = NT_STATUS_OK;
464 int ret;
466 smb_fname_parent = synthetic_smb_fname(ctx, inherit_from_dir,
467 NULL, NULL);
468 if (smb_fname_parent == NULL) {
469 return NT_STATUS_NO_MEMORY;
472 ret = SMB_VFS_STAT(conn, smb_fname_parent);
473 if (ret == -1) {
474 status = map_nt_error_from_unix(errno);
475 DEBUG(0,("change_dir_owner_to_parent: failed to stat parent "
476 "directory %s. Error was %s\n",
477 smb_fname_str_dbg(smb_fname_parent),
478 strerror(errno)));
479 goto out;
482 /* We've already done an lstat into psbuf, and we know it's a
483 directory. If we can cd into the directory and the dev/ino
484 are the same then we can safely chown without races as
485 we're locking the directory in place by being in it. This
486 should work on any UNIX (thanks tridge :-). JRA.
489 saved_dir = vfs_GetWd(ctx,conn);
490 if (!saved_dir) {
491 status = map_nt_error_from_unix(errno);
492 DEBUG(0,("change_dir_owner_to_parent: failed to get "
493 "current working directory. Error was %s\n",
494 strerror(errno)));
495 goto out;
498 /* Chdir into the new path. */
499 if (vfs_ChDir(conn, fname) == -1) {
500 status = map_nt_error_from_unix(errno);
501 DEBUG(0,("change_dir_owner_to_parent: failed to change "
502 "current working directory to %s. Error "
503 "was %s\n", fname, strerror(errno) ));
504 goto chdir;
507 smb_fname_cwd = synthetic_smb_fname(ctx, ".", NULL, NULL);
508 if (smb_fname_cwd == NULL) {
509 status = NT_STATUS_NO_MEMORY;
510 goto chdir;
513 ret = SMB_VFS_STAT(conn, smb_fname_cwd);
514 if (ret == -1) {
515 status = map_nt_error_from_unix(errno);
516 DEBUG(0,("change_dir_owner_to_parent: failed to stat "
517 "directory '.' (%s) Error was %s\n",
518 fname, strerror(errno)));
519 goto chdir;
522 /* Ensure we're pointing at the same place. */
523 if (smb_fname_cwd->st.st_ex_dev != psbuf->st_ex_dev ||
524 smb_fname_cwd->st.st_ex_ino != psbuf->st_ex_ino) {
525 DEBUG(0,("change_dir_owner_to_parent: "
526 "device/inode on directory %s changed. "
527 "Refusing to chown !\n", fname ));
528 status = NT_STATUS_ACCESS_DENIED;
529 goto chdir;
532 if (smb_fname_parent->st.st_ex_uid == smb_fname_cwd->st.st_ex_uid) {
533 /* Already this uid - no need to change. */
534 DEBUG(10,("change_dir_owner_to_parent: directory %s "
535 "is already owned by uid %d\n",
536 fname,
537 (int)smb_fname_cwd->st.st_ex_uid ));
538 status = NT_STATUS_OK;
539 goto chdir;
542 become_root();
543 ret = SMB_VFS_LCHOWN(conn, ".", smb_fname_parent->st.st_ex_uid,
544 (gid_t)-1);
545 unbecome_root();
546 if (ret == -1) {
547 status = map_nt_error_from_unix(errno);
548 DEBUG(10,("change_dir_owner_to_parent: failed to chown "
549 "directory %s to parent directory uid %u. "
550 "Error was %s\n", fname,
551 (unsigned int)smb_fname_parent->st.st_ex_uid,
552 strerror(errno) ));
553 } else {
554 DEBUG(10,("change_dir_owner_to_parent: changed ownership of new "
555 "directory %s to parent directory uid %u.\n",
556 fname, (unsigned int)smb_fname_parent->st.st_ex_uid ));
557 /* Ensure the uid entry is updated. */
558 psbuf->st_ex_uid = smb_fname_parent->st.st_ex_uid;
561 chdir:
562 vfs_ChDir(conn,saved_dir);
563 out:
564 TALLOC_FREE(smb_fname_parent);
565 TALLOC_FREE(smb_fname_cwd);
566 return status;
569 /****************************************************************************
570 Open a file - returning a guaranteed ATOMIC indication of if the
571 file was created or not.
572 ****************************************************************************/
574 static NTSTATUS fd_open_atomic(struct connection_struct *conn,
575 files_struct *fsp,
576 int flags,
577 mode_t mode,
578 bool *file_created)
580 NTSTATUS status = NT_STATUS_UNSUCCESSFUL;
581 bool file_existed = VALID_STAT(fsp->fsp_name->st);
583 *file_created = false;
585 if (!(flags & O_CREAT)) {
587 * We're not creating the file, just pass through.
589 return fd_open(conn, fsp, flags, mode);
592 if (flags & O_EXCL) {
594 * Fail if already exists, just pass through.
596 status = fd_open(conn, fsp, flags, mode);
599 * Here we've opened with O_CREAT|O_EXCL. If that went
600 * NT_STATUS_OK, we *know* we created this file.
602 *file_created = NT_STATUS_IS_OK(status);
604 return status;
608 * Now it gets tricky. We have O_CREAT, but not O_EXCL.
609 * To know absolutely if we created the file or not,
610 * we can never call O_CREAT without O_EXCL. So if
611 * we think the file existed, try without O_CREAT|O_EXCL.
612 * If we think the file didn't exist, try with
613 * O_CREAT|O_EXCL. Keep bouncing between these two
614 * requests until either the file is created, or
615 * opened. Either way, we keep going until we get
616 * a returnable result (error, or open/create).
619 while(1) {
620 int curr_flags = flags;
622 if (file_existed) {
623 /* Just try open, do not create. */
624 curr_flags &= ~(O_CREAT);
625 status = fd_open(conn, fsp, curr_flags, mode);
626 if (NT_STATUS_EQUAL(status,
627 NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
629 * Someone deleted it in the meantime.
630 * Retry with O_EXCL.
632 file_existed = false;
633 DEBUG(10,("fd_open_atomic: file %s existed. "
634 "Retry.\n",
635 smb_fname_str_dbg(fsp->fsp_name)));
636 continue;
638 } else {
639 /* Try create exclusively, fail if it exists. */
640 curr_flags |= O_EXCL;
641 status = fd_open(conn, fsp, curr_flags, mode);
642 if (NT_STATUS_EQUAL(status,
643 NT_STATUS_OBJECT_NAME_COLLISION)) {
645 * Someone created it in the meantime.
646 * Retry without O_CREAT.
648 file_existed = true;
649 DEBUG(10,("fd_open_atomic: file %s "
650 "did not exist. Retry.\n",
651 smb_fname_str_dbg(fsp->fsp_name)));
652 continue;
654 if (NT_STATUS_IS_OK(status)) {
656 * Here we've opened with O_CREAT|O_EXCL
657 * and got success. We *know* we created
658 * this file.
660 *file_created = true;
663 /* Create is done, or failed. */
664 break;
666 return status;
669 /****************************************************************************
670 Open a file.
671 ****************************************************************************/
673 static NTSTATUS open_file(files_struct *fsp,
674 connection_struct *conn,
675 struct smb_request *req,
676 const char *parent_dir,
677 int flags,
678 mode_t unx_mode,
679 uint32 access_mask, /* client requested access mask. */
680 uint32 open_access_mask, /* what we're actually using in the open. */
681 bool *p_file_created)
683 struct smb_filename *smb_fname = fsp->fsp_name;
684 NTSTATUS status = NT_STATUS_OK;
685 int accmode = (flags & O_ACCMODE);
686 int local_flags = flags;
687 bool file_existed = VALID_STAT(fsp->fsp_name->st);
689 fsp->fh->fd = -1;
690 errno = EPERM;
692 /* Check permissions */
695 * This code was changed after seeing a client open request
696 * containing the open mode of (DENY_WRITE/read-only) with
697 * the 'create if not exist' bit set. The previous code
698 * would fail to open the file read only on a read-only share
699 * as it was checking the flags parameter directly against O_RDONLY,
700 * this was failing as the flags parameter was set to O_RDONLY|O_CREAT.
701 * JRA.
704 if (!CAN_WRITE(conn)) {
705 /* It's a read-only share - fail if we wanted to write. */
706 if(accmode != O_RDONLY || (flags & O_TRUNC) || (flags & O_APPEND)) {
707 DEBUG(3,("Permission denied opening %s\n",
708 smb_fname_str_dbg(smb_fname)));
709 return NT_STATUS_ACCESS_DENIED;
711 if (flags & O_CREAT) {
712 /* We don't want to write - but we must make sure that
713 O_CREAT doesn't create the file if we have write
714 access into the directory.
716 flags &= ~(O_CREAT|O_EXCL);
717 local_flags &= ~(O_CREAT|O_EXCL);
722 * This little piece of insanity is inspired by the
723 * fact that an NT client can open a file for O_RDONLY,
724 * but set the create disposition to FILE_EXISTS_TRUNCATE.
725 * If the client *can* write to the file, then it expects to
726 * truncate the file, even though it is opening for readonly.
727 * Quicken uses this stupid trick in backup file creation...
728 * Thanks *greatly* to "David W. Chapman Jr." <dwcjr@inethouston.net>
729 * for helping track this one down. It didn't bite us in 2.0.x
730 * as we always opened files read-write in that release. JRA.
733 if ((accmode == O_RDONLY) && ((flags & O_TRUNC) == O_TRUNC)) {
734 DEBUG(10,("open_file: truncate requested on read-only open "
735 "for file %s\n", smb_fname_str_dbg(smb_fname)));
736 local_flags = (flags & ~O_ACCMODE)|O_RDWR;
739 if ((open_access_mask & (FILE_READ_DATA|FILE_WRITE_DATA|FILE_APPEND_DATA|FILE_EXECUTE)) ||
740 (!file_existed && (local_flags & O_CREAT)) ||
741 ((local_flags & O_TRUNC) == O_TRUNC) ) {
742 const char *wild;
743 int ret;
745 #if defined(O_NONBLOCK) && defined(S_ISFIFO)
747 * We would block on opening a FIFO with no one else on the
748 * other end. Do what we used to do and add O_NONBLOCK to the
749 * open flags. JRA.
752 if (file_existed && S_ISFIFO(smb_fname->st.st_ex_mode)) {
753 local_flags &= ~O_TRUNC; /* Can't truncate a FIFO. */
754 local_flags |= O_NONBLOCK;
756 #endif
758 /* Don't create files with Microsoft wildcard characters. */
759 if (fsp->base_fsp) {
761 * wildcard characters are allowed in stream names
762 * only test the basefilename
764 wild = fsp->base_fsp->fsp_name->base_name;
765 } else {
766 wild = smb_fname->base_name;
768 if ((local_flags & O_CREAT) && !file_existed &&
769 ms_has_wild(wild)) {
770 return NT_STATUS_OBJECT_NAME_INVALID;
773 /* Can we access this file ? */
774 if (!fsp->base_fsp) {
775 /* Only do this check on non-stream open. */
776 if (file_existed) {
777 status = smbd_check_access_rights(conn,
778 smb_fname,
779 false,
780 access_mask);
781 } else if (local_flags & O_CREAT){
782 status = check_parent_access(conn,
783 smb_fname,
784 SEC_DIR_ADD_FILE);
785 } else {
786 /* File didn't exist and no O_CREAT. */
787 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
789 if (!NT_STATUS_IS_OK(status)) {
790 DEBUG(10,("open_file: "
791 "%s on file "
792 "%s returned %s\n",
793 file_existed ?
794 "smbd_check_access_rights" :
795 "check_parent_access",
796 smb_fname_str_dbg(smb_fname),
797 nt_errstr(status) ));
798 return status;
802 /* Actually do the open */
803 status = fd_open_atomic(conn, fsp, local_flags,
804 unx_mode, p_file_created);
805 if (!NT_STATUS_IS_OK(status)) {
806 DEBUG(3,("Error opening file %s (%s) (local_flags=%d) "
807 "(flags=%d)\n", smb_fname_str_dbg(smb_fname),
808 nt_errstr(status),local_flags,flags));
809 return status;
812 ret = SMB_VFS_FSTAT(fsp, &smb_fname->st);
813 if (ret == -1) {
814 /* If we have an fd, this stat should succeed. */
815 DEBUG(0,("Error doing fstat on open file %s "
816 "(%s)\n",
817 smb_fname_str_dbg(smb_fname),
818 strerror(errno) ));
819 status = map_nt_error_from_unix(errno);
820 fd_close(fsp);
821 return status;
824 if (*p_file_created) {
825 /* We created this file. */
827 bool need_re_stat = false;
828 /* Do all inheritance work after we've
829 done a successful fstat call and filled
830 in the stat struct in fsp->fsp_name. */
832 /* Inherit the ACL if required */
833 if (lp_inherit_perms(SNUM(conn))) {
834 inherit_access_posix_acl(conn, parent_dir,
835 smb_fname->base_name,
836 unx_mode);
837 need_re_stat = true;
840 /* Change the owner if required. */
841 if (lp_inherit_owner(SNUM(conn))) {
842 change_file_owner_to_parent(conn, parent_dir,
843 fsp);
844 need_re_stat = true;
847 if (need_re_stat) {
848 ret = SMB_VFS_FSTAT(fsp, &smb_fname->st);
849 /* If we have an fd, this stat should succeed. */
850 if (ret == -1) {
851 DEBUG(0,("Error doing fstat on open file %s "
852 "(%s)\n",
853 smb_fname_str_dbg(smb_fname),
854 strerror(errno) ));
858 notify_fname(conn, NOTIFY_ACTION_ADDED,
859 FILE_NOTIFY_CHANGE_FILE_NAME,
860 smb_fname->base_name);
862 } else {
863 fsp->fh->fd = -1; /* What we used to call a stat open. */
864 if (!file_existed) {
865 /* File must exist for a stat open. */
866 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
869 status = smbd_check_access_rights(conn,
870 smb_fname,
871 false,
872 access_mask);
874 if (NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND) &&
875 fsp->posix_open &&
876 S_ISLNK(smb_fname->st.st_ex_mode)) {
877 /* This is a POSIX stat open for delete
878 * or rename on a symlink that points
879 * nowhere. Allow. */
880 DEBUG(10,("open_file: allowing POSIX "
881 "open on bad symlink %s\n",
882 smb_fname_str_dbg(smb_fname)));
883 status = NT_STATUS_OK;
886 if (!NT_STATUS_IS_OK(status)) {
887 DEBUG(10,("open_file: "
888 "smbd_check_access_rights on file "
889 "%s returned %s\n",
890 smb_fname_str_dbg(smb_fname),
891 nt_errstr(status) ));
892 return status;
897 * POSIX allows read-only opens of directories. We don't
898 * want to do this (we use a different code path for this)
899 * so catch a directory open and return an EISDIR. JRA.
902 if(S_ISDIR(smb_fname->st.st_ex_mode)) {
903 fd_close(fsp);
904 errno = EISDIR;
905 return NT_STATUS_FILE_IS_A_DIRECTORY;
908 fsp->file_id = vfs_file_id_from_sbuf(conn, &smb_fname->st);
909 fsp->vuid = req ? req->vuid : UID_FIELD_INVALID;
910 fsp->file_pid = req ? req->smbpid : 0;
911 fsp->can_lock = True;
912 fsp->can_read = ((access_mask & FILE_READ_DATA) != 0);
913 fsp->can_write =
914 CAN_WRITE(conn) &&
915 ((access_mask & (FILE_WRITE_DATA | FILE_APPEND_DATA)) != 0);
916 fsp->print_file = NULL;
917 fsp->modified = False;
918 fsp->sent_oplock_break = NO_BREAK_SENT;
919 fsp->is_directory = False;
920 if (conn->aio_write_behind_list &&
921 is_in_path(smb_fname->base_name, conn->aio_write_behind_list,
922 conn->case_sensitive)) {
923 fsp->aio_write_behind = True;
926 fsp->wcp = NULL; /* Write cache pointer. */
928 DEBUG(2,("%s opened file %s read=%s write=%s (numopen=%d)\n",
929 conn->session_info->unix_info->unix_name,
930 smb_fname_str_dbg(smb_fname),
931 BOOLSTR(fsp->can_read), BOOLSTR(fsp->can_write),
932 conn->num_files_open));
934 errno = 0;
935 return NT_STATUS_OK;
938 /****************************************************************************
939 Check if we can open a file with a share mode.
940 Returns True if conflict, False if not.
941 ****************************************************************************/
943 static bool share_conflict(struct share_mode_entry *entry,
944 uint32 access_mask,
945 uint32 share_access)
947 DEBUG(10,("share_conflict: entry->access_mask = 0x%x, "
948 "entry->share_access = 0x%x, "
949 "entry->private_options = 0x%x\n",
950 (unsigned int)entry->access_mask,
951 (unsigned int)entry->share_access,
952 (unsigned int)entry->private_options));
954 if (server_id_is_disconnected(&entry->pid)) {
956 * note: cleanup should have been done by
957 * delay_for_batch_oplocks()
959 return false;
962 DEBUG(10,("share_conflict: access_mask = 0x%x, share_access = 0x%x\n",
963 (unsigned int)access_mask, (unsigned int)share_access));
965 if ((entry->access_mask & (FILE_WRITE_DATA|
966 FILE_APPEND_DATA|
967 FILE_READ_DATA|
968 FILE_EXECUTE|
969 DELETE_ACCESS)) == 0) {
970 DEBUG(10,("share_conflict: No conflict due to "
971 "entry->access_mask = 0x%x\n",
972 (unsigned int)entry->access_mask ));
973 return False;
976 if ((access_mask & (FILE_WRITE_DATA|
977 FILE_APPEND_DATA|
978 FILE_READ_DATA|
979 FILE_EXECUTE|
980 DELETE_ACCESS)) == 0) {
981 DEBUG(10,("share_conflict: No conflict due to "
982 "access_mask = 0x%x\n",
983 (unsigned int)access_mask ));
984 return False;
987 #if 1 /* JRA TEST - Superdebug. */
988 #define CHECK_MASK(num, am, right, sa, share) \
989 DEBUG(10,("share_conflict: [%d] am (0x%x) & right (0x%x) = 0x%x\n", \
990 (unsigned int)(num), (unsigned int)(am), \
991 (unsigned int)(right), (unsigned int)(am)&(right) )); \
992 DEBUG(10,("share_conflict: [%d] sa (0x%x) & share (0x%x) = 0x%x\n", \
993 (unsigned int)(num), (unsigned int)(sa), \
994 (unsigned int)(share), (unsigned int)(sa)&(share) )); \
995 if (((am) & (right)) && !((sa) & (share))) { \
996 DEBUG(10,("share_conflict: check %d conflict am = 0x%x, right = 0x%x, \
997 sa = 0x%x, share = 0x%x\n", (num), (unsigned int)(am), (unsigned int)(right), (unsigned int)(sa), \
998 (unsigned int)(share) )); \
999 return True; \
1001 #else
1002 #define CHECK_MASK(num, am, right, sa, share) \
1003 if (((am) & (right)) && !((sa) & (share))) { \
1004 DEBUG(10,("share_conflict: check %d conflict am = 0x%x, right = 0x%x, \
1005 sa = 0x%x, share = 0x%x\n", (num), (unsigned int)(am), (unsigned int)(right), (unsigned int)(sa), \
1006 (unsigned int)(share) )); \
1007 return True; \
1009 #endif
1011 CHECK_MASK(1, entry->access_mask, FILE_WRITE_DATA | FILE_APPEND_DATA,
1012 share_access, FILE_SHARE_WRITE);
1013 CHECK_MASK(2, access_mask, FILE_WRITE_DATA | FILE_APPEND_DATA,
1014 entry->share_access, FILE_SHARE_WRITE);
1016 CHECK_MASK(3, entry->access_mask, FILE_READ_DATA | FILE_EXECUTE,
1017 share_access, FILE_SHARE_READ);
1018 CHECK_MASK(4, access_mask, FILE_READ_DATA | FILE_EXECUTE,
1019 entry->share_access, FILE_SHARE_READ);
1021 CHECK_MASK(5, entry->access_mask, DELETE_ACCESS,
1022 share_access, FILE_SHARE_DELETE);
1023 CHECK_MASK(6, access_mask, DELETE_ACCESS,
1024 entry->share_access, FILE_SHARE_DELETE);
1026 DEBUG(10,("share_conflict: No conflict.\n"));
1027 return False;
1030 #if defined(DEVELOPER)
1031 static void validate_my_share_entries(struct smbd_server_connection *sconn,
1032 int num,
1033 struct share_mode_entry *share_entry)
1035 struct server_id self = messaging_server_id(sconn->msg_ctx);
1036 files_struct *fsp;
1038 if (!serverid_equal(&self, &share_entry->pid)) {
1039 return;
1042 if (!is_valid_share_mode_entry(share_entry)) {
1043 return;
1046 fsp = file_find_dif(sconn, share_entry->id,
1047 share_entry->share_file_id);
1048 if (!fsp) {
1049 DEBUG(0,("validate_my_share_entries: PANIC : %s\n",
1050 share_mode_str(talloc_tos(), num, share_entry) ));
1051 smb_panic("validate_my_share_entries: Cannot match a "
1052 "share entry with an open file\n");
1055 if ((share_entry->op_type == NO_OPLOCK) &&
1056 (fsp->oplock_type == FAKE_LEVEL_II_OPLOCK))
1058 /* Someone has already written to it, but I haven't yet
1059 * noticed */
1060 return;
1063 if (((uint16)fsp->oplock_type) != share_entry->op_type) {
1064 goto panic;
1067 return;
1069 panic:
1071 char *str;
1072 DEBUG(0,("validate_my_share_entries: PANIC : %s\n",
1073 share_mode_str(talloc_tos(), num, share_entry) ));
1074 str = talloc_asprintf(talloc_tos(),
1075 "validate_my_share_entries: "
1076 "file %s, oplock_type = 0x%x, op_type = 0x%x\n",
1077 fsp->fsp_name->base_name,
1078 (unsigned int)fsp->oplock_type,
1079 (unsigned int)share_entry->op_type );
1080 smb_panic(str);
1083 #endif
1085 bool is_stat_open(uint32 access_mask)
1087 const uint32_t stat_open_bits =
1088 (SYNCHRONIZE_ACCESS|
1089 FILE_READ_ATTRIBUTES|
1090 FILE_WRITE_ATTRIBUTES);
1092 return (((access_mask & stat_open_bits) != 0) &&
1093 ((access_mask & ~stat_open_bits) == 0));
1096 /****************************************************************************
1097 Deal with share modes
1098 Invarient: Share mode must be locked on entry and exit.
1099 Returns -1 on error, or number of share modes on success (may be zero).
1100 ****************************************************************************/
1102 static NTSTATUS open_mode_check(connection_struct *conn,
1103 struct share_mode_lock *lck,
1104 uint32_t name_hash,
1105 uint32 access_mask,
1106 uint32 share_access,
1107 uint32 create_options,
1108 bool *file_existed)
1110 int i;
1112 if(lck->data->num_share_modes == 0) {
1113 return NT_STATUS_OK;
1116 /* A delete on close prohibits everything */
1118 if (is_delete_on_close_set(lck, name_hash)) {
1120 * Check the delete on close token
1121 * is valid. It could have been left
1122 * after a server crash.
1124 for(i = 0; i < lck->data->num_share_modes; i++) {
1125 if (!share_mode_stale_pid(lck->data, i)) {
1127 *file_existed = true;
1129 return NT_STATUS_DELETE_PENDING;
1132 return NT_STATUS_OK;
1135 if (is_stat_open(access_mask)) {
1136 /* Stat open that doesn't trigger oplock breaks or share mode
1137 * checks... ! JRA. */
1138 return NT_STATUS_OK;
1142 * Check if the share modes will give us access.
1145 #if defined(DEVELOPER)
1146 for(i = 0; i < lck->data->num_share_modes; i++) {
1147 validate_my_share_entries(conn->sconn, i,
1148 &lck->data->share_modes[i]);
1150 #endif
1152 /* Now we check the share modes, after any oplock breaks. */
1153 for(i = 0; i < lck->data->num_share_modes; i++) {
1155 if (!is_valid_share_mode_entry(&lck->data->share_modes[i])) {
1156 continue;
1159 /* someone else has a share lock on it, check to see if we can
1160 * too */
1161 if (share_conflict(&lck->data->share_modes[i],
1162 access_mask, share_access)) {
1164 if (share_mode_stale_pid(lck->data, i)) {
1165 continue;
1168 *file_existed = true;
1170 return NT_STATUS_SHARING_VIOLATION;
1174 if (lck->data->num_share_modes != 0) {
1175 *file_existed = true;
1178 return NT_STATUS_OK;
1182 * Send a break message to the oplock holder and delay the open for
1183 * our client.
1186 static NTSTATUS send_break_message(files_struct *fsp,
1187 struct share_mode_entry *exclusive,
1188 uint64_t mid,
1189 int oplock_request)
1191 NTSTATUS status;
1192 char msg[MSG_SMB_SHARE_MODE_ENTRY_SIZE];
1194 DEBUG(10, ("Sending break request to PID %s\n",
1195 procid_str_static(&exclusive->pid)));
1196 exclusive->op_mid = mid;
1198 /* Create the message. */
1199 share_mode_entry_to_message(msg, exclusive);
1201 /* Add in the FORCE_OPLOCK_BREAK_TO_NONE bit in the message if set. We
1202 don't want this set in the share mode struct pointed to by lck. */
1204 if (oplock_request & FORCE_OPLOCK_BREAK_TO_NONE) {
1205 SSVAL(msg,OP_BREAK_MSG_OP_TYPE_OFFSET,
1206 exclusive->op_type | FORCE_OPLOCK_BREAK_TO_NONE);
1209 status = messaging_send_buf(fsp->conn->sconn->msg_ctx, exclusive->pid,
1210 MSG_SMB_BREAK_REQUEST,
1211 (uint8 *)msg,
1212 MSG_SMB_SHARE_MODE_ENTRY_SIZE);
1213 if (!NT_STATUS_IS_OK(status)) {
1214 DEBUG(3, ("Could not send oplock break message: %s\n",
1215 nt_errstr(status)));
1218 return status;
1222 * Return share_mode_entry pointers for :
1223 * 1). Batch oplock entry.
1224 * 2). Batch or exclusive oplock entry (may be identical to #1).
1225 * bool have_level2_oplock
1226 * bool have_no_oplock.
1227 * Do internal consistency checks on the share mode for a file.
1230 static void find_oplock_types(files_struct *fsp,
1231 int oplock_request,
1232 const struct share_mode_lock *lck,
1233 struct share_mode_entry **pp_batch,
1234 struct share_mode_entry **pp_ex_or_batch,
1235 bool *got_level2,
1236 bool *got_no_oplock)
1238 int i;
1240 *pp_batch = NULL;
1241 *pp_ex_or_batch = NULL;
1242 *got_level2 = false;
1243 *got_no_oplock = false;
1245 /* Ignore stat or internal opens, as is done in
1246 delay_for_batch_oplocks() and
1247 delay_for_exclusive_oplocks().
1249 if ((oplock_request & INTERNAL_OPEN_ONLY) || is_stat_open(fsp->access_mask)) {
1250 return;
1253 for (i=0; i<lck->data->num_share_modes; i++) {
1254 struct share_mode_entry *e = &lck->data->share_modes[i];
1256 if (!is_valid_share_mode_entry(e)) {
1257 continue;
1260 if (e->op_type == NO_OPLOCK && is_stat_open(e->access_mask)) {
1261 /* We ignore stat opens in the table - they
1262 always have NO_OPLOCK and never get or
1263 cause breaks. JRA. */
1264 continue;
1267 if (BATCH_OPLOCK_TYPE(e->op_type)) {
1268 /* batch - can only be one. */
1269 if (share_mode_stale_pid(lck->data, i)) {
1270 DEBUG(10, ("Found stale batch oplock\n"));
1271 continue;
1273 if (*pp_ex_or_batch || *pp_batch || *got_level2 || *got_no_oplock) {
1274 smb_panic("Bad batch oplock entry.");
1276 *pp_batch = e;
1279 if (EXCLUSIVE_OPLOCK_TYPE(e->op_type)) {
1280 if (share_mode_stale_pid(lck->data, i)) {
1281 DEBUG(10, ("Found stale duplicate oplock\n"));
1282 continue;
1284 /* Exclusive or batch - can only be one. */
1285 if (*pp_ex_or_batch || *got_level2 || *got_no_oplock) {
1286 smb_panic("Bad exclusive or batch oplock entry.");
1288 *pp_ex_or_batch = e;
1291 if (LEVEL_II_OPLOCK_TYPE(e->op_type)) {
1292 if (*pp_batch || *pp_ex_or_batch) {
1293 if (share_mode_stale_pid(lck->data, i)) {
1294 DEBUG(10, ("Found stale LevelII "
1295 "oplock\n"));
1296 continue;
1298 smb_panic("Bad levelII oplock entry.");
1300 *got_level2 = true;
1303 if (e->op_type == NO_OPLOCK) {
1304 if (*pp_batch || *pp_ex_or_batch) {
1305 if (share_mode_stale_pid(lck->data, i)) {
1306 DEBUG(10, ("Found stale NO_OPLOCK "
1307 "entry\n"));
1308 continue;
1310 smb_panic("Bad no oplock entry.");
1312 *got_no_oplock = true;
1317 static bool delay_for_batch_oplocks(files_struct *fsp,
1318 uint64_t mid,
1319 int oplock_request,
1320 struct share_mode_entry *batch_entry)
1322 if ((oplock_request & INTERNAL_OPEN_ONLY) || is_stat_open(fsp->access_mask)) {
1323 return false;
1325 if (batch_entry == NULL) {
1326 return false;
1329 if (server_id_is_disconnected(&batch_entry->pid)) {
1331 * TODO: clean up.
1332 * This could be achieved by sending a break message
1333 * to ourselves. Special considerations for files
1334 * with delete_on_close flag set!
1336 * For now we keep it simple and do not
1337 * allow delete on close for durable handles.
1339 return false;
1342 /* Found a batch oplock */
1343 send_break_message(fsp, batch_entry, mid, oplock_request);
1344 return true;
1347 static bool delay_for_exclusive_oplocks(files_struct *fsp,
1348 uint64_t mid,
1349 int oplock_request,
1350 struct share_mode_entry *ex_entry)
1352 if ((oplock_request & INTERNAL_OPEN_ONLY) || is_stat_open(fsp->access_mask)) {
1353 return false;
1355 if (ex_entry == NULL) {
1356 return false;
1359 if (server_id_is_disconnected(&ex_entry->pid)) {
1361 * since only durable handles can get disconnected,
1362 * and we can only get durable handles with batch oplocks,
1363 * this should actually never be reached...
1365 return false;
1368 send_break_message(fsp, ex_entry, mid, oplock_request);
1369 return true;
1372 static bool file_has_brlocks(files_struct *fsp)
1374 struct byte_range_lock *br_lck;
1376 br_lck = brl_get_locks_readonly(fsp);
1377 if (!br_lck)
1378 return false;
1380 return br_lck->num_locks > 0 ? true : false;
1383 static void grant_fsp_oplock_type(files_struct *fsp,
1384 int oplock_request,
1385 bool got_level2_oplock,
1386 bool got_a_none_oplock)
1388 bool allow_level2 = (global_client_caps & CAP_LEVEL_II_OPLOCKS) &&
1389 lp_level2_oplocks(SNUM(fsp->conn));
1391 /* Start by granting what the client asked for,
1392 but ensure no SAMBA_PRIVATE bits can be set. */
1393 fsp->oplock_type = (oplock_request & ~SAMBA_PRIVATE_OPLOCK_MASK);
1395 if (oplock_request & INTERNAL_OPEN_ONLY) {
1396 /* No oplocks on internal open. */
1397 fsp->oplock_type = NO_OPLOCK;
1398 DEBUG(10,("grant_fsp_oplock_type: oplock type 0x%x on file %s\n",
1399 fsp->oplock_type, fsp_str_dbg(fsp)));
1400 return;
1403 if (lp_locking(fsp->conn->params) && file_has_brlocks(fsp)) {
1404 DEBUG(10,("grant_fsp_oplock_type: file %s has byte range locks\n",
1405 fsp_str_dbg(fsp)));
1406 fsp->oplock_type = NO_OPLOCK;
1409 if (is_stat_open(fsp->access_mask)) {
1410 /* Leave the value already set. */
1411 DEBUG(10,("grant_fsp_oplock_type: oplock type 0x%x on file %s\n",
1412 fsp->oplock_type, fsp_str_dbg(fsp)));
1413 return;
1417 * Match what was requested (fsp->oplock_type) with
1418 * what was found in the existing share modes.
1421 if (got_a_none_oplock) {
1422 fsp->oplock_type = NO_OPLOCK;
1423 } else if (got_level2_oplock) {
1424 if (fsp->oplock_type == NO_OPLOCK ||
1425 fsp->oplock_type == FAKE_LEVEL_II_OPLOCK) {
1426 /* Store a level2 oplock, but don't tell the client */
1427 fsp->oplock_type = FAKE_LEVEL_II_OPLOCK;
1428 } else {
1429 fsp->oplock_type = LEVEL_II_OPLOCK;
1431 } else {
1432 /* All share_mode_entries are placeholders or deferred.
1433 * Silently upgrade to fake levelII if the client didn't
1434 * ask for an oplock. */
1435 if (fsp->oplock_type == NO_OPLOCK) {
1436 /* Store a level2 oplock, but don't tell the client */
1437 fsp->oplock_type = FAKE_LEVEL_II_OPLOCK;
1442 * Don't grant level2 to clients that don't want them
1443 * or if we've turned them off.
1445 if (fsp->oplock_type == LEVEL_II_OPLOCK && !allow_level2) {
1446 fsp->oplock_type = FAKE_LEVEL_II_OPLOCK;
1449 DEBUG(10,("grant_fsp_oplock_type: oplock type 0x%x on file %s\n",
1450 fsp->oplock_type, fsp_str_dbg(fsp)));
1453 static bool request_timed_out(struct timeval request_time,
1454 struct timeval timeout)
1456 struct timeval now, end_time;
1457 GetTimeOfDay(&now);
1458 end_time = timeval_sum(&request_time, &timeout);
1459 return (timeval_compare(&end_time, &now) < 0);
1462 struct defer_open_state {
1463 struct smbd_server_connection *sconn;
1464 uint64_t mid;
1467 static void defer_open_done(struct tevent_req *req);
1469 /****************************************************************************
1470 Handle the 1 second delay in returning a SHARING_VIOLATION error.
1471 ****************************************************************************/
1473 static void defer_open(struct share_mode_lock *lck,
1474 struct timeval request_time,
1475 struct timeval timeout,
1476 struct smb_request *req,
1477 struct deferred_open_record *state)
1479 DEBUG(10,("defer_open_sharing_error: time [%u.%06u] adding deferred "
1480 "open entry for mid %llu\n",
1481 (unsigned int)request_time.tv_sec,
1482 (unsigned int)request_time.tv_usec,
1483 (unsigned long long)req->mid));
1485 if (!push_deferred_open_message_smb(req, request_time, timeout,
1486 state->id, (char *)state, sizeof(*state))) {
1487 TALLOC_FREE(lck);
1488 exit_server("push_deferred_open_message_smb failed");
1490 if (lck) {
1491 struct defer_open_state *watch_state;
1492 struct tevent_req *watch_req;
1493 bool ret;
1495 watch_state = talloc(req->sconn, struct defer_open_state);
1496 if (watch_state == NULL) {
1497 exit_server("talloc failed");
1499 watch_state->sconn = req->sconn;
1500 watch_state->mid = req->mid;
1502 DEBUG(10, ("defering mid %llu\n",
1503 (unsigned long long)req->mid));
1505 watch_req = dbwrap_record_watch_send(
1506 watch_state, req->sconn->ev_ctx, lck->data->record,
1507 req->sconn->msg_ctx);
1508 if (watch_req == NULL) {
1509 exit_server("Could not watch share mode record");
1511 tevent_req_set_callback(watch_req, defer_open_done,
1512 watch_state);
1514 ret = tevent_req_set_endtime(
1515 watch_req, req->sconn->ev_ctx,
1516 timeval_sum(&request_time, &timeout));
1517 SMB_ASSERT(ret);
1521 static void defer_open_done(struct tevent_req *req)
1523 struct defer_open_state *state = tevent_req_callback_data(
1524 req, struct defer_open_state);
1525 NTSTATUS status;
1526 bool ret;
1528 status = dbwrap_record_watch_recv(req, talloc_tos(), NULL);
1529 TALLOC_FREE(req);
1530 if (!NT_STATUS_IS_OK(status)) {
1531 DEBUG(5, ("dbwrap_record_watch_recv returned %s\n",
1532 nt_errstr(status)));
1534 * Even if it failed, retry anyway. TODO: We need a way to
1535 * tell a re-scheduled open about that error.
1539 DEBUG(10, ("scheduling mid %llu\n", (unsigned long long)state->mid));
1541 ret = schedule_deferred_open_message_smb(state->sconn, state->mid);
1542 SMB_ASSERT(ret);
1543 TALLOC_FREE(state);
1547 /****************************************************************************
1548 On overwrite open ensure that the attributes match.
1549 ****************************************************************************/
1551 static bool open_match_attributes(connection_struct *conn,
1552 uint32 old_dos_attr,
1553 uint32 new_dos_attr,
1554 mode_t existing_unx_mode,
1555 mode_t new_unx_mode,
1556 mode_t *returned_unx_mode)
1558 uint32 noarch_old_dos_attr, noarch_new_dos_attr;
1560 noarch_old_dos_attr = (old_dos_attr & ~FILE_ATTRIBUTE_ARCHIVE);
1561 noarch_new_dos_attr = (new_dos_attr & ~FILE_ATTRIBUTE_ARCHIVE);
1563 if((noarch_old_dos_attr == 0 && noarch_new_dos_attr != 0) ||
1564 (noarch_old_dos_attr != 0 && ((noarch_old_dos_attr & noarch_new_dos_attr) == noarch_old_dos_attr))) {
1565 *returned_unx_mode = new_unx_mode;
1566 } else {
1567 *returned_unx_mode = (mode_t)0;
1570 DEBUG(10,("open_match_attributes: old_dos_attr = 0x%x, "
1571 "existing_unx_mode = 0%o, new_dos_attr = 0x%x "
1572 "returned_unx_mode = 0%o\n",
1573 (unsigned int)old_dos_attr,
1574 (unsigned int)existing_unx_mode,
1575 (unsigned int)new_dos_attr,
1576 (unsigned int)*returned_unx_mode ));
1578 /* If we're mapping SYSTEM and HIDDEN ensure they match. */
1579 if (lp_map_system(SNUM(conn)) || lp_store_dos_attributes(SNUM(conn))) {
1580 if ((old_dos_attr & FILE_ATTRIBUTE_SYSTEM) &&
1581 !(new_dos_attr & FILE_ATTRIBUTE_SYSTEM)) {
1582 return False;
1585 if (lp_map_hidden(SNUM(conn)) || lp_store_dos_attributes(SNUM(conn))) {
1586 if ((old_dos_attr & FILE_ATTRIBUTE_HIDDEN) &&
1587 !(new_dos_attr & FILE_ATTRIBUTE_HIDDEN)) {
1588 return False;
1591 return True;
1594 /****************************************************************************
1595 Special FCB or DOS processing in the case of a sharing violation.
1596 Try and find a duplicated file handle.
1597 ****************************************************************************/
1599 static NTSTATUS fcb_or_dos_open(struct smb_request *req,
1600 connection_struct *conn,
1601 files_struct *fsp_to_dup_into,
1602 const struct smb_filename *smb_fname,
1603 struct file_id id,
1604 uint16 file_pid,
1605 uint64_t vuid,
1606 uint32 access_mask,
1607 uint32 share_access,
1608 uint32 create_options)
1610 files_struct *fsp;
1612 DEBUG(5,("fcb_or_dos_open: attempting old open semantics for "
1613 "file %s.\n", smb_fname_str_dbg(smb_fname)));
1615 for(fsp = file_find_di_first(conn->sconn, id); fsp;
1616 fsp = file_find_di_next(fsp)) {
1618 DEBUG(10,("fcb_or_dos_open: checking file %s, fd = %d, "
1619 "vuid = %llu, file_pid = %u, private_options = 0x%x "
1620 "access_mask = 0x%x\n", fsp_str_dbg(fsp),
1621 fsp->fh->fd, (unsigned long long)fsp->vuid,
1622 (unsigned int)fsp->file_pid,
1623 (unsigned int)fsp->fh->private_options,
1624 (unsigned int)fsp->access_mask ));
1626 if (fsp != fsp_to_dup_into &&
1627 fsp->fh->fd != -1 &&
1628 fsp->vuid == vuid &&
1629 fsp->file_pid == file_pid &&
1630 (fsp->fh->private_options & (NTCREATEX_OPTIONS_PRIVATE_DENY_DOS |
1631 NTCREATEX_OPTIONS_PRIVATE_DENY_FCB)) &&
1632 (fsp->access_mask & FILE_WRITE_DATA) &&
1633 strequal(fsp->fsp_name->base_name, smb_fname->base_name) &&
1634 strequal(fsp->fsp_name->stream_name,
1635 smb_fname->stream_name)) {
1636 DEBUG(10,("fcb_or_dos_open: file match\n"));
1637 break;
1641 if (!fsp) {
1642 return NT_STATUS_NOT_FOUND;
1645 /* quite an insane set of semantics ... */
1646 if (is_executable(smb_fname->base_name) &&
1647 (fsp->fh->private_options & NTCREATEX_OPTIONS_PRIVATE_DENY_DOS)) {
1648 DEBUG(10,("fcb_or_dos_open: file fail due to is_executable.\n"));
1649 return NT_STATUS_INVALID_PARAMETER;
1652 /* We need to duplicate this fsp. */
1653 return dup_file_fsp(req, fsp, access_mask, share_access,
1654 create_options, fsp_to_dup_into);
1657 static void schedule_defer_open(struct share_mode_lock *lck,
1658 struct timeval request_time,
1659 struct smb_request *req)
1661 struct deferred_open_record state;
1663 /* This is a relative time, added to the absolute
1664 request_time value to get the absolute timeout time.
1665 Note that if this is the second or greater time we enter
1666 this codepath for this particular request mid then
1667 request_time is left as the absolute time of the *first*
1668 time this request mid was processed. This is what allows
1669 the request to eventually time out. */
1671 struct timeval timeout;
1673 /* Normally the smbd we asked should respond within
1674 * OPLOCK_BREAK_TIMEOUT seconds regardless of whether
1675 * the client did, give twice the timeout as a safety
1676 * measure here in case the other smbd is stuck
1677 * somewhere else. */
1679 timeout = timeval_set(OPLOCK_BREAK_TIMEOUT*2, 0);
1681 /* Nothing actually uses state.delayed_for_oplocks
1682 but it's handy to differentiate in debug messages
1683 between a 30 second delay due to oplock break, and
1684 a 1 second delay for share mode conflicts. */
1686 state.delayed_for_oplocks = True;
1687 state.async_open = false;
1688 state.id = lck->data->id;
1690 if (!request_timed_out(request_time, timeout)) {
1691 defer_open(lck, request_time, timeout, req, &state);
1695 /****************************************************************************
1696 Reschedule an open call that went asynchronous.
1697 ****************************************************************************/
1699 static void schedule_async_open(struct timeval request_time,
1700 struct smb_request *req)
1702 struct deferred_open_record state;
1703 struct timeval timeout;
1705 timeout = timeval_set(20, 0);
1707 ZERO_STRUCT(state);
1708 state.delayed_for_oplocks = false;
1709 state.async_open = true;
1711 if (!request_timed_out(request_time, timeout)) {
1712 defer_open(NULL, request_time, timeout, req, &state);
1716 /****************************************************************************
1717 Work out what access_mask to use from what the client sent us.
1718 ****************************************************************************/
1720 static NTSTATUS smbd_calculate_maximum_allowed_access(
1721 connection_struct *conn,
1722 const struct smb_filename *smb_fname,
1723 bool use_privs,
1724 uint32_t *p_access_mask)
1726 struct security_descriptor *sd;
1727 uint32_t access_granted;
1728 NTSTATUS status;
1730 if (!use_privs && (get_current_uid(conn) == (uid_t)0)) {
1731 *p_access_mask |= FILE_GENERIC_ALL;
1732 return NT_STATUS_OK;
1735 status = SMB_VFS_GET_NT_ACL(conn, smb_fname->base_name,
1736 (SECINFO_OWNER |
1737 SECINFO_GROUP |
1738 SECINFO_DACL),
1739 talloc_tos(), &sd);
1741 if (NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
1743 * File did not exist
1745 *p_access_mask = FILE_GENERIC_ALL;
1746 return NT_STATUS_OK;
1748 if (!NT_STATUS_IS_OK(status)) {
1749 DEBUG(10,("Could not get acl on file %s: %s\n",
1750 smb_fname_str_dbg(smb_fname),
1751 nt_errstr(status)));
1752 return NT_STATUS_ACCESS_DENIED;
1756 * If we can access the path to this file, by
1757 * default we have FILE_READ_ATTRIBUTES from the
1758 * containing directory. See the section:
1759 * "Algorithm to Check Access to an Existing File"
1760 * in MS-FSA.pdf.
1762 * se_file_access_check()
1763 * also takes care of owner WRITE_DAC and READ_CONTROL.
1765 status = se_file_access_check(sd,
1766 get_current_nttok(conn),
1767 use_privs,
1768 (*p_access_mask & ~FILE_READ_ATTRIBUTES),
1769 &access_granted);
1771 TALLOC_FREE(sd);
1773 if (!NT_STATUS_IS_OK(status)) {
1774 DEBUG(10, ("Access denied on file %s: "
1775 "when calculating maximum access\n",
1776 smb_fname_str_dbg(smb_fname)));
1777 return NT_STATUS_ACCESS_DENIED;
1779 *p_access_mask = (access_granted | FILE_READ_ATTRIBUTES);
1781 if (!(access_granted & DELETE_ACCESS)) {
1782 if (can_delete_file_in_directory(conn, smb_fname)) {
1783 *p_access_mask |= DELETE_ACCESS;
1787 return NT_STATUS_OK;
1790 NTSTATUS smbd_calculate_access_mask(connection_struct *conn,
1791 const struct smb_filename *smb_fname,
1792 bool use_privs,
1793 uint32_t access_mask,
1794 uint32_t *access_mask_out)
1796 NTSTATUS status;
1797 uint32_t orig_access_mask = access_mask;
1798 uint32_t rejected_share_access;
1801 * Convert GENERIC bits to specific bits.
1804 se_map_generic(&access_mask, &file_generic_mapping);
1806 /* Calculate MAXIMUM_ALLOWED_ACCESS if requested. */
1807 if (access_mask & MAXIMUM_ALLOWED_ACCESS) {
1809 status = smbd_calculate_maximum_allowed_access(
1810 conn, smb_fname, use_privs, &access_mask);
1812 if (!NT_STATUS_IS_OK(status)) {
1813 return status;
1816 access_mask &= conn->share_access;
1819 rejected_share_access = access_mask & ~(conn->share_access);
1821 if (rejected_share_access) {
1822 DEBUG(10, ("smbd_calculate_access_mask: Access denied on "
1823 "file %s: rejected by share access mask[0x%08X] "
1824 "orig[0x%08X] mapped[0x%08X] reject[0x%08X]\n",
1825 smb_fname_str_dbg(smb_fname),
1826 conn->share_access,
1827 orig_access_mask, access_mask,
1828 rejected_share_access));
1829 return NT_STATUS_ACCESS_DENIED;
1832 *access_mask_out = access_mask;
1833 return NT_STATUS_OK;
1836 /****************************************************************************
1837 Remove the deferred open entry under lock.
1838 ****************************************************************************/
1840 /****************************************************************************
1841 Return true if this is a state pointer to an asynchronous create.
1842 ****************************************************************************/
1844 bool is_deferred_open_async(const void *ptr)
1846 const struct deferred_open_record *state = (const struct deferred_open_record *)ptr;
1848 return state->async_open;
1851 static bool clear_ads(uint32_t create_disposition)
1853 bool ret = false;
1855 switch (create_disposition) {
1856 case FILE_SUPERSEDE:
1857 case FILE_OVERWRITE_IF:
1858 case FILE_OVERWRITE:
1859 ret = true;
1860 break;
1861 default:
1862 break;
1864 return ret;
1867 static int disposition_to_open_flags(uint32_t create_disposition)
1869 int ret = 0;
1872 * Currently we're using FILE_SUPERSEDE as the same as
1873 * FILE_OVERWRITE_IF but they really are
1874 * different. FILE_SUPERSEDE deletes an existing file
1875 * (requiring delete access) then recreates it.
1878 switch (create_disposition) {
1879 case FILE_SUPERSEDE:
1880 case FILE_OVERWRITE_IF:
1882 * If file exists replace/overwrite. If file doesn't
1883 * exist create.
1885 ret = O_CREAT|O_TRUNC;
1886 break;
1888 case FILE_OPEN:
1890 * If file exists open. If file doesn't exist error.
1892 ret = 0;
1893 break;
1895 case FILE_OVERWRITE:
1897 * If file exists overwrite. If file doesn't exist
1898 * error.
1900 ret = O_TRUNC;
1901 break;
1903 case FILE_CREATE:
1905 * If file exists error. If file doesn't exist create.
1907 ret = O_CREAT|O_EXCL;
1908 break;
1910 case FILE_OPEN_IF:
1912 * If file exists open. If file doesn't exist create.
1914 ret = O_CREAT;
1915 break;
1917 return ret;
1920 static int calculate_open_access_flags(uint32_t access_mask,
1921 int oplock_request,
1922 uint32_t private_flags)
1924 bool need_write, need_read;
1927 * Note that we ignore the append flag as append does not
1928 * mean the same thing under DOS and Unix.
1931 need_write =
1932 ((access_mask & (FILE_WRITE_DATA | FILE_APPEND_DATA)) ||
1933 (oplock_request & FORCE_OPLOCK_BREAK_TO_NONE));
1935 if (!need_write) {
1936 return O_RDONLY;
1939 /* DENY_DOS opens are always underlying read-write on the
1940 file handle, no matter what the requested access mask
1941 says. */
1943 need_read =
1944 ((private_flags & NTCREATEX_OPTIONS_PRIVATE_DENY_DOS) ||
1945 access_mask & (FILE_READ_ATTRIBUTES|FILE_READ_DATA|
1946 FILE_READ_EA|FILE_EXECUTE));
1948 if (!need_read) {
1949 return O_WRONLY;
1951 return O_RDWR;
1954 /****************************************************************************
1955 Open a file with a share mode. Passed in an already created files_struct *.
1956 ****************************************************************************/
1958 static NTSTATUS open_file_ntcreate(connection_struct *conn,
1959 struct smb_request *req,
1960 uint32 access_mask, /* access bits (FILE_READ_DATA etc.) */
1961 uint32 share_access, /* share constants (FILE_SHARE_READ etc) */
1962 uint32 create_disposition, /* FILE_OPEN_IF etc. */
1963 uint32 create_options, /* options such as delete on close. */
1964 uint32 new_dos_attributes, /* attributes used for new file. */
1965 int oplock_request, /* internal Samba oplock codes. */
1966 /* Information (FILE_EXISTS etc.) */
1967 uint32_t private_flags, /* Samba specific flags. */
1968 int *pinfo,
1969 files_struct *fsp)
1971 struct smb_filename *smb_fname = fsp->fsp_name;
1972 int flags=0;
1973 int flags2=0;
1974 bool file_existed = VALID_STAT(smb_fname->st);
1975 bool def_acl = False;
1976 bool posix_open = False;
1977 bool new_file_created = False;
1978 bool first_open_attempt = true;
1979 NTSTATUS fsp_open = NT_STATUS_ACCESS_DENIED;
1980 mode_t new_unx_mode = (mode_t)0;
1981 mode_t unx_mode = (mode_t)0;
1982 int info;
1983 uint32 existing_dos_attributes = 0;
1984 struct timeval request_time = timeval_zero();
1985 struct share_mode_lock *lck = NULL;
1986 uint32 open_access_mask = access_mask;
1987 NTSTATUS status;
1988 char *parent_dir;
1989 SMB_STRUCT_STAT saved_stat = smb_fname->st;
1990 struct share_mode_entry *batch_entry = NULL;
1991 struct share_mode_entry *exclusive_entry = NULL;
1992 bool got_level2_oplock = false;
1993 bool got_a_none_oplock = false;
1994 struct timespec old_write_time;
1995 struct file_id id;
1997 if (conn->printer) {
1999 * Printers are handled completely differently.
2000 * Most of the passed parameters are ignored.
2003 if (pinfo) {
2004 *pinfo = FILE_WAS_CREATED;
2007 DEBUG(10, ("open_file_ntcreate: printer open fname=%s\n",
2008 smb_fname_str_dbg(smb_fname)));
2010 if (!req) {
2011 DEBUG(0,("open_file_ntcreate: printer open without "
2012 "an SMB request!\n"));
2013 return NT_STATUS_INTERNAL_ERROR;
2016 return print_spool_open(fsp, smb_fname->base_name,
2017 req->vuid);
2020 if (!parent_dirname(talloc_tos(), smb_fname->base_name, &parent_dir,
2021 NULL)) {
2022 return NT_STATUS_NO_MEMORY;
2025 if (new_dos_attributes & FILE_FLAG_POSIX_SEMANTICS) {
2026 posix_open = True;
2027 unx_mode = (mode_t)(new_dos_attributes & ~FILE_FLAG_POSIX_SEMANTICS);
2028 new_dos_attributes = 0;
2029 } else {
2030 /* Windows allows a new file to be created and
2031 silently removes a FILE_ATTRIBUTE_DIRECTORY
2032 sent by the client. Do the same. */
2034 new_dos_attributes &= ~FILE_ATTRIBUTE_DIRECTORY;
2036 /* We add FILE_ATTRIBUTE_ARCHIVE to this as this mode is only used if the file is
2037 * created new. */
2038 unx_mode = unix_mode(conn, new_dos_attributes | FILE_ATTRIBUTE_ARCHIVE,
2039 smb_fname, parent_dir);
2042 DEBUG(10, ("open_file_ntcreate: fname=%s, dos_attrs=0x%x "
2043 "access_mask=0x%x share_access=0x%x "
2044 "create_disposition = 0x%x create_options=0x%x "
2045 "unix mode=0%o oplock_request=%d private_flags = 0x%x\n",
2046 smb_fname_str_dbg(smb_fname), new_dos_attributes,
2047 access_mask, share_access, create_disposition,
2048 create_options, (unsigned int)unx_mode, oplock_request,
2049 (unsigned int)private_flags));
2051 if ((req == NULL) && ((oplock_request & INTERNAL_OPEN_ONLY) == 0)) {
2052 DEBUG(0, ("No smb request but not an internal only open!\n"));
2053 return NT_STATUS_INTERNAL_ERROR;
2057 * Only non-internal opens can be deferred at all
2060 if (req) {
2061 void *ptr;
2062 if (get_deferred_open_message_state(req,
2063 &request_time,
2064 &ptr)) {
2065 /* Remember the absolute time of the original
2066 request with this mid. We'll use it later to
2067 see if this has timed out. */
2069 /* If it was an async create retry, the file
2070 didn't exist. */
2072 if (is_deferred_open_async(ptr)) {
2073 SET_STAT_INVALID(smb_fname->st);
2074 file_existed = false;
2077 /* Ensure we don't reprocess this message. */
2078 remove_deferred_open_message_smb(req->sconn, req->mid);
2080 first_open_attempt = false;
2084 if (!posix_open) {
2085 new_dos_attributes &= SAMBA_ATTRIBUTES_MASK;
2086 if (file_existed) {
2087 existing_dos_attributes = dos_mode(conn, smb_fname);
2091 /* ignore any oplock requests if oplocks are disabled */
2092 if (!lp_oplocks(SNUM(conn)) ||
2093 IS_VETO_OPLOCK_PATH(conn, smb_fname->base_name)) {
2094 /* Mask off everything except the private Samba bits. */
2095 oplock_request &= SAMBA_PRIVATE_OPLOCK_MASK;
2098 /* this is for OS/2 long file names - say we don't support them */
2099 if (!lp_posix_pathnames() && strstr(smb_fname->base_name,".+,;=[].")) {
2100 /* OS/2 Workplace shell fix may be main code stream in a later
2101 * release. */
2102 DEBUG(5,("open_file_ntcreate: OS/2 long filenames are not "
2103 "supported.\n"));
2104 if (use_nt_status()) {
2105 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
2107 return NT_STATUS_DOS(ERRDOS, ERRcannotopen);
2110 switch( create_disposition ) {
2111 case FILE_OPEN:
2112 /* If file exists open. If file doesn't exist error. */
2113 if (!file_existed) {
2114 DEBUG(5,("open_file_ntcreate: FILE_OPEN "
2115 "requested for file %s and file "
2116 "doesn't exist.\n",
2117 smb_fname_str_dbg(smb_fname)));
2118 errno = ENOENT;
2119 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
2121 break;
2123 case FILE_OVERWRITE:
2124 /* If file exists overwrite. If file doesn't exist
2125 * error. */
2126 if (!file_existed) {
2127 DEBUG(5,("open_file_ntcreate: FILE_OVERWRITE "
2128 "requested for file %s and file "
2129 "doesn't exist.\n",
2130 smb_fname_str_dbg(smb_fname) ));
2131 errno = ENOENT;
2132 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
2134 break;
2136 case FILE_CREATE:
2137 /* If file exists error. If file doesn't exist
2138 * create. */
2139 if (file_existed) {
2140 DEBUG(5,("open_file_ntcreate: FILE_CREATE "
2141 "requested for file %s and file "
2142 "already exists.\n",
2143 smb_fname_str_dbg(smb_fname)));
2144 if (S_ISDIR(smb_fname->st.st_ex_mode)) {
2145 errno = EISDIR;
2146 } else {
2147 errno = EEXIST;
2149 return map_nt_error_from_unix(errno);
2151 break;
2153 case FILE_SUPERSEDE:
2154 case FILE_OVERWRITE_IF:
2155 case FILE_OPEN_IF:
2156 break;
2157 default:
2158 return NT_STATUS_INVALID_PARAMETER;
2161 flags2 = disposition_to_open_flags(create_disposition);
2163 /* We only care about matching attributes on file exists and
2164 * overwrite. */
2166 if (!posix_open && file_existed &&
2167 ((create_disposition == FILE_OVERWRITE) ||
2168 (create_disposition == FILE_OVERWRITE_IF))) {
2169 if (!open_match_attributes(conn, existing_dos_attributes,
2170 new_dos_attributes,
2171 smb_fname->st.st_ex_mode,
2172 unx_mode, &new_unx_mode)) {
2173 DEBUG(5,("open_file_ntcreate: attributes missmatch "
2174 "for file %s (%x %x) (0%o, 0%o)\n",
2175 smb_fname_str_dbg(smb_fname),
2176 existing_dos_attributes,
2177 new_dos_attributes,
2178 (unsigned int)smb_fname->st.st_ex_mode,
2179 (unsigned int)unx_mode ));
2180 errno = EACCES;
2181 return NT_STATUS_ACCESS_DENIED;
2185 status = smbd_calculate_access_mask(conn, smb_fname,
2186 false,
2187 access_mask,
2188 &access_mask);
2189 if (!NT_STATUS_IS_OK(status)) {
2190 DEBUG(10, ("open_file_ntcreate: smbd_calculate_access_mask "
2191 "on file %s returned %s\n",
2192 smb_fname_str_dbg(smb_fname), nt_errstr(status)));
2193 return status;
2196 open_access_mask = access_mask;
2198 if ((flags2 & O_TRUNC) || (oplock_request & FORCE_OPLOCK_BREAK_TO_NONE)) {
2199 open_access_mask |= FILE_WRITE_DATA; /* This will cause oplock breaks. */
2202 DEBUG(10, ("open_file_ntcreate: fname=%s, after mapping "
2203 "access_mask=0x%x\n", smb_fname_str_dbg(smb_fname),
2204 access_mask));
2207 * Note that we ignore the append flag as append does not
2208 * mean the same thing under DOS and Unix.
2211 flags = calculate_open_access_flags(access_mask, oplock_request,
2212 private_flags);
2215 * Currently we only look at FILE_WRITE_THROUGH for create options.
2218 #if defined(O_SYNC)
2219 if ((create_options & FILE_WRITE_THROUGH) && lp_strict_sync(SNUM(conn))) {
2220 flags2 |= O_SYNC;
2222 #endif /* O_SYNC */
2224 if (posix_open && (access_mask & FILE_APPEND_DATA)) {
2225 flags2 |= O_APPEND;
2228 if (!posix_open && !CAN_WRITE(conn)) {
2230 * We should really return a permission denied error if either
2231 * O_CREAT or O_TRUNC are set, but for compatibility with
2232 * older versions of Samba we just AND them out.
2234 flags2 &= ~(O_CREAT|O_TRUNC);
2237 if (first_open_attempt && lp_kernel_oplocks(SNUM(conn))) {
2239 * With kernel oplocks the open breaking an oplock
2240 * blocks until the oplock holder has given up the
2241 * oplock or closed the file. We prevent this by first
2242 * trying to open the file with O_NONBLOCK (see "man
2243 * fcntl" on Linux). For the second try, triggered by
2244 * an oplock break response, we do not need this
2245 * anymore.
2247 * This is true under the assumption that only Samba
2248 * requests kernel oplocks. Once someone else like
2249 * NFSv4 starts to use that API, we will have to
2250 * modify this by communicating with the NFSv4 server.
2252 flags2 |= O_NONBLOCK;
2256 * Ensure we can't write on a read-only share or file.
2259 if (flags != O_RDONLY && file_existed &&
2260 (!CAN_WRITE(conn) || IS_DOS_READONLY(existing_dos_attributes))) {
2261 DEBUG(5,("open_file_ntcreate: write access requested for "
2262 "file %s on read only %s\n",
2263 smb_fname_str_dbg(smb_fname),
2264 !CAN_WRITE(conn) ? "share" : "file" ));
2265 errno = EACCES;
2266 return NT_STATUS_ACCESS_DENIED;
2269 fsp->file_id = vfs_file_id_from_sbuf(conn, &smb_fname->st);
2270 fsp->share_access = share_access;
2271 fsp->fh->private_options = private_flags;
2272 fsp->access_mask = open_access_mask; /* We change this to the
2273 * requested access_mask after
2274 * the open is done. */
2275 fsp->posix_open = posix_open;
2277 /* Ensure no SAMBA_PRIVATE bits can be set. */
2278 fsp->oplock_type = (oplock_request & ~SAMBA_PRIVATE_OPLOCK_MASK);
2280 if (timeval_is_zero(&request_time)) {
2281 request_time = fsp->open_time;
2285 * Ensure we pay attention to default ACLs on directories if required.
2288 if ((flags2 & O_CREAT) && lp_inherit_acls(SNUM(conn)) &&
2289 (def_acl = directory_has_default_acl(conn, parent_dir))) {
2290 unx_mode = (0777 & lp_create_mask(SNUM(conn)));
2293 DEBUG(4,("calling open_file with flags=0x%X flags2=0x%X mode=0%o, "
2294 "access_mask = 0x%x, open_access_mask = 0x%x\n",
2295 (unsigned int)flags, (unsigned int)flags2,
2296 (unsigned int)unx_mode, (unsigned int)access_mask,
2297 (unsigned int)open_access_mask));
2299 fsp_open = open_file(fsp, conn, req, parent_dir,
2300 flags|flags2, unx_mode, access_mask,
2301 open_access_mask, &new_file_created);
2303 if (NT_STATUS_EQUAL(fsp_open, NT_STATUS_NETWORK_BUSY)) {
2304 struct deferred_open_record state;
2307 * EWOULDBLOCK/EAGAIN maps to NETWORK_BUSY.
2309 if (file_existed && S_ISFIFO(fsp->fsp_name->st.st_ex_mode)) {
2310 DEBUG(10, ("FIFO busy\n"));
2311 return NT_STATUS_NETWORK_BUSY;
2313 if (req == NULL) {
2314 DEBUG(10, ("Internal open busy\n"));
2315 return NT_STATUS_NETWORK_BUSY;
2319 * From here on we assume this is an oplock break triggered
2322 lck = get_existing_share_mode_lock(talloc_tos(), fsp->file_id);
2323 if (lck == NULL) {
2324 state.delayed_for_oplocks = false;
2325 state.async_open = false;
2326 state.id = fsp->file_id;
2327 defer_open(NULL, request_time, timeval_set(0, 0),
2328 req, &state);
2329 DEBUG(10, ("No share mode lock found after "
2330 "EWOULDBLOCK, retrying sync\n"));
2331 return NT_STATUS_SHARING_VIOLATION;
2334 find_oplock_types(fsp, 0, lck, &batch_entry, &exclusive_entry,
2335 &got_level2_oplock, &got_a_none_oplock);
2337 if (delay_for_batch_oplocks(fsp, req->mid, 0, batch_entry) ||
2338 delay_for_exclusive_oplocks(fsp, req->mid, 0,
2339 exclusive_entry)) {
2340 schedule_defer_open(lck, request_time, req);
2341 TALLOC_FREE(lck);
2342 DEBUG(10, ("Sent oplock break request to kernel "
2343 "oplock holder\n"));
2344 return NT_STATUS_SHARING_VIOLATION;
2348 * No oplock from Samba around. Immediately retry with
2349 * a blocking open.
2351 state.delayed_for_oplocks = false;
2352 state.async_open = false;
2353 state.id = lck->data->id;
2354 defer_open(lck, request_time, timeval_set(0, 0), req, &state);
2355 TALLOC_FREE(lck);
2356 DEBUG(10, ("No Samba oplock around after EWOULDBLOCK. "
2357 "Retrying sync\n"));
2358 return NT_STATUS_SHARING_VIOLATION;
2361 if (!NT_STATUS_IS_OK(fsp_open)) {
2362 if (NT_STATUS_EQUAL(fsp_open, NT_STATUS_RETRY)) {
2363 schedule_async_open(request_time, req);
2365 TALLOC_FREE(lck);
2366 return fsp_open;
2369 if (file_existed && !check_same_dev_ino(&saved_stat, &smb_fname->st)) {
2371 * The file did exist, but some other (local or NFS)
2372 * process either renamed/unlinked and re-created the
2373 * file with different dev/ino after we walked the path,
2374 * but before we did the open. We could retry the
2375 * open but it's a rare enough case it's easier to
2376 * just fail the open to prevent creating any problems
2377 * in the open file db having the wrong dev/ino key.
2379 TALLOC_FREE(lck);
2380 fd_close(fsp);
2381 DEBUG(1,("open_file_ntcreate: file %s - dev/ino mismatch. "
2382 "Old (dev=0x%llu, ino =0x%llu). "
2383 "New (dev=0x%llu, ino=0x%llu). Failing open "
2384 " with NT_STATUS_ACCESS_DENIED.\n",
2385 smb_fname_str_dbg(smb_fname),
2386 (unsigned long long)saved_stat.st_ex_dev,
2387 (unsigned long long)saved_stat.st_ex_ino,
2388 (unsigned long long)smb_fname->st.st_ex_dev,
2389 (unsigned long long)smb_fname->st.st_ex_ino));
2390 return NT_STATUS_ACCESS_DENIED;
2393 old_write_time = smb_fname->st.st_ex_mtime;
2396 * Deal with the race condition where two smbd's detect the
2397 * file doesn't exist and do the create at the same time. One
2398 * of them will win and set a share mode, the other (ie. this
2399 * one) should check if the requested share mode for this
2400 * create is allowed.
2404 * Now the file exists and fsp is successfully opened,
2405 * fsp->dev and fsp->inode are valid and should replace the
2406 * dev=0,inode=0 from a non existent file. Spotted by
2407 * Nadav Danieli <nadavd@exanet.com>. JRA.
2410 id = fsp->file_id;
2412 lck = get_share_mode_lock(talloc_tos(), id,
2413 conn->connectpath,
2414 smb_fname, &old_write_time);
2416 if (lck == NULL) {
2417 DEBUG(0, ("open_file_ntcreate: Could not get share "
2418 "mode lock for %s\n",
2419 smb_fname_str_dbg(smb_fname)));
2420 fd_close(fsp);
2421 return NT_STATUS_SHARING_VIOLATION;
2424 /* Get the types we need to examine. */
2425 find_oplock_types(fsp,
2426 oplock_request,
2427 lck,
2428 &batch_entry,
2429 &exclusive_entry,
2430 &got_level2_oplock,
2431 &got_a_none_oplock);
2433 /* First pass - send break only on batch oplocks. */
2434 if ((req != NULL) &&
2435 delay_for_batch_oplocks(fsp,
2436 req->mid,
2437 oplock_request,
2438 batch_entry)) {
2439 schedule_defer_open(lck, request_time, req);
2440 TALLOC_FREE(lck);
2441 fd_close(fsp);
2442 return NT_STATUS_SHARING_VIOLATION;
2445 status = open_mode_check(conn, lck, fsp->name_hash,
2446 access_mask, share_access,
2447 create_options, &file_existed);
2449 if (NT_STATUS_IS_OK(status)) {
2450 /* We might be going to allow this open. Check oplock
2451 * status again. */
2452 /* Second pass - send break for both batch or
2453 * exclusive oplocks. */
2454 if ((req != NULL) &&
2455 delay_for_exclusive_oplocks(
2456 fsp,
2457 req->mid,
2458 oplock_request,
2459 exclusive_entry)) {
2460 schedule_defer_open(lck, request_time, req);
2461 TALLOC_FREE(lck);
2462 fd_close(fsp);
2463 return NT_STATUS_SHARING_VIOLATION;
2467 if (NT_STATUS_EQUAL(status, NT_STATUS_DELETE_PENDING)) {
2468 /* DELETE_PENDING is not deferred for a second */
2469 TALLOC_FREE(lck);
2470 fd_close(fsp);
2471 return status;
2474 if (!NT_STATUS_IS_OK(status)) {
2475 uint32 can_access_mask;
2476 bool can_access = True;
2478 SMB_ASSERT(NT_STATUS_EQUAL(status, NT_STATUS_SHARING_VIOLATION));
2480 /* Check if this can be done with the deny_dos and fcb
2481 * calls. */
2482 if (private_flags &
2483 (NTCREATEX_OPTIONS_PRIVATE_DENY_DOS|
2484 NTCREATEX_OPTIONS_PRIVATE_DENY_FCB)) {
2485 if (req == NULL) {
2486 DEBUG(0, ("DOS open without an SMB "
2487 "request!\n"));
2488 TALLOC_FREE(lck);
2489 fd_close(fsp);
2490 return NT_STATUS_INTERNAL_ERROR;
2493 /* Use the client requested access mask here,
2494 * not the one we open with. */
2495 status = fcb_or_dos_open(req,
2496 conn,
2497 fsp,
2498 smb_fname,
2500 req->smbpid,
2501 req->vuid,
2502 access_mask,
2503 share_access,
2504 create_options);
2506 if (NT_STATUS_IS_OK(status)) {
2507 TALLOC_FREE(lck);
2508 if (pinfo) {
2509 *pinfo = FILE_WAS_OPENED;
2511 return NT_STATUS_OK;
2516 * This next line is a subtlety we need for
2517 * MS-Access. If a file open will fail due to share
2518 * permissions and also for security (access) reasons,
2519 * we need to return the access failed error, not the
2520 * share error. We can't open the file due to kernel
2521 * oplock deadlock (it's possible we failed above on
2522 * the open_mode_check()) so use a userspace check.
2525 if (flags & O_RDWR) {
2526 can_access_mask = FILE_READ_DATA|FILE_WRITE_DATA;
2527 } else if (flags & O_WRONLY) {
2528 can_access_mask = FILE_WRITE_DATA;
2529 } else {
2530 can_access_mask = FILE_READ_DATA;
2533 if (((can_access_mask & FILE_WRITE_DATA) &&
2534 !CAN_WRITE(conn)) ||
2535 !NT_STATUS_IS_OK(smbd_check_access_rights(conn,
2536 smb_fname,
2537 false,
2538 can_access_mask))) {
2539 can_access = False;
2543 * If we're returning a share violation, ensure we
2544 * cope with the braindead 1 second delay (SMB1 only).
2547 if (!(oplock_request & INTERNAL_OPEN_ONLY) &&
2548 !conn->sconn->using_smb2 &&
2549 lp_defer_sharing_violations()) {
2550 struct timeval timeout;
2551 struct deferred_open_record state;
2552 int timeout_usecs;
2554 /* this is a hack to speed up torture tests
2555 in 'make test' */
2556 timeout_usecs = lp_parm_int(SNUM(conn),
2557 "smbd","sharedelay",
2558 SHARING_VIOLATION_USEC_WAIT);
2560 /* This is a relative time, added to the absolute
2561 request_time value to get the absolute timeout time.
2562 Note that if this is the second or greater time we enter
2563 this codepath for this particular request mid then
2564 request_time is left as the absolute time of the *first*
2565 time this request mid was processed. This is what allows
2566 the request to eventually time out. */
2568 timeout = timeval_set(0, timeout_usecs);
2570 /* Nothing actually uses state.delayed_for_oplocks
2571 but it's handy to differentiate in debug messages
2572 between a 30 second delay due to oplock break, and
2573 a 1 second delay for share mode conflicts. */
2575 state.delayed_for_oplocks = False;
2576 state.async_open = false;
2577 state.id = id;
2579 if ((req != NULL)
2580 && !request_timed_out(request_time,
2581 timeout)) {
2582 defer_open(lck, request_time, timeout,
2583 req, &state);
2587 TALLOC_FREE(lck);
2588 fd_close(fsp);
2589 if (can_access) {
2591 * We have detected a sharing violation here
2592 * so return the correct error code
2594 status = NT_STATUS_SHARING_VIOLATION;
2595 } else {
2596 status = NT_STATUS_ACCESS_DENIED;
2598 return status;
2601 grant_fsp_oplock_type(fsp,
2602 oplock_request,
2603 got_level2_oplock,
2604 got_a_none_oplock);
2607 * We have the share entry *locked*.....
2610 /* Delete streams if create_disposition requires it */
2611 if (!new_file_created && clear_ads(create_disposition) &&
2612 !is_ntfs_stream_smb_fname(smb_fname)) {
2613 status = delete_all_streams(conn, smb_fname->base_name);
2614 if (!NT_STATUS_IS_OK(status)) {
2615 TALLOC_FREE(lck);
2616 fd_close(fsp);
2617 return status;
2621 /* note that we ignore failure for the following. It is
2622 basically a hack for NFS, and NFS will never set one of
2623 these only read them. Nobody but Samba can ever set a deny
2624 mode and we have already checked our more authoritative
2625 locking database for permission to set this deny mode. If
2626 the kernel refuses the operations then the kernel is wrong.
2627 note that GPFS supports it as well - jmcd */
2629 if (fsp->fh->fd != -1 && lp_kernel_share_modes(SNUM(conn))) {
2630 int ret_flock;
2631 ret_flock = SMB_VFS_KERNEL_FLOCK(fsp, share_access, access_mask);
2632 if(ret_flock == -1 ){
2634 TALLOC_FREE(lck);
2635 fd_close(fsp);
2637 return NT_STATUS_SHARING_VIOLATION;
2642 * At this point onwards, we can guarantee that the share entry
2643 * is locked, whether we created the file or not, and that the
2644 * deny mode is compatible with all current opens.
2648 * According to Samba4, SEC_FILE_READ_ATTRIBUTE is always granted,
2649 * but we don't have to store this - just ignore it on access check.
2651 if (conn->sconn->using_smb2) {
2653 * SMB2 doesn't return it (according to Microsoft tests).
2654 * Test Case: TestSuite_ScenarioNo009GrantedAccessTestS0
2655 * File created with access = 0x7 (Read, Write, Delete)
2656 * Query Info on file returns 0x87 (Read, Write, Delete, Read Attributes)
2658 fsp->access_mask = access_mask;
2659 } else {
2660 /* But SMB1 does. */
2661 fsp->access_mask = access_mask | FILE_READ_ATTRIBUTES;
2664 if (file_existed) {
2665 /* stat opens on existing files don't get oplocks. */
2666 if (is_stat_open(open_access_mask)) {
2667 fsp->oplock_type = NO_OPLOCK;
2671 if (new_file_created) {
2672 info = FILE_WAS_CREATED;
2673 } else {
2674 if (flags2 & O_TRUNC) {
2675 info = FILE_WAS_OVERWRITTEN;
2676 } else {
2677 info = FILE_WAS_OPENED;
2681 if (pinfo) {
2682 *pinfo = info;
2686 * Setup the oplock info in both the shared memory and
2687 * file structs.
2690 status = set_file_oplock(fsp, fsp->oplock_type);
2691 if (!NT_STATUS_IS_OK(status)) {
2693 * Could not get the kernel oplock or there are byte-range
2694 * locks on the file.
2696 fsp->oplock_type = NO_OPLOCK;
2699 set_share_mode(lck, fsp, get_current_uid(conn),
2700 req ? req->mid : 0,
2701 fsp->oplock_type);
2703 /* Handle strange delete on close create semantics. */
2704 if (create_options & FILE_DELETE_ON_CLOSE) {
2706 status = can_set_delete_on_close(fsp, new_dos_attributes);
2708 if (!NT_STATUS_IS_OK(status)) {
2709 /* Remember to delete the mode we just added. */
2710 del_share_mode(lck, fsp);
2711 TALLOC_FREE(lck);
2712 fd_close(fsp);
2713 return status;
2715 /* Note that here we set the *inital* delete on close flag,
2716 not the regular one. The magic gets handled in close. */
2717 fsp->initial_delete_on_close = True;
2720 if (info != FILE_WAS_OPENED) {
2721 /* Files should be initially set as archive */
2722 if (lp_map_archive(SNUM(conn)) ||
2723 lp_store_dos_attributes(SNUM(conn))) {
2724 if (!posix_open) {
2725 if (file_set_dosmode(conn, smb_fname,
2726 new_dos_attributes | FILE_ATTRIBUTE_ARCHIVE,
2727 parent_dir, true) == 0) {
2728 unx_mode = smb_fname->st.st_ex_mode;
2734 /* Determine sparse flag. */
2735 if (posix_open) {
2736 /* POSIX opens are sparse by default. */
2737 fsp->is_sparse = true;
2738 } else {
2739 fsp->is_sparse = (file_existed &&
2740 (existing_dos_attributes & FILE_ATTRIBUTE_SPARSE));
2744 * Take care of inherited ACLs on created files - if default ACL not
2745 * selected.
2748 if (!posix_open && new_file_created && !def_acl) {
2750 int saved_errno = errno; /* We might get ENOSYS in the next
2751 * call.. */
2753 if (SMB_VFS_FCHMOD_ACL(fsp, unx_mode) == -1 &&
2754 errno == ENOSYS) {
2755 errno = saved_errno; /* Ignore ENOSYS */
2758 } else if (new_unx_mode) {
2760 int ret = -1;
2762 /* Attributes need changing. File already existed. */
2765 int saved_errno = errno; /* We might get ENOSYS in the
2766 * next call.. */
2767 ret = SMB_VFS_FCHMOD_ACL(fsp, new_unx_mode);
2769 if (ret == -1 && errno == ENOSYS) {
2770 errno = saved_errno; /* Ignore ENOSYS */
2771 } else {
2772 DEBUG(5, ("open_file_ntcreate: reset "
2773 "attributes of file %s to 0%o\n",
2774 smb_fname_str_dbg(smb_fname),
2775 (unsigned int)new_unx_mode));
2776 ret = 0; /* Don't do the fchmod below. */
2780 if ((ret == -1) &&
2781 (SMB_VFS_FCHMOD(fsp, new_unx_mode) == -1))
2782 DEBUG(5, ("open_file_ntcreate: failed to reset "
2783 "attributes of file %s to 0%o\n",
2784 smb_fname_str_dbg(smb_fname),
2785 (unsigned int)new_unx_mode));
2788 TALLOC_FREE(lck);
2790 return NT_STATUS_OK;
2794 /****************************************************************************
2795 Open a file for for write to ensure that we can fchmod it.
2796 ****************************************************************************/
2798 NTSTATUS open_file_fchmod(connection_struct *conn,
2799 struct smb_filename *smb_fname,
2800 files_struct **result)
2802 if (!VALID_STAT(smb_fname->st)) {
2803 return NT_STATUS_INVALID_PARAMETER;
2806 return SMB_VFS_CREATE_FILE(
2807 conn, /* conn */
2808 NULL, /* req */
2809 0, /* root_dir_fid */
2810 smb_fname, /* fname */
2811 FILE_WRITE_DATA, /* access_mask */
2812 (FILE_SHARE_READ | FILE_SHARE_WRITE | /* share_access */
2813 FILE_SHARE_DELETE),
2814 FILE_OPEN, /* create_disposition*/
2815 0, /* create_options */
2816 0, /* file_attributes */
2817 INTERNAL_OPEN_ONLY, /* oplock_request */
2818 0, /* allocation_size */
2819 0, /* private_flags */
2820 NULL, /* sd */
2821 NULL, /* ea_list */
2822 result, /* result */
2823 NULL); /* pinfo */
2826 static NTSTATUS mkdir_internal(connection_struct *conn,
2827 struct smb_filename *smb_dname,
2828 uint32 file_attributes)
2830 mode_t mode;
2831 char *parent_dir = NULL;
2832 NTSTATUS status;
2833 bool posix_open = false;
2834 bool need_re_stat = false;
2835 uint32_t access_mask = SEC_DIR_ADD_SUBDIR;
2837 if (!CAN_WRITE(conn) || (access_mask & ~(conn->share_access))) {
2838 DEBUG(5,("mkdir_internal: failing share access "
2839 "%s\n", lp_servicename(talloc_tos(), SNUM(conn))));
2840 return NT_STATUS_ACCESS_DENIED;
2843 if (!parent_dirname(talloc_tos(), smb_dname->base_name, &parent_dir,
2844 NULL)) {
2845 return NT_STATUS_NO_MEMORY;
2848 if (file_attributes & FILE_FLAG_POSIX_SEMANTICS) {
2849 posix_open = true;
2850 mode = (mode_t)(file_attributes & ~FILE_FLAG_POSIX_SEMANTICS);
2851 } else {
2852 mode = unix_mode(conn, FILE_ATTRIBUTE_DIRECTORY, smb_dname, parent_dir);
2855 status = check_parent_access(conn,
2856 smb_dname,
2857 access_mask);
2858 if(!NT_STATUS_IS_OK(status)) {
2859 DEBUG(5,("mkdir_internal: check_parent_access "
2860 "on directory %s for path %s returned %s\n",
2861 parent_dir,
2862 smb_dname->base_name,
2863 nt_errstr(status) ));
2864 return status;
2867 if (SMB_VFS_MKDIR(conn, smb_dname->base_name, mode) != 0) {
2868 return map_nt_error_from_unix(errno);
2871 /* Ensure we're checking for a symlink here.... */
2872 /* We don't want to get caught by a symlink racer. */
2874 if (SMB_VFS_LSTAT(conn, smb_dname) == -1) {
2875 DEBUG(2, ("Could not stat directory '%s' just created: %s\n",
2876 smb_fname_str_dbg(smb_dname), strerror(errno)));
2877 return map_nt_error_from_unix(errno);
2880 if (!S_ISDIR(smb_dname->st.st_ex_mode)) {
2881 DEBUG(0, ("Directory '%s' just created is not a directory !\n",
2882 smb_fname_str_dbg(smb_dname)));
2883 return NT_STATUS_NOT_A_DIRECTORY;
2886 if (lp_store_dos_attributes(SNUM(conn))) {
2887 if (!posix_open) {
2888 file_set_dosmode(conn, smb_dname,
2889 file_attributes | FILE_ATTRIBUTE_DIRECTORY,
2890 parent_dir, true);
2894 if (lp_inherit_perms(SNUM(conn))) {
2895 inherit_access_posix_acl(conn, parent_dir,
2896 smb_dname->base_name, mode);
2897 need_re_stat = true;
2900 if (!posix_open) {
2902 * Check if high bits should have been set,
2903 * then (if bits are missing): add them.
2904 * Consider bits automagically set by UNIX, i.e. SGID bit from parent
2905 * dir.
2907 if ((mode & ~(S_IRWXU|S_IRWXG|S_IRWXO)) &&
2908 (mode & ~smb_dname->st.st_ex_mode)) {
2909 SMB_VFS_CHMOD(conn, smb_dname->base_name,
2910 (smb_dname->st.st_ex_mode |
2911 (mode & ~smb_dname->st.st_ex_mode)));
2912 need_re_stat = true;
2916 /* Change the owner if required. */
2917 if (lp_inherit_owner(SNUM(conn))) {
2918 change_dir_owner_to_parent(conn, parent_dir,
2919 smb_dname->base_name,
2920 &smb_dname->st);
2921 need_re_stat = true;
2924 if (need_re_stat) {
2925 if (SMB_VFS_LSTAT(conn, smb_dname) == -1) {
2926 DEBUG(2, ("Could not stat directory '%s' just created: %s\n",
2927 smb_fname_str_dbg(smb_dname), strerror(errno)));
2928 return map_nt_error_from_unix(errno);
2932 notify_fname(conn, NOTIFY_ACTION_ADDED, FILE_NOTIFY_CHANGE_DIR_NAME,
2933 smb_dname->base_name);
2935 return NT_STATUS_OK;
2938 /****************************************************************************
2939 Open a directory from an NT SMB call.
2940 ****************************************************************************/
2942 static NTSTATUS open_directory(connection_struct *conn,
2943 struct smb_request *req,
2944 struct smb_filename *smb_dname,
2945 uint32 access_mask,
2946 uint32 share_access,
2947 uint32 create_disposition,
2948 uint32 create_options,
2949 uint32 file_attributes,
2950 int *pinfo,
2951 files_struct **result)
2953 files_struct *fsp = NULL;
2954 bool dir_existed = VALID_STAT(smb_dname->st) ? True : False;
2955 struct share_mode_lock *lck = NULL;
2956 NTSTATUS status;
2957 struct timespec mtimespec;
2958 int info = 0;
2960 if (is_ntfs_stream_smb_fname(smb_dname)) {
2961 DEBUG(2, ("open_directory: %s is a stream name!\n",
2962 smb_fname_str_dbg(smb_dname)));
2963 return NT_STATUS_NOT_A_DIRECTORY;
2966 if (!(file_attributes & FILE_FLAG_POSIX_SEMANTICS)) {
2967 /* Ensure we have a directory attribute. */
2968 file_attributes |= FILE_ATTRIBUTE_DIRECTORY;
2971 DEBUG(5,("open_directory: opening directory %s, access_mask = 0x%x, "
2972 "share_access = 0x%x create_options = 0x%x, "
2973 "create_disposition = 0x%x, file_attributes = 0x%x\n",
2974 smb_fname_str_dbg(smb_dname),
2975 (unsigned int)access_mask,
2976 (unsigned int)share_access,
2977 (unsigned int)create_options,
2978 (unsigned int)create_disposition,
2979 (unsigned int)file_attributes));
2981 status = smbd_calculate_access_mask(conn, smb_dname, false,
2982 access_mask, &access_mask);
2983 if (!NT_STATUS_IS_OK(status)) {
2984 DEBUG(10, ("open_directory: smbd_calculate_access_mask "
2985 "on file %s returned %s\n",
2986 smb_fname_str_dbg(smb_dname),
2987 nt_errstr(status)));
2988 return status;
2991 if ((access_mask & SEC_FLAG_SYSTEM_SECURITY) &&
2992 !security_token_has_privilege(get_current_nttok(conn),
2993 SEC_PRIV_SECURITY)) {
2994 DEBUG(10, ("open_directory: open on %s "
2995 "failed - SEC_FLAG_SYSTEM_SECURITY denied.\n",
2996 smb_fname_str_dbg(smb_dname)));
2997 return NT_STATUS_PRIVILEGE_NOT_HELD;
3000 switch( create_disposition ) {
3001 case FILE_OPEN:
3003 if (!dir_existed) {
3004 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3007 info = FILE_WAS_OPENED;
3008 break;
3010 case FILE_CREATE:
3012 /* If directory exists error. If directory doesn't
3013 * exist create. */
3015 if (dir_existed) {
3016 status = NT_STATUS_OBJECT_NAME_COLLISION;
3017 DEBUG(2, ("open_directory: unable to create "
3018 "%s. Error was %s\n",
3019 smb_fname_str_dbg(smb_dname),
3020 nt_errstr(status)));
3021 return status;
3024 status = mkdir_internal(conn, smb_dname,
3025 file_attributes);
3027 if (!NT_STATUS_IS_OK(status)) {
3028 DEBUG(2, ("open_directory: unable to create "
3029 "%s. Error was %s\n",
3030 smb_fname_str_dbg(smb_dname),
3031 nt_errstr(status)));
3032 return status;
3035 info = FILE_WAS_CREATED;
3036 break;
3038 case FILE_OPEN_IF:
3040 * If directory exists open. If directory doesn't
3041 * exist create.
3044 if (dir_existed) {
3045 status = NT_STATUS_OK;
3046 info = FILE_WAS_OPENED;
3047 } else {
3048 status = mkdir_internal(conn, smb_dname,
3049 file_attributes);
3051 if (NT_STATUS_IS_OK(status)) {
3052 info = FILE_WAS_CREATED;
3053 } else {
3054 /* Cope with create race. */
3055 if (!NT_STATUS_EQUAL(status,
3056 NT_STATUS_OBJECT_NAME_COLLISION)) {
3057 DEBUG(2, ("open_directory: unable to create "
3058 "%s. Error was %s\n",
3059 smb_fname_str_dbg(smb_dname),
3060 nt_errstr(status)));
3061 return status;
3063 info = FILE_WAS_OPENED;
3067 break;
3069 case FILE_SUPERSEDE:
3070 case FILE_OVERWRITE:
3071 case FILE_OVERWRITE_IF:
3072 default:
3073 DEBUG(5,("open_directory: invalid create_disposition "
3074 "0x%x for directory %s\n",
3075 (unsigned int)create_disposition,
3076 smb_fname_str_dbg(smb_dname)));
3077 return NT_STATUS_INVALID_PARAMETER;
3080 if(!S_ISDIR(smb_dname->st.st_ex_mode)) {
3081 DEBUG(5,("open_directory: %s is not a directory !\n",
3082 smb_fname_str_dbg(smb_dname)));
3083 return NT_STATUS_NOT_A_DIRECTORY;
3086 if (info == FILE_WAS_OPENED) {
3087 status = smbd_check_access_rights(conn,
3088 smb_dname,
3089 false,
3090 access_mask);
3091 if (!NT_STATUS_IS_OK(status)) {
3092 DEBUG(10, ("open_directory: smbd_check_access_rights on "
3093 "file %s failed with %s\n",
3094 smb_fname_str_dbg(smb_dname),
3095 nt_errstr(status)));
3096 return status;
3100 status = file_new(req, conn, &fsp);
3101 if(!NT_STATUS_IS_OK(status)) {
3102 return status;
3106 * Setup the files_struct for it.
3109 fsp->file_id = vfs_file_id_from_sbuf(conn, &smb_dname->st);
3110 fsp->vuid = req ? req->vuid : UID_FIELD_INVALID;
3111 fsp->file_pid = req ? req->smbpid : 0;
3112 fsp->can_lock = False;
3113 fsp->can_read = False;
3114 fsp->can_write = False;
3116 fsp->share_access = share_access;
3117 fsp->fh->private_options = 0;
3119 * According to Samba4, SEC_FILE_READ_ATTRIBUTE is always granted,
3121 fsp->access_mask = access_mask | FILE_READ_ATTRIBUTES;
3122 fsp->print_file = NULL;
3123 fsp->modified = False;
3124 fsp->oplock_type = NO_OPLOCK;
3125 fsp->sent_oplock_break = NO_BREAK_SENT;
3126 fsp->is_directory = True;
3127 fsp->posix_open = (file_attributes & FILE_FLAG_POSIX_SEMANTICS) ? True : False;
3128 status = fsp_set_smb_fname(fsp, smb_dname);
3129 if (!NT_STATUS_IS_OK(status)) {
3130 file_free(req, fsp);
3131 return status;
3134 mtimespec = smb_dname->st.st_ex_mtime;
3136 #ifdef O_DIRECTORY
3137 status = fd_open(conn, fsp, O_RDONLY|O_DIRECTORY, 0);
3138 #else
3139 /* POSIX allows us to open a directory with O_RDONLY. */
3140 status = fd_open(conn, fsp, O_RDONLY, 0);
3141 #endif
3142 if (!NT_STATUS_IS_OK(status)) {
3143 DEBUG(5, ("open_directory: Could not open fd for "
3144 "%s (%s)\n",
3145 smb_fname_str_dbg(smb_dname),
3146 nt_errstr(status)));
3147 file_free(req, fsp);
3148 return status;
3151 status = vfs_stat_fsp(fsp);
3152 if (!NT_STATUS_IS_OK(status)) {
3153 fd_close(fsp);
3154 file_free(req, fsp);
3155 return status;
3158 /* Ensure there was no race condition. */
3159 if (!check_same_stat(&smb_dname->st, &fsp->fsp_name->st)) {
3160 DEBUG(5,("open_directory: stat struct differs for "
3161 "directory %s.\n",
3162 smb_fname_str_dbg(smb_dname)));
3163 fd_close(fsp);
3164 file_free(req, fsp);
3165 return NT_STATUS_ACCESS_DENIED;
3168 lck = get_share_mode_lock(talloc_tos(), fsp->file_id,
3169 conn->connectpath, smb_dname,
3170 &mtimespec);
3172 if (lck == NULL) {
3173 DEBUG(0, ("open_directory: Could not get share mode lock for "
3174 "%s\n", smb_fname_str_dbg(smb_dname)));
3175 fd_close(fsp);
3176 file_free(req, fsp);
3177 return NT_STATUS_SHARING_VIOLATION;
3180 status = open_mode_check(conn, lck, fsp->name_hash,
3181 access_mask, share_access,
3182 create_options, &dir_existed);
3184 if (!NT_STATUS_IS_OK(status)) {
3185 TALLOC_FREE(lck);
3186 fd_close(fsp);
3187 file_free(req, fsp);
3188 return status;
3191 set_share_mode(lck, fsp, get_current_uid(conn),
3192 req ? req->mid : 0, NO_OPLOCK);
3194 /* For directories the delete on close bit at open time seems
3195 always to be honored on close... See test 19 in Samba4 BASE-DELETE. */
3196 if (create_options & FILE_DELETE_ON_CLOSE) {
3197 status = can_set_delete_on_close(fsp, 0);
3198 if (!NT_STATUS_IS_OK(status) && !NT_STATUS_EQUAL(status, NT_STATUS_DIRECTORY_NOT_EMPTY)) {
3199 TALLOC_FREE(lck);
3200 fd_close(fsp);
3201 file_free(req, fsp);
3202 return status;
3205 if (NT_STATUS_IS_OK(status)) {
3206 /* Note that here we set the *inital* delete on close flag,
3207 not the regular one. The magic gets handled in close. */
3208 fsp->initial_delete_on_close = True;
3212 TALLOC_FREE(lck);
3214 if (pinfo) {
3215 *pinfo = info;
3218 *result = fsp;
3219 return NT_STATUS_OK;
3222 NTSTATUS create_directory(connection_struct *conn, struct smb_request *req,
3223 struct smb_filename *smb_dname)
3225 NTSTATUS status;
3226 files_struct *fsp;
3228 status = SMB_VFS_CREATE_FILE(
3229 conn, /* conn */
3230 req, /* req */
3231 0, /* root_dir_fid */
3232 smb_dname, /* fname */
3233 FILE_READ_ATTRIBUTES, /* access_mask */
3234 FILE_SHARE_NONE, /* share_access */
3235 FILE_CREATE, /* create_disposition*/
3236 FILE_DIRECTORY_FILE, /* create_options */
3237 FILE_ATTRIBUTE_DIRECTORY, /* file_attributes */
3238 0, /* oplock_request */
3239 0, /* allocation_size */
3240 0, /* private_flags */
3241 NULL, /* sd */
3242 NULL, /* ea_list */
3243 &fsp, /* result */
3244 NULL); /* pinfo */
3246 if (NT_STATUS_IS_OK(status)) {
3247 close_file(req, fsp, NORMAL_CLOSE);
3250 return status;
3253 /****************************************************************************
3254 Receive notification that one of our open files has been renamed by another
3255 smbd process.
3256 ****************************************************************************/
3258 void msg_file_was_renamed(struct messaging_context *msg,
3259 void *private_data,
3260 uint32_t msg_type,
3261 struct server_id server_id,
3262 DATA_BLOB *data)
3264 files_struct *fsp;
3265 char *frm = (char *)data->data;
3266 struct file_id id;
3267 const char *sharepath;
3268 const char *base_name;
3269 const char *stream_name;
3270 struct smb_filename *smb_fname = NULL;
3271 size_t sp_len, bn_len;
3272 NTSTATUS status;
3273 struct smbd_server_connection *sconn =
3274 talloc_get_type_abort(private_data,
3275 struct smbd_server_connection);
3277 if (data->data == NULL
3278 || data->length < MSG_FILE_RENAMED_MIN_SIZE + 2) {
3279 DEBUG(0, ("msg_file_was_renamed: Got invalid msg len %d\n",
3280 (int)data->length));
3281 return;
3284 /* Unpack the message. */
3285 pull_file_id_24(frm, &id);
3286 sharepath = &frm[24];
3287 sp_len = strlen(sharepath);
3288 base_name = sharepath + sp_len + 1;
3289 bn_len = strlen(base_name);
3290 stream_name = sharepath + sp_len + 1 + bn_len + 1;
3292 /* stream_name must always be NULL if there is no stream. */
3293 if (stream_name[0] == '\0') {
3294 stream_name = NULL;
3297 smb_fname = synthetic_smb_fname(talloc_tos(), base_name,
3298 stream_name, NULL);
3299 if (smb_fname == NULL) {
3300 return;
3303 DEBUG(10,("msg_file_was_renamed: Got rename message for sharepath %s, new name %s, "
3304 "file_id %s\n",
3305 sharepath, smb_fname_str_dbg(smb_fname),
3306 file_id_string_tos(&id)));
3308 for(fsp = file_find_di_first(sconn, id); fsp;
3309 fsp = file_find_di_next(fsp)) {
3310 if (memcmp(fsp->conn->connectpath, sharepath, sp_len) == 0) {
3312 DEBUG(10,("msg_file_was_renamed: renaming file %s from %s -> %s\n",
3313 fsp_fnum_dbg(fsp), fsp_str_dbg(fsp),
3314 smb_fname_str_dbg(smb_fname)));
3315 status = fsp_set_smb_fname(fsp, smb_fname);
3316 if (!NT_STATUS_IS_OK(status)) {
3317 goto out;
3319 } else {
3320 /* TODO. JRA. */
3321 /* Now we have the complete path we can work out if this is
3322 actually within this share and adjust newname accordingly. */
3323 DEBUG(10,("msg_file_was_renamed: share mismatch (sharepath %s "
3324 "not sharepath %s) "
3325 "%s from %s -> %s\n",
3326 fsp->conn->connectpath,
3327 sharepath,
3328 fsp_fnum_dbg(fsp),
3329 fsp_str_dbg(fsp),
3330 smb_fname_str_dbg(smb_fname)));
3333 out:
3334 TALLOC_FREE(smb_fname);
3335 return;
3339 * If a main file is opened for delete, all streams need to be checked for
3340 * !FILE_SHARE_DELETE. Do this by opening with DELETE_ACCESS.
3341 * If that works, delete them all by setting the delete on close and close.
3344 NTSTATUS open_streams_for_delete(connection_struct *conn,
3345 const char *fname)
3347 struct stream_struct *stream_info = NULL;
3348 files_struct **streams = NULL;
3349 int i;
3350 unsigned int num_streams = 0;
3351 TALLOC_CTX *frame = talloc_stackframe();
3352 NTSTATUS status;
3354 status = vfs_streaminfo(conn, NULL, fname, talloc_tos(),
3355 &num_streams, &stream_info);
3357 if (NT_STATUS_EQUAL(status, NT_STATUS_NOT_IMPLEMENTED)
3358 || NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
3359 DEBUG(10, ("no streams around\n"));
3360 TALLOC_FREE(frame);
3361 return NT_STATUS_OK;
3364 if (!NT_STATUS_IS_OK(status)) {
3365 DEBUG(10, ("vfs_streaminfo failed: %s\n",
3366 nt_errstr(status)));
3367 goto fail;
3370 DEBUG(10, ("open_streams_for_delete found %d streams\n",
3371 num_streams));
3373 if (num_streams == 0) {
3374 TALLOC_FREE(frame);
3375 return NT_STATUS_OK;
3378 streams = talloc_array(talloc_tos(), files_struct *, num_streams);
3379 if (streams == NULL) {
3380 DEBUG(0, ("talloc failed\n"));
3381 status = NT_STATUS_NO_MEMORY;
3382 goto fail;
3385 for (i=0; i<num_streams; i++) {
3386 struct smb_filename *smb_fname;
3388 if (strequal(stream_info[i].name, "::$DATA")) {
3389 streams[i] = NULL;
3390 continue;
3393 smb_fname = synthetic_smb_fname(
3394 talloc_tos(), fname, stream_info[i].name, NULL);
3395 if (smb_fname == NULL) {
3396 status = NT_STATUS_NO_MEMORY;
3397 goto fail;
3400 if (SMB_VFS_STAT(conn, smb_fname) == -1) {
3401 DEBUG(10, ("Unable to stat stream: %s\n",
3402 smb_fname_str_dbg(smb_fname)));
3405 status = SMB_VFS_CREATE_FILE(
3406 conn, /* conn */
3407 NULL, /* req */
3408 0, /* root_dir_fid */
3409 smb_fname, /* fname */
3410 DELETE_ACCESS, /* access_mask */
3411 (FILE_SHARE_READ | /* share_access */
3412 FILE_SHARE_WRITE | FILE_SHARE_DELETE),
3413 FILE_OPEN, /* create_disposition*/
3414 0, /* create_options */
3415 FILE_ATTRIBUTE_NORMAL, /* file_attributes */
3416 0, /* oplock_request */
3417 0, /* allocation_size */
3418 NTCREATEX_OPTIONS_PRIVATE_STREAM_DELETE, /* private_flags */
3419 NULL, /* sd */
3420 NULL, /* ea_list */
3421 &streams[i], /* result */
3422 NULL); /* pinfo */
3424 if (!NT_STATUS_IS_OK(status)) {
3425 DEBUG(10, ("Could not open stream %s: %s\n",
3426 smb_fname_str_dbg(smb_fname),
3427 nt_errstr(status)));
3429 TALLOC_FREE(smb_fname);
3430 break;
3432 TALLOC_FREE(smb_fname);
3436 * don't touch the variable "status" beyond this point :-)
3439 for (i -= 1 ; i >= 0; i--) {
3440 if (streams[i] == NULL) {
3441 continue;
3444 DEBUG(10, ("Closing stream # %d, %s\n", i,
3445 fsp_str_dbg(streams[i])));
3446 close_file(NULL, streams[i], NORMAL_CLOSE);
3449 fail:
3450 TALLOC_FREE(frame);
3451 return status;
3454 /*********************************************************************
3455 Create a default ACL by inheriting from the parent. If no inheritance
3456 from the parent available, don't set anything. This will leave the actual
3457 permissions the new file or directory already got from the filesystem
3458 as the NT ACL when read.
3459 *********************************************************************/
3461 static NTSTATUS inherit_new_acl(files_struct *fsp)
3463 TALLOC_CTX *frame = talloc_stackframe();
3464 char *parent_name = NULL;
3465 struct security_descriptor *parent_desc = NULL;
3466 NTSTATUS status = NT_STATUS_OK;
3467 struct security_descriptor *psd = NULL;
3468 const struct dom_sid *owner_sid = NULL;
3469 const struct dom_sid *group_sid = NULL;
3470 uint32_t security_info_sent = (SECINFO_OWNER | SECINFO_GROUP | SECINFO_DACL);
3471 struct security_token *token = fsp->conn->session_info->security_token;
3472 bool inherit_owner = lp_inherit_owner(SNUM(fsp->conn));
3473 bool inheritable_components = false;
3474 bool try_builtin_administrators = false;
3475 const struct dom_sid *BA_U_sid = NULL;
3476 const struct dom_sid *BA_G_sid = NULL;
3477 bool try_system = false;
3478 const struct dom_sid *SY_U_sid = NULL;
3479 const struct dom_sid *SY_G_sid = NULL;
3480 size_t size = 0;
3482 if (!parent_dirname(frame, fsp->fsp_name->base_name, &parent_name, NULL)) {
3483 TALLOC_FREE(frame);
3484 return NT_STATUS_NO_MEMORY;
3487 status = SMB_VFS_GET_NT_ACL(fsp->conn,
3488 parent_name,
3489 (SECINFO_OWNER | SECINFO_GROUP | SECINFO_DACL),
3490 frame,
3491 &parent_desc);
3492 if (!NT_STATUS_IS_OK(status)) {
3493 TALLOC_FREE(frame);
3494 return status;
3497 inheritable_components = sd_has_inheritable_components(parent_desc,
3498 fsp->is_directory);
3500 if (!inheritable_components && !inherit_owner) {
3501 TALLOC_FREE(frame);
3502 /* Nothing to inherit and not setting owner. */
3503 return NT_STATUS_OK;
3506 /* Create an inherited descriptor from the parent. */
3508 if (DEBUGLEVEL >= 10) {
3509 DEBUG(10,("inherit_new_acl: parent acl for %s is:\n",
3510 fsp_str_dbg(fsp) ));
3511 NDR_PRINT_DEBUG(security_descriptor, parent_desc);
3514 /* Inherit from parent descriptor if "inherit owner" set. */
3515 if (inherit_owner) {
3516 owner_sid = parent_desc->owner_sid;
3517 group_sid = parent_desc->group_sid;
3520 if (owner_sid == NULL) {
3521 if (security_token_has_builtin_administrators(token)) {
3522 try_builtin_administrators = true;
3523 } else if (security_token_is_system(token)) {
3524 try_builtin_administrators = true;
3525 try_system = true;
3529 if (group_sid == NULL &&
3530 token->num_sids == PRIMARY_GROUP_SID_INDEX)
3532 if (security_token_is_system(token)) {
3533 try_builtin_administrators = true;
3534 try_system = true;
3538 if (try_builtin_administrators) {
3539 struct unixid ids;
3540 bool ok;
3542 ZERO_STRUCT(ids);
3543 ok = sids_to_unixids(&global_sid_Builtin_Administrators, 1, &ids);
3544 if (ok) {
3545 switch (ids.type) {
3546 case ID_TYPE_BOTH:
3547 BA_U_sid = &global_sid_Builtin_Administrators;
3548 BA_G_sid = &global_sid_Builtin_Administrators;
3549 break;
3550 case ID_TYPE_UID:
3551 BA_U_sid = &global_sid_Builtin_Administrators;
3552 break;
3553 case ID_TYPE_GID:
3554 BA_G_sid = &global_sid_Builtin_Administrators;
3555 break;
3556 default:
3557 break;
3562 if (try_system) {
3563 struct unixid ids;
3564 bool ok;
3566 ZERO_STRUCT(ids);
3567 ok = sids_to_unixids(&global_sid_System, 1, &ids);
3568 if (ok) {
3569 switch (ids.type) {
3570 case ID_TYPE_BOTH:
3571 SY_U_sid = &global_sid_System;
3572 SY_G_sid = &global_sid_System;
3573 break;
3574 case ID_TYPE_UID:
3575 SY_U_sid = &global_sid_System;
3576 break;
3577 case ID_TYPE_GID:
3578 SY_G_sid = &global_sid_System;
3579 break;
3580 default:
3581 break;
3586 if (owner_sid == NULL) {
3587 owner_sid = BA_U_sid;
3590 if (owner_sid == NULL) {
3591 owner_sid = SY_U_sid;
3594 if (group_sid == NULL) {
3595 group_sid = SY_G_sid;
3598 if (try_system && group_sid == NULL) {
3599 group_sid = BA_G_sid;
3602 if (owner_sid == NULL) {
3603 owner_sid = &token->sids[PRIMARY_USER_SID_INDEX];
3605 if (group_sid == NULL) {
3606 if (token->num_sids == PRIMARY_GROUP_SID_INDEX) {
3607 group_sid = &token->sids[PRIMARY_USER_SID_INDEX];
3608 } else {
3609 group_sid = &token->sids[PRIMARY_GROUP_SID_INDEX];
3613 status = se_create_child_secdesc(frame,
3614 &psd,
3615 &size,
3616 parent_desc,
3617 owner_sid,
3618 group_sid,
3619 fsp->is_directory);
3620 if (!NT_STATUS_IS_OK(status)) {
3621 TALLOC_FREE(frame);
3622 return status;
3625 /* If inheritable_components == false,
3626 se_create_child_secdesc()
3627 creates a security desriptor with a NULL dacl
3628 entry, but with SEC_DESC_DACL_PRESENT. We need
3629 to remove that flag. */
3631 if (!inheritable_components) {
3632 security_info_sent &= ~SECINFO_DACL;
3633 psd->type &= ~SEC_DESC_DACL_PRESENT;
3636 if (DEBUGLEVEL >= 10) {
3637 DEBUG(10,("inherit_new_acl: child acl for %s is:\n",
3638 fsp_str_dbg(fsp) ));
3639 NDR_PRINT_DEBUG(security_descriptor, psd);
3642 if (inherit_owner) {
3643 /* We need to be root to force this. */
3644 become_root();
3646 status = SMB_VFS_FSET_NT_ACL(fsp,
3647 security_info_sent,
3648 psd);
3649 if (inherit_owner) {
3650 unbecome_root();
3652 TALLOC_FREE(frame);
3653 return status;
3657 * Wrapper around open_file_ntcreate and open_directory
3660 static NTSTATUS create_file_unixpath(connection_struct *conn,
3661 struct smb_request *req,
3662 struct smb_filename *smb_fname,
3663 uint32_t access_mask,
3664 uint32_t share_access,
3665 uint32_t create_disposition,
3666 uint32_t create_options,
3667 uint32_t file_attributes,
3668 uint32_t oplock_request,
3669 uint64_t allocation_size,
3670 uint32_t private_flags,
3671 struct security_descriptor *sd,
3672 struct ea_list *ea_list,
3674 files_struct **result,
3675 int *pinfo)
3677 int info = FILE_WAS_OPENED;
3678 files_struct *base_fsp = NULL;
3679 files_struct *fsp = NULL;
3680 NTSTATUS status;
3682 DEBUG(10,("create_file_unixpath: access_mask = 0x%x "
3683 "file_attributes = 0x%x, share_access = 0x%x, "
3684 "create_disposition = 0x%x create_options = 0x%x "
3685 "oplock_request = 0x%x private_flags = 0x%x "
3686 "ea_list = 0x%p, sd = 0x%p, "
3687 "fname = %s\n",
3688 (unsigned int)access_mask,
3689 (unsigned int)file_attributes,
3690 (unsigned int)share_access,
3691 (unsigned int)create_disposition,
3692 (unsigned int)create_options,
3693 (unsigned int)oplock_request,
3694 (unsigned int)private_flags,
3695 ea_list, sd, smb_fname_str_dbg(smb_fname)));
3697 if (create_options & FILE_OPEN_BY_FILE_ID) {
3698 status = NT_STATUS_NOT_SUPPORTED;
3699 goto fail;
3702 if (create_options & NTCREATEX_OPTIONS_INVALID_PARAM_MASK) {
3703 status = NT_STATUS_INVALID_PARAMETER;
3704 goto fail;
3707 if (req == NULL) {
3708 oplock_request |= INTERNAL_OPEN_ONLY;
3711 if ((conn->fs_capabilities & FILE_NAMED_STREAMS)
3712 && (access_mask & DELETE_ACCESS)
3713 && !is_ntfs_stream_smb_fname(smb_fname)) {
3715 * We can't open a file with DELETE access if any of the
3716 * streams is open without FILE_SHARE_DELETE
3718 status = open_streams_for_delete(conn, smb_fname->base_name);
3720 if (!NT_STATUS_IS_OK(status)) {
3721 goto fail;
3725 if ((access_mask & SEC_FLAG_SYSTEM_SECURITY) &&
3726 !security_token_has_privilege(get_current_nttok(conn),
3727 SEC_PRIV_SECURITY)) {
3728 DEBUG(10, ("create_file_unixpath: open on %s "
3729 "failed - SEC_FLAG_SYSTEM_SECURITY denied.\n",
3730 smb_fname_str_dbg(smb_fname)));
3731 status = NT_STATUS_PRIVILEGE_NOT_HELD;
3732 goto fail;
3735 if ((conn->fs_capabilities & FILE_NAMED_STREAMS)
3736 && is_ntfs_stream_smb_fname(smb_fname)
3737 && (!(private_flags & NTCREATEX_OPTIONS_PRIVATE_STREAM_DELETE))) {
3738 uint32 base_create_disposition;
3739 struct smb_filename *smb_fname_base = NULL;
3741 if (create_options & FILE_DIRECTORY_FILE) {
3742 status = NT_STATUS_NOT_A_DIRECTORY;
3743 goto fail;
3746 switch (create_disposition) {
3747 case FILE_OPEN:
3748 base_create_disposition = FILE_OPEN;
3749 break;
3750 default:
3751 base_create_disposition = FILE_OPEN_IF;
3752 break;
3755 /* Create an smb_filename with stream_name == NULL. */
3756 smb_fname_base = synthetic_smb_fname(talloc_tos(),
3757 smb_fname->base_name,
3758 NULL, NULL);
3759 if (smb_fname_base == NULL) {
3760 status = NT_STATUS_NO_MEMORY;
3761 goto fail;
3764 if (SMB_VFS_STAT(conn, smb_fname_base) == -1) {
3765 DEBUG(10, ("Unable to stat stream: %s\n",
3766 smb_fname_str_dbg(smb_fname_base)));
3769 /* Open the base file. */
3770 status = create_file_unixpath(conn, NULL, smb_fname_base, 0,
3771 FILE_SHARE_READ
3772 | FILE_SHARE_WRITE
3773 | FILE_SHARE_DELETE,
3774 base_create_disposition,
3775 0, 0, 0, 0, 0, NULL, NULL,
3776 &base_fsp, NULL);
3777 TALLOC_FREE(smb_fname_base);
3779 if (!NT_STATUS_IS_OK(status)) {
3780 DEBUG(10, ("create_file_unixpath for base %s failed: "
3781 "%s\n", smb_fname->base_name,
3782 nt_errstr(status)));
3783 goto fail;
3785 /* we don't need to low level fd */
3786 fd_close(base_fsp);
3790 * If it's a request for a directory open, deal with it separately.
3793 if (create_options & FILE_DIRECTORY_FILE) {
3795 if (create_options & FILE_NON_DIRECTORY_FILE) {
3796 status = NT_STATUS_INVALID_PARAMETER;
3797 goto fail;
3800 /* Can't open a temp directory. IFS kit test. */
3801 if (!(file_attributes & FILE_FLAG_POSIX_SEMANTICS) &&
3802 (file_attributes & FILE_ATTRIBUTE_TEMPORARY)) {
3803 status = NT_STATUS_INVALID_PARAMETER;
3804 goto fail;
3808 * We will get a create directory here if the Win32
3809 * app specified a security descriptor in the
3810 * CreateDirectory() call.
3813 oplock_request = 0;
3814 status = open_directory(
3815 conn, req, smb_fname, access_mask, share_access,
3816 create_disposition, create_options, file_attributes,
3817 &info, &fsp);
3818 } else {
3821 * Ordinary file case.
3824 status = file_new(req, conn, &fsp);
3825 if(!NT_STATUS_IS_OK(status)) {
3826 goto fail;
3829 status = fsp_set_smb_fname(fsp, smb_fname);
3830 if (!NT_STATUS_IS_OK(status)) {
3831 goto fail;
3834 if (base_fsp) {
3836 * We're opening the stream element of a
3837 * base_fsp we already opened. Set up the
3838 * base_fsp pointer.
3840 fsp->base_fsp = base_fsp;
3843 if (allocation_size) {
3844 fsp->initial_allocation_size = smb_roundup(fsp->conn,
3845 allocation_size);
3848 status = open_file_ntcreate(conn,
3849 req,
3850 access_mask,
3851 share_access,
3852 create_disposition,
3853 create_options,
3854 file_attributes,
3855 oplock_request,
3856 private_flags,
3857 &info,
3858 fsp);
3860 if(!NT_STATUS_IS_OK(status)) {
3861 file_free(req, fsp);
3862 fsp = NULL;
3865 if (NT_STATUS_EQUAL(status, NT_STATUS_FILE_IS_A_DIRECTORY)) {
3867 /* A stream open never opens a directory */
3869 if (base_fsp) {
3870 status = NT_STATUS_FILE_IS_A_DIRECTORY;
3871 goto fail;
3875 * Fail the open if it was explicitly a non-directory
3876 * file.
3879 if (create_options & FILE_NON_DIRECTORY_FILE) {
3880 status = NT_STATUS_FILE_IS_A_DIRECTORY;
3881 goto fail;
3884 oplock_request = 0;
3885 status = open_directory(
3886 conn, req, smb_fname, access_mask,
3887 share_access, create_disposition,
3888 create_options, file_attributes,
3889 &info, &fsp);
3893 if (!NT_STATUS_IS_OK(status)) {
3894 goto fail;
3897 fsp->base_fsp = base_fsp;
3899 if ((ea_list != NULL) &&
3900 ((info == FILE_WAS_CREATED) || (info == FILE_WAS_OVERWRITTEN))) {
3901 status = set_ea(conn, fsp, fsp->fsp_name, ea_list);
3902 if (!NT_STATUS_IS_OK(status)) {
3903 goto fail;
3907 if (!fsp->is_directory && S_ISDIR(fsp->fsp_name->st.st_ex_mode)) {
3908 status = NT_STATUS_ACCESS_DENIED;
3909 goto fail;
3912 /* Save the requested allocation size. */
3913 if ((info == FILE_WAS_CREATED) || (info == FILE_WAS_OVERWRITTEN)) {
3914 if (allocation_size
3915 && (allocation_size > fsp->fsp_name->st.st_ex_size)) {
3916 fsp->initial_allocation_size = smb_roundup(
3917 fsp->conn, allocation_size);
3918 if (fsp->is_directory) {
3919 /* Can't set allocation size on a directory. */
3920 status = NT_STATUS_ACCESS_DENIED;
3921 goto fail;
3923 if (vfs_allocate_file_space(
3924 fsp, fsp->initial_allocation_size) == -1) {
3925 status = NT_STATUS_DISK_FULL;
3926 goto fail;
3928 } else {
3929 fsp->initial_allocation_size = smb_roundup(
3930 fsp->conn, (uint64_t)fsp->fsp_name->st.st_ex_size);
3932 } else {
3933 fsp->initial_allocation_size = 0;
3936 if ((info == FILE_WAS_CREATED) && lp_nt_acl_support(SNUM(conn)) &&
3937 fsp->base_fsp == NULL) {
3938 if (sd != NULL) {
3940 * According to the MS documentation, the only time the security
3941 * descriptor is applied to the opened file is iff we *created* the
3942 * file; an existing file stays the same.
3944 * Also, it seems (from observation) that you can open the file with
3945 * any access mask but you can still write the sd. We need to override
3946 * the granted access before we call set_sd
3947 * Patch for bug #2242 from Tom Lackemann <cessnatomny@yahoo.com>.
3950 uint32_t sec_info_sent;
3951 uint32_t saved_access_mask = fsp->access_mask;
3953 sec_info_sent = get_sec_info(sd);
3955 fsp->access_mask = FILE_GENERIC_ALL;
3957 if (sec_info_sent & (SECINFO_OWNER|
3958 SECINFO_GROUP|
3959 SECINFO_DACL|
3960 SECINFO_SACL)) {
3961 status = set_sd(fsp, sd, sec_info_sent);
3964 fsp->access_mask = saved_access_mask;
3966 if (!NT_STATUS_IS_OK(status)) {
3967 goto fail;
3969 } else if (lp_inherit_acls(SNUM(conn))) {
3970 /* Inherit from parent. Errors here are not fatal. */
3971 status = inherit_new_acl(fsp);
3972 if (!NT_STATUS_IS_OK(status)) {
3973 DEBUG(10,("inherit_new_acl: failed for %s with %s\n",
3974 fsp_str_dbg(fsp),
3975 nt_errstr(status) ));
3980 DEBUG(10, ("create_file_unixpath: info=%d\n", info));
3982 *result = fsp;
3983 if (pinfo != NULL) {
3984 *pinfo = info;
3987 smb_fname->st = fsp->fsp_name->st;
3989 return NT_STATUS_OK;
3991 fail:
3992 DEBUG(10, ("create_file_unixpath: %s\n", nt_errstr(status)));
3994 if (fsp != NULL) {
3995 if (base_fsp && fsp->base_fsp == base_fsp) {
3997 * The close_file below will close
3998 * fsp->base_fsp.
4000 base_fsp = NULL;
4002 close_file(req, fsp, ERROR_CLOSE);
4003 fsp = NULL;
4005 if (base_fsp != NULL) {
4006 close_file(req, base_fsp, ERROR_CLOSE);
4007 base_fsp = NULL;
4009 return status;
4013 * Calculate the full path name given a relative fid.
4015 NTSTATUS get_relative_fid_filename(connection_struct *conn,
4016 struct smb_request *req,
4017 uint16_t root_dir_fid,
4018 const struct smb_filename *smb_fname,
4019 struct smb_filename **smb_fname_out)
4021 files_struct *dir_fsp;
4022 char *parent_fname = NULL;
4023 char *new_base_name = NULL;
4024 NTSTATUS status;
4026 if (root_dir_fid == 0 || !smb_fname) {
4027 status = NT_STATUS_INTERNAL_ERROR;
4028 goto out;
4031 dir_fsp = file_fsp(req, root_dir_fid);
4033 if (dir_fsp == NULL) {
4034 status = NT_STATUS_INVALID_HANDLE;
4035 goto out;
4038 if (is_ntfs_stream_smb_fname(dir_fsp->fsp_name)) {
4039 status = NT_STATUS_INVALID_HANDLE;
4040 goto out;
4043 if (!dir_fsp->is_directory) {
4046 * Check to see if this is a mac fork of some kind.
4049 if ((conn->fs_capabilities & FILE_NAMED_STREAMS) &&
4050 is_ntfs_stream_smb_fname(smb_fname)) {
4051 status = NT_STATUS_OBJECT_PATH_NOT_FOUND;
4052 goto out;
4056 we need to handle the case when we get a
4057 relative open relative to a file and the
4058 pathname is blank - this is a reopen!
4059 (hint from demyn plantenberg)
4062 status = NT_STATUS_INVALID_HANDLE;
4063 goto out;
4066 if (ISDOT(dir_fsp->fsp_name->base_name)) {
4068 * We're at the toplevel dir, the final file name
4069 * must not contain ./, as this is filtered out
4070 * normally by srvstr_get_path and unix_convert
4071 * explicitly rejects paths containing ./.
4073 parent_fname = talloc_strdup(talloc_tos(), "");
4074 if (parent_fname == NULL) {
4075 status = NT_STATUS_NO_MEMORY;
4076 goto out;
4078 } else {
4079 size_t dir_name_len = strlen(dir_fsp->fsp_name->base_name);
4082 * Copy in the base directory name.
4085 parent_fname = talloc_array(talloc_tos(), char,
4086 dir_name_len+2);
4087 if (parent_fname == NULL) {
4088 status = NT_STATUS_NO_MEMORY;
4089 goto out;
4091 memcpy(parent_fname, dir_fsp->fsp_name->base_name,
4092 dir_name_len+1);
4095 * Ensure it ends in a '/'.
4096 * We used TALLOC_SIZE +2 to add space for the '/'.
4099 if(dir_name_len
4100 && (parent_fname[dir_name_len-1] != '\\')
4101 && (parent_fname[dir_name_len-1] != '/')) {
4102 parent_fname[dir_name_len] = '/';
4103 parent_fname[dir_name_len+1] = '\0';
4107 new_base_name = talloc_asprintf(talloc_tos(), "%s%s", parent_fname,
4108 smb_fname->base_name);
4109 if (new_base_name == NULL) {
4110 status = NT_STATUS_NO_MEMORY;
4111 goto out;
4114 status = filename_convert(req,
4115 conn,
4116 req->flags2 & FLAGS2_DFS_PATHNAMES,
4117 new_base_name,
4119 NULL,
4120 smb_fname_out);
4121 if (!NT_STATUS_IS_OK(status)) {
4122 goto out;
4125 out:
4126 TALLOC_FREE(parent_fname);
4127 TALLOC_FREE(new_base_name);
4128 return status;
4131 NTSTATUS create_file_default(connection_struct *conn,
4132 struct smb_request *req,
4133 uint16_t root_dir_fid,
4134 struct smb_filename *smb_fname,
4135 uint32_t access_mask,
4136 uint32_t share_access,
4137 uint32_t create_disposition,
4138 uint32_t create_options,
4139 uint32_t file_attributes,
4140 uint32_t oplock_request,
4141 uint64_t allocation_size,
4142 uint32_t private_flags,
4143 struct security_descriptor *sd,
4144 struct ea_list *ea_list,
4145 files_struct **result,
4146 int *pinfo)
4148 int info = FILE_WAS_OPENED;
4149 files_struct *fsp = NULL;
4150 NTSTATUS status;
4151 bool stream_name = false;
4153 DEBUG(10,("create_file: access_mask = 0x%x "
4154 "file_attributes = 0x%x, share_access = 0x%x, "
4155 "create_disposition = 0x%x create_options = 0x%x "
4156 "oplock_request = 0x%x "
4157 "private_flags = 0x%x "
4158 "root_dir_fid = 0x%x, ea_list = 0x%p, sd = 0x%p, "
4159 "fname = %s\n",
4160 (unsigned int)access_mask,
4161 (unsigned int)file_attributes,
4162 (unsigned int)share_access,
4163 (unsigned int)create_disposition,
4164 (unsigned int)create_options,
4165 (unsigned int)oplock_request,
4166 (unsigned int)private_flags,
4167 (unsigned int)root_dir_fid,
4168 ea_list, sd, smb_fname_str_dbg(smb_fname)));
4171 * Calculate the filename from the root_dir_if if necessary.
4174 if (root_dir_fid != 0) {
4175 struct smb_filename *smb_fname_out = NULL;
4176 status = get_relative_fid_filename(conn, req, root_dir_fid,
4177 smb_fname, &smb_fname_out);
4178 if (!NT_STATUS_IS_OK(status)) {
4179 goto fail;
4181 smb_fname = smb_fname_out;
4185 * Check to see if this is a mac fork of some kind.
4188 stream_name = is_ntfs_stream_smb_fname(smb_fname);
4189 if (stream_name) {
4190 enum FAKE_FILE_TYPE fake_file_type;
4192 fake_file_type = is_fake_file(smb_fname);
4194 if (fake_file_type != FAKE_FILE_TYPE_NONE) {
4197 * Here we go! support for changing the disk quotas
4198 * --metze
4200 * We need to fake up to open this MAGIC QUOTA file
4201 * and return a valid FID.
4203 * w2k close this file directly after openening xp
4204 * also tries a QUERY_FILE_INFO on the file and then
4205 * close it
4207 status = open_fake_file(req, conn, req->vuid,
4208 fake_file_type, smb_fname,
4209 access_mask, &fsp);
4210 if (!NT_STATUS_IS_OK(status)) {
4211 goto fail;
4214 ZERO_STRUCT(smb_fname->st);
4215 goto done;
4218 if (!(conn->fs_capabilities & FILE_NAMED_STREAMS)) {
4219 status = NT_STATUS_OBJECT_NAME_NOT_FOUND;
4220 goto fail;
4224 if (is_ntfs_default_stream_smb_fname(smb_fname)) {
4225 int ret;
4226 smb_fname->stream_name = NULL;
4227 /* We have to handle this error here. */
4228 if (create_options & FILE_DIRECTORY_FILE) {
4229 status = NT_STATUS_NOT_A_DIRECTORY;
4230 goto fail;
4232 if (lp_posix_pathnames()) {
4233 ret = SMB_VFS_LSTAT(conn, smb_fname);
4234 } else {
4235 ret = SMB_VFS_STAT(conn, smb_fname);
4238 if (ret == 0 && VALID_STAT_OF_DIR(smb_fname->st)) {
4239 status = NT_STATUS_FILE_IS_A_DIRECTORY;
4240 goto fail;
4244 status = create_file_unixpath(
4245 conn, req, smb_fname, access_mask, share_access,
4246 create_disposition, create_options, file_attributes,
4247 oplock_request, allocation_size, private_flags,
4248 sd, ea_list,
4249 &fsp, &info);
4251 if (!NT_STATUS_IS_OK(status)) {
4252 goto fail;
4255 done:
4256 DEBUG(10, ("create_file: info=%d\n", info));
4258 *result = fsp;
4259 if (pinfo != NULL) {
4260 *pinfo = info;
4262 return NT_STATUS_OK;
4264 fail:
4265 DEBUG(10, ("create_file: %s\n", nt_errstr(status)));
4267 if (fsp != NULL) {
4268 close_file(req, fsp, ERROR_CLOSE);
4269 fsp = NULL;
4271 return status;