smbd: Do not fetch the record in defer_open_done
[Samba/bjacke.git] / source3 / smbd / open.c
blob7d02e521081467bb32d5d4c7ca8561e69ac6ae77
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 NTSTATUS status;
1511 bool ret;
1513 status = dbwrap_record_watch_recv(req, talloc_tos(), NULL);
1514 TALLOC_FREE(req);
1515 if (!NT_STATUS_IS_OK(status)) {
1516 DEBUG(5, ("dbwrap_record_watch_recv returned %s\n",
1517 nt_errstr(status)));
1519 * Even if it failed, retry anyway. TODO: We need a way to
1520 * tell a re-scheduled open about that error.
1524 DEBUG(10, ("scheduling mid %llu\n", (unsigned long long)state->mid));
1526 ret = schedule_deferred_open_message_smb(state->sconn, state->mid);
1527 SMB_ASSERT(ret);
1528 TALLOC_FREE(state);
1532 /****************************************************************************
1533 On overwrite open ensure that the attributes match.
1534 ****************************************************************************/
1536 static bool open_match_attributes(connection_struct *conn,
1537 uint32 old_dos_attr,
1538 uint32 new_dos_attr,
1539 mode_t existing_unx_mode,
1540 mode_t new_unx_mode,
1541 mode_t *returned_unx_mode)
1543 uint32 noarch_old_dos_attr, noarch_new_dos_attr;
1545 noarch_old_dos_attr = (old_dos_attr & ~FILE_ATTRIBUTE_ARCHIVE);
1546 noarch_new_dos_attr = (new_dos_attr & ~FILE_ATTRIBUTE_ARCHIVE);
1548 if((noarch_old_dos_attr == 0 && noarch_new_dos_attr != 0) ||
1549 (noarch_old_dos_attr != 0 && ((noarch_old_dos_attr & noarch_new_dos_attr) == noarch_old_dos_attr))) {
1550 *returned_unx_mode = new_unx_mode;
1551 } else {
1552 *returned_unx_mode = (mode_t)0;
1555 DEBUG(10,("open_match_attributes: old_dos_attr = 0x%x, "
1556 "existing_unx_mode = 0%o, new_dos_attr = 0x%x "
1557 "returned_unx_mode = 0%o\n",
1558 (unsigned int)old_dos_attr,
1559 (unsigned int)existing_unx_mode,
1560 (unsigned int)new_dos_attr,
1561 (unsigned int)*returned_unx_mode ));
1563 /* If we're mapping SYSTEM and HIDDEN ensure they match. */
1564 if (lp_map_system(SNUM(conn)) || lp_store_dos_attributes(SNUM(conn))) {
1565 if ((old_dos_attr & FILE_ATTRIBUTE_SYSTEM) &&
1566 !(new_dos_attr & FILE_ATTRIBUTE_SYSTEM)) {
1567 return False;
1570 if (lp_map_hidden(SNUM(conn)) || lp_store_dos_attributes(SNUM(conn))) {
1571 if ((old_dos_attr & FILE_ATTRIBUTE_HIDDEN) &&
1572 !(new_dos_attr & FILE_ATTRIBUTE_HIDDEN)) {
1573 return False;
1576 return True;
1579 /****************************************************************************
1580 Special FCB or DOS processing in the case of a sharing violation.
1581 Try and find a duplicated file handle.
1582 ****************************************************************************/
1584 static NTSTATUS fcb_or_dos_open(struct smb_request *req,
1585 connection_struct *conn,
1586 files_struct *fsp_to_dup_into,
1587 const struct smb_filename *smb_fname,
1588 struct file_id id,
1589 uint16 file_pid,
1590 uint64_t vuid,
1591 uint32 access_mask,
1592 uint32 share_access,
1593 uint32 create_options)
1595 files_struct *fsp;
1597 DEBUG(5,("fcb_or_dos_open: attempting old open semantics for "
1598 "file %s.\n", smb_fname_str_dbg(smb_fname)));
1600 for(fsp = file_find_di_first(conn->sconn, id); fsp;
1601 fsp = file_find_di_next(fsp)) {
1603 DEBUG(10,("fcb_or_dos_open: checking file %s, fd = %d, "
1604 "vuid = %llu, file_pid = %u, private_options = 0x%x "
1605 "access_mask = 0x%x\n", fsp_str_dbg(fsp),
1606 fsp->fh->fd, (unsigned long long)fsp->vuid,
1607 (unsigned int)fsp->file_pid,
1608 (unsigned int)fsp->fh->private_options,
1609 (unsigned int)fsp->access_mask ));
1611 if (fsp != fsp_to_dup_into &&
1612 fsp->fh->fd != -1 &&
1613 fsp->vuid == vuid &&
1614 fsp->file_pid == file_pid &&
1615 (fsp->fh->private_options & (NTCREATEX_OPTIONS_PRIVATE_DENY_DOS |
1616 NTCREATEX_OPTIONS_PRIVATE_DENY_FCB)) &&
1617 (fsp->access_mask & FILE_WRITE_DATA) &&
1618 strequal(fsp->fsp_name->base_name, smb_fname->base_name) &&
1619 strequal(fsp->fsp_name->stream_name,
1620 smb_fname->stream_name)) {
1621 DEBUG(10,("fcb_or_dos_open: file match\n"));
1622 break;
1626 if (!fsp) {
1627 return NT_STATUS_NOT_FOUND;
1630 /* quite an insane set of semantics ... */
1631 if (is_executable(smb_fname->base_name) &&
1632 (fsp->fh->private_options & NTCREATEX_OPTIONS_PRIVATE_DENY_DOS)) {
1633 DEBUG(10,("fcb_or_dos_open: file fail due to is_executable.\n"));
1634 return NT_STATUS_INVALID_PARAMETER;
1637 /* We need to duplicate this fsp. */
1638 return dup_file_fsp(req, fsp, access_mask, share_access,
1639 create_options, fsp_to_dup_into);
1642 static void schedule_defer_open(struct share_mode_lock *lck,
1643 struct timeval request_time,
1644 struct smb_request *req)
1646 struct deferred_open_record state;
1648 /* This is a relative time, added to the absolute
1649 request_time value to get the absolute timeout time.
1650 Note that if this is the second or greater time we enter
1651 this codepath for this particular request mid then
1652 request_time is left as the absolute time of the *first*
1653 time this request mid was processed. This is what allows
1654 the request to eventually time out. */
1656 struct timeval timeout;
1658 /* Normally the smbd we asked should respond within
1659 * OPLOCK_BREAK_TIMEOUT seconds regardless of whether
1660 * the client did, give twice the timeout as a safety
1661 * measure here in case the other smbd is stuck
1662 * somewhere else. */
1664 timeout = timeval_set(OPLOCK_BREAK_TIMEOUT*2, 0);
1666 /* Nothing actually uses state.delayed_for_oplocks
1667 but it's handy to differentiate in debug messages
1668 between a 30 second delay due to oplock break, and
1669 a 1 second delay for share mode conflicts. */
1671 state.delayed_for_oplocks = True;
1672 state.async_open = false;
1673 state.id = lck->data->id;
1675 if (!request_timed_out(request_time, timeout)) {
1676 defer_open(lck, request_time, timeout, req, &state);
1680 /****************************************************************************
1681 Reschedule an open call that went asynchronous.
1682 ****************************************************************************/
1684 static void schedule_async_open(struct timeval request_time,
1685 struct smb_request *req)
1687 struct deferred_open_record state;
1688 struct timeval timeout;
1690 timeout = timeval_set(20, 0);
1692 ZERO_STRUCT(state);
1693 state.delayed_for_oplocks = false;
1694 state.async_open = true;
1696 if (!request_timed_out(request_time, timeout)) {
1697 defer_open(NULL, request_time, timeout, req, &state);
1701 /****************************************************************************
1702 Work out what access_mask to use from what the client sent us.
1703 ****************************************************************************/
1705 static NTSTATUS smbd_calculate_maximum_allowed_access(
1706 connection_struct *conn,
1707 const struct smb_filename *smb_fname,
1708 bool use_privs,
1709 uint32_t *p_access_mask)
1711 struct security_descriptor *sd;
1712 uint32_t access_granted;
1713 NTSTATUS status;
1715 if (!use_privs && (get_current_uid(conn) == (uid_t)0)) {
1716 *p_access_mask |= FILE_GENERIC_ALL;
1717 return NT_STATUS_OK;
1720 status = SMB_VFS_GET_NT_ACL(conn, smb_fname->base_name,
1721 (SECINFO_OWNER |
1722 SECINFO_GROUP |
1723 SECINFO_DACL),
1724 talloc_tos(), &sd);
1726 if (NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
1728 * File did not exist
1730 *p_access_mask = FILE_GENERIC_ALL;
1731 return NT_STATUS_OK;
1733 if (!NT_STATUS_IS_OK(status)) {
1734 DEBUG(10,("Could not get acl on file %s: %s\n",
1735 smb_fname_str_dbg(smb_fname),
1736 nt_errstr(status)));
1737 return NT_STATUS_ACCESS_DENIED;
1741 * If we can access the path to this file, by
1742 * default we have FILE_READ_ATTRIBUTES from the
1743 * containing directory. See the section:
1744 * "Algorithm to Check Access to an Existing File"
1745 * in MS-FSA.pdf.
1747 * se_file_access_check()
1748 * also takes care of owner WRITE_DAC and READ_CONTROL.
1750 status = se_file_access_check(sd,
1751 get_current_nttok(conn),
1752 use_privs,
1753 (*p_access_mask & ~FILE_READ_ATTRIBUTES),
1754 &access_granted);
1756 TALLOC_FREE(sd);
1758 if (!NT_STATUS_IS_OK(status)) {
1759 DEBUG(10, ("Access denied on file %s: "
1760 "when calculating maximum access\n",
1761 smb_fname_str_dbg(smb_fname)));
1762 return NT_STATUS_ACCESS_DENIED;
1764 *p_access_mask = (access_granted | FILE_READ_ATTRIBUTES);
1766 if (!(access_granted & DELETE_ACCESS)) {
1767 if (can_delete_file_in_directory(conn, smb_fname)) {
1768 *p_access_mask |= DELETE_ACCESS;
1772 return NT_STATUS_OK;
1775 NTSTATUS smbd_calculate_access_mask(connection_struct *conn,
1776 const struct smb_filename *smb_fname,
1777 bool use_privs,
1778 uint32_t access_mask,
1779 uint32_t *access_mask_out)
1781 NTSTATUS status;
1782 uint32_t orig_access_mask = access_mask;
1783 uint32_t rejected_share_access;
1786 * Convert GENERIC bits to specific bits.
1789 se_map_generic(&access_mask, &file_generic_mapping);
1791 /* Calculate MAXIMUM_ALLOWED_ACCESS if requested. */
1792 if (access_mask & MAXIMUM_ALLOWED_ACCESS) {
1794 status = smbd_calculate_maximum_allowed_access(
1795 conn, smb_fname, use_privs, &access_mask);
1797 if (!NT_STATUS_IS_OK(status)) {
1798 return status;
1801 access_mask &= conn->share_access;
1804 rejected_share_access = access_mask & ~(conn->share_access);
1806 if (rejected_share_access) {
1807 DEBUG(10, ("smbd_calculate_access_mask: Access denied on "
1808 "file %s: rejected by share access mask[0x%08X] "
1809 "orig[0x%08X] mapped[0x%08X] reject[0x%08X]\n",
1810 smb_fname_str_dbg(smb_fname),
1811 conn->share_access,
1812 orig_access_mask, access_mask,
1813 rejected_share_access));
1814 return NT_STATUS_ACCESS_DENIED;
1817 *access_mask_out = access_mask;
1818 return NT_STATUS_OK;
1821 /****************************************************************************
1822 Remove the deferred open entry under lock.
1823 ****************************************************************************/
1825 /****************************************************************************
1826 Return true if this is a state pointer to an asynchronous create.
1827 ****************************************************************************/
1829 bool is_deferred_open_async(const void *ptr)
1831 const struct deferred_open_record *state = (const struct deferred_open_record *)ptr;
1833 return state->async_open;
1836 static bool clear_ads(uint32_t create_disposition)
1838 bool ret = false;
1840 switch (create_disposition) {
1841 case FILE_SUPERSEDE:
1842 case FILE_OVERWRITE_IF:
1843 case FILE_OVERWRITE:
1844 ret = true;
1845 break;
1846 default:
1847 break;
1849 return ret;
1852 static int disposition_to_open_flags(uint32_t create_disposition)
1854 int ret = 0;
1857 * Currently we're using FILE_SUPERSEDE as the same as
1858 * FILE_OVERWRITE_IF but they really are
1859 * different. FILE_SUPERSEDE deletes an existing file
1860 * (requiring delete access) then recreates it.
1863 switch (create_disposition) {
1864 case FILE_SUPERSEDE:
1865 case FILE_OVERWRITE_IF:
1867 * If file exists replace/overwrite. If file doesn't
1868 * exist create.
1870 ret = O_CREAT|O_TRUNC;
1871 break;
1873 case FILE_OPEN:
1875 * If file exists open. If file doesn't exist error.
1877 ret = 0;
1878 break;
1880 case FILE_OVERWRITE:
1882 * If file exists overwrite. If file doesn't exist
1883 * error.
1885 ret = O_TRUNC;
1886 break;
1888 case FILE_CREATE:
1890 * If file exists error. If file doesn't exist create.
1892 ret = O_CREAT|O_EXCL;
1893 break;
1895 case FILE_OPEN_IF:
1897 * If file exists open. If file doesn't exist create.
1899 ret = O_CREAT;
1900 break;
1902 return ret;
1905 static int calculate_open_access_flags(uint32_t access_mask,
1906 int oplock_request,
1907 uint32_t private_flags)
1909 bool need_write, need_read;
1912 * Note that we ignore the append flag as append does not
1913 * mean the same thing under DOS and Unix.
1916 need_write =
1917 ((access_mask & (FILE_WRITE_DATA | FILE_APPEND_DATA)) ||
1918 (oplock_request & FORCE_OPLOCK_BREAK_TO_NONE));
1920 if (!need_write) {
1921 return O_RDONLY;
1924 /* DENY_DOS opens are always underlying read-write on the
1925 file handle, no matter what the requested access mask
1926 says. */
1928 need_read =
1929 ((private_flags & NTCREATEX_OPTIONS_PRIVATE_DENY_DOS) ||
1930 access_mask & (FILE_READ_ATTRIBUTES|FILE_READ_DATA|
1931 FILE_READ_EA|FILE_EXECUTE));
1933 if (!need_read) {
1934 return O_WRONLY;
1936 return O_RDWR;
1939 /****************************************************************************
1940 Open a file with a share mode. Passed in an already created files_struct *.
1941 ****************************************************************************/
1943 static NTSTATUS open_file_ntcreate(connection_struct *conn,
1944 struct smb_request *req,
1945 uint32 access_mask, /* access bits (FILE_READ_DATA etc.) */
1946 uint32 share_access, /* share constants (FILE_SHARE_READ etc) */
1947 uint32 create_disposition, /* FILE_OPEN_IF etc. */
1948 uint32 create_options, /* options such as delete on close. */
1949 uint32 new_dos_attributes, /* attributes used for new file. */
1950 int oplock_request, /* internal Samba oplock codes. */
1951 /* Information (FILE_EXISTS etc.) */
1952 uint32_t private_flags, /* Samba specific flags. */
1953 int *pinfo,
1954 files_struct *fsp)
1956 struct smb_filename *smb_fname = fsp->fsp_name;
1957 int flags=0;
1958 int flags2=0;
1959 bool file_existed = VALID_STAT(smb_fname->st);
1960 bool def_acl = False;
1961 bool posix_open = False;
1962 bool new_file_created = False;
1963 bool first_open_attempt = true;
1964 NTSTATUS fsp_open = NT_STATUS_ACCESS_DENIED;
1965 mode_t new_unx_mode = (mode_t)0;
1966 mode_t unx_mode = (mode_t)0;
1967 int info;
1968 uint32 existing_dos_attributes = 0;
1969 struct timeval request_time = timeval_zero();
1970 struct share_mode_lock *lck = NULL;
1971 uint32 open_access_mask = access_mask;
1972 NTSTATUS status;
1973 char *parent_dir;
1974 SMB_STRUCT_STAT saved_stat = smb_fname->st;
1975 struct share_mode_entry *batch_entry = NULL;
1976 struct share_mode_entry *exclusive_entry = NULL;
1977 bool got_level2_oplock = false;
1978 bool got_a_none_oplock = false;
1979 struct timespec old_write_time;
1980 struct file_id id;
1982 if (conn->printer) {
1984 * Printers are handled completely differently.
1985 * Most of the passed parameters are ignored.
1988 if (pinfo) {
1989 *pinfo = FILE_WAS_CREATED;
1992 DEBUG(10, ("open_file_ntcreate: printer open fname=%s\n",
1993 smb_fname_str_dbg(smb_fname)));
1995 if (!req) {
1996 DEBUG(0,("open_file_ntcreate: printer open without "
1997 "an SMB request!\n"));
1998 return NT_STATUS_INTERNAL_ERROR;
2001 return print_spool_open(fsp, smb_fname->base_name,
2002 req->vuid);
2005 if (!parent_dirname(talloc_tos(), smb_fname->base_name, &parent_dir,
2006 NULL)) {
2007 return NT_STATUS_NO_MEMORY;
2010 if (new_dos_attributes & FILE_FLAG_POSIX_SEMANTICS) {
2011 posix_open = True;
2012 unx_mode = (mode_t)(new_dos_attributes & ~FILE_FLAG_POSIX_SEMANTICS);
2013 new_dos_attributes = 0;
2014 } else {
2015 /* Windows allows a new file to be created and
2016 silently removes a FILE_ATTRIBUTE_DIRECTORY
2017 sent by the client. Do the same. */
2019 new_dos_attributes &= ~FILE_ATTRIBUTE_DIRECTORY;
2021 /* We add FILE_ATTRIBUTE_ARCHIVE to this as this mode is only used if the file is
2022 * created new. */
2023 unx_mode = unix_mode(conn, new_dos_attributes | FILE_ATTRIBUTE_ARCHIVE,
2024 smb_fname, parent_dir);
2027 DEBUG(10, ("open_file_ntcreate: fname=%s, dos_attrs=0x%x "
2028 "access_mask=0x%x share_access=0x%x "
2029 "create_disposition = 0x%x create_options=0x%x "
2030 "unix mode=0%o oplock_request=%d private_flags = 0x%x\n",
2031 smb_fname_str_dbg(smb_fname), new_dos_attributes,
2032 access_mask, share_access, create_disposition,
2033 create_options, (unsigned int)unx_mode, oplock_request,
2034 (unsigned int)private_flags));
2036 if ((req == NULL) && ((oplock_request & INTERNAL_OPEN_ONLY) == 0)) {
2037 DEBUG(0, ("No smb request but not an internal only open!\n"));
2038 return NT_STATUS_INTERNAL_ERROR;
2042 * Only non-internal opens can be deferred at all
2045 if (req) {
2046 void *ptr;
2047 if (get_deferred_open_message_state(req,
2048 &request_time,
2049 &ptr)) {
2050 /* Remember the absolute time of the original
2051 request with this mid. We'll use it later to
2052 see if this has timed out. */
2054 /* If it was an async create retry, the file
2055 didn't exist. */
2057 if (is_deferred_open_async(ptr)) {
2058 SET_STAT_INVALID(smb_fname->st);
2059 file_existed = false;
2062 /* Ensure we don't reprocess this message. */
2063 remove_deferred_open_message_smb(req->sconn, req->mid);
2065 first_open_attempt = false;
2069 if (!posix_open) {
2070 new_dos_attributes &= SAMBA_ATTRIBUTES_MASK;
2071 if (file_existed) {
2072 existing_dos_attributes = dos_mode(conn, smb_fname);
2076 /* ignore any oplock requests if oplocks are disabled */
2077 if (!lp_oplocks(SNUM(conn)) ||
2078 IS_VETO_OPLOCK_PATH(conn, smb_fname->base_name)) {
2079 /* Mask off everything except the private Samba bits. */
2080 oplock_request &= SAMBA_PRIVATE_OPLOCK_MASK;
2083 /* this is for OS/2 long file names - say we don't support them */
2084 if (!lp_posix_pathnames() && strstr(smb_fname->base_name,".+,;=[].")) {
2085 /* OS/2 Workplace shell fix may be main code stream in a later
2086 * release. */
2087 DEBUG(5,("open_file_ntcreate: OS/2 long filenames are not "
2088 "supported.\n"));
2089 if (use_nt_status()) {
2090 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
2092 return NT_STATUS_DOS(ERRDOS, ERRcannotopen);
2095 switch( create_disposition ) {
2096 case FILE_OPEN:
2097 /* If file exists open. If file doesn't exist error. */
2098 if (!file_existed) {
2099 DEBUG(5,("open_file_ntcreate: FILE_OPEN "
2100 "requested for file %s and file "
2101 "doesn't exist.\n",
2102 smb_fname_str_dbg(smb_fname)));
2103 errno = ENOENT;
2104 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
2106 break;
2108 case FILE_OVERWRITE:
2109 /* If file exists overwrite. If file doesn't exist
2110 * error. */
2111 if (!file_existed) {
2112 DEBUG(5,("open_file_ntcreate: FILE_OVERWRITE "
2113 "requested for file %s and file "
2114 "doesn't exist.\n",
2115 smb_fname_str_dbg(smb_fname) ));
2116 errno = ENOENT;
2117 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
2119 break;
2121 case FILE_CREATE:
2122 /* If file exists error. If file doesn't exist
2123 * create. */
2124 if (file_existed) {
2125 DEBUG(5,("open_file_ntcreate: FILE_CREATE "
2126 "requested for file %s and file "
2127 "already exists.\n",
2128 smb_fname_str_dbg(smb_fname)));
2129 if (S_ISDIR(smb_fname->st.st_ex_mode)) {
2130 errno = EISDIR;
2131 } else {
2132 errno = EEXIST;
2134 return map_nt_error_from_unix(errno);
2136 break;
2138 case FILE_SUPERSEDE:
2139 case FILE_OVERWRITE_IF:
2140 case FILE_OPEN_IF:
2141 break;
2142 default:
2143 return NT_STATUS_INVALID_PARAMETER;
2146 flags2 = disposition_to_open_flags(create_disposition);
2148 /* We only care about matching attributes on file exists and
2149 * overwrite. */
2151 if (!posix_open && file_existed &&
2152 ((create_disposition == FILE_OVERWRITE) ||
2153 (create_disposition == FILE_OVERWRITE_IF))) {
2154 if (!open_match_attributes(conn, existing_dos_attributes,
2155 new_dos_attributes,
2156 smb_fname->st.st_ex_mode,
2157 unx_mode, &new_unx_mode)) {
2158 DEBUG(5,("open_file_ntcreate: attributes missmatch "
2159 "for file %s (%x %x) (0%o, 0%o)\n",
2160 smb_fname_str_dbg(smb_fname),
2161 existing_dos_attributes,
2162 new_dos_attributes,
2163 (unsigned int)smb_fname->st.st_ex_mode,
2164 (unsigned int)unx_mode ));
2165 errno = EACCES;
2166 return NT_STATUS_ACCESS_DENIED;
2170 status = smbd_calculate_access_mask(conn, smb_fname,
2171 false,
2172 access_mask,
2173 &access_mask);
2174 if (!NT_STATUS_IS_OK(status)) {
2175 DEBUG(10, ("open_file_ntcreate: smbd_calculate_access_mask "
2176 "on file %s returned %s\n",
2177 smb_fname_str_dbg(smb_fname), nt_errstr(status)));
2178 return status;
2181 open_access_mask = access_mask;
2183 if ((flags2 & O_TRUNC) || (oplock_request & FORCE_OPLOCK_BREAK_TO_NONE)) {
2184 open_access_mask |= FILE_WRITE_DATA; /* This will cause oplock breaks. */
2187 DEBUG(10, ("open_file_ntcreate: fname=%s, after mapping "
2188 "access_mask=0x%x\n", smb_fname_str_dbg(smb_fname),
2189 access_mask));
2192 * Note that we ignore the append flag as append does not
2193 * mean the same thing under DOS and Unix.
2196 flags = calculate_open_access_flags(access_mask, oplock_request,
2197 private_flags);
2200 * Currently we only look at FILE_WRITE_THROUGH for create options.
2203 #if defined(O_SYNC)
2204 if ((create_options & FILE_WRITE_THROUGH) && lp_strict_sync(SNUM(conn))) {
2205 flags2 |= O_SYNC;
2207 #endif /* O_SYNC */
2209 if (posix_open && (access_mask & FILE_APPEND_DATA)) {
2210 flags2 |= O_APPEND;
2213 if (!posix_open && !CAN_WRITE(conn)) {
2215 * We should really return a permission denied error if either
2216 * O_CREAT or O_TRUNC are set, but for compatibility with
2217 * older versions of Samba we just AND them out.
2219 flags2 &= ~(O_CREAT|O_TRUNC);
2222 if (first_open_attempt && lp_kernel_oplocks(SNUM(conn))) {
2224 * With kernel oplocks the open breaking an oplock
2225 * blocks until the oplock holder has given up the
2226 * oplock or closed the file. We prevent this by first
2227 * trying to open the file with O_NONBLOCK (see "man
2228 * fcntl" on Linux). For the second try, triggered by
2229 * an oplock break response, we do not need this
2230 * anymore.
2232 * This is true under the assumption that only Samba
2233 * requests kernel oplocks. Once someone else like
2234 * NFSv4 starts to use that API, we will have to
2235 * modify this by communicating with the NFSv4 server.
2237 flags2 |= O_NONBLOCK;
2241 * Ensure we can't write on a read-only share or file.
2244 if (flags != O_RDONLY && file_existed &&
2245 (!CAN_WRITE(conn) || IS_DOS_READONLY(existing_dos_attributes))) {
2246 DEBUG(5,("open_file_ntcreate: write access requested for "
2247 "file %s on read only %s\n",
2248 smb_fname_str_dbg(smb_fname),
2249 !CAN_WRITE(conn) ? "share" : "file" ));
2250 errno = EACCES;
2251 return NT_STATUS_ACCESS_DENIED;
2254 fsp->file_id = vfs_file_id_from_sbuf(conn, &smb_fname->st);
2255 fsp->share_access = share_access;
2256 fsp->fh->private_options = private_flags;
2257 fsp->access_mask = open_access_mask; /* We change this to the
2258 * requested access_mask after
2259 * the open is done. */
2260 fsp->posix_open = posix_open;
2262 /* Ensure no SAMBA_PRIVATE bits can be set. */
2263 fsp->oplock_type = (oplock_request & ~SAMBA_PRIVATE_OPLOCK_MASK);
2265 if (timeval_is_zero(&request_time)) {
2266 request_time = fsp->open_time;
2270 * Ensure we pay attention to default ACLs on directories if required.
2273 if ((flags2 & O_CREAT) && lp_inherit_acls(SNUM(conn)) &&
2274 (def_acl = directory_has_default_acl(conn, parent_dir))) {
2275 unx_mode = (0777 & lp_create_mask(SNUM(conn)));
2278 DEBUG(4,("calling open_file with flags=0x%X flags2=0x%X mode=0%o, "
2279 "access_mask = 0x%x, open_access_mask = 0x%x\n",
2280 (unsigned int)flags, (unsigned int)flags2,
2281 (unsigned int)unx_mode, (unsigned int)access_mask,
2282 (unsigned int)open_access_mask));
2284 fsp_open = open_file(fsp, conn, req, parent_dir,
2285 flags|flags2, unx_mode, access_mask,
2286 open_access_mask, &new_file_created);
2288 if (NT_STATUS_EQUAL(fsp_open, NT_STATUS_NETWORK_BUSY)) {
2289 struct deferred_open_record state;
2292 * EWOULDBLOCK/EAGAIN maps to NETWORK_BUSY.
2294 if (file_existed && S_ISFIFO(fsp->fsp_name->st.st_ex_mode)) {
2295 DEBUG(10, ("FIFO busy\n"));
2296 return NT_STATUS_NETWORK_BUSY;
2298 if (req == NULL) {
2299 DEBUG(10, ("Internal open busy\n"));
2300 return NT_STATUS_NETWORK_BUSY;
2304 * From here on we assume this is an oplock break triggered
2307 lck = get_existing_share_mode_lock(talloc_tos(), fsp->file_id);
2308 if (lck == NULL) {
2309 state.delayed_for_oplocks = false;
2310 state.async_open = false;
2311 state.id = fsp->file_id;
2312 defer_open(NULL, request_time, timeval_set(0, 0),
2313 req, &state);
2314 DEBUG(10, ("No share mode lock found after "
2315 "EWOULDBLOCK, retrying sync\n"));
2316 return NT_STATUS_SHARING_VIOLATION;
2319 find_oplock_types(fsp, 0, lck, &batch_entry, &exclusive_entry,
2320 &got_level2_oplock, &got_a_none_oplock);
2322 if (delay_for_batch_oplocks(fsp, req->mid, 0, batch_entry) ||
2323 delay_for_exclusive_oplocks(fsp, req->mid, 0,
2324 exclusive_entry)) {
2325 schedule_defer_open(lck, request_time, req);
2326 TALLOC_FREE(lck);
2327 DEBUG(10, ("Sent oplock break request to kernel "
2328 "oplock holder\n"));
2329 return NT_STATUS_SHARING_VIOLATION;
2333 * No oplock from Samba around. Immediately retry with
2334 * a blocking open.
2336 state.delayed_for_oplocks = false;
2337 state.async_open = false;
2338 state.id = lck->data->id;
2339 defer_open(lck, request_time, timeval_set(0, 0), req, &state);
2340 TALLOC_FREE(lck);
2341 DEBUG(10, ("No Samba oplock around after EWOULDBLOCK. "
2342 "Retrying sync\n"));
2343 return NT_STATUS_SHARING_VIOLATION;
2346 if (!NT_STATUS_IS_OK(fsp_open)) {
2347 if (NT_STATUS_EQUAL(fsp_open, NT_STATUS_RETRY)) {
2348 schedule_async_open(request_time, req);
2350 TALLOC_FREE(lck);
2351 return fsp_open;
2354 if (file_existed && !check_same_dev_ino(&saved_stat, &smb_fname->st)) {
2356 * The file did exist, but some other (local or NFS)
2357 * process either renamed/unlinked and re-created the
2358 * file with different dev/ino after we walked the path,
2359 * but before we did the open. We could retry the
2360 * open but it's a rare enough case it's easier to
2361 * just fail the open to prevent creating any problems
2362 * in the open file db having the wrong dev/ino key.
2364 TALLOC_FREE(lck);
2365 fd_close(fsp);
2366 DEBUG(1,("open_file_ntcreate: file %s - dev/ino mismatch. "
2367 "Old (dev=0x%llu, ino =0x%llu). "
2368 "New (dev=0x%llu, ino=0x%llu). Failing open "
2369 " with NT_STATUS_ACCESS_DENIED.\n",
2370 smb_fname_str_dbg(smb_fname),
2371 (unsigned long long)saved_stat.st_ex_dev,
2372 (unsigned long long)saved_stat.st_ex_ino,
2373 (unsigned long long)smb_fname->st.st_ex_dev,
2374 (unsigned long long)smb_fname->st.st_ex_ino));
2375 return NT_STATUS_ACCESS_DENIED;
2378 old_write_time = smb_fname->st.st_ex_mtime;
2381 * Deal with the race condition where two smbd's detect the
2382 * file doesn't exist and do the create at the same time. One
2383 * of them will win and set a share mode, the other (ie. this
2384 * one) should check if the requested share mode for this
2385 * create is allowed.
2389 * Now the file exists and fsp is successfully opened,
2390 * fsp->dev and fsp->inode are valid and should replace the
2391 * dev=0,inode=0 from a non existent file. Spotted by
2392 * Nadav Danieli <nadavd@exanet.com>. JRA.
2395 id = fsp->file_id;
2397 lck = get_share_mode_lock(talloc_tos(), id,
2398 conn->connectpath,
2399 smb_fname, &old_write_time);
2401 if (lck == NULL) {
2402 DEBUG(0, ("open_file_ntcreate: Could not get share "
2403 "mode lock for %s\n",
2404 smb_fname_str_dbg(smb_fname)));
2405 fd_close(fsp);
2406 return NT_STATUS_SHARING_VIOLATION;
2409 /* Get the types we need to examine. */
2410 find_oplock_types(fsp,
2411 oplock_request,
2412 lck,
2413 &batch_entry,
2414 &exclusive_entry,
2415 &got_level2_oplock,
2416 &got_a_none_oplock);
2418 /* First pass - send break only on batch oplocks. */
2419 if ((req != NULL) &&
2420 delay_for_batch_oplocks(fsp,
2421 req->mid,
2422 oplock_request,
2423 batch_entry)) {
2424 schedule_defer_open(lck, request_time, req);
2425 TALLOC_FREE(lck);
2426 fd_close(fsp);
2427 return NT_STATUS_SHARING_VIOLATION;
2430 status = open_mode_check(conn, lck, fsp->name_hash,
2431 access_mask, share_access,
2432 create_options, &file_existed);
2434 if (NT_STATUS_IS_OK(status)) {
2435 /* We might be going to allow this open. Check oplock
2436 * status again. */
2437 /* Second pass - send break for both batch or
2438 * exclusive oplocks. */
2439 if ((req != NULL) &&
2440 delay_for_exclusive_oplocks(
2441 fsp,
2442 req->mid,
2443 oplock_request,
2444 exclusive_entry)) {
2445 schedule_defer_open(lck, request_time, req);
2446 TALLOC_FREE(lck);
2447 fd_close(fsp);
2448 return NT_STATUS_SHARING_VIOLATION;
2452 if (NT_STATUS_EQUAL(status, NT_STATUS_DELETE_PENDING)) {
2453 /* DELETE_PENDING is not deferred for a second */
2454 TALLOC_FREE(lck);
2455 fd_close(fsp);
2456 return status;
2459 if (!NT_STATUS_IS_OK(status)) {
2460 uint32 can_access_mask;
2461 bool can_access = True;
2463 SMB_ASSERT(NT_STATUS_EQUAL(status, NT_STATUS_SHARING_VIOLATION));
2465 /* Check if this can be done with the deny_dos and fcb
2466 * calls. */
2467 if (private_flags &
2468 (NTCREATEX_OPTIONS_PRIVATE_DENY_DOS|
2469 NTCREATEX_OPTIONS_PRIVATE_DENY_FCB)) {
2470 if (req == NULL) {
2471 DEBUG(0, ("DOS open without an SMB "
2472 "request!\n"));
2473 TALLOC_FREE(lck);
2474 fd_close(fsp);
2475 return NT_STATUS_INTERNAL_ERROR;
2478 /* Use the client requested access mask here,
2479 * not the one we open with. */
2480 status = fcb_or_dos_open(req,
2481 conn,
2482 fsp,
2483 smb_fname,
2485 req->smbpid,
2486 req->vuid,
2487 access_mask,
2488 share_access,
2489 create_options);
2491 if (NT_STATUS_IS_OK(status)) {
2492 TALLOC_FREE(lck);
2493 if (pinfo) {
2494 *pinfo = FILE_WAS_OPENED;
2496 return NT_STATUS_OK;
2501 * This next line is a subtlety we need for
2502 * MS-Access. If a file open will fail due to share
2503 * permissions and also for security (access) reasons,
2504 * we need to return the access failed error, not the
2505 * share error. We can't open the file due to kernel
2506 * oplock deadlock (it's possible we failed above on
2507 * the open_mode_check()) so use a userspace check.
2510 if (flags & O_RDWR) {
2511 can_access_mask = FILE_READ_DATA|FILE_WRITE_DATA;
2512 } else if (flags & O_WRONLY) {
2513 can_access_mask = FILE_WRITE_DATA;
2514 } else {
2515 can_access_mask = FILE_READ_DATA;
2518 if (((can_access_mask & FILE_WRITE_DATA) &&
2519 !CAN_WRITE(conn)) ||
2520 !NT_STATUS_IS_OK(smbd_check_access_rights(conn,
2521 smb_fname,
2522 false,
2523 can_access_mask))) {
2524 can_access = False;
2528 * If we're returning a share violation, ensure we
2529 * cope with the braindead 1 second delay.
2532 if (!(oplock_request & INTERNAL_OPEN_ONLY) &&
2533 lp_defer_sharing_violations()) {
2534 struct timeval timeout;
2535 struct deferred_open_record state;
2536 int timeout_usecs;
2538 /* this is a hack to speed up torture tests
2539 in 'make test' */
2540 timeout_usecs = lp_parm_int(SNUM(conn),
2541 "smbd","sharedelay",
2542 SHARING_VIOLATION_USEC_WAIT);
2544 /* This is a relative time, added to the absolute
2545 request_time value to get the absolute timeout time.
2546 Note that if this is the second or greater time we enter
2547 this codepath for this particular request mid then
2548 request_time is left as the absolute time of the *first*
2549 time this request mid was processed. This is what allows
2550 the request to eventually time out. */
2552 timeout = timeval_set(0, timeout_usecs);
2554 /* Nothing actually uses state.delayed_for_oplocks
2555 but it's handy to differentiate in debug messages
2556 between a 30 second delay due to oplock break, and
2557 a 1 second delay for share mode conflicts. */
2559 state.delayed_for_oplocks = False;
2560 state.async_open = false;
2561 state.id = id;
2563 if ((req != NULL)
2564 && !request_timed_out(request_time,
2565 timeout)) {
2566 defer_open(lck, request_time, timeout,
2567 req, &state);
2571 TALLOC_FREE(lck);
2572 fd_close(fsp);
2573 if (can_access) {
2575 * We have detected a sharing violation here
2576 * so return the correct error code
2578 status = NT_STATUS_SHARING_VIOLATION;
2579 } else {
2580 status = NT_STATUS_ACCESS_DENIED;
2582 return status;
2585 grant_fsp_oplock_type(fsp,
2586 oplock_request,
2587 got_level2_oplock,
2588 got_a_none_oplock);
2591 * We have the share entry *locked*.....
2594 /* Delete streams if create_disposition requires it */
2595 if (!new_file_created && clear_ads(create_disposition) &&
2596 !is_ntfs_stream_smb_fname(smb_fname)) {
2597 status = delete_all_streams(conn, smb_fname->base_name);
2598 if (!NT_STATUS_IS_OK(status)) {
2599 TALLOC_FREE(lck);
2600 fd_close(fsp);
2601 return status;
2605 /* note that we ignore failure for the following. It is
2606 basically a hack for NFS, and NFS will never set one of
2607 these only read them. Nobody but Samba can ever set a deny
2608 mode and we have already checked our more authoritative
2609 locking database for permission to set this deny mode. If
2610 the kernel refuses the operations then the kernel is wrong.
2611 note that GPFS supports it as well - jmcd */
2613 if (fsp->fh->fd != -1 && lp_kernel_share_modes(SNUM(conn))) {
2614 int ret_flock;
2615 ret_flock = SMB_VFS_KERNEL_FLOCK(fsp, share_access, access_mask);
2616 if(ret_flock == -1 ){
2618 TALLOC_FREE(lck);
2619 fd_close(fsp);
2621 return NT_STATUS_SHARING_VIOLATION;
2626 * At this point onwards, we can guarantee that the share entry
2627 * is locked, whether we created the file or not, and that the
2628 * deny mode is compatible with all current opens.
2632 * According to Samba4, SEC_FILE_READ_ATTRIBUTE is always granted,
2633 * but we don't have to store this - just ignore it on access check.
2635 if (conn->sconn->using_smb2) {
2637 * SMB2 doesn't return it (according to Microsoft tests).
2638 * Test Case: TestSuite_ScenarioNo009GrantedAccessTestS0
2639 * File created with access = 0x7 (Read, Write, Delete)
2640 * Query Info on file returns 0x87 (Read, Write, Delete, Read Attributes)
2642 fsp->access_mask = access_mask;
2643 } else {
2644 /* But SMB1 does. */
2645 fsp->access_mask = access_mask | FILE_READ_ATTRIBUTES;
2648 if (file_existed) {
2649 /* stat opens on existing files don't get oplocks. */
2650 if (is_stat_open(open_access_mask)) {
2651 fsp->oplock_type = NO_OPLOCK;
2655 if (new_file_created) {
2656 info = FILE_WAS_CREATED;
2657 } else {
2658 if (flags2 & O_TRUNC) {
2659 info = FILE_WAS_OVERWRITTEN;
2660 } else {
2661 info = FILE_WAS_OPENED;
2665 if (pinfo) {
2666 *pinfo = info;
2670 * Setup the oplock info in both the shared memory and
2671 * file structs.
2674 status = set_file_oplock(fsp, fsp->oplock_type);
2675 if (!NT_STATUS_IS_OK(status)) {
2677 * Could not get the kernel oplock or there are byte-range
2678 * locks on the file.
2680 fsp->oplock_type = NO_OPLOCK;
2683 set_share_mode(lck, fsp, get_current_uid(conn),
2684 req ? req->mid : 0,
2685 fsp->oplock_type);
2687 /* Handle strange delete on close create semantics. */
2688 if (create_options & FILE_DELETE_ON_CLOSE) {
2690 status = can_set_delete_on_close(fsp, new_dos_attributes);
2692 if (!NT_STATUS_IS_OK(status)) {
2693 /* Remember to delete the mode we just added. */
2694 del_share_mode(lck, fsp);
2695 TALLOC_FREE(lck);
2696 fd_close(fsp);
2697 return status;
2699 /* Note that here we set the *inital* delete on close flag,
2700 not the regular one. The magic gets handled in close. */
2701 fsp->initial_delete_on_close = True;
2704 if (info != FILE_WAS_OPENED) {
2705 /* Files should be initially set as archive */
2706 if (lp_map_archive(SNUM(conn)) ||
2707 lp_store_dos_attributes(SNUM(conn))) {
2708 if (!posix_open) {
2709 if (file_set_dosmode(conn, smb_fname,
2710 new_dos_attributes | FILE_ATTRIBUTE_ARCHIVE,
2711 parent_dir, true) == 0) {
2712 unx_mode = smb_fname->st.st_ex_mode;
2718 /* Determine sparse flag. */
2719 if (posix_open) {
2720 /* POSIX opens are sparse by default. */
2721 fsp->is_sparse = true;
2722 } else {
2723 fsp->is_sparse = (file_existed &&
2724 (existing_dos_attributes & FILE_ATTRIBUTE_SPARSE));
2728 * Take care of inherited ACLs on created files - if default ACL not
2729 * selected.
2732 if (!posix_open && new_file_created && !def_acl) {
2734 int saved_errno = errno; /* We might get ENOSYS in the next
2735 * call.. */
2737 if (SMB_VFS_FCHMOD_ACL(fsp, unx_mode) == -1 &&
2738 errno == ENOSYS) {
2739 errno = saved_errno; /* Ignore ENOSYS */
2742 } else if (new_unx_mode) {
2744 int ret = -1;
2746 /* Attributes need changing. File already existed. */
2749 int saved_errno = errno; /* We might get ENOSYS in the
2750 * next call.. */
2751 ret = SMB_VFS_FCHMOD_ACL(fsp, new_unx_mode);
2753 if (ret == -1 && errno == ENOSYS) {
2754 errno = saved_errno; /* Ignore ENOSYS */
2755 } else {
2756 DEBUG(5, ("open_file_ntcreate: reset "
2757 "attributes of file %s to 0%o\n",
2758 smb_fname_str_dbg(smb_fname),
2759 (unsigned int)new_unx_mode));
2760 ret = 0; /* Don't do the fchmod below. */
2764 if ((ret == -1) &&
2765 (SMB_VFS_FCHMOD(fsp, new_unx_mode) == -1))
2766 DEBUG(5, ("open_file_ntcreate: failed to reset "
2767 "attributes of file %s to 0%o\n",
2768 smb_fname_str_dbg(smb_fname),
2769 (unsigned int)new_unx_mode));
2772 TALLOC_FREE(lck);
2774 return NT_STATUS_OK;
2778 /****************************************************************************
2779 Open a file for for write to ensure that we can fchmod it.
2780 ****************************************************************************/
2782 NTSTATUS open_file_fchmod(connection_struct *conn,
2783 struct smb_filename *smb_fname,
2784 files_struct **result)
2786 if (!VALID_STAT(smb_fname->st)) {
2787 return NT_STATUS_INVALID_PARAMETER;
2790 return SMB_VFS_CREATE_FILE(
2791 conn, /* conn */
2792 NULL, /* req */
2793 0, /* root_dir_fid */
2794 smb_fname, /* fname */
2795 FILE_WRITE_DATA, /* access_mask */
2796 (FILE_SHARE_READ | FILE_SHARE_WRITE | /* share_access */
2797 FILE_SHARE_DELETE),
2798 FILE_OPEN, /* create_disposition*/
2799 0, /* create_options */
2800 0, /* file_attributes */
2801 INTERNAL_OPEN_ONLY, /* oplock_request */
2802 0, /* allocation_size */
2803 0, /* private_flags */
2804 NULL, /* sd */
2805 NULL, /* ea_list */
2806 result, /* result */
2807 NULL); /* pinfo */
2810 static NTSTATUS mkdir_internal(connection_struct *conn,
2811 struct smb_filename *smb_dname,
2812 uint32 file_attributes)
2814 mode_t mode;
2815 char *parent_dir = NULL;
2816 NTSTATUS status;
2817 bool posix_open = false;
2818 bool need_re_stat = false;
2819 uint32_t access_mask = SEC_DIR_ADD_SUBDIR;
2821 if (!CAN_WRITE(conn) || (access_mask & ~(conn->share_access))) {
2822 DEBUG(5,("mkdir_internal: failing share access "
2823 "%s\n", lp_servicename(talloc_tos(), SNUM(conn))));
2824 return NT_STATUS_ACCESS_DENIED;
2827 if (!parent_dirname(talloc_tos(), smb_dname->base_name, &parent_dir,
2828 NULL)) {
2829 return NT_STATUS_NO_MEMORY;
2832 if (file_attributes & FILE_FLAG_POSIX_SEMANTICS) {
2833 posix_open = true;
2834 mode = (mode_t)(file_attributes & ~FILE_FLAG_POSIX_SEMANTICS);
2835 } else {
2836 mode = unix_mode(conn, FILE_ATTRIBUTE_DIRECTORY, smb_dname, parent_dir);
2839 status = check_parent_access(conn,
2840 smb_dname,
2841 access_mask);
2842 if(!NT_STATUS_IS_OK(status)) {
2843 DEBUG(5,("mkdir_internal: check_parent_access "
2844 "on directory %s for path %s returned %s\n",
2845 parent_dir,
2846 smb_dname->base_name,
2847 nt_errstr(status) ));
2848 return status;
2851 if (SMB_VFS_MKDIR(conn, smb_dname->base_name, mode) != 0) {
2852 return map_nt_error_from_unix(errno);
2855 /* Ensure we're checking for a symlink here.... */
2856 /* We don't want to get caught by a symlink racer. */
2858 if (SMB_VFS_LSTAT(conn, smb_dname) == -1) {
2859 DEBUG(2, ("Could not stat directory '%s' just created: %s\n",
2860 smb_fname_str_dbg(smb_dname), strerror(errno)));
2861 return map_nt_error_from_unix(errno);
2864 if (!S_ISDIR(smb_dname->st.st_ex_mode)) {
2865 DEBUG(0, ("Directory '%s' just created is not a directory !\n",
2866 smb_fname_str_dbg(smb_dname)));
2867 return NT_STATUS_NOT_A_DIRECTORY;
2870 if (lp_store_dos_attributes(SNUM(conn))) {
2871 if (!posix_open) {
2872 file_set_dosmode(conn, smb_dname,
2873 file_attributes | FILE_ATTRIBUTE_DIRECTORY,
2874 parent_dir, true);
2878 if (lp_inherit_perms(SNUM(conn))) {
2879 inherit_access_posix_acl(conn, parent_dir,
2880 smb_dname->base_name, mode);
2881 need_re_stat = true;
2884 if (!posix_open) {
2886 * Check if high bits should have been set,
2887 * then (if bits are missing): add them.
2888 * Consider bits automagically set by UNIX, i.e. SGID bit from parent
2889 * dir.
2891 if ((mode & ~(S_IRWXU|S_IRWXG|S_IRWXO)) &&
2892 (mode & ~smb_dname->st.st_ex_mode)) {
2893 SMB_VFS_CHMOD(conn, smb_dname->base_name,
2894 (smb_dname->st.st_ex_mode |
2895 (mode & ~smb_dname->st.st_ex_mode)));
2896 need_re_stat = true;
2900 /* Change the owner if required. */
2901 if (lp_inherit_owner(SNUM(conn))) {
2902 change_dir_owner_to_parent(conn, parent_dir,
2903 smb_dname->base_name,
2904 &smb_dname->st);
2905 need_re_stat = true;
2908 if (need_re_stat) {
2909 if (SMB_VFS_LSTAT(conn, smb_dname) == -1) {
2910 DEBUG(2, ("Could not stat directory '%s' just created: %s\n",
2911 smb_fname_str_dbg(smb_dname), strerror(errno)));
2912 return map_nt_error_from_unix(errno);
2916 notify_fname(conn, NOTIFY_ACTION_ADDED, FILE_NOTIFY_CHANGE_DIR_NAME,
2917 smb_dname->base_name);
2919 return NT_STATUS_OK;
2922 /****************************************************************************
2923 Open a directory from an NT SMB call.
2924 ****************************************************************************/
2926 static NTSTATUS open_directory(connection_struct *conn,
2927 struct smb_request *req,
2928 struct smb_filename *smb_dname,
2929 uint32 access_mask,
2930 uint32 share_access,
2931 uint32 create_disposition,
2932 uint32 create_options,
2933 uint32 file_attributes,
2934 int *pinfo,
2935 files_struct **result)
2937 files_struct *fsp = NULL;
2938 bool dir_existed = VALID_STAT(smb_dname->st) ? True : False;
2939 struct share_mode_lock *lck = NULL;
2940 NTSTATUS status;
2941 struct timespec mtimespec;
2942 int info = 0;
2944 if (is_ntfs_stream_smb_fname(smb_dname)) {
2945 DEBUG(2, ("open_directory: %s is a stream name!\n",
2946 smb_fname_str_dbg(smb_dname)));
2947 return NT_STATUS_NOT_A_DIRECTORY;
2950 if (!(file_attributes & FILE_FLAG_POSIX_SEMANTICS)) {
2951 /* Ensure we have a directory attribute. */
2952 file_attributes |= FILE_ATTRIBUTE_DIRECTORY;
2955 DEBUG(5,("open_directory: opening directory %s, access_mask = 0x%x, "
2956 "share_access = 0x%x create_options = 0x%x, "
2957 "create_disposition = 0x%x, file_attributes = 0x%x\n",
2958 smb_fname_str_dbg(smb_dname),
2959 (unsigned int)access_mask,
2960 (unsigned int)share_access,
2961 (unsigned int)create_options,
2962 (unsigned int)create_disposition,
2963 (unsigned int)file_attributes));
2965 status = smbd_calculate_access_mask(conn, smb_dname, false,
2966 access_mask, &access_mask);
2967 if (!NT_STATUS_IS_OK(status)) {
2968 DEBUG(10, ("open_directory: smbd_calculate_access_mask "
2969 "on file %s returned %s\n",
2970 smb_fname_str_dbg(smb_dname),
2971 nt_errstr(status)));
2972 return status;
2975 if ((access_mask & SEC_FLAG_SYSTEM_SECURITY) &&
2976 !security_token_has_privilege(get_current_nttok(conn),
2977 SEC_PRIV_SECURITY)) {
2978 DEBUG(10, ("open_directory: open on %s "
2979 "failed - SEC_FLAG_SYSTEM_SECURITY denied.\n",
2980 smb_fname_str_dbg(smb_dname)));
2981 return NT_STATUS_PRIVILEGE_NOT_HELD;
2984 switch( create_disposition ) {
2985 case FILE_OPEN:
2987 if (!dir_existed) {
2988 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
2991 info = FILE_WAS_OPENED;
2992 break;
2994 case FILE_CREATE:
2996 /* If directory exists error. If directory doesn't
2997 * exist create. */
2999 if (dir_existed) {
3000 status = NT_STATUS_OBJECT_NAME_COLLISION;
3001 DEBUG(2, ("open_directory: unable to create "
3002 "%s. Error was %s\n",
3003 smb_fname_str_dbg(smb_dname),
3004 nt_errstr(status)));
3005 return status;
3008 status = mkdir_internal(conn, smb_dname,
3009 file_attributes);
3011 if (!NT_STATUS_IS_OK(status)) {
3012 DEBUG(2, ("open_directory: unable to create "
3013 "%s. Error was %s\n",
3014 smb_fname_str_dbg(smb_dname),
3015 nt_errstr(status)));
3016 return status;
3019 info = FILE_WAS_CREATED;
3020 break;
3022 case FILE_OPEN_IF:
3024 * If directory exists open. If directory doesn't
3025 * exist create.
3028 if (dir_existed) {
3029 status = NT_STATUS_OK;
3030 info = FILE_WAS_OPENED;
3031 } else {
3032 status = mkdir_internal(conn, smb_dname,
3033 file_attributes);
3035 if (NT_STATUS_IS_OK(status)) {
3036 info = FILE_WAS_CREATED;
3037 } else {
3038 /* Cope with create race. */
3039 if (!NT_STATUS_EQUAL(status,
3040 NT_STATUS_OBJECT_NAME_COLLISION)) {
3041 DEBUG(2, ("open_directory: unable to create "
3042 "%s. Error was %s\n",
3043 smb_fname_str_dbg(smb_dname),
3044 nt_errstr(status)));
3045 return status;
3047 info = FILE_WAS_OPENED;
3051 break;
3053 case FILE_SUPERSEDE:
3054 case FILE_OVERWRITE:
3055 case FILE_OVERWRITE_IF:
3056 default:
3057 DEBUG(5,("open_directory: invalid create_disposition "
3058 "0x%x for directory %s\n",
3059 (unsigned int)create_disposition,
3060 smb_fname_str_dbg(smb_dname)));
3061 return NT_STATUS_INVALID_PARAMETER;
3064 if(!S_ISDIR(smb_dname->st.st_ex_mode)) {
3065 DEBUG(5,("open_directory: %s is not a directory !\n",
3066 smb_fname_str_dbg(smb_dname)));
3067 return NT_STATUS_NOT_A_DIRECTORY;
3070 if (info == FILE_WAS_OPENED) {
3071 status = smbd_check_access_rights(conn,
3072 smb_dname,
3073 false,
3074 access_mask);
3075 if (!NT_STATUS_IS_OK(status)) {
3076 DEBUG(10, ("open_directory: smbd_check_access_rights on "
3077 "file %s failed with %s\n",
3078 smb_fname_str_dbg(smb_dname),
3079 nt_errstr(status)));
3080 return status;
3084 status = file_new(req, conn, &fsp);
3085 if(!NT_STATUS_IS_OK(status)) {
3086 return status;
3090 * Setup the files_struct for it.
3093 fsp->file_id = vfs_file_id_from_sbuf(conn, &smb_dname->st);
3094 fsp->vuid = req ? req->vuid : UID_FIELD_INVALID;
3095 fsp->file_pid = req ? req->smbpid : 0;
3096 fsp->can_lock = False;
3097 fsp->can_read = False;
3098 fsp->can_write = False;
3100 fsp->share_access = share_access;
3101 fsp->fh->private_options = 0;
3103 * According to Samba4, SEC_FILE_READ_ATTRIBUTE is always granted,
3105 fsp->access_mask = access_mask | FILE_READ_ATTRIBUTES;
3106 fsp->print_file = NULL;
3107 fsp->modified = False;
3108 fsp->oplock_type = NO_OPLOCK;
3109 fsp->sent_oplock_break = NO_BREAK_SENT;
3110 fsp->is_directory = True;
3111 fsp->posix_open = (file_attributes & FILE_FLAG_POSIX_SEMANTICS) ? True : False;
3112 status = fsp_set_smb_fname(fsp, smb_dname);
3113 if (!NT_STATUS_IS_OK(status)) {
3114 file_free(req, fsp);
3115 return status;
3118 mtimespec = smb_dname->st.st_ex_mtime;
3120 #ifdef O_DIRECTORY
3121 status = fd_open(conn, fsp, O_RDONLY|O_DIRECTORY, 0);
3122 #else
3123 /* POSIX allows us to open a directory with O_RDONLY. */
3124 status = fd_open(conn, fsp, O_RDONLY, 0);
3125 #endif
3126 if (!NT_STATUS_IS_OK(status)) {
3127 DEBUG(5, ("open_directory: Could not open fd for "
3128 "%s (%s)\n",
3129 smb_fname_str_dbg(smb_dname),
3130 nt_errstr(status)));
3131 file_free(req, fsp);
3132 return status;
3135 status = vfs_stat_fsp(fsp);
3136 if (!NT_STATUS_IS_OK(status)) {
3137 fd_close(fsp);
3138 file_free(req, fsp);
3139 return status;
3142 /* Ensure there was no race condition. */
3143 if (!check_same_stat(&smb_dname->st, &fsp->fsp_name->st)) {
3144 DEBUG(5,("open_directory: stat struct differs for "
3145 "directory %s.\n",
3146 smb_fname_str_dbg(smb_dname)));
3147 fd_close(fsp);
3148 file_free(req, fsp);
3149 return NT_STATUS_ACCESS_DENIED;
3152 lck = get_share_mode_lock(talloc_tos(), fsp->file_id,
3153 conn->connectpath, smb_dname,
3154 &mtimespec);
3156 if (lck == NULL) {
3157 DEBUG(0, ("open_directory: Could not get share mode lock for "
3158 "%s\n", smb_fname_str_dbg(smb_dname)));
3159 fd_close(fsp);
3160 file_free(req, fsp);
3161 return NT_STATUS_SHARING_VIOLATION;
3164 status = open_mode_check(conn, lck, fsp->name_hash,
3165 access_mask, share_access,
3166 create_options, &dir_existed);
3168 if (!NT_STATUS_IS_OK(status)) {
3169 TALLOC_FREE(lck);
3170 fd_close(fsp);
3171 file_free(req, fsp);
3172 return status;
3175 set_share_mode(lck, fsp, get_current_uid(conn),
3176 req ? req->mid : 0, NO_OPLOCK);
3178 /* For directories the delete on close bit at open time seems
3179 always to be honored on close... See test 19 in Samba4 BASE-DELETE. */
3180 if (create_options & FILE_DELETE_ON_CLOSE) {
3181 status = can_set_delete_on_close(fsp, 0);
3182 if (!NT_STATUS_IS_OK(status) && !NT_STATUS_EQUAL(status, NT_STATUS_DIRECTORY_NOT_EMPTY)) {
3183 TALLOC_FREE(lck);
3184 fd_close(fsp);
3185 file_free(req, fsp);
3186 return status;
3189 if (NT_STATUS_IS_OK(status)) {
3190 /* Note that here we set the *inital* delete on close flag,
3191 not the regular one. The magic gets handled in close. */
3192 fsp->initial_delete_on_close = True;
3196 TALLOC_FREE(lck);
3198 if (pinfo) {
3199 *pinfo = info;
3202 *result = fsp;
3203 return NT_STATUS_OK;
3206 NTSTATUS create_directory(connection_struct *conn, struct smb_request *req,
3207 struct smb_filename *smb_dname)
3209 NTSTATUS status;
3210 files_struct *fsp;
3212 status = SMB_VFS_CREATE_FILE(
3213 conn, /* conn */
3214 req, /* req */
3215 0, /* root_dir_fid */
3216 smb_dname, /* fname */
3217 FILE_READ_ATTRIBUTES, /* access_mask */
3218 FILE_SHARE_NONE, /* share_access */
3219 FILE_CREATE, /* create_disposition*/
3220 FILE_DIRECTORY_FILE, /* create_options */
3221 FILE_ATTRIBUTE_DIRECTORY, /* file_attributes */
3222 0, /* oplock_request */
3223 0, /* allocation_size */
3224 0, /* private_flags */
3225 NULL, /* sd */
3226 NULL, /* ea_list */
3227 &fsp, /* result */
3228 NULL); /* pinfo */
3230 if (NT_STATUS_IS_OK(status)) {
3231 close_file(req, fsp, NORMAL_CLOSE);
3234 return status;
3237 /****************************************************************************
3238 Receive notification that one of our open files has been renamed by another
3239 smbd process.
3240 ****************************************************************************/
3242 void msg_file_was_renamed(struct messaging_context *msg,
3243 void *private_data,
3244 uint32_t msg_type,
3245 struct server_id server_id,
3246 DATA_BLOB *data)
3248 files_struct *fsp;
3249 char *frm = (char *)data->data;
3250 struct file_id id;
3251 const char *sharepath;
3252 const char *base_name;
3253 const char *stream_name;
3254 struct smb_filename *smb_fname = NULL;
3255 size_t sp_len, bn_len;
3256 NTSTATUS status;
3257 struct smbd_server_connection *sconn =
3258 talloc_get_type_abort(private_data,
3259 struct smbd_server_connection);
3261 if (data->data == NULL
3262 || data->length < MSG_FILE_RENAMED_MIN_SIZE + 2) {
3263 DEBUG(0, ("msg_file_was_renamed: Got invalid msg len %d\n",
3264 (int)data->length));
3265 return;
3268 /* Unpack the message. */
3269 pull_file_id_24(frm, &id);
3270 sharepath = &frm[24];
3271 sp_len = strlen(sharepath);
3272 base_name = sharepath + sp_len + 1;
3273 bn_len = strlen(base_name);
3274 stream_name = sharepath + sp_len + 1 + bn_len + 1;
3276 /* stream_name must always be NULL if there is no stream. */
3277 if (stream_name[0] == '\0') {
3278 stream_name = NULL;
3281 smb_fname = synthetic_smb_fname(talloc_tos(), base_name,
3282 stream_name, NULL);
3283 if (smb_fname == NULL) {
3284 return;
3287 DEBUG(10,("msg_file_was_renamed: Got rename message for sharepath %s, new name %s, "
3288 "file_id %s\n",
3289 sharepath, smb_fname_str_dbg(smb_fname),
3290 file_id_string_tos(&id)));
3292 for(fsp = file_find_di_first(sconn, id); fsp;
3293 fsp = file_find_di_next(fsp)) {
3294 if (memcmp(fsp->conn->connectpath, sharepath, sp_len) == 0) {
3296 DEBUG(10,("msg_file_was_renamed: renaming file %s from %s -> %s\n",
3297 fsp_fnum_dbg(fsp), fsp_str_dbg(fsp),
3298 smb_fname_str_dbg(smb_fname)));
3299 status = fsp_set_smb_fname(fsp, smb_fname);
3300 if (!NT_STATUS_IS_OK(status)) {
3301 goto out;
3303 } else {
3304 /* TODO. JRA. */
3305 /* Now we have the complete path we can work out if this is
3306 actually within this share and adjust newname accordingly. */
3307 DEBUG(10,("msg_file_was_renamed: share mismatch (sharepath %s "
3308 "not sharepath %s) "
3309 "%s from %s -> %s\n",
3310 fsp->conn->connectpath,
3311 sharepath,
3312 fsp_fnum_dbg(fsp),
3313 fsp_str_dbg(fsp),
3314 smb_fname_str_dbg(smb_fname)));
3317 out:
3318 TALLOC_FREE(smb_fname);
3319 return;
3323 * If a main file is opened for delete, all streams need to be checked for
3324 * !FILE_SHARE_DELETE. Do this by opening with DELETE_ACCESS.
3325 * If that works, delete them all by setting the delete on close and close.
3328 NTSTATUS open_streams_for_delete(connection_struct *conn,
3329 const char *fname)
3331 struct stream_struct *stream_info = NULL;
3332 files_struct **streams = NULL;
3333 int i;
3334 unsigned int num_streams = 0;
3335 TALLOC_CTX *frame = talloc_stackframe();
3336 NTSTATUS status;
3338 status = vfs_streaminfo(conn, NULL, fname, talloc_tos(),
3339 &num_streams, &stream_info);
3341 if (NT_STATUS_EQUAL(status, NT_STATUS_NOT_IMPLEMENTED)
3342 || NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
3343 DEBUG(10, ("no streams around\n"));
3344 TALLOC_FREE(frame);
3345 return NT_STATUS_OK;
3348 if (!NT_STATUS_IS_OK(status)) {
3349 DEBUG(10, ("vfs_streaminfo failed: %s\n",
3350 nt_errstr(status)));
3351 goto fail;
3354 DEBUG(10, ("open_streams_for_delete found %d streams\n",
3355 num_streams));
3357 if (num_streams == 0) {
3358 TALLOC_FREE(frame);
3359 return NT_STATUS_OK;
3362 streams = talloc_array(talloc_tos(), files_struct *, num_streams);
3363 if (streams == NULL) {
3364 DEBUG(0, ("talloc failed\n"));
3365 status = NT_STATUS_NO_MEMORY;
3366 goto fail;
3369 for (i=0; i<num_streams; i++) {
3370 struct smb_filename *smb_fname;
3372 if (strequal(stream_info[i].name, "::$DATA")) {
3373 streams[i] = NULL;
3374 continue;
3377 smb_fname = synthetic_smb_fname(
3378 talloc_tos(), fname, stream_info[i].name, NULL);
3379 if (smb_fname == NULL) {
3380 status = NT_STATUS_NO_MEMORY;
3381 goto fail;
3384 if (SMB_VFS_STAT(conn, smb_fname) == -1) {
3385 DEBUG(10, ("Unable to stat stream: %s\n",
3386 smb_fname_str_dbg(smb_fname)));
3389 status = SMB_VFS_CREATE_FILE(
3390 conn, /* conn */
3391 NULL, /* req */
3392 0, /* root_dir_fid */
3393 smb_fname, /* fname */
3394 DELETE_ACCESS, /* access_mask */
3395 (FILE_SHARE_READ | /* share_access */
3396 FILE_SHARE_WRITE | FILE_SHARE_DELETE),
3397 FILE_OPEN, /* create_disposition*/
3398 0, /* create_options */
3399 FILE_ATTRIBUTE_NORMAL, /* file_attributes */
3400 0, /* oplock_request */
3401 0, /* allocation_size */
3402 NTCREATEX_OPTIONS_PRIVATE_STREAM_DELETE, /* private_flags */
3403 NULL, /* sd */
3404 NULL, /* ea_list */
3405 &streams[i], /* result */
3406 NULL); /* pinfo */
3408 if (!NT_STATUS_IS_OK(status)) {
3409 DEBUG(10, ("Could not open stream %s: %s\n",
3410 smb_fname_str_dbg(smb_fname),
3411 nt_errstr(status)));
3413 TALLOC_FREE(smb_fname);
3414 break;
3416 TALLOC_FREE(smb_fname);
3420 * don't touch the variable "status" beyond this point :-)
3423 for (i -= 1 ; i >= 0; i--) {
3424 if (streams[i] == NULL) {
3425 continue;
3428 DEBUG(10, ("Closing stream # %d, %s\n", i,
3429 fsp_str_dbg(streams[i])));
3430 close_file(NULL, streams[i], NORMAL_CLOSE);
3433 fail:
3434 TALLOC_FREE(frame);
3435 return status;
3438 /*********************************************************************
3439 Create a default ACL by inheriting from the parent. If no inheritance
3440 from the parent available, don't set anything. This will leave the actual
3441 permissions the new file or directory already got from the filesystem
3442 as the NT ACL when read.
3443 *********************************************************************/
3445 static NTSTATUS inherit_new_acl(files_struct *fsp)
3447 TALLOC_CTX *frame = talloc_stackframe();
3448 char *parent_name = NULL;
3449 struct security_descriptor *parent_desc = NULL;
3450 NTSTATUS status = NT_STATUS_OK;
3451 struct security_descriptor *psd = NULL;
3452 const struct dom_sid *owner_sid = NULL;
3453 const struct dom_sid *group_sid = NULL;
3454 uint32_t security_info_sent = (SECINFO_OWNER | SECINFO_GROUP | SECINFO_DACL);
3455 struct security_token *token = fsp->conn->session_info->security_token;
3456 bool inherit_owner = lp_inherit_owner(SNUM(fsp->conn));
3457 bool inheritable_components = false;
3458 bool try_builtin_administrators = false;
3459 const struct dom_sid *BA_U_sid = NULL;
3460 const struct dom_sid *BA_G_sid = NULL;
3461 bool try_system = false;
3462 const struct dom_sid *SY_U_sid = NULL;
3463 const struct dom_sid *SY_G_sid = NULL;
3464 size_t size = 0;
3466 if (!parent_dirname(frame, fsp->fsp_name->base_name, &parent_name, NULL)) {
3467 TALLOC_FREE(frame);
3468 return NT_STATUS_NO_MEMORY;
3471 status = SMB_VFS_GET_NT_ACL(fsp->conn,
3472 parent_name,
3473 (SECINFO_OWNER | SECINFO_GROUP | SECINFO_DACL),
3474 frame,
3475 &parent_desc);
3476 if (!NT_STATUS_IS_OK(status)) {
3477 TALLOC_FREE(frame);
3478 return status;
3481 inheritable_components = sd_has_inheritable_components(parent_desc,
3482 fsp->is_directory);
3484 if (!inheritable_components && !inherit_owner) {
3485 TALLOC_FREE(frame);
3486 /* Nothing to inherit and not setting owner. */
3487 return NT_STATUS_OK;
3490 /* Create an inherited descriptor from the parent. */
3492 if (DEBUGLEVEL >= 10) {
3493 DEBUG(10,("inherit_new_acl: parent acl for %s is:\n",
3494 fsp_str_dbg(fsp) ));
3495 NDR_PRINT_DEBUG(security_descriptor, parent_desc);
3498 /* Inherit from parent descriptor if "inherit owner" set. */
3499 if (inherit_owner) {
3500 owner_sid = parent_desc->owner_sid;
3501 group_sid = parent_desc->group_sid;
3504 if (owner_sid == NULL) {
3505 if (security_token_has_builtin_administrators(token)) {
3506 try_builtin_administrators = true;
3507 } else if (security_token_is_system(token)) {
3508 try_builtin_administrators = true;
3509 try_system = true;
3513 if (group_sid == NULL &&
3514 token->num_sids == PRIMARY_GROUP_SID_INDEX)
3516 if (security_token_is_system(token)) {
3517 try_builtin_administrators = true;
3518 try_system = true;
3522 if (try_builtin_administrators) {
3523 struct unixid ids;
3524 bool ok;
3526 ZERO_STRUCT(ids);
3527 ok = sids_to_unixids(&global_sid_Builtin_Administrators, 1, &ids);
3528 if (ok) {
3529 switch (ids.type) {
3530 case ID_TYPE_BOTH:
3531 BA_U_sid = &global_sid_Builtin_Administrators;
3532 BA_G_sid = &global_sid_Builtin_Administrators;
3533 break;
3534 case ID_TYPE_UID:
3535 BA_U_sid = &global_sid_Builtin_Administrators;
3536 break;
3537 case ID_TYPE_GID:
3538 BA_G_sid = &global_sid_Builtin_Administrators;
3539 break;
3540 default:
3541 break;
3546 if (try_system) {
3547 struct unixid ids;
3548 bool ok;
3550 ZERO_STRUCT(ids);
3551 ok = sids_to_unixids(&global_sid_System, 1, &ids);
3552 if (ok) {
3553 switch (ids.type) {
3554 case ID_TYPE_BOTH:
3555 SY_U_sid = &global_sid_System;
3556 SY_G_sid = &global_sid_System;
3557 break;
3558 case ID_TYPE_UID:
3559 SY_U_sid = &global_sid_System;
3560 break;
3561 case ID_TYPE_GID:
3562 SY_G_sid = &global_sid_System;
3563 break;
3564 default:
3565 break;
3570 if (owner_sid == NULL) {
3571 owner_sid = BA_U_sid;
3574 if (owner_sid == NULL) {
3575 owner_sid = SY_U_sid;
3578 if (group_sid == NULL) {
3579 group_sid = SY_G_sid;
3582 if (try_system && group_sid == NULL) {
3583 group_sid = BA_G_sid;
3586 if (owner_sid == NULL) {
3587 owner_sid = &token->sids[PRIMARY_USER_SID_INDEX];
3589 if (group_sid == NULL) {
3590 if (token->num_sids == PRIMARY_GROUP_SID_INDEX) {
3591 group_sid = &token->sids[PRIMARY_USER_SID_INDEX];
3592 } else {
3593 group_sid = &token->sids[PRIMARY_GROUP_SID_INDEX];
3597 status = se_create_child_secdesc(frame,
3598 &psd,
3599 &size,
3600 parent_desc,
3601 owner_sid,
3602 group_sid,
3603 fsp->is_directory);
3604 if (!NT_STATUS_IS_OK(status)) {
3605 TALLOC_FREE(frame);
3606 return status;
3609 /* If inheritable_components == false,
3610 se_create_child_secdesc()
3611 creates a security desriptor with a NULL dacl
3612 entry, but with SEC_DESC_DACL_PRESENT. We need
3613 to remove that flag. */
3615 if (!inheritable_components) {
3616 security_info_sent &= ~SECINFO_DACL;
3617 psd->type &= ~SEC_DESC_DACL_PRESENT;
3620 if (DEBUGLEVEL >= 10) {
3621 DEBUG(10,("inherit_new_acl: child acl for %s is:\n",
3622 fsp_str_dbg(fsp) ));
3623 NDR_PRINT_DEBUG(security_descriptor, psd);
3626 if (inherit_owner) {
3627 /* We need to be root to force this. */
3628 become_root();
3630 status = SMB_VFS_FSET_NT_ACL(fsp,
3631 security_info_sent,
3632 psd);
3633 if (inherit_owner) {
3634 unbecome_root();
3636 TALLOC_FREE(frame);
3637 return status;
3641 * Wrapper around open_file_ntcreate and open_directory
3644 static NTSTATUS create_file_unixpath(connection_struct *conn,
3645 struct smb_request *req,
3646 struct smb_filename *smb_fname,
3647 uint32_t access_mask,
3648 uint32_t share_access,
3649 uint32_t create_disposition,
3650 uint32_t create_options,
3651 uint32_t file_attributes,
3652 uint32_t oplock_request,
3653 uint64_t allocation_size,
3654 uint32_t private_flags,
3655 struct security_descriptor *sd,
3656 struct ea_list *ea_list,
3658 files_struct **result,
3659 int *pinfo)
3661 int info = FILE_WAS_OPENED;
3662 files_struct *base_fsp = NULL;
3663 files_struct *fsp = NULL;
3664 NTSTATUS status;
3666 DEBUG(10,("create_file_unixpath: access_mask = 0x%x "
3667 "file_attributes = 0x%x, share_access = 0x%x, "
3668 "create_disposition = 0x%x create_options = 0x%x "
3669 "oplock_request = 0x%x private_flags = 0x%x "
3670 "ea_list = 0x%p, sd = 0x%p, "
3671 "fname = %s\n",
3672 (unsigned int)access_mask,
3673 (unsigned int)file_attributes,
3674 (unsigned int)share_access,
3675 (unsigned int)create_disposition,
3676 (unsigned int)create_options,
3677 (unsigned int)oplock_request,
3678 (unsigned int)private_flags,
3679 ea_list, sd, smb_fname_str_dbg(smb_fname)));
3681 if (create_options & FILE_OPEN_BY_FILE_ID) {
3682 status = NT_STATUS_NOT_SUPPORTED;
3683 goto fail;
3686 if (create_options & NTCREATEX_OPTIONS_INVALID_PARAM_MASK) {
3687 status = NT_STATUS_INVALID_PARAMETER;
3688 goto fail;
3691 if (req == NULL) {
3692 oplock_request |= INTERNAL_OPEN_ONLY;
3695 if ((conn->fs_capabilities & FILE_NAMED_STREAMS)
3696 && (access_mask & DELETE_ACCESS)
3697 && !is_ntfs_stream_smb_fname(smb_fname)) {
3699 * We can't open a file with DELETE access if any of the
3700 * streams is open without FILE_SHARE_DELETE
3702 status = open_streams_for_delete(conn, smb_fname->base_name);
3704 if (!NT_STATUS_IS_OK(status)) {
3705 goto fail;
3709 if ((access_mask & SEC_FLAG_SYSTEM_SECURITY) &&
3710 !security_token_has_privilege(get_current_nttok(conn),
3711 SEC_PRIV_SECURITY)) {
3712 DEBUG(10, ("create_file_unixpath: open on %s "
3713 "failed - SEC_FLAG_SYSTEM_SECURITY denied.\n",
3714 smb_fname_str_dbg(smb_fname)));
3715 status = NT_STATUS_PRIVILEGE_NOT_HELD;
3716 goto fail;
3719 if ((conn->fs_capabilities & FILE_NAMED_STREAMS)
3720 && is_ntfs_stream_smb_fname(smb_fname)
3721 && (!(private_flags & NTCREATEX_OPTIONS_PRIVATE_STREAM_DELETE))) {
3722 uint32 base_create_disposition;
3723 struct smb_filename *smb_fname_base = NULL;
3725 if (create_options & FILE_DIRECTORY_FILE) {
3726 status = NT_STATUS_NOT_A_DIRECTORY;
3727 goto fail;
3730 switch (create_disposition) {
3731 case FILE_OPEN:
3732 base_create_disposition = FILE_OPEN;
3733 break;
3734 default:
3735 base_create_disposition = FILE_OPEN_IF;
3736 break;
3739 /* Create an smb_filename with stream_name == NULL. */
3740 smb_fname_base = synthetic_smb_fname(talloc_tos(),
3741 smb_fname->base_name,
3742 NULL, NULL);
3743 if (smb_fname_base == NULL) {
3744 status = NT_STATUS_NO_MEMORY;
3745 goto fail;
3748 if (SMB_VFS_STAT(conn, smb_fname_base) == -1) {
3749 DEBUG(10, ("Unable to stat stream: %s\n",
3750 smb_fname_str_dbg(smb_fname_base)));
3753 /* Open the base file. */
3754 status = create_file_unixpath(conn, NULL, smb_fname_base, 0,
3755 FILE_SHARE_READ
3756 | FILE_SHARE_WRITE
3757 | FILE_SHARE_DELETE,
3758 base_create_disposition,
3759 0, 0, 0, 0, 0, NULL, NULL,
3760 &base_fsp, NULL);
3761 TALLOC_FREE(smb_fname_base);
3763 if (!NT_STATUS_IS_OK(status)) {
3764 DEBUG(10, ("create_file_unixpath for base %s failed: "
3765 "%s\n", smb_fname->base_name,
3766 nt_errstr(status)));
3767 goto fail;
3769 /* we don't need to low level fd */
3770 fd_close(base_fsp);
3774 * If it's a request for a directory open, deal with it separately.
3777 if (create_options & FILE_DIRECTORY_FILE) {
3779 if (create_options & FILE_NON_DIRECTORY_FILE) {
3780 status = NT_STATUS_INVALID_PARAMETER;
3781 goto fail;
3784 /* Can't open a temp directory. IFS kit test. */
3785 if (!(file_attributes & FILE_FLAG_POSIX_SEMANTICS) &&
3786 (file_attributes & FILE_ATTRIBUTE_TEMPORARY)) {
3787 status = NT_STATUS_INVALID_PARAMETER;
3788 goto fail;
3792 * We will get a create directory here if the Win32
3793 * app specified a security descriptor in the
3794 * CreateDirectory() call.
3797 oplock_request = 0;
3798 status = open_directory(
3799 conn, req, smb_fname, access_mask, share_access,
3800 create_disposition, create_options, file_attributes,
3801 &info, &fsp);
3802 } else {
3805 * Ordinary file case.
3808 status = file_new(req, conn, &fsp);
3809 if(!NT_STATUS_IS_OK(status)) {
3810 goto fail;
3813 status = fsp_set_smb_fname(fsp, smb_fname);
3814 if (!NT_STATUS_IS_OK(status)) {
3815 goto fail;
3818 if (base_fsp) {
3820 * We're opening the stream element of a
3821 * base_fsp we already opened. Set up the
3822 * base_fsp pointer.
3824 fsp->base_fsp = base_fsp;
3827 if (allocation_size) {
3828 fsp->initial_allocation_size = smb_roundup(fsp->conn,
3829 allocation_size);
3832 status = open_file_ntcreate(conn,
3833 req,
3834 access_mask,
3835 share_access,
3836 create_disposition,
3837 create_options,
3838 file_attributes,
3839 oplock_request,
3840 private_flags,
3841 &info,
3842 fsp);
3844 if(!NT_STATUS_IS_OK(status)) {
3845 file_free(req, fsp);
3846 fsp = NULL;
3849 if (NT_STATUS_EQUAL(status, NT_STATUS_FILE_IS_A_DIRECTORY)) {
3851 /* A stream open never opens a directory */
3853 if (base_fsp) {
3854 status = NT_STATUS_FILE_IS_A_DIRECTORY;
3855 goto fail;
3859 * Fail the open if it was explicitly a non-directory
3860 * file.
3863 if (create_options & FILE_NON_DIRECTORY_FILE) {
3864 status = NT_STATUS_FILE_IS_A_DIRECTORY;
3865 goto fail;
3868 oplock_request = 0;
3869 status = open_directory(
3870 conn, req, smb_fname, access_mask,
3871 share_access, create_disposition,
3872 create_options, file_attributes,
3873 &info, &fsp);
3877 if (!NT_STATUS_IS_OK(status)) {
3878 goto fail;
3881 fsp->base_fsp = base_fsp;
3883 if ((ea_list != NULL) &&
3884 ((info == FILE_WAS_CREATED) || (info == FILE_WAS_OVERWRITTEN))) {
3885 status = set_ea(conn, fsp, fsp->fsp_name, ea_list);
3886 if (!NT_STATUS_IS_OK(status)) {
3887 goto fail;
3891 if (!fsp->is_directory && S_ISDIR(fsp->fsp_name->st.st_ex_mode)) {
3892 status = NT_STATUS_ACCESS_DENIED;
3893 goto fail;
3896 /* Save the requested allocation size. */
3897 if ((info == FILE_WAS_CREATED) || (info == FILE_WAS_OVERWRITTEN)) {
3898 if (allocation_size
3899 && (allocation_size > fsp->fsp_name->st.st_ex_size)) {
3900 fsp->initial_allocation_size = smb_roundup(
3901 fsp->conn, allocation_size);
3902 if (fsp->is_directory) {
3903 /* Can't set allocation size on a directory. */
3904 status = NT_STATUS_ACCESS_DENIED;
3905 goto fail;
3907 if (vfs_allocate_file_space(
3908 fsp, fsp->initial_allocation_size) == -1) {
3909 status = NT_STATUS_DISK_FULL;
3910 goto fail;
3912 } else {
3913 fsp->initial_allocation_size = smb_roundup(
3914 fsp->conn, (uint64_t)fsp->fsp_name->st.st_ex_size);
3916 } else {
3917 fsp->initial_allocation_size = 0;
3920 if ((info == FILE_WAS_CREATED) && lp_nt_acl_support(SNUM(conn)) &&
3921 fsp->base_fsp == NULL) {
3922 if (sd != NULL) {
3924 * According to the MS documentation, the only time the security
3925 * descriptor is applied to the opened file is iff we *created* the
3926 * file; an existing file stays the same.
3928 * Also, it seems (from observation) that you can open the file with
3929 * any access mask but you can still write the sd. We need to override
3930 * the granted access before we call set_sd
3931 * Patch for bug #2242 from Tom Lackemann <cessnatomny@yahoo.com>.
3934 uint32_t sec_info_sent;
3935 uint32_t saved_access_mask = fsp->access_mask;
3937 sec_info_sent = get_sec_info(sd);
3939 fsp->access_mask = FILE_GENERIC_ALL;
3941 if (sec_info_sent & (SECINFO_OWNER|
3942 SECINFO_GROUP|
3943 SECINFO_DACL|
3944 SECINFO_SACL)) {
3945 status = set_sd(fsp, sd, sec_info_sent);
3948 fsp->access_mask = saved_access_mask;
3950 if (!NT_STATUS_IS_OK(status)) {
3951 goto fail;
3953 } else if (lp_inherit_acls(SNUM(conn))) {
3954 /* Inherit from parent. Errors here are not fatal. */
3955 status = inherit_new_acl(fsp);
3956 if (!NT_STATUS_IS_OK(status)) {
3957 DEBUG(10,("inherit_new_acl: failed for %s with %s\n",
3958 fsp_str_dbg(fsp),
3959 nt_errstr(status) ));
3964 DEBUG(10, ("create_file_unixpath: info=%d\n", info));
3966 *result = fsp;
3967 if (pinfo != NULL) {
3968 *pinfo = info;
3971 smb_fname->st = fsp->fsp_name->st;
3973 return NT_STATUS_OK;
3975 fail:
3976 DEBUG(10, ("create_file_unixpath: %s\n", nt_errstr(status)));
3978 if (fsp != NULL) {
3979 if (base_fsp && fsp->base_fsp == base_fsp) {
3981 * The close_file below will close
3982 * fsp->base_fsp.
3984 base_fsp = NULL;
3986 close_file(req, fsp, ERROR_CLOSE);
3987 fsp = NULL;
3989 if (base_fsp != NULL) {
3990 close_file(req, base_fsp, ERROR_CLOSE);
3991 base_fsp = NULL;
3993 return status;
3997 * Calculate the full path name given a relative fid.
3999 NTSTATUS get_relative_fid_filename(connection_struct *conn,
4000 struct smb_request *req,
4001 uint16_t root_dir_fid,
4002 const struct smb_filename *smb_fname,
4003 struct smb_filename **smb_fname_out)
4005 files_struct *dir_fsp;
4006 char *parent_fname = NULL;
4007 char *new_base_name = NULL;
4008 NTSTATUS status;
4010 if (root_dir_fid == 0 || !smb_fname) {
4011 status = NT_STATUS_INTERNAL_ERROR;
4012 goto out;
4015 dir_fsp = file_fsp(req, root_dir_fid);
4017 if (dir_fsp == NULL) {
4018 status = NT_STATUS_INVALID_HANDLE;
4019 goto out;
4022 if (is_ntfs_stream_smb_fname(dir_fsp->fsp_name)) {
4023 status = NT_STATUS_INVALID_HANDLE;
4024 goto out;
4027 if (!dir_fsp->is_directory) {
4030 * Check to see if this is a mac fork of some kind.
4033 if ((conn->fs_capabilities & FILE_NAMED_STREAMS) &&
4034 is_ntfs_stream_smb_fname(smb_fname)) {
4035 status = NT_STATUS_OBJECT_PATH_NOT_FOUND;
4036 goto out;
4040 we need to handle the case when we get a
4041 relative open relative to a file and the
4042 pathname is blank - this is a reopen!
4043 (hint from demyn plantenberg)
4046 status = NT_STATUS_INVALID_HANDLE;
4047 goto out;
4050 if (ISDOT(dir_fsp->fsp_name->base_name)) {
4052 * We're at the toplevel dir, the final file name
4053 * must not contain ./, as this is filtered out
4054 * normally by srvstr_get_path and unix_convert
4055 * explicitly rejects paths containing ./.
4057 parent_fname = talloc_strdup(talloc_tos(), "");
4058 if (parent_fname == NULL) {
4059 status = NT_STATUS_NO_MEMORY;
4060 goto out;
4062 } else {
4063 size_t dir_name_len = strlen(dir_fsp->fsp_name->base_name);
4066 * Copy in the base directory name.
4069 parent_fname = talloc_array(talloc_tos(), char,
4070 dir_name_len+2);
4071 if (parent_fname == NULL) {
4072 status = NT_STATUS_NO_MEMORY;
4073 goto out;
4075 memcpy(parent_fname, dir_fsp->fsp_name->base_name,
4076 dir_name_len+1);
4079 * Ensure it ends in a '/'.
4080 * We used TALLOC_SIZE +2 to add space for the '/'.
4083 if(dir_name_len
4084 && (parent_fname[dir_name_len-1] != '\\')
4085 && (parent_fname[dir_name_len-1] != '/')) {
4086 parent_fname[dir_name_len] = '/';
4087 parent_fname[dir_name_len+1] = '\0';
4091 new_base_name = talloc_asprintf(talloc_tos(), "%s%s", parent_fname,
4092 smb_fname->base_name);
4093 if (new_base_name == NULL) {
4094 status = NT_STATUS_NO_MEMORY;
4095 goto out;
4098 status = filename_convert(req,
4099 conn,
4100 req->flags2 & FLAGS2_DFS_PATHNAMES,
4101 new_base_name,
4103 NULL,
4104 smb_fname_out);
4105 if (!NT_STATUS_IS_OK(status)) {
4106 goto out;
4109 out:
4110 TALLOC_FREE(parent_fname);
4111 TALLOC_FREE(new_base_name);
4112 return status;
4115 NTSTATUS create_file_default(connection_struct *conn,
4116 struct smb_request *req,
4117 uint16_t root_dir_fid,
4118 struct smb_filename *smb_fname,
4119 uint32_t access_mask,
4120 uint32_t share_access,
4121 uint32_t create_disposition,
4122 uint32_t create_options,
4123 uint32_t file_attributes,
4124 uint32_t oplock_request,
4125 uint64_t allocation_size,
4126 uint32_t private_flags,
4127 struct security_descriptor *sd,
4128 struct ea_list *ea_list,
4129 files_struct **result,
4130 int *pinfo)
4132 int info = FILE_WAS_OPENED;
4133 files_struct *fsp = NULL;
4134 NTSTATUS status;
4135 bool stream_name = false;
4137 DEBUG(10,("create_file: access_mask = 0x%x "
4138 "file_attributes = 0x%x, share_access = 0x%x, "
4139 "create_disposition = 0x%x create_options = 0x%x "
4140 "oplock_request = 0x%x "
4141 "private_flags = 0x%x "
4142 "root_dir_fid = 0x%x, ea_list = 0x%p, sd = 0x%p, "
4143 "fname = %s\n",
4144 (unsigned int)access_mask,
4145 (unsigned int)file_attributes,
4146 (unsigned int)share_access,
4147 (unsigned int)create_disposition,
4148 (unsigned int)create_options,
4149 (unsigned int)oplock_request,
4150 (unsigned int)private_flags,
4151 (unsigned int)root_dir_fid,
4152 ea_list, sd, smb_fname_str_dbg(smb_fname)));
4155 * Calculate the filename from the root_dir_if if necessary.
4158 if (root_dir_fid != 0) {
4159 struct smb_filename *smb_fname_out = NULL;
4160 status = get_relative_fid_filename(conn, req, root_dir_fid,
4161 smb_fname, &smb_fname_out);
4162 if (!NT_STATUS_IS_OK(status)) {
4163 goto fail;
4165 smb_fname = smb_fname_out;
4169 * Check to see if this is a mac fork of some kind.
4172 stream_name = is_ntfs_stream_smb_fname(smb_fname);
4173 if (stream_name) {
4174 enum FAKE_FILE_TYPE fake_file_type;
4176 fake_file_type = is_fake_file(smb_fname);
4178 if (fake_file_type != FAKE_FILE_TYPE_NONE) {
4181 * Here we go! support for changing the disk quotas
4182 * --metze
4184 * We need to fake up to open this MAGIC QUOTA file
4185 * and return a valid FID.
4187 * w2k close this file directly after openening xp
4188 * also tries a QUERY_FILE_INFO on the file and then
4189 * close it
4191 status = open_fake_file(req, conn, req->vuid,
4192 fake_file_type, smb_fname,
4193 access_mask, &fsp);
4194 if (!NT_STATUS_IS_OK(status)) {
4195 goto fail;
4198 ZERO_STRUCT(smb_fname->st);
4199 goto done;
4202 if (!(conn->fs_capabilities & FILE_NAMED_STREAMS)) {
4203 status = NT_STATUS_OBJECT_NAME_NOT_FOUND;
4204 goto fail;
4208 if (is_ntfs_default_stream_smb_fname(smb_fname)) {
4209 int ret;
4210 smb_fname->stream_name = NULL;
4211 /* We have to handle this error here. */
4212 if (create_options & FILE_DIRECTORY_FILE) {
4213 status = NT_STATUS_NOT_A_DIRECTORY;
4214 goto fail;
4216 if (lp_posix_pathnames()) {
4217 ret = SMB_VFS_LSTAT(conn, smb_fname);
4218 } else {
4219 ret = SMB_VFS_STAT(conn, smb_fname);
4222 if (ret == 0 && VALID_STAT_OF_DIR(smb_fname->st)) {
4223 status = NT_STATUS_FILE_IS_A_DIRECTORY;
4224 goto fail;
4228 status = create_file_unixpath(
4229 conn, req, smb_fname, access_mask, share_access,
4230 create_disposition, create_options, file_attributes,
4231 oplock_request, allocation_size, private_flags,
4232 sd, ea_list,
4233 &fsp, &info);
4235 if (!NT_STATUS_IS_OK(status)) {
4236 goto fail;
4239 done:
4240 DEBUG(10, ("create_file: info=%d\n", info));
4242 *result = fsp;
4243 if (pinfo != NULL) {
4244 *pinfo = info;
4246 return NT_STATUS_OK;
4248 fail:
4249 DEBUG(10, ("create_file: %s\n", nt_errstr(status)));
4251 if (fsp != NULL) {
4252 close_file(req, fsp, ERROR_CLOSE);
4253 fsp = NULL;
4255 return status;