smbd: We don't use DEFERRED_OPEN_ENTRY anymore
[Samba/id10ts.git] / source3 / smbd / open.c
blobeff36f002c4930ba70d3ae136406cc28d7cd6288
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;
80 rejected_share_access = access_mask & ~(conn->share_access);
82 if (rejected_share_access) {
83 DEBUG(10, ("smbd_check_access_rights: rejected share access 0x%x "
84 "on %s (0x%x)\n",
85 (unsigned int)access_mask,
86 smb_fname_str_dbg(smb_fname),
87 (unsigned int)rejected_share_access ));
88 return NT_STATUS_ACCESS_DENIED;
91 if (!use_privs && get_current_uid(conn) == (uid_t)0) {
92 /* I'm sorry sir, I didn't know you were root... */
93 DEBUG(10,("smbd_check_access_rights: root override "
94 "on %s. Granting 0x%x\n",
95 smb_fname_str_dbg(smb_fname),
96 (unsigned int)access_mask ));
97 return NT_STATUS_OK;
100 if ((access_mask & DELETE_ACCESS) && !lp_acl_check_permissions(SNUM(conn))) {
101 DEBUG(10,("smbd_check_access_rights: not checking ACL "
102 "on DELETE_ACCESS on file %s. Granting 0x%x\n",
103 smb_fname_str_dbg(smb_fname),
104 (unsigned int)access_mask ));
105 return NT_STATUS_OK;
108 if (access_mask == DELETE_ACCESS &&
109 VALID_STAT(smb_fname->st) &&
110 S_ISLNK(smb_fname->st.st_ex_mode)) {
111 /* We can always delete a symlink. */
112 DEBUG(10,("smbd_check_access_rights: not checking ACL "
113 "on DELETE_ACCESS on symlink %s.\n",
114 smb_fname_str_dbg(smb_fname) ));
115 return NT_STATUS_OK;
118 status = SMB_VFS_GET_NT_ACL(conn, smb_fname->base_name,
119 (SECINFO_OWNER |
120 SECINFO_GROUP |
121 SECINFO_DACL), talloc_tos(), &sd);
123 if (!NT_STATUS_IS_OK(status)) {
124 DEBUG(10, ("smbd_check_access_rights: Could not get acl "
125 "on %s: %s\n",
126 smb_fname_str_dbg(smb_fname),
127 nt_errstr(status)));
129 if (NT_STATUS_EQUAL(status, NT_STATUS_ACCESS_DENIED)) {
130 goto access_denied;
133 return status;
137 * If we can access the path to this file, by
138 * default we have FILE_READ_ATTRIBUTES from the
139 * containing directory. See the section:
140 * "Algorithm to Check Access to an Existing File"
141 * in MS-FSA.pdf.
143 * se_file_access_check() also takes care of
144 * owner WRITE_DAC and READ_CONTROL.
146 status = se_file_access_check(sd,
147 get_current_nttok(conn),
148 use_privs,
149 (access_mask & ~FILE_READ_ATTRIBUTES),
150 &rejected_mask);
152 DEBUG(10,("smbd_check_access_rights: file %s requesting "
153 "0x%x returning 0x%x (%s)\n",
154 smb_fname_str_dbg(smb_fname),
155 (unsigned int)access_mask,
156 (unsigned int)rejected_mask,
157 nt_errstr(status) ));
159 if (!NT_STATUS_IS_OK(status)) {
160 if (DEBUGLEVEL >= 10) {
161 DEBUG(10,("smbd_check_access_rights: acl for %s is:\n",
162 smb_fname_str_dbg(smb_fname) ));
163 NDR_PRINT_DEBUG(security_descriptor, sd);
167 TALLOC_FREE(sd);
169 if (NT_STATUS_IS_OK(status) ||
170 !NT_STATUS_EQUAL(status, NT_STATUS_ACCESS_DENIED)) {
171 return status;
174 /* Here we know status == NT_STATUS_ACCESS_DENIED. */
176 access_denied:
178 if ((access_mask & FILE_WRITE_ATTRIBUTES) &&
179 (rejected_mask & FILE_WRITE_ATTRIBUTES) &&
180 !lp_store_dos_attributes(SNUM(conn)) &&
181 (lp_map_readonly(SNUM(conn)) ||
182 lp_map_archive(SNUM(conn)) ||
183 lp_map_hidden(SNUM(conn)) ||
184 lp_map_system(SNUM(conn)))) {
185 rejected_mask &= ~FILE_WRITE_ATTRIBUTES;
187 DEBUG(10,("smbd_check_access_rights: "
188 "overrode "
189 "FILE_WRITE_ATTRIBUTES "
190 "on file %s\n",
191 smb_fname_str_dbg(smb_fname)));
194 if (parent_override_delete(conn,
195 smb_fname,
196 access_mask,
197 rejected_mask)) {
198 /* Were we trying to do an open
199 * for delete and didn't get DELETE
200 * access (only) ? Check if the
201 * directory allows DELETE_CHILD.
202 * See here:
203 * http://blogs.msdn.com/oldnewthing/archive/2004/06/04/148426.aspx
204 * for details. */
206 rejected_mask &= ~DELETE_ACCESS;
208 DEBUG(10,("smbd_check_access_rights: "
209 "overrode "
210 "DELETE_ACCESS on "
211 "file %s\n",
212 smb_fname_str_dbg(smb_fname)));
215 if (rejected_mask != 0) {
216 return NT_STATUS_ACCESS_DENIED;
218 return NT_STATUS_OK;
221 static NTSTATUS check_parent_access(struct connection_struct *conn,
222 struct smb_filename *smb_fname,
223 uint32_t access_mask)
225 NTSTATUS status;
226 char *parent_dir = NULL;
227 struct security_descriptor *parent_sd = NULL;
228 uint32_t access_granted = 0;
230 if (!parent_dirname(talloc_tos(),
231 smb_fname->base_name,
232 &parent_dir,
233 NULL)) {
234 return NT_STATUS_NO_MEMORY;
237 if (get_current_uid(conn) == (uid_t)0) {
238 /* I'm sorry sir, I didn't know you were root... */
239 DEBUG(10,("check_parent_access: root override "
240 "on %s. Granting 0x%x\n",
241 smb_fname_str_dbg(smb_fname),
242 (unsigned int)access_mask ));
243 return NT_STATUS_OK;
246 status = SMB_VFS_GET_NT_ACL(conn,
247 parent_dir,
248 SECINFO_DACL,
249 talloc_tos(),
250 &parent_sd);
252 if (!NT_STATUS_IS_OK(status)) {
253 DEBUG(5,("check_parent_access: SMB_VFS_GET_NT_ACL failed for "
254 "%s with error %s\n",
255 parent_dir,
256 nt_errstr(status)));
257 return status;
261 * If we can access the path to this file, by
262 * default we have FILE_READ_ATTRIBUTES from the
263 * containing directory. See the section:
264 * "Algorithm to Check Access to an Existing File"
265 * in MS-FSA.pdf.
267 * se_file_access_check() also takes care of
268 * owner WRITE_DAC and READ_CONTROL.
270 status = se_file_access_check(parent_sd,
271 get_current_nttok(conn),
272 false,
273 (access_mask & ~FILE_READ_ATTRIBUTES),
274 &access_granted);
275 if(!NT_STATUS_IS_OK(status)) {
276 DEBUG(5,("check_parent_access: access check "
277 "on directory %s for "
278 "path %s for mask 0x%x returned (0x%x) %s\n",
279 parent_dir,
280 smb_fname->base_name,
281 access_mask,
282 access_granted,
283 nt_errstr(status) ));
284 return status;
287 return NT_STATUS_OK;
290 /****************************************************************************
291 fd support routines - attempt to do a dos_open.
292 ****************************************************************************/
294 NTSTATUS fd_open(struct connection_struct *conn,
295 files_struct *fsp,
296 int flags,
297 mode_t mode)
299 struct smb_filename *smb_fname = fsp->fsp_name;
300 NTSTATUS status = NT_STATUS_OK;
302 #ifdef O_NOFOLLOW
304 * Never follow symlinks on a POSIX client. The
305 * client should be doing this.
308 if (fsp->posix_open || !lp_symlinks(SNUM(conn))) {
309 flags |= O_NOFOLLOW;
311 #endif
313 fsp->fh->fd = SMB_VFS_OPEN(conn, smb_fname, fsp, flags, mode);
314 if (fsp->fh->fd == -1) {
315 int posix_errno = errno;
316 #ifdef O_NOFOLLOW
317 #if defined(ENOTSUP) && defined(OSF1)
318 /* handle special Tru64 errno */
319 if (errno == ENOTSUP) {
320 posix_errno = ELOOP;
322 #endif /* ENOTSUP */
323 #ifdef EFTYPE
324 /* fix broken NetBSD errno */
325 if (errno == EFTYPE) {
326 posix_errno = ELOOP;
328 #endif /* EFTYPE */
329 /* fix broken FreeBSD errno */
330 if (errno == EMLINK) {
331 posix_errno = ELOOP;
333 #endif /* O_NOFOLLOW */
334 status = map_nt_error_from_unix(posix_errno);
335 if (errno == EMFILE) {
336 static time_t last_warned = 0L;
338 if (time((time_t *) NULL) > last_warned) {
339 DEBUG(0,("Too many open files, unable "
340 "to open more! smbd's max "
341 "open files = %d\n",
342 lp_max_open_files()));
343 last_warned = time((time_t *) NULL);
349 DEBUG(10,("fd_open: name %s, flags = 0%o mode = 0%o, fd = %d. %s\n",
350 smb_fname_str_dbg(smb_fname), flags, (int)mode, fsp->fh->fd,
351 (fsp->fh->fd == -1) ? strerror(errno) : "" ));
353 return status;
356 /****************************************************************************
357 Close the file associated with a fsp.
358 ****************************************************************************/
360 NTSTATUS fd_close(files_struct *fsp)
362 int ret;
364 if (fsp->dptr) {
365 dptr_CloseDir(fsp);
367 if (fsp->fh->fd == -1) {
368 return NT_STATUS_OK; /* What we used to call a stat open. */
370 if (fsp->fh->ref_count > 1) {
371 return NT_STATUS_OK; /* Shared handle. Only close last reference. */
374 ret = SMB_VFS_CLOSE(fsp);
375 fsp->fh->fd = -1;
376 if (ret == -1) {
377 return map_nt_error_from_unix(errno);
379 return NT_STATUS_OK;
382 /****************************************************************************
383 Change the ownership of a file to that of the parent directory.
384 Do this by fd if possible.
385 ****************************************************************************/
387 void change_file_owner_to_parent(connection_struct *conn,
388 const char *inherit_from_dir,
389 files_struct *fsp)
391 struct smb_filename *smb_fname_parent;
392 int ret;
394 smb_fname_parent = synthetic_smb_fname(talloc_tos(), inherit_from_dir,
395 NULL, NULL);
396 if (smb_fname_parent == NULL) {
397 return;
400 ret = SMB_VFS_STAT(conn, smb_fname_parent);
401 if (ret == -1) {
402 DEBUG(0,("change_file_owner_to_parent: failed to stat parent "
403 "directory %s. Error was %s\n",
404 smb_fname_str_dbg(smb_fname_parent),
405 strerror(errno)));
406 TALLOC_FREE(smb_fname_parent);
407 return;
410 if (smb_fname_parent->st.st_ex_uid == fsp->fsp_name->st.st_ex_uid) {
411 /* Already this uid - no need to change. */
412 DEBUG(10,("change_file_owner_to_parent: file %s "
413 "is already owned by uid %d\n",
414 fsp_str_dbg(fsp),
415 (int)fsp->fsp_name->st.st_ex_uid ));
416 TALLOC_FREE(smb_fname_parent);
417 return;
420 become_root();
421 ret = SMB_VFS_FCHOWN(fsp, smb_fname_parent->st.st_ex_uid, (gid_t)-1);
422 unbecome_root();
423 if (ret == -1) {
424 DEBUG(0,("change_file_owner_to_parent: failed to fchown "
425 "file %s to parent directory uid %u. Error "
426 "was %s\n", fsp_str_dbg(fsp),
427 (unsigned int)smb_fname_parent->st.st_ex_uid,
428 strerror(errno) ));
429 } else {
430 DEBUG(10,("change_file_owner_to_parent: changed new file %s to "
431 "parent directory uid %u.\n", fsp_str_dbg(fsp),
432 (unsigned int)smb_fname_parent->st.st_ex_uid));
433 /* Ensure the uid entry is updated. */
434 fsp->fsp_name->st.st_ex_uid = smb_fname_parent->st.st_ex_uid;
437 TALLOC_FREE(smb_fname_parent);
440 NTSTATUS change_dir_owner_to_parent(connection_struct *conn,
441 const char *inherit_from_dir,
442 const char *fname,
443 SMB_STRUCT_STAT *psbuf)
445 struct smb_filename *smb_fname_parent;
446 struct smb_filename *smb_fname_cwd = NULL;
447 char *saved_dir = NULL;
448 TALLOC_CTX *ctx = talloc_tos();
449 NTSTATUS status = NT_STATUS_OK;
450 int ret;
452 smb_fname_parent = synthetic_smb_fname(ctx, inherit_from_dir,
453 NULL, NULL);
454 if (smb_fname_parent == NULL) {
455 return NT_STATUS_NO_MEMORY;
458 ret = SMB_VFS_STAT(conn, smb_fname_parent);
459 if (ret == -1) {
460 status = map_nt_error_from_unix(errno);
461 DEBUG(0,("change_dir_owner_to_parent: failed to stat parent "
462 "directory %s. Error was %s\n",
463 smb_fname_str_dbg(smb_fname_parent),
464 strerror(errno)));
465 goto out;
468 /* We've already done an lstat into psbuf, and we know it's a
469 directory. If we can cd into the directory and the dev/ino
470 are the same then we can safely chown without races as
471 we're locking the directory in place by being in it. This
472 should work on any UNIX (thanks tridge :-). JRA.
475 saved_dir = vfs_GetWd(ctx,conn);
476 if (!saved_dir) {
477 status = map_nt_error_from_unix(errno);
478 DEBUG(0,("change_dir_owner_to_parent: failed to get "
479 "current working directory. Error was %s\n",
480 strerror(errno)));
481 goto out;
484 /* Chdir into the new path. */
485 if (vfs_ChDir(conn, fname) == -1) {
486 status = map_nt_error_from_unix(errno);
487 DEBUG(0,("change_dir_owner_to_parent: failed to change "
488 "current working directory to %s. Error "
489 "was %s\n", fname, strerror(errno) ));
490 goto chdir;
493 smb_fname_cwd = synthetic_smb_fname(ctx, ".", NULL, NULL);
494 if (smb_fname_cwd == NULL) {
495 status = NT_STATUS_NO_MEMORY;
496 goto chdir;
499 ret = SMB_VFS_STAT(conn, smb_fname_cwd);
500 if (ret == -1) {
501 status = map_nt_error_from_unix(errno);
502 DEBUG(0,("change_dir_owner_to_parent: failed to stat "
503 "directory '.' (%s) Error was %s\n",
504 fname, strerror(errno)));
505 goto chdir;
508 /* Ensure we're pointing at the same place. */
509 if (smb_fname_cwd->st.st_ex_dev != psbuf->st_ex_dev ||
510 smb_fname_cwd->st.st_ex_ino != psbuf->st_ex_ino) {
511 DEBUG(0,("change_dir_owner_to_parent: "
512 "device/inode on directory %s changed. "
513 "Refusing to chown !\n", fname ));
514 status = NT_STATUS_ACCESS_DENIED;
515 goto chdir;
518 if (smb_fname_parent->st.st_ex_uid == smb_fname_cwd->st.st_ex_uid) {
519 /* Already this uid - no need to change. */
520 DEBUG(10,("change_dir_owner_to_parent: directory %s "
521 "is already owned by uid %d\n",
522 fname,
523 (int)smb_fname_cwd->st.st_ex_uid ));
524 status = NT_STATUS_OK;
525 goto chdir;
528 become_root();
529 ret = SMB_VFS_LCHOWN(conn, ".", smb_fname_parent->st.st_ex_uid,
530 (gid_t)-1);
531 unbecome_root();
532 if (ret == -1) {
533 status = map_nt_error_from_unix(errno);
534 DEBUG(10,("change_dir_owner_to_parent: failed to chown "
535 "directory %s to parent directory uid %u. "
536 "Error was %s\n", fname,
537 (unsigned int)smb_fname_parent->st.st_ex_uid,
538 strerror(errno) ));
539 } else {
540 DEBUG(10,("change_dir_owner_to_parent: changed ownership of new "
541 "directory %s to parent directory uid %u.\n",
542 fname, (unsigned int)smb_fname_parent->st.st_ex_uid ));
543 /* Ensure the uid entry is updated. */
544 psbuf->st_ex_uid = smb_fname_parent->st.st_ex_uid;
547 chdir:
548 vfs_ChDir(conn,saved_dir);
549 out:
550 TALLOC_FREE(smb_fname_parent);
551 TALLOC_FREE(smb_fname_cwd);
552 return status;
555 /****************************************************************************
556 Open a file - returning a guaranteed ATOMIC indication of if the
557 file was created or not.
558 ****************************************************************************/
560 static NTSTATUS fd_open_atomic(struct connection_struct *conn,
561 files_struct *fsp,
562 int flags,
563 mode_t mode,
564 bool *file_created)
566 NTSTATUS status = NT_STATUS_UNSUCCESSFUL;
567 bool file_existed = VALID_STAT(fsp->fsp_name->st);
569 *file_created = false;
571 if (!(flags & O_CREAT)) {
573 * We're not creating the file, just pass through.
575 return fd_open(conn, fsp, flags, mode);
578 if (flags & O_EXCL) {
580 * Fail if already exists, just pass through.
582 status = fd_open(conn, fsp, flags, mode);
585 * Here we've opened with O_CREAT|O_EXCL. If that went
586 * NT_STATUS_OK, we *know* we created this file.
588 *file_created = NT_STATUS_IS_OK(status);
590 return status;
594 * Now it gets tricky. We have O_CREAT, but not O_EXCL.
595 * To know absolutely if we created the file or not,
596 * we can never call O_CREAT without O_EXCL. So if
597 * we think the file existed, try without O_CREAT|O_EXCL.
598 * If we think the file didn't exist, try with
599 * O_CREAT|O_EXCL. Keep bouncing between these two
600 * requests until either the file is created, or
601 * opened. Either way, we keep going until we get
602 * a returnable result (error, or open/create).
605 while(1) {
606 int curr_flags = flags;
608 if (file_existed) {
609 /* Just try open, do not create. */
610 curr_flags &= ~(O_CREAT);
611 status = fd_open(conn, fsp, curr_flags, mode);
612 if (NT_STATUS_EQUAL(status,
613 NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
615 * Someone deleted it in the meantime.
616 * Retry with O_EXCL.
618 file_existed = false;
619 DEBUG(10,("fd_open_atomic: file %s existed. "
620 "Retry.\n",
621 smb_fname_str_dbg(fsp->fsp_name)));
622 continue;
624 } else {
625 /* Try create exclusively, fail if it exists. */
626 curr_flags |= O_EXCL;
627 status = fd_open(conn, fsp, curr_flags, mode);
628 if (NT_STATUS_EQUAL(status,
629 NT_STATUS_OBJECT_NAME_COLLISION)) {
631 * Someone created it in the meantime.
632 * Retry without O_CREAT.
634 file_existed = true;
635 DEBUG(10,("fd_open_atomic: file %s "
636 "did not exist. Retry.\n",
637 smb_fname_str_dbg(fsp->fsp_name)));
638 continue;
640 if (NT_STATUS_IS_OK(status)) {
642 * Here we've opened with O_CREAT|O_EXCL
643 * and got success. We *know* we created
644 * this file.
646 *file_created = true;
649 /* Create is done, or failed. */
650 break;
652 return status;
655 /****************************************************************************
656 Open a file.
657 ****************************************************************************/
659 static NTSTATUS open_file(files_struct *fsp,
660 connection_struct *conn,
661 struct smb_request *req,
662 const char *parent_dir,
663 int flags,
664 mode_t unx_mode,
665 uint32 access_mask, /* client requested access mask. */
666 uint32 open_access_mask, /* what we're actually using in the open. */
667 bool *p_file_created)
669 struct smb_filename *smb_fname = fsp->fsp_name;
670 NTSTATUS status = NT_STATUS_OK;
671 int accmode = (flags & O_ACCMODE);
672 int local_flags = flags;
673 bool file_existed = VALID_STAT(fsp->fsp_name->st);
675 fsp->fh->fd = -1;
676 errno = EPERM;
678 /* Check permissions */
681 * This code was changed after seeing a client open request
682 * containing the open mode of (DENY_WRITE/read-only) with
683 * the 'create if not exist' bit set. The previous code
684 * would fail to open the file read only on a read-only share
685 * as it was checking the flags parameter directly against O_RDONLY,
686 * this was failing as the flags parameter was set to O_RDONLY|O_CREAT.
687 * JRA.
690 if (!CAN_WRITE(conn)) {
691 /* It's a read-only share - fail if we wanted to write. */
692 if(accmode != O_RDONLY || (flags & O_TRUNC) || (flags & O_APPEND)) {
693 DEBUG(3,("Permission denied opening %s\n",
694 smb_fname_str_dbg(smb_fname)));
695 return NT_STATUS_ACCESS_DENIED;
697 if (flags & O_CREAT) {
698 /* We don't want to write - but we must make sure that
699 O_CREAT doesn't create the file if we have write
700 access into the directory.
702 flags &= ~(O_CREAT|O_EXCL);
703 local_flags &= ~(O_CREAT|O_EXCL);
708 * This little piece of insanity is inspired by the
709 * fact that an NT client can open a file for O_RDONLY,
710 * but set the create disposition to FILE_EXISTS_TRUNCATE.
711 * If the client *can* write to the file, then it expects to
712 * truncate the file, even though it is opening for readonly.
713 * Quicken uses this stupid trick in backup file creation...
714 * Thanks *greatly* to "David W. Chapman Jr." <dwcjr@inethouston.net>
715 * for helping track this one down. It didn't bite us in 2.0.x
716 * as we always opened files read-write in that release. JRA.
719 if ((accmode == O_RDONLY) && ((flags & O_TRUNC) == O_TRUNC)) {
720 DEBUG(10,("open_file: truncate requested on read-only open "
721 "for file %s\n", smb_fname_str_dbg(smb_fname)));
722 local_flags = (flags & ~O_ACCMODE)|O_RDWR;
725 if ((open_access_mask & (FILE_READ_DATA|FILE_WRITE_DATA|FILE_APPEND_DATA|FILE_EXECUTE)) ||
726 (!file_existed && (local_flags & O_CREAT)) ||
727 ((local_flags & O_TRUNC) == O_TRUNC) ) {
728 const char *wild;
729 int ret;
731 #if defined(O_NONBLOCK) && defined(S_ISFIFO)
733 * We would block on opening a FIFO with no one else on the
734 * other end. Do what we used to do and add O_NONBLOCK to the
735 * open flags. JRA.
738 if (file_existed && S_ISFIFO(smb_fname->st.st_ex_mode)) {
739 local_flags &= ~O_TRUNC; /* Can't truncate a FIFO. */
740 local_flags |= O_NONBLOCK;
742 #endif
744 /* Don't create files with Microsoft wildcard characters. */
745 if (fsp->base_fsp) {
747 * wildcard characters are allowed in stream names
748 * only test the basefilename
750 wild = fsp->base_fsp->fsp_name->base_name;
751 } else {
752 wild = smb_fname->base_name;
754 if ((local_flags & O_CREAT) && !file_existed &&
755 ms_has_wild(wild)) {
756 return NT_STATUS_OBJECT_NAME_INVALID;
759 /* Can we access this file ? */
760 if (!fsp->base_fsp) {
761 /* Only do this check on non-stream open. */
762 if (file_existed) {
763 status = smbd_check_access_rights(conn,
764 smb_fname,
765 false,
766 access_mask);
767 } else if (local_flags & O_CREAT){
768 status = check_parent_access(conn,
769 smb_fname,
770 SEC_DIR_ADD_FILE);
771 } else {
772 /* File didn't exist and no O_CREAT. */
773 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
775 if (!NT_STATUS_IS_OK(status)) {
776 DEBUG(10,("open_file: "
777 "%s on file "
778 "%s returned %s\n",
779 file_existed ?
780 "smbd_check_access_rights" :
781 "check_parent_access",
782 smb_fname_str_dbg(smb_fname),
783 nt_errstr(status) ));
784 return status;
788 /* Actually do the open */
789 status = fd_open_atomic(conn, fsp, local_flags,
790 unx_mode, p_file_created);
791 if (!NT_STATUS_IS_OK(status)) {
792 DEBUG(3,("Error opening file %s (%s) (local_flags=%d) "
793 "(flags=%d)\n", smb_fname_str_dbg(smb_fname),
794 nt_errstr(status),local_flags,flags));
795 return status;
798 ret = SMB_VFS_FSTAT(fsp, &smb_fname->st);
799 if (ret == -1) {
800 /* If we have an fd, this stat should succeed. */
801 DEBUG(0,("Error doing fstat on open file %s "
802 "(%s)\n",
803 smb_fname_str_dbg(smb_fname),
804 strerror(errno) ));
805 status = map_nt_error_from_unix(errno);
806 fd_close(fsp);
807 return status;
810 if (*p_file_created) {
811 /* We created this file. */
813 bool need_re_stat = false;
814 /* Do all inheritance work after we've
815 done a successful fstat call and filled
816 in the stat struct in fsp->fsp_name. */
818 /* Inherit the ACL if required */
819 if (lp_inherit_perms(SNUM(conn))) {
820 inherit_access_posix_acl(conn, parent_dir,
821 smb_fname->base_name,
822 unx_mode);
823 need_re_stat = true;
826 /* Change the owner if required. */
827 if (lp_inherit_owner(SNUM(conn))) {
828 change_file_owner_to_parent(conn, parent_dir,
829 fsp);
830 need_re_stat = true;
833 if (need_re_stat) {
834 ret = SMB_VFS_FSTAT(fsp, &smb_fname->st);
835 /* If we have an fd, this stat should succeed. */
836 if (ret == -1) {
837 DEBUG(0,("Error doing fstat on open file %s "
838 "(%s)\n",
839 smb_fname_str_dbg(smb_fname),
840 strerror(errno) ));
844 notify_fname(conn, NOTIFY_ACTION_ADDED,
845 FILE_NOTIFY_CHANGE_FILE_NAME,
846 smb_fname->base_name);
848 } else {
849 fsp->fh->fd = -1; /* What we used to call a stat open. */
850 if (!file_existed) {
851 /* File must exist for a stat open. */
852 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
855 status = smbd_check_access_rights(conn,
856 smb_fname,
857 false,
858 access_mask);
860 if (NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND) &&
861 fsp->posix_open &&
862 S_ISLNK(smb_fname->st.st_ex_mode)) {
863 /* This is a POSIX stat open for delete
864 * or rename on a symlink that points
865 * nowhere. Allow. */
866 DEBUG(10,("open_file: allowing POSIX "
867 "open on bad symlink %s\n",
868 smb_fname_str_dbg(smb_fname)));
869 status = NT_STATUS_OK;
872 if (!NT_STATUS_IS_OK(status)) {
873 DEBUG(10,("open_file: "
874 "smbd_check_access_rights on file "
875 "%s returned %s\n",
876 smb_fname_str_dbg(smb_fname),
877 nt_errstr(status) ));
878 return status;
883 * POSIX allows read-only opens of directories. We don't
884 * want to do this (we use a different code path for this)
885 * so catch a directory open and return an EISDIR. JRA.
888 if(S_ISDIR(smb_fname->st.st_ex_mode)) {
889 fd_close(fsp);
890 errno = EISDIR;
891 return NT_STATUS_FILE_IS_A_DIRECTORY;
894 fsp->file_id = vfs_file_id_from_sbuf(conn, &smb_fname->st);
895 fsp->vuid = req ? req->vuid : UID_FIELD_INVALID;
896 fsp->file_pid = req ? req->smbpid : 0;
897 fsp->can_lock = True;
898 fsp->can_read = ((access_mask & FILE_READ_DATA) != 0);
899 fsp->can_write =
900 CAN_WRITE(conn) &&
901 ((access_mask & (FILE_WRITE_DATA | FILE_APPEND_DATA)) != 0);
902 fsp->print_file = NULL;
903 fsp->modified = False;
904 fsp->sent_oplock_break = NO_BREAK_SENT;
905 fsp->is_directory = False;
906 if (conn->aio_write_behind_list &&
907 is_in_path(smb_fname->base_name, conn->aio_write_behind_list,
908 conn->case_sensitive)) {
909 fsp->aio_write_behind = True;
912 fsp->wcp = NULL; /* Write cache pointer. */
914 DEBUG(2,("%s opened file %s read=%s write=%s (numopen=%d)\n",
915 conn->session_info->unix_info->unix_name,
916 smb_fname_str_dbg(smb_fname),
917 BOOLSTR(fsp->can_read), BOOLSTR(fsp->can_write),
918 conn->num_files_open));
920 errno = 0;
921 return NT_STATUS_OK;
924 /****************************************************************************
925 Check if we can open a file with a share mode.
926 Returns True if conflict, False if not.
927 ****************************************************************************/
929 static bool share_conflict(struct share_mode_entry *entry,
930 uint32 access_mask,
931 uint32 share_access)
933 DEBUG(10,("share_conflict: entry->access_mask = 0x%x, "
934 "entry->share_access = 0x%x, "
935 "entry->private_options = 0x%x\n",
936 (unsigned int)entry->access_mask,
937 (unsigned int)entry->share_access,
938 (unsigned int)entry->private_options));
940 if (server_id_is_disconnected(&entry->pid)) {
942 * note: cleanup should have been done by
943 * delay_for_batch_oplocks()
945 return false;
948 DEBUG(10,("share_conflict: access_mask = 0x%x, share_access = 0x%x\n",
949 (unsigned int)access_mask, (unsigned int)share_access));
951 if ((entry->access_mask & (FILE_WRITE_DATA|
952 FILE_APPEND_DATA|
953 FILE_READ_DATA|
954 FILE_EXECUTE|
955 DELETE_ACCESS)) == 0) {
956 DEBUG(10,("share_conflict: No conflict due to "
957 "entry->access_mask = 0x%x\n",
958 (unsigned int)entry->access_mask ));
959 return False;
962 if ((access_mask & (FILE_WRITE_DATA|
963 FILE_APPEND_DATA|
964 FILE_READ_DATA|
965 FILE_EXECUTE|
966 DELETE_ACCESS)) == 0) {
967 DEBUG(10,("share_conflict: No conflict due to "
968 "access_mask = 0x%x\n",
969 (unsigned int)access_mask ));
970 return False;
973 #if 1 /* JRA TEST - Superdebug. */
974 #define CHECK_MASK(num, am, right, sa, share) \
975 DEBUG(10,("share_conflict: [%d] am (0x%x) & right (0x%x) = 0x%x\n", \
976 (unsigned int)(num), (unsigned int)(am), \
977 (unsigned int)(right), (unsigned int)(am)&(right) )); \
978 DEBUG(10,("share_conflict: [%d] sa (0x%x) & share (0x%x) = 0x%x\n", \
979 (unsigned int)(num), (unsigned int)(sa), \
980 (unsigned int)(share), (unsigned int)(sa)&(share) )); \
981 if (((am) & (right)) && !((sa) & (share))) { \
982 DEBUG(10,("share_conflict: check %d conflict am = 0x%x, right = 0x%x, \
983 sa = 0x%x, share = 0x%x\n", (num), (unsigned int)(am), (unsigned int)(right), (unsigned int)(sa), \
984 (unsigned int)(share) )); \
985 return True; \
987 #else
988 #define CHECK_MASK(num, am, right, sa, share) \
989 if (((am) & (right)) && !((sa) & (share))) { \
990 DEBUG(10,("share_conflict: check %d conflict am = 0x%x, right = 0x%x, \
991 sa = 0x%x, share = 0x%x\n", (num), (unsigned int)(am), (unsigned int)(right), (unsigned int)(sa), \
992 (unsigned int)(share) )); \
993 return True; \
995 #endif
997 CHECK_MASK(1, entry->access_mask, FILE_WRITE_DATA | FILE_APPEND_DATA,
998 share_access, FILE_SHARE_WRITE);
999 CHECK_MASK(2, access_mask, FILE_WRITE_DATA | FILE_APPEND_DATA,
1000 entry->share_access, FILE_SHARE_WRITE);
1002 CHECK_MASK(3, entry->access_mask, FILE_READ_DATA | FILE_EXECUTE,
1003 share_access, FILE_SHARE_READ);
1004 CHECK_MASK(4, access_mask, FILE_READ_DATA | FILE_EXECUTE,
1005 entry->share_access, FILE_SHARE_READ);
1007 CHECK_MASK(5, entry->access_mask, DELETE_ACCESS,
1008 share_access, FILE_SHARE_DELETE);
1009 CHECK_MASK(6, access_mask, DELETE_ACCESS,
1010 entry->share_access, FILE_SHARE_DELETE);
1012 DEBUG(10,("share_conflict: No conflict.\n"));
1013 return False;
1016 #if defined(DEVELOPER)
1017 static void validate_my_share_entries(struct smbd_server_connection *sconn,
1018 int num,
1019 struct share_mode_entry *share_entry)
1021 struct server_id self = messaging_server_id(sconn->msg_ctx);
1022 files_struct *fsp;
1024 if (!serverid_equal(&self, &share_entry->pid)) {
1025 return;
1028 if (!is_valid_share_mode_entry(share_entry)) {
1029 return;
1032 fsp = file_find_dif(sconn, share_entry->id,
1033 share_entry->share_file_id);
1034 if (!fsp) {
1035 DEBUG(0,("validate_my_share_entries: PANIC : %s\n",
1036 share_mode_str(talloc_tos(), num, share_entry) ));
1037 smb_panic("validate_my_share_entries: Cannot match a "
1038 "share entry with an open file\n");
1041 if ((share_entry->op_type == NO_OPLOCK) &&
1042 (fsp->oplock_type == FAKE_LEVEL_II_OPLOCK))
1044 /* Someone has already written to it, but I haven't yet
1045 * noticed */
1046 return;
1049 if (((uint16)fsp->oplock_type) != share_entry->op_type) {
1050 goto panic;
1053 return;
1055 panic:
1057 char *str;
1058 DEBUG(0,("validate_my_share_entries: PANIC : %s\n",
1059 share_mode_str(talloc_tos(), num, share_entry) ));
1060 str = talloc_asprintf(talloc_tos(),
1061 "validate_my_share_entries: "
1062 "file %s, oplock_type = 0x%x, op_type = 0x%x\n",
1063 fsp->fsp_name->base_name,
1064 (unsigned int)fsp->oplock_type,
1065 (unsigned int)share_entry->op_type );
1066 smb_panic(str);
1069 #endif
1071 bool is_stat_open(uint32 access_mask)
1073 const uint32_t stat_open_bits =
1074 (SYNCHRONIZE_ACCESS|
1075 FILE_READ_ATTRIBUTES|
1076 FILE_WRITE_ATTRIBUTES);
1078 return (((access_mask & stat_open_bits) != 0) &&
1079 ((access_mask & ~stat_open_bits) == 0));
1082 /****************************************************************************
1083 Deal with share modes
1084 Invarient: Share mode must be locked on entry and exit.
1085 Returns -1 on error, or number of share modes on success (may be zero).
1086 ****************************************************************************/
1088 static NTSTATUS open_mode_check(connection_struct *conn,
1089 struct share_mode_lock *lck,
1090 uint32_t name_hash,
1091 uint32 access_mask,
1092 uint32 share_access,
1093 uint32 create_options,
1094 bool *file_existed)
1096 int i;
1098 if(lck->data->num_share_modes == 0) {
1099 return NT_STATUS_OK;
1102 /* A delete on close prohibits everything */
1104 if (is_delete_on_close_set(lck, name_hash)) {
1106 * Check the delete on close token
1107 * is valid. It could have been left
1108 * after a server crash.
1110 for(i = 0; i < lck->data->num_share_modes; i++) {
1111 if (!share_mode_stale_pid(lck->data, i)) {
1113 *file_existed = true;
1115 return NT_STATUS_DELETE_PENDING;
1118 return NT_STATUS_OK;
1121 if (is_stat_open(access_mask)) {
1122 /* Stat open that doesn't trigger oplock breaks or share mode
1123 * checks... ! JRA. */
1124 return NT_STATUS_OK;
1128 * Check if the share modes will give us access.
1131 #if defined(DEVELOPER)
1132 for(i = 0; i < lck->data->num_share_modes; i++) {
1133 validate_my_share_entries(conn->sconn, i,
1134 &lck->data->share_modes[i]);
1136 #endif
1138 /* Now we check the share modes, after any oplock breaks. */
1139 for(i = 0; i < lck->data->num_share_modes; i++) {
1141 if (!is_valid_share_mode_entry(&lck->data->share_modes[i])) {
1142 continue;
1145 /* someone else has a share lock on it, check to see if we can
1146 * too */
1147 if (share_conflict(&lck->data->share_modes[i],
1148 access_mask, share_access)) {
1150 if (share_mode_stale_pid(lck->data, i)) {
1151 continue;
1154 *file_existed = true;
1156 return NT_STATUS_SHARING_VIOLATION;
1160 if (lck->data->num_share_modes != 0) {
1161 *file_existed = true;
1164 return NT_STATUS_OK;
1168 * Send a break message to the oplock holder and delay the open for
1169 * our client.
1172 static NTSTATUS send_break_message(files_struct *fsp,
1173 struct share_mode_entry *exclusive,
1174 uint64_t mid,
1175 int oplock_request)
1177 NTSTATUS status;
1178 char msg[MSG_SMB_SHARE_MODE_ENTRY_SIZE];
1180 DEBUG(10, ("Sending break request to PID %s\n",
1181 procid_str_static(&exclusive->pid)));
1182 exclusive->op_mid = mid;
1184 /* Create the message. */
1185 share_mode_entry_to_message(msg, exclusive);
1187 /* Add in the FORCE_OPLOCK_BREAK_TO_NONE bit in the message if set. We
1188 don't want this set in the share mode struct pointed to by lck. */
1190 if (oplock_request & FORCE_OPLOCK_BREAK_TO_NONE) {
1191 SSVAL(msg,OP_BREAK_MSG_OP_TYPE_OFFSET,
1192 exclusive->op_type | FORCE_OPLOCK_BREAK_TO_NONE);
1195 status = messaging_send_buf(fsp->conn->sconn->msg_ctx, exclusive->pid,
1196 MSG_SMB_BREAK_REQUEST,
1197 (uint8 *)msg,
1198 MSG_SMB_SHARE_MODE_ENTRY_SIZE);
1199 if (!NT_STATUS_IS_OK(status)) {
1200 DEBUG(3, ("Could not send oplock break message: %s\n",
1201 nt_errstr(status)));
1204 return status;
1208 * Return share_mode_entry pointers for :
1209 * 1). Batch oplock entry.
1210 * 2). Batch or exclusive oplock entry (may be identical to #1).
1211 * bool have_level2_oplock
1212 * bool have_no_oplock.
1213 * Do internal consistency checks on the share mode for a file.
1216 static void find_oplock_types(files_struct *fsp,
1217 int oplock_request,
1218 const struct share_mode_lock *lck,
1219 struct share_mode_entry **pp_batch,
1220 struct share_mode_entry **pp_ex_or_batch,
1221 bool *got_level2,
1222 bool *got_no_oplock)
1224 int i;
1226 *pp_batch = NULL;
1227 *pp_ex_or_batch = NULL;
1228 *got_level2 = false;
1229 *got_no_oplock = false;
1231 /* Ignore stat or internal opens, as is done in
1232 delay_for_batch_oplocks() and
1233 delay_for_exclusive_oplocks().
1235 if ((oplock_request & INTERNAL_OPEN_ONLY) || is_stat_open(fsp->access_mask)) {
1236 return;
1239 for (i=0; i<lck->data->num_share_modes; i++) {
1240 if (!is_valid_share_mode_entry(&lck->data->share_modes[i])) {
1241 continue;
1244 if (lck->data->share_modes[i].op_type == NO_OPLOCK &&
1245 is_stat_open(lck->data->share_modes[i].access_mask)) {
1246 /* We ignore stat opens in the table - they
1247 always have NO_OPLOCK and never get or
1248 cause breaks. JRA. */
1249 continue;
1252 if (BATCH_OPLOCK_TYPE(lck->data->share_modes[i].op_type)) {
1253 /* batch - can only be one. */
1254 if (share_mode_stale_pid(lck->data, i)) {
1255 DEBUG(10, ("Found stale batch oplock\n"));
1256 continue;
1258 if (*pp_ex_or_batch || *pp_batch || *got_level2 || *got_no_oplock) {
1259 smb_panic("Bad batch oplock entry.");
1261 *pp_batch = &lck->data->share_modes[i];
1264 if (EXCLUSIVE_OPLOCK_TYPE(lck->data->share_modes[i].op_type)) {
1265 if (share_mode_stale_pid(lck->data, i)) {
1266 DEBUG(10, ("Found stale duplicate oplock\n"));
1267 continue;
1269 /* Exclusive or batch - can only be one. */
1270 if (*pp_ex_or_batch || *got_level2 || *got_no_oplock) {
1271 smb_panic("Bad exclusive or batch oplock entry.");
1273 *pp_ex_or_batch = &lck->data->share_modes[i];
1276 if (LEVEL_II_OPLOCK_TYPE(lck->data->share_modes[i].op_type)) {
1277 if (*pp_batch || *pp_ex_or_batch) {
1278 if (share_mode_stale_pid(lck->data, i)) {
1279 DEBUG(10, ("Found stale LevelII "
1280 "oplock\n"));
1281 continue;
1283 smb_panic("Bad levelII oplock entry.");
1285 *got_level2 = true;
1288 if (lck->data->share_modes[i].op_type == NO_OPLOCK) {
1289 if (*pp_batch || *pp_ex_or_batch) {
1290 if (share_mode_stale_pid(lck->data, i)) {
1291 DEBUG(10, ("Found stale NO_OPLOCK "
1292 "entry\n"));
1293 continue;
1295 smb_panic("Bad no oplock entry.");
1297 *got_no_oplock = true;
1302 static bool delay_for_batch_oplocks(files_struct *fsp,
1303 uint64_t mid,
1304 int oplock_request,
1305 struct share_mode_entry *batch_entry)
1307 if ((oplock_request & INTERNAL_OPEN_ONLY) || is_stat_open(fsp->access_mask)) {
1308 return false;
1310 if (batch_entry == NULL) {
1311 return false;
1314 if (server_id_is_disconnected(&batch_entry->pid)) {
1316 * TODO: clean up.
1317 * This could be achieved by sending a break message
1318 * to ourselves. Special considerations for files
1319 * with delete_on_close flag set!
1321 * For now we keep it simple and do not
1322 * allow delete on close for durable handles.
1324 return false;
1327 /* Found a batch oplock */
1328 send_break_message(fsp, batch_entry, mid, oplock_request);
1329 return true;
1332 static bool delay_for_exclusive_oplocks(files_struct *fsp,
1333 uint64_t mid,
1334 int oplock_request,
1335 struct share_mode_entry *ex_entry)
1337 if ((oplock_request & INTERNAL_OPEN_ONLY) || is_stat_open(fsp->access_mask)) {
1338 return false;
1340 if (ex_entry == NULL) {
1341 return false;
1344 if (server_id_is_disconnected(&ex_entry->pid)) {
1346 * since only durable handles can get disconnected,
1347 * and we can only get durable handles with batch oplocks,
1348 * this should actually never be reached...
1350 return false;
1353 send_break_message(fsp, ex_entry, mid, oplock_request);
1354 return true;
1357 static bool file_has_brlocks(files_struct *fsp)
1359 struct byte_range_lock *br_lck;
1361 br_lck = brl_get_locks_readonly(fsp);
1362 if (!br_lck)
1363 return false;
1365 return br_lck->num_locks > 0 ? true : false;
1368 static void grant_fsp_oplock_type(files_struct *fsp,
1369 int oplock_request,
1370 bool got_level2_oplock,
1371 bool got_a_none_oplock)
1373 bool allow_level2 = (global_client_caps & CAP_LEVEL_II_OPLOCKS) &&
1374 lp_level2_oplocks(SNUM(fsp->conn));
1376 /* Start by granting what the client asked for,
1377 but ensure no SAMBA_PRIVATE bits can be set. */
1378 fsp->oplock_type = (oplock_request & ~SAMBA_PRIVATE_OPLOCK_MASK);
1380 if (oplock_request & INTERNAL_OPEN_ONLY) {
1381 /* No oplocks on internal open. */
1382 fsp->oplock_type = NO_OPLOCK;
1383 DEBUG(10,("grant_fsp_oplock_type: oplock type 0x%x on file %s\n",
1384 fsp->oplock_type, fsp_str_dbg(fsp)));
1385 return;
1388 if (lp_locking(fsp->conn->params) && file_has_brlocks(fsp)) {
1389 DEBUG(10,("grant_fsp_oplock_type: file %s has byte range locks\n",
1390 fsp_str_dbg(fsp)));
1391 fsp->oplock_type = NO_OPLOCK;
1394 if (is_stat_open(fsp->access_mask)) {
1395 /* Leave the value already set. */
1396 DEBUG(10,("grant_fsp_oplock_type: oplock type 0x%x on file %s\n",
1397 fsp->oplock_type, fsp_str_dbg(fsp)));
1398 return;
1402 * Match what was requested (fsp->oplock_type) with
1403 * what was found in the existing share modes.
1406 if (got_a_none_oplock) {
1407 fsp->oplock_type = NO_OPLOCK;
1408 } else if (got_level2_oplock) {
1409 if (fsp->oplock_type == NO_OPLOCK ||
1410 fsp->oplock_type == FAKE_LEVEL_II_OPLOCK) {
1411 /* Store a level2 oplock, but don't tell the client */
1412 fsp->oplock_type = FAKE_LEVEL_II_OPLOCK;
1413 } else {
1414 fsp->oplock_type = LEVEL_II_OPLOCK;
1416 } else {
1417 /* All share_mode_entries are placeholders or deferred.
1418 * Silently upgrade to fake levelII if the client didn't
1419 * ask for an oplock. */
1420 if (fsp->oplock_type == NO_OPLOCK) {
1421 /* Store a level2 oplock, but don't tell the client */
1422 fsp->oplock_type = FAKE_LEVEL_II_OPLOCK;
1427 * Don't grant level2 to clients that don't want them
1428 * or if we've turned them off.
1430 if (fsp->oplock_type == LEVEL_II_OPLOCK && !allow_level2) {
1431 fsp->oplock_type = FAKE_LEVEL_II_OPLOCK;
1434 DEBUG(10,("grant_fsp_oplock_type: oplock type 0x%x on file %s\n",
1435 fsp->oplock_type, fsp_str_dbg(fsp)));
1438 static bool request_timed_out(struct timeval request_time,
1439 struct timeval timeout)
1441 struct timeval now, end_time;
1442 GetTimeOfDay(&now);
1443 end_time = timeval_sum(&request_time, &timeout);
1444 return (timeval_compare(&end_time, &now) < 0);
1447 struct defer_open_state {
1448 struct smbd_server_connection *sconn;
1449 uint64_t mid;
1452 static void defer_open_done(struct tevent_req *req);
1454 /****************************************************************************
1455 Handle the 1 second delay in returning a SHARING_VIOLATION error.
1456 ****************************************************************************/
1458 static void defer_open(struct share_mode_lock *lck,
1459 struct timeval request_time,
1460 struct timeval timeout,
1461 struct smb_request *req,
1462 struct deferred_open_record *state)
1464 DEBUG(10,("defer_open_sharing_error: time [%u.%06u] adding deferred "
1465 "open entry for mid %llu\n",
1466 (unsigned int)request_time.tv_sec,
1467 (unsigned int)request_time.tv_usec,
1468 (unsigned long long)req->mid));
1470 if (!push_deferred_open_message_smb(req, request_time, timeout,
1471 state->id, (char *)state, sizeof(*state))) {
1472 TALLOC_FREE(lck);
1473 exit_server("push_deferred_open_message_smb failed");
1475 if (lck) {
1476 struct defer_open_state *watch_state;
1477 struct tevent_req *watch_req;
1478 bool ret;
1480 watch_state = talloc(req->sconn, struct defer_open_state);
1481 if (watch_state == NULL) {
1482 exit_server("talloc failed");
1484 watch_state->sconn = req->sconn;
1485 watch_state->mid = req->mid;
1487 DEBUG(10, ("defering mid %llu\n",
1488 (unsigned long long)req->mid));
1490 watch_req = dbwrap_record_watch_send(
1491 watch_state, req->sconn->ev_ctx, lck->data->record,
1492 req->sconn->msg_ctx);
1493 if (watch_req == NULL) {
1494 exit_server("Could not watch share mode record");
1496 tevent_req_set_callback(watch_req, defer_open_done,
1497 watch_state);
1499 ret = tevent_req_set_endtime(
1500 watch_req, req->sconn->ev_ctx,
1501 timeval_sum(&request_time, &timeout));
1502 SMB_ASSERT(ret);
1506 static void defer_open_done(struct tevent_req *req)
1508 struct defer_open_state *state = tevent_req_callback_data(
1509 req, struct defer_open_state);
1510 struct db_record *rec = NULL;
1511 NTSTATUS status;
1512 bool ret;
1514 status = dbwrap_record_watch_recv(req, talloc_tos(), &rec);
1515 TALLOC_FREE(req);
1516 if (!NT_STATUS_IS_OK(status)) {
1517 DEBUG(5, ("dbwrap_record_watch_recv returned %s\n",
1518 nt_errstr(status)));
1520 * Even if it failed, retry anyway. TODO: We need a way to
1521 * tell a re-scheduled open about that error.
1526 * TODO: We need a version of dbwrap_record_watch_recv that does not
1527 * fetch_lock the record.
1529 TALLOC_FREE(rec);
1531 DEBUG(10, ("scheduling mid %llu\n", (unsigned long long)state->mid));
1533 ret = schedule_deferred_open_message_smb(state->sconn, state->mid);
1534 SMB_ASSERT(ret);
1535 TALLOC_FREE(state);
1539 /****************************************************************************
1540 On overwrite open ensure that the attributes match.
1541 ****************************************************************************/
1543 static bool open_match_attributes(connection_struct *conn,
1544 uint32 old_dos_attr,
1545 uint32 new_dos_attr,
1546 mode_t existing_unx_mode,
1547 mode_t new_unx_mode,
1548 mode_t *returned_unx_mode)
1550 uint32 noarch_old_dos_attr, noarch_new_dos_attr;
1552 noarch_old_dos_attr = (old_dos_attr & ~FILE_ATTRIBUTE_ARCHIVE);
1553 noarch_new_dos_attr = (new_dos_attr & ~FILE_ATTRIBUTE_ARCHIVE);
1555 if((noarch_old_dos_attr == 0 && noarch_new_dos_attr != 0) ||
1556 (noarch_old_dos_attr != 0 && ((noarch_old_dos_attr & noarch_new_dos_attr) == noarch_old_dos_attr))) {
1557 *returned_unx_mode = new_unx_mode;
1558 } else {
1559 *returned_unx_mode = (mode_t)0;
1562 DEBUG(10,("open_match_attributes: old_dos_attr = 0x%x, "
1563 "existing_unx_mode = 0%o, new_dos_attr = 0x%x "
1564 "returned_unx_mode = 0%o\n",
1565 (unsigned int)old_dos_attr,
1566 (unsigned int)existing_unx_mode,
1567 (unsigned int)new_dos_attr,
1568 (unsigned int)*returned_unx_mode ));
1570 /* If we're mapping SYSTEM and HIDDEN ensure they match. */
1571 if (lp_map_system(SNUM(conn)) || lp_store_dos_attributes(SNUM(conn))) {
1572 if ((old_dos_attr & FILE_ATTRIBUTE_SYSTEM) &&
1573 !(new_dos_attr & FILE_ATTRIBUTE_SYSTEM)) {
1574 return False;
1577 if (lp_map_hidden(SNUM(conn)) || lp_store_dos_attributes(SNUM(conn))) {
1578 if ((old_dos_attr & FILE_ATTRIBUTE_HIDDEN) &&
1579 !(new_dos_attr & FILE_ATTRIBUTE_HIDDEN)) {
1580 return False;
1583 return True;
1586 /****************************************************************************
1587 Special FCB or DOS processing in the case of a sharing violation.
1588 Try and find a duplicated file handle.
1589 ****************************************************************************/
1591 static NTSTATUS fcb_or_dos_open(struct smb_request *req,
1592 connection_struct *conn,
1593 files_struct *fsp_to_dup_into,
1594 const struct smb_filename *smb_fname,
1595 struct file_id id,
1596 uint16 file_pid,
1597 uint64_t vuid,
1598 uint32 access_mask,
1599 uint32 share_access,
1600 uint32 create_options)
1602 files_struct *fsp;
1604 DEBUG(5,("fcb_or_dos_open: attempting old open semantics for "
1605 "file %s.\n", smb_fname_str_dbg(smb_fname)));
1607 for(fsp = file_find_di_first(conn->sconn, id); fsp;
1608 fsp = file_find_di_next(fsp)) {
1610 DEBUG(10,("fcb_or_dos_open: checking file %s, fd = %d, "
1611 "vuid = %llu, file_pid = %u, private_options = 0x%x "
1612 "access_mask = 0x%x\n", fsp_str_dbg(fsp),
1613 fsp->fh->fd, (unsigned long long)fsp->vuid,
1614 (unsigned int)fsp->file_pid,
1615 (unsigned int)fsp->fh->private_options,
1616 (unsigned int)fsp->access_mask ));
1618 if (fsp != fsp_to_dup_into &&
1619 fsp->fh->fd != -1 &&
1620 fsp->vuid == vuid &&
1621 fsp->file_pid == file_pid &&
1622 (fsp->fh->private_options & (NTCREATEX_OPTIONS_PRIVATE_DENY_DOS |
1623 NTCREATEX_OPTIONS_PRIVATE_DENY_FCB)) &&
1624 (fsp->access_mask & FILE_WRITE_DATA) &&
1625 strequal(fsp->fsp_name->base_name, smb_fname->base_name) &&
1626 strequal(fsp->fsp_name->stream_name,
1627 smb_fname->stream_name)) {
1628 DEBUG(10,("fcb_or_dos_open: file match\n"));
1629 break;
1633 if (!fsp) {
1634 return NT_STATUS_NOT_FOUND;
1637 /* quite an insane set of semantics ... */
1638 if (is_executable(smb_fname->base_name) &&
1639 (fsp->fh->private_options & NTCREATEX_OPTIONS_PRIVATE_DENY_DOS)) {
1640 DEBUG(10,("fcb_or_dos_open: file fail due to is_executable.\n"));
1641 return NT_STATUS_INVALID_PARAMETER;
1644 /* We need to duplicate this fsp. */
1645 return dup_file_fsp(req, fsp, access_mask, share_access,
1646 create_options, fsp_to_dup_into);
1649 static void schedule_defer_open(struct share_mode_lock *lck,
1650 struct timeval request_time,
1651 struct smb_request *req)
1653 struct deferred_open_record state;
1655 /* This is a relative time, added to the absolute
1656 request_time value to get the absolute timeout time.
1657 Note that if this is the second or greater time we enter
1658 this codepath for this particular request mid then
1659 request_time is left as the absolute time of the *first*
1660 time this request mid was processed. This is what allows
1661 the request to eventually time out. */
1663 struct timeval timeout;
1665 /* Normally the smbd we asked should respond within
1666 * OPLOCK_BREAK_TIMEOUT seconds regardless of whether
1667 * the client did, give twice the timeout as a safety
1668 * measure here in case the other smbd is stuck
1669 * somewhere else. */
1671 timeout = timeval_set(OPLOCK_BREAK_TIMEOUT*2, 0);
1673 /* Nothing actually uses state.delayed_for_oplocks
1674 but it's handy to differentiate in debug messages
1675 between a 30 second delay due to oplock break, and
1676 a 1 second delay for share mode conflicts. */
1678 state.delayed_for_oplocks = True;
1679 state.async_open = false;
1680 state.id = lck->data->id;
1682 if (!request_timed_out(request_time, timeout)) {
1683 defer_open(lck, request_time, timeout, req, &state);
1687 /****************************************************************************
1688 Reschedule an open call that went asynchronous.
1689 ****************************************************************************/
1691 static void schedule_async_open(struct timeval request_time,
1692 struct smb_request *req)
1694 struct deferred_open_record state;
1695 struct timeval timeout;
1697 timeout = timeval_set(20, 0);
1699 ZERO_STRUCT(state);
1700 state.delayed_for_oplocks = false;
1701 state.async_open = true;
1703 if (!request_timed_out(request_time, timeout)) {
1704 defer_open(NULL, request_time, timeout, req, &state);
1708 /****************************************************************************
1709 Work out what access_mask to use from what the client sent us.
1710 ****************************************************************************/
1712 static NTSTATUS smbd_calculate_maximum_allowed_access(
1713 connection_struct *conn,
1714 const struct smb_filename *smb_fname,
1715 bool use_privs,
1716 uint32_t *p_access_mask)
1718 struct security_descriptor *sd;
1719 uint32_t access_granted;
1720 NTSTATUS status;
1722 if (!use_privs && (get_current_uid(conn) == (uid_t)0)) {
1723 *p_access_mask |= FILE_GENERIC_ALL;
1724 return NT_STATUS_OK;
1727 status = SMB_VFS_GET_NT_ACL(conn, smb_fname->base_name,
1728 (SECINFO_OWNER |
1729 SECINFO_GROUP |
1730 SECINFO_DACL),
1731 talloc_tos(), &sd);
1733 if (NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
1735 * File did not exist
1737 *p_access_mask = FILE_GENERIC_ALL;
1738 return NT_STATUS_OK;
1740 if (!NT_STATUS_IS_OK(status)) {
1741 DEBUG(10,("Could not get acl on file %s: %s\n",
1742 smb_fname_str_dbg(smb_fname),
1743 nt_errstr(status)));
1744 return NT_STATUS_ACCESS_DENIED;
1748 * If we can access the path to this file, by
1749 * default we have FILE_READ_ATTRIBUTES from the
1750 * containing directory. See the section:
1751 * "Algorithm to Check Access to an Existing File"
1752 * in MS-FSA.pdf.
1754 * se_file_access_check()
1755 * also takes care of owner WRITE_DAC and READ_CONTROL.
1757 status = se_file_access_check(sd,
1758 get_current_nttok(conn),
1759 use_privs,
1760 (*p_access_mask & ~FILE_READ_ATTRIBUTES),
1761 &access_granted);
1763 TALLOC_FREE(sd);
1765 if (!NT_STATUS_IS_OK(status)) {
1766 DEBUG(10, ("Access denied on file %s: "
1767 "when calculating maximum access\n",
1768 smb_fname_str_dbg(smb_fname)));
1769 return NT_STATUS_ACCESS_DENIED;
1771 *p_access_mask = (access_granted | FILE_READ_ATTRIBUTES);
1773 if (!(access_granted & DELETE_ACCESS)) {
1774 if (can_delete_file_in_directory(conn, smb_fname)) {
1775 *p_access_mask |= DELETE_ACCESS;
1779 return NT_STATUS_OK;
1782 NTSTATUS smbd_calculate_access_mask(connection_struct *conn,
1783 const struct smb_filename *smb_fname,
1784 bool use_privs,
1785 uint32_t access_mask,
1786 uint32_t *access_mask_out)
1788 NTSTATUS status;
1789 uint32_t orig_access_mask = access_mask;
1790 uint32_t rejected_share_access;
1793 * Convert GENERIC bits to specific bits.
1796 se_map_generic(&access_mask, &file_generic_mapping);
1798 /* Calculate MAXIMUM_ALLOWED_ACCESS if requested. */
1799 if (access_mask & MAXIMUM_ALLOWED_ACCESS) {
1801 status = smbd_calculate_maximum_allowed_access(
1802 conn, smb_fname, use_privs, &access_mask);
1804 if (!NT_STATUS_IS_OK(status)) {
1805 return status;
1808 access_mask &= conn->share_access;
1811 rejected_share_access = access_mask & ~(conn->share_access);
1813 if (rejected_share_access) {
1814 DEBUG(10, ("smbd_calculate_access_mask: Access denied on "
1815 "file %s: rejected by share access mask[0x%08X] "
1816 "orig[0x%08X] mapped[0x%08X] reject[0x%08X]\n",
1817 smb_fname_str_dbg(smb_fname),
1818 conn->share_access,
1819 orig_access_mask, access_mask,
1820 rejected_share_access));
1821 return NT_STATUS_ACCESS_DENIED;
1824 *access_mask_out = access_mask;
1825 return NT_STATUS_OK;
1828 /****************************************************************************
1829 Remove the deferred open entry under lock.
1830 ****************************************************************************/
1832 /****************************************************************************
1833 Return true if this is a state pointer to an asynchronous create.
1834 ****************************************************************************/
1836 bool is_deferred_open_async(const void *ptr)
1838 const struct deferred_open_record *state = (const struct deferred_open_record *)ptr;
1840 return state->async_open;
1843 static bool clear_ads(uint32_t create_disposition)
1845 bool ret = false;
1847 switch (create_disposition) {
1848 case FILE_SUPERSEDE:
1849 case FILE_OVERWRITE_IF:
1850 case FILE_OVERWRITE:
1851 ret = true;
1852 break;
1853 default:
1854 break;
1856 return ret;
1859 static int disposition_to_open_flags(uint32_t create_disposition)
1861 int ret = 0;
1864 * Currently we're using FILE_SUPERSEDE as the same as
1865 * FILE_OVERWRITE_IF but they really are
1866 * different. FILE_SUPERSEDE deletes an existing file
1867 * (requiring delete access) then recreates it.
1870 switch (create_disposition) {
1871 case FILE_SUPERSEDE:
1872 case FILE_OVERWRITE_IF:
1874 * If file exists replace/overwrite. If file doesn't
1875 * exist create.
1877 ret = O_CREAT|O_TRUNC;
1878 break;
1880 case FILE_OPEN:
1882 * If file exists open. If file doesn't exist error.
1884 ret = 0;
1885 break;
1887 case FILE_OVERWRITE:
1889 * If file exists overwrite. If file doesn't exist
1890 * error.
1892 ret = O_TRUNC;
1893 break;
1895 case FILE_CREATE:
1897 * If file exists error. If file doesn't exist create.
1899 ret = O_CREAT|O_EXCL;
1900 break;
1902 case FILE_OPEN_IF:
1904 * If file exists open. If file doesn't exist create.
1906 ret = O_CREAT;
1907 break;
1909 return ret;
1912 static int calculate_open_access_flags(uint32_t access_mask,
1913 int oplock_request,
1914 uint32_t private_flags)
1916 bool need_write, need_read;
1919 * Note that we ignore the append flag as append does not
1920 * mean the same thing under DOS and Unix.
1923 need_write =
1924 ((access_mask & (FILE_WRITE_DATA | FILE_APPEND_DATA)) ||
1925 (oplock_request & FORCE_OPLOCK_BREAK_TO_NONE));
1927 if (!need_write) {
1928 return O_RDONLY;
1931 /* DENY_DOS opens are always underlying read-write on the
1932 file handle, no matter what the requested access mask
1933 says. */
1935 need_read =
1936 ((private_flags & NTCREATEX_OPTIONS_PRIVATE_DENY_DOS) ||
1937 access_mask & (FILE_READ_ATTRIBUTES|FILE_READ_DATA|
1938 FILE_READ_EA|FILE_EXECUTE));
1940 if (!need_read) {
1941 return O_WRONLY;
1943 return O_RDWR;
1946 /****************************************************************************
1947 Open a file with a share mode. Passed in an already created files_struct *.
1948 ****************************************************************************/
1950 static NTSTATUS open_file_ntcreate(connection_struct *conn,
1951 struct smb_request *req,
1952 uint32 access_mask, /* access bits (FILE_READ_DATA etc.) */
1953 uint32 share_access, /* share constants (FILE_SHARE_READ etc) */
1954 uint32 create_disposition, /* FILE_OPEN_IF etc. */
1955 uint32 create_options, /* options such as delete on close. */
1956 uint32 new_dos_attributes, /* attributes used for new file. */
1957 int oplock_request, /* internal Samba oplock codes. */
1958 /* Information (FILE_EXISTS etc.) */
1959 uint32_t private_flags, /* Samba specific flags. */
1960 int *pinfo,
1961 files_struct *fsp)
1963 struct smb_filename *smb_fname = fsp->fsp_name;
1964 int flags=0;
1965 int flags2=0;
1966 bool file_existed = VALID_STAT(smb_fname->st);
1967 bool def_acl = False;
1968 bool posix_open = False;
1969 bool new_file_created = False;
1970 bool first_open_attempt = true;
1971 NTSTATUS fsp_open = NT_STATUS_ACCESS_DENIED;
1972 mode_t new_unx_mode = (mode_t)0;
1973 mode_t unx_mode = (mode_t)0;
1974 int info;
1975 uint32 existing_dos_attributes = 0;
1976 struct timeval request_time = timeval_zero();
1977 struct share_mode_lock *lck = NULL;
1978 uint32 open_access_mask = access_mask;
1979 NTSTATUS status;
1980 char *parent_dir;
1981 SMB_STRUCT_STAT saved_stat = smb_fname->st;
1982 struct share_mode_entry *batch_entry = NULL;
1983 struct share_mode_entry *exclusive_entry = NULL;
1984 bool got_level2_oplock = false;
1985 bool got_a_none_oplock = false;
1986 struct timespec old_write_time;
1987 struct file_id id;
1989 if (conn->printer) {
1991 * Printers are handled completely differently.
1992 * Most of the passed parameters are ignored.
1995 if (pinfo) {
1996 *pinfo = FILE_WAS_CREATED;
1999 DEBUG(10, ("open_file_ntcreate: printer open fname=%s\n",
2000 smb_fname_str_dbg(smb_fname)));
2002 if (!req) {
2003 DEBUG(0,("open_file_ntcreate: printer open without "
2004 "an SMB request!\n"));
2005 return NT_STATUS_INTERNAL_ERROR;
2008 return print_spool_open(fsp, smb_fname->base_name,
2009 req->vuid);
2012 if (!parent_dirname(talloc_tos(), smb_fname->base_name, &parent_dir,
2013 NULL)) {
2014 return NT_STATUS_NO_MEMORY;
2017 if (new_dos_attributes & FILE_FLAG_POSIX_SEMANTICS) {
2018 posix_open = True;
2019 unx_mode = (mode_t)(new_dos_attributes & ~FILE_FLAG_POSIX_SEMANTICS);
2020 new_dos_attributes = 0;
2021 } else {
2022 /* Windows allows a new file to be created and
2023 silently removes a FILE_ATTRIBUTE_DIRECTORY
2024 sent by the client. Do the same. */
2026 new_dos_attributes &= ~FILE_ATTRIBUTE_DIRECTORY;
2028 /* We add FILE_ATTRIBUTE_ARCHIVE to this as this mode is only used if the file is
2029 * created new. */
2030 unx_mode = unix_mode(conn, new_dos_attributes | FILE_ATTRIBUTE_ARCHIVE,
2031 smb_fname, parent_dir);
2034 DEBUG(10, ("open_file_ntcreate: fname=%s, dos_attrs=0x%x "
2035 "access_mask=0x%x share_access=0x%x "
2036 "create_disposition = 0x%x create_options=0x%x "
2037 "unix mode=0%o oplock_request=%d private_flags = 0x%x\n",
2038 smb_fname_str_dbg(smb_fname), new_dos_attributes,
2039 access_mask, share_access, create_disposition,
2040 create_options, (unsigned int)unx_mode, oplock_request,
2041 (unsigned int)private_flags));
2043 if ((req == NULL) && ((oplock_request & INTERNAL_OPEN_ONLY) == 0)) {
2044 DEBUG(0, ("No smb request but not an internal only open!\n"));
2045 return NT_STATUS_INTERNAL_ERROR;
2049 * Only non-internal opens can be deferred at all
2052 if (req) {
2053 void *ptr;
2054 if (get_deferred_open_message_state(req,
2055 &request_time,
2056 &ptr)) {
2057 /* Remember the absolute time of the original
2058 request with this mid. We'll use it later to
2059 see if this has timed out. */
2061 /* If it was an async create retry, the file
2062 didn't exist. */
2064 if (is_deferred_open_async(ptr)) {
2065 SET_STAT_INVALID(smb_fname->st);
2066 file_existed = false;
2069 /* Ensure we don't reprocess this message. */
2070 remove_deferred_open_message_smb(req->sconn, req->mid);
2072 first_open_attempt = false;
2076 if (!posix_open) {
2077 new_dos_attributes &= SAMBA_ATTRIBUTES_MASK;
2078 if (file_existed) {
2079 existing_dos_attributes = dos_mode(conn, smb_fname);
2083 /* ignore any oplock requests if oplocks are disabled */
2084 if (!lp_oplocks(SNUM(conn)) ||
2085 IS_VETO_OPLOCK_PATH(conn, smb_fname->base_name)) {
2086 /* Mask off everything except the private Samba bits. */
2087 oplock_request &= SAMBA_PRIVATE_OPLOCK_MASK;
2090 /* this is for OS/2 long file names - say we don't support them */
2091 if (!lp_posix_pathnames() && strstr(smb_fname->base_name,".+,;=[].")) {
2092 /* OS/2 Workplace shell fix may be main code stream in a later
2093 * release. */
2094 DEBUG(5,("open_file_ntcreate: OS/2 long filenames are not "
2095 "supported.\n"));
2096 if (use_nt_status()) {
2097 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
2099 return NT_STATUS_DOS(ERRDOS, ERRcannotopen);
2102 switch( create_disposition ) {
2103 case FILE_OPEN:
2104 /* If file exists open. If file doesn't exist error. */
2105 if (!file_existed) {
2106 DEBUG(5,("open_file_ntcreate: FILE_OPEN "
2107 "requested for file %s and file "
2108 "doesn't exist.\n",
2109 smb_fname_str_dbg(smb_fname)));
2110 errno = ENOENT;
2111 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
2113 break;
2115 case FILE_OVERWRITE:
2116 /* If file exists overwrite. If file doesn't exist
2117 * error. */
2118 if (!file_existed) {
2119 DEBUG(5,("open_file_ntcreate: FILE_OVERWRITE "
2120 "requested for file %s and file "
2121 "doesn't exist.\n",
2122 smb_fname_str_dbg(smb_fname) ));
2123 errno = ENOENT;
2124 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
2126 break;
2128 case FILE_CREATE:
2129 /* If file exists error. If file doesn't exist
2130 * create. */
2131 if (file_existed) {
2132 DEBUG(5,("open_file_ntcreate: FILE_CREATE "
2133 "requested for file %s and file "
2134 "already exists.\n",
2135 smb_fname_str_dbg(smb_fname)));
2136 if (S_ISDIR(smb_fname->st.st_ex_mode)) {
2137 errno = EISDIR;
2138 } else {
2139 errno = EEXIST;
2141 return map_nt_error_from_unix(errno);
2143 break;
2145 case FILE_SUPERSEDE:
2146 case FILE_OVERWRITE_IF:
2147 case FILE_OPEN_IF:
2148 break;
2149 default:
2150 return NT_STATUS_INVALID_PARAMETER;
2153 flags2 = disposition_to_open_flags(create_disposition);
2155 /* We only care about matching attributes on file exists and
2156 * overwrite. */
2158 if (!posix_open && file_existed &&
2159 ((create_disposition == FILE_OVERWRITE) ||
2160 (create_disposition == FILE_OVERWRITE_IF))) {
2161 if (!open_match_attributes(conn, existing_dos_attributes,
2162 new_dos_attributes,
2163 smb_fname->st.st_ex_mode,
2164 unx_mode, &new_unx_mode)) {
2165 DEBUG(5,("open_file_ntcreate: attributes missmatch "
2166 "for file %s (%x %x) (0%o, 0%o)\n",
2167 smb_fname_str_dbg(smb_fname),
2168 existing_dos_attributes,
2169 new_dos_attributes,
2170 (unsigned int)smb_fname->st.st_ex_mode,
2171 (unsigned int)unx_mode ));
2172 errno = EACCES;
2173 return NT_STATUS_ACCESS_DENIED;
2177 status = smbd_calculate_access_mask(conn, smb_fname,
2178 false,
2179 access_mask,
2180 &access_mask);
2181 if (!NT_STATUS_IS_OK(status)) {
2182 DEBUG(10, ("open_file_ntcreate: smbd_calculate_access_mask "
2183 "on file %s returned %s\n",
2184 smb_fname_str_dbg(smb_fname), nt_errstr(status)));
2185 return status;
2188 open_access_mask = access_mask;
2190 if ((flags2 & O_TRUNC) || (oplock_request & FORCE_OPLOCK_BREAK_TO_NONE)) {
2191 open_access_mask |= FILE_WRITE_DATA; /* This will cause oplock breaks. */
2194 DEBUG(10, ("open_file_ntcreate: fname=%s, after mapping "
2195 "access_mask=0x%x\n", smb_fname_str_dbg(smb_fname),
2196 access_mask));
2199 * Note that we ignore the append flag as append does not
2200 * mean the same thing under DOS and Unix.
2203 flags = calculate_open_access_flags(access_mask, oplock_request,
2204 private_flags);
2207 * Currently we only look at FILE_WRITE_THROUGH for create options.
2210 #if defined(O_SYNC)
2211 if ((create_options & FILE_WRITE_THROUGH) && lp_strict_sync(SNUM(conn))) {
2212 flags2 |= O_SYNC;
2214 #endif /* O_SYNC */
2216 if (posix_open && (access_mask & FILE_APPEND_DATA)) {
2217 flags2 |= O_APPEND;
2220 if (!posix_open && !CAN_WRITE(conn)) {
2222 * We should really return a permission denied error if either
2223 * O_CREAT or O_TRUNC are set, but for compatibility with
2224 * older versions of Samba we just AND them out.
2226 flags2 &= ~(O_CREAT|O_TRUNC);
2229 if (first_open_attempt && lp_kernel_oplocks(SNUM(conn))) {
2231 * With kernel oplocks the open breaking an oplock
2232 * blocks until the oplock holder has given up the
2233 * oplock or closed the file. We prevent this by first
2234 * trying to open the file with O_NONBLOCK (see "man
2235 * fcntl" on Linux). For the second try, triggered by
2236 * an oplock break response, we do not need this
2237 * anymore.
2239 * This is true under the assumption that only Samba
2240 * requests kernel oplocks. Once someone else like
2241 * NFSv4 starts to use that API, we will have to
2242 * modify this by communicating with the NFSv4 server.
2244 flags2 |= O_NONBLOCK;
2248 * Ensure we can't write on a read-only share or file.
2251 if (flags != O_RDONLY && file_existed &&
2252 (!CAN_WRITE(conn) || IS_DOS_READONLY(existing_dos_attributes))) {
2253 DEBUG(5,("open_file_ntcreate: write access requested for "
2254 "file %s on read only %s\n",
2255 smb_fname_str_dbg(smb_fname),
2256 !CAN_WRITE(conn) ? "share" : "file" ));
2257 errno = EACCES;
2258 return NT_STATUS_ACCESS_DENIED;
2261 fsp->file_id = vfs_file_id_from_sbuf(conn, &smb_fname->st);
2262 fsp->share_access = share_access;
2263 fsp->fh->private_options = private_flags;
2264 fsp->access_mask = open_access_mask; /* We change this to the
2265 * requested access_mask after
2266 * the open is done. */
2267 fsp->posix_open = posix_open;
2269 /* Ensure no SAMBA_PRIVATE bits can be set. */
2270 fsp->oplock_type = (oplock_request & ~SAMBA_PRIVATE_OPLOCK_MASK);
2272 if (timeval_is_zero(&request_time)) {
2273 request_time = fsp->open_time;
2277 * Ensure we pay attention to default ACLs on directories if required.
2280 if ((flags2 & O_CREAT) && lp_inherit_acls(SNUM(conn)) &&
2281 (def_acl = directory_has_default_acl(conn, parent_dir))) {
2282 unx_mode = (0777 & lp_create_mask(SNUM(conn)));
2285 DEBUG(4,("calling open_file with flags=0x%X flags2=0x%X mode=0%o, "
2286 "access_mask = 0x%x, open_access_mask = 0x%x\n",
2287 (unsigned int)flags, (unsigned int)flags2,
2288 (unsigned int)unx_mode, (unsigned int)access_mask,
2289 (unsigned int)open_access_mask));
2291 fsp_open = open_file(fsp, conn, req, parent_dir,
2292 flags|flags2, unx_mode, access_mask,
2293 open_access_mask, &new_file_created);
2295 if (NT_STATUS_EQUAL(fsp_open, NT_STATUS_NETWORK_BUSY)) {
2296 struct deferred_open_record state;
2299 * EWOULDBLOCK/EAGAIN maps to NETWORK_BUSY.
2301 if (file_existed && S_ISFIFO(fsp->fsp_name->st.st_ex_mode)) {
2302 DEBUG(10, ("FIFO busy\n"));
2303 return NT_STATUS_NETWORK_BUSY;
2305 if (req == NULL) {
2306 DEBUG(10, ("Internal open busy\n"));
2307 return NT_STATUS_NETWORK_BUSY;
2311 * From here on we assume this is an oplock break triggered
2314 lck = get_existing_share_mode_lock(talloc_tos(), fsp->file_id);
2315 if (lck == NULL) {
2316 state.delayed_for_oplocks = false;
2317 state.async_open = false;
2318 state.id = fsp->file_id;
2319 defer_open(NULL, request_time, timeval_set(0, 0),
2320 req, &state);
2321 DEBUG(10, ("No share mode lock found after "
2322 "EWOULDBLOCK, retrying sync\n"));
2323 return NT_STATUS_SHARING_VIOLATION;
2326 find_oplock_types(fsp, 0, lck, &batch_entry, &exclusive_entry,
2327 &got_level2_oplock, &got_a_none_oplock);
2329 if (delay_for_batch_oplocks(fsp, req->mid, 0, batch_entry) ||
2330 delay_for_exclusive_oplocks(fsp, req->mid, 0,
2331 exclusive_entry)) {
2332 schedule_defer_open(lck, request_time, req);
2333 TALLOC_FREE(lck);
2334 DEBUG(10, ("Sent oplock break request to kernel "
2335 "oplock holder\n"));
2336 return NT_STATUS_SHARING_VIOLATION;
2340 * No oplock from Samba around. Immediately retry with
2341 * a blocking open.
2343 state.delayed_for_oplocks = false;
2344 state.async_open = false;
2345 state.id = lck->data->id;
2346 defer_open(lck, request_time, timeval_set(0, 0), req, &state);
2347 TALLOC_FREE(lck);
2348 DEBUG(10, ("No Samba oplock around after EWOULDBLOCK. "
2349 "Retrying sync\n"));
2350 return NT_STATUS_SHARING_VIOLATION;
2353 if (!NT_STATUS_IS_OK(fsp_open)) {
2354 if (NT_STATUS_EQUAL(fsp_open, NT_STATUS_RETRY)) {
2355 schedule_async_open(request_time, req);
2357 TALLOC_FREE(lck);
2358 return fsp_open;
2361 if (file_existed && !check_same_dev_ino(&saved_stat, &smb_fname->st)) {
2363 * The file did exist, but some other (local or NFS)
2364 * process either renamed/unlinked and re-created the
2365 * file with different dev/ino after we walked the path,
2366 * but before we did the open. We could retry the
2367 * open but it's a rare enough case it's easier to
2368 * just fail the open to prevent creating any problems
2369 * in the open file db having the wrong dev/ino key.
2371 TALLOC_FREE(lck);
2372 fd_close(fsp);
2373 DEBUG(1,("open_file_ntcreate: file %s - dev/ino mismatch. "
2374 "Old (dev=0x%llu, ino =0x%llu). "
2375 "New (dev=0x%llu, ino=0x%llu). Failing open "
2376 " with NT_STATUS_ACCESS_DENIED.\n",
2377 smb_fname_str_dbg(smb_fname),
2378 (unsigned long long)saved_stat.st_ex_dev,
2379 (unsigned long long)saved_stat.st_ex_ino,
2380 (unsigned long long)smb_fname->st.st_ex_dev,
2381 (unsigned long long)smb_fname->st.st_ex_ino));
2382 return NT_STATUS_ACCESS_DENIED;
2385 old_write_time = smb_fname->st.st_ex_mtime;
2388 * Deal with the race condition where two smbd's detect the
2389 * file doesn't exist and do the create at the same time. One
2390 * of them will win and set a share mode, the other (ie. this
2391 * one) should check if the requested share mode for this
2392 * create is allowed.
2396 * Now the file exists and fsp is successfully opened,
2397 * fsp->dev and fsp->inode are valid and should replace the
2398 * dev=0,inode=0 from a non existent file. Spotted by
2399 * Nadav Danieli <nadavd@exanet.com>. JRA.
2402 id = fsp->file_id;
2404 lck = get_share_mode_lock(talloc_tos(), id,
2405 conn->connectpath,
2406 smb_fname, &old_write_time);
2408 if (lck == NULL) {
2409 DEBUG(0, ("open_file_ntcreate: Could not get share "
2410 "mode lock for %s\n",
2411 smb_fname_str_dbg(smb_fname)));
2412 fd_close(fsp);
2413 return NT_STATUS_SHARING_VIOLATION;
2416 /* Get the types we need to examine. */
2417 find_oplock_types(fsp,
2418 oplock_request,
2419 lck,
2420 &batch_entry,
2421 &exclusive_entry,
2422 &got_level2_oplock,
2423 &got_a_none_oplock);
2425 /* First pass - send break only on batch oplocks. */
2426 if ((req != NULL) &&
2427 delay_for_batch_oplocks(fsp,
2428 req->mid,
2429 oplock_request,
2430 batch_entry)) {
2431 schedule_defer_open(lck, request_time, req);
2432 TALLOC_FREE(lck);
2433 fd_close(fsp);
2434 return NT_STATUS_SHARING_VIOLATION;
2437 status = open_mode_check(conn, lck, fsp->name_hash,
2438 access_mask, share_access,
2439 create_options, &file_existed);
2441 if (NT_STATUS_IS_OK(status)) {
2442 /* We might be going to allow this open. Check oplock
2443 * status again. */
2444 /* Second pass - send break for both batch or
2445 * exclusive oplocks. */
2446 if ((req != NULL) &&
2447 delay_for_exclusive_oplocks(
2448 fsp,
2449 req->mid,
2450 oplock_request,
2451 exclusive_entry)) {
2452 schedule_defer_open(lck, request_time, req);
2453 TALLOC_FREE(lck);
2454 fd_close(fsp);
2455 return NT_STATUS_SHARING_VIOLATION;
2459 if (NT_STATUS_EQUAL(status, NT_STATUS_DELETE_PENDING)) {
2460 /* DELETE_PENDING is not deferred for a second */
2461 TALLOC_FREE(lck);
2462 fd_close(fsp);
2463 return status;
2466 if (!NT_STATUS_IS_OK(status)) {
2467 uint32 can_access_mask;
2468 bool can_access = True;
2470 SMB_ASSERT(NT_STATUS_EQUAL(status, NT_STATUS_SHARING_VIOLATION));
2472 /* Check if this can be done with the deny_dos and fcb
2473 * calls. */
2474 if (private_flags &
2475 (NTCREATEX_OPTIONS_PRIVATE_DENY_DOS|
2476 NTCREATEX_OPTIONS_PRIVATE_DENY_FCB)) {
2477 if (req == NULL) {
2478 DEBUG(0, ("DOS open without an SMB "
2479 "request!\n"));
2480 TALLOC_FREE(lck);
2481 fd_close(fsp);
2482 return NT_STATUS_INTERNAL_ERROR;
2485 /* Use the client requested access mask here,
2486 * not the one we open with. */
2487 status = fcb_or_dos_open(req,
2488 conn,
2489 fsp,
2490 smb_fname,
2492 req->smbpid,
2493 req->vuid,
2494 access_mask,
2495 share_access,
2496 create_options);
2498 if (NT_STATUS_IS_OK(status)) {
2499 TALLOC_FREE(lck);
2500 if (pinfo) {
2501 *pinfo = FILE_WAS_OPENED;
2503 return NT_STATUS_OK;
2508 * This next line is a subtlety we need for
2509 * MS-Access. If a file open will fail due to share
2510 * permissions and also for security (access) reasons,
2511 * we need to return the access failed error, not the
2512 * share error. We can't open the file due to kernel
2513 * oplock deadlock (it's possible we failed above on
2514 * the open_mode_check()) so use a userspace check.
2517 if (flags & O_RDWR) {
2518 can_access_mask = FILE_READ_DATA|FILE_WRITE_DATA;
2519 } else if (flags & O_WRONLY) {
2520 can_access_mask = FILE_WRITE_DATA;
2521 } else {
2522 can_access_mask = FILE_READ_DATA;
2525 if (((can_access_mask & FILE_WRITE_DATA) &&
2526 !CAN_WRITE(conn)) ||
2527 !NT_STATUS_IS_OK(smbd_check_access_rights(conn,
2528 smb_fname,
2529 false,
2530 can_access_mask))) {
2531 can_access = False;
2535 * If we're returning a share violation, ensure we
2536 * cope with the braindead 1 second delay.
2539 if (!(oplock_request & INTERNAL_OPEN_ONLY) &&
2540 lp_defer_sharing_violations()) {
2541 struct timeval timeout;
2542 struct deferred_open_record state;
2543 int timeout_usecs;
2545 /* this is a hack to speed up torture tests
2546 in 'make test' */
2547 timeout_usecs = lp_parm_int(SNUM(conn),
2548 "smbd","sharedelay",
2549 SHARING_VIOLATION_USEC_WAIT);
2551 /* This is a relative time, added to the absolute
2552 request_time value to get the absolute timeout time.
2553 Note that if this is the second or greater time we enter
2554 this codepath for this particular request mid then
2555 request_time is left as the absolute time of the *first*
2556 time this request mid was processed. This is what allows
2557 the request to eventually time out. */
2559 timeout = timeval_set(0, timeout_usecs);
2561 /* Nothing actually uses state.delayed_for_oplocks
2562 but it's handy to differentiate in debug messages
2563 between a 30 second delay due to oplock break, and
2564 a 1 second delay for share mode conflicts. */
2566 state.delayed_for_oplocks = False;
2567 state.async_open = false;
2568 state.id = id;
2570 if ((req != NULL)
2571 && !request_timed_out(request_time,
2572 timeout)) {
2573 defer_open(lck, request_time, timeout,
2574 req, &state);
2578 TALLOC_FREE(lck);
2579 fd_close(fsp);
2580 if (can_access) {
2582 * We have detected a sharing violation here
2583 * so return the correct error code
2585 status = NT_STATUS_SHARING_VIOLATION;
2586 } else {
2587 status = NT_STATUS_ACCESS_DENIED;
2589 return status;
2592 grant_fsp_oplock_type(fsp,
2593 oplock_request,
2594 got_level2_oplock,
2595 got_a_none_oplock);
2598 * We have the share entry *locked*.....
2601 /* Delete streams if create_disposition requires it */
2602 if (!new_file_created && clear_ads(create_disposition) &&
2603 !is_ntfs_stream_smb_fname(smb_fname)) {
2604 status = delete_all_streams(conn, smb_fname->base_name);
2605 if (!NT_STATUS_IS_OK(status)) {
2606 TALLOC_FREE(lck);
2607 fd_close(fsp);
2608 return status;
2612 /* note that we ignore failure for the following. It is
2613 basically a hack for NFS, and NFS will never set one of
2614 these only read them. Nobody but Samba can ever set a deny
2615 mode and we have already checked our more authoritative
2616 locking database for permission to set this deny mode. If
2617 the kernel refuses the operations then the kernel is wrong.
2618 note that GPFS supports it as well - jmcd */
2620 if (fsp->fh->fd != -1 && lp_kernel_share_modes(SNUM(conn))) {
2621 int ret_flock;
2622 ret_flock = SMB_VFS_KERNEL_FLOCK(fsp, share_access, access_mask);
2623 if(ret_flock == -1 ){
2625 TALLOC_FREE(lck);
2626 fd_close(fsp);
2628 return NT_STATUS_SHARING_VIOLATION;
2633 * At this point onwards, we can guarantee that the share entry
2634 * is locked, whether we created the file or not, and that the
2635 * deny mode is compatible with all current opens.
2639 * According to Samba4, SEC_FILE_READ_ATTRIBUTE is always granted,
2640 * but we don't have to store this - just ignore it on access check.
2642 if (conn->sconn->using_smb2) {
2644 * SMB2 doesn't return it (according to Microsoft tests).
2645 * Test Case: TestSuite_ScenarioNo009GrantedAccessTestS0
2646 * File created with access = 0x7 (Read, Write, Delete)
2647 * Query Info on file returns 0x87 (Read, Write, Delete, Read Attributes)
2649 fsp->access_mask = access_mask;
2650 } else {
2651 /* But SMB1 does. */
2652 fsp->access_mask = access_mask | FILE_READ_ATTRIBUTES;
2655 if (file_existed) {
2656 /* stat opens on existing files don't get oplocks. */
2657 if (is_stat_open(open_access_mask)) {
2658 fsp->oplock_type = NO_OPLOCK;
2662 if (new_file_created) {
2663 info = FILE_WAS_CREATED;
2664 } else {
2665 if (flags2 & O_TRUNC) {
2666 info = FILE_WAS_OVERWRITTEN;
2667 } else {
2668 info = FILE_WAS_OPENED;
2672 if (pinfo) {
2673 *pinfo = info;
2677 * Setup the oplock info in both the shared memory and
2678 * file structs.
2681 status = set_file_oplock(fsp, fsp->oplock_type);
2682 if (!NT_STATUS_IS_OK(status)) {
2684 * Could not get the kernel oplock or there are byte-range
2685 * locks on the file.
2687 fsp->oplock_type = NO_OPLOCK;
2690 set_share_mode(lck, fsp, get_current_uid(conn),
2691 req ? req->mid : 0,
2692 fsp->oplock_type);
2694 /* Handle strange delete on close create semantics. */
2695 if (create_options & FILE_DELETE_ON_CLOSE) {
2697 status = can_set_delete_on_close(fsp, new_dos_attributes);
2699 if (!NT_STATUS_IS_OK(status)) {
2700 /* Remember to delete the mode we just added. */
2701 del_share_mode(lck, fsp);
2702 TALLOC_FREE(lck);
2703 fd_close(fsp);
2704 return status;
2706 /* Note that here we set the *inital* delete on close flag,
2707 not the regular one. The magic gets handled in close. */
2708 fsp->initial_delete_on_close = True;
2711 if (info != FILE_WAS_OPENED) {
2712 /* Files should be initially set as archive */
2713 if (lp_map_archive(SNUM(conn)) ||
2714 lp_store_dos_attributes(SNUM(conn))) {
2715 if (!posix_open) {
2716 if (file_set_dosmode(conn, smb_fname,
2717 new_dos_attributes | FILE_ATTRIBUTE_ARCHIVE,
2718 parent_dir, true) == 0) {
2719 unx_mode = smb_fname->st.st_ex_mode;
2725 /* Determine sparse flag. */
2726 if (posix_open) {
2727 /* POSIX opens are sparse by default. */
2728 fsp->is_sparse = true;
2729 } else {
2730 fsp->is_sparse = (file_existed &&
2731 (existing_dos_attributes & FILE_ATTRIBUTE_SPARSE));
2735 * Take care of inherited ACLs on created files - if default ACL not
2736 * selected.
2739 if (!posix_open && new_file_created && !def_acl) {
2741 int saved_errno = errno; /* We might get ENOSYS in the next
2742 * call.. */
2744 if (SMB_VFS_FCHMOD_ACL(fsp, unx_mode) == -1 &&
2745 errno == ENOSYS) {
2746 errno = saved_errno; /* Ignore ENOSYS */
2749 } else if (new_unx_mode) {
2751 int ret = -1;
2753 /* Attributes need changing. File already existed. */
2756 int saved_errno = errno; /* We might get ENOSYS in the
2757 * next call.. */
2758 ret = SMB_VFS_FCHMOD_ACL(fsp, new_unx_mode);
2760 if (ret == -1 && errno == ENOSYS) {
2761 errno = saved_errno; /* Ignore ENOSYS */
2762 } else {
2763 DEBUG(5, ("open_file_ntcreate: reset "
2764 "attributes of file %s to 0%o\n",
2765 smb_fname_str_dbg(smb_fname),
2766 (unsigned int)new_unx_mode));
2767 ret = 0; /* Don't do the fchmod below. */
2771 if ((ret == -1) &&
2772 (SMB_VFS_FCHMOD(fsp, new_unx_mode) == -1))
2773 DEBUG(5, ("open_file_ntcreate: failed to reset "
2774 "attributes of file %s to 0%o\n",
2775 smb_fname_str_dbg(smb_fname),
2776 (unsigned int)new_unx_mode));
2779 TALLOC_FREE(lck);
2781 return NT_STATUS_OK;
2785 /****************************************************************************
2786 Open a file for for write to ensure that we can fchmod it.
2787 ****************************************************************************/
2789 NTSTATUS open_file_fchmod(connection_struct *conn,
2790 struct smb_filename *smb_fname,
2791 files_struct **result)
2793 if (!VALID_STAT(smb_fname->st)) {
2794 return NT_STATUS_INVALID_PARAMETER;
2797 return SMB_VFS_CREATE_FILE(
2798 conn, /* conn */
2799 NULL, /* req */
2800 0, /* root_dir_fid */
2801 smb_fname, /* fname */
2802 FILE_WRITE_DATA, /* access_mask */
2803 (FILE_SHARE_READ | FILE_SHARE_WRITE | /* share_access */
2804 FILE_SHARE_DELETE),
2805 FILE_OPEN, /* create_disposition*/
2806 0, /* create_options */
2807 0, /* file_attributes */
2808 INTERNAL_OPEN_ONLY, /* oplock_request */
2809 0, /* allocation_size */
2810 0, /* private_flags */
2811 NULL, /* sd */
2812 NULL, /* ea_list */
2813 result, /* result */
2814 NULL); /* pinfo */
2817 static NTSTATUS mkdir_internal(connection_struct *conn,
2818 struct smb_filename *smb_dname,
2819 uint32 file_attributes)
2821 mode_t mode;
2822 char *parent_dir = NULL;
2823 NTSTATUS status;
2824 bool posix_open = false;
2825 bool need_re_stat = false;
2826 uint32_t access_mask = SEC_DIR_ADD_SUBDIR;
2828 if (!CAN_WRITE(conn) || (access_mask & ~(conn->share_access))) {
2829 DEBUG(5,("mkdir_internal: failing share access "
2830 "%s\n", lp_servicename(talloc_tos(), SNUM(conn))));
2831 return NT_STATUS_ACCESS_DENIED;
2834 if (!parent_dirname(talloc_tos(), smb_dname->base_name, &parent_dir,
2835 NULL)) {
2836 return NT_STATUS_NO_MEMORY;
2839 if (file_attributes & FILE_FLAG_POSIX_SEMANTICS) {
2840 posix_open = true;
2841 mode = (mode_t)(file_attributes & ~FILE_FLAG_POSIX_SEMANTICS);
2842 } else {
2843 mode = unix_mode(conn, FILE_ATTRIBUTE_DIRECTORY, smb_dname, parent_dir);
2846 status = check_parent_access(conn,
2847 smb_dname,
2848 access_mask);
2849 if(!NT_STATUS_IS_OK(status)) {
2850 DEBUG(5,("mkdir_internal: check_parent_access "
2851 "on directory %s for path %s returned %s\n",
2852 parent_dir,
2853 smb_dname->base_name,
2854 nt_errstr(status) ));
2855 return status;
2858 if (SMB_VFS_MKDIR(conn, smb_dname->base_name, mode) != 0) {
2859 return map_nt_error_from_unix(errno);
2862 /* Ensure we're checking for a symlink here.... */
2863 /* We don't want to get caught by a symlink racer. */
2865 if (SMB_VFS_LSTAT(conn, smb_dname) == -1) {
2866 DEBUG(2, ("Could not stat directory '%s' just created: %s\n",
2867 smb_fname_str_dbg(smb_dname), strerror(errno)));
2868 return map_nt_error_from_unix(errno);
2871 if (!S_ISDIR(smb_dname->st.st_ex_mode)) {
2872 DEBUG(0, ("Directory '%s' just created is not a directory !\n",
2873 smb_fname_str_dbg(smb_dname)));
2874 return NT_STATUS_NOT_A_DIRECTORY;
2877 if (lp_store_dos_attributes(SNUM(conn))) {
2878 if (!posix_open) {
2879 file_set_dosmode(conn, smb_dname,
2880 file_attributes | FILE_ATTRIBUTE_DIRECTORY,
2881 parent_dir, true);
2885 if (lp_inherit_perms(SNUM(conn))) {
2886 inherit_access_posix_acl(conn, parent_dir,
2887 smb_dname->base_name, mode);
2888 need_re_stat = true;
2891 if (!posix_open) {
2893 * Check if high bits should have been set,
2894 * then (if bits are missing): add them.
2895 * Consider bits automagically set by UNIX, i.e. SGID bit from parent
2896 * dir.
2898 if ((mode & ~(S_IRWXU|S_IRWXG|S_IRWXO)) &&
2899 (mode & ~smb_dname->st.st_ex_mode)) {
2900 SMB_VFS_CHMOD(conn, smb_dname->base_name,
2901 (smb_dname->st.st_ex_mode |
2902 (mode & ~smb_dname->st.st_ex_mode)));
2903 need_re_stat = true;
2907 /* Change the owner if required. */
2908 if (lp_inherit_owner(SNUM(conn))) {
2909 change_dir_owner_to_parent(conn, parent_dir,
2910 smb_dname->base_name,
2911 &smb_dname->st);
2912 need_re_stat = true;
2915 if (need_re_stat) {
2916 if (SMB_VFS_LSTAT(conn, smb_dname) == -1) {
2917 DEBUG(2, ("Could not stat directory '%s' just created: %s\n",
2918 smb_fname_str_dbg(smb_dname), strerror(errno)));
2919 return map_nt_error_from_unix(errno);
2923 notify_fname(conn, NOTIFY_ACTION_ADDED, FILE_NOTIFY_CHANGE_DIR_NAME,
2924 smb_dname->base_name);
2926 return NT_STATUS_OK;
2929 /****************************************************************************
2930 Open a directory from an NT SMB call.
2931 ****************************************************************************/
2933 static NTSTATUS open_directory(connection_struct *conn,
2934 struct smb_request *req,
2935 struct smb_filename *smb_dname,
2936 uint32 access_mask,
2937 uint32 share_access,
2938 uint32 create_disposition,
2939 uint32 create_options,
2940 uint32 file_attributes,
2941 int *pinfo,
2942 files_struct **result)
2944 files_struct *fsp = NULL;
2945 bool dir_existed = VALID_STAT(smb_dname->st) ? True : False;
2946 struct share_mode_lock *lck = NULL;
2947 NTSTATUS status;
2948 struct timespec mtimespec;
2949 int info = 0;
2951 if (is_ntfs_stream_smb_fname(smb_dname)) {
2952 DEBUG(2, ("open_directory: %s is a stream name!\n",
2953 smb_fname_str_dbg(smb_dname)));
2954 return NT_STATUS_NOT_A_DIRECTORY;
2957 if (!(file_attributes & FILE_FLAG_POSIX_SEMANTICS)) {
2958 /* Ensure we have a directory attribute. */
2959 file_attributes |= FILE_ATTRIBUTE_DIRECTORY;
2962 DEBUG(5,("open_directory: opening directory %s, access_mask = 0x%x, "
2963 "share_access = 0x%x create_options = 0x%x, "
2964 "create_disposition = 0x%x, file_attributes = 0x%x\n",
2965 smb_fname_str_dbg(smb_dname),
2966 (unsigned int)access_mask,
2967 (unsigned int)share_access,
2968 (unsigned int)create_options,
2969 (unsigned int)create_disposition,
2970 (unsigned int)file_attributes));
2972 status = smbd_calculate_access_mask(conn, smb_dname, false,
2973 access_mask, &access_mask);
2974 if (!NT_STATUS_IS_OK(status)) {
2975 DEBUG(10, ("open_directory: smbd_calculate_access_mask "
2976 "on file %s returned %s\n",
2977 smb_fname_str_dbg(smb_dname),
2978 nt_errstr(status)));
2979 return status;
2982 if ((access_mask & SEC_FLAG_SYSTEM_SECURITY) &&
2983 !security_token_has_privilege(get_current_nttok(conn),
2984 SEC_PRIV_SECURITY)) {
2985 DEBUG(10, ("open_directory: open on %s "
2986 "failed - SEC_FLAG_SYSTEM_SECURITY denied.\n",
2987 smb_fname_str_dbg(smb_dname)));
2988 return NT_STATUS_PRIVILEGE_NOT_HELD;
2991 switch( create_disposition ) {
2992 case FILE_OPEN:
2994 if (!dir_existed) {
2995 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
2998 info = FILE_WAS_OPENED;
2999 break;
3001 case FILE_CREATE:
3003 /* If directory exists error. If directory doesn't
3004 * exist create. */
3006 if (dir_existed) {
3007 status = NT_STATUS_OBJECT_NAME_COLLISION;
3008 DEBUG(2, ("open_directory: unable to create "
3009 "%s. Error was %s\n",
3010 smb_fname_str_dbg(smb_dname),
3011 nt_errstr(status)));
3012 return status;
3015 status = mkdir_internal(conn, smb_dname,
3016 file_attributes);
3018 if (!NT_STATUS_IS_OK(status)) {
3019 DEBUG(2, ("open_directory: unable to create "
3020 "%s. Error was %s\n",
3021 smb_fname_str_dbg(smb_dname),
3022 nt_errstr(status)));
3023 return status;
3026 info = FILE_WAS_CREATED;
3027 break;
3029 case FILE_OPEN_IF:
3031 * If directory exists open. If directory doesn't
3032 * exist create.
3035 if (dir_existed) {
3036 status = NT_STATUS_OK;
3037 info = FILE_WAS_OPENED;
3038 } else {
3039 status = mkdir_internal(conn, smb_dname,
3040 file_attributes);
3042 if (NT_STATUS_IS_OK(status)) {
3043 info = FILE_WAS_CREATED;
3044 } else {
3045 /* Cope with create race. */
3046 if (!NT_STATUS_EQUAL(status,
3047 NT_STATUS_OBJECT_NAME_COLLISION)) {
3048 DEBUG(2, ("open_directory: unable to create "
3049 "%s. Error was %s\n",
3050 smb_fname_str_dbg(smb_dname),
3051 nt_errstr(status)));
3052 return status;
3054 info = FILE_WAS_OPENED;
3058 break;
3060 case FILE_SUPERSEDE:
3061 case FILE_OVERWRITE:
3062 case FILE_OVERWRITE_IF:
3063 default:
3064 DEBUG(5,("open_directory: invalid create_disposition "
3065 "0x%x for directory %s\n",
3066 (unsigned int)create_disposition,
3067 smb_fname_str_dbg(smb_dname)));
3068 return NT_STATUS_INVALID_PARAMETER;
3071 if(!S_ISDIR(smb_dname->st.st_ex_mode)) {
3072 DEBUG(5,("open_directory: %s is not a directory !\n",
3073 smb_fname_str_dbg(smb_dname)));
3074 return NT_STATUS_NOT_A_DIRECTORY;
3077 if (info == FILE_WAS_OPENED) {
3078 status = smbd_check_access_rights(conn,
3079 smb_dname,
3080 false,
3081 access_mask);
3082 if (!NT_STATUS_IS_OK(status)) {
3083 DEBUG(10, ("open_directory: smbd_check_access_rights on "
3084 "file %s failed with %s\n",
3085 smb_fname_str_dbg(smb_dname),
3086 nt_errstr(status)));
3087 return status;
3091 status = file_new(req, conn, &fsp);
3092 if(!NT_STATUS_IS_OK(status)) {
3093 return status;
3097 * Setup the files_struct for it.
3100 fsp->file_id = vfs_file_id_from_sbuf(conn, &smb_dname->st);
3101 fsp->vuid = req ? req->vuid : UID_FIELD_INVALID;
3102 fsp->file_pid = req ? req->smbpid : 0;
3103 fsp->can_lock = False;
3104 fsp->can_read = False;
3105 fsp->can_write = False;
3107 fsp->share_access = share_access;
3108 fsp->fh->private_options = 0;
3110 * According to Samba4, SEC_FILE_READ_ATTRIBUTE is always granted,
3112 fsp->access_mask = access_mask | FILE_READ_ATTRIBUTES;
3113 fsp->print_file = NULL;
3114 fsp->modified = False;
3115 fsp->oplock_type = NO_OPLOCK;
3116 fsp->sent_oplock_break = NO_BREAK_SENT;
3117 fsp->is_directory = True;
3118 fsp->posix_open = (file_attributes & FILE_FLAG_POSIX_SEMANTICS) ? True : False;
3119 status = fsp_set_smb_fname(fsp, smb_dname);
3120 if (!NT_STATUS_IS_OK(status)) {
3121 file_free(req, fsp);
3122 return status;
3125 mtimespec = smb_dname->st.st_ex_mtime;
3127 #ifdef O_DIRECTORY
3128 status = fd_open(conn, fsp, O_RDONLY|O_DIRECTORY, 0);
3129 #else
3130 /* POSIX allows us to open a directory with O_RDONLY. */
3131 status = fd_open(conn, fsp, O_RDONLY, 0);
3132 #endif
3133 if (!NT_STATUS_IS_OK(status)) {
3134 DEBUG(5, ("open_directory: Could not open fd for "
3135 "%s (%s)\n",
3136 smb_fname_str_dbg(smb_dname),
3137 nt_errstr(status)));
3138 file_free(req, fsp);
3139 return status;
3142 status = vfs_stat_fsp(fsp);
3143 if (!NT_STATUS_IS_OK(status)) {
3144 fd_close(fsp);
3145 file_free(req, fsp);
3146 return status;
3149 /* Ensure there was no race condition. */
3150 if (!check_same_stat(&smb_dname->st, &fsp->fsp_name->st)) {
3151 DEBUG(5,("open_directory: stat struct differs for "
3152 "directory %s.\n",
3153 smb_fname_str_dbg(smb_dname)));
3154 fd_close(fsp);
3155 file_free(req, fsp);
3156 return NT_STATUS_ACCESS_DENIED;
3159 lck = get_share_mode_lock(talloc_tos(), fsp->file_id,
3160 conn->connectpath, smb_dname,
3161 &mtimespec);
3163 if (lck == NULL) {
3164 DEBUG(0, ("open_directory: Could not get share mode lock for "
3165 "%s\n", smb_fname_str_dbg(smb_dname)));
3166 fd_close(fsp);
3167 file_free(req, fsp);
3168 return NT_STATUS_SHARING_VIOLATION;
3171 status = open_mode_check(conn, lck, fsp->name_hash,
3172 access_mask, share_access,
3173 create_options, &dir_existed);
3175 if (!NT_STATUS_IS_OK(status)) {
3176 TALLOC_FREE(lck);
3177 fd_close(fsp);
3178 file_free(req, fsp);
3179 return status;
3182 set_share_mode(lck, fsp, get_current_uid(conn),
3183 req ? req->mid : 0, NO_OPLOCK);
3185 /* For directories the delete on close bit at open time seems
3186 always to be honored on close... See test 19 in Samba4 BASE-DELETE. */
3187 if (create_options & FILE_DELETE_ON_CLOSE) {
3188 status = can_set_delete_on_close(fsp, 0);
3189 if (!NT_STATUS_IS_OK(status) && !NT_STATUS_EQUAL(status, NT_STATUS_DIRECTORY_NOT_EMPTY)) {
3190 TALLOC_FREE(lck);
3191 fd_close(fsp);
3192 file_free(req, fsp);
3193 return status;
3196 if (NT_STATUS_IS_OK(status)) {
3197 /* Note that here we set the *inital* delete on close flag,
3198 not the regular one. The magic gets handled in close. */
3199 fsp->initial_delete_on_close = True;
3203 TALLOC_FREE(lck);
3205 if (pinfo) {
3206 *pinfo = info;
3209 *result = fsp;
3210 return NT_STATUS_OK;
3213 NTSTATUS create_directory(connection_struct *conn, struct smb_request *req,
3214 struct smb_filename *smb_dname)
3216 NTSTATUS status;
3217 files_struct *fsp;
3219 status = SMB_VFS_CREATE_FILE(
3220 conn, /* conn */
3221 req, /* req */
3222 0, /* root_dir_fid */
3223 smb_dname, /* fname */
3224 FILE_READ_ATTRIBUTES, /* access_mask */
3225 FILE_SHARE_NONE, /* share_access */
3226 FILE_CREATE, /* create_disposition*/
3227 FILE_DIRECTORY_FILE, /* create_options */
3228 FILE_ATTRIBUTE_DIRECTORY, /* file_attributes */
3229 0, /* oplock_request */
3230 0, /* allocation_size */
3231 0, /* private_flags */
3232 NULL, /* sd */
3233 NULL, /* ea_list */
3234 &fsp, /* result */
3235 NULL); /* pinfo */
3237 if (NT_STATUS_IS_OK(status)) {
3238 close_file(req, fsp, NORMAL_CLOSE);
3241 return status;
3244 /****************************************************************************
3245 Receive notification that one of our open files has been renamed by another
3246 smbd process.
3247 ****************************************************************************/
3249 void msg_file_was_renamed(struct messaging_context *msg,
3250 void *private_data,
3251 uint32_t msg_type,
3252 struct server_id server_id,
3253 DATA_BLOB *data)
3255 files_struct *fsp;
3256 char *frm = (char *)data->data;
3257 struct file_id id;
3258 const char *sharepath;
3259 const char *base_name;
3260 const char *stream_name;
3261 struct smb_filename *smb_fname = NULL;
3262 size_t sp_len, bn_len;
3263 NTSTATUS status;
3264 struct smbd_server_connection *sconn =
3265 talloc_get_type_abort(private_data,
3266 struct smbd_server_connection);
3268 if (data->data == NULL
3269 || data->length < MSG_FILE_RENAMED_MIN_SIZE + 2) {
3270 DEBUG(0, ("msg_file_was_renamed: Got invalid msg len %d\n",
3271 (int)data->length));
3272 return;
3275 /* Unpack the message. */
3276 pull_file_id_24(frm, &id);
3277 sharepath = &frm[24];
3278 sp_len = strlen(sharepath);
3279 base_name = sharepath + sp_len + 1;
3280 bn_len = strlen(base_name);
3281 stream_name = sharepath + sp_len + 1 + bn_len + 1;
3283 /* stream_name must always be NULL if there is no stream. */
3284 if (stream_name[0] == '\0') {
3285 stream_name = NULL;
3288 smb_fname = synthetic_smb_fname(talloc_tos(), base_name,
3289 stream_name, NULL);
3290 if (smb_fname == NULL) {
3291 return;
3294 DEBUG(10,("msg_file_was_renamed: Got rename message for sharepath %s, new name %s, "
3295 "file_id %s\n",
3296 sharepath, smb_fname_str_dbg(smb_fname),
3297 file_id_string_tos(&id)));
3299 for(fsp = file_find_di_first(sconn, id); fsp;
3300 fsp = file_find_di_next(fsp)) {
3301 if (memcmp(fsp->conn->connectpath, sharepath, sp_len) == 0) {
3303 DEBUG(10,("msg_file_was_renamed: renaming file %s from %s -> %s\n",
3304 fsp_fnum_dbg(fsp), fsp_str_dbg(fsp),
3305 smb_fname_str_dbg(smb_fname)));
3306 status = fsp_set_smb_fname(fsp, smb_fname);
3307 if (!NT_STATUS_IS_OK(status)) {
3308 goto out;
3310 } else {
3311 /* TODO. JRA. */
3312 /* Now we have the complete path we can work out if this is
3313 actually within this share and adjust newname accordingly. */
3314 DEBUG(10,("msg_file_was_renamed: share mismatch (sharepath %s "
3315 "not sharepath %s) "
3316 "%s from %s -> %s\n",
3317 fsp->conn->connectpath,
3318 sharepath,
3319 fsp_fnum_dbg(fsp),
3320 fsp_str_dbg(fsp),
3321 smb_fname_str_dbg(smb_fname)));
3324 out:
3325 TALLOC_FREE(smb_fname);
3326 return;
3330 * If a main file is opened for delete, all streams need to be checked for
3331 * !FILE_SHARE_DELETE. Do this by opening with DELETE_ACCESS.
3332 * If that works, delete them all by setting the delete on close and close.
3335 NTSTATUS open_streams_for_delete(connection_struct *conn,
3336 const char *fname)
3338 struct stream_struct *stream_info = NULL;
3339 files_struct **streams = NULL;
3340 int i;
3341 unsigned int num_streams = 0;
3342 TALLOC_CTX *frame = talloc_stackframe();
3343 NTSTATUS status;
3345 status = vfs_streaminfo(conn, NULL, fname, talloc_tos(),
3346 &num_streams, &stream_info);
3348 if (NT_STATUS_EQUAL(status, NT_STATUS_NOT_IMPLEMENTED)
3349 || NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
3350 DEBUG(10, ("no streams around\n"));
3351 TALLOC_FREE(frame);
3352 return NT_STATUS_OK;
3355 if (!NT_STATUS_IS_OK(status)) {
3356 DEBUG(10, ("vfs_streaminfo failed: %s\n",
3357 nt_errstr(status)));
3358 goto fail;
3361 DEBUG(10, ("open_streams_for_delete found %d streams\n",
3362 num_streams));
3364 if (num_streams == 0) {
3365 TALLOC_FREE(frame);
3366 return NT_STATUS_OK;
3369 streams = talloc_array(talloc_tos(), files_struct *, num_streams);
3370 if (streams == NULL) {
3371 DEBUG(0, ("talloc failed\n"));
3372 status = NT_STATUS_NO_MEMORY;
3373 goto fail;
3376 for (i=0; i<num_streams; i++) {
3377 struct smb_filename *smb_fname;
3379 if (strequal(stream_info[i].name, "::$DATA")) {
3380 streams[i] = NULL;
3381 continue;
3384 smb_fname = synthetic_smb_fname(
3385 talloc_tos(), fname, stream_info[i].name, NULL);
3386 if (smb_fname == NULL) {
3387 status = NT_STATUS_NO_MEMORY;
3388 goto fail;
3391 if (SMB_VFS_STAT(conn, smb_fname) == -1) {
3392 DEBUG(10, ("Unable to stat stream: %s\n",
3393 smb_fname_str_dbg(smb_fname)));
3396 status = SMB_VFS_CREATE_FILE(
3397 conn, /* conn */
3398 NULL, /* req */
3399 0, /* root_dir_fid */
3400 smb_fname, /* fname */
3401 DELETE_ACCESS, /* access_mask */
3402 (FILE_SHARE_READ | /* share_access */
3403 FILE_SHARE_WRITE | FILE_SHARE_DELETE),
3404 FILE_OPEN, /* create_disposition*/
3405 0, /* create_options */
3406 FILE_ATTRIBUTE_NORMAL, /* file_attributes */
3407 0, /* oplock_request */
3408 0, /* allocation_size */
3409 NTCREATEX_OPTIONS_PRIVATE_STREAM_DELETE, /* private_flags */
3410 NULL, /* sd */
3411 NULL, /* ea_list */
3412 &streams[i], /* result */
3413 NULL); /* pinfo */
3415 if (!NT_STATUS_IS_OK(status)) {
3416 DEBUG(10, ("Could not open stream %s: %s\n",
3417 smb_fname_str_dbg(smb_fname),
3418 nt_errstr(status)));
3420 TALLOC_FREE(smb_fname);
3421 break;
3423 TALLOC_FREE(smb_fname);
3427 * don't touch the variable "status" beyond this point :-)
3430 for (i -= 1 ; i >= 0; i--) {
3431 if (streams[i] == NULL) {
3432 continue;
3435 DEBUG(10, ("Closing stream # %d, %s\n", i,
3436 fsp_str_dbg(streams[i])));
3437 close_file(NULL, streams[i], NORMAL_CLOSE);
3440 fail:
3441 TALLOC_FREE(frame);
3442 return status;
3445 /*********************************************************************
3446 Create a default ACL by inheriting from the parent. If no inheritance
3447 from the parent available, don't set anything. This will leave the actual
3448 permissions the new file or directory already got from the filesystem
3449 as the NT ACL when read.
3450 *********************************************************************/
3452 static NTSTATUS inherit_new_acl(files_struct *fsp)
3454 TALLOC_CTX *frame = talloc_stackframe();
3455 char *parent_name = NULL;
3456 struct security_descriptor *parent_desc = NULL;
3457 NTSTATUS status = NT_STATUS_OK;
3458 struct security_descriptor *psd = NULL;
3459 const struct dom_sid *owner_sid = NULL;
3460 const struct dom_sid *group_sid = NULL;
3461 uint32_t security_info_sent = (SECINFO_OWNER | SECINFO_GROUP | SECINFO_DACL);
3462 struct security_token *token = fsp->conn->session_info->security_token;
3463 bool inherit_owner = lp_inherit_owner(SNUM(fsp->conn));
3464 bool inheritable_components = false;
3465 bool try_builtin_administrators = false;
3466 const struct dom_sid *BA_U_sid = NULL;
3467 const struct dom_sid *BA_G_sid = NULL;
3468 bool try_system = false;
3469 const struct dom_sid *SY_U_sid = NULL;
3470 const struct dom_sid *SY_G_sid = NULL;
3471 size_t size = 0;
3473 if (!parent_dirname(frame, fsp->fsp_name->base_name, &parent_name, NULL)) {
3474 TALLOC_FREE(frame);
3475 return NT_STATUS_NO_MEMORY;
3478 status = SMB_VFS_GET_NT_ACL(fsp->conn,
3479 parent_name,
3480 (SECINFO_OWNER | SECINFO_GROUP | SECINFO_DACL),
3481 frame,
3482 &parent_desc);
3483 if (!NT_STATUS_IS_OK(status)) {
3484 TALLOC_FREE(frame);
3485 return status;
3488 inheritable_components = sd_has_inheritable_components(parent_desc,
3489 fsp->is_directory);
3491 if (!inheritable_components && !inherit_owner) {
3492 TALLOC_FREE(frame);
3493 /* Nothing to inherit and not setting owner. */
3494 return NT_STATUS_OK;
3497 /* Create an inherited descriptor from the parent. */
3499 if (DEBUGLEVEL >= 10) {
3500 DEBUG(10,("inherit_new_acl: parent acl for %s is:\n",
3501 fsp_str_dbg(fsp) ));
3502 NDR_PRINT_DEBUG(security_descriptor, parent_desc);
3505 /* Inherit from parent descriptor if "inherit owner" set. */
3506 if (inherit_owner) {
3507 owner_sid = parent_desc->owner_sid;
3508 group_sid = parent_desc->group_sid;
3511 if (owner_sid == NULL) {
3512 if (security_token_has_builtin_administrators(token)) {
3513 try_builtin_administrators = true;
3514 } else if (security_token_is_system(token)) {
3515 try_builtin_administrators = true;
3516 try_system = true;
3520 if (group_sid == NULL &&
3521 token->num_sids == PRIMARY_GROUP_SID_INDEX)
3523 if (security_token_is_system(token)) {
3524 try_builtin_administrators = true;
3525 try_system = true;
3529 if (try_builtin_administrators) {
3530 struct unixid ids;
3531 bool ok;
3533 ZERO_STRUCT(ids);
3534 ok = sids_to_unixids(&global_sid_Builtin_Administrators, 1, &ids);
3535 if (ok) {
3536 switch (ids.type) {
3537 case ID_TYPE_BOTH:
3538 BA_U_sid = &global_sid_Builtin_Administrators;
3539 BA_G_sid = &global_sid_Builtin_Administrators;
3540 break;
3541 case ID_TYPE_UID:
3542 BA_U_sid = &global_sid_Builtin_Administrators;
3543 break;
3544 case ID_TYPE_GID:
3545 BA_G_sid = &global_sid_Builtin_Administrators;
3546 break;
3547 default:
3548 break;
3553 if (try_system) {
3554 struct unixid ids;
3555 bool ok;
3557 ZERO_STRUCT(ids);
3558 ok = sids_to_unixids(&global_sid_System, 1, &ids);
3559 if (ok) {
3560 switch (ids.type) {
3561 case ID_TYPE_BOTH:
3562 SY_U_sid = &global_sid_System;
3563 SY_G_sid = &global_sid_System;
3564 break;
3565 case ID_TYPE_UID:
3566 SY_U_sid = &global_sid_System;
3567 break;
3568 case ID_TYPE_GID:
3569 SY_G_sid = &global_sid_System;
3570 break;
3571 default:
3572 break;
3577 if (owner_sid == NULL) {
3578 owner_sid = BA_U_sid;
3581 if (owner_sid == NULL) {
3582 owner_sid = SY_U_sid;
3585 if (group_sid == NULL) {
3586 group_sid = SY_G_sid;
3589 if (try_system && group_sid == NULL) {
3590 group_sid = BA_G_sid;
3593 if (owner_sid == NULL) {
3594 owner_sid = &token->sids[PRIMARY_USER_SID_INDEX];
3596 if (group_sid == NULL) {
3597 if (token->num_sids == PRIMARY_GROUP_SID_INDEX) {
3598 group_sid = &token->sids[PRIMARY_USER_SID_INDEX];
3599 } else {
3600 group_sid = &token->sids[PRIMARY_GROUP_SID_INDEX];
3604 status = se_create_child_secdesc(frame,
3605 &psd,
3606 &size,
3607 parent_desc,
3608 owner_sid,
3609 group_sid,
3610 fsp->is_directory);
3611 if (!NT_STATUS_IS_OK(status)) {
3612 TALLOC_FREE(frame);
3613 return status;
3616 /* If inheritable_components == false,
3617 se_create_child_secdesc()
3618 creates a security desriptor with a NULL dacl
3619 entry, but with SEC_DESC_DACL_PRESENT. We need
3620 to remove that flag. */
3622 if (!inheritable_components) {
3623 security_info_sent &= ~SECINFO_DACL;
3624 psd->type &= ~SEC_DESC_DACL_PRESENT;
3627 if (DEBUGLEVEL >= 10) {
3628 DEBUG(10,("inherit_new_acl: child acl for %s is:\n",
3629 fsp_str_dbg(fsp) ));
3630 NDR_PRINT_DEBUG(security_descriptor, psd);
3633 if (inherit_owner) {
3634 /* We need to be root to force this. */
3635 become_root();
3637 status = SMB_VFS_FSET_NT_ACL(fsp,
3638 security_info_sent,
3639 psd);
3640 if (inherit_owner) {
3641 unbecome_root();
3643 TALLOC_FREE(frame);
3644 return status;
3648 * Wrapper around open_file_ntcreate and open_directory
3651 static NTSTATUS create_file_unixpath(connection_struct *conn,
3652 struct smb_request *req,
3653 struct smb_filename *smb_fname,
3654 uint32_t access_mask,
3655 uint32_t share_access,
3656 uint32_t create_disposition,
3657 uint32_t create_options,
3658 uint32_t file_attributes,
3659 uint32_t oplock_request,
3660 uint64_t allocation_size,
3661 uint32_t private_flags,
3662 struct security_descriptor *sd,
3663 struct ea_list *ea_list,
3665 files_struct **result,
3666 int *pinfo)
3668 int info = FILE_WAS_OPENED;
3669 files_struct *base_fsp = NULL;
3670 files_struct *fsp = NULL;
3671 NTSTATUS status;
3673 DEBUG(10,("create_file_unixpath: access_mask = 0x%x "
3674 "file_attributes = 0x%x, share_access = 0x%x, "
3675 "create_disposition = 0x%x create_options = 0x%x "
3676 "oplock_request = 0x%x private_flags = 0x%x "
3677 "ea_list = 0x%p, sd = 0x%p, "
3678 "fname = %s\n",
3679 (unsigned int)access_mask,
3680 (unsigned int)file_attributes,
3681 (unsigned int)share_access,
3682 (unsigned int)create_disposition,
3683 (unsigned int)create_options,
3684 (unsigned int)oplock_request,
3685 (unsigned int)private_flags,
3686 ea_list, sd, smb_fname_str_dbg(smb_fname)));
3688 if (create_options & FILE_OPEN_BY_FILE_ID) {
3689 status = NT_STATUS_NOT_SUPPORTED;
3690 goto fail;
3693 if (create_options & NTCREATEX_OPTIONS_INVALID_PARAM_MASK) {
3694 status = NT_STATUS_INVALID_PARAMETER;
3695 goto fail;
3698 if (req == NULL) {
3699 oplock_request |= INTERNAL_OPEN_ONLY;
3702 if ((conn->fs_capabilities & FILE_NAMED_STREAMS)
3703 && (access_mask & DELETE_ACCESS)
3704 && !is_ntfs_stream_smb_fname(smb_fname)) {
3706 * We can't open a file with DELETE access if any of the
3707 * streams is open without FILE_SHARE_DELETE
3709 status = open_streams_for_delete(conn, smb_fname->base_name);
3711 if (!NT_STATUS_IS_OK(status)) {
3712 goto fail;
3716 if ((access_mask & SEC_FLAG_SYSTEM_SECURITY) &&
3717 !security_token_has_privilege(get_current_nttok(conn),
3718 SEC_PRIV_SECURITY)) {
3719 DEBUG(10, ("create_file_unixpath: open on %s "
3720 "failed - SEC_FLAG_SYSTEM_SECURITY denied.\n",
3721 smb_fname_str_dbg(smb_fname)));
3722 status = NT_STATUS_PRIVILEGE_NOT_HELD;
3723 goto fail;
3726 if ((conn->fs_capabilities & FILE_NAMED_STREAMS)
3727 && is_ntfs_stream_smb_fname(smb_fname)
3728 && (!(private_flags & NTCREATEX_OPTIONS_PRIVATE_STREAM_DELETE))) {
3729 uint32 base_create_disposition;
3730 struct smb_filename *smb_fname_base = NULL;
3732 if (create_options & FILE_DIRECTORY_FILE) {
3733 status = NT_STATUS_NOT_A_DIRECTORY;
3734 goto fail;
3737 switch (create_disposition) {
3738 case FILE_OPEN:
3739 base_create_disposition = FILE_OPEN;
3740 break;
3741 default:
3742 base_create_disposition = FILE_OPEN_IF;
3743 break;
3746 /* Create an smb_filename with stream_name == NULL. */
3747 smb_fname_base = synthetic_smb_fname(talloc_tos(),
3748 smb_fname->base_name,
3749 NULL, NULL);
3750 if (smb_fname_base == NULL) {
3751 status = NT_STATUS_NO_MEMORY;
3752 goto fail;
3755 if (SMB_VFS_STAT(conn, smb_fname_base) == -1) {
3756 DEBUG(10, ("Unable to stat stream: %s\n",
3757 smb_fname_str_dbg(smb_fname_base)));
3760 /* Open the base file. */
3761 status = create_file_unixpath(conn, NULL, smb_fname_base, 0,
3762 FILE_SHARE_READ
3763 | FILE_SHARE_WRITE
3764 | FILE_SHARE_DELETE,
3765 base_create_disposition,
3766 0, 0, 0, 0, 0, NULL, NULL,
3767 &base_fsp, NULL);
3768 TALLOC_FREE(smb_fname_base);
3770 if (!NT_STATUS_IS_OK(status)) {
3771 DEBUG(10, ("create_file_unixpath for base %s failed: "
3772 "%s\n", smb_fname->base_name,
3773 nt_errstr(status)));
3774 goto fail;
3776 /* we don't need to low level fd */
3777 fd_close(base_fsp);
3781 * If it's a request for a directory open, deal with it separately.
3784 if (create_options & FILE_DIRECTORY_FILE) {
3786 if (create_options & FILE_NON_DIRECTORY_FILE) {
3787 status = NT_STATUS_INVALID_PARAMETER;
3788 goto fail;
3791 /* Can't open a temp directory. IFS kit test. */
3792 if (!(file_attributes & FILE_FLAG_POSIX_SEMANTICS) &&
3793 (file_attributes & FILE_ATTRIBUTE_TEMPORARY)) {
3794 status = NT_STATUS_INVALID_PARAMETER;
3795 goto fail;
3799 * We will get a create directory here if the Win32
3800 * app specified a security descriptor in the
3801 * CreateDirectory() call.
3804 oplock_request = 0;
3805 status = open_directory(
3806 conn, req, smb_fname, access_mask, share_access,
3807 create_disposition, create_options, file_attributes,
3808 &info, &fsp);
3809 } else {
3812 * Ordinary file case.
3815 status = file_new(req, conn, &fsp);
3816 if(!NT_STATUS_IS_OK(status)) {
3817 goto fail;
3820 status = fsp_set_smb_fname(fsp, smb_fname);
3821 if (!NT_STATUS_IS_OK(status)) {
3822 goto fail;
3825 if (base_fsp) {
3827 * We're opening the stream element of a
3828 * base_fsp we already opened. Set up the
3829 * base_fsp pointer.
3831 fsp->base_fsp = base_fsp;
3834 if (allocation_size) {
3835 fsp->initial_allocation_size = smb_roundup(fsp->conn,
3836 allocation_size);
3839 status = open_file_ntcreate(conn,
3840 req,
3841 access_mask,
3842 share_access,
3843 create_disposition,
3844 create_options,
3845 file_attributes,
3846 oplock_request,
3847 private_flags,
3848 &info,
3849 fsp);
3851 if(!NT_STATUS_IS_OK(status)) {
3852 file_free(req, fsp);
3853 fsp = NULL;
3856 if (NT_STATUS_EQUAL(status, NT_STATUS_FILE_IS_A_DIRECTORY)) {
3858 /* A stream open never opens a directory */
3860 if (base_fsp) {
3861 status = NT_STATUS_FILE_IS_A_DIRECTORY;
3862 goto fail;
3866 * Fail the open if it was explicitly a non-directory
3867 * file.
3870 if (create_options & FILE_NON_DIRECTORY_FILE) {
3871 status = NT_STATUS_FILE_IS_A_DIRECTORY;
3872 goto fail;
3875 oplock_request = 0;
3876 status = open_directory(
3877 conn, req, smb_fname, access_mask,
3878 share_access, create_disposition,
3879 create_options, file_attributes,
3880 &info, &fsp);
3884 if (!NT_STATUS_IS_OK(status)) {
3885 goto fail;
3888 fsp->base_fsp = base_fsp;
3890 if ((ea_list != NULL) &&
3891 ((info == FILE_WAS_CREATED) || (info == FILE_WAS_OVERWRITTEN))) {
3892 status = set_ea(conn, fsp, fsp->fsp_name, ea_list);
3893 if (!NT_STATUS_IS_OK(status)) {
3894 goto fail;
3898 if (!fsp->is_directory && S_ISDIR(fsp->fsp_name->st.st_ex_mode)) {
3899 status = NT_STATUS_ACCESS_DENIED;
3900 goto fail;
3903 /* Save the requested allocation size. */
3904 if ((info == FILE_WAS_CREATED) || (info == FILE_WAS_OVERWRITTEN)) {
3905 if (allocation_size
3906 && (allocation_size > fsp->fsp_name->st.st_ex_size)) {
3907 fsp->initial_allocation_size = smb_roundup(
3908 fsp->conn, allocation_size);
3909 if (fsp->is_directory) {
3910 /* Can't set allocation size on a directory. */
3911 status = NT_STATUS_ACCESS_DENIED;
3912 goto fail;
3914 if (vfs_allocate_file_space(
3915 fsp, fsp->initial_allocation_size) == -1) {
3916 status = NT_STATUS_DISK_FULL;
3917 goto fail;
3919 } else {
3920 fsp->initial_allocation_size = smb_roundup(
3921 fsp->conn, (uint64_t)fsp->fsp_name->st.st_ex_size);
3923 } else {
3924 fsp->initial_allocation_size = 0;
3927 if ((info == FILE_WAS_CREATED) && lp_nt_acl_support(SNUM(conn)) &&
3928 fsp->base_fsp == NULL) {
3929 if (sd != NULL) {
3931 * According to the MS documentation, the only time the security
3932 * descriptor is applied to the opened file is iff we *created* the
3933 * file; an existing file stays the same.
3935 * Also, it seems (from observation) that you can open the file with
3936 * any access mask but you can still write the sd. We need to override
3937 * the granted access before we call set_sd
3938 * Patch for bug #2242 from Tom Lackemann <cessnatomny@yahoo.com>.
3941 uint32_t sec_info_sent;
3942 uint32_t saved_access_mask = fsp->access_mask;
3944 sec_info_sent = get_sec_info(sd);
3946 fsp->access_mask = FILE_GENERIC_ALL;
3948 if (sec_info_sent & (SECINFO_OWNER|
3949 SECINFO_GROUP|
3950 SECINFO_DACL|
3951 SECINFO_SACL)) {
3952 status = set_sd(fsp, sd, sec_info_sent);
3955 fsp->access_mask = saved_access_mask;
3957 if (!NT_STATUS_IS_OK(status)) {
3958 goto fail;
3960 } else if (lp_inherit_acls(SNUM(conn))) {
3961 /* Inherit from parent. Errors here are not fatal. */
3962 status = inherit_new_acl(fsp);
3963 if (!NT_STATUS_IS_OK(status)) {
3964 DEBUG(10,("inherit_new_acl: failed for %s with %s\n",
3965 fsp_str_dbg(fsp),
3966 nt_errstr(status) ));
3971 DEBUG(10, ("create_file_unixpath: info=%d\n", info));
3973 *result = fsp;
3974 if (pinfo != NULL) {
3975 *pinfo = info;
3978 smb_fname->st = fsp->fsp_name->st;
3980 return NT_STATUS_OK;
3982 fail:
3983 DEBUG(10, ("create_file_unixpath: %s\n", nt_errstr(status)));
3985 if (fsp != NULL) {
3986 if (base_fsp && fsp->base_fsp == base_fsp) {
3988 * The close_file below will close
3989 * fsp->base_fsp.
3991 base_fsp = NULL;
3993 close_file(req, fsp, ERROR_CLOSE);
3994 fsp = NULL;
3996 if (base_fsp != NULL) {
3997 close_file(req, base_fsp, ERROR_CLOSE);
3998 base_fsp = NULL;
4000 return status;
4004 * Calculate the full path name given a relative fid.
4006 NTSTATUS get_relative_fid_filename(connection_struct *conn,
4007 struct smb_request *req,
4008 uint16_t root_dir_fid,
4009 const struct smb_filename *smb_fname,
4010 struct smb_filename **smb_fname_out)
4012 files_struct *dir_fsp;
4013 char *parent_fname = NULL;
4014 char *new_base_name = NULL;
4015 NTSTATUS status;
4017 if (root_dir_fid == 0 || !smb_fname) {
4018 status = NT_STATUS_INTERNAL_ERROR;
4019 goto out;
4022 dir_fsp = file_fsp(req, root_dir_fid);
4024 if (dir_fsp == NULL) {
4025 status = NT_STATUS_INVALID_HANDLE;
4026 goto out;
4029 if (is_ntfs_stream_smb_fname(dir_fsp->fsp_name)) {
4030 status = NT_STATUS_INVALID_HANDLE;
4031 goto out;
4034 if (!dir_fsp->is_directory) {
4037 * Check to see if this is a mac fork of some kind.
4040 if ((conn->fs_capabilities & FILE_NAMED_STREAMS) &&
4041 is_ntfs_stream_smb_fname(smb_fname)) {
4042 status = NT_STATUS_OBJECT_PATH_NOT_FOUND;
4043 goto out;
4047 we need to handle the case when we get a
4048 relative open relative to a file and the
4049 pathname is blank - this is a reopen!
4050 (hint from demyn plantenberg)
4053 status = NT_STATUS_INVALID_HANDLE;
4054 goto out;
4057 if (ISDOT(dir_fsp->fsp_name->base_name)) {
4059 * We're at the toplevel dir, the final file name
4060 * must not contain ./, as this is filtered out
4061 * normally by srvstr_get_path and unix_convert
4062 * explicitly rejects paths containing ./.
4064 parent_fname = talloc_strdup(talloc_tos(), "");
4065 if (parent_fname == NULL) {
4066 status = NT_STATUS_NO_MEMORY;
4067 goto out;
4069 } else {
4070 size_t dir_name_len = strlen(dir_fsp->fsp_name->base_name);
4073 * Copy in the base directory name.
4076 parent_fname = talloc_array(talloc_tos(), char,
4077 dir_name_len+2);
4078 if (parent_fname == NULL) {
4079 status = NT_STATUS_NO_MEMORY;
4080 goto out;
4082 memcpy(parent_fname, dir_fsp->fsp_name->base_name,
4083 dir_name_len+1);
4086 * Ensure it ends in a '/'.
4087 * We used TALLOC_SIZE +2 to add space for the '/'.
4090 if(dir_name_len
4091 && (parent_fname[dir_name_len-1] != '\\')
4092 && (parent_fname[dir_name_len-1] != '/')) {
4093 parent_fname[dir_name_len] = '/';
4094 parent_fname[dir_name_len+1] = '\0';
4098 new_base_name = talloc_asprintf(talloc_tos(), "%s%s", parent_fname,
4099 smb_fname->base_name);
4100 if (new_base_name == NULL) {
4101 status = NT_STATUS_NO_MEMORY;
4102 goto out;
4105 status = filename_convert(req,
4106 conn,
4107 req->flags2 & FLAGS2_DFS_PATHNAMES,
4108 new_base_name,
4110 NULL,
4111 smb_fname_out);
4112 if (!NT_STATUS_IS_OK(status)) {
4113 goto out;
4116 out:
4117 TALLOC_FREE(parent_fname);
4118 TALLOC_FREE(new_base_name);
4119 return status;
4122 NTSTATUS create_file_default(connection_struct *conn,
4123 struct smb_request *req,
4124 uint16_t root_dir_fid,
4125 struct smb_filename *smb_fname,
4126 uint32_t access_mask,
4127 uint32_t share_access,
4128 uint32_t create_disposition,
4129 uint32_t create_options,
4130 uint32_t file_attributes,
4131 uint32_t oplock_request,
4132 uint64_t allocation_size,
4133 uint32_t private_flags,
4134 struct security_descriptor *sd,
4135 struct ea_list *ea_list,
4136 files_struct **result,
4137 int *pinfo)
4139 int info = FILE_WAS_OPENED;
4140 files_struct *fsp = NULL;
4141 NTSTATUS status;
4142 bool stream_name = false;
4144 DEBUG(10,("create_file: access_mask = 0x%x "
4145 "file_attributes = 0x%x, share_access = 0x%x, "
4146 "create_disposition = 0x%x create_options = 0x%x "
4147 "oplock_request = 0x%x "
4148 "private_flags = 0x%x "
4149 "root_dir_fid = 0x%x, ea_list = 0x%p, sd = 0x%p, "
4150 "fname = %s\n",
4151 (unsigned int)access_mask,
4152 (unsigned int)file_attributes,
4153 (unsigned int)share_access,
4154 (unsigned int)create_disposition,
4155 (unsigned int)create_options,
4156 (unsigned int)oplock_request,
4157 (unsigned int)private_flags,
4158 (unsigned int)root_dir_fid,
4159 ea_list, sd, smb_fname_str_dbg(smb_fname)));
4162 * Calculate the filename from the root_dir_if if necessary.
4165 if (root_dir_fid != 0) {
4166 struct smb_filename *smb_fname_out = NULL;
4167 status = get_relative_fid_filename(conn, req, root_dir_fid,
4168 smb_fname, &smb_fname_out);
4169 if (!NT_STATUS_IS_OK(status)) {
4170 goto fail;
4172 smb_fname = smb_fname_out;
4176 * Check to see if this is a mac fork of some kind.
4179 stream_name = is_ntfs_stream_smb_fname(smb_fname);
4180 if (stream_name) {
4181 enum FAKE_FILE_TYPE fake_file_type;
4183 fake_file_type = is_fake_file(smb_fname);
4185 if (fake_file_type != FAKE_FILE_TYPE_NONE) {
4188 * Here we go! support for changing the disk quotas
4189 * --metze
4191 * We need to fake up to open this MAGIC QUOTA file
4192 * and return a valid FID.
4194 * w2k close this file directly after openening xp
4195 * also tries a QUERY_FILE_INFO on the file and then
4196 * close it
4198 status = open_fake_file(req, conn, req->vuid,
4199 fake_file_type, smb_fname,
4200 access_mask, &fsp);
4201 if (!NT_STATUS_IS_OK(status)) {
4202 goto fail;
4205 ZERO_STRUCT(smb_fname->st);
4206 goto done;
4209 if (!(conn->fs_capabilities & FILE_NAMED_STREAMS)) {
4210 status = NT_STATUS_OBJECT_NAME_NOT_FOUND;
4211 goto fail;
4215 if (is_ntfs_default_stream_smb_fname(smb_fname)) {
4216 int ret;
4217 smb_fname->stream_name = NULL;
4218 /* We have to handle this error here. */
4219 if (create_options & FILE_DIRECTORY_FILE) {
4220 status = NT_STATUS_NOT_A_DIRECTORY;
4221 goto fail;
4223 if (lp_posix_pathnames()) {
4224 ret = SMB_VFS_LSTAT(conn, smb_fname);
4225 } else {
4226 ret = SMB_VFS_STAT(conn, smb_fname);
4229 if (ret == 0 && VALID_STAT_OF_DIR(smb_fname->st)) {
4230 status = NT_STATUS_FILE_IS_A_DIRECTORY;
4231 goto fail;
4235 status = create_file_unixpath(
4236 conn, req, smb_fname, access_mask, share_access,
4237 create_disposition, create_options, file_attributes,
4238 oplock_request, allocation_size, private_flags,
4239 sd, ea_list,
4240 &fsp, &info);
4242 if (!NT_STATUS_IS_OK(status)) {
4243 goto fail;
4246 done:
4247 DEBUG(10, ("create_file: info=%d\n", info));
4249 *result = fsp;
4250 if (pinfo != NULL) {
4251 *pinfo = info;
4253 return NT_STATUS_OK;
4255 fail:
4256 DEBUG(10, ("create_file: %s\n", nt_errstr(status)));
4258 if (fsp != NULL) {
4259 close_file(req, fsp, ERROR_CLOSE);
4260 fsp = NULL;
4262 return status;