smbd: Use dbwrap_record_watch_send for defer_open
[Samba/id10ts.git] / source3 / smbd / open.c
blob4442cfce01d3896b6e4860ee4b88f1dffffddd4f
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_deferred_open_entry(share_entry) &&
1029 !open_was_deferred(sconn, share_entry->op_mid))
1031 char *str = talloc_asprintf(talloc_tos(),
1032 "Got a deferred entry without a request: "
1033 "PANIC: %s\n",
1034 share_mode_str(talloc_tos(), num, share_entry));
1035 smb_panic(str);
1038 if (!is_valid_share_mode_entry(share_entry)) {
1039 return;
1042 fsp = file_find_dif(sconn, share_entry->id,
1043 share_entry->share_file_id);
1044 if (!fsp) {
1045 DEBUG(0,("validate_my_share_entries: PANIC : %s\n",
1046 share_mode_str(talloc_tos(), num, share_entry) ));
1047 smb_panic("validate_my_share_entries: Cannot match a "
1048 "share entry with an open file\n");
1051 if (is_deferred_open_entry(share_entry)) {
1052 goto panic;
1055 if ((share_entry->op_type == NO_OPLOCK) &&
1056 (fsp->oplock_type == FAKE_LEVEL_II_OPLOCK))
1058 /* Someone has already written to it, but I haven't yet
1059 * noticed */
1060 return;
1063 if (((uint16)fsp->oplock_type) != share_entry->op_type) {
1064 goto panic;
1067 return;
1069 panic:
1071 char *str;
1072 DEBUG(0,("validate_my_share_entries: PANIC : %s\n",
1073 share_mode_str(talloc_tos(), num, share_entry) ));
1074 str = talloc_asprintf(talloc_tos(),
1075 "validate_my_share_entries: "
1076 "file %s, oplock_type = 0x%x, op_type = 0x%x\n",
1077 fsp->fsp_name->base_name,
1078 (unsigned int)fsp->oplock_type,
1079 (unsigned int)share_entry->op_type );
1080 smb_panic(str);
1083 #endif
1085 bool is_stat_open(uint32 access_mask)
1087 const uint32_t stat_open_bits =
1088 (SYNCHRONIZE_ACCESS|
1089 FILE_READ_ATTRIBUTES|
1090 FILE_WRITE_ATTRIBUTES);
1092 return (((access_mask & stat_open_bits) != 0) &&
1093 ((access_mask & ~stat_open_bits) == 0));
1096 /****************************************************************************
1097 Deal with share modes
1098 Invarient: Share mode must be locked on entry and exit.
1099 Returns -1 on error, or number of share modes on success (may be zero).
1100 ****************************************************************************/
1102 static NTSTATUS open_mode_check(connection_struct *conn,
1103 struct share_mode_lock *lck,
1104 uint32_t name_hash,
1105 uint32 access_mask,
1106 uint32 share_access,
1107 uint32 create_options,
1108 bool *file_existed)
1110 int i;
1112 if(lck->data->num_share_modes == 0) {
1113 return NT_STATUS_OK;
1116 /* A delete on close prohibits everything */
1118 if (is_delete_on_close_set(lck, name_hash)) {
1120 * Check the delete on close token
1121 * is valid. It could have been left
1122 * after a server crash.
1124 for(i = 0; i < lck->data->num_share_modes; i++) {
1125 if (!share_mode_stale_pid(lck->data, i)) {
1127 *file_existed = true;
1129 return NT_STATUS_DELETE_PENDING;
1132 return NT_STATUS_OK;
1135 if (is_stat_open(access_mask)) {
1136 /* Stat open that doesn't trigger oplock breaks or share mode
1137 * checks... ! JRA. */
1138 return NT_STATUS_OK;
1142 * Check if the share modes will give us access.
1145 #if defined(DEVELOPER)
1146 for(i = 0; i < lck->data->num_share_modes; i++) {
1147 validate_my_share_entries(conn->sconn, i,
1148 &lck->data->share_modes[i]);
1150 #endif
1152 /* Now we check the share modes, after any oplock breaks. */
1153 for(i = 0; i < lck->data->num_share_modes; i++) {
1155 if (!is_valid_share_mode_entry(&lck->data->share_modes[i])) {
1156 continue;
1159 /* someone else has a share lock on it, check to see if we can
1160 * too */
1161 if (share_conflict(&lck->data->share_modes[i],
1162 access_mask, share_access)) {
1164 if (share_mode_stale_pid(lck->data, i)) {
1165 continue;
1168 *file_existed = true;
1170 return NT_STATUS_SHARING_VIOLATION;
1174 if (lck->data->num_share_modes != 0) {
1175 *file_existed = true;
1178 return NT_STATUS_OK;
1182 * Send a break message to the oplock holder and delay the open for
1183 * our client.
1186 static NTSTATUS send_break_message(files_struct *fsp,
1187 struct share_mode_entry *exclusive,
1188 uint64_t mid,
1189 int oplock_request)
1191 NTSTATUS status;
1192 char msg[MSG_SMB_SHARE_MODE_ENTRY_SIZE];
1194 DEBUG(10, ("Sending break request to PID %s\n",
1195 procid_str_static(&exclusive->pid)));
1196 exclusive->op_mid = mid;
1198 /* Create the message. */
1199 share_mode_entry_to_message(msg, exclusive);
1201 /* Add in the FORCE_OPLOCK_BREAK_TO_NONE bit in the message if set. We
1202 don't want this set in the share mode struct pointed to by lck. */
1204 if (oplock_request & FORCE_OPLOCK_BREAK_TO_NONE) {
1205 SSVAL(msg,OP_BREAK_MSG_OP_TYPE_OFFSET,
1206 exclusive->op_type | FORCE_OPLOCK_BREAK_TO_NONE);
1209 status = messaging_send_buf(fsp->conn->sconn->msg_ctx, exclusive->pid,
1210 MSG_SMB_BREAK_REQUEST,
1211 (uint8 *)msg,
1212 MSG_SMB_SHARE_MODE_ENTRY_SIZE);
1213 if (!NT_STATUS_IS_OK(status)) {
1214 DEBUG(3, ("Could not send oplock break message: %s\n",
1215 nt_errstr(status)));
1218 return status;
1222 * Return share_mode_entry pointers for :
1223 * 1). Batch oplock entry.
1224 * 2). Batch or exclusive oplock entry (may be identical to #1).
1225 * bool have_level2_oplock
1226 * bool have_no_oplock.
1227 * Do internal consistency checks on the share mode for a file.
1230 static void find_oplock_types(files_struct *fsp,
1231 int oplock_request,
1232 const struct share_mode_lock *lck,
1233 struct share_mode_entry **pp_batch,
1234 struct share_mode_entry **pp_ex_or_batch,
1235 bool *got_level2,
1236 bool *got_no_oplock)
1238 int i;
1240 *pp_batch = NULL;
1241 *pp_ex_or_batch = NULL;
1242 *got_level2 = false;
1243 *got_no_oplock = false;
1245 /* Ignore stat or internal opens, as is done in
1246 delay_for_batch_oplocks() and
1247 delay_for_exclusive_oplocks().
1249 if ((oplock_request & INTERNAL_OPEN_ONLY) || is_stat_open(fsp->access_mask)) {
1250 return;
1253 for (i=0; i<lck->data->num_share_modes; i++) {
1254 if (!is_valid_share_mode_entry(&lck->data->share_modes[i])) {
1255 continue;
1258 if (lck->data->share_modes[i].op_type == NO_OPLOCK &&
1259 is_stat_open(lck->data->share_modes[i].access_mask)) {
1260 /* We ignore stat opens in the table - they
1261 always have NO_OPLOCK and never get or
1262 cause breaks. JRA. */
1263 continue;
1266 if (BATCH_OPLOCK_TYPE(lck->data->share_modes[i].op_type)) {
1267 /* batch - can only be one. */
1268 if (share_mode_stale_pid(lck->data, i)) {
1269 DEBUG(10, ("Found stale batch oplock\n"));
1270 continue;
1272 if (*pp_ex_or_batch || *pp_batch || *got_level2 || *got_no_oplock) {
1273 smb_panic("Bad batch oplock entry.");
1275 *pp_batch = &lck->data->share_modes[i];
1278 if (EXCLUSIVE_OPLOCK_TYPE(lck->data->share_modes[i].op_type)) {
1279 if (share_mode_stale_pid(lck->data, i)) {
1280 DEBUG(10, ("Found stale duplicate oplock\n"));
1281 continue;
1283 /* Exclusive or batch - can only be one. */
1284 if (*pp_ex_or_batch || *got_level2 || *got_no_oplock) {
1285 smb_panic("Bad exclusive or batch oplock entry.");
1287 *pp_ex_or_batch = &lck->data->share_modes[i];
1290 if (LEVEL_II_OPLOCK_TYPE(lck->data->share_modes[i].op_type)) {
1291 if (*pp_batch || *pp_ex_or_batch) {
1292 if (share_mode_stale_pid(lck->data, i)) {
1293 DEBUG(10, ("Found stale LevelII "
1294 "oplock\n"));
1295 continue;
1297 smb_panic("Bad levelII oplock entry.");
1299 *got_level2 = true;
1302 if (lck->data->share_modes[i].op_type == NO_OPLOCK) {
1303 if (*pp_batch || *pp_ex_or_batch) {
1304 if (share_mode_stale_pid(lck->data, i)) {
1305 DEBUG(10, ("Found stale NO_OPLOCK "
1306 "entry\n"));
1307 continue;
1309 smb_panic("Bad no oplock entry.");
1311 *got_no_oplock = true;
1316 static bool delay_for_batch_oplocks(files_struct *fsp,
1317 uint64_t mid,
1318 int oplock_request,
1319 struct share_mode_entry *batch_entry)
1321 if ((oplock_request & INTERNAL_OPEN_ONLY) || is_stat_open(fsp->access_mask)) {
1322 return false;
1324 if (batch_entry == NULL) {
1325 return false;
1328 if (server_id_is_disconnected(&batch_entry->pid)) {
1330 * TODO: clean up.
1331 * This could be achieved by sending a break message
1332 * to ourselves. Special considerations for files
1333 * with delete_on_close flag set!
1335 * For now we keep it simple and do not
1336 * allow delete on close for durable handles.
1338 return false;
1341 /* Found a batch oplock */
1342 send_break_message(fsp, batch_entry, mid, oplock_request);
1343 return true;
1346 static bool delay_for_exclusive_oplocks(files_struct *fsp,
1347 uint64_t mid,
1348 int oplock_request,
1349 struct share_mode_entry *ex_entry)
1351 if ((oplock_request & INTERNAL_OPEN_ONLY) || is_stat_open(fsp->access_mask)) {
1352 return false;
1354 if (ex_entry == NULL) {
1355 return false;
1358 if (server_id_is_disconnected(&ex_entry->pid)) {
1360 * since only durable handles can get disconnected,
1361 * and we can only get durable handles with batch oplocks,
1362 * this should actually never be reached...
1364 return false;
1367 send_break_message(fsp, ex_entry, mid, oplock_request);
1368 return true;
1371 static bool file_has_brlocks(files_struct *fsp)
1373 struct byte_range_lock *br_lck;
1375 br_lck = brl_get_locks_readonly(fsp);
1376 if (!br_lck)
1377 return false;
1379 return br_lck->num_locks > 0 ? true : false;
1382 static void grant_fsp_oplock_type(files_struct *fsp,
1383 int oplock_request,
1384 bool got_level2_oplock,
1385 bool got_a_none_oplock)
1387 bool allow_level2 = (global_client_caps & CAP_LEVEL_II_OPLOCKS) &&
1388 lp_level2_oplocks(SNUM(fsp->conn));
1390 /* Start by granting what the client asked for,
1391 but ensure no SAMBA_PRIVATE bits can be set. */
1392 fsp->oplock_type = (oplock_request & ~SAMBA_PRIVATE_OPLOCK_MASK);
1394 if (oplock_request & INTERNAL_OPEN_ONLY) {
1395 /* No oplocks on internal open. */
1396 fsp->oplock_type = NO_OPLOCK;
1397 DEBUG(10,("grant_fsp_oplock_type: oplock type 0x%x on file %s\n",
1398 fsp->oplock_type, fsp_str_dbg(fsp)));
1399 return;
1402 if (lp_locking(fsp->conn->params) && file_has_brlocks(fsp)) {
1403 DEBUG(10,("grant_fsp_oplock_type: file %s has byte range locks\n",
1404 fsp_str_dbg(fsp)));
1405 fsp->oplock_type = NO_OPLOCK;
1408 if (is_stat_open(fsp->access_mask)) {
1409 /* Leave the value already set. */
1410 DEBUG(10,("grant_fsp_oplock_type: oplock type 0x%x on file %s\n",
1411 fsp->oplock_type, fsp_str_dbg(fsp)));
1412 return;
1416 * Match what was requested (fsp->oplock_type) with
1417 * what was found in the existing share modes.
1420 if (got_a_none_oplock) {
1421 fsp->oplock_type = NO_OPLOCK;
1422 } else if (got_level2_oplock) {
1423 if (fsp->oplock_type == NO_OPLOCK ||
1424 fsp->oplock_type == FAKE_LEVEL_II_OPLOCK) {
1425 /* Store a level2 oplock, but don't tell the client */
1426 fsp->oplock_type = FAKE_LEVEL_II_OPLOCK;
1427 } else {
1428 fsp->oplock_type = LEVEL_II_OPLOCK;
1430 } else {
1431 /* All share_mode_entries are placeholders or deferred.
1432 * Silently upgrade to fake levelII if the client didn't
1433 * ask for an oplock. */
1434 if (fsp->oplock_type == NO_OPLOCK) {
1435 /* Store a level2 oplock, but don't tell the client */
1436 fsp->oplock_type = FAKE_LEVEL_II_OPLOCK;
1441 * Don't grant level2 to clients that don't want them
1442 * or if we've turned them off.
1444 if (fsp->oplock_type == LEVEL_II_OPLOCK && !allow_level2) {
1445 fsp->oplock_type = FAKE_LEVEL_II_OPLOCK;
1448 DEBUG(10,("grant_fsp_oplock_type: oplock type 0x%x on file %s\n",
1449 fsp->oplock_type, fsp_str_dbg(fsp)));
1452 static bool request_timed_out(struct timeval request_time,
1453 struct timeval timeout)
1455 struct timeval now, end_time;
1456 GetTimeOfDay(&now);
1457 end_time = timeval_sum(&request_time, &timeout);
1458 return (timeval_compare(&end_time, &now) < 0);
1461 struct defer_open_state {
1462 struct smbd_server_connection *sconn;
1463 uint64_t mid;
1466 static void defer_open_done(struct tevent_req *req);
1468 /****************************************************************************
1469 Handle the 1 second delay in returning a SHARING_VIOLATION error.
1470 ****************************************************************************/
1472 static void defer_open(struct share_mode_lock *lck,
1473 struct timeval request_time,
1474 struct timeval timeout,
1475 struct smb_request *req,
1476 struct deferred_open_record *state)
1478 struct server_id self = messaging_server_id(req->sconn->msg_ctx);
1480 /* Paranoia check */
1482 if (lck) {
1483 int i;
1485 for (i=0; i<lck->data->num_share_modes; i++) {
1486 struct share_mode_entry *e = &lck->data->share_modes[i];
1488 if (is_deferred_open_entry(e) &&
1489 serverid_equal(&self, &e->pid) &&
1490 (e->op_mid == req->mid)) {
1491 DEBUG(0, ("Trying to defer an already deferred "
1492 "request: mid=%llu, exiting\n",
1493 (unsigned long long)req->mid));
1494 TALLOC_FREE(lck);
1495 exit_server("attempt to defer a deferred request");
1500 /* End paranoia check */
1502 DEBUG(10,("defer_open_sharing_error: time [%u.%06u] adding deferred "
1503 "open entry for mid %llu\n",
1504 (unsigned int)request_time.tv_sec,
1505 (unsigned int)request_time.tv_usec,
1506 (unsigned long long)req->mid));
1508 if (!push_deferred_open_message_smb(req, request_time, timeout,
1509 state->id, (char *)state, sizeof(*state))) {
1510 TALLOC_FREE(lck);
1511 exit_server("push_deferred_open_message_smb failed");
1513 if (lck) {
1514 struct defer_open_state *watch_state;
1515 struct tevent_req *watch_req;
1516 bool ret;
1518 watch_state = talloc(req->sconn, struct defer_open_state);
1519 if (watch_state == NULL) {
1520 exit_server("talloc failed");
1522 watch_state->sconn = req->sconn;
1523 watch_state->mid = req->mid;
1525 DEBUG(10, ("defering mid %llu\n",
1526 (unsigned long long)req->mid));
1528 watch_req = dbwrap_record_watch_send(
1529 watch_state, req->sconn->ev_ctx, lck->data->record,
1530 req->sconn->msg_ctx);
1531 if (watch_req == NULL) {
1532 exit_server("Could not watch share mode record");
1534 tevent_req_set_callback(watch_req, defer_open_done,
1535 watch_state);
1537 ret = tevent_req_set_endtime(
1538 watch_req, req->sconn->ev_ctx,
1539 timeval_sum(&request_time, &timeout));
1540 SMB_ASSERT(ret);
1544 static void defer_open_done(struct tevent_req *req)
1546 struct defer_open_state *state = tevent_req_callback_data(
1547 req, struct defer_open_state);
1548 struct db_record *rec = NULL;
1549 NTSTATUS status;
1550 bool ret;
1552 status = dbwrap_record_watch_recv(req, talloc_tos(), &rec);
1553 TALLOC_FREE(req);
1554 if (!NT_STATUS_IS_OK(status)) {
1555 DEBUG(5, ("dbwrap_record_watch_recv returned %s\n",
1556 nt_errstr(status)));
1558 * Even if it failed, retry anyway. TODO: We need a way to
1559 * tell a re-scheduled open about that error.
1564 * TODO: We need a version of dbwrap_record_watch_recv that does not
1565 * fetch_lock the record.
1567 TALLOC_FREE(rec);
1569 DEBUG(10, ("scheduling mid %llu\n", (unsigned long long)state->mid));
1571 ret = schedule_deferred_open_message_smb(state->sconn, state->mid);
1572 SMB_ASSERT(ret);
1573 TALLOC_FREE(state);
1577 /****************************************************************************
1578 On overwrite open ensure that the attributes match.
1579 ****************************************************************************/
1581 static bool open_match_attributes(connection_struct *conn,
1582 uint32 old_dos_attr,
1583 uint32 new_dos_attr,
1584 mode_t existing_unx_mode,
1585 mode_t new_unx_mode,
1586 mode_t *returned_unx_mode)
1588 uint32 noarch_old_dos_attr, noarch_new_dos_attr;
1590 noarch_old_dos_attr = (old_dos_attr & ~FILE_ATTRIBUTE_ARCHIVE);
1591 noarch_new_dos_attr = (new_dos_attr & ~FILE_ATTRIBUTE_ARCHIVE);
1593 if((noarch_old_dos_attr == 0 && noarch_new_dos_attr != 0) ||
1594 (noarch_old_dos_attr != 0 && ((noarch_old_dos_attr & noarch_new_dos_attr) == noarch_old_dos_attr))) {
1595 *returned_unx_mode = new_unx_mode;
1596 } else {
1597 *returned_unx_mode = (mode_t)0;
1600 DEBUG(10,("open_match_attributes: old_dos_attr = 0x%x, "
1601 "existing_unx_mode = 0%o, new_dos_attr = 0x%x "
1602 "returned_unx_mode = 0%o\n",
1603 (unsigned int)old_dos_attr,
1604 (unsigned int)existing_unx_mode,
1605 (unsigned int)new_dos_attr,
1606 (unsigned int)*returned_unx_mode ));
1608 /* If we're mapping SYSTEM and HIDDEN ensure they match. */
1609 if (lp_map_system(SNUM(conn)) || lp_store_dos_attributes(SNUM(conn))) {
1610 if ((old_dos_attr & FILE_ATTRIBUTE_SYSTEM) &&
1611 !(new_dos_attr & FILE_ATTRIBUTE_SYSTEM)) {
1612 return False;
1615 if (lp_map_hidden(SNUM(conn)) || lp_store_dos_attributes(SNUM(conn))) {
1616 if ((old_dos_attr & FILE_ATTRIBUTE_HIDDEN) &&
1617 !(new_dos_attr & FILE_ATTRIBUTE_HIDDEN)) {
1618 return False;
1621 return True;
1624 /****************************************************************************
1625 Special FCB or DOS processing in the case of a sharing violation.
1626 Try and find a duplicated file handle.
1627 ****************************************************************************/
1629 static NTSTATUS fcb_or_dos_open(struct smb_request *req,
1630 connection_struct *conn,
1631 files_struct *fsp_to_dup_into,
1632 const struct smb_filename *smb_fname,
1633 struct file_id id,
1634 uint16 file_pid,
1635 uint64_t vuid,
1636 uint32 access_mask,
1637 uint32 share_access,
1638 uint32 create_options)
1640 files_struct *fsp;
1642 DEBUG(5,("fcb_or_dos_open: attempting old open semantics for "
1643 "file %s.\n", smb_fname_str_dbg(smb_fname)));
1645 for(fsp = file_find_di_first(conn->sconn, id); fsp;
1646 fsp = file_find_di_next(fsp)) {
1648 DEBUG(10,("fcb_or_dos_open: checking file %s, fd = %d, "
1649 "vuid = %llu, file_pid = %u, private_options = 0x%x "
1650 "access_mask = 0x%x\n", fsp_str_dbg(fsp),
1651 fsp->fh->fd, (unsigned long long)fsp->vuid,
1652 (unsigned int)fsp->file_pid,
1653 (unsigned int)fsp->fh->private_options,
1654 (unsigned int)fsp->access_mask ));
1656 if (fsp != fsp_to_dup_into &&
1657 fsp->fh->fd != -1 &&
1658 fsp->vuid == vuid &&
1659 fsp->file_pid == file_pid &&
1660 (fsp->fh->private_options & (NTCREATEX_OPTIONS_PRIVATE_DENY_DOS |
1661 NTCREATEX_OPTIONS_PRIVATE_DENY_FCB)) &&
1662 (fsp->access_mask & FILE_WRITE_DATA) &&
1663 strequal(fsp->fsp_name->base_name, smb_fname->base_name) &&
1664 strequal(fsp->fsp_name->stream_name,
1665 smb_fname->stream_name)) {
1666 DEBUG(10,("fcb_or_dos_open: file match\n"));
1667 break;
1671 if (!fsp) {
1672 return NT_STATUS_NOT_FOUND;
1675 /* quite an insane set of semantics ... */
1676 if (is_executable(smb_fname->base_name) &&
1677 (fsp->fh->private_options & NTCREATEX_OPTIONS_PRIVATE_DENY_DOS)) {
1678 DEBUG(10,("fcb_or_dos_open: file fail due to is_executable.\n"));
1679 return NT_STATUS_INVALID_PARAMETER;
1682 /* We need to duplicate this fsp. */
1683 return dup_file_fsp(req, fsp, access_mask, share_access,
1684 create_options, fsp_to_dup_into);
1687 static void schedule_defer_open(struct share_mode_lock *lck,
1688 struct timeval request_time,
1689 struct smb_request *req)
1691 struct deferred_open_record state;
1693 /* This is a relative time, added to the absolute
1694 request_time value to get the absolute timeout time.
1695 Note that if this is the second or greater time we enter
1696 this codepath for this particular request mid then
1697 request_time is left as the absolute time of the *first*
1698 time this request mid was processed. This is what allows
1699 the request to eventually time out. */
1701 struct timeval timeout;
1703 /* Normally the smbd we asked should respond within
1704 * OPLOCK_BREAK_TIMEOUT seconds regardless of whether
1705 * the client did, give twice the timeout as a safety
1706 * measure here in case the other smbd is stuck
1707 * somewhere else. */
1709 timeout = timeval_set(OPLOCK_BREAK_TIMEOUT*2, 0);
1711 /* Nothing actually uses state.delayed_for_oplocks
1712 but it's handy to differentiate in debug messages
1713 between a 30 second delay due to oplock break, and
1714 a 1 second delay for share mode conflicts. */
1716 state.delayed_for_oplocks = True;
1717 state.async_open = false;
1718 state.id = lck->data->id;
1720 if (!request_timed_out(request_time, timeout)) {
1721 defer_open(lck, request_time, timeout, req, &state);
1725 /****************************************************************************
1726 Reschedule an open call that went asynchronous.
1727 ****************************************************************************/
1729 static void schedule_async_open(struct timeval request_time,
1730 struct smb_request *req)
1732 struct deferred_open_record state;
1733 struct timeval timeout;
1735 timeout = timeval_set(20, 0);
1737 ZERO_STRUCT(state);
1738 state.delayed_for_oplocks = false;
1739 state.async_open = true;
1741 if (!request_timed_out(request_time, timeout)) {
1742 defer_open(NULL, request_time, timeout, req, &state);
1746 /****************************************************************************
1747 Work out what access_mask to use from what the client sent us.
1748 ****************************************************************************/
1750 static NTSTATUS smbd_calculate_maximum_allowed_access(
1751 connection_struct *conn,
1752 const struct smb_filename *smb_fname,
1753 bool use_privs,
1754 uint32_t *p_access_mask)
1756 struct security_descriptor *sd;
1757 uint32_t access_granted;
1758 NTSTATUS status;
1760 if (!use_privs && (get_current_uid(conn) == (uid_t)0)) {
1761 *p_access_mask |= FILE_GENERIC_ALL;
1762 return NT_STATUS_OK;
1765 status = SMB_VFS_GET_NT_ACL(conn, smb_fname->base_name,
1766 (SECINFO_OWNER |
1767 SECINFO_GROUP |
1768 SECINFO_DACL),
1769 talloc_tos(), &sd);
1771 if (NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
1773 * File did not exist
1775 *p_access_mask = FILE_GENERIC_ALL;
1776 return NT_STATUS_OK;
1778 if (!NT_STATUS_IS_OK(status)) {
1779 DEBUG(10,("Could not get acl on file %s: %s\n",
1780 smb_fname_str_dbg(smb_fname),
1781 nt_errstr(status)));
1782 return NT_STATUS_ACCESS_DENIED;
1786 * If we can access the path to this file, by
1787 * default we have FILE_READ_ATTRIBUTES from the
1788 * containing directory. See the section:
1789 * "Algorithm to Check Access to an Existing File"
1790 * in MS-FSA.pdf.
1792 * se_file_access_check()
1793 * also takes care of owner WRITE_DAC and READ_CONTROL.
1795 status = se_file_access_check(sd,
1796 get_current_nttok(conn),
1797 use_privs,
1798 (*p_access_mask & ~FILE_READ_ATTRIBUTES),
1799 &access_granted);
1801 TALLOC_FREE(sd);
1803 if (!NT_STATUS_IS_OK(status)) {
1804 DEBUG(10, ("Access denied on file %s: "
1805 "when calculating maximum access\n",
1806 smb_fname_str_dbg(smb_fname)));
1807 return NT_STATUS_ACCESS_DENIED;
1809 *p_access_mask = (access_granted | FILE_READ_ATTRIBUTES);
1811 if (!(access_granted & DELETE_ACCESS)) {
1812 if (can_delete_file_in_directory(conn, smb_fname)) {
1813 *p_access_mask |= DELETE_ACCESS;
1817 return NT_STATUS_OK;
1820 NTSTATUS smbd_calculate_access_mask(connection_struct *conn,
1821 const struct smb_filename *smb_fname,
1822 bool use_privs,
1823 uint32_t access_mask,
1824 uint32_t *access_mask_out)
1826 NTSTATUS status;
1827 uint32_t orig_access_mask = access_mask;
1828 uint32_t rejected_share_access;
1831 * Convert GENERIC bits to specific bits.
1834 se_map_generic(&access_mask, &file_generic_mapping);
1836 /* Calculate MAXIMUM_ALLOWED_ACCESS if requested. */
1837 if (access_mask & MAXIMUM_ALLOWED_ACCESS) {
1839 status = smbd_calculate_maximum_allowed_access(
1840 conn, smb_fname, use_privs, &access_mask);
1842 if (!NT_STATUS_IS_OK(status)) {
1843 return status;
1846 access_mask &= conn->share_access;
1849 rejected_share_access = access_mask & ~(conn->share_access);
1851 if (rejected_share_access) {
1852 DEBUG(10, ("smbd_calculate_access_mask: Access denied on "
1853 "file %s: rejected by share access mask[0x%08X] "
1854 "orig[0x%08X] mapped[0x%08X] reject[0x%08X]\n",
1855 smb_fname_str_dbg(smb_fname),
1856 conn->share_access,
1857 orig_access_mask, access_mask,
1858 rejected_share_access));
1859 return NT_STATUS_ACCESS_DENIED;
1862 *access_mask_out = access_mask;
1863 return NT_STATUS_OK;
1866 /****************************************************************************
1867 Remove the deferred open entry under lock.
1868 ****************************************************************************/
1870 void remove_deferred_open_entry(struct file_id id, uint64_t mid,
1871 struct server_id pid)
1873 struct share_mode_lock *lck = get_existing_share_mode_lock(
1874 talloc_tos(), id);
1875 if (lck == NULL) {
1876 DEBUG(0, ("could not get share mode lock\n"));
1877 return;
1879 del_deferred_open_entry(lck, mid, pid);
1880 TALLOC_FREE(lck);
1883 /****************************************************************************
1884 Return true if this is a state pointer to an asynchronous create.
1885 ****************************************************************************/
1887 bool is_deferred_open_async(const void *ptr)
1889 const struct deferred_open_record *state = (const struct deferred_open_record *)ptr;
1891 return state->async_open;
1894 static bool clear_ads(uint32_t create_disposition)
1896 bool ret = false;
1898 switch (create_disposition) {
1899 case FILE_SUPERSEDE:
1900 case FILE_OVERWRITE_IF:
1901 case FILE_OVERWRITE:
1902 ret = true;
1903 break;
1904 default:
1905 break;
1907 return ret;
1910 static int disposition_to_open_flags(uint32_t create_disposition)
1912 int ret = 0;
1915 * Currently we're using FILE_SUPERSEDE as the same as
1916 * FILE_OVERWRITE_IF but they really are
1917 * different. FILE_SUPERSEDE deletes an existing file
1918 * (requiring delete access) then recreates it.
1921 switch (create_disposition) {
1922 case FILE_SUPERSEDE:
1923 case FILE_OVERWRITE_IF:
1925 * If file exists replace/overwrite. If file doesn't
1926 * exist create.
1928 ret = O_CREAT|O_TRUNC;
1929 break;
1931 case FILE_OPEN:
1933 * If file exists open. If file doesn't exist error.
1935 ret = 0;
1936 break;
1938 case FILE_OVERWRITE:
1940 * If file exists overwrite. If file doesn't exist
1941 * error.
1943 ret = O_TRUNC;
1944 break;
1946 case FILE_CREATE:
1948 * If file exists error. If file doesn't exist create.
1950 ret = O_CREAT|O_EXCL;
1951 break;
1953 case FILE_OPEN_IF:
1955 * If file exists open. If file doesn't exist create.
1957 ret = O_CREAT;
1958 break;
1960 return ret;
1963 static int calculate_open_access_flags(uint32_t access_mask,
1964 int oplock_request,
1965 uint32_t private_flags)
1967 bool need_write, need_read;
1970 * Note that we ignore the append flag as append does not
1971 * mean the same thing under DOS and Unix.
1974 need_write =
1975 ((access_mask & (FILE_WRITE_DATA | FILE_APPEND_DATA)) ||
1976 (oplock_request & FORCE_OPLOCK_BREAK_TO_NONE));
1978 if (!need_write) {
1979 return O_RDONLY;
1982 /* DENY_DOS opens are always underlying read-write on the
1983 file handle, no matter what the requested access mask
1984 says. */
1986 need_read =
1987 ((private_flags & NTCREATEX_OPTIONS_PRIVATE_DENY_DOS) ||
1988 access_mask & (FILE_READ_ATTRIBUTES|FILE_READ_DATA|
1989 FILE_READ_EA|FILE_EXECUTE));
1991 if (!need_read) {
1992 return O_WRONLY;
1994 return O_RDWR;
1997 /****************************************************************************
1998 Open a file with a share mode. Passed in an already created files_struct *.
1999 ****************************************************************************/
2001 static NTSTATUS open_file_ntcreate(connection_struct *conn,
2002 struct smb_request *req,
2003 uint32 access_mask, /* access bits (FILE_READ_DATA etc.) */
2004 uint32 share_access, /* share constants (FILE_SHARE_READ etc) */
2005 uint32 create_disposition, /* FILE_OPEN_IF etc. */
2006 uint32 create_options, /* options such as delete on close. */
2007 uint32 new_dos_attributes, /* attributes used for new file. */
2008 int oplock_request, /* internal Samba oplock codes. */
2009 /* Information (FILE_EXISTS etc.) */
2010 uint32_t private_flags, /* Samba specific flags. */
2011 int *pinfo,
2012 files_struct *fsp)
2014 struct smb_filename *smb_fname = fsp->fsp_name;
2015 int flags=0;
2016 int flags2=0;
2017 bool file_existed = VALID_STAT(smb_fname->st);
2018 bool def_acl = False;
2019 bool posix_open = False;
2020 bool new_file_created = False;
2021 bool first_open_attempt = true;
2022 NTSTATUS fsp_open = NT_STATUS_ACCESS_DENIED;
2023 mode_t new_unx_mode = (mode_t)0;
2024 mode_t unx_mode = (mode_t)0;
2025 int info;
2026 uint32 existing_dos_attributes = 0;
2027 struct timeval request_time = timeval_zero();
2028 struct share_mode_lock *lck = NULL;
2029 uint32 open_access_mask = access_mask;
2030 NTSTATUS status;
2031 char *parent_dir;
2032 SMB_STRUCT_STAT saved_stat = smb_fname->st;
2033 struct share_mode_entry *batch_entry = NULL;
2034 struct share_mode_entry *exclusive_entry = NULL;
2035 bool got_level2_oplock = false;
2036 bool got_a_none_oplock = false;
2037 struct timespec old_write_time;
2038 struct file_id id;
2040 if (conn->printer) {
2042 * Printers are handled completely differently.
2043 * Most of the passed parameters are ignored.
2046 if (pinfo) {
2047 *pinfo = FILE_WAS_CREATED;
2050 DEBUG(10, ("open_file_ntcreate: printer open fname=%s\n",
2051 smb_fname_str_dbg(smb_fname)));
2053 if (!req) {
2054 DEBUG(0,("open_file_ntcreate: printer open without "
2055 "an SMB request!\n"));
2056 return NT_STATUS_INTERNAL_ERROR;
2059 return print_spool_open(fsp, smb_fname->base_name,
2060 req->vuid);
2063 if (!parent_dirname(talloc_tos(), smb_fname->base_name, &parent_dir,
2064 NULL)) {
2065 return NT_STATUS_NO_MEMORY;
2068 if (new_dos_attributes & FILE_FLAG_POSIX_SEMANTICS) {
2069 posix_open = True;
2070 unx_mode = (mode_t)(new_dos_attributes & ~FILE_FLAG_POSIX_SEMANTICS);
2071 new_dos_attributes = 0;
2072 } else {
2073 /* Windows allows a new file to be created and
2074 silently removes a FILE_ATTRIBUTE_DIRECTORY
2075 sent by the client. Do the same. */
2077 new_dos_attributes &= ~FILE_ATTRIBUTE_DIRECTORY;
2079 /* We add FILE_ATTRIBUTE_ARCHIVE to this as this mode is only used if the file is
2080 * created new. */
2081 unx_mode = unix_mode(conn, new_dos_attributes | FILE_ATTRIBUTE_ARCHIVE,
2082 smb_fname, parent_dir);
2085 DEBUG(10, ("open_file_ntcreate: fname=%s, dos_attrs=0x%x "
2086 "access_mask=0x%x share_access=0x%x "
2087 "create_disposition = 0x%x create_options=0x%x "
2088 "unix mode=0%o oplock_request=%d private_flags = 0x%x\n",
2089 smb_fname_str_dbg(smb_fname), new_dos_attributes,
2090 access_mask, share_access, create_disposition,
2091 create_options, (unsigned int)unx_mode, oplock_request,
2092 (unsigned int)private_flags));
2094 if ((req == NULL) && ((oplock_request & INTERNAL_OPEN_ONLY) == 0)) {
2095 DEBUG(0, ("No smb request but not an internal only open!\n"));
2096 return NT_STATUS_INTERNAL_ERROR;
2100 * Only non-internal opens can be deferred at all
2103 if (req) {
2104 void *ptr;
2105 if (get_deferred_open_message_state(req,
2106 &request_time,
2107 &ptr)) {
2108 /* Remember the absolute time of the original
2109 request with this mid. We'll use it later to
2110 see if this has timed out. */
2112 /* If it was an async create retry, the file
2113 didn't exist. */
2115 if (is_deferred_open_async(ptr)) {
2116 SET_STAT_INVALID(smb_fname->st);
2117 file_existed = false;
2118 } else {
2119 struct deferred_open_record *state = (struct deferred_open_record *)ptr;
2120 /* Remove the deferred open entry under lock. */
2121 remove_deferred_open_entry(
2122 state->id, req->mid,
2123 messaging_server_id(req->sconn->msg_ctx));
2126 /* Ensure we don't reprocess this message. */
2127 remove_deferred_open_message_smb(req->sconn, req->mid);
2129 first_open_attempt = false;
2133 if (!posix_open) {
2134 new_dos_attributes &= SAMBA_ATTRIBUTES_MASK;
2135 if (file_existed) {
2136 existing_dos_attributes = dos_mode(conn, smb_fname);
2140 /* ignore any oplock requests if oplocks are disabled */
2141 if (!lp_oplocks(SNUM(conn)) ||
2142 IS_VETO_OPLOCK_PATH(conn, smb_fname->base_name)) {
2143 /* Mask off everything except the private Samba bits. */
2144 oplock_request &= SAMBA_PRIVATE_OPLOCK_MASK;
2147 /* this is for OS/2 long file names - say we don't support them */
2148 if (!lp_posix_pathnames() && strstr(smb_fname->base_name,".+,;=[].")) {
2149 /* OS/2 Workplace shell fix may be main code stream in a later
2150 * release. */
2151 DEBUG(5,("open_file_ntcreate: OS/2 long filenames are not "
2152 "supported.\n"));
2153 if (use_nt_status()) {
2154 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
2156 return NT_STATUS_DOS(ERRDOS, ERRcannotopen);
2159 switch( create_disposition ) {
2160 case FILE_OPEN:
2161 /* If file exists open. If file doesn't exist error. */
2162 if (!file_existed) {
2163 DEBUG(5,("open_file_ntcreate: FILE_OPEN "
2164 "requested for file %s and file "
2165 "doesn't exist.\n",
2166 smb_fname_str_dbg(smb_fname)));
2167 errno = ENOENT;
2168 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
2170 break;
2172 case FILE_OVERWRITE:
2173 /* If file exists overwrite. If file doesn't exist
2174 * error. */
2175 if (!file_existed) {
2176 DEBUG(5,("open_file_ntcreate: FILE_OVERWRITE "
2177 "requested for file %s and file "
2178 "doesn't exist.\n",
2179 smb_fname_str_dbg(smb_fname) ));
2180 errno = ENOENT;
2181 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
2183 break;
2185 case FILE_CREATE:
2186 /* If file exists error. If file doesn't exist
2187 * create. */
2188 if (file_existed) {
2189 DEBUG(5,("open_file_ntcreate: FILE_CREATE "
2190 "requested for file %s and file "
2191 "already exists.\n",
2192 smb_fname_str_dbg(smb_fname)));
2193 if (S_ISDIR(smb_fname->st.st_ex_mode)) {
2194 errno = EISDIR;
2195 } else {
2196 errno = EEXIST;
2198 return map_nt_error_from_unix(errno);
2200 break;
2202 case FILE_SUPERSEDE:
2203 case FILE_OVERWRITE_IF:
2204 case FILE_OPEN_IF:
2205 break;
2206 default:
2207 return NT_STATUS_INVALID_PARAMETER;
2210 flags2 = disposition_to_open_flags(create_disposition);
2212 /* We only care about matching attributes on file exists and
2213 * overwrite. */
2215 if (!posix_open && file_existed &&
2216 ((create_disposition == FILE_OVERWRITE) ||
2217 (create_disposition == FILE_OVERWRITE_IF))) {
2218 if (!open_match_attributes(conn, existing_dos_attributes,
2219 new_dos_attributes,
2220 smb_fname->st.st_ex_mode,
2221 unx_mode, &new_unx_mode)) {
2222 DEBUG(5,("open_file_ntcreate: attributes missmatch "
2223 "for file %s (%x %x) (0%o, 0%o)\n",
2224 smb_fname_str_dbg(smb_fname),
2225 existing_dos_attributes,
2226 new_dos_attributes,
2227 (unsigned int)smb_fname->st.st_ex_mode,
2228 (unsigned int)unx_mode ));
2229 errno = EACCES;
2230 return NT_STATUS_ACCESS_DENIED;
2234 status = smbd_calculate_access_mask(conn, smb_fname,
2235 false,
2236 access_mask,
2237 &access_mask);
2238 if (!NT_STATUS_IS_OK(status)) {
2239 DEBUG(10, ("open_file_ntcreate: smbd_calculate_access_mask "
2240 "on file %s returned %s\n",
2241 smb_fname_str_dbg(smb_fname), nt_errstr(status)));
2242 return status;
2245 open_access_mask = access_mask;
2247 if ((flags2 & O_TRUNC) || (oplock_request & FORCE_OPLOCK_BREAK_TO_NONE)) {
2248 open_access_mask |= FILE_WRITE_DATA; /* This will cause oplock breaks. */
2251 DEBUG(10, ("open_file_ntcreate: fname=%s, after mapping "
2252 "access_mask=0x%x\n", smb_fname_str_dbg(smb_fname),
2253 access_mask));
2256 * Note that we ignore the append flag as append does not
2257 * mean the same thing under DOS and Unix.
2260 flags = calculate_open_access_flags(access_mask, oplock_request,
2261 private_flags);
2264 * Currently we only look at FILE_WRITE_THROUGH for create options.
2267 #if defined(O_SYNC)
2268 if ((create_options & FILE_WRITE_THROUGH) && lp_strict_sync(SNUM(conn))) {
2269 flags2 |= O_SYNC;
2271 #endif /* O_SYNC */
2273 if (posix_open && (access_mask & FILE_APPEND_DATA)) {
2274 flags2 |= O_APPEND;
2277 if (!posix_open && !CAN_WRITE(conn)) {
2279 * We should really return a permission denied error if either
2280 * O_CREAT or O_TRUNC are set, but for compatibility with
2281 * older versions of Samba we just AND them out.
2283 flags2 &= ~(O_CREAT|O_TRUNC);
2286 if (first_open_attempt && lp_kernel_oplocks(SNUM(conn))) {
2288 * With kernel oplocks the open breaking an oplock
2289 * blocks until the oplock holder has given up the
2290 * oplock or closed the file. We prevent this by first
2291 * trying to open the file with O_NONBLOCK (see "man
2292 * fcntl" on Linux). For the second try, triggered by
2293 * an oplock break response, we do not need this
2294 * anymore.
2296 * This is true under the assumption that only Samba
2297 * requests kernel oplocks. Once someone else like
2298 * NFSv4 starts to use that API, we will have to
2299 * modify this by communicating with the NFSv4 server.
2301 flags2 |= O_NONBLOCK;
2305 * Ensure we can't write on a read-only share or file.
2308 if (flags != O_RDONLY && file_existed &&
2309 (!CAN_WRITE(conn) || IS_DOS_READONLY(existing_dos_attributes))) {
2310 DEBUG(5,("open_file_ntcreate: write access requested for "
2311 "file %s on read only %s\n",
2312 smb_fname_str_dbg(smb_fname),
2313 !CAN_WRITE(conn) ? "share" : "file" ));
2314 errno = EACCES;
2315 return NT_STATUS_ACCESS_DENIED;
2318 fsp->file_id = vfs_file_id_from_sbuf(conn, &smb_fname->st);
2319 fsp->share_access = share_access;
2320 fsp->fh->private_options = private_flags;
2321 fsp->access_mask = open_access_mask; /* We change this to the
2322 * requested access_mask after
2323 * the open is done. */
2324 fsp->posix_open = posix_open;
2326 /* Ensure no SAMBA_PRIVATE bits can be set. */
2327 fsp->oplock_type = (oplock_request & ~SAMBA_PRIVATE_OPLOCK_MASK);
2329 if (timeval_is_zero(&request_time)) {
2330 request_time = fsp->open_time;
2334 * Ensure we pay attention to default ACLs on directories if required.
2337 if ((flags2 & O_CREAT) && lp_inherit_acls(SNUM(conn)) &&
2338 (def_acl = directory_has_default_acl(conn, parent_dir))) {
2339 unx_mode = (0777 & lp_create_mask(SNUM(conn)));
2342 DEBUG(4,("calling open_file with flags=0x%X flags2=0x%X mode=0%o, "
2343 "access_mask = 0x%x, open_access_mask = 0x%x\n",
2344 (unsigned int)flags, (unsigned int)flags2,
2345 (unsigned int)unx_mode, (unsigned int)access_mask,
2346 (unsigned int)open_access_mask));
2348 fsp_open = open_file(fsp, conn, req, parent_dir,
2349 flags|flags2, unx_mode, access_mask,
2350 open_access_mask, &new_file_created);
2352 if (NT_STATUS_EQUAL(fsp_open, NT_STATUS_NETWORK_BUSY)) {
2353 struct deferred_open_record state;
2356 * EWOULDBLOCK/EAGAIN maps to NETWORK_BUSY.
2358 if (file_existed && S_ISFIFO(fsp->fsp_name->st.st_ex_mode)) {
2359 DEBUG(10, ("FIFO busy\n"));
2360 return NT_STATUS_NETWORK_BUSY;
2362 if (req == NULL) {
2363 DEBUG(10, ("Internal open busy\n"));
2364 return NT_STATUS_NETWORK_BUSY;
2368 * From here on we assume this is an oplock break triggered
2371 lck = get_existing_share_mode_lock(talloc_tos(), fsp->file_id);
2372 if (lck == NULL) {
2373 state.delayed_for_oplocks = false;
2374 state.async_open = false;
2375 state.id = fsp->file_id;
2376 defer_open(NULL, request_time, timeval_set(0, 0),
2377 req, &state);
2378 DEBUG(10, ("No share mode lock found after "
2379 "EWOULDBLOCK, retrying sync\n"));
2380 return NT_STATUS_SHARING_VIOLATION;
2383 find_oplock_types(fsp, 0, lck, &batch_entry, &exclusive_entry,
2384 &got_level2_oplock, &got_a_none_oplock);
2386 if (delay_for_batch_oplocks(fsp, req->mid, 0, batch_entry) ||
2387 delay_for_exclusive_oplocks(fsp, req->mid, 0,
2388 exclusive_entry)) {
2389 schedule_defer_open(lck, request_time, req);
2390 TALLOC_FREE(lck);
2391 DEBUG(10, ("Sent oplock break request to kernel "
2392 "oplock holder\n"));
2393 return NT_STATUS_SHARING_VIOLATION;
2397 * No oplock from Samba around. Immediately retry with
2398 * a blocking open.
2400 state.delayed_for_oplocks = false;
2401 state.async_open = false;
2402 state.id = lck->data->id;
2403 defer_open(lck, request_time, timeval_set(0, 0), req, &state);
2404 TALLOC_FREE(lck);
2405 DEBUG(10, ("No Samba oplock around after EWOULDBLOCK. "
2406 "Retrying sync\n"));
2407 return NT_STATUS_SHARING_VIOLATION;
2410 if (!NT_STATUS_IS_OK(fsp_open)) {
2411 if (NT_STATUS_EQUAL(fsp_open, NT_STATUS_RETRY)) {
2412 schedule_async_open(request_time, req);
2414 TALLOC_FREE(lck);
2415 return fsp_open;
2418 if (file_existed && !check_same_dev_ino(&saved_stat, &smb_fname->st)) {
2420 * The file did exist, but some other (local or NFS)
2421 * process either renamed/unlinked and re-created the
2422 * file with different dev/ino after we walked the path,
2423 * but before we did the open. We could retry the
2424 * open but it's a rare enough case it's easier to
2425 * just fail the open to prevent creating any problems
2426 * in the open file db having the wrong dev/ino key.
2428 TALLOC_FREE(lck);
2429 fd_close(fsp);
2430 DEBUG(1,("open_file_ntcreate: file %s - dev/ino mismatch. "
2431 "Old (dev=0x%llu, ino =0x%llu). "
2432 "New (dev=0x%llu, ino=0x%llu). Failing open "
2433 " with NT_STATUS_ACCESS_DENIED.\n",
2434 smb_fname_str_dbg(smb_fname),
2435 (unsigned long long)saved_stat.st_ex_dev,
2436 (unsigned long long)saved_stat.st_ex_ino,
2437 (unsigned long long)smb_fname->st.st_ex_dev,
2438 (unsigned long long)smb_fname->st.st_ex_ino));
2439 return NT_STATUS_ACCESS_DENIED;
2442 old_write_time = smb_fname->st.st_ex_mtime;
2445 * Deal with the race condition where two smbd's detect the
2446 * file doesn't exist and do the create at the same time. One
2447 * of them will win and set a share mode, the other (ie. this
2448 * one) should check if the requested share mode for this
2449 * create is allowed.
2453 * Now the file exists and fsp is successfully opened,
2454 * fsp->dev and fsp->inode are valid and should replace the
2455 * dev=0,inode=0 from a non existent file. Spotted by
2456 * Nadav Danieli <nadavd@exanet.com>. JRA.
2459 id = fsp->file_id;
2461 lck = get_share_mode_lock(talloc_tos(), id,
2462 conn->connectpath,
2463 smb_fname, &old_write_time);
2465 if (lck == NULL) {
2466 DEBUG(0, ("open_file_ntcreate: Could not get share "
2467 "mode lock for %s\n",
2468 smb_fname_str_dbg(smb_fname)));
2469 fd_close(fsp);
2470 return NT_STATUS_SHARING_VIOLATION;
2473 /* Get the types we need to examine. */
2474 find_oplock_types(fsp,
2475 oplock_request,
2476 lck,
2477 &batch_entry,
2478 &exclusive_entry,
2479 &got_level2_oplock,
2480 &got_a_none_oplock);
2482 /* First pass - send break only on batch oplocks. */
2483 if ((req != NULL) &&
2484 delay_for_batch_oplocks(fsp,
2485 req->mid,
2486 oplock_request,
2487 batch_entry)) {
2488 schedule_defer_open(lck, request_time, req);
2489 TALLOC_FREE(lck);
2490 fd_close(fsp);
2491 return NT_STATUS_SHARING_VIOLATION;
2494 status = open_mode_check(conn, lck, fsp->name_hash,
2495 access_mask, share_access,
2496 create_options, &file_existed);
2498 if (NT_STATUS_IS_OK(status)) {
2499 /* We might be going to allow this open. Check oplock
2500 * status again. */
2501 /* Second pass - send break for both batch or
2502 * exclusive oplocks. */
2503 if ((req != NULL) &&
2504 delay_for_exclusive_oplocks(
2505 fsp,
2506 req->mid,
2507 oplock_request,
2508 exclusive_entry)) {
2509 schedule_defer_open(lck, request_time, req);
2510 TALLOC_FREE(lck);
2511 fd_close(fsp);
2512 return NT_STATUS_SHARING_VIOLATION;
2516 if (NT_STATUS_EQUAL(status, NT_STATUS_DELETE_PENDING)) {
2517 /* DELETE_PENDING is not deferred for a second */
2518 TALLOC_FREE(lck);
2519 fd_close(fsp);
2520 return status;
2523 if (!NT_STATUS_IS_OK(status)) {
2524 uint32 can_access_mask;
2525 bool can_access = True;
2527 SMB_ASSERT(NT_STATUS_EQUAL(status, NT_STATUS_SHARING_VIOLATION));
2529 /* Check if this can be done with the deny_dos and fcb
2530 * calls. */
2531 if (private_flags &
2532 (NTCREATEX_OPTIONS_PRIVATE_DENY_DOS|
2533 NTCREATEX_OPTIONS_PRIVATE_DENY_FCB)) {
2534 if (req == NULL) {
2535 DEBUG(0, ("DOS open without an SMB "
2536 "request!\n"));
2537 TALLOC_FREE(lck);
2538 fd_close(fsp);
2539 return NT_STATUS_INTERNAL_ERROR;
2542 /* Use the client requested access mask here,
2543 * not the one we open with. */
2544 status = fcb_or_dos_open(req,
2545 conn,
2546 fsp,
2547 smb_fname,
2549 req->smbpid,
2550 req->vuid,
2551 access_mask,
2552 share_access,
2553 create_options);
2555 if (NT_STATUS_IS_OK(status)) {
2556 TALLOC_FREE(lck);
2557 if (pinfo) {
2558 *pinfo = FILE_WAS_OPENED;
2560 return NT_STATUS_OK;
2565 * This next line is a subtlety we need for
2566 * MS-Access. If a file open will fail due to share
2567 * permissions and also for security (access) reasons,
2568 * we need to return the access failed error, not the
2569 * share error. We can't open the file due to kernel
2570 * oplock deadlock (it's possible we failed above on
2571 * the open_mode_check()) so use a userspace check.
2574 if (flags & O_RDWR) {
2575 can_access_mask = FILE_READ_DATA|FILE_WRITE_DATA;
2576 } else if (flags & O_WRONLY) {
2577 can_access_mask = FILE_WRITE_DATA;
2578 } else {
2579 can_access_mask = FILE_READ_DATA;
2582 if (((can_access_mask & FILE_WRITE_DATA) &&
2583 !CAN_WRITE(conn)) ||
2584 !NT_STATUS_IS_OK(smbd_check_access_rights(conn,
2585 smb_fname,
2586 false,
2587 can_access_mask))) {
2588 can_access = False;
2592 * If we're returning a share violation, ensure we
2593 * cope with the braindead 1 second delay.
2596 if (!(oplock_request & INTERNAL_OPEN_ONLY) &&
2597 lp_defer_sharing_violations()) {
2598 struct timeval timeout;
2599 struct deferred_open_record state;
2600 int timeout_usecs;
2602 /* this is a hack to speed up torture tests
2603 in 'make test' */
2604 timeout_usecs = lp_parm_int(SNUM(conn),
2605 "smbd","sharedelay",
2606 SHARING_VIOLATION_USEC_WAIT);
2608 /* This is a relative time, added to the absolute
2609 request_time value to get the absolute timeout time.
2610 Note that if this is the second or greater time we enter
2611 this codepath for this particular request mid then
2612 request_time is left as the absolute time of the *first*
2613 time this request mid was processed. This is what allows
2614 the request to eventually time out. */
2616 timeout = timeval_set(0, timeout_usecs);
2618 /* Nothing actually uses state.delayed_for_oplocks
2619 but it's handy to differentiate in debug messages
2620 between a 30 second delay due to oplock break, and
2621 a 1 second delay for share mode conflicts. */
2623 state.delayed_for_oplocks = False;
2624 state.async_open = false;
2625 state.id = id;
2627 if ((req != NULL)
2628 && !request_timed_out(request_time,
2629 timeout)) {
2630 defer_open(lck, request_time, timeout,
2631 req, &state);
2635 TALLOC_FREE(lck);
2636 fd_close(fsp);
2637 if (can_access) {
2639 * We have detected a sharing violation here
2640 * so return the correct error code
2642 status = NT_STATUS_SHARING_VIOLATION;
2643 } else {
2644 status = NT_STATUS_ACCESS_DENIED;
2646 return status;
2649 grant_fsp_oplock_type(fsp,
2650 oplock_request,
2651 got_level2_oplock,
2652 got_a_none_oplock);
2655 * We have the share entry *locked*.....
2658 /* Delete streams if create_disposition requires it */
2659 if (!new_file_created && clear_ads(create_disposition) &&
2660 !is_ntfs_stream_smb_fname(smb_fname)) {
2661 status = delete_all_streams(conn, smb_fname->base_name);
2662 if (!NT_STATUS_IS_OK(status)) {
2663 TALLOC_FREE(lck);
2664 fd_close(fsp);
2665 return status;
2669 /* note that we ignore failure for the following. It is
2670 basically a hack for NFS, and NFS will never set one of
2671 these only read them. Nobody but Samba can ever set a deny
2672 mode and we have already checked our more authoritative
2673 locking database for permission to set this deny mode. If
2674 the kernel refuses the operations then the kernel is wrong.
2675 note that GPFS supports it as well - jmcd */
2677 if (fsp->fh->fd != -1 && lp_kernel_share_modes(SNUM(conn))) {
2678 int ret_flock;
2679 ret_flock = SMB_VFS_KERNEL_FLOCK(fsp, share_access, access_mask);
2680 if(ret_flock == -1 ){
2682 TALLOC_FREE(lck);
2683 fd_close(fsp);
2685 return NT_STATUS_SHARING_VIOLATION;
2690 * At this point onwards, we can guarantee that the share entry
2691 * is locked, whether we created the file or not, and that the
2692 * deny mode is compatible with all current opens.
2696 * According to Samba4, SEC_FILE_READ_ATTRIBUTE is always granted,
2697 * but we don't have to store this - just ignore it on access check.
2699 if (conn->sconn->using_smb2) {
2701 * SMB2 doesn't return it (according to Microsoft tests).
2702 * Test Case: TestSuite_ScenarioNo009GrantedAccessTestS0
2703 * File created with access = 0x7 (Read, Write, Delete)
2704 * Query Info on file returns 0x87 (Read, Write, Delete, Read Attributes)
2706 fsp->access_mask = access_mask;
2707 } else {
2708 /* But SMB1 does. */
2709 fsp->access_mask = access_mask | FILE_READ_ATTRIBUTES;
2712 if (file_existed) {
2713 /* stat opens on existing files don't get oplocks. */
2714 if (is_stat_open(open_access_mask)) {
2715 fsp->oplock_type = NO_OPLOCK;
2719 if (new_file_created) {
2720 info = FILE_WAS_CREATED;
2721 } else {
2722 if (flags2 & O_TRUNC) {
2723 info = FILE_WAS_OVERWRITTEN;
2724 } else {
2725 info = FILE_WAS_OPENED;
2729 if (pinfo) {
2730 *pinfo = info;
2734 * Setup the oplock info in both the shared memory and
2735 * file structs.
2738 status = set_file_oplock(fsp, fsp->oplock_type);
2739 if (!NT_STATUS_IS_OK(status)) {
2741 * Could not get the kernel oplock or there are byte-range
2742 * locks on the file.
2744 fsp->oplock_type = NO_OPLOCK;
2747 set_share_mode(lck, fsp, get_current_uid(conn),
2748 req ? req->mid : 0,
2749 fsp->oplock_type);
2751 /* Handle strange delete on close create semantics. */
2752 if (create_options & FILE_DELETE_ON_CLOSE) {
2754 status = can_set_delete_on_close(fsp, new_dos_attributes);
2756 if (!NT_STATUS_IS_OK(status)) {
2757 /* Remember to delete the mode we just added. */
2758 del_share_mode(lck, fsp);
2759 TALLOC_FREE(lck);
2760 fd_close(fsp);
2761 return status;
2763 /* Note that here we set the *inital* delete on close flag,
2764 not the regular one. The magic gets handled in close. */
2765 fsp->initial_delete_on_close = True;
2768 if (info != FILE_WAS_OPENED) {
2769 /* Files should be initially set as archive */
2770 if (lp_map_archive(SNUM(conn)) ||
2771 lp_store_dos_attributes(SNUM(conn))) {
2772 if (!posix_open) {
2773 if (file_set_dosmode(conn, smb_fname,
2774 new_dos_attributes | FILE_ATTRIBUTE_ARCHIVE,
2775 parent_dir, true) == 0) {
2776 unx_mode = smb_fname->st.st_ex_mode;
2782 /* Determine sparse flag. */
2783 if (posix_open) {
2784 /* POSIX opens are sparse by default. */
2785 fsp->is_sparse = true;
2786 } else {
2787 fsp->is_sparse = (file_existed &&
2788 (existing_dos_attributes & FILE_ATTRIBUTE_SPARSE));
2792 * Take care of inherited ACLs on created files - if default ACL not
2793 * selected.
2796 if (!posix_open && new_file_created && !def_acl) {
2798 int saved_errno = errno; /* We might get ENOSYS in the next
2799 * call.. */
2801 if (SMB_VFS_FCHMOD_ACL(fsp, unx_mode) == -1 &&
2802 errno == ENOSYS) {
2803 errno = saved_errno; /* Ignore ENOSYS */
2806 } else if (new_unx_mode) {
2808 int ret = -1;
2810 /* Attributes need changing. File already existed. */
2813 int saved_errno = errno; /* We might get ENOSYS in the
2814 * next call.. */
2815 ret = SMB_VFS_FCHMOD_ACL(fsp, new_unx_mode);
2817 if (ret == -1 && errno == ENOSYS) {
2818 errno = saved_errno; /* Ignore ENOSYS */
2819 } else {
2820 DEBUG(5, ("open_file_ntcreate: reset "
2821 "attributes of file %s to 0%o\n",
2822 smb_fname_str_dbg(smb_fname),
2823 (unsigned int)new_unx_mode));
2824 ret = 0; /* Don't do the fchmod below. */
2828 if ((ret == -1) &&
2829 (SMB_VFS_FCHMOD(fsp, new_unx_mode) == -1))
2830 DEBUG(5, ("open_file_ntcreate: failed to reset "
2831 "attributes of file %s to 0%o\n",
2832 smb_fname_str_dbg(smb_fname),
2833 (unsigned int)new_unx_mode));
2836 /* If this is a successful open, we must remove any deferred open
2837 * records. */
2838 if (req != NULL) {
2839 del_deferred_open_entry(lck, req->mid,
2840 messaging_server_id(req->sconn->msg_ctx));
2842 TALLOC_FREE(lck);
2844 return NT_STATUS_OK;
2848 /****************************************************************************
2849 Open a file for for write to ensure that we can fchmod it.
2850 ****************************************************************************/
2852 NTSTATUS open_file_fchmod(connection_struct *conn,
2853 struct smb_filename *smb_fname,
2854 files_struct **result)
2856 if (!VALID_STAT(smb_fname->st)) {
2857 return NT_STATUS_INVALID_PARAMETER;
2860 return SMB_VFS_CREATE_FILE(
2861 conn, /* conn */
2862 NULL, /* req */
2863 0, /* root_dir_fid */
2864 smb_fname, /* fname */
2865 FILE_WRITE_DATA, /* access_mask */
2866 (FILE_SHARE_READ | FILE_SHARE_WRITE | /* share_access */
2867 FILE_SHARE_DELETE),
2868 FILE_OPEN, /* create_disposition*/
2869 0, /* create_options */
2870 0, /* file_attributes */
2871 INTERNAL_OPEN_ONLY, /* oplock_request */
2872 0, /* allocation_size */
2873 0, /* private_flags */
2874 NULL, /* sd */
2875 NULL, /* ea_list */
2876 result, /* result */
2877 NULL); /* pinfo */
2880 static NTSTATUS mkdir_internal(connection_struct *conn,
2881 struct smb_filename *smb_dname,
2882 uint32 file_attributes)
2884 mode_t mode;
2885 char *parent_dir = NULL;
2886 NTSTATUS status;
2887 bool posix_open = false;
2888 bool need_re_stat = false;
2889 uint32_t access_mask = SEC_DIR_ADD_SUBDIR;
2891 if (!CAN_WRITE(conn) || (access_mask & ~(conn->share_access))) {
2892 DEBUG(5,("mkdir_internal: failing share access "
2893 "%s\n", lp_servicename(talloc_tos(), SNUM(conn))));
2894 return NT_STATUS_ACCESS_DENIED;
2897 if (!parent_dirname(talloc_tos(), smb_dname->base_name, &parent_dir,
2898 NULL)) {
2899 return NT_STATUS_NO_MEMORY;
2902 if (file_attributes & FILE_FLAG_POSIX_SEMANTICS) {
2903 posix_open = true;
2904 mode = (mode_t)(file_attributes & ~FILE_FLAG_POSIX_SEMANTICS);
2905 } else {
2906 mode = unix_mode(conn, FILE_ATTRIBUTE_DIRECTORY, smb_dname, parent_dir);
2909 status = check_parent_access(conn,
2910 smb_dname,
2911 access_mask);
2912 if(!NT_STATUS_IS_OK(status)) {
2913 DEBUG(5,("mkdir_internal: check_parent_access "
2914 "on directory %s for path %s returned %s\n",
2915 parent_dir,
2916 smb_dname->base_name,
2917 nt_errstr(status) ));
2918 return status;
2921 if (SMB_VFS_MKDIR(conn, smb_dname->base_name, mode) != 0) {
2922 return map_nt_error_from_unix(errno);
2925 /* Ensure we're checking for a symlink here.... */
2926 /* We don't want to get caught by a symlink racer. */
2928 if (SMB_VFS_LSTAT(conn, smb_dname) == -1) {
2929 DEBUG(2, ("Could not stat directory '%s' just created: %s\n",
2930 smb_fname_str_dbg(smb_dname), strerror(errno)));
2931 return map_nt_error_from_unix(errno);
2934 if (!S_ISDIR(smb_dname->st.st_ex_mode)) {
2935 DEBUG(0, ("Directory '%s' just created is not a directory !\n",
2936 smb_fname_str_dbg(smb_dname)));
2937 return NT_STATUS_NOT_A_DIRECTORY;
2940 if (lp_store_dos_attributes(SNUM(conn))) {
2941 if (!posix_open) {
2942 file_set_dosmode(conn, smb_dname,
2943 file_attributes | FILE_ATTRIBUTE_DIRECTORY,
2944 parent_dir, true);
2948 if (lp_inherit_perms(SNUM(conn))) {
2949 inherit_access_posix_acl(conn, parent_dir,
2950 smb_dname->base_name, mode);
2951 need_re_stat = true;
2954 if (!posix_open) {
2956 * Check if high bits should have been set,
2957 * then (if bits are missing): add them.
2958 * Consider bits automagically set by UNIX, i.e. SGID bit from parent
2959 * dir.
2961 if ((mode & ~(S_IRWXU|S_IRWXG|S_IRWXO)) &&
2962 (mode & ~smb_dname->st.st_ex_mode)) {
2963 SMB_VFS_CHMOD(conn, smb_dname->base_name,
2964 (smb_dname->st.st_ex_mode |
2965 (mode & ~smb_dname->st.st_ex_mode)));
2966 need_re_stat = true;
2970 /* Change the owner if required. */
2971 if (lp_inherit_owner(SNUM(conn))) {
2972 change_dir_owner_to_parent(conn, parent_dir,
2973 smb_dname->base_name,
2974 &smb_dname->st);
2975 need_re_stat = true;
2978 if (need_re_stat) {
2979 if (SMB_VFS_LSTAT(conn, smb_dname) == -1) {
2980 DEBUG(2, ("Could not stat directory '%s' just created: %s\n",
2981 smb_fname_str_dbg(smb_dname), strerror(errno)));
2982 return map_nt_error_from_unix(errno);
2986 notify_fname(conn, NOTIFY_ACTION_ADDED, FILE_NOTIFY_CHANGE_DIR_NAME,
2987 smb_dname->base_name);
2989 return NT_STATUS_OK;
2992 /****************************************************************************
2993 Open a directory from an NT SMB call.
2994 ****************************************************************************/
2996 static NTSTATUS open_directory(connection_struct *conn,
2997 struct smb_request *req,
2998 struct smb_filename *smb_dname,
2999 uint32 access_mask,
3000 uint32 share_access,
3001 uint32 create_disposition,
3002 uint32 create_options,
3003 uint32 file_attributes,
3004 int *pinfo,
3005 files_struct **result)
3007 files_struct *fsp = NULL;
3008 bool dir_existed = VALID_STAT(smb_dname->st) ? True : False;
3009 struct share_mode_lock *lck = NULL;
3010 NTSTATUS status;
3011 struct timespec mtimespec;
3012 int info = 0;
3014 if (is_ntfs_stream_smb_fname(smb_dname)) {
3015 DEBUG(2, ("open_directory: %s is a stream name!\n",
3016 smb_fname_str_dbg(smb_dname)));
3017 return NT_STATUS_NOT_A_DIRECTORY;
3020 if (!(file_attributes & FILE_FLAG_POSIX_SEMANTICS)) {
3021 /* Ensure we have a directory attribute. */
3022 file_attributes |= FILE_ATTRIBUTE_DIRECTORY;
3025 DEBUG(5,("open_directory: opening directory %s, access_mask = 0x%x, "
3026 "share_access = 0x%x create_options = 0x%x, "
3027 "create_disposition = 0x%x, file_attributes = 0x%x\n",
3028 smb_fname_str_dbg(smb_dname),
3029 (unsigned int)access_mask,
3030 (unsigned int)share_access,
3031 (unsigned int)create_options,
3032 (unsigned int)create_disposition,
3033 (unsigned int)file_attributes));
3035 status = smbd_calculate_access_mask(conn, smb_dname, false,
3036 access_mask, &access_mask);
3037 if (!NT_STATUS_IS_OK(status)) {
3038 DEBUG(10, ("open_directory: smbd_calculate_access_mask "
3039 "on file %s returned %s\n",
3040 smb_fname_str_dbg(smb_dname),
3041 nt_errstr(status)));
3042 return status;
3045 if ((access_mask & SEC_FLAG_SYSTEM_SECURITY) &&
3046 !security_token_has_privilege(get_current_nttok(conn),
3047 SEC_PRIV_SECURITY)) {
3048 DEBUG(10, ("open_directory: open on %s "
3049 "failed - SEC_FLAG_SYSTEM_SECURITY denied.\n",
3050 smb_fname_str_dbg(smb_dname)));
3051 return NT_STATUS_PRIVILEGE_NOT_HELD;
3054 switch( create_disposition ) {
3055 case FILE_OPEN:
3057 if (!dir_existed) {
3058 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3061 info = FILE_WAS_OPENED;
3062 break;
3064 case FILE_CREATE:
3066 /* If directory exists error. If directory doesn't
3067 * exist create. */
3069 if (dir_existed) {
3070 status = NT_STATUS_OBJECT_NAME_COLLISION;
3071 DEBUG(2, ("open_directory: unable to create "
3072 "%s. Error was %s\n",
3073 smb_fname_str_dbg(smb_dname),
3074 nt_errstr(status)));
3075 return status;
3078 status = mkdir_internal(conn, smb_dname,
3079 file_attributes);
3081 if (!NT_STATUS_IS_OK(status)) {
3082 DEBUG(2, ("open_directory: unable to create "
3083 "%s. Error was %s\n",
3084 smb_fname_str_dbg(smb_dname),
3085 nt_errstr(status)));
3086 return status;
3089 info = FILE_WAS_CREATED;
3090 break;
3092 case FILE_OPEN_IF:
3094 * If directory exists open. If directory doesn't
3095 * exist create.
3098 if (dir_existed) {
3099 status = NT_STATUS_OK;
3100 info = FILE_WAS_OPENED;
3101 } else {
3102 status = mkdir_internal(conn, smb_dname,
3103 file_attributes);
3105 if (NT_STATUS_IS_OK(status)) {
3106 info = FILE_WAS_CREATED;
3107 } else {
3108 /* Cope with create race. */
3109 if (!NT_STATUS_EQUAL(status,
3110 NT_STATUS_OBJECT_NAME_COLLISION)) {
3111 DEBUG(2, ("open_directory: unable to create "
3112 "%s. Error was %s\n",
3113 smb_fname_str_dbg(smb_dname),
3114 nt_errstr(status)));
3115 return status;
3117 info = FILE_WAS_OPENED;
3121 break;
3123 case FILE_SUPERSEDE:
3124 case FILE_OVERWRITE:
3125 case FILE_OVERWRITE_IF:
3126 default:
3127 DEBUG(5,("open_directory: invalid create_disposition "
3128 "0x%x for directory %s\n",
3129 (unsigned int)create_disposition,
3130 smb_fname_str_dbg(smb_dname)));
3131 return NT_STATUS_INVALID_PARAMETER;
3134 if(!S_ISDIR(smb_dname->st.st_ex_mode)) {
3135 DEBUG(5,("open_directory: %s is not a directory !\n",
3136 smb_fname_str_dbg(smb_dname)));
3137 return NT_STATUS_NOT_A_DIRECTORY;
3140 if (info == FILE_WAS_OPENED) {
3141 status = smbd_check_access_rights(conn,
3142 smb_dname,
3143 false,
3144 access_mask);
3145 if (!NT_STATUS_IS_OK(status)) {
3146 DEBUG(10, ("open_directory: smbd_check_access_rights on "
3147 "file %s failed with %s\n",
3148 smb_fname_str_dbg(smb_dname),
3149 nt_errstr(status)));
3150 return status;
3154 status = file_new(req, conn, &fsp);
3155 if(!NT_STATUS_IS_OK(status)) {
3156 return status;
3160 * Setup the files_struct for it.
3163 fsp->file_id = vfs_file_id_from_sbuf(conn, &smb_dname->st);
3164 fsp->vuid = req ? req->vuid : UID_FIELD_INVALID;
3165 fsp->file_pid = req ? req->smbpid : 0;
3166 fsp->can_lock = False;
3167 fsp->can_read = False;
3168 fsp->can_write = False;
3170 fsp->share_access = share_access;
3171 fsp->fh->private_options = 0;
3173 * According to Samba4, SEC_FILE_READ_ATTRIBUTE is always granted,
3175 fsp->access_mask = access_mask | FILE_READ_ATTRIBUTES;
3176 fsp->print_file = NULL;
3177 fsp->modified = False;
3178 fsp->oplock_type = NO_OPLOCK;
3179 fsp->sent_oplock_break = NO_BREAK_SENT;
3180 fsp->is_directory = True;
3181 fsp->posix_open = (file_attributes & FILE_FLAG_POSIX_SEMANTICS) ? True : False;
3182 status = fsp_set_smb_fname(fsp, smb_dname);
3183 if (!NT_STATUS_IS_OK(status)) {
3184 file_free(req, fsp);
3185 return status;
3188 mtimespec = smb_dname->st.st_ex_mtime;
3190 #ifdef O_DIRECTORY
3191 status = fd_open(conn, fsp, O_RDONLY|O_DIRECTORY, 0);
3192 #else
3193 /* POSIX allows us to open a directory with O_RDONLY. */
3194 status = fd_open(conn, fsp, O_RDONLY, 0);
3195 #endif
3196 if (!NT_STATUS_IS_OK(status)) {
3197 DEBUG(5, ("open_directory: Could not open fd for "
3198 "%s (%s)\n",
3199 smb_fname_str_dbg(smb_dname),
3200 nt_errstr(status)));
3201 file_free(req, fsp);
3202 return status;
3205 status = vfs_stat_fsp(fsp);
3206 if (!NT_STATUS_IS_OK(status)) {
3207 fd_close(fsp);
3208 file_free(req, fsp);
3209 return status;
3212 /* Ensure there was no race condition. */
3213 if (!check_same_stat(&smb_dname->st, &fsp->fsp_name->st)) {
3214 DEBUG(5,("open_directory: stat struct differs for "
3215 "directory %s.\n",
3216 smb_fname_str_dbg(smb_dname)));
3217 fd_close(fsp);
3218 file_free(req, fsp);
3219 return NT_STATUS_ACCESS_DENIED;
3222 lck = get_share_mode_lock(talloc_tos(), fsp->file_id,
3223 conn->connectpath, smb_dname,
3224 &mtimespec);
3226 if (lck == NULL) {
3227 DEBUG(0, ("open_directory: Could not get share mode lock for "
3228 "%s\n", smb_fname_str_dbg(smb_dname)));
3229 fd_close(fsp);
3230 file_free(req, fsp);
3231 return NT_STATUS_SHARING_VIOLATION;
3234 status = open_mode_check(conn, lck, fsp->name_hash,
3235 access_mask, share_access,
3236 create_options, &dir_existed);
3238 if (!NT_STATUS_IS_OK(status)) {
3239 TALLOC_FREE(lck);
3240 fd_close(fsp);
3241 file_free(req, fsp);
3242 return status;
3245 set_share_mode(lck, fsp, get_current_uid(conn),
3246 req ? req->mid : 0, NO_OPLOCK);
3248 /* For directories the delete on close bit at open time seems
3249 always to be honored on close... See test 19 in Samba4 BASE-DELETE. */
3250 if (create_options & FILE_DELETE_ON_CLOSE) {
3251 status = can_set_delete_on_close(fsp, 0);
3252 if (!NT_STATUS_IS_OK(status) && !NT_STATUS_EQUAL(status, NT_STATUS_DIRECTORY_NOT_EMPTY)) {
3253 TALLOC_FREE(lck);
3254 fd_close(fsp);
3255 file_free(req, fsp);
3256 return status;
3259 if (NT_STATUS_IS_OK(status)) {
3260 /* Note that here we set the *inital* delete on close flag,
3261 not the regular one. The magic gets handled in close. */
3262 fsp->initial_delete_on_close = True;
3266 TALLOC_FREE(lck);
3268 if (pinfo) {
3269 *pinfo = info;
3272 *result = fsp;
3273 return NT_STATUS_OK;
3276 NTSTATUS create_directory(connection_struct *conn, struct smb_request *req,
3277 struct smb_filename *smb_dname)
3279 NTSTATUS status;
3280 files_struct *fsp;
3282 status = SMB_VFS_CREATE_FILE(
3283 conn, /* conn */
3284 req, /* req */
3285 0, /* root_dir_fid */
3286 smb_dname, /* fname */
3287 FILE_READ_ATTRIBUTES, /* access_mask */
3288 FILE_SHARE_NONE, /* share_access */
3289 FILE_CREATE, /* create_disposition*/
3290 FILE_DIRECTORY_FILE, /* create_options */
3291 FILE_ATTRIBUTE_DIRECTORY, /* file_attributes */
3292 0, /* oplock_request */
3293 0, /* allocation_size */
3294 0, /* private_flags */
3295 NULL, /* sd */
3296 NULL, /* ea_list */
3297 &fsp, /* result */
3298 NULL); /* pinfo */
3300 if (NT_STATUS_IS_OK(status)) {
3301 close_file(req, fsp, NORMAL_CLOSE);
3304 return status;
3307 /****************************************************************************
3308 Receive notification that one of our open files has been renamed by another
3309 smbd process.
3310 ****************************************************************************/
3312 void msg_file_was_renamed(struct messaging_context *msg,
3313 void *private_data,
3314 uint32_t msg_type,
3315 struct server_id server_id,
3316 DATA_BLOB *data)
3318 files_struct *fsp;
3319 char *frm = (char *)data->data;
3320 struct file_id id;
3321 const char *sharepath;
3322 const char *base_name;
3323 const char *stream_name;
3324 struct smb_filename *smb_fname = NULL;
3325 size_t sp_len, bn_len;
3326 NTSTATUS status;
3327 struct smbd_server_connection *sconn =
3328 talloc_get_type_abort(private_data,
3329 struct smbd_server_connection);
3331 if (data->data == NULL
3332 || data->length < MSG_FILE_RENAMED_MIN_SIZE + 2) {
3333 DEBUG(0, ("msg_file_was_renamed: Got invalid msg len %d\n",
3334 (int)data->length));
3335 return;
3338 /* Unpack the message. */
3339 pull_file_id_24(frm, &id);
3340 sharepath = &frm[24];
3341 sp_len = strlen(sharepath);
3342 base_name = sharepath + sp_len + 1;
3343 bn_len = strlen(base_name);
3344 stream_name = sharepath + sp_len + 1 + bn_len + 1;
3346 /* stream_name must always be NULL if there is no stream. */
3347 if (stream_name[0] == '\0') {
3348 stream_name = NULL;
3351 smb_fname = synthetic_smb_fname(talloc_tos(), base_name,
3352 stream_name, NULL);
3353 if (smb_fname == NULL) {
3354 return;
3357 DEBUG(10,("msg_file_was_renamed: Got rename message for sharepath %s, new name %s, "
3358 "file_id %s\n",
3359 sharepath, smb_fname_str_dbg(smb_fname),
3360 file_id_string_tos(&id)));
3362 for(fsp = file_find_di_first(sconn, id); fsp;
3363 fsp = file_find_di_next(fsp)) {
3364 if (memcmp(fsp->conn->connectpath, sharepath, sp_len) == 0) {
3366 DEBUG(10,("msg_file_was_renamed: renaming file %s from %s -> %s\n",
3367 fsp_fnum_dbg(fsp), fsp_str_dbg(fsp),
3368 smb_fname_str_dbg(smb_fname)));
3369 status = fsp_set_smb_fname(fsp, smb_fname);
3370 if (!NT_STATUS_IS_OK(status)) {
3371 goto out;
3373 } else {
3374 /* TODO. JRA. */
3375 /* Now we have the complete path we can work out if this is
3376 actually within this share and adjust newname accordingly. */
3377 DEBUG(10,("msg_file_was_renamed: share mismatch (sharepath %s "
3378 "not sharepath %s) "
3379 "%s from %s -> %s\n",
3380 fsp->conn->connectpath,
3381 sharepath,
3382 fsp_fnum_dbg(fsp),
3383 fsp_str_dbg(fsp),
3384 smb_fname_str_dbg(smb_fname)));
3387 out:
3388 TALLOC_FREE(smb_fname);
3389 return;
3393 * If a main file is opened for delete, all streams need to be checked for
3394 * !FILE_SHARE_DELETE. Do this by opening with DELETE_ACCESS.
3395 * If that works, delete them all by setting the delete on close and close.
3398 NTSTATUS open_streams_for_delete(connection_struct *conn,
3399 const char *fname)
3401 struct stream_struct *stream_info = NULL;
3402 files_struct **streams = NULL;
3403 int i;
3404 unsigned int num_streams = 0;
3405 TALLOC_CTX *frame = talloc_stackframe();
3406 NTSTATUS status;
3408 status = vfs_streaminfo(conn, NULL, fname, talloc_tos(),
3409 &num_streams, &stream_info);
3411 if (NT_STATUS_EQUAL(status, NT_STATUS_NOT_IMPLEMENTED)
3412 || NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
3413 DEBUG(10, ("no streams around\n"));
3414 TALLOC_FREE(frame);
3415 return NT_STATUS_OK;
3418 if (!NT_STATUS_IS_OK(status)) {
3419 DEBUG(10, ("vfs_streaminfo failed: %s\n",
3420 nt_errstr(status)));
3421 goto fail;
3424 DEBUG(10, ("open_streams_for_delete found %d streams\n",
3425 num_streams));
3427 if (num_streams == 0) {
3428 TALLOC_FREE(frame);
3429 return NT_STATUS_OK;
3432 streams = talloc_array(talloc_tos(), files_struct *, num_streams);
3433 if (streams == NULL) {
3434 DEBUG(0, ("talloc failed\n"));
3435 status = NT_STATUS_NO_MEMORY;
3436 goto fail;
3439 for (i=0; i<num_streams; i++) {
3440 struct smb_filename *smb_fname;
3442 if (strequal(stream_info[i].name, "::$DATA")) {
3443 streams[i] = NULL;
3444 continue;
3447 smb_fname = synthetic_smb_fname(
3448 talloc_tos(), fname, stream_info[i].name, NULL);
3449 if (smb_fname == NULL) {
3450 status = NT_STATUS_NO_MEMORY;
3451 goto fail;
3454 if (SMB_VFS_STAT(conn, smb_fname) == -1) {
3455 DEBUG(10, ("Unable to stat stream: %s\n",
3456 smb_fname_str_dbg(smb_fname)));
3459 status = SMB_VFS_CREATE_FILE(
3460 conn, /* conn */
3461 NULL, /* req */
3462 0, /* root_dir_fid */
3463 smb_fname, /* fname */
3464 DELETE_ACCESS, /* access_mask */
3465 (FILE_SHARE_READ | /* share_access */
3466 FILE_SHARE_WRITE | FILE_SHARE_DELETE),
3467 FILE_OPEN, /* create_disposition*/
3468 0, /* create_options */
3469 FILE_ATTRIBUTE_NORMAL, /* file_attributes */
3470 0, /* oplock_request */
3471 0, /* allocation_size */
3472 NTCREATEX_OPTIONS_PRIVATE_STREAM_DELETE, /* private_flags */
3473 NULL, /* sd */
3474 NULL, /* ea_list */
3475 &streams[i], /* result */
3476 NULL); /* pinfo */
3478 if (!NT_STATUS_IS_OK(status)) {
3479 DEBUG(10, ("Could not open stream %s: %s\n",
3480 smb_fname_str_dbg(smb_fname),
3481 nt_errstr(status)));
3483 TALLOC_FREE(smb_fname);
3484 break;
3486 TALLOC_FREE(smb_fname);
3490 * don't touch the variable "status" beyond this point :-)
3493 for (i -= 1 ; i >= 0; i--) {
3494 if (streams[i] == NULL) {
3495 continue;
3498 DEBUG(10, ("Closing stream # %d, %s\n", i,
3499 fsp_str_dbg(streams[i])));
3500 close_file(NULL, streams[i], NORMAL_CLOSE);
3503 fail:
3504 TALLOC_FREE(frame);
3505 return status;
3508 /*********************************************************************
3509 Create a default ACL by inheriting from the parent. If no inheritance
3510 from the parent available, don't set anything. This will leave the actual
3511 permissions the new file or directory already got from the filesystem
3512 as the NT ACL when read.
3513 *********************************************************************/
3515 static NTSTATUS inherit_new_acl(files_struct *fsp)
3517 TALLOC_CTX *frame = talloc_stackframe();
3518 char *parent_name = NULL;
3519 struct security_descriptor *parent_desc = NULL;
3520 NTSTATUS status = NT_STATUS_OK;
3521 struct security_descriptor *psd = NULL;
3522 const struct dom_sid *owner_sid = NULL;
3523 const struct dom_sid *group_sid = NULL;
3524 uint32_t security_info_sent = (SECINFO_OWNER | SECINFO_GROUP | SECINFO_DACL);
3525 struct security_token *token = fsp->conn->session_info->security_token;
3526 bool inherit_owner = lp_inherit_owner(SNUM(fsp->conn));
3527 bool inheritable_components = false;
3528 bool try_builtin_administrators = false;
3529 const struct dom_sid *BA_U_sid = NULL;
3530 const struct dom_sid *BA_G_sid = NULL;
3531 bool try_system = false;
3532 const struct dom_sid *SY_U_sid = NULL;
3533 const struct dom_sid *SY_G_sid = NULL;
3534 size_t size = 0;
3536 if (!parent_dirname(frame, fsp->fsp_name->base_name, &parent_name, NULL)) {
3537 TALLOC_FREE(frame);
3538 return NT_STATUS_NO_MEMORY;
3541 status = SMB_VFS_GET_NT_ACL(fsp->conn,
3542 parent_name,
3543 (SECINFO_OWNER | SECINFO_GROUP | SECINFO_DACL),
3544 frame,
3545 &parent_desc);
3546 if (!NT_STATUS_IS_OK(status)) {
3547 TALLOC_FREE(frame);
3548 return status;
3551 inheritable_components = sd_has_inheritable_components(parent_desc,
3552 fsp->is_directory);
3554 if (!inheritable_components && !inherit_owner) {
3555 TALLOC_FREE(frame);
3556 /* Nothing to inherit and not setting owner. */
3557 return NT_STATUS_OK;
3560 /* Create an inherited descriptor from the parent. */
3562 if (DEBUGLEVEL >= 10) {
3563 DEBUG(10,("inherit_new_acl: parent acl for %s is:\n",
3564 fsp_str_dbg(fsp) ));
3565 NDR_PRINT_DEBUG(security_descriptor, parent_desc);
3568 /* Inherit from parent descriptor if "inherit owner" set. */
3569 if (inherit_owner) {
3570 owner_sid = parent_desc->owner_sid;
3571 group_sid = parent_desc->group_sid;
3574 if (owner_sid == NULL) {
3575 if (security_token_has_builtin_administrators(token)) {
3576 try_builtin_administrators = true;
3577 } else if (security_token_is_system(token)) {
3578 try_builtin_administrators = true;
3579 try_system = true;
3583 if (group_sid == NULL &&
3584 token->num_sids == PRIMARY_GROUP_SID_INDEX)
3586 if (security_token_is_system(token)) {
3587 try_builtin_administrators = true;
3588 try_system = true;
3592 if (try_builtin_administrators) {
3593 struct unixid ids;
3594 bool ok;
3596 ZERO_STRUCT(ids);
3597 ok = sids_to_unixids(&global_sid_Builtin_Administrators, 1, &ids);
3598 if (ok) {
3599 switch (ids.type) {
3600 case ID_TYPE_BOTH:
3601 BA_U_sid = &global_sid_Builtin_Administrators;
3602 BA_G_sid = &global_sid_Builtin_Administrators;
3603 break;
3604 case ID_TYPE_UID:
3605 BA_U_sid = &global_sid_Builtin_Administrators;
3606 break;
3607 case ID_TYPE_GID:
3608 BA_G_sid = &global_sid_Builtin_Administrators;
3609 break;
3610 default:
3611 break;
3616 if (try_system) {
3617 struct unixid ids;
3618 bool ok;
3620 ZERO_STRUCT(ids);
3621 ok = sids_to_unixids(&global_sid_System, 1, &ids);
3622 if (ok) {
3623 switch (ids.type) {
3624 case ID_TYPE_BOTH:
3625 SY_U_sid = &global_sid_System;
3626 SY_G_sid = &global_sid_System;
3627 break;
3628 case ID_TYPE_UID:
3629 SY_U_sid = &global_sid_System;
3630 break;
3631 case ID_TYPE_GID:
3632 SY_G_sid = &global_sid_System;
3633 break;
3634 default:
3635 break;
3640 if (owner_sid == NULL) {
3641 owner_sid = BA_U_sid;
3644 if (owner_sid == NULL) {
3645 owner_sid = SY_U_sid;
3648 if (group_sid == NULL) {
3649 group_sid = SY_G_sid;
3652 if (try_system && group_sid == NULL) {
3653 group_sid = BA_G_sid;
3656 if (owner_sid == NULL) {
3657 owner_sid = &token->sids[PRIMARY_USER_SID_INDEX];
3659 if (group_sid == NULL) {
3660 if (token->num_sids == PRIMARY_GROUP_SID_INDEX) {
3661 group_sid = &token->sids[PRIMARY_USER_SID_INDEX];
3662 } else {
3663 group_sid = &token->sids[PRIMARY_GROUP_SID_INDEX];
3667 status = se_create_child_secdesc(frame,
3668 &psd,
3669 &size,
3670 parent_desc,
3671 owner_sid,
3672 group_sid,
3673 fsp->is_directory);
3674 if (!NT_STATUS_IS_OK(status)) {
3675 TALLOC_FREE(frame);
3676 return status;
3679 /* If inheritable_components == false,
3680 se_create_child_secdesc()
3681 creates a security desriptor with a NULL dacl
3682 entry, but with SEC_DESC_DACL_PRESENT. We need
3683 to remove that flag. */
3685 if (!inheritable_components) {
3686 security_info_sent &= ~SECINFO_DACL;
3687 psd->type &= ~SEC_DESC_DACL_PRESENT;
3690 if (DEBUGLEVEL >= 10) {
3691 DEBUG(10,("inherit_new_acl: child acl for %s is:\n",
3692 fsp_str_dbg(fsp) ));
3693 NDR_PRINT_DEBUG(security_descriptor, psd);
3696 if (inherit_owner) {
3697 /* We need to be root to force this. */
3698 become_root();
3700 status = SMB_VFS_FSET_NT_ACL(fsp,
3701 security_info_sent,
3702 psd);
3703 if (inherit_owner) {
3704 unbecome_root();
3706 TALLOC_FREE(frame);
3707 return status;
3711 * Wrapper around open_file_ntcreate and open_directory
3714 static NTSTATUS create_file_unixpath(connection_struct *conn,
3715 struct smb_request *req,
3716 struct smb_filename *smb_fname,
3717 uint32_t access_mask,
3718 uint32_t share_access,
3719 uint32_t create_disposition,
3720 uint32_t create_options,
3721 uint32_t file_attributes,
3722 uint32_t oplock_request,
3723 uint64_t allocation_size,
3724 uint32_t private_flags,
3725 struct security_descriptor *sd,
3726 struct ea_list *ea_list,
3728 files_struct **result,
3729 int *pinfo)
3731 int info = FILE_WAS_OPENED;
3732 files_struct *base_fsp = NULL;
3733 files_struct *fsp = NULL;
3734 NTSTATUS status;
3736 DEBUG(10,("create_file_unixpath: access_mask = 0x%x "
3737 "file_attributes = 0x%x, share_access = 0x%x, "
3738 "create_disposition = 0x%x create_options = 0x%x "
3739 "oplock_request = 0x%x private_flags = 0x%x "
3740 "ea_list = 0x%p, sd = 0x%p, "
3741 "fname = %s\n",
3742 (unsigned int)access_mask,
3743 (unsigned int)file_attributes,
3744 (unsigned int)share_access,
3745 (unsigned int)create_disposition,
3746 (unsigned int)create_options,
3747 (unsigned int)oplock_request,
3748 (unsigned int)private_flags,
3749 ea_list, sd, smb_fname_str_dbg(smb_fname)));
3751 if (create_options & FILE_OPEN_BY_FILE_ID) {
3752 status = NT_STATUS_NOT_SUPPORTED;
3753 goto fail;
3756 if (create_options & NTCREATEX_OPTIONS_INVALID_PARAM_MASK) {
3757 status = NT_STATUS_INVALID_PARAMETER;
3758 goto fail;
3761 if (req == NULL) {
3762 oplock_request |= INTERNAL_OPEN_ONLY;
3765 if ((conn->fs_capabilities & FILE_NAMED_STREAMS)
3766 && (access_mask & DELETE_ACCESS)
3767 && !is_ntfs_stream_smb_fname(smb_fname)) {
3769 * We can't open a file with DELETE access if any of the
3770 * streams is open without FILE_SHARE_DELETE
3772 status = open_streams_for_delete(conn, smb_fname->base_name);
3774 if (!NT_STATUS_IS_OK(status)) {
3775 goto fail;
3779 if ((access_mask & SEC_FLAG_SYSTEM_SECURITY) &&
3780 !security_token_has_privilege(get_current_nttok(conn),
3781 SEC_PRIV_SECURITY)) {
3782 DEBUG(10, ("create_file_unixpath: open on %s "
3783 "failed - SEC_FLAG_SYSTEM_SECURITY denied.\n",
3784 smb_fname_str_dbg(smb_fname)));
3785 status = NT_STATUS_PRIVILEGE_NOT_HELD;
3786 goto fail;
3789 if ((conn->fs_capabilities & FILE_NAMED_STREAMS)
3790 && is_ntfs_stream_smb_fname(smb_fname)
3791 && (!(private_flags & NTCREATEX_OPTIONS_PRIVATE_STREAM_DELETE))) {
3792 uint32 base_create_disposition;
3793 struct smb_filename *smb_fname_base = NULL;
3795 if (create_options & FILE_DIRECTORY_FILE) {
3796 status = NT_STATUS_NOT_A_DIRECTORY;
3797 goto fail;
3800 switch (create_disposition) {
3801 case FILE_OPEN:
3802 base_create_disposition = FILE_OPEN;
3803 break;
3804 default:
3805 base_create_disposition = FILE_OPEN_IF;
3806 break;
3809 /* Create an smb_filename with stream_name == NULL. */
3810 smb_fname_base = synthetic_smb_fname(talloc_tos(),
3811 smb_fname->base_name,
3812 NULL, NULL);
3813 if (smb_fname_base == NULL) {
3814 status = NT_STATUS_NO_MEMORY;
3815 goto fail;
3818 if (SMB_VFS_STAT(conn, smb_fname_base) == -1) {
3819 DEBUG(10, ("Unable to stat stream: %s\n",
3820 smb_fname_str_dbg(smb_fname_base)));
3823 /* Open the base file. */
3824 status = create_file_unixpath(conn, NULL, smb_fname_base, 0,
3825 FILE_SHARE_READ
3826 | FILE_SHARE_WRITE
3827 | FILE_SHARE_DELETE,
3828 base_create_disposition,
3829 0, 0, 0, 0, 0, NULL, NULL,
3830 &base_fsp, NULL);
3831 TALLOC_FREE(smb_fname_base);
3833 if (!NT_STATUS_IS_OK(status)) {
3834 DEBUG(10, ("create_file_unixpath for base %s failed: "
3835 "%s\n", smb_fname->base_name,
3836 nt_errstr(status)));
3837 goto fail;
3839 /* we don't need to low level fd */
3840 fd_close(base_fsp);
3844 * If it's a request for a directory open, deal with it separately.
3847 if (create_options & FILE_DIRECTORY_FILE) {
3849 if (create_options & FILE_NON_DIRECTORY_FILE) {
3850 status = NT_STATUS_INVALID_PARAMETER;
3851 goto fail;
3854 /* Can't open a temp directory. IFS kit test. */
3855 if (!(file_attributes & FILE_FLAG_POSIX_SEMANTICS) &&
3856 (file_attributes & FILE_ATTRIBUTE_TEMPORARY)) {
3857 status = NT_STATUS_INVALID_PARAMETER;
3858 goto fail;
3862 * We will get a create directory here if the Win32
3863 * app specified a security descriptor in the
3864 * CreateDirectory() call.
3867 oplock_request = 0;
3868 status = open_directory(
3869 conn, req, smb_fname, access_mask, share_access,
3870 create_disposition, create_options, file_attributes,
3871 &info, &fsp);
3872 } else {
3875 * Ordinary file case.
3878 status = file_new(req, conn, &fsp);
3879 if(!NT_STATUS_IS_OK(status)) {
3880 goto fail;
3883 status = fsp_set_smb_fname(fsp, smb_fname);
3884 if (!NT_STATUS_IS_OK(status)) {
3885 goto fail;
3888 if (base_fsp) {
3890 * We're opening the stream element of a
3891 * base_fsp we already opened. Set up the
3892 * base_fsp pointer.
3894 fsp->base_fsp = base_fsp;
3897 if (allocation_size) {
3898 fsp->initial_allocation_size = smb_roundup(fsp->conn,
3899 allocation_size);
3902 status = open_file_ntcreate(conn,
3903 req,
3904 access_mask,
3905 share_access,
3906 create_disposition,
3907 create_options,
3908 file_attributes,
3909 oplock_request,
3910 private_flags,
3911 &info,
3912 fsp);
3914 if(!NT_STATUS_IS_OK(status)) {
3915 file_free(req, fsp);
3916 fsp = NULL;
3919 if (NT_STATUS_EQUAL(status, NT_STATUS_FILE_IS_A_DIRECTORY)) {
3921 /* A stream open never opens a directory */
3923 if (base_fsp) {
3924 status = NT_STATUS_FILE_IS_A_DIRECTORY;
3925 goto fail;
3929 * Fail the open if it was explicitly a non-directory
3930 * file.
3933 if (create_options & FILE_NON_DIRECTORY_FILE) {
3934 status = NT_STATUS_FILE_IS_A_DIRECTORY;
3935 goto fail;
3938 oplock_request = 0;
3939 status = open_directory(
3940 conn, req, smb_fname, access_mask,
3941 share_access, create_disposition,
3942 create_options, file_attributes,
3943 &info, &fsp);
3947 if (!NT_STATUS_IS_OK(status)) {
3948 goto fail;
3951 fsp->base_fsp = base_fsp;
3953 if ((ea_list != NULL) &&
3954 ((info == FILE_WAS_CREATED) || (info == FILE_WAS_OVERWRITTEN))) {
3955 status = set_ea(conn, fsp, fsp->fsp_name, ea_list);
3956 if (!NT_STATUS_IS_OK(status)) {
3957 goto fail;
3961 if (!fsp->is_directory && S_ISDIR(fsp->fsp_name->st.st_ex_mode)) {
3962 status = NT_STATUS_ACCESS_DENIED;
3963 goto fail;
3966 /* Save the requested allocation size. */
3967 if ((info == FILE_WAS_CREATED) || (info == FILE_WAS_OVERWRITTEN)) {
3968 if (allocation_size
3969 && (allocation_size > fsp->fsp_name->st.st_ex_size)) {
3970 fsp->initial_allocation_size = smb_roundup(
3971 fsp->conn, allocation_size);
3972 if (fsp->is_directory) {
3973 /* Can't set allocation size on a directory. */
3974 status = NT_STATUS_ACCESS_DENIED;
3975 goto fail;
3977 if (vfs_allocate_file_space(
3978 fsp, fsp->initial_allocation_size) == -1) {
3979 status = NT_STATUS_DISK_FULL;
3980 goto fail;
3982 } else {
3983 fsp->initial_allocation_size = smb_roundup(
3984 fsp->conn, (uint64_t)fsp->fsp_name->st.st_ex_size);
3986 } else {
3987 fsp->initial_allocation_size = 0;
3990 if ((info == FILE_WAS_CREATED) && lp_nt_acl_support(SNUM(conn)) &&
3991 fsp->base_fsp == NULL) {
3992 if (sd != NULL) {
3994 * According to the MS documentation, the only time the security
3995 * descriptor is applied to the opened file is iff we *created* the
3996 * file; an existing file stays the same.
3998 * Also, it seems (from observation) that you can open the file with
3999 * any access mask but you can still write the sd. We need to override
4000 * the granted access before we call set_sd
4001 * Patch for bug #2242 from Tom Lackemann <cessnatomny@yahoo.com>.
4004 uint32_t sec_info_sent;
4005 uint32_t saved_access_mask = fsp->access_mask;
4007 sec_info_sent = get_sec_info(sd);
4009 fsp->access_mask = FILE_GENERIC_ALL;
4011 if (sec_info_sent & (SECINFO_OWNER|
4012 SECINFO_GROUP|
4013 SECINFO_DACL|
4014 SECINFO_SACL)) {
4015 status = set_sd(fsp, sd, sec_info_sent);
4018 fsp->access_mask = saved_access_mask;
4020 if (!NT_STATUS_IS_OK(status)) {
4021 goto fail;
4023 } else if (lp_inherit_acls(SNUM(conn))) {
4024 /* Inherit from parent. Errors here are not fatal. */
4025 status = inherit_new_acl(fsp);
4026 if (!NT_STATUS_IS_OK(status)) {
4027 DEBUG(10,("inherit_new_acl: failed for %s with %s\n",
4028 fsp_str_dbg(fsp),
4029 nt_errstr(status) ));
4034 DEBUG(10, ("create_file_unixpath: info=%d\n", info));
4036 *result = fsp;
4037 if (pinfo != NULL) {
4038 *pinfo = info;
4041 smb_fname->st = fsp->fsp_name->st;
4043 return NT_STATUS_OK;
4045 fail:
4046 DEBUG(10, ("create_file_unixpath: %s\n", nt_errstr(status)));
4048 if (fsp != NULL) {
4049 if (base_fsp && fsp->base_fsp == base_fsp) {
4051 * The close_file below will close
4052 * fsp->base_fsp.
4054 base_fsp = NULL;
4056 close_file(req, fsp, ERROR_CLOSE);
4057 fsp = NULL;
4059 if (base_fsp != NULL) {
4060 close_file(req, base_fsp, ERROR_CLOSE);
4061 base_fsp = NULL;
4063 return status;
4067 * Calculate the full path name given a relative fid.
4069 NTSTATUS get_relative_fid_filename(connection_struct *conn,
4070 struct smb_request *req,
4071 uint16_t root_dir_fid,
4072 const struct smb_filename *smb_fname,
4073 struct smb_filename **smb_fname_out)
4075 files_struct *dir_fsp;
4076 char *parent_fname = NULL;
4077 char *new_base_name = NULL;
4078 NTSTATUS status;
4080 if (root_dir_fid == 0 || !smb_fname) {
4081 status = NT_STATUS_INTERNAL_ERROR;
4082 goto out;
4085 dir_fsp = file_fsp(req, root_dir_fid);
4087 if (dir_fsp == NULL) {
4088 status = NT_STATUS_INVALID_HANDLE;
4089 goto out;
4092 if (is_ntfs_stream_smb_fname(dir_fsp->fsp_name)) {
4093 status = NT_STATUS_INVALID_HANDLE;
4094 goto out;
4097 if (!dir_fsp->is_directory) {
4100 * Check to see if this is a mac fork of some kind.
4103 if ((conn->fs_capabilities & FILE_NAMED_STREAMS) &&
4104 is_ntfs_stream_smb_fname(smb_fname)) {
4105 status = NT_STATUS_OBJECT_PATH_NOT_FOUND;
4106 goto out;
4110 we need to handle the case when we get a
4111 relative open relative to a file and the
4112 pathname is blank - this is a reopen!
4113 (hint from demyn plantenberg)
4116 status = NT_STATUS_INVALID_HANDLE;
4117 goto out;
4120 if (ISDOT(dir_fsp->fsp_name->base_name)) {
4122 * We're at the toplevel dir, the final file name
4123 * must not contain ./, as this is filtered out
4124 * normally by srvstr_get_path and unix_convert
4125 * explicitly rejects paths containing ./.
4127 parent_fname = talloc_strdup(talloc_tos(), "");
4128 if (parent_fname == NULL) {
4129 status = NT_STATUS_NO_MEMORY;
4130 goto out;
4132 } else {
4133 size_t dir_name_len = strlen(dir_fsp->fsp_name->base_name);
4136 * Copy in the base directory name.
4139 parent_fname = talloc_array(talloc_tos(), char,
4140 dir_name_len+2);
4141 if (parent_fname == NULL) {
4142 status = NT_STATUS_NO_MEMORY;
4143 goto out;
4145 memcpy(parent_fname, dir_fsp->fsp_name->base_name,
4146 dir_name_len+1);
4149 * Ensure it ends in a '/'.
4150 * We used TALLOC_SIZE +2 to add space for the '/'.
4153 if(dir_name_len
4154 && (parent_fname[dir_name_len-1] != '\\')
4155 && (parent_fname[dir_name_len-1] != '/')) {
4156 parent_fname[dir_name_len] = '/';
4157 parent_fname[dir_name_len+1] = '\0';
4161 new_base_name = talloc_asprintf(talloc_tos(), "%s%s", parent_fname,
4162 smb_fname->base_name);
4163 if (new_base_name == NULL) {
4164 status = NT_STATUS_NO_MEMORY;
4165 goto out;
4168 status = filename_convert(req,
4169 conn,
4170 req->flags2 & FLAGS2_DFS_PATHNAMES,
4171 new_base_name,
4173 NULL,
4174 smb_fname_out);
4175 if (!NT_STATUS_IS_OK(status)) {
4176 goto out;
4179 out:
4180 TALLOC_FREE(parent_fname);
4181 TALLOC_FREE(new_base_name);
4182 return status;
4185 NTSTATUS create_file_default(connection_struct *conn,
4186 struct smb_request *req,
4187 uint16_t root_dir_fid,
4188 struct smb_filename *smb_fname,
4189 uint32_t access_mask,
4190 uint32_t share_access,
4191 uint32_t create_disposition,
4192 uint32_t create_options,
4193 uint32_t file_attributes,
4194 uint32_t oplock_request,
4195 uint64_t allocation_size,
4196 uint32_t private_flags,
4197 struct security_descriptor *sd,
4198 struct ea_list *ea_list,
4199 files_struct **result,
4200 int *pinfo)
4202 int info = FILE_WAS_OPENED;
4203 files_struct *fsp = NULL;
4204 NTSTATUS status;
4205 bool stream_name = false;
4207 DEBUG(10,("create_file: access_mask = 0x%x "
4208 "file_attributes = 0x%x, share_access = 0x%x, "
4209 "create_disposition = 0x%x create_options = 0x%x "
4210 "oplock_request = 0x%x "
4211 "private_flags = 0x%x "
4212 "root_dir_fid = 0x%x, ea_list = 0x%p, sd = 0x%p, "
4213 "fname = %s\n",
4214 (unsigned int)access_mask,
4215 (unsigned int)file_attributes,
4216 (unsigned int)share_access,
4217 (unsigned int)create_disposition,
4218 (unsigned int)create_options,
4219 (unsigned int)oplock_request,
4220 (unsigned int)private_flags,
4221 (unsigned int)root_dir_fid,
4222 ea_list, sd, smb_fname_str_dbg(smb_fname)));
4225 * Calculate the filename from the root_dir_if if necessary.
4228 if (root_dir_fid != 0) {
4229 struct smb_filename *smb_fname_out = NULL;
4230 status = get_relative_fid_filename(conn, req, root_dir_fid,
4231 smb_fname, &smb_fname_out);
4232 if (!NT_STATUS_IS_OK(status)) {
4233 goto fail;
4235 smb_fname = smb_fname_out;
4239 * Check to see if this is a mac fork of some kind.
4242 stream_name = is_ntfs_stream_smb_fname(smb_fname);
4243 if (stream_name) {
4244 enum FAKE_FILE_TYPE fake_file_type;
4246 fake_file_type = is_fake_file(smb_fname);
4248 if (fake_file_type != FAKE_FILE_TYPE_NONE) {
4251 * Here we go! support for changing the disk quotas
4252 * --metze
4254 * We need to fake up to open this MAGIC QUOTA file
4255 * and return a valid FID.
4257 * w2k close this file directly after openening xp
4258 * also tries a QUERY_FILE_INFO on the file and then
4259 * close it
4261 status = open_fake_file(req, conn, req->vuid,
4262 fake_file_type, smb_fname,
4263 access_mask, &fsp);
4264 if (!NT_STATUS_IS_OK(status)) {
4265 goto fail;
4268 ZERO_STRUCT(smb_fname->st);
4269 goto done;
4272 if (!(conn->fs_capabilities & FILE_NAMED_STREAMS)) {
4273 status = NT_STATUS_OBJECT_NAME_NOT_FOUND;
4274 goto fail;
4278 if (is_ntfs_default_stream_smb_fname(smb_fname)) {
4279 int ret;
4280 smb_fname->stream_name = NULL;
4281 /* We have to handle this error here. */
4282 if (create_options & FILE_DIRECTORY_FILE) {
4283 status = NT_STATUS_NOT_A_DIRECTORY;
4284 goto fail;
4286 if (lp_posix_pathnames()) {
4287 ret = SMB_VFS_LSTAT(conn, smb_fname);
4288 } else {
4289 ret = SMB_VFS_STAT(conn, smb_fname);
4292 if (ret == 0 && VALID_STAT_OF_DIR(smb_fname->st)) {
4293 status = NT_STATUS_FILE_IS_A_DIRECTORY;
4294 goto fail;
4298 status = create_file_unixpath(
4299 conn, req, smb_fname, access_mask, share_access,
4300 create_disposition, create_options, file_attributes,
4301 oplock_request, allocation_size, private_flags,
4302 sd, ea_list,
4303 &fsp, &info);
4305 if (!NT_STATUS_IS_OK(status)) {
4306 goto fail;
4309 done:
4310 DEBUG(10, ("create_file: info=%d\n", info));
4312 *result = fsp;
4313 if (pinfo != NULL) {
4314 *pinfo = info;
4316 return NT_STATUS_OK;
4318 fail:
4319 DEBUG(10, ("create_file: %s\n", nt_errstr(status)));
4321 if (fsp != NULL) {
4322 close_file(req, fsp, ERROR_CLOSE);
4323 fsp = NULL;
4325 return status;