smbd: Remove unused "mid" from delay_for_oplock
[Samba.git] / source3 / smbd / open.c
bloba9147f80b82e75435b9ec76a8230848c6b66e022
1 /*
2 Unix SMB/CIFS implementation.
3 file opening and share modes
4 Copyright (C) Andrew Tridgell 1992-1998
5 Copyright (C) Jeremy Allison 2001-2004
6 Copyright (C) Volker Lendecke 2005
8 This program is free software; you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation; either version 3 of the License, or
11 (at your option) any later version.
13 This program is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with this program. If not, see <http://www.gnu.org/licenses/>.
22 #include "includes.h"
23 #include "system/filesys.h"
24 #include "printing.h"
25 #include "smbd/smbd.h"
26 #include "smbd/globals.h"
27 #include "fake_file.h"
28 #include "../libcli/security/security.h"
29 #include "../librpc/gen_ndr/ndr_security.h"
30 #include "../librpc/gen_ndr/open_files.h"
31 #include "../librpc/gen_ndr/idmap.h"
32 #include "passdb/lookup_sid.h"
33 #include "auth.h"
34 #include "serverid.h"
35 #include "messages.h"
36 #include "source3/lib/dbwrap/dbwrap_watch.h"
38 extern const struct generic_mapping file_generic_mapping;
40 struct deferred_open_record {
41 bool delayed_for_oplocks;
42 bool async_open;
43 struct file_id id;
46 /****************************************************************************
47 If the requester wanted DELETE_ACCESS and was rejected because
48 the file ACL didn't include DELETE_ACCESS, see if the parent ACL
49 overrides this.
50 ****************************************************************************/
52 static bool parent_override_delete(connection_struct *conn,
53 const struct smb_filename *smb_fname,
54 uint32_t access_mask,
55 uint32_t rejected_mask)
57 if ((access_mask & DELETE_ACCESS) &&
58 (rejected_mask & DELETE_ACCESS) &&
59 can_delete_file_in_directory(conn, smb_fname)) {
60 return true;
62 return false;
65 /****************************************************************************
66 Check if we have open rights.
67 ****************************************************************************/
69 NTSTATUS smbd_check_access_rights(struct connection_struct *conn,
70 const struct smb_filename *smb_fname,
71 bool use_privs,
72 uint32_t access_mask)
74 /* Check if we have rights to open. */
75 NTSTATUS status;
76 struct security_descriptor *sd = NULL;
77 uint32_t rejected_share_access;
78 uint32_t rejected_mask = access_mask;
79 uint32_t do_not_check_mask = 0;
81 rejected_share_access = access_mask & ~(conn->share_access);
83 if (rejected_share_access) {
84 DEBUG(10, ("smbd_check_access_rights: rejected share access 0x%x "
85 "on %s (0x%x)\n",
86 (unsigned int)access_mask,
87 smb_fname_str_dbg(smb_fname),
88 (unsigned int)rejected_share_access ));
89 return NT_STATUS_ACCESS_DENIED;
92 if (!use_privs && get_current_uid(conn) == (uid_t)0) {
93 /* I'm sorry sir, I didn't know you were root... */
94 DEBUG(10,("smbd_check_access_rights: root override "
95 "on %s. Granting 0x%x\n",
96 smb_fname_str_dbg(smb_fname),
97 (unsigned int)access_mask ));
98 return NT_STATUS_OK;
101 if ((access_mask & DELETE_ACCESS) && !lp_acl_check_permissions(SNUM(conn))) {
102 DEBUG(10,("smbd_check_access_rights: not checking ACL "
103 "on DELETE_ACCESS on file %s. Granting 0x%x\n",
104 smb_fname_str_dbg(smb_fname),
105 (unsigned int)access_mask ));
106 return NT_STATUS_OK;
109 if (access_mask == DELETE_ACCESS &&
110 VALID_STAT(smb_fname->st) &&
111 S_ISLNK(smb_fname->st.st_ex_mode)) {
112 /* We can always delete a symlink. */
113 DEBUG(10,("smbd_check_access_rights: not checking ACL "
114 "on DELETE_ACCESS on symlink %s.\n",
115 smb_fname_str_dbg(smb_fname) ));
116 return NT_STATUS_OK;
119 status = SMB_VFS_GET_NT_ACL(conn, smb_fname->base_name,
120 (SECINFO_OWNER |
121 SECINFO_GROUP |
122 SECINFO_DACL), talloc_tos(), &sd);
124 if (!NT_STATUS_IS_OK(status)) {
125 DEBUG(10, ("smbd_check_access_rights: Could not get acl "
126 "on %s: %s\n",
127 smb_fname_str_dbg(smb_fname),
128 nt_errstr(status)));
130 if (NT_STATUS_EQUAL(status, NT_STATUS_ACCESS_DENIED)) {
131 goto access_denied;
134 return status;
138 * If we can access the path to this file, by
139 * default we have FILE_READ_ATTRIBUTES from the
140 * containing directory. See the section:
141 * "Algorithm to Check Access to an Existing File"
142 * in MS-FSA.pdf.
144 * se_file_access_check() also takes care of
145 * owner WRITE_DAC and READ_CONTROL.
147 do_not_check_mask = FILE_READ_ATTRIBUTES;
150 * Samba 3.6 and earlier granted execute access even
151 * if the ACL did not contain execute rights.
152 * Samba 4.0 is more correct and checks it.
153 * The compatibilty mode allows to skip this check
154 * to smoothen upgrades.
156 if (lp_acl_allow_execute_always(SNUM(conn))) {
157 do_not_check_mask |= FILE_EXECUTE;
160 status = se_file_access_check(sd,
161 get_current_nttok(conn),
162 use_privs,
163 (access_mask & ~do_not_check_mask),
164 &rejected_mask);
166 DEBUG(10,("smbd_check_access_rights: file %s requesting "
167 "0x%x returning 0x%x (%s)\n",
168 smb_fname_str_dbg(smb_fname),
169 (unsigned int)access_mask,
170 (unsigned int)rejected_mask,
171 nt_errstr(status) ));
173 if (!NT_STATUS_IS_OK(status)) {
174 if (DEBUGLEVEL >= 10) {
175 DEBUG(10,("smbd_check_access_rights: acl for %s is:\n",
176 smb_fname_str_dbg(smb_fname) ));
177 NDR_PRINT_DEBUG(security_descriptor, sd);
181 TALLOC_FREE(sd);
183 if (NT_STATUS_IS_OK(status) ||
184 !NT_STATUS_EQUAL(status, NT_STATUS_ACCESS_DENIED)) {
185 return status;
188 /* Here we know status == NT_STATUS_ACCESS_DENIED. */
190 access_denied:
192 if ((access_mask & FILE_WRITE_ATTRIBUTES) &&
193 (rejected_mask & FILE_WRITE_ATTRIBUTES) &&
194 !lp_store_dos_attributes(SNUM(conn)) &&
195 (lp_map_readonly(SNUM(conn)) ||
196 lp_map_archive(SNUM(conn)) ||
197 lp_map_hidden(SNUM(conn)) ||
198 lp_map_system(SNUM(conn)))) {
199 rejected_mask &= ~FILE_WRITE_ATTRIBUTES;
201 DEBUG(10,("smbd_check_access_rights: "
202 "overrode "
203 "FILE_WRITE_ATTRIBUTES "
204 "on file %s\n",
205 smb_fname_str_dbg(smb_fname)));
208 if (parent_override_delete(conn,
209 smb_fname,
210 access_mask,
211 rejected_mask)) {
212 /* Were we trying to do an open
213 * for delete and didn't get DELETE
214 * access (only) ? Check if the
215 * directory allows DELETE_CHILD.
216 * See here:
217 * http://blogs.msdn.com/oldnewthing/archive/2004/06/04/148426.aspx
218 * for details. */
220 rejected_mask &= ~DELETE_ACCESS;
222 DEBUG(10,("smbd_check_access_rights: "
223 "overrode "
224 "DELETE_ACCESS on "
225 "file %s\n",
226 smb_fname_str_dbg(smb_fname)));
229 if (rejected_mask != 0) {
230 return NT_STATUS_ACCESS_DENIED;
232 return NT_STATUS_OK;
235 static NTSTATUS check_parent_access(struct connection_struct *conn,
236 struct smb_filename *smb_fname,
237 uint32_t access_mask)
239 NTSTATUS status;
240 char *parent_dir = NULL;
241 struct security_descriptor *parent_sd = NULL;
242 uint32_t access_granted = 0;
244 if (!parent_dirname(talloc_tos(),
245 smb_fname->base_name,
246 &parent_dir,
247 NULL)) {
248 return NT_STATUS_NO_MEMORY;
251 if (get_current_uid(conn) == (uid_t)0) {
252 /* I'm sorry sir, I didn't know you were root... */
253 DEBUG(10,("check_parent_access: root override "
254 "on %s. Granting 0x%x\n",
255 smb_fname_str_dbg(smb_fname),
256 (unsigned int)access_mask ));
257 return NT_STATUS_OK;
260 status = SMB_VFS_GET_NT_ACL(conn,
261 parent_dir,
262 SECINFO_DACL,
263 talloc_tos(),
264 &parent_sd);
266 if (!NT_STATUS_IS_OK(status)) {
267 DEBUG(5,("check_parent_access: SMB_VFS_GET_NT_ACL failed for "
268 "%s with error %s\n",
269 parent_dir,
270 nt_errstr(status)));
271 return status;
275 * If we can access the path to this file, by
276 * default we have FILE_READ_ATTRIBUTES from the
277 * containing directory. See the section:
278 * "Algorithm to Check Access to an Existing File"
279 * in MS-FSA.pdf.
281 * se_file_access_check() also takes care of
282 * owner WRITE_DAC and READ_CONTROL.
284 status = se_file_access_check(parent_sd,
285 get_current_nttok(conn),
286 false,
287 (access_mask & ~FILE_READ_ATTRIBUTES),
288 &access_granted);
289 if(!NT_STATUS_IS_OK(status)) {
290 DEBUG(5,("check_parent_access: access check "
291 "on directory %s for "
292 "path %s for mask 0x%x returned (0x%x) %s\n",
293 parent_dir,
294 smb_fname->base_name,
295 access_mask,
296 access_granted,
297 nt_errstr(status) ));
298 return status;
301 return NT_STATUS_OK;
304 /****************************************************************************
305 fd support routines - attempt to do a dos_open.
306 ****************************************************************************/
308 NTSTATUS fd_open(struct connection_struct *conn,
309 files_struct *fsp,
310 int flags,
311 mode_t mode)
313 struct smb_filename *smb_fname = fsp->fsp_name;
314 NTSTATUS status = NT_STATUS_OK;
316 #ifdef O_NOFOLLOW
318 * Never follow symlinks on a POSIX client. The
319 * client should be doing this.
322 if (fsp->posix_open || !lp_symlinks(SNUM(conn))) {
323 flags |= O_NOFOLLOW;
325 #endif
327 fsp->fh->fd = SMB_VFS_OPEN(conn, smb_fname, fsp, flags, mode);
328 if (fsp->fh->fd == -1) {
329 int posix_errno = errno;
330 #ifdef O_NOFOLLOW
331 #if defined(ENOTSUP) && defined(OSF1)
332 /* handle special Tru64 errno */
333 if (errno == ENOTSUP) {
334 posix_errno = ELOOP;
336 #endif /* ENOTSUP */
337 #ifdef EFTYPE
338 /* fix broken NetBSD errno */
339 if (errno == EFTYPE) {
340 posix_errno = ELOOP;
342 #endif /* EFTYPE */
343 /* fix broken FreeBSD errno */
344 if (errno == EMLINK) {
345 posix_errno = ELOOP;
347 #endif /* O_NOFOLLOW */
348 status = map_nt_error_from_unix(posix_errno);
349 if (errno == EMFILE) {
350 static time_t last_warned = 0L;
352 if (time((time_t *) NULL) > last_warned) {
353 DEBUG(0,("Too many open files, unable "
354 "to open more! smbd's max "
355 "open files = %d\n",
356 lp_max_open_files()));
357 last_warned = time((time_t *) NULL);
363 DEBUG(10,("fd_open: name %s, flags = 0%o mode = 0%o, fd = %d. %s\n",
364 smb_fname_str_dbg(smb_fname), flags, (int)mode, fsp->fh->fd,
365 (fsp->fh->fd == -1) ? strerror(errno) : "" ));
367 return status;
370 /****************************************************************************
371 Close the file associated with a fsp.
372 ****************************************************************************/
374 NTSTATUS fd_close(files_struct *fsp)
376 int ret;
378 if (fsp->dptr) {
379 dptr_CloseDir(fsp);
381 if (fsp->fh->fd == -1) {
382 return NT_STATUS_OK; /* What we used to call a stat open. */
384 if (fsp->fh->ref_count > 1) {
385 return NT_STATUS_OK; /* Shared handle. Only close last reference. */
388 ret = SMB_VFS_CLOSE(fsp);
389 fsp->fh->fd = -1;
390 if (ret == -1) {
391 return map_nt_error_from_unix(errno);
393 return NT_STATUS_OK;
396 /****************************************************************************
397 Change the ownership of a file to that of the parent directory.
398 Do this by fd if possible.
399 ****************************************************************************/
401 void change_file_owner_to_parent(connection_struct *conn,
402 const char *inherit_from_dir,
403 files_struct *fsp)
405 struct smb_filename *smb_fname_parent;
406 int ret;
408 smb_fname_parent = synthetic_smb_fname(talloc_tos(), inherit_from_dir,
409 NULL, NULL);
410 if (smb_fname_parent == NULL) {
411 return;
414 ret = SMB_VFS_STAT(conn, smb_fname_parent);
415 if (ret == -1) {
416 DEBUG(0,("change_file_owner_to_parent: failed to stat parent "
417 "directory %s. Error was %s\n",
418 smb_fname_str_dbg(smb_fname_parent),
419 strerror(errno)));
420 TALLOC_FREE(smb_fname_parent);
421 return;
424 if (smb_fname_parent->st.st_ex_uid == fsp->fsp_name->st.st_ex_uid) {
425 /* Already this uid - no need to change. */
426 DEBUG(10,("change_file_owner_to_parent: file %s "
427 "is already owned by uid %d\n",
428 fsp_str_dbg(fsp),
429 (int)fsp->fsp_name->st.st_ex_uid ));
430 TALLOC_FREE(smb_fname_parent);
431 return;
434 become_root();
435 ret = SMB_VFS_FCHOWN(fsp, smb_fname_parent->st.st_ex_uid, (gid_t)-1);
436 unbecome_root();
437 if (ret == -1) {
438 DEBUG(0,("change_file_owner_to_parent: failed to fchown "
439 "file %s to parent directory uid %u. Error "
440 "was %s\n", fsp_str_dbg(fsp),
441 (unsigned int)smb_fname_parent->st.st_ex_uid,
442 strerror(errno) ));
443 } else {
444 DEBUG(10,("change_file_owner_to_parent: changed new file %s to "
445 "parent directory uid %u.\n", fsp_str_dbg(fsp),
446 (unsigned int)smb_fname_parent->st.st_ex_uid));
447 /* Ensure the uid entry is updated. */
448 fsp->fsp_name->st.st_ex_uid = smb_fname_parent->st.st_ex_uid;
451 TALLOC_FREE(smb_fname_parent);
454 NTSTATUS change_dir_owner_to_parent(connection_struct *conn,
455 const char *inherit_from_dir,
456 const char *fname,
457 SMB_STRUCT_STAT *psbuf)
459 struct smb_filename *smb_fname_parent;
460 struct smb_filename *smb_fname_cwd = NULL;
461 char *saved_dir = NULL;
462 TALLOC_CTX *ctx = talloc_tos();
463 NTSTATUS status = NT_STATUS_OK;
464 int ret;
466 smb_fname_parent = synthetic_smb_fname(ctx, inherit_from_dir,
467 NULL, NULL);
468 if (smb_fname_parent == NULL) {
469 return NT_STATUS_NO_MEMORY;
472 ret = SMB_VFS_STAT(conn, smb_fname_parent);
473 if (ret == -1) {
474 status = map_nt_error_from_unix(errno);
475 DEBUG(0,("change_dir_owner_to_parent: failed to stat parent "
476 "directory %s. Error was %s\n",
477 smb_fname_str_dbg(smb_fname_parent),
478 strerror(errno)));
479 goto out;
482 /* We've already done an lstat into psbuf, and we know it's a
483 directory. If we can cd into the directory and the dev/ino
484 are the same then we can safely chown without races as
485 we're locking the directory in place by being in it. This
486 should work on any UNIX (thanks tridge :-). JRA.
489 saved_dir = vfs_GetWd(ctx,conn);
490 if (!saved_dir) {
491 status = map_nt_error_from_unix(errno);
492 DEBUG(0,("change_dir_owner_to_parent: failed to get "
493 "current working directory. Error was %s\n",
494 strerror(errno)));
495 goto out;
498 /* Chdir into the new path. */
499 if (vfs_ChDir(conn, fname) == -1) {
500 status = map_nt_error_from_unix(errno);
501 DEBUG(0,("change_dir_owner_to_parent: failed to change "
502 "current working directory to %s. Error "
503 "was %s\n", fname, strerror(errno) ));
504 goto chdir;
507 smb_fname_cwd = synthetic_smb_fname(ctx, ".", NULL, NULL);
508 if (smb_fname_cwd == NULL) {
509 status = NT_STATUS_NO_MEMORY;
510 goto chdir;
513 ret = SMB_VFS_STAT(conn, smb_fname_cwd);
514 if (ret == -1) {
515 status = map_nt_error_from_unix(errno);
516 DEBUG(0,("change_dir_owner_to_parent: failed to stat "
517 "directory '.' (%s) Error was %s\n",
518 fname, strerror(errno)));
519 goto chdir;
522 /* Ensure we're pointing at the same place. */
523 if (smb_fname_cwd->st.st_ex_dev != psbuf->st_ex_dev ||
524 smb_fname_cwd->st.st_ex_ino != psbuf->st_ex_ino) {
525 DEBUG(0,("change_dir_owner_to_parent: "
526 "device/inode on directory %s changed. "
527 "Refusing to chown !\n", fname ));
528 status = NT_STATUS_ACCESS_DENIED;
529 goto chdir;
532 if (smb_fname_parent->st.st_ex_uid == smb_fname_cwd->st.st_ex_uid) {
533 /* Already this uid - no need to change. */
534 DEBUG(10,("change_dir_owner_to_parent: directory %s "
535 "is already owned by uid %d\n",
536 fname,
537 (int)smb_fname_cwd->st.st_ex_uid ));
538 status = NT_STATUS_OK;
539 goto chdir;
542 become_root();
543 ret = SMB_VFS_LCHOWN(conn, ".", smb_fname_parent->st.st_ex_uid,
544 (gid_t)-1);
545 unbecome_root();
546 if (ret == -1) {
547 status = map_nt_error_from_unix(errno);
548 DEBUG(10,("change_dir_owner_to_parent: failed to chown "
549 "directory %s to parent directory uid %u. "
550 "Error was %s\n", fname,
551 (unsigned int)smb_fname_parent->st.st_ex_uid,
552 strerror(errno) ));
553 } else {
554 DEBUG(10,("change_dir_owner_to_parent: changed ownership of new "
555 "directory %s to parent directory uid %u.\n",
556 fname, (unsigned int)smb_fname_parent->st.st_ex_uid ));
557 /* Ensure the uid entry is updated. */
558 psbuf->st_ex_uid = smb_fname_parent->st.st_ex_uid;
561 chdir:
562 vfs_ChDir(conn,saved_dir);
563 out:
564 TALLOC_FREE(smb_fname_parent);
565 TALLOC_FREE(smb_fname_cwd);
566 return status;
569 /****************************************************************************
570 Open a file - returning a guaranteed ATOMIC indication of if the
571 file was created or not.
572 ****************************************************************************/
574 static NTSTATUS fd_open_atomic(struct connection_struct *conn,
575 files_struct *fsp,
576 int flags,
577 mode_t mode,
578 bool *file_created)
580 NTSTATUS status = NT_STATUS_UNSUCCESSFUL;
581 bool file_existed = VALID_STAT(fsp->fsp_name->st);
583 *file_created = false;
585 if (!(flags & O_CREAT)) {
587 * We're not creating the file, just pass through.
589 return fd_open(conn, fsp, flags, mode);
592 if (flags & O_EXCL) {
594 * Fail if already exists, just pass through.
596 status = fd_open(conn, fsp, flags, mode);
599 * Here we've opened with O_CREAT|O_EXCL. If that went
600 * NT_STATUS_OK, we *know* we created this file.
602 *file_created = NT_STATUS_IS_OK(status);
604 return status;
608 * Now it gets tricky. We have O_CREAT, but not O_EXCL.
609 * To know absolutely if we created the file or not,
610 * we can never call O_CREAT without O_EXCL. So if
611 * we think the file existed, try without O_CREAT|O_EXCL.
612 * If we think the file didn't exist, try with
613 * O_CREAT|O_EXCL. Keep bouncing between these two
614 * requests until either the file is created, or
615 * opened. Either way, we keep going until we get
616 * a returnable result (error, or open/create).
619 while(1) {
620 int curr_flags = flags;
622 if (file_existed) {
623 /* Just try open, do not create. */
624 curr_flags &= ~(O_CREAT);
625 status = fd_open(conn, fsp, curr_flags, mode);
626 if (NT_STATUS_EQUAL(status,
627 NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
629 * Someone deleted it in the meantime.
630 * Retry with O_EXCL.
632 file_existed = false;
633 DEBUG(10,("fd_open_atomic: file %s existed. "
634 "Retry.\n",
635 smb_fname_str_dbg(fsp->fsp_name)));
636 continue;
638 } else {
639 /* Try create exclusively, fail if it exists. */
640 curr_flags |= O_EXCL;
641 status = fd_open(conn, fsp, curr_flags, mode);
642 if (NT_STATUS_EQUAL(status,
643 NT_STATUS_OBJECT_NAME_COLLISION)) {
645 * Someone created it in the meantime.
646 * Retry without O_CREAT.
648 file_existed = true;
649 DEBUG(10,("fd_open_atomic: file %s "
650 "did not exist. Retry.\n",
651 smb_fname_str_dbg(fsp->fsp_name)));
652 continue;
654 if (NT_STATUS_IS_OK(status)) {
656 * Here we've opened with O_CREAT|O_EXCL
657 * and got success. We *know* we created
658 * this file.
660 *file_created = true;
663 /* Create is done, or failed. */
664 break;
666 return status;
669 /****************************************************************************
670 Open a file.
671 ****************************************************************************/
673 static NTSTATUS open_file(files_struct *fsp,
674 connection_struct *conn,
675 struct smb_request *req,
676 const char *parent_dir,
677 int flags,
678 mode_t unx_mode,
679 uint32 access_mask, /* client requested access mask. */
680 uint32 open_access_mask, /* what we're actually using in the open. */
681 bool *p_file_created)
683 struct smb_filename *smb_fname = fsp->fsp_name;
684 NTSTATUS status = NT_STATUS_OK;
685 int accmode = (flags & O_ACCMODE);
686 int local_flags = flags;
687 bool file_existed = VALID_STAT(fsp->fsp_name->st);
689 fsp->fh->fd = -1;
690 errno = EPERM;
692 /* Check permissions */
695 * This code was changed after seeing a client open request
696 * containing the open mode of (DENY_WRITE/read-only) with
697 * the 'create if not exist' bit set. The previous code
698 * would fail to open the file read only on a read-only share
699 * as it was checking the flags parameter directly against O_RDONLY,
700 * this was failing as the flags parameter was set to O_RDONLY|O_CREAT.
701 * JRA.
704 if (!CAN_WRITE(conn)) {
705 /* It's a read-only share - fail if we wanted to write. */
706 if(accmode != O_RDONLY || (flags & O_TRUNC) || (flags & O_APPEND)) {
707 DEBUG(3,("Permission denied opening %s\n",
708 smb_fname_str_dbg(smb_fname)));
709 return NT_STATUS_ACCESS_DENIED;
711 if (flags & O_CREAT) {
712 /* We don't want to write - but we must make sure that
713 O_CREAT doesn't create the file if we have write
714 access into the directory.
716 flags &= ~(O_CREAT|O_EXCL);
717 local_flags &= ~(O_CREAT|O_EXCL);
722 * This little piece of insanity is inspired by the
723 * fact that an NT client can open a file for O_RDONLY,
724 * but set the create disposition to FILE_EXISTS_TRUNCATE.
725 * If the client *can* write to the file, then it expects to
726 * truncate the file, even though it is opening for readonly.
727 * Quicken uses this stupid trick in backup file creation...
728 * Thanks *greatly* to "David W. Chapman Jr." <dwcjr@inethouston.net>
729 * for helping track this one down. It didn't bite us in 2.0.x
730 * as we always opened files read-write in that release. JRA.
733 if ((accmode == O_RDONLY) && ((flags & O_TRUNC) == O_TRUNC)) {
734 DEBUG(10,("open_file: truncate requested on read-only open "
735 "for file %s\n", smb_fname_str_dbg(smb_fname)));
736 local_flags = (flags & ~O_ACCMODE)|O_RDWR;
739 if ((open_access_mask & (FILE_READ_DATA|FILE_WRITE_DATA|FILE_APPEND_DATA|FILE_EXECUTE)) ||
740 (!file_existed && (local_flags & O_CREAT)) ||
741 ((local_flags & O_TRUNC) == O_TRUNC) ) {
742 const char *wild;
743 int ret;
745 #if defined(O_NONBLOCK) && defined(S_ISFIFO)
747 * We would block on opening a FIFO with no one else on the
748 * other end. Do what we used to do and add O_NONBLOCK to the
749 * open flags. JRA.
752 if (file_existed && S_ISFIFO(smb_fname->st.st_ex_mode)) {
753 local_flags &= ~O_TRUNC; /* Can't truncate a FIFO. */
754 local_flags |= O_NONBLOCK;
756 #endif
758 /* Don't create files with Microsoft wildcard characters. */
759 if (fsp->base_fsp) {
761 * wildcard characters are allowed in stream names
762 * only test the basefilename
764 wild = fsp->base_fsp->fsp_name->base_name;
765 } else {
766 wild = smb_fname->base_name;
768 if ((local_flags & O_CREAT) && !file_existed &&
769 ms_has_wild(wild)) {
770 return NT_STATUS_OBJECT_NAME_INVALID;
773 /* Can we access this file ? */
774 if (!fsp->base_fsp) {
775 /* Only do this check on non-stream open. */
776 if (file_existed) {
777 status = smbd_check_access_rights(conn,
778 smb_fname,
779 false,
780 access_mask);
781 } else if (local_flags & O_CREAT){
782 status = check_parent_access(conn,
783 smb_fname,
784 SEC_DIR_ADD_FILE);
785 } else {
786 /* File didn't exist and no O_CREAT. */
787 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
789 if (!NT_STATUS_IS_OK(status)) {
790 DEBUG(10,("open_file: "
791 "%s on file "
792 "%s returned %s\n",
793 file_existed ?
794 "smbd_check_access_rights" :
795 "check_parent_access",
796 smb_fname_str_dbg(smb_fname),
797 nt_errstr(status) ));
798 return status;
802 /* Actually do the open */
803 status = fd_open_atomic(conn, fsp, local_flags,
804 unx_mode, p_file_created);
805 if (!NT_STATUS_IS_OK(status)) {
806 DEBUG(3,("Error opening file %s (%s) (local_flags=%d) "
807 "(flags=%d)\n", smb_fname_str_dbg(smb_fname),
808 nt_errstr(status),local_flags,flags));
809 return status;
812 ret = SMB_VFS_FSTAT(fsp, &smb_fname->st);
813 if (ret == -1) {
814 /* If we have an fd, this stat should succeed. */
815 DEBUG(0,("Error doing fstat on open file %s "
816 "(%s)\n",
817 smb_fname_str_dbg(smb_fname),
818 strerror(errno) ));
819 status = map_nt_error_from_unix(errno);
820 fd_close(fsp);
821 return status;
824 if (*p_file_created) {
825 /* We created this file. */
827 bool need_re_stat = false;
828 /* Do all inheritance work after we've
829 done a successful fstat call and filled
830 in the stat struct in fsp->fsp_name. */
832 /* Inherit the ACL if required */
833 if (lp_inherit_perms(SNUM(conn))) {
834 inherit_access_posix_acl(conn, parent_dir,
835 smb_fname->base_name,
836 unx_mode);
837 need_re_stat = true;
840 /* Change the owner if required. */
841 if (lp_inherit_owner(SNUM(conn))) {
842 change_file_owner_to_parent(conn, parent_dir,
843 fsp);
844 need_re_stat = true;
847 if (need_re_stat) {
848 ret = SMB_VFS_FSTAT(fsp, &smb_fname->st);
849 /* If we have an fd, this stat should succeed. */
850 if (ret == -1) {
851 DEBUG(0,("Error doing fstat on open file %s "
852 "(%s)\n",
853 smb_fname_str_dbg(smb_fname),
854 strerror(errno) ));
858 notify_fname(conn, NOTIFY_ACTION_ADDED,
859 FILE_NOTIFY_CHANGE_FILE_NAME,
860 smb_fname->base_name);
862 } else {
863 fsp->fh->fd = -1; /* What we used to call a stat open. */
864 if (!file_existed) {
865 /* File must exist for a stat open. */
866 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
869 status = smbd_check_access_rights(conn,
870 smb_fname,
871 false,
872 access_mask);
874 if (NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND) &&
875 fsp->posix_open &&
876 S_ISLNK(smb_fname->st.st_ex_mode)) {
877 /* This is a POSIX stat open for delete
878 * or rename on a symlink that points
879 * nowhere. Allow. */
880 DEBUG(10,("open_file: allowing POSIX "
881 "open on bad symlink %s\n",
882 smb_fname_str_dbg(smb_fname)));
883 status = NT_STATUS_OK;
886 if (!NT_STATUS_IS_OK(status)) {
887 DEBUG(10,("open_file: "
888 "smbd_check_access_rights on file "
889 "%s returned %s\n",
890 smb_fname_str_dbg(smb_fname),
891 nt_errstr(status) ));
892 return status;
897 * POSIX allows read-only opens of directories. We don't
898 * want to do this (we use a different code path for this)
899 * so catch a directory open and return an EISDIR. JRA.
902 if(S_ISDIR(smb_fname->st.st_ex_mode)) {
903 fd_close(fsp);
904 errno = EISDIR;
905 return NT_STATUS_FILE_IS_A_DIRECTORY;
908 fsp->file_id = vfs_file_id_from_sbuf(conn, &smb_fname->st);
909 fsp->vuid = req ? req->vuid : UID_FIELD_INVALID;
910 fsp->file_pid = req ? req->smbpid : 0;
911 fsp->can_lock = True;
912 fsp->can_read = ((access_mask & FILE_READ_DATA) != 0);
913 fsp->can_write =
914 CAN_WRITE(conn) &&
915 ((access_mask & (FILE_WRITE_DATA | FILE_APPEND_DATA)) != 0);
916 fsp->print_file = NULL;
917 fsp->modified = False;
918 fsp->sent_oplock_break = NO_BREAK_SENT;
919 fsp->is_directory = False;
920 if (conn->aio_write_behind_list &&
921 is_in_path(smb_fname->base_name, conn->aio_write_behind_list,
922 conn->case_sensitive)) {
923 fsp->aio_write_behind = True;
926 fsp->wcp = NULL; /* Write cache pointer. */
928 DEBUG(2,("%s opened file %s read=%s write=%s (numopen=%d)\n",
929 conn->session_info->unix_info->unix_name,
930 smb_fname_str_dbg(smb_fname),
931 BOOLSTR(fsp->can_read), BOOLSTR(fsp->can_write),
932 conn->num_files_open));
934 errno = 0;
935 return NT_STATUS_OK;
938 /****************************************************************************
939 Check if we can open a file with a share mode.
940 Returns True if conflict, False if not.
941 ****************************************************************************/
943 static bool share_conflict(struct share_mode_entry *entry,
944 uint32 access_mask,
945 uint32 share_access)
947 DEBUG(10,("share_conflict: entry->access_mask = 0x%x, "
948 "entry->share_access = 0x%x, "
949 "entry->private_options = 0x%x\n",
950 (unsigned int)entry->access_mask,
951 (unsigned int)entry->share_access,
952 (unsigned int)entry->private_options));
954 if (server_id_is_disconnected(&entry->pid)) {
956 * note: cleanup should have been done by
957 * delay_for_batch_oplocks()
959 return false;
962 DEBUG(10,("share_conflict: access_mask = 0x%x, share_access = 0x%x\n",
963 (unsigned int)access_mask, (unsigned int)share_access));
965 if ((entry->access_mask & (FILE_WRITE_DATA|
966 FILE_APPEND_DATA|
967 FILE_READ_DATA|
968 FILE_EXECUTE|
969 DELETE_ACCESS)) == 0) {
970 DEBUG(10,("share_conflict: No conflict due to "
971 "entry->access_mask = 0x%x\n",
972 (unsigned int)entry->access_mask ));
973 return False;
976 if ((access_mask & (FILE_WRITE_DATA|
977 FILE_APPEND_DATA|
978 FILE_READ_DATA|
979 FILE_EXECUTE|
980 DELETE_ACCESS)) == 0) {
981 DEBUG(10,("share_conflict: No conflict due to "
982 "access_mask = 0x%x\n",
983 (unsigned int)access_mask ));
984 return False;
987 #if 1 /* JRA TEST - Superdebug. */
988 #define CHECK_MASK(num, am, right, sa, share) \
989 DEBUG(10,("share_conflict: [%d] am (0x%x) & right (0x%x) = 0x%x\n", \
990 (unsigned int)(num), (unsigned int)(am), \
991 (unsigned int)(right), (unsigned int)(am)&(right) )); \
992 DEBUG(10,("share_conflict: [%d] sa (0x%x) & share (0x%x) = 0x%x\n", \
993 (unsigned int)(num), (unsigned int)(sa), \
994 (unsigned int)(share), (unsigned int)(sa)&(share) )); \
995 if (((am) & (right)) && !((sa) & (share))) { \
996 DEBUG(10,("share_conflict: check %d conflict am = 0x%x, right = 0x%x, \
997 sa = 0x%x, share = 0x%x\n", (num), (unsigned int)(am), (unsigned int)(right), (unsigned int)(sa), \
998 (unsigned int)(share) )); \
999 return True; \
1001 #else
1002 #define CHECK_MASK(num, am, right, sa, share) \
1003 if (((am) & (right)) && !((sa) & (share))) { \
1004 DEBUG(10,("share_conflict: check %d conflict am = 0x%x, right = 0x%x, \
1005 sa = 0x%x, share = 0x%x\n", (num), (unsigned int)(am), (unsigned int)(right), (unsigned int)(sa), \
1006 (unsigned int)(share) )); \
1007 return True; \
1009 #endif
1011 CHECK_MASK(1, entry->access_mask, FILE_WRITE_DATA | FILE_APPEND_DATA,
1012 share_access, FILE_SHARE_WRITE);
1013 CHECK_MASK(2, access_mask, FILE_WRITE_DATA | FILE_APPEND_DATA,
1014 entry->share_access, FILE_SHARE_WRITE);
1016 CHECK_MASK(3, entry->access_mask, FILE_READ_DATA | FILE_EXECUTE,
1017 share_access, FILE_SHARE_READ);
1018 CHECK_MASK(4, access_mask, FILE_READ_DATA | FILE_EXECUTE,
1019 entry->share_access, FILE_SHARE_READ);
1021 CHECK_MASK(5, entry->access_mask, DELETE_ACCESS,
1022 share_access, FILE_SHARE_DELETE);
1023 CHECK_MASK(6, access_mask, DELETE_ACCESS,
1024 entry->share_access, FILE_SHARE_DELETE);
1026 DEBUG(10,("share_conflict: No conflict.\n"));
1027 return False;
1030 #if defined(DEVELOPER)
1031 static void validate_my_share_entries(struct smbd_server_connection *sconn,
1032 int num,
1033 struct share_mode_entry *share_entry)
1035 struct server_id self = messaging_server_id(sconn->msg_ctx);
1036 files_struct *fsp;
1038 if (!serverid_equal(&self, &share_entry->pid)) {
1039 return;
1042 if (!is_valid_share_mode_entry(share_entry)) {
1043 return;
1046 fsp = file_find_dif(sconn, share_entry->id,
1047 share_entry->share_file_id);
1048 if (!fsp) {
1049 DEBUG(0,("validate_my_share_entries: PANIC : %s\n",
1050 share_mode_str(talloc_tos(), num, share_entry) ));
1051 smb_panic("validate_my_share_entries: Cannot match a "
1052 "share entry with an open file\n");
1055 if (((uint16)fsp->oplock_type) != share_entry->op_type) {
1056 goto panic;
1059 return;
1061 panic:
1063 char *str;
1064 DEBUG(0,("validate_my_share_entries: PANIC : %s\n",
1065 share_mode_str(talloc_tos(), num, share_entry) ));
1066 str = talloc_asprintf(talloc_tos(),
1067 "validate_my_share_entries: "
1068 "file %s, oplock_type = 0x%x, op_type = 0x%x\n",
1069 fsp->fsp_name->base_name,
1070 (unsigned int)fsp->oplock_type,
1071 (unsigned int)share_entry->op_type );
1072 smb_panic(str);
1075 #endif
1077 bool is_stat_open(uint32 access_mask)
1079 const uint32_t stat_open_bits =
1080 (SYNCHRONIZE_ACCESS|
1081 FILE_READ_ATTRIBUTES|
1082 FILE_WRITE_ATTRIBUTES);
1084 return (((access_mask & stat_open_bits) != 0) &&
1085 ((access_mask & ~stat_open_bits) == 0));
1088 static bool has_delete_on_close(struct share_mode_lock *lck,
1089 uint32_t name_hash)
1091 struct share_mode_data *d = lck->data;
1092 uint32_t i;
1094 if (d->num_share_modes == 0) {
1095 return false;
1097 if (!is_delete_on_close_set(lck, name_hash)) {
1098 return false;
1100 for (i=0; i<d->num_share_modes; i++) {
1101 if (!share_mode_stale_pid(d, i)) {
1102 return true;
1105 return false;
1108 /****************************************************************************
1109 Deal with share modes
1110 Invarient: Share mode must be locked on entry and exit.
1111 Returns -1 on error, or number of share modes on success (may be zero).
1112 ****************************************************************************/
1114 static NTSTATUS open_mode_check(connection_struct *conn,
1115 struct share_mode_lock *lck,
1116 uint32 access_mask,
1117 uint32 share_access)
1119 int i;
1121 if(lck->data->num_share_modes == 0) {
1122 return NT_STATUS_OK;
1125 if (is_stat_open(access_mask)) {
1126 /* Stat open that doesn't trigger oplock breaks or share mode
1127 * checks... ! JRA. */
1128 return NT_STATUS_OK;
1132 * Check if the share modes will give us access.
1135 #if defined(DEVELOPER)
1136 for(i = 0; i < lck->data->num_share_modes; i++) {
1137 validate_my_share_entries(conn->sconn, i,
1138 &lck->data->share_modes[i]);
1140 #endif
1142 /* Now we check the share modes, after any oplock breaks. */
1143 for(i = 0; i < lck->data->num_share_modes; i++) {
1145 if (!is_valid_share_mode_entry(&lck->data->share_modes[i])) {
1146 continue;
1149 /* someone else has a share lock on it, check to see if we can
1150 * too */
1151 if (share_conflict(&lck->data->share_modes[i],
1152 access_mask, share_access)) {
1154 if (share_mode_stale_pid(lck->data, i)) {
1155 continue;
1158 return NT_STATUS_SHARING_VIOLATION;
1162 return NT_STATUS_OK;
1166 * Send a break message to the oplock holder and delay the open for
1167 * our client.
1170 static NTSTATUS send_break_message(struct messaging_context *msg_ctx,
1171 const struct share_mode_entry *exclusive)
1173 NTSTATUS status;
1174 char msg[MSG_SMB_SHARE_MODE_ENTRY_SIZE];
1176 DEBUG(10, ("Sending break request to PID %s\n",
1177 procid_str_static(&exclusive->pid)));
1179 /* Create the message. */
1180 share_mode_entry_to_message(msg, exclusive);
1182 status = messaging_send_buf(msg_ctx, exclusive->pid,
1183 MSG_SMB_BREAK_REQUEST,
1184 (uint8 *)msg, sizeof(msg));
1185 if (!NT_STATUS_IS_OK(status)) {
1186 DEBUG(3, ("Could not send oplock break message: %s\n",
1187 nt_errstr(status)));
1190 return status;
1194 * Do internal consistency checks on the share mode for a file.
1197 static bool validate_oplock_types(struct share_mode_lock *lck)
1199 struct share_mode_data *d = lck->data;
1200 bool batch = false;
1201 bool ex_or_batch = false;
1202 bool level2 = false;
1203 bool no_oplock = false;
1204 uint32_t num_non_stat_opens = 0;
1205 uint32_t i;
1207 for (i=0; i<d->num_share_modes; i++) {
1208 struct share_mode_entry *e = &d->share_modes[i];
1210 if (!is_valid_share_mode_entry(e)) {
1211 continue;
1214 if (e->op_type == NO_OPLOCK && is_stat_open(e->access_mask)) {
1215 /* We ignore stat opens in the table - they
1216 always have NO_OPLOCK and never get or
1217 cause breaks. JRA. */
1218 continue;
1221 num_non_stat_opens += 1;
1223 if (BATCH_OPLOCK_TYPE(e->op_type)) {
1224 /* batch - can only be one. */
1225 if (share_mode_stale_pid(d, i)) {
1226 DEBUG(10, ("Found stale batch oplock\n"));
1227 continue;
1229 if (ex_or_batch || batch || level2 || no_oplock) {
1230 DEBUG(0, ("Bad batch oplock entry %u.",
1231 (unsigned)i));
1232 return false;
1234 batch = true;
1237 if (EXCLUSIVE_OPLOCK_TYPE(e->op_type)) {
1238 if (share_mode_stale_pid(d, i)) {
1239 DEBUG(10, ("Found stale duplicate oplock\n"));
1240 continue;
1242 /* Exclusive or batch - can only be one. */
1243 if (ex_or_batch || level2 || no_oplock) {
1244 DEBUG(0, ("Bad exclusive or batch oplock "
1245 "entry %u.", (unsigned)i));
1246 return false;
1248 ex_or_batch = true;
1251 if (LEVEL_II_OPLOCK_TYPE(e->op_type)) {
1252 if (batch || ex_or_batch) {
1253 if (share_mode_stale_pid(d, i)) {
1254 DEBUG(10, ("Found stale LevelII "
1255 "oplock\n"));
1256 continue;
1258 DEBUG(0, ("Bad levelII oplock entry %u.",
1259 (unsigned)i));
1260 return false;
1262 level2 = true;
1265 if (e->op_type == NO_OPLOCK) {
1266 if (batch || ex_or_batch) {
1267 if (share_mode_stale_pid(d, i)) {
1268 DEBUG(10, ("Found stale NO_OPLOCK "
1269 "entry\n"));
1270 continue;
1272 DEBUG(0, ("Bad no oplock entry %u.",
1273 (unsigned)i));
1274 return false;
1276 no_oplock = true;
1280 remove_stale_share_mode_entries(d);
1282 if ((batch || ex_or_batch) && (num_non_stat_opens != 1)) {
1283 DEBUG(1, ("got batch (%d) or ex (%d) non-exclusively (%d)\n",
1284 (int)batch, (int)ex_or_batch,
1285 (int)d->num_share_modes));
1286 return false;
1289 return true;
1292 static bool delay_for_oplock(files_struct *fsp,
1293 int oplock_request,
1294 struct share_mode_lock *lck,
1295 bool have_sharing_violation)
1297 struct share_mode_data *d = lck->data;
1298 struct share_mode_entry *entry;
1299 uint32_t num_non_stat_opens = 0;
1300 uint32_t i;
1302 if ((oplock_request & INTERNAL_OPEN_ONLY) || is_stat_open(fsp->access_mask)) {
1303 return false;
1305 for (i=0; i<d->num_share_modes; i++) {
1306 struct share_mode_entry *e = &d->share_modes[i];
1307 if (e->op_type == NO_OPLOCK && is_stat_open(e->access_mask)) {
1308 continue;
1310 num_non_stat_opens += 1;
1313 * We found the a non-stat open, which in the exclusive/batch
1314 * case will be inspected further down.
1316 entry = e;
1318 if (num_non_stat_opens == 0) {
1320 * Nothing to wait for around
1322 return false;
1324 if (num_non_stat_opens != 1) {
1326 * More than one open around. There can't be any exclusive or
1327 * batch left, this is all level2.
1329 return false;
1332 if (server_id_is_disconnected(&entry->pid)) {
1334 * TODO: clean up.
1335 * This could be achieved by sending a break message
1336 * to ourselves. Special considerations for files
1337 * with delete_on_close flag set!
1339 * For now we keep it simple and do not
1340 * allow delete on close for durable handles.
1342 return false;
1345 if (have_sharing_violation && (entry->op_type & BATCH_OPLOCK)) {
1346 if (share_mode_stale_pid(d, 0)) {
1347 return false;
1349 send_break_message(fsp->conn->sconn->msg_ctx, entry);
1350 return true;
1352 if (have_sharing_violation) {
1354 * Non-batch exclusive is not broken if we have a sharing
1355 * violation
1357 return false;
1359 if (!EXCLUSIVE_OPLOCK_TYPE(entry->op_type)) {
1361 * No break for NO_OPLOCK or LEVEL2_OPLOCK oplocks
1363 return false;
1365 if (share_mode_stale_pid(d, 0)) {
1366 return false;
1369 send_break_message(fsp->conn->sconn->msg_ctx, entry);
1370 return true;
1373 static bool file_has_brlocks(files_struct *fsp)
1375 struct byte_range_lock *br_lck;
1377 br_lck = brl_get_locks_readonly(fsp);
1378 if (!br_lck)
1379 return false;
1381 return (brl_num_locks(br_lck) > 0);
1384 static void grant_fsp_oplock_type(files_struct *fsp,
1385 struct share_mode_lock *lck,
1386 int oplock_request)
1388 bool allow_level2 = (global_client_caps & CAP_LEVEL_II_OPLOCKS) &&
1389 lp_level2_oplocks(SNUM(fsp->conn));
1390 bool got_level2_oplock, got_a_none_oplock;
1391 uint32_t i;
1393 /* Start by granting what the client asked for,
1394 but ensure no SAMBA_PRIVATE bits can be set. */
1395 fsp->oplock_type = (oplock_request & ~SAMBA_PRIVATE_OPLOCK_MASK);
1397 if (oplock_request & INTERNAL_OPEN_ONLY) {
1398 /* No oplocks on internal open. */
1399 fsp->oplock_type = NO_OPLOCK;
1400 DEBUG(10,("grant_fsp_oplock_type: oplock type 0x%x on file %s\n",
1401 fsp->oplock_type, fsp_str_dbg(fsp)));
1402 return;
1405 if (lp_locking(fsp->conn->params) && file_has_brlocks(fsp)) {
1406 DEBUG(10,("grant_fsp_oplock_type: file %s has byte range locks\n",
1407 fsp_str_dbg(fsp)));
1408 fsp->oplock_type = NO_OPLOCK;
1411 if (is_stat_open(fsp->access_mask)) {
1412 /* Leave the value already set. */
1413 DEBUG(10,("grant_fsp_oplock_type: oplock type 0x%x on file %s\n",
1414 fsp->oplock_type, fsp_str_dbg(fsp)));
1415 return;
1418 got_level2_oplock = false;
1419 got_a_none_oplock = false;
1421 for (i=0; i<lck->data->num_share_modes; i++) {
1422 int op_type = lck->data->share_modes[i].op_type;
1424 if (LEVEL_II_OPLOCK_TYPE(op_type)) {
1425 got_level2_oplock = true;
1427 if (op_type == NO_OPLOCK) {
1428 got_a_none_oplock = true;
1433 * Match what was requested (fsp->oplock_type) with
1434 * what was found in the existing share modes.
1437 if (got_level2_oplock || got_a_none_oplock) {
1438 if (EXCLUSIVE_OPLOCK_TYPE(fsp->oplock_type)) {
1439 fsp->oplock_type = LEVEL_II_OPLOCK;
1444 * Don't grant level2 to clients that don't want them
1445 * or if we've turned them off.
1447 if (fsp->oplock_type == LEVEL_II_OPLOCK && !allow_level2) {
1448 fsp->oplock_type = NO_OPLOCK;
1451 if (fsp->oplock_type == LEVEL_II_OPLOCK && !got_level2_oplock) {
1453 * We're the first level2 oplock. Indicate that in brlock.tdb.
1455 struct byte_range_lock *brl;
1457 brl = brl_get_locks(talloc_tos(), fsp);
1458 if (brl != NULL) {
1459 brl_set_have_read_oplocks(brl, true);
1460 TALLOC_FREE(brl);
1464 DEBUG(10,("grant_fsp_oplock_type: oplock type 0x%x on file %s\n",
1465 fsp->oplock_type, fsp_str_dbg(fsp)));
1468 static bool request_timed_out(struct timeval request_time,
1469 struct timeval timeout)
1471 struct timeval now, end_time;
1472 GetTimeOfDay(&now);
1473 end_time = timeval_sum(&request_time, &timeout);
1474 return (timeval_compare(&end_time, &now) < 0);
1477 struct defer_open_state {
1478 struct smbd_server_connection *sconn;
1479 uint64_t mid;
1482 static void defer_open_done(struct tevent_req *req);
1484 /****************************************************************************
1485 Handle the 1 second delay in returning a SHARING_VIOLATION error.
1486 ****************************************************************************/
1488 static void defer_open(struct share_mode_lock *lck,
1489 struct timeval request_time,
1490 struct timeval timeout,
1491 struct smb_request *req,
1492 struct deferred_open_record *state)
1494 DEBUG(10,("defer_open_sharing_error: time [%u.%06u] adding deferred "
1495 "open entry for mid %llu\n",
1496 (unsigned int)request_time.tv_sec,
1497 (unsigned int)request_time.tv_usec,
1498 (unsigned long long)req->mid));
1500 if (!push_deferred_open_message_smb(req, request_time, timeout,
1501 state->id, (char *)state, sizeof(*state))) {
1502 TALLOC_FREE(lck);
1503 exit_server("push_deferred_open_message_smb failed");
1505 if (lck) {
1506 struct defer_open_state *watch_state;
1507 struct tevent_req *watch_req;
1508 bool ret;
1510 watch_state = talloc(req->sconn, struct defer_open_state);
1511 if (watch_state == NULL) {
1512 exit_server("talloc failed");
1514 watch_state->sconn = req->sconn;
1515 watch_state->mid = req->mid;
1517 DEBUG(10, ("defering mid %llu\n",
1518 (unsigned long long)req->mid));
1520 watch_req = dbwrap_record_watch_send(
1521 watch_state, req->sconn->ev_ctx, lck->data->record,
1522 req->sconn->msg_ctx);
1523 if (watch_req == NULL) {
1524 exit_server("Could not watch share mode record");
1526 tevent_req_set_callback(watch_req, defer_open_done,
1527 watch_state);
1529 ret = tevent_req_set_endtime(
1530 watch_req, req->sconn->ev_ctx,
1531 timeval_sum(&request_time, &timeout));
1532 SMB_ASSERT(ret);
1536 static void defer_open_done(struct tevent_req *req)
1538 struct defer_open_state *state = tevent_req_callback_data(
1539 req, struct defer_open_state);
1540 NTSTATUS status;
1541 bool ret;
1543 status = dbwrap_record_watch_recv(req, talloc_tos(), NULL);
1544 TALLOC_FREE(req);
1545 if (!NT_STATUS_IS_OK(status)) {
1546 DEBUG(5, ("dbwrap_record_watch_recv returned %s\n",
1547 nt_errstr(status)));
1549 * Even if it failed, retry anyway. TODO: We need a way to
1550 * tell a re-scheduled open about that error.
1554 DEBUG(10, ("scheduling mid %llu\n", (unsigned long long)state->mid));
1556 ret = schedule_deferred_open_message_smb(state->sconn, state->mid);
1557 SMB_ASSERT(ret);
1558 TALLOC_FREE(state);
1562 /****************************************************************************
1563 On overwrite open ensure that the attributes match.
1564 ****************************************************************************/
1566 static bool open_match_attributes(connection_struct *conn,
1567 uint32 old_dos_attr,
1568 uint32 new_dos_attr,
1569 mode_t existing_unx_mode,
1570 mode_t new_unx_mode,
1571 mode_t *returned_unx_mode)
1573 uint32 noarch_old_dos_attr, noarch_new_dos_attr;
1575 noarch_old_dos_attr = (old_dos_attr & ~FILE_ATTRIBUTE_ARCHIVE);
1576 noarch_new_dos_attr = (new_dos_attr & ~FILE_ATTRIBUTE_ARCHIVE);
1578 if((noarch_old_dos_attr == 0 && noarch_new_dos_attr != 0) ||
1579 (noarch_old_dos_attr != 0 && ((noarch_old_dos_attr & noarch_new_dos_attr) == noarch_old_dos_attr))) {
1580 *returned_unx_mode = new_unx_mode;
1581 } else {
1582 *returned_unx_mode = (mode_t)0;
1585 DEBUG(10,("open_match_attributes: old_dos_attr = 0x%x, "
1586 "existing_unx_mode = 0%o, new_dos_attr = 0x%x "
1587 "returned_unx_mode = 0%o\n",
1588 (unsigned int)old_dos_attr,
1589 (unsigned int)existing_unx_mode,
1590 (unsigned int)new_dos_attr,
1591 (unsigned int)*returned_unx_mode ));
1593 /* If we're mapping SYSTEM and HIDDEN ensure they match. */
1594 if (lp_map_system(SNUM(conn)) || lp_store_dos_attributes(SNUM(conn))) {
1595 if ((old_dos_attr & FILE_ATTRIBUTE_SYSTEM) &&
1596 !(new_dos_attr & FILE_ATTRIBUTE_SYSTEM)) {
1597 return False;
1600 if (lp_map_hidden(SNUM(conn)) || lp_store_dos_attributes(SNUM(conn))) {
1601 if ((old_dos_attr & FILE_ATTRIBUTE_HIDDEN) &&
1602 !(new_dos_attr & FILE_ATTRIBUTE_HIDDEN)) {
1603 return False;
1606 return True;
1609 /****************************************************************************
1610 Special FCB or DOS processing in the case of a sharing violation.
1611 Try and find a duplicated file handle.
1612 ****************************************************************************/
1614 static NTSTATUS fcb_or_dos_open(struct smb_request *req,
1615 connection_struct *conn,
1616 files_struct *fsp_to_dup_into,
1617 const struct smb_filename *smb_fname,
1618 struct file_id id,
1619 uint16 file_pid,
1620 uint64_t vuid,
1621 uint32 access_mask,
1622 uint32 share_access,
1623 uint32 create_options)
1625 files_struct *fsp;
1627 DEBUG(5,("fcb_or_dos_open: attempting old open semantics for "
1628 "file %s.\n", smb_fname_str_dbg(smb_fname)));
1630 for(fsp = file_find_di_first(conn->sconn, id); fsp;
1631 fsp = file_find_di_next(fsp)) {
1633 DEBUG(10,("fcb_or_dos_open: checking file %s, fd = %d, "
1634 "vuid = %llu, file_pid = %u, private_options = 0x%x "
1635 "access_mask = 0x%x\n", fsp_str_dbg(fsp),
1636 fsp->fh->fd, (unsigned long long)fsp->vuid,
1637 (unsigned int)fsp->file_pid,
1638 (unsigned int)fsp->fh->private_options,
1639 (unsigned int)fsp->access_mask ));
1641 if (fsp != fsp_to_dup_into &&
1642 fsp->fh->fd != -1 &&
1643 fsp->vuid == vuid &&
1644 fsp->file_pid == file_pid &&
1645 (fsp->fh->private_options & (NTCREATEX_OPTIONS_PRIVATE_DENY_DOS |
1646 NTCREATEX_OPTIONS_PRIVATE_DENY_FCB)) &&
1647 (fsp->access_mask & FILE_WRITE_DATA) &&
1648 strequal(fsp->fsp_name->base_name, smb_fname->base_name) &&
1649 strequal(fsp->fsp_name->stream_name,
1650 smb_fname->stream_name)) {
1651 DEBUG(10,("fcb_or_dos_open: file match\n"));
1652 break;
1656 if (!fsp) {
1657 return NT_STATUS_NOT_FOUND;
1660 /* quite an insane set of semantics ... */
1661 if (is_executable(smb_fname->base_name) &&
1662 (fsp->fh->private_options & NTCREATEX_OPTIONS_PRIVATE_DENY_DOS)) {
1663 DEBUG(10,("fcb_or_dos_open: file fail due to is_executable.\n"));
1664 return NT_STATUS_INVALID_PARAMETER;
1667 /* We need to duplicate this fsp. */
1668 return dup_file_fsp(req, fsp, access_mask, share_access,
1669 create_options, fsp_to_dup_into);
1672 static void schedule_defer_open(struct share_mode_lock *lck,
1673 struct timeval request_time,
1674 struct smb_request *req)
1676 struct deferred_open_record state;
1678 /* This is a relative time, added to the absolute
1679 request_time value to get the absolute timeout time.
1680 Note that if this is the second or greater time we enter
1681 this codepath for this particular request mid then
1682 request_time is left as the absolute time of the *first*
1683 time this request mid was processed. This is what allows
1684 the request to eventually time out. */
1686 struct timeval timeout;
1688 /* Normally the smbd we asked should respond within
1689 * OPLOCK_BREAK_TIMEOUT seconds regardless of whether
1690 * the client did, give twice the timeout as a safety
1691 * measure here in case the other smbd is stuck
1692 * somewhere else. */
1694 timeout = timeval_set(OPLOCK_BREAK_TIMEOUT*2, 0);
1696 /* Nothing actually uses state.delayed_for_oplocks
1697 but it's handy to differentiate in debug messages
1698 between a 30 second delay due to oplock break, and
1699 a 1 second delay for share mode conflicts. */
1701 state.delayed_for_oplocks = True;
1702 state.async_open = false;
1703 state.id = lck->data->id;
1705 if (!request_timed_out(request_time, timeout)) {
1706 defer_open(lck, request_time, timeout, req, &state);
1710 /****************************************************************************
1711 Reschedule an open call that went asynchronous.
1712 ****************************************************************************/
1714 static void schedule_async_open(struct timeval request_time,
1715 struct smb_request *req)
1717 struct deferred_open_record state;
1718 struct timeval timeout;
1720 timeout = timeval_set(20, 0);
1722 ZERO_STRUCT(state);
1723 state.delayed_for_oplocks = false;
1724 state.async_open = true;
1726 if (!request_timed_out(request_time, timeout)) {
1727 defer_open(NULL, request_time, timeout, req, &state);
1731 /****************************************************************************
1732 Work out what access_mask to use from what the client sent us.
1733 ****************************************************************************/
1735 static NTSTATUS smbd_calculate_maximum_allowed_access(
1736 connection_struct *conn,
1737 const struct smb_filename *smb_fname,
1738 bool use_privs,
1739 uint32_t *p_access_mask)
1741 struct security_descriptor *sd;
1742 uint32_t access_granted;
1743 NTSTATUS status;
1745 if (!use_privs && (get_current_uid(conn) == (uid_t)0)) {
1746 *p_access_mask |= FILE_GENERIC_ALL;
1747 return NT_STATUS_OK;
1750 status = SMB_VFS_GET_NT_ACL(conn, smb_fname->base_name,
1751 (SECINFO_OWNER |
1752 SECINFO_GROUP |
1753 SECINFO_DACL),
1754 talloc_tos(), &sd);
1756 if (NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
1758 * File did not exist
1760 *p_access_mask = FILE_GENERIC_ALL;
1761 return NT_STATUS_OK;
1763 if (!NT_STATUS_IS_OK(status)) {
1764 DEBUG(10,("Could not get acl on file %s: %s\n",
1765 smb_fname_str_dbg(smb_fname),
1766 nt_errstr(status)));
1767 return NT_STATUS_ACCESS_DENIED;
1771 * If we can access the path to this file, by
1772 * default we have FILE_READ_ATTRIBUTES from the
1773 * containing directory. See the section:
1774 * "Algorithm to Check Access to an Existing File"
1775 * in MS-FSA.pdf.
1777 * se_file_access_check()
1778 * also takes care of owner WRITE_DAC and READ_CONTROL.
1780 status = se_file_access_check(sd,
1781 get_current_nttok(conn),
1782 use_privs,
1783 (*p_access_mask & ~FILE_READ_ATTRIBUTES),
1784 &access_granted);
1786 TALLOC_FREE(sd);
1788 if (!NT_STATUS_IS_OK(status)) {
1789 DEBUG(10, ("Access denied on file %s: "
1790 "when calculating maximum access\n",
1791 smb_fname_str_dbg(smb_fname)));
1792 return NT_STATUS_ACCESS_DENIED;
1794 *p_access_mask = (access_granted | FILE_READ_ATTRIBUTES);
1796 if (!(access_granted & DELETE_ACCESS)) {
1797 if (can_delete_file_in_directory(conn, smb_fname)) {
1798 *p_access_mask |= DELETE_ACCESS;
1802 return NT_STATUS_OK;
1805 NTSTATUS smbd_calculate_access_mask(connection_struct *conn,
1806 const struct smb_filename *smb_fname,
1807 bool use_privs,
1808 uint32_t access_mask,
1809 uint32_t *access_mask_out)
1811 NTSTATUS status;
1812 uint32_t orig_access_mask = access_mask;
1813 uint32_t rejected_share_access;
1816 * Convert GENERIC bits to specific bits.
1819 se_map_generic(&access_mask, &file_generic_mapping);
1821 /* Calculate MAXIMUM_ALLOWED_ACCESS if requested. */
1822 if (access_mask & MAXIMUM_ALLOWED_ACCESS) {
1824 status = smbd_calculate_maximum_allowed_access(
1825 conn, smb_fname, use_privs, &access_mask);
1827 if (!NT_STATUS_IS_OK(status)) {
1828 return status;
1831 access_mask &= conn->share_access;
1834 rejected_share_access = access_mask & ~(conn->share_access);
1836 if (rejected_share_access) {
1837 DEBUG(10, ("smbd_calculate_access_mask: Access denied on "
1838 "file %s: rejected by share access mask[0x%08X] "
1839 "orig[0x%08X] mapped[0x%08X] reject[0x%08X]\n",
1840 smb_fname_str_dbg(smb_fname),
1841 conn->share_access,
1842 orig_access_mask, access_mask,
1843 rejected_share_access));
1844 return NT_STATUS_ACCESS_DENIED;
1847 *access_mask_out = access_mask;
1848 return NT_STATUS_OK;
1851 /****************************************************************************
1852 Remove the deferred open entry under lock.
1853 ****************************************************************************/
1855 /****************************************************************************
1856 Return true if this is a state pointer to an asynchronous create.
1857 ****************************************************************************/
1859 bool is_deferred_open_async(const void *ptr)
1861 const struct deferred_open_record *state = (const struct deferred_open_record *)ptr;
1863 return state->async_open;
1866 static bool clear_ads(uint32_t create_disposition)
1868 bool ret = false;
1870 switch (create_disposition) {
1871 case FILE_SUPERSEDE:
1872 case FILE_OVERWRITE_IF:
1873 case FILE_OVERWRITE:
1874 ret = true;
1875 break;
1876 default:
1877 break;
1879 return ret;
1882 static int disposition_to_open_flags(uint32_t create_disposition)
1884 int ret = 0;
1887 * Currently we're using FILE_SUPERSEDE as the same as
1888 * FILE_OVERWRITE_IF but they really are
1889 * different. FILE_SUPERSEDE deletes an existing file
1890 * (requiring delete access) then recreates it.
1893 switch (create_disposition) {
1894 case FILE_SUPERSEDE:
1895 case FILE_OVERWRITE_IF:
1897 * If file exists replace/overwrite. If file doesn't
1898 * exist create.
1900 ret = O_CREAT|O_TRUNC;
1901 break;
1903 case FILE_OPEN:
1905 * If file exists open. If file doesn't exist error.
1907 ret = 0;
1908 break;
1910 case FILE_OVERWRITE:
1912 * If file exists overwrite. If file doesn't exist
1913 * error.
1915 ret = O_TRUNC;
1916 break;
1918 case FILE_CREATE:
1920 * If file exists error. If file doesn't exist create.
1922 ret = O_CREAT|O_EXCL;
1923 break;
1925 case FILE_OPEN_IF:
1927 * If file exists open. If file doesn't exist create.
1929 ret = O_CREAT;
1930 break;
1932 return ret;
1935 static int calculate_open_access_flags(uint32_t access_mask,
1936 int oplock_request,
1937 uint32_t private_flags)
1939 bool need_write, need_read;
1942 * Note that we ignore the append flag as append does not
1943 * mean the same thing under DOS and Unix.
1946 need_write = (access_mask & (FILE_WRITE_DATA | FILE_APPEND_DATA));
1947 if (!need_write) {
1948 return O_RDONLY;
1951 /* DENY_DOS opens are always underlying read-write on the
1952 file handle, no matter what the requested access mask
1953 says. */
1955 need_read =
1956 ((private_flags & NTCREATEX_OPTIONS_PRIVATE_DENY_DOS) ||
1957 access_mask & (FILE_READ_ATTRIBUTES|FILE_READ_DATA|
1958 FILE_READ_EA|FILE_EXECUTE));
1960 if (!need_read) {
1961 return O_WRONLY;
1963 return O_RDWR;
1966 /****************************************************************************
1967 Open a file with a share mode. Passed in an already created files_struct *.
1968 ****************************************************************************/
1970 static NTSTATUS open_file_ntcreate(connection_struct *conn,
1971 struct smb_request *req,
1972 uint32 access_mask, /* access bits (FILE_READ_DATA etc.) */
1973 uint32 share_access, /* share constants (FILE_SHARE_READ etc) */
1974 uint32 create_disposition, /* FILE_OPEN_IF etc. */
1975 uint32 create_options, /* options such as delete on close. */
1976 uint32 new_dos_attributes, /* attributes used for new file. */
1977 int oplock_request, /* internal Samba oplock codes. */
1978 /* Information (FILE_EXISTS etc.) */
1979 uint32_t private_flags, /* Samba specific flags. */
1980 int *pinfo,
1981 files_struct *fsp)
1983 struct smb_filename *smb_fname = fsp->fsp_name;
1984 int flags=0;
1985 int flags2=0;
1986 bool file_existed = VALID_STAT(smb_fname->st);
1987 bool def_acl = False;
1988 bool posix_open = False;
1989 bool new_file_created = False;
1990 bool first_open_attempt = true;
1991 NTSTATUS fsp_open = NT_STATUS_ACCESS_DENIED;
1992 mode_t new_unx_mode = (mode_t)0;
1993 mode_t unx_mode = (mode_t)0;
1994 int info;
1995 uint32 existing_dos_attributes = 0;
1996 struct timeval request_time = timeval_zero();
1997 struct share_mode_lock *lck = NULL;
1998 uint32 open_access_mask = access_mask;
1999 NTSTATUS status;
2000 char *parent_dir;
2001 SMB_STRUCT_STAT saved_stat = smb_fname->st;
2002 struct timespec old_write_time;
2003 struct file_id id;
2005 if (conn->printer) {
2007 * Printers are handled completely differently.
2008 * Most of the passed parameters are ignored.
2011 if (pinfo) {
2012 *pinfo = FILE_WAS_CREATED;
2015 DEBUG(10, ("open_file_ntcreate: printer open fname=%s\n",
2016 smb_fname_str_dbg(smb_fname)));
2018 if (!req) {
2019 DEBUG(0,("open_file_ntcreate: printer open without "
2020 "an SMB request!\n"));
2021 return NT_STATUS_INTERNAL_ERROR;
2024 return print_spool_open(fsp, smb_fname->base_name,
2025 req->vuid);
2028 if (!parent_dirname(talloc_tos(), smb_fname->base_name, &parent_dir,
2029 NULL)) {
2030 return NT_STATUS_NO_MEMORY;
2033 if (new_dos_attributes & FILE_FLAG_POSIX_SEMANTICS) {
2034 posix_open = True;
2035 unx_mode = (mode_t)(new_dos_attributes & ~FILE_FLAG_POSIX_SEMANTICS);
2036 new_dos_attributes = 0;
2037 } else {
2038 /* Windows allows a new file to be created and
2039 silently removes a FILE_ATTRIBUTE_DIRECTORY
2040 sent by the client. Do the same. */
2042 new_dos_attributes &= ~FILE_ATTRIBUTE_DIRECTORY;
2044 /* We add FILE_ATTRIBUTE_ARCHIVE to this as this mode is only used if the file is
2045 * created new. */
2046 unx_mode = unix_mode(conn, new_dos_attributes | FILE_ATTRIBUTE_ARCHIVE,
2047 smb_fname, parent_dir);
2050 DEBUG(10, ("open_file_ntcreate: fname=%s, dos_attrs=0x%x "
2051 "access_mask=0x%x share_access=0x%x "
2052 "create_disposition = 0x%x create_options=0x%x "
2053 "unix mode=0%o oplock_request=%d private_flags = 0x%x\n",
2054 smb_fname_str_dbg(smb_fname), new_dos_attributes,
2055 access_mask, share_access, create_disposition,
2056 create_options, (unsigned int)unx_mode, oplock_request,
2057 (unsigned int)private_flags));
2059 if ((req == NULL) && ((oplock_request & INTERNAL_OPEN_ONLY) == 0)) {
2060 DEBUG(0, ("No smb request but not an internal only open!\n"));
2061 return NT_STATUS_INTERNAL_ERROR;
2065 * Only non-internal opens can be deferred at all
2068 if (req) {
2069 void *ptr;
2070 if (get_deferred_open_message_state(req,
2071 &request_time,
2072 &ptr)) {
2073 /* Remember the absolute time of the original
2074 request with this mid. We'll use it later to
2075 see if this has timed out. */
2077 /* If it was an async create retry, the file
2078 didn't exist. */
2080 if (is_deferred_open_async(ptr)) {
2081 SET_STAT_INVALID(smb_fname->st);
2082 file_existed = false;
2085 /* Ensure we don't reprocess this message. */
2086 remove_deferred_open_message_smb(req->sconn, req->mid);
2088 first_open_attempt = false;
2092 if (!posix_open) {
2093 new_dos_attributes &= SAMBA_ATTRIBUTES_MASK;
2094 if (file_existed) {
2095 existing_dos_attributes = dos_mode(conn, smb_fname);
2099 /* ignore any oplock requests if oplocks are disabled */
2100 if (!lp_oplocks(SNUM(conn)) ||
2101 IS_VETO_OPLOCK_PATH(conn, smb_fname->base_name)) {
2102 /* Mask off everything except the private Samba bits. */
2103 oplock_request &= SAMBA_PRIVATE_OPLOCK_MASK;
2106 /* this is for OS/2 long file names - say we don't support them */
2107 if (!lp_posix_pathnames() && strstr(smb_fname->base_name,".+,;=[].")) {
2108 /* OS/2 Workplace shell fix may be main code stream in a later
2109 * release. */
2110 DEBUG(5,("open_file_ntcreate: OS/2 long filenames are not "
2111 "supported.\n"));
2112 if (use_nt_status()) {
2113 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
2115 return NT_STATUS_DOS(ERRDOS, ERRcannotopen);
2118 switch( create_disposition ) {
2119 case FILE_OPEN:
2120 /* If file exists open. If file doesn't exist error. */
2121 if (!file_existed) {
2122 DEBUG(5,("open_file_ntcreate: FILE_OPEN "
2123 "requested for file %s and file "
2124 "doesn't exist.\n",
2125 smb_fname_str_dbg(smb_fname)));
2126 errno = ENOENT;
2127 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
2129 break;
2131 case FILE_OVERWRITE:
2132 /* If file exists overwrite. If file doesn't exist
2133 * error. */
2134 if (!file_existed) {
2135 DEBUG(5,("open_file_ntcreate: FILE_OVERWRITE "
2136 "requested for file %s and file "
2137 "doesn't exist.\n",
2138 smb_fname_str_dbg(smb_fname) ));
2139 errno = ENOENT;
2140 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
2142 break;
2144 case FILE_CREATE:
2145 /* If file exists error. If file doesn't exist
2146 * create. */
2147 if (file_existed) {
2148 DEBUG(5,("open_file_ntcreate: FILE_CREATE "
2149 "requested for file %s and file "
2150 "already exists.\n",
2151 smb_fname_str_dbg(smb_fname)));
2152 if (S_ISDIR(smb_fname->st.st_ex_mode)) {
2153 errno = EISDIR;
2154 } else {
2155 errno = EEXIST;
2157 return map_nt_error_from_unix(errno);
2159 break;
2161 case FILE_SUPERSEDE:
2162 case FILE_OVERWRITE_IF:
2163 case FILE_OPEN_IF:
2164 break;
2165 default:
2166 return NT_STATUS_INVALID_PARAMETER;
2169 flags2 = disposition_to_open_flags(create_disposition);
2171 /* We only care about matching attributes on file exists and
2172 * overwrite. */
2174 if (!posix_open && file_existed &&
2175 ((create_disposition == FILE_OVERWRITE) ||
2176 (create_disposition == FILE_OVERWRITE_IF))) {
2177 if (!open_match_attributes(conn, existing_dos_attributes,
2178 new_dos_attributes,
2179 smb_fname->st.st_ex_mode,
2180 unx_mode, &new_unx_mode)) {
2181 DEBUG(5,("open_file_ntcreate: attributes missmatch "
2182 "for file %s (%x %x) (0%o, 0%o)\n",
2183 smb_fname_str_dbg(smb_fname),
2184 existing_dos_attributes,
2185 new_dos_attributes,
2186 (unsigned int)smb_fname->st.st_ex_mode,
2187 (unsigned int)unx_mode ));
2188 errno = EACCES;
2189 return NT_STATUS_ACCESS_DENIED;
2193 status = smbd_calculate_access_mask(conn, smb_fname,
2194 false,
2195 access_mask,
2196 &access_mask);
2197 if (!NT_STATUS_IS_OK(status)) {
2198 DEBUG(10, ("open_file_ntcreate: smbd_calculate_access_mask "
2199 "on file %s returned %s\n",
2200 smb_fname_str_dbg(smb_fname), nt_errstr(status)));
2201 return status;
2204 open_access_mask = access_mask;
2206 if (flags2 & O_TRUNC) {
2207 open_access_mask |= FILE_WRITE_DATA; /* This will cause oplock breaks. */
2210 DEBUG(10, ("open_file_ntcreate: fname=%s, after mapping "
2211 "access_mask=0x%x\n", smb_fname_str_dbg(smb_fname),
2212 access_mask));
2215 * Note that we ignore the append flag as append does not
2216 * mean the same thing under DOS and Unix.
2219 flags = calculate_open_access_flags(access_mask, oplock_request,
2220 private_flags);
2223 * Currently we only look at FILE_WRITE_THROUGH for create options.
2226 #if defined(O_SYNC)
2227 if ((create_options & FILE_WRITE_THROUGH) && lp_strict_sync(SNUM(conn))) {
2228 flags2 |= O_SYNC;
2230 #endif /* O_SYNC */
2232 if (posix_open && (access_mask & FILE_APPEND_DATA)) {
2233 flags2 |= O_APPEND;
2236 if (!posix_open && !CAN_WRITE(conn)) {
2238 * We should really return a permission denied error if either
2239 * O_CREAT or O_TRUNC are set, but for compatibility with
2240 * older versions of Samba we just AND them out.
2242 flags2 &= ~(O_CREAT|O_TRUNC);
2245 if (first_open_attempt && lp_kernel_oplocks(SNUM(conn))) {
2247 * With kernel oplocks the open breaking an oplock
2248 * blocks until the oplock holder has given up the
2249 * oplock or closed the file. We prevent this by first
2250 * trying to open the file with O_NONBLOCK (see "man
2251 * fcntl" on Linux). For the second try, triggered by
2252 * an oplock break response, we do not need this
2253 * anymore.
2255 * This is true under the assumption that only Samba
2256 * requests kernel oplocks. Once someone else like
2257 * NFSv4 starts to use that API, we will have to
2258 * modify this by communicating with the NFSv4 server.
2260 flags2 |= O_NONBLOCK;
2264 * Ensure we can't write on a read-only share or file.
2267 if (flags != O_RDONLY && file_existed &&
2268 (!CAN_WRITE(conn) || IS_DOS_READONLY(existing_dos_attributes))) {
2269 DEBUG(5,("open_file_ntcreate: write access requested for "
2270 "file %s on read only %s\n",
2271 smb_fname_str_dbg(smb_fname),
2272 !CAN_WRITE(conn) ? "share" : "file" ));
2273 errno = EACCES;
2274 return NT_STATUS_ACCESS_DENIED;
2277 fsp->file_id = vfs_file_id_from_sbuf(conn, &smb_fname->st);
2278 fsp->share_access = share_access;
2279 fsp->fh->private_options = private_flags;
2280 fsp->access_mask = open_access_mask; /* We change this to the
2281 * requested access_mask after
2282 * the open is done. */
2283 fsp->posix_open = posix_open;
2285 /* Ensure no SAMBA_PRIVATE bits can be set. */
2286 fsp->oplock_type = (oplock_request & ~SAMBA_PRIVATE_OPLOCK_MASK);
2288 if (timeval_is_zero(&request_time)) {
2289 request_time = fsp->open_time;
2293 * Ensure we pay attention to default ACLs on directories if required.
2296 if ((flags2 & O_CREAT) && lp_inherit_acls(SNUM(conn)) &&
2297 (def_acl = directory_has_default_acl(conn, parent_dir))) {
2298 unx_mode = (0777 & lp_create_mask(SNUM(conn)));
2301 DEBUG(4,("calling open_file with flags=0x%X flags2=0x%X mode=0%o, "
2302 "access_mask = 0x%x, open_access_mask = 0x%x\n",
2303 (unsigned int)flags, (unsigned int)flags2,
2304 (unsigned int)unx_mode, (unsigned int)access_mask,
2305 (unsigned int)open_access_mask));
2307 fsp_open = open_file(fsp, conn, req, parent_dir,
2308 flags|flags2, unx_mode, access_mask,
2309 open_access_mask, &new_file_created);
2311 if (NT_STATUS_EQUAL(fsp_open, NT_STATUS_NETWORK_BUSY)) {
2312 struct deferred_open_record state;
2315 * EWOULDBLOCK/EAGAIN maps to NETWORK_BUSY.
2317 if (file_existed && S_ISFIFO(fsp->fsp_name->st.st_ex_mode)) {
2318 DEBUG(10, ("FIFO busy\n"));
2319 return NT_STATUS_NETWORK_BUSY;
2321 if (req == NULL) {
2322 DEBUG(10, ("Internal open busy\n"));
2323 return NT_STATUS_NETWORK_BUSY;
2327 * From here on we assume this is an oplock break triggered
2330 lck = get_existing_share_mode_lock(talloc_tos(), fsp->file_id);
2331 if (lck == NULL) {
2332 state.delayed_for_oplocks = false;
2333 state.async_open = false;
2334 state.id = fsp->file_id;
2335 defer_open(NULL, request_time, timeval_set(0, 0),
2336 req, &state);
2337 DEBUG(10, ("No share mode lock found after "
2338 "EWOULDBLOCK, retrying sync\n"));
2339 return NT_STATUS_SHARING_VIOLATION;
2342 if (!validate_oplock_types(lck)) {
2343 smb_panic("validate_oplock_types failed");
2346 if (delay_for_oplock(fsp, 0, lck, false)) {
2347 schedule_defer_open(lck, request_time, req);
2348 TALLOC_FREE(lck);
2349 DEBUG(10, ("Sent oplock break request to kernel "
2350 "oplock holder\n"));
2351 return NT_STATUS_SHARING_VIOLATION;
2355 * No oplock from Samba around. Immediately retry with
2356 * a blocking open.
2358 state.delayed_for_oplocks = false;
2359 state.async_open = false;
2360 state.id = lck->data->id;
2361 defer_open(lck, request_time, timeval_set(0, 0), req, &state);
2362 TALLOC_FREE(lck);
2363 DEBUG(10, ("No Samba oplock around after EWOULDBLOCK. "
2364 "Retrying sync\n"));
2365 return NT_STATUS_SHARING_VIOLATION;
2368 if (!NT_STATUS_IS_OK(fsp_open)) {
2369 if (NT_STATUS_EQUAL(fsp_open, NT_STATUS_RETRY)) {
2370 schedule_async_open(request_time, req);
2372 return fsp_open;
2375 if (file_existed && !check_same_dev_ino(&saved_stat, &smb_fname->st)) {
2377 * The file did exist, but some other (local or NFS)
2378 * process either renamed/unlinked and re-created the
2379 * file with different dev/ino after we walked the path,
2380 * but before we did the open. We could retry the
2381 * open but it's a rare enough case it's easier to
2382 * just fail the open to prevent creating any problems
2383 * in the open file db having the wrong dev/ino key.
2385 fd_close(fsp);
2386 DEBUG(1,("open_file_ntcreate: file %s - dev/ino mismatch. "
2387 "Old (dev=0x%llu, ino =0x%llu). "
2388 "New (dev=0x%llu, ino=0x%llu). Failing open "
2389 " with NT_STATUS_ACCESS_DENIED.\n",
2390 smb_fname_str_dbg(smb_fname),
2391 (unsigned long long)saved_stat.st_ex_dev,
2392 (unsigned long long)saved_stat.st_ex_ino,
2393 (unsigned long long)smb_fname->st.st_ex_dev,
2394 (unsigned long long)smb_fname->st.st_ex_ino));
2395 return NT_STATUS_ACCESS_DENIED;
2398 old_write_time = smb_fname->st.st_ex_mtime;
2401 * Deal with the race condition where two smbd's detect the
2402 * file doesn't exist and do the create at the same time. One
2403 * of them will win and set a share mode, the other (ie. this
2404 * one) should check if the requested share mode for this
2405 * create is allowed.
2409 * Now the file exists and fsp is successfully opened,
2410 * fsp->dev and fsp->inode are valid and should replace the
2411 * dev=0,inode=0 from a non existent file. Spotted by
2412 * Nadav Danieli <nadavd@exanet.com>. JRA.
2415 id = fsp->file_id;
2417 lck = get_share_mode_lock(talloc_tos(), id,
2418 conn->connectpath,
2419 smb_fname, &old_write_time);
2421 if (lck == NULL) {
2422 DEBUG(0, ("open_file_ntcreate: Could not get share "
2423 "mode lock for %s\n",
2424 smb_fname_str_dbg(smb_fname)));
2425 fd_close(fsp);
2426 return NT_STATUS_SHARING_VIOLATION;
2429 /* Get the types we need to examine. */
2430 if (!validate_oplock_types(lck)) {
2431 smb_panic("validate_oplock_types failed");
2434 if (has_delete_on_close(lck, fsp->name_hash)) {
2435 TALLOC_FREE(lck);
2436 fd_close(fsp);
2437 return NT_STATUS_DELETE_PENDING;
2440 status = open_mode_check(conn, lck,
2441 access_mask, share_access);
2443 if (NT_STATUS_EQUAL(status, NT_STATUS_SHARING_VIOLATION) ||
2444 (lck->data->num_share_modes > 0)) {
2446 * This comes from ancient times out of open_mode_check. I
2447 * have no clue whether this is still necessary. I can't think
2448 * of a case where this would actually matter further down in
2449 * this function. I leave it here for further investigation
2450 * :-)
2452 file_existed = true;
2455 if ((req != NULL) &&
2456 delay_for_oplock(
2457 fsp, oplock_request, lck,
2458 NT_STATUS_EQUAL(status, NT_STATUS_SHARING_VIOLATION))) {
2459 schedule_defer_open(lck, request_time, req);
2460 TALLOC_FREE(lck);
2461 fd_close(fsp);
2462 return NT_STATUS_SHARING_VIOLATION;
2465 if (!NT_STATUS_IS_OK(status)) {
2466 uint32 can_access_mask;
2467 bool can_access = True;
2469 SMB_ASSERT(NT_STATUS_EQUAL(status, NT_STATUS_SHARING_VIOLATION));
2471 /* Check if this can be done with the deny_dos and fcb
2472 * calls. */
2473 if (private_flags &
2474 (NTCREATEX_OPTIONS_PRIVATE_DENY_DOS|
2475 NTCREATEX_OPTIONS_PRIVATE_DENY_FCB)) {
2476 if (req == NULL) {
2477 DEBUG(0, ("DOS open without an SMB "
2478 "request!\n"));
2479 TALLOC_FREE(lck);
2480 fd_close(fsp);
2481 return NT_STATUS_INTERNAL_ERROR;
2484 /* Use the client requested access mask here,
2485 * not the one we open with. */
2486 status = fcb_or_dos_open(req,
2487 conn,
2488 fsp,
2489 smb_fname,
2491 req->smbpid,
2492 req->vuid,
2493 access_mask,
2494 share_access,
2495 create_options);
2497 if (NT_STATUS_IS_OK(status)) {
2498 TALLOC_FREE(lck);
2499 if (pinfo) {
2500 *pinfo = FILE_WAS_OPENED;
2502 return NT_STATUS_OK;
2507 * This next line is a subtlety we need for
2508 * MS-Access. If a file open will fail due to share
2509 * permissions and also for security (access) reasons,
2510 * we need to return the access failed error, not the
2511 * share error. We can't open the file due to kernel
2512 * oplock deadlock (it's possible we failed above on
2513 * the open_mode_check()) so use a userspace check.
2516 if (flags & O_RDWR) {
2517 can_access_mask = FILE_READ_DATA|FILE_WRITE_DATA;
2518 } else if (flags & O_WRONLY) {
2519 can_access_mask = FILE_WRITE_DATA;
2520 } else {
2521 can_access_mask = FILE_READ_DATA;
2524 if (((can_access_mask & FILE_WRITE_DATA) &&
2525 !CAN_WRITE(conn)) ||
2526 !NT_STATUS_IS_OK(smbd_check_access_rights(conn,
2527 smb_fname,
2528 false,
2529 can_access_mask))) {
2530 can_access = False;
2534 * If we're returning a share violation, ensure we
2535 * cope with the braindead 1 second delay (SMB1 only).
2538 if (!(oplock_request & INTERNAL_OPEN_ONLY) &&
2539 !conn->sconn->using_smb2 &&
2540 lp_defer_sharing_violations()) {
2541 struct timeval timeout;
2542 struct deferred_open_record state;
2543 int timeout_usecs;
2545 /* this is a hack to speed up torture tests
2546 in 'make test' */
2547 timeout_usecs = lp_parm_int(SNUM(conn),
2548 "smbd","sharedelay",
2549 SHARING_VIOLATION_USEC_WAIT);
2551 /* This is a relative time, added to the absolute
2552 request_time value to get the absolute timeout time.
2553 Note that if this is the second or greater time we enter
2554 this codepath for this particular request mid then
2555 request_time is left as the absolute time of the *first*
2556 time this request mid was processed. This is what allows
2557 the request to eventually time out. */
2559 timeout = timeval_set(0, timeout_usecs);
2561 /* Nothing actually uses state.delayed_for_oplocks
2562 but it's handy to differentiate in debug messages
2563 between a 30 second delay due to oplock break, and
2564 a 1 second delay for share mode conflicts. */
2566 state.delayed_for_oplocks = False;
2567 state.async_open = false;
2568 state.id = id;
2570 if ((req != NULL)
2571 && !request_timed_out(request_time,
2572 timeout)) {
2573 defer_open(lck, request_time, timeout,
2574 req, &state);
2578 TALLOC_FREE(lck);
2579 fd_close(fsp);
2580 if (can_access) {
2582 * We have detected a sharing violation here
2583 * so return the correct error code
2585 status = NT_STATUS_SHARING_VIOLATION;
2586 } else {
2587 status = NT_STATUS_ACCESS_DENIED;
2589 return status;
2592 grant_fsp_oplock_type(fsp, lck, oplock_request);
2595 * We have the share entry *locked*.....
2598 /* Delete streams if create_disposition requires it */
2599 if (!new_file_created && clear_ads(create_disposition) &&
2600 !is_ntfs_stream_smb_fname(smb_fname)) {
2601 status = delete_all_streams(conn, smb_fname->base_name);
2602 if (!NT_STATUS_IS_OK(status)) {
2603 TALLOC_FREE(lck);
2604 fd_close(fsp);
2605 return status;
2609 /* note that we ignore failure for the following. It is
2610 basically a hack for NFS, and NFS will never set one of
2611 these only read them. Nobody but Samba can ever set a deny
2612 mode and we have already checked our more authoritative
2613 locking database for permission to set this deny mode. If
2614 the kernel refuses the operations then the kernel is wrong.
2615 note that GPFS supports it as well - jmcd */
2617 if (fsp->fh->fd != -1 && lp_kernel_share_modes(SNUM(conn))) {
2618 int ret_flock;
2619 ret_flock = SMB_VFS_KERNEL_FLOCK(fsp, share_access, access_mask);
2620 if(ret_flock == -1 ){
2622 TALLOC_FREE(lck);
2623 fd_close(fsp);
2625 return NT_STATUS_SHARING_VIOLATION;
2630 * At this point onwards, we can guarantee that the share entry
2631 * is locked, whether we created the file or not, and that the
2632 * deny mode is compatible with all current opens.
2636 * According to Samba4, SEC_FILE_READ_ATTRIBUTE is always granted,
2637 * but we don't have to store this - just ignore it on access check.
2639 if (conn->sconn->using_smb2) {
2641 * SMB2 doesn't return it (according to Microsoft tests).
2642 * Test Case: TestSuite_ScenarioNo009GrantedAccessTestS0
2643 * File created with access = 0x7 (Read, Write, Delete)
2644 * Query Info on file returns 0x87 (Read, Write, Delete, Read Attributes)
2646 fsp->access_mask = access_mask;
2647 } else {
2648 /* But SMB1 does. */
2649 fsp->access_mask = access_mask | FILE_READ_ATTRIBUTES;
2652 if (file_existed) {
2653 /* stat opens on existing files don't get oplocks. */
2654 if (is_stat_open(open_access_mask)) {
2655 fsp->oplock_type = NO_OPLOCK;
2659 if (new_file_created) {
2660 info = FILE_WAS_CREATED;
2661 } else {
2662 if (flags2 & O_TRUNC) {
2663 info = FILE_WAS_OVERWRITTEN;
2664 } else {
2665 info = FILE_WAS_OPENED;
2669 if (pinfo) {
2670 *pinfo = info;
2674 * Setup the oplock info in both the shared memory and
2675 * file structs.
2678 status = set_file_oplock(fsp, fsp->oplock_type);
2679 if (!NT_STATUS_IS_OK(status)) {
2681 * Could not get the kernel oplock
2683 fsp->oplock_type = NO_OPLOCK;
2686 if (!set_share_mode(lck, fsp, get_current_uid(conn),
2687 req ? req->mid : 0,
2688 fsp->oplock_type)) {
2689 TALLOC_FREE(lck);
2690 fd_close(fsp);
2691 return NT_STATUS_NO_MEMORY;
2694 /* Handle strange delete on close create semantics. */
2695 if (create_options & FILE_DELETE_ON_CLOSE) {
2697 status = can_set_delete_on_close(fsp, new_dos_attributes);
2699 if (!NT_STATUS_IS_OK(status)) {
2700 /* Remember to delete the mode we just added. */
2701 del_share_mode(lck, fsp);
2702 TALLOC_FREE(lck);
2703 fd_close(fsp);
2704 return status;
2706 /* Note that here we set the *inital* delete on close flag,
2707 not the regular one. The magic gets handled in close. */
2708 fsp->initial_delete_on_close = True;
2711 if (info != FILE_WAS_OPENED) {
2712 /* Files should be initially set as archive */
2713 if (lp_map_archive(SNUM(conn)) ||
2714 lp_store_dos_attributes(SNUM(conn))) {
2715 if (!posix_open) {
2716 if (file_set_dosmode(conn, smb_fname,
2717 new_dos_attributes | FILE_ATTRIBUTE_ARCHIVE,
2718 parent_dir, true) == 0) {
2719 unx_mode = smb_fname->st.st_ex_mode;
2725 /* Determine sparse flag. */
2726 if (posix_open) {
2727 /* POSIX opens are sparse by default. */
2728 fsp->is_sparse = true;
2729 } else {
2730 fsp->is_sparse = (file_existed &&
2731 (existing_dos_attributes & FILE_ATTRIBUTE_SPARSE));
2735 * Take care of inherited ACLs on created files - if default ACL not
2736 * selected.
2739 if (!posix_open && new_file_created && !def_acl) {
2741 int saved_errno = errno; /* We might get ENOSYS in the next
2742 * call.. */
2744 if (SMB_VFS_FCHMOD_ACL(fsp, unx_mode) == -1 &&
2745 errno == ENOSYS) {
2746 errno = saved_errno; /* Ignore ENOSYS */
2749 } else if (new_unx_mode) {
2751 int ret = -1;
2753 /* Attributes need changing. File already existed. */
2756 int saved_errno = errno; /* We might get ENOSYS in the
2757 * next call.. */
2758 ret = SMB_VFS_FCHMOD_ACL(fsp, new_unx_mode);
2760 if (ret == -1 && errno == ENOSYS) {
2761 errno = saved_errno; /* Ignore ENOSYS */
2762 } else {
2763 DEBUG(5, ("open_file_ntcreate: reset "
2764 "attributes of file %s to 0%o\n",
2765 smb_fname_str_dbg(smb_fname),
2766 (unsigned int)new_unx_mode));
2767 ret = 0; /* Don't do the fchmod below. */
2771 if ((ret == -1) &&
2772 (SMB_VFS_FCHMOD(fsp, new_unx_mode) == -1))
2773 DEBUG(5, ("open_file_ntcreate: failed to reset "
2774 "attributes of file %s to 0%o\n",
2775 smb_fname_str_dbg(smb_fname),
2776 (unsigned int)new_unx_mode));
2779 TALLOC_FREE(lck);
2781 return NT_STATUS_OK;
2785 /****************************************************************************
2786 Open a file for for write to ensure that we can fchmod it.
2787 ****************************************************************************/
2789 NTSTATUS open_file_fchmod(connection_struct *conn,
2790 struct smb_filename *smb_fname,
2791 files_struct **result)
2793 if (!VALID_STAT(smb_fname->st)) {
2794 return NT_STATUS_INVALID_PARAMETER;
2797 return SMB_VFS_CREATE_FILE(
2798 conn, /* conn */
2799 NULL, /* req */
2800 0, /* root_dir_fid */
2801 smb_fname, /* fname */
2802 FILE_WRITE_DATA, /* access_mask */
2803 (FILE_SHARE_READ | FILE_SHARE_WRITE | /* share_access */
2804 FILE_SHARE_DELETE),
2805 FILE_OPEN, /* create_disposition*/
2806 0, /* create_options */
2807 0, /* file_attributes */
2808 INTERNAL_OPEN_ONLY, /* oplock_request */
2809 0, /* allocation_size */
2810 0, /* private_flags */
2811 NULL, /* sd */
2812 NULL, /* ea_list */
2813 result, /* result */
2814 NULL); /* pinfo */
2817 static NTSTATUS mkdir_internal(connection_struct *conn,
2818 struct smb_filename *smb_dname,
2819 uint32 file_attributes)
2821 mode_t mode;
2822 char *parent_dir = NULL;
2823 NTSTATUS status;
2824 bool posix_open = false;
2825 bool need_re_stat = false;
2826 uint32_t access_mask = SEC_DIR_ADD_SUBDIR;
2828 if (!CAN_WRITE(conn) || (access_mask & ~(conn->share_access))) {
2829 DEBUG(5,("mkdir_internal: failing share access "
2830 "%s\n", lp_servicename(talloc_tos(), SNUM(conn))));
2831 return NT_STATUS_ACCESS_DENIED;
2834 if (!parent_dirname(talloc_tos(), smb_dname->base_name, &parent_dir,
2835 NULL)) {
2836 return NT_STATUS_NO_MEMORY;
2839 if (file_attributes & FILE_FLAG_POSIX_SEMANTICS) {
2840 posix_open = true;
2841 mode = (mode_t)(file_attributes & ~FILE_FLAG_POSIX_SEMANTICS);
2842 } else {
2843 mode = unix_mode(conn, FILE_ATTRIBUTE_DIRECTORY, smb_dname, parent_dir);
2846 status = check_parent_access(conn,
2847 smb_dname,
2848 access_mask);
2849 if(!NT_STATUS_IS_OK(status)) {
2850 DEBUG(5,("mkdir_internal: check_parent_access "
2851 "on directory %s for path %s returned %s\n",
2852 parent_dir,
2853 smb_dname->base_name,
2854 nt_errstr(status) ));
2855 return status;
2858 if (SMB_VFS_MKDIR(conn, smb_dname->base_name, mode) != 0) {
2859 return map_nt_error_from_unix(errno);
2862 /* Ensure we're checking for a symlink here.... */
2863 /* We don't want to get caught by a symlink racer. */
2865 if (SMB_VFS_LSTAT(conn, smb_dname) == -1) {
2866 DEBUG(2, ("Could not stat directory '%s' just created: %s\n",
2867 smb_fname_str_dbg(smb_dname), strerror(errno)));
2868 return map_nt_error_from_unix(errno);
2871 if (!S_ISDIR(smb_dname->st.st_ex_mode)) {
2872 DEBUG(0, ("Directory '%s' just created is not a directory !\n",
2873 smb_fname_str_dbg(smb_dname)));
2874 return NT_STATUS_NOT_A_DIRECTORY;
2877 if (lp_store_dos_attributes(SNUM(conn))) {
2878 if (!posix_open) {
2879 file_set_dosmode(conn, smb_dname,
2880 file_attributes | FILE_ATTRIBUTE_DIRECTORY,
2881 parent_dir, true);
2885 if (lp_inherit_perms(SNUM(conn))) {
2886 inherit_access_posix_acl(conn, parent_dir,
2887 smb_dname->base_name, mode);
2888 need_re_stat = true;
2891 if (!posix_open) {
2893 * Check if high bits should have been set,
2894 * then (if bits are missing): add them.
2895 * Consider bits automagically set by UNIX, i.e. SGID bit from parent
2896 * dir.
2898 if ((mode & ~(S_IRWXU|S_IRWXG|S_IRWXO)) &&
2899 (mode & ~smb_dname->st.st_ex_mode)) {
2900 SMB_VFS_CHMOD(conn, smb_dname->base_name,
2901 (smb_dname->st.st_ex_mode |
2902 (mode & ~smb_dname->st.st_ex_mode)));
2903 need_re_stat = true;
2907 /* Change the owner if required. */
2908 if (lp_inherit_owner(SNUM(conn))) {
2909 change_dir_owner_to_parent(conn, parent_dir,
2910 smb_dname->base_name,
2911 &smb_dname->st);
2912 need_re_stat = true;
2915 if (need_re_stat) {
2916 if (SMB_VFS_LSTAT(conn, smb_dname) == -1) {
2917 DEBUG(2, ("Could not stat directory '%s' just created: %s\n",
2918 smb_fname_str_dbg(smb_dname), strerror(errno)));
2919 return map_nt_error_from_unix(errno);
2923 notify_fname(conn, NOTIFY_ACTION_ADDED, FILE_NOTIFY_CHANGE_DIR_NAME,
2924 smb_dname->base_name);
2926 return NT_STATUS_OK;
2929 /****************************************************************************
2930 Open a directory from an NT SMB call.
2931 ****************************************************************************/
2933 static NTSTATUS open_directory(connection_struct *conn,
2934 struct smb_request *req,
2935 struct smb_filename *smb_dname,
2936 uint32 access_mask,
2937 uint32 share_access,
2938 uint32 create_disposition,
2939 uint32 create_options,
2940 uint32 file_attributes,
2941 int *pinfo,
2942 files_struct **result)
2944 files_struct *fsp = NULL;
2945 bool dir_existed = VALID_STAT(smb_dname->st) ? True : False;
2946 struct share_mode_lock *lck = NULL;
2947 NTSTATUS status;
2948 struct timespec mtimespec;
2949 int info = 0;
2951 if (is_ntfs_stream_smb_fname(smb_dname)) {
2952 DEBUG(2, ("open_directory: %s is a stream name!\n",
2953 smb_fname_str_dbg(smb_dname)));
2954 return NT_STATUS_NOT_A_DIRECTORY;
2957 if (!(file_attributes & FILE_FLAG_POSIX_SEMANTICS)) {
2958 /* Ensure we have a directory attribute. */
2959 file_attributes |= FILE_ATTRIBUTE_DIRECTORY;
2962 DEBUG(5,("open_directory: opening directory %s, access_mask = 0x%x, "
2963 "share_access = 0x%x create_options = 0x%x, "
2964 "create_disposition = 0x%x, file_attributes = 0x%x\n",
2965 smb_fname_str_dbg(smb_dname),
2966 (unsigned int)access_mask,
2967 (unsigned int)share_access,
2968 (unsigned int)create_options,
2969 (unsigned int)create_disposition,
2970 (unsigned int)file_attributes));
2972 status = smbd_calculate_access_mask(conn, smb_dname, false,
2973 access_mask, &access_mask);
2974 if (!NT_STATUS_IS_OK(status)) {
2975 DEBUG(10, ("open_directory: smbd_calculate_access_mask "
2976 "on file %s returned %s\n",
2977 smb_fname_str_dbg(smb_dname),
2978 nt_errstr(status)));
2979 return status;
2982 if ((access_mask & SEC_FLAG_SYSTEM_SECURITY) &&
2983 !security_token_has_privilege(get_current_nttok(conn),
2984 SEC_PRIV_SECURITY)) {
2985 DEBUG(10, ("open_directory: open on %s "
2986 "failed - SEC_FLAG_SYSTEM_SECURITY denied.\n",
2987 smb_fname_str_dbg(smb_dname)));
2988 return NT_STATUS_PRIVILEGE_NOT_HELD;
2991 switch( create_disposition ) {
2992 case FILE_OPEN:
2994 if (!dir_existed) {
2995 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
2998 info = FILE_WAS_OPENED;
2999 break;
3001 case FILE_CREATE:
3003 /* If directory exists error. If directory doesn't
3004 * exist create. */
3006 if (dir_existed) {
3007 status = NT_STATUS_OBJECT_NAME_COLLISION;
3008 DEBUG(2, ("open_directory: unable to create "
3009 "%s. Error was %s\n",
3010 smb_fname_str_dbg(smb_dname),
3011 nt_errstr(status)));
3012 return status;
3015 status = mkdir_internal(conn, smb_dname,
3016 file_attributes);
3018 if (!NT_STATUS_IS_OK(status)) {
3019 DEBUG(2, ("open_directory: unable to create "
3020 "%s. Error was %s\n",
3021 smb_fname_str_dbg(smb_dname),
3022 nt_errstr(status)));
3023 return status;
3026 info = FILE_WAS_CREATED;
3027 break;
3029 case FILE_OPEN_IF:
3031 * If directory exists open. If directory doesn't
3032 * exist create.
3035 if (dir_existed) {
3036 status = NT_STATUS_OK;
3037 info = FILE_WAS_OPENED;
3038 } else {
3039 status = mkdir_internal(conn, smb_dname,
3040 file_attributes);
3042 if (NT_STATUS_IS_OK(status)) {
3043 info = FILE_WAS_CREATED;
3044 } else {
3045 /* Cope with create race. */
3046 if (!NT_STATUS_EQUAL(status,
3047 NT_STATUS_OBJECT_NAME_COLLISION)) {
3048 DEBUG(2, ("open_directory: unable to create "
3049 "%s. Error was %s\n",
3050 smb_fname_str_dbg(smb_dname),
3051 nt_errstr(status)));
3052 return status;
3054 info = FILE_WAS_OPENED;
3058 break;
3060 case FILE_SUPERSEDE:
3061 case FILE_OVERWRITE:
3062 case FILE_OVERWRITE_IF:
3063 default:
3064 DEBUG(5,("open_directory: invalid create_disposition "
3065 "0x%x for directory %s\n",
3066 (unsigned int)create_disposition,
3067 smb_fname_str_dbg(smb_dname)));
3068 return NT_STATUS_INVALID_PARAMETER;
3071 if(!S_ISDIR(smb_dname->st.st_ex_mode)) {
3072 DEBUG(5,("open_directory: %s is not a directory !\n",
3073 smb_fname_str_dbg(smb_dname)));
3074 return NT_STATUS_NOT_A_DIRECTORY;
3077 if (info == FILE_WAS_OPENED) {
3078 status = smbd_check_access_rights(conn,
3079 smb_dname,
3080 false,
3081 access_mask);
3082 if (!NT_STATUS_IS_OK(status)) {
3083 DEBUG(10, ("open_directory: smbd_check_access_rights on "
3084 "file %s failed with %s\n",
3085 smb_fname_str_dbg(smb_dname),
3086 nt_errstr(status)));
3087 return status;
3091 status = file_new(req, conn, &fsp);
3092 if(!NT_STATUS_IS_OK(status)) {
3093 return status;
3097 * Setup the files_struct for it.
3100 fsp->file_id = vfs_file_id_from_sbuf(conn, &smb_dname->st);
3101 fsp->vuid = req ? req->vuid : UID_FIELD_INVALID;
3102 fsp->file_pid = req ? req->smbpid : 0;
3103 fsp->can_lock = False;
3104 fsp->can_read = False;
3105 fsp->can_write = False;
3107 fsp->share_access = share_access;
3108 fsp->fh->private_options = 0;
3110 * According to Samba4, SEC_FILE_READ_ATTRIBUTE is always granted,
3112 fsp->access_mask = access_mask | FILE_READ_ATTRIBUTES;
3113 fsp->print_file = NULL;
3114 fsp->modified = False;
3115 fsp->oplock_type = NO_OPLOCK;
3116 fsp->sent_oplock_break = NO_BREAK_SENT;
3117 fsp->is_directory = True;
3118 fsp->posix_open = (file_attributes & FILE_FLAG_POSIX_SEMANTICS) ? True : False;
3119 status = fsp_set_smb_fname(fsp, smb_dname);
3120 if (!NT_STATUS_IS_OK(status)) {
3121 file_free(req, fsp);
3122 return status;
3125 mtimespec = smb_dname->st.st_ex_mtime;
3127 #ifdef O_DIRECTORY
3128 status = fd_open(conn, fsp, O_RDONLY|O_DIRECTORY, 0);
3129 #else
3130 /* POSIX allows us to open a directory with O_RDONLY. */
3131 status = fd_open(conn, fsp, O_RDONLY, 0);
3132 #endif
3133 if (!NT_STATUS_IS_OK(status)) {
3134 DEBUG(5, ("open_directory: Could not open fd for "
3135 "%s (%s)\n",
3136 smb_fname_str_dbg(smb_dname),
3137 nt_errstr(status)));
3138 file_free(req, fsp);
3139 return status;
3142 status = vfs_stat_fsp(fsp);
3143 if (!NT_STATUS_IS_OK(status)) {
3144 fd_close(fsp);
3145 file_free(req, fsp);
3146 return status;
3149 /* Ensure there was no race condition. */
3150 if (!check_same_stat(&smb_dname->st, &fsp->fsp_name->st)) {
3151 DEBUG(5,("open_directory: stat struct differs for "
3152 "directory %s.\n",
3153 smb_fname_str_dbg(smb_dname)));
3154 fd_close(fsp);
3155 file_free(req, fsp);
3156 return NT_STATUS_ACCESS_DENIED;
3159 lck = get_share_mode_lock(talloc_tos(), fsp->file_id,
3160 conn->connectpath, smb_dname,
3161 &mtimespec);
3163 if (lck == NULL) {
3164 DEBUG(0, ("open_directory: Could not get share mode lock for "
3165 "%s\n", smb_fname_str_dbg(smb_dname)));
3166 fd_close(fsp);
3167 file_free(req, fsp);
3168 return NT_STATUS_SHARING_VIOLATION;
3171 if (has_delete_on_close(lck, fsp->name_hash)) {
3172 TALLOC_FREE(lck);
3173 fd_close(fsp);
3174 file_free(req, fsp);
3175 return NT_STATUS_DELETE_PENDING;
3178 status = open_mode_check(conn, lck,
3179 access_mask, share_access);
3181 if (!NT_STATUS_IS_OK(status)) {
3182 TALLOC_FREE(lck);
3183 fd_close(fsp);
3184 file_free(req, fsp);
3185 return status;
3188 if (!set_share_mode(lck, fsp, get_current_uid(conn),
3189 req ? req->mid : 0, NO_OPLOCK)) {
3190 TALLOC_FREE(lck);
3191 fd_close(fsp);
3192 file_free(req, fsp);
3193 return NT_STATUS_NO_MEMORY;
3196 /* For directories the delete on close bit at open time seems
3197 always to be honored on close... See test 19 in Samba4 BASE-DELETE. */
3198 if (create_options & FILE_DELETE_ON_CLOSE) {
3199 status = can_set_delete_on_close(fsp, 0);
3200 if (!NT_STATUS_IS_OK(status) && !NT_STATUS_EQUAL(status, NT_STATUS_DIRECTORY_NOT_EMPTY)) {
3201 del_share_mode(lck, fsp);
3202 TALLOC_FREE(lck);
3203 fd_close(fsp);
3204 file_free(req, fsp);
3205 return status;
3208 if (NT_STATUS_IS_OK(status)) {
3209 /* Note that here we set the *inital* delete on close flag,
3210 not the regular one. The magic gets handled in close. */
3211 fsp->initial_delete_on_close = True;
3215 TALLOC_FREE(lck);
3217 if (pinfo) {
3218 *pinfo = info;
3221 *result = fsp;
3222 return NT_STATUS_OK;
3225 NTSTATUS create_directory(connection_struct *conn, struct smb_request *req,
3226 struct smb_filename *smb_dname)
3228 NTSTATUS status;
3229 files_struct *fsp;
3231 status = SMB_VFS_CREATE_FILE(
3232 conn, /* conn */
3233 req, /* req */
3234 0, /* root_dir_fid */
3235 smb_dname, /* fname */
3236 FILE_READ_ATTRIBUTES, /* access_mask */
3237 FILE_SHARE_NONE, /* share_access */
3238 FILE_CREATE, /* create_disposition*/
3239 FILE_DIRECTORY_FILE, /* create_options */
3240 FILE_ATTRIBUTE_DIRECTORY, /* file_attributes */
3241 0, /* oplock_request */
3242 0, /* allocation_size */
3243 0, /* private_flags */
3244 NULL, /* sd */
3245 NULL, /* ea_list */
3246 &fsp, /* result */
3247 NULL); /* pinfo */
3249 if (NT_STATUS_IS_OK(status)) {
3250 close_file(req, fsp, NORMAL_CLOSE);
3253 return status;
3256 /****************************************************************************
3257 Receive notification that one of our open files has been renamed by another
3258 smbd process.
3259 ****************************************************************************/
3261 void msg_file_was_renamed(struct messaging_context *msg,
3262 void *private_data,
3263 uint32_t msg_type,
3264 struct server_id server_id,
3265 DATA_BLOB *data)
3267 files_struct *fsp;
3268 char *frm = (char *)data->data;
3269 struct file_id id;
3270 const char *sharepath;
3271 const char *base_name;
3272 const char *stream_name;
3273 struct smb_filename *smb_fname = NULL;
3274 size_t sp_len, bn_len;
3275 NTSTATUS status;
3276 struct smbd_server_connection *sconn =
3277 talloc_get_type_abort(private_data,
3278 struct smbd_server_connection);
3280 if (data->data == NULL
3281 || data->length < MSG_FILE_RENAMED_MIN_SIZE + 2) {
3282 DEBUG(0, ("msg_file_was_renamed: Got invalid msg len %d\n",
3283 (int)data->length));
3284 return;
3287 /* Unpack the message. */
3288 pull_file_id_24(frm, &id);
3289 sharepath = &frm[24];
3290 sp_len = strlen(sharepath);
3291 base_name = sharepath + sp_len + 1;
3292 bn_len = strlen(base_name);
3293 stream_name = sharepath + sp_len + 1 + bn_len + 1;
3295 /* stream_name must always be NULL if there is no stream. */
3296 if (stream_name[0] == '\0') {
3297 stream_name = NULL;
3300 smb_fname = synthetic_smb_fname(talloc_tos(), base_name,
3301 stream_name, NULL);
3302 if (smb_fname == NULL) {
3303 return;
3306 DEBUG(10,("msg_file_was_renamed: Got rename message for sharepath %s, new name %s, "
3307 "file_id %s\n",
3308 sharepath, smb_fname_str_dbg(smb_fname),
3309 file_id_string_tos(&id)));
3311 for(fsp = file_find_di_first(sconn, id); fsp;
3312 fsp = file_find_di_next(fsp)) {
3313 if (memcmp(fsp->conn->connectpath, sharepath, sp_len) == 0) {
3315 DEBUG(10,("msg_file_was_renamed: renaming file %s from %s -> %s\n",
3316 fsp_fnum_dbg(fsp), fsp_str_dbg(fsp),
3317 smb_fname_str_dbg(smb_fname)));
3318 status = fsp_set_smb_fname(fsp, smb_fname);
3319 if (!NT_STATUS_IS_OK(status)) {
3320 goto out;
3322 } else {
3323 /* TODO. JRA. */
3324 /* Now we have the complete path we can work out if this is
3325 actually within this share and adjust newname accordingly. */
3326 DEBUG(10,("msg_file_was_renamed: share mismatch (sharepath %s "
3327 "not sharepath %s) "
3328 "%s from %s -> %s\n",
3329 fsp->conn->connectpath,
3330 sharepath,
3331 fsp_fnum_dbg(fsp),
3332 fsp_str_dbg(fsp),
3333 smb_fname_str_dbg(smb_fname)));
3336 out:
3337 TALLOC_FREE(smb_fname);
3338 return;
3342 * If a main file is opened for delete, all streams need to be checked for
3343 * !FILE_SHARE_DELETE. Do this by opening with DELETE_ACCESS.
3344 * If that works, delete them all by setting the delete on close and close.
3347 NTSTATUS open_streams_for_delete(connection_struct *conn,
3348 const char *fname)
3350 struct stream_struct *stream_info = NULL;
3351 files_struct **streams = NULL;
3352 int i;
3353 unsigned int num_streams = 0;
3354 TALLOC_CTX *frame = talloc_stackframe();
3355 NTSTATUS status;
3357 status = vfs_streaminfo(conn, NULL, fname, talloc_tos(),
3358 &num_streams, &stream_info);
3360 if (NT_STATUS_EQUAL(status, NT_STATUS_NOT_IMPLEMENTED)
3361 || NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
3362 DEBUG(10, ("no streams around\n"));
3363 TALLOC_FREE(frame);
3364 return NT_STATUS_OK;
3367 if (!NT_STATUS_IS_OK(status)) {
3368 DEBUG(10, ("vfs_streaminfo failed: %s\n",
3369 nt_errstr(status)));
3370 goto fail;
3373 DEBUG(10, ("open_streams_for_delete found %d streams\n",
3374 num_streams));
3376 if (num_streams == 0) {
3377 TALLOC_FREE(frame);
3378 return NT_STATUS_OK;
3381 streams = talloc_array(talloc_tos(), files_struct *, num_streams);
3382 if (streams == NULL) {
3383 DEBUG(0, ("talloc failed\n"));
3384 status = NT_STATUS_NO_MEMORY;
3385 goto fail;
3388 for (i=0; i<num_streams; i++) {
3389 struct smb_filename *smb_fname;
3391 if (strequal(stream_info[i].name, "::$DATA")) {
3392 streams[i] = NULL;
3393 continue;
3396 smb_fname = synthetic_smb_fname(
3397 talloc_tos(), fname, stream_info[i].name, NULL);
3398 if (smb_fname == NULL) {
3399 status = NT_STATUS_NO_MEMORY;
3400 goto fail;
3403 if (SMB_VFS_STAT(conn, smb_fname) == -1) {
3404 DEBUG(10, ("Unable to stat stream: %s\n",
3405 smb_fname_str_dbg(smb_fname)));
3408 status = SMB_VFS_CREATE_FILE(
3409 conn, /* conn */
3410 NULL, /* req */
3411 0, /* root_dir_fid */
3412 smb_fname, /* fname */
3413 DELETE_ACCESS, /* access_mask */
3414 (FILE_SHARE_READ | /* share_access */
3415 FILE_SHARE_WRITE | FILE_SHARE_DELETE),
3416 FILE_OPEN, /* create_disposition*/
3417 0, /* create_options */
3418 FILE_ATTRIBUTE_NORMAL, /* file_attributes */
3419 0, /* oplock_request */
3420 0, /* allocation_size */
3421 NTCREATEX_OPTIONS_PRIVATE_STREAM_DELETE, /* private_flags */
3422 NULL, /* sd */
3423 NULL, /* ea_list */
3424 &streams[i], /* result */
3425 NULL); /* pinfo */
3427 if (!NT_STATUS_IS_OK(status)) {
3428 DEBUG(10, ("Could not open stream %s: %s\n",
3429 smb_fname_str_dbg(smb_fname),
3430 nt_errstr(status)));
3432 TALLOC_FREE(smb_fname);
3433 break;
3435 TALLOC_FREE(smb_fname);
3439 * don't touch the variable "status" beyond this point :-)
3442 for (i -= 1 ; i >= 0; i--) {
3443 if (streams[i] == NULL) {
3444 continue;
3447 DEBUG(10, ("Closing stream # %d, %s\n", i,
3448 fsp_str_dbg(streams[i])));
3449 close_file(NULL, streams[i], NORMAL_CLOSE);
3452 fail:
3453 TALLOC_FREE(frame);
3454 return status;
3457 /*********************************************************************
3458 Create a default ACL by inheriting from the parent. If no inheritance
3459 from the parent available, don't set anything. This will leave the actual
3460 permissions the new file or directory already got from the filesystem
3461 as the NT ACL when read.
3462 *********************************************************************/
3464 static NTSTATUS inherit_new_acl(files_struct *fsp)
3466 TALLOC_CTX *frame = talloc_stackframe();
3467 char *parent_name = NULL;
3468 struct security_descriptor *parent_desc = NULL;
3469 NTSTATUS status = NT_STATUS_OK;
3470 struct security_descriptor *psd = NULL;
3471 const struct dom_sid *owner_sid = NULL;
3472 const struct dom_sid *group_sid = NULL;
3473 uint32_t security_info_sent = (SECINFO_OWNER | SECINFO_GROUP | SECINFO_DACL);
3474 struct security_token *token = fsp->conn->session_info->security_token;
3475 bool inherit_owner = lp_inherit_owner(SNUM(fsp->conn));
3476 bool inheritable_components = false;
3477 bool try_builtin_administrators = false;
3478 const struct dom_sid *BA_U_sid = NULL;
3479 const struct dom_sid *BA_G_sid = NULL;
3480 bool try_system = false;
3481 const struct dom_sid *SY_U_sid = NULL;
3482 const struct dom_sid *SY_G_sid = NULL;
3483 size_t size = 0;
3485 if (!parent_dirname(frame, fsp->fsp_name->base_name, &parent_name, NULL)) {
3486 TALLOC_FREE(frame);
3487 return NT_STATUS_NO_MEMORY;
3490 status = SMB_VFS_GET_NT_ACL(fsp->conn,
3491 parent_name,
3492 (SECINFO_OWNER | SECINFO_GROUP | SECINFO_DACL),
3493 frame,
3494 &parent_desc);
3495 if (!NT_STATUS_IS_OK(status)) {
3496 TALLOC_FREE(frame);
3497 return status;
3500 inheritable_components = sd_has_inheritable_components(parent_desc,
3501 fsp->is_directory);
3503 if (!inheritable_components && !inherit_owner) {
3504 TALLOC_FREE(frame);
3505 /* Nothing to inherit and not setting owner. */
3506 return NT_STATUS_OK;
3509 /* Create an inherited descriptor from the parent. */
3511 if (DEBUGLEVEL >= 10) {
3512 DEBUG(10,("inherit_new_acl: parent acl for %s is:\n",
3513 fsp_str_dbg(fsp) ));
3514 NDR_PRINT_DEBUG(security_descriptor, parent_desc);
3517 /* Inherit from parent descriptor if "inherit owner" set. */
3518 if (inherit_owner) {
3519 owner_sid = parent_desc->owner_sid;
3520 group_sid = parent_desc->group_sid;
3523 if (owner_sid == NULL) {
3524 if (security_token_has_builtin_administrators(token)) {
3525 try_builtin_administrators = true;
3526 } else if (security_token_is_system(token)) {
3527 try_builtin_administrators = true;
3528 try_system = true;
3532 if (group_sid == NULL &&
3533 token->num_sids == PRIMARY_GROUP_SID_INDEX)
3535 if (security_token_is_system(token)) {
3536 try_builtin_administrators = true;
3537 try_system = true;
3541 if (try_builtin_administrators) {
3542 struct unixid ids;
3543 bool ok;
3545 ZERO_STRUCT(ids);
3546 ok = sids_to_unixids(&global_sid_Builtin_Administrators, 1, &ids);
3547 if (ok) {
3548 switch (ids.type) {
3549 case ID_TYPE_BOTH:
3550 BA_U_sid = &global_sid_Builtin_Administrators;
3551 BA_G_sid = &global_sid_Builtin_Administrators;
3552 break;
3553 case ID_TYPE_UID:
3554 BA_U_sid = &global_sid_Builtin_Administrators;
3555 break;
3556 case ID_TYPE_GID:
3557 BA_G_sid = &global_sid_Builtin_Administrators;
3558 break;
3559 default:
3560 break;
3565 if (try_system) {
3566 struct unixid ids;
3567 bool ok;
3569 ZERO_STRUCT(ids);
3570 ok = sids_to_unixids(&global_sid_System, 1, &ids);
3571 if (ok) {
3572 switch (ids.type) {
3573 case ID_TYPE_BOTH:
3574 SY_U_sid = &global_sid_System;
3575 SY_G_sid = &global_sid_System;
3576 break;
3577 case ID_TYPE_UID:
3578 SY_U_sid = &global_sid_System;
3579 break;
3580 case ID_TYPE_GID:
3581 SY_G_sid = &global_sid_System;
3582 break;
3583 default:
3584 break;
3589 if (owner_sid == NULL) {
3590 owner_sid = BA_U_sid;
3593 if (owner_sid == NULL) {
3594 owner_sid = SY_U_sid;
3597 if (group_sid == NULL) {
3598 group_sid = SY_G_sid;
3601 if (try_system && group_sid == NULL) {
3602 group_sid = BA_G_sid;
3605 if (owner_sid == NULL) {
3606 owner_sid = &token->sids[PRIMARY_USER_SID_INDEX];
3608 if (group_sid == NULL) {
3609 if (token->num_sids == PRIMARY_GROUP_SID_INDEX) {
3610 group_sid = &token->sids[PRIMARY_USER_SID_INDEX];
3611 } else {
3612 group_sid = &token->sids[PRIMARY_GROUP_SID_INDEX];
3616 status = se_create_child_secdesc(frame,
3617 &psd,
3618 &size,
3619 parent_desc,
3620 owner_sid,
3621 group_sid,
3622 fsp->is_directory);
3623 if (!NT_STATUS_IS_OK(status)) {
3624 TALLOC_FREE(frame);
3625 return status;
3628 /* If inheritable_components == false,
3629 se_create_child_secdesc()
3630 creates a security desriptor with a NULL dacl
3631 entry, but with SEC_DESC_DACL_PRESENT. We need
3632 to remove that flag. */
3634 if (!inheritable_components) {
3635 security_info_sent &= ~SECINFO_DACL;
3636 psd->type &= ~SEC_DESC_DACL_PRESENT;
3639 if (DEBUGLEVEL >= 10) {
3640 DEBUG(10,("inherit_new_acl: child acl for %s is:\n",
3641 fsp_str_dbg(fsp) ));
3642 NDR_PRINT_DEBUG(security_descriptor, psd);
3645 if (inherit_owner) {
3646 /* We need to be root to force this. */
3647 become_root();
3649 status = SMB_VFS_FSET_NT_ACL(fsp,
3650 security_info_sent,
3651 psd);
3652 if (inherit_owner) {
3653 unbecome_root();
3655 TALLOC_FREE(frame);
3656 return status;
3660 * Wrapper around open_file_ntcreate and open_directory
3663 static NTSTATUS create_file_unixpath(connection_struct *conn,
3664 struct smb_request *req,
3665 struct smb_filename *smb_fname,
3666 uint32_t access_mask,
3667 uint32_t share_access,
3668 uint32_t create_disposition,
3669 uint32_t create_options,
3670 uint32_t file_attributes,
3671 uint32_t oplock_request,
3672 uint64_t allocation_size,
3673 uint32_t private_flags,
3674 struct security_descriptor *sd,
3675 struct ea_list *ea_list,
3677 files_struct **result,
3678 int *pinfo)
3680 int info = FILE_WAS_OPENED;
3681 files_struct *base_fsp = NULL;
3682 files_struct *fsp = NULL;
3683 NTSTATUS status;
3685 DEBUG(10,("create_file_unixpath: access_mask = 0x%x "
3686 "file_attributes = 0x%x, share_access = 0x%x, "
3687 "create_disposition = 0x%x create_options = 0x%x "
3688 "oplock_request = 0x%x private_flags = 0x%x "
3689 "ea_list = 0x%p, sd = 0x%p, "
3690 "fname = %s\n",
3691 (unsigned int)access_mask,
3692 (unsigned int)file_attributes,
3693 (unsigned int)share_access,
3694 (unsigned int)create_disposition,
3695 (unsigned int)create_options,
3696 (unsigned int)oplock_request,
3697 (unsigned int)private_flags,
3698 ea_list, sd, smb_fname_str_dbg(smb_fname)));
3700 if (create_options & FILE_OPEN_BY_FILE_ID) {
3701 status = NT_STATUS_NOT_SUPPORTED;
3702 goto fail;
3705 if (create_options & NTCREATEX_OPTIONS_INVALID_PARAM_MASK) {
3706 status = NT_STATUS_INVALID_PARAMETER;
3707 goto fail;
3710 if (req == NULL) {
3711 oplock_request |= INTERNAL_OPEN_ONLY;
3714 if ((conn->fs_capabilities & FILE_NAMED_STREAMS)
3715 && (access_mask & DELETE_ACCESS)
3716 && !is_ntfs_stream_smb_fname(smb_fname)) {
3718 * We can't open a file with DELETE access if any of the
3719 * streams is open without FILE_SHARE_DELETE
3721 status = open_streams_for_delete(conn, smb_fname->base_name);
3723 if (!NT_STATUS_IS_OK(status)) {
3724 goto fail;
3728 if ((access_mask & SEC_FLAG_SYSTEM_SECURITY) &&
3729 !security_token_has_privilege(get_current_nttok(conn),
3730 SEC_PRIV_SECURITY)) {
3731 DEBUG(10, ("create_file_unixpath: open on %s "
3732 "failed - SEC_FLAG_SYSTEM_SECURITY denied.\n",
3733 smb_fname_str_dbg(smb_fname)));
3734 status = NT_STATUS_PRIVILEGE_NOT_HELD;
3735 goto fail;
3738 if ((conn->fs_capabilities & FILE_NAMED_STREAMS)
3739 && is_ntfs_stream_smb_fname(smb_fname)
3740 && (!(private_flags & NTCREATEX_OPTIONS_PRIVATE_STREAM_DELETE))) {
3741 uint32 base_create_disposition;
3742 struct smb_filename *smb_fname_base = NULL;
3744 if (create_options & FILE_DIRECTORY_FILE) {
3745 status = NT_STATUS_NOT_A_DIRECTORY;
3746 goto fail;
3749 switch (create_disposition) {
3750 case FILE_OPEN:
3751 base_create_disposition = FILE_OPEN;
3752 break;
3753 default:
3754 base_create_disposition = FILE_OPEN_IF;
3755 break;
3758 /* Create an smb_filename with stream_name == NULL. */
3759 smb_fname_base = synthetic_smb_fname(talloc_tos(),
3760 smb_fname->base_name,
3761 NULL, NULL);
3762 if (smb_fname_base == NULL) {
3763 status = NT_STATUS_NO_MEMORY;
3764 goto fail;
3767 if (SMB_VFS_STAT(conn, smb_fname_base) == -1) {
3768 DEBUG(10, ("Unable to stat stream: %s\n",
3769 smb_fname_str_dbg(smb_fname_base)));
3772 /* Open the base file. */
3773 status = create_file_unixpath(conn, NULL, smb_fname_base, 0,
3774 FILE_SHARE_READ
3775 | FILE_SHARE_WRITE
3776 | FILE_SHARE_DELETE,
3777 base_create_disposition,
3778 0, 0, 0, 0, 0, NULL, NULL,
3779 &base_fsp, NULL);
3780 TALLOC_FREE(smb_fname_base);
3782 if (!NT_STATUS_IS_OK(status)) {
3783 DEBUG(10, ("create_file_unixpath for base %s failed: "
3784 "%s\n", smb_fname->base_name,
3785 nt_errstr(status)));
3786 goto fail;
3788 /* we don't need to low level fd */
3789 fd_close(base_fsp);
3793 * If it's a request for a directory open, deal with it separately.
3796 if (create_options & FILE_DIRECTORY_FILE) {
3798 if (create_options & FILE_NON_DIRECTORY_FILE) {
3799 status = NT_STATUS_INVALID_PARAMETER;
3800 goto fail;
3803 /* Can't open a temp directory. IFS kit test. */
3804 if (!(file_attributes & FILE_FLAG_POSIX_SEMANTICS) &&
3805 (file_attributes & FILE_ATTRIBUTE_TEMPORARY)) {
3806 status = NT_STATUS_INVALID_PARAMETER;
3807 goto fail;
3811 * We will get a create directory here if the Win32
3812 * app specified a security descriptor in the
3813 * CreateDirectory() call.
3816 oplock_request = 0;
3817 status = open_directory(
3818 conn, req, smb_fname, access_mask, share_access,
3819 create_disposition, create_options, file_attributes,
3820 &info, &fsp);
3821 } else {
3824 * Ordinary file case.
3827 status = file_new(req, conn, &fsp);
3828 if(!NT_STATUS_IS_OK(status)) {
3829 goto fail;
3832 status = fsp_set_smb_fname(fsp, smb_fname);
3833 if (!NT_STATUS_IS_OK(status)) {
3834 goto fail;
3837 if (base_fsp) {
3839 * We're opening the stream element of a
3840 * base_fsp we already opened. Set up the
3841 * base_fsp pointer.
3843 fsp->base_fsp = base_fsp;
3846 if (allocation_size) {
3847 fsp->initial_allocation_size = smb_roundup(fsp->conn,
3848 allocation_size);
3851 status = open_file_ntcreate(conn,
3852 req,
3853 access_mask,
3854 share_access,
3855 create_disposition,
3856 create_options,
3857 file_attributes,
3858 oplock_request,
3859 private_flags,
3860 &info,
3861 fsp);
3863 if(!NT_STATUS_IS_OK(status)) {
3864 file_free(req, fsp);
3865 fsp = NULL;
3868 if (NT_STATUS_EQUAL(status, NT_STATUS_FILE_IS_A_DIRECTORY)) {
3870 /* A stream open never opens a directory */
3872 if (base_fsp) {
3873 status = NT_STATUS_FILE_IS_A_DIRECTORY;
3874 goto fail;
3878 * Fail the open if it was explicitly a non-directory
3879 * file.
3882 if (create_options & FILE_NON_DIRECTORY_FILE) {
3883 status = NT_STATUS_FILE_IS_A_DIRECTORY;
3884 goto fail;
3887 oplock_request = 0;
3888 status = open_directory(
3889 conn, req, smb_fname, access_mask,
3890 share_access, create_disposition,
3891 create_options, file_attributes,
3892 &info, &fsp);
3896 if (!NT_STATUS_IS_OK(status)) {
3897 goto fail;
3900 fsp->base_fsp = base_fsp;
3902 if ((ea_list != NULL) &&
3903 ((info == FILE_WAS_CREATED) || (info == FILE_WAS_OVERWRITTEN))) {
3904 status = set_ea(conn, fsp, fsp->fsp_name, ea_list);
3905 if (!NT_STATUS_IS_OK(status)) {
3906 goto fail;
3910 if (!fsp->is_directory && S_ISDIR(fsp->fsp_name->st.st_ex_mode)) {
3911 status = NT_STATUS_ACCESS_DENIED;
3912 goto fail;
3915 /* Save the requested allocation size. */
3916 if ((info == FILE_WAS_CREATED) || (info == FILE_WAS_OVERWRITTEN)) {
3917 if (allocation_size
3918 && (allocation_size > fsp->fsp_name->st.st_ex_size)) {
3919 fsp->initial_allocation_size = smb_roundup(
3920 fsp->conn, allocation_size);
3921 if (fsp->is_directory) {
3922 /* Can't set allocation size on a directory. */
3923 status = NT_STATUS_ACCESS_DENIED;
3924 goto fail;
3926 if (vfs_allocate_file_space(
3927 fsp, fsp->initial_allocation_size) == -1) {
3928 status = NT_STATUS_DISK_FULL;
3929 goto fail;
3931 } else {
3932 fsp->initial_allocation_size = smb_roundup(
3933 fsp->conn, (uint64_t)fsp->fsp_name->st.st_ex_size);
3935 } else {
3936 fsp->initial_allocation_size = 0;
3939 if ((info == FILE_WAS_CREATED) && lp_nt_acl_support(SNUM(conn)) &&
3940 fsp->base_fsp == NULL) {
3941 if (sd != NULL) {
3943 * According to the MS documentation, the only time the security
3944 * descriptor is applied to the opened file is iff we *created* the
3945 * file; an existing file stays the same.
3947 * Also, it seems (from observation) that you can open the file with
3948 * any access mask but you can still write the sd. We need to override
3949 * the granted access before we call set_sd
3950 * Patch for bug #2242 from Tom Lackemann <cessnatomny@yahoo.com>.
3953 uint32_t sec_info_sent;
3954 uint32_t saved_access_mask = fsp->access_mask;
3956 sec_info_sent = get_sec_info(sd);
3958 fsp->access_mask = FILE_GENERIC_ALL;
3960 if (sec_info_sent & (SECINFO_OWNER|
3961 SECINFO_GROUP|
3962 SECINFO_DACL|
3963 SECINFO_SACL)) {
3964 status = set_sd(fsp, sd, sec_info_sent);
3967 fsp->access_mask = saved_access_mask;
3969 if (!NT_STATUS_IS_OK(status)) {
3970 goto fail;
3972 } else if (lp_inherit_acls(SNUM(conn))) {
3973 /* Inherit from parent. Errors here are not fatal. */
3974 status = inherit_new_acl(fsp);
3975 if (!NT_STATUS_IS_OK(status)) {
3976 DEBUG(10,("inherit_new_acl: failed for %s with %s\n",
3977 fsp_str_dbg(fsp),
3978 nt_errstr(status) ));
3983 DEBUG(10, ("create_file_unixpath: info=%d\n", info));
3985 *result = fsp;
3986 if (pinfo != NULL) {
3987 *pinfo = info;
3990 smb_fname->st = fsp->fsp_name->st;
3992 return NT_STATUS_OK;
3994 fail:
3995 DEBUG(10, ("create_file_unixpath: %s\n", nt_errstr(status)));
3997 if (fsp != NULL) {
3998 if (base_fsp && fsp->base_fsp == base_fsp) {
4000 * The close_file below will close
4001 * fsp->base_fsp.
4003 base_fsp = NULL;
4005 close_file(req, fsp, ERROR_CLOSE);
4006 fsp = NULL;
4008 if (base_fsp != NULL) {
4009 close_file(req, base_fsp, ERROR_CLOSE);
4010 base_fsp = NULL;
4012 return status;
4016 * Calculate the full path name given a relative fid.
4018 NTSTATUS get_relative_fid_filename(connection_struct *conn,
4019 struct smb_request *req,
4020 uint16_t root_dir_fid,
4021 const struct smb_filename *smb_fname,
4022 struct smb_filename **smb_fname_out)
4024 files_struct *dir_fsp;
4025 char *parent_fname = NULL;
4026 char *new_base_name = NULL;
4027 NTSTATUS status;
4029 if (root_dir_fid == 0 || !smb_fname) {
4030 status = NT_STATUS_INTERNAL_ERROR;
4031 goto out;
4034 dir_fsp = file_fsp(req, root_dir_fid);
4036 if (dir_fsp == NULL) {
4037 status = NT_STATUS_INVALID_HANDLE;
4038 goto out;
4041 if (is_ntfs_stream_smb_fname(dir_fsp->fsp_name)) {
4042 status = NT_STATUS_INVALID_HANDLE;
4043 goto out;
4046 if (!dir_fsp->is_directory) {
4049 * Check to see if this is a mac fork of some kind.
4052 if ((conn->fs_capabilities & FILE_NAMED_STREAMS) &&
4053 is_ntfs_stream_smb_fname(smb_fname)) {
4054 status = NT_STATUS_OBJECT_PATH_NOT_FOUND;
4055 goto out;
4059 we need to handle the case when we get a
4060 relative open relative to a file and the
4061 pathname is blank - this is a reopen!
4062 (hint from demyn plantenberg)
4065 status = NT_STATUS_INVALID_HANDLE;
4066 goto out;
4069 if (ISDOT(dir_fsp->fsp_name->base_name)) {
4071 * We're at the toplevel dir, the final file name
4072 * must not contain ./, as this is filtered out
4073 * normally by srvstr_get_path and unix_convert
4074 * explicitly rejects paths containing ./.
4076 parent_fname = talloc_strdup(talloc_tos(), "");
4077 if (parent_fname == NULL) {
4078 status = NT_STATUS_NO_MEMORY;
4079 goto out;
4081 } else {
4082 size_t dir_name_len = strlen(dir_fsp->fsp_name->base_name);
4085 * Copy in the base directory name.
4088 parent_fname = talloc_array(talloc_tos(), char,
4089 dir_name_len+2);
4090 if (parent_fname == NULL) {
4091 status = NT_STATUS_NO_MEMORY;
4092 goto out;
4094 memcpy(parent_fname, dir_fsp->fsp_name->base_name,
4095 dir_name_len+1);
4098 * Ensure it ends in a '/'.
4099 * We used TALLOC_SIZE +2 to add space for the '/'.
4102 if(dir_name_len
4103 && (parent_fname[dir_name_len-1] != '\\')
4104 && (parent_fname[dir_name_len-1] != '/')) {
4105 parent_fname[dir_name_len] = '/';
4106 parent_fname[dir_name_len+1] = '\0';
4110 new_base_name = talloc_asprintf(talloc_tos(), "%s%s", parent_fname,
4111 smb_fname->base_name);
4112 if (new_base_name == NULL) {
4113 status = NT_STATUS_NO_MEMORY;
4114 goto out;
4117 status = filename_convert(req,
4118 conn,
4119 req->flags2 & FLAGS2_DFS_PATHNAMES,
4120 new_base_name,
4122 NULL,
4123 smb_fname_out);
4124 if (!NT_STATUS_IS_OK(status)) {
4125 goto out;
4128 out:
4129 TALLOC_FREE(parent_fname);
4130 TALLOC_FREE(new_base_name);
4131 return status;
4134 NTSTATUS create_file_default(connection_struct *conn,
4135 struct smb_request *req,
4136 uint16_t root_dir_fid,
4137 struct smb_filename *smb_fname,
4138 uint32_t access_mask,
4139 uint32_t share_access,
4140 uint32_t create_disposition,
4141 uint32_t create_options,
4142 uint32_t file_attributes,
4143 uint32_t oplock_request,
4144 uint64_t allocation_size,
4145 uint32_t private_flags,
4146 struct security_descriptor *sd,
4147 struct ea_list *ea_list,
4148 files_struct **result,
4149 int *pinfo)
4151 int info = FILE_WAS_OPENED;
4152 files_struct *fsp = NULL;
4153 NTSTATUS status;
4154 bool stream_name = false;
4156 DEBUG(10,("create_file: access_mask = 0x%x "
4157 "file_attributes = 0x%x, share_access = 0x%x, "
4158 "create_disposition = 0x%x create_options = 0x%x "
4159 "oplock_request = 0x%x "
4160 "private_flags = 0x%x "
4161 "root_dir_fid = 0x%x, ea_list = 0x%p, sd = 0x%p, "
4162 "fname = %s\n",
4163 (unsigned int)access_mask,
4164 (unsigned int)file_attributes,
4165 (unsigned int)share_access,
4166 (unsigned int)create_disposition,
4167 (unsigned int)create_options,
4168 (unsigned int)oplock_request,
4169 (unsigned int)private_flags,
4170 (unsigned int)root_dir_fid,
4171 ea_list, sd, smb_fname_str_dbg(smb_fname)));
4174 * Calculate the filename from the root_dir_if if necessary.
4177 if (root_dir_fid != 0) {
4178 struct smb_filename *smb_fname_out = NULL;
4179 status = get_relative_fid_filename(conn, req, root_dir_fid,
4180 smb_fname, &smb_fname_out);
4181 if (!NT_STATUS_IS_OK(status)) {
4182 goto fail;
4184 smb_fname = smb_fname_out;
4188 * Check to see if this is a mac fork of some kind.
4191 stream_name = is_ntfs_stream_smb_fname(smb_fname);
4192 if (stream_name) {
4193 enum FAKE_FILE_TYPE fake_file_type;
4195 fake_file_type = is_fake_file(smb_fname);
4197 if (fake_file_type != FAKE_FILE_TYPE_NONE) {
4200 * Here we go! support for changing the disk quotas
4201 * --metze
4203 * We need to fake up to open this MAGIC QUOTA file
4204 * and return a valid FID.
4206 * w2k close this file directly after openening xp
4207 * also tries a QUERY_FILE_INFO on the file and then
4208 * close it
4210 status = open_fake_file(req, conn, req->vuid,
4211 fake_file_type, smb_fname,
4212 access_mask, &fsp);
4213 if (!NT_STATUS_IS_OK(status)) {
4214 goto fail;
4217 ZERO_STRUCT(smb_fname->st);
4218 goto done;
4221 if (!(conn->fs_capabilities & FILE_NAMED_STREAMS)) {
4222 status = NT_STATUS_OBJECT_NAME_NOT_FOUND;
4223 goto fail;
4227 if (is_ntfs_default_stream_smb_fname(smb_fname)) {
4228 int ret;
4229 smb_fname->stream_name = NULL;
4230 /* We have to handle this error here. */
4231 if (create_options & FILE_DIRECTORY_FILE) {
4232 status = NT_STATUS_NOT_A_DIRECTORY;
4233 goto fail;
4235 if (lp_posix_pathnames()) {
4236 ret = SMB_VFS_LSTAT(conn, smb_fname);
4237 } else {
4238 ret = SMB_VFS_STAT(conn, smb_fname);
4241 if (ret == 0 && VALID_STAT_OF_DIR(smb_fname->st)) {
4242 status = NT_STATUS_FILE_IS_A_DIRECTORY;
4243 goto fail;
4247 status = create_file_unixpath(
4248 conn, req, smb_fname, access_mask, share_access,
4249 create_disposition, create_options, file_attributes,
4250 oplock_request, allocation_size, private_flags,
4251 sd, ea_list,
4252 &fsp, &info);
4254 if (!NT_STATUS_IS_OK(status)) {
4255 goto fail;
4258 done:
4259 DEBUG(10, ("create_file: info=%d\n", info));
4261 *result = fsp;
4262 if (pinfo != NULL) {
4263 *pinfo = info;
4265 return NT_STATUS_OK;
4267 fail:
4268 DEBUG(10, ("create_file: %s\n", nt_errstr(status)));
4270 if (fsp != NULL) {
4271 close_file(req, fsp, ERROR_CLOSE);
4272 fsp = NULL;
4274 return status;