s3:smbd/open: use Builtin_Administrators as owner of files (if possible)
[Samba/gebeck_regimport.git] / source3 / smbd / open.c
blob955660c14834cadf195df4984380067b974981d2
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"
37 extern const struct generic_mapping file_generic_mapping;
39 struct deferred_open_record {
40 bool delayed_for_oplocks;
41 bool async_open;
42 struct file_id id;
45 /****************************************************************************
46 If the requester wanted DELETE_ACCESS and was rejected because
47 the file ACL didn't include DELETE_ACCESS, see if the parent ACL
48 overrides this.
49 ****************************************************************************/
51 static bool parent_override_delete(connection_struct *conn,
52 const struct smb_filename *smb_fname,
53 uint32_t access_mask,
54 uint32_t rejected_mask)
56 if ((access_mask & DELETE_ACCESS) &&
57 (rejected_mask & DELETE_ACCESS) &&
58 can_delete_file_in_directory(conn, smb_fname)) {
59 return true;
61 return false;
64 /****************************************************************************
65 Check if we have open rights.
66 ****************************************************************************/
68 NTSTATUS smbd_check_access_rights(struct connection_struct *conn,
69 const struct smb_filename *smb_fname,
70 bool use_privs,
71 uint32_t access_mask)
73 /* Check if we have rights to open. */
74 NTSTATUS status;
75 struct security_descriptor *sd = NULL;
76 uint32_t rejected_share_access;
77 uint32_t rejected_mask = access_mask;
79 rejected_share_access = access_mask & ~(conn->share_access);
81 if (rejected_share_access) {
82 DEBUG(10, ("smbd_check_access_rights: rejected share access 0x%x "
83 "on %s (0x%x)\n",
84 (unsigned int)access_mask,
85 smb_fname_str_dbg(smb_fname),
86 (unsigned int)rejected_share_access ));
87 return NT_STATUS_ACCESS_DENIED;
90 if (!use_privs && get_current_uid(conn) == (uid_t)0) {
91 /* I'm sorry sir, I didn't know you were root... */
92 DEBUG(10,("smbd_check_access_rights: root override "
93 "on %s. Granting 0x%x\n",
94 smb_fname_str_dbg(smb_fname),
95 (unsigned int)access_mask ));
96 return NT_STATUS_OK;
99 if ((access_mask & DELETE_ACCESS) && !lp_acl_check_permissions(SNUM(conn))) {
100 DEBUG(10,("smbd_check_access_rights: not checking ACL "
101 "on DELETE_ACCESS on file %s. Granting 0x%x\n",
102 smb_fname_str_dbg(smb_fname),
103 (unsigned int)access_mask ));
104 return NT_STATUS_OK;
107 if (access_mask == DELETE_ACCESS &&
108 VALID_STAT(smb_fname->st) &&
109 S_ISLNK(smb_fname->st.st_ex_mode)) {
110 /* We can always delete a symlink. */
111 DEBUG(10,("smbd_check_access_rights: not checking ACL "
112 "on DELETE_ACCESS on symlink %s.\n",
113 smb_fname_str_dbg(smb_fname) ));
114 return NT_STATUS_OK;
117 status = SMB_VFS_GET_NT_ACL(conn, smb_fname->base_name,
118 (SECINFO_OWNER |
119 SECINFO_GROUP |
120 SECINFO_DACL), talloc_tos(), &sd);
122 if (!NT_STATUS_IS_OK(status)) {
123 DEBUG(10, ("smbd_check_access_rights: Could not get acl "
124 "on %s: %s\n",
125 smb_fname_str_dbg(smb_fname),
126 nt_errstr(status)));
128 if (NT_STATUS_EQUAL(status, NT_STATUS_ACCESS_DENIED)) {
129 goto access_denied;
132 return status;
136 * If we can access the path to this file, by
137 * default we have FILE_READ_ATTRIBUTES from the
138 * containing directory. See the section:
139 * "Algorithm to Check Access to an Existing File"
140 * in MS-FSA.pdf.
142 * se_file_access_check() also takes care of
143 * owner WRITE_DAC and READ_CONTROL.
145 status = se_file_access_check(sd,
146 get_current_nttok(conn),
147 use_privs,
148 (access_mask & ~FILE_READ_ATTRIBUTES),
149 &rejected_mask);
151 DEBUG(10,("smbd_check_access_rights: file %s requesting "
152 "0x%x returning 0x%x (%s)\n",
153 smb_fname_str_dbg(smb_fname),
154 (unsigned int)access_mask,
155 (unsigned int)rejected_mask,
156 nt_errstr(status) ));
158 if (!NT_STATUS_IS_OK(status)) {
159 if (DEBUGLEVEL >= 10) {
160 DEBUG(10,("smbd_check_access_rights: acl for %s is:\n",
161 smb_fname_str_dbg(smb_fname) ));
162 NDR_PRINT_DEBUG(security_descriptor, sd);
166 TALLOC_FREE(sd);
168 if (NT_STATUS_IS_OK(status) ||
169 !NT_STATUS_EQUAL(status, NT_STATUS_ACCESS_DENIED)) {
170 return status;
173 /* Here we know status == NT_STATUS_ACCESS_DENIED. */
175 access_denied:
177 if ((access_mask & FILE_WRITE_ATTRIBUTES) &&
178 (rejected_mask & FILE_WRITE_ATTRIBUTES) &&
179 !lp_store_dos_attributes(SNUM(conn)) &&
180 (lp_map_readonly(SNUM(conn)) ||
181 lp_map_archive(SNUM(conn)) ||
182 lp_map_hidden(SNUM(conn)) ||
183 lp_map_system(SNUM(conn)))) {
184 rejected_mask &= ~FILE_WRITE_ATTRIBUTES;
186 DEBUG(10,("smbd_check_access_rights: "
187 "overrode "
188 "FILE_WRITE_ATTRIBUTES "
189 "on file %s\n",
190 smb_fname_str_dbg(smb_fname)));
193 if (parent_override_delete(conn,
194 smb_fname,
195 access_mask,
196 rejected_mask)) {
197 /* Were we trying to do an open
198 * for delete and didn't get DELETE
199 * access (only) ? Check if the
200 * directory allows DELETE_CHILD.
201 * See here:
202 * http://blogs.msdn.com/oldnewthing/archive/2004/06/04/148426.aspx
203 * for details. */
205 rejected_mask &= ~DELETE_ACCESS;
207 DEBUG(10,("smbd_check_access_rights: "
208 "overrode "
209 "DELETE_ACCESS on "
210 "file %s\n",
211 smb_fname_str_dbg(smb_fname)));
214 if (rejected_mask != 0) {
215 return NT_STATUS_ACCESS_DENIED;
217 return NT_STATUS_OK;
220 static NTSTATUS check_parent_access(struct connection_struct *conn,
221 struct smb_filename *smb_fname,
222 uint32_t access_mask)
224 NTSTATUS status;
225 char *parent_dir = NULL;
226 struct security_descriptor *parent_sd = NULL;
227 uint32_t access_granted = 0;
229 if (!parent_dirname(talloc_tos(),
230 smb_fname->base_name,
231 &parent_dir,
232 NULL)) {
233 return NT_STATUS_NO_MEMORY;
236 if (get_current_uid(conn) == (uid_t)0) {
237 /* I'm sorry sir, I didn't know you were root... */
238 DEBUG(10,("check_parent_access: root override "
239 "on %s. Granting 0x%x\n",
240 smb_fname_str_dbg(smb_fname),
241 (unsigned int)access_mask ));
242 return NT_STATUS_OK;
245 status = SMB_VFS_GET_NT_ACL(conn,
246 parent_dir,
247 SECINFO_DACL,
248 talloc_tos(),
249 &parent_sd);
251 if (!NT_STATUS_IS_OK(status)) {
252 DEBUG(5,("check_parent_access: SMB_VFS_GET_NT_ACL failed for "
253 "%s with error %s\n",
254 parent_dir,
255 nt_errstr(status)));
256 return status;
260 * If we can access the path to this file, by
261 * default we have FILE_READ_ATTRIBUTES from the
262 * containing directory. See the section:
263 * "Algorithm to Check Access to an Existing File"
264 * in MS-FSA.pdf.
266 * se_file_access_check() also takes care of
267 * owner WRITE_DAC and READ_CONTROL.
269 status = se_file_access_check(parent_sd,
270 get_current_nttok(conn),
271 false,
272 (access_mask & ~FILE_READ_ATTRIBUTES),
273 &access_granted);
274 if(!NT_STATUS_IS_OK(status)) {
275 DEBUG(5,("check_parent_access: access check "
276 "on directory %s for "
277 "path %s for mask 0x%x returned (0x%x) %s\n",
278 parent_dir,
279 smb_fname->base_name,
280 access_mask,
281 access_granted,
282 nt_errstr(status) ));
283 return status;
286 return NT_STATUS_OK;
289 /****************************************************************************
290 fd support routines - attempt to do a dos_open.
291 ****************************************************************************/
293 NTSTATUS fd_open(struct connection_struct *conn,
294 files_struct *fsp,
295 int flags,
296 mode_t mode)
298 struct smb_filename *smb_fname = fsp->fsp_name;
299 NTSTATUS status = NT_STATUS_OK;
301 #ifdef O_NOFOLLOW
303 * Never follow symlinks on a POSIX client. The
304 * client should be doing this.
307 if (fsp->posix_open || !lp_symlinks(SNUM(conn))) {
308 flags |= O_NOFOLLOW;
310 #endif
312 fsp->fh->fd = SMB_VFS_OPEN(conn, smb_fname, fsp, flags, mode);
313 if (fsp->fh->fd == -1) {
314 int posix_errno = errno;
315 #ifdef O_NOFOLLOW
316 #if defined(ENOTSUP) && defined(OSF1)
317 /* handle special Tru64 errno */
318 if (errno == ENOTSUP) {
319 posix_errno = ELOOP;
321 #endif /* ENOTSUP */
322 #ifdef EFTYPE
323 /* fix broken NetBSD errno */
324 if (errno == EFTYPE) {
325 posix_errno = ELOOP;
327 #endif /* EFTYPE */
328 /* fix broken FreeBSD errno */
329 if (errno == EMLINK) {
330 posix_errno = ELOOP;
332 #endif /* O_NOFOLLOW */
333 status = map_nt_error_from_unix(posix_errno);
334 if (errno == EMFILE) {
335 static time_t last_warned = 0L;
337 if (time((time_t *) NULL) > last_warned) {
338 DEBUG(0,("Too many open files, unable "
339 "to open more! smbd's max "
340 "open files = %d\n",
341 lp_max_open_files()));
342 last_warned = time((time_t *) NULL);
348 DEBUG(10,("fd_open: name %s, flags = 0%o mode = 0%o, fd = %d. %s\n",
349 smb_fname_str_dbg(smb_fname), flags, (int)mode, fsp->fh->fd,
350 (fsp->fh->fd == -1) ? strerror(errno) : "" ));
352 return status;
355 /****************************************************************************
356 Close the file associated with a fsp.
357 ****************************************************************************/
359 NTSTATUS fd_close(files_struct *fsp)
361 int ret;
363 if (fsp->dptr) {
364 dptr_CloseDir(fsp);
366 if (fsp->fh->fd == -1) {
367 return NT_STATUS_OK; /* What we used to call a stat open. */
369 if (fsp->fh->ref_count > 1) {
370 return NT_STATUS_OK; /* Shared handle. Only close last reference. */
373 ret = SMB_VFS_CLOSE(fsp);
374 fsp->fh->fd = -1;
375 if (ret == -1) {
376 return map_nt_error_from_unix(errno);
378 return NT_STATUS_OK;
381 /****************************************************************************
382 Change the ownership of a file to that of the parent directory.
383 Do this by fd if possible.
384 ****************************************************************************/
386 void change_file_owner_to_parent(connection_struct *conn,
387 const char *inherit_from_dir,
388 files_struct *fsp)
390 struct smb_filename *smb_fname_parent = NULL;
391 NTSTATUS status;
392 int ret;
394 status = create_synthetic_smb_fname(talloc_tos(), inherit_from_dir,
395 NULL, NULL, &smb_fname_parent);
396 if (!NT_STATUS_IS_OK(status)) {
397 return;
400 ret = SMB_VFS_STAT(conn, smb_fname_parent);
401 if (ret == -1) {
402 DEBUG(0,("change_file_owner_to_parent: failed to stat parent "
403 "directory %s. Error was %s\n",
404 smb_fname_str_dbg(smb_fname_parent),
405 strerror(errno)));
406 TALLOC_FREE(smb_fname_parent);
407 return;
410 if (smb_fname_parent->st.st_ex_uid == fsp->fsp_name->st.st_ex_uid) {
411 /* Already this uid - no need to change. */
412 DEBUG(10,("change_file_owner_to_parent: file %s "
413 "is already owned by uid %d\n",
414 fsp_str_dbg(fsp),
415 (int)fsp->fsp_name->st.st_ex_uid ));
416 TALLOC_FREE(smb_fname_parent);
417 return;
420 become_root();
421 ret = SMB_VFS_FCHOWN(fsp, smb_fname_parent->st.st_ex_uid, (gid_t)-1);
422 unbecome_root();
423 if (ret == -1) {
424 DEBUG(0,("change_file_owner_to_parent: failed to fchown "
425 "file %s to parent directory uid %u. Error "
426 "was %s\n", fsp_str_dbg(fsp),
427 (unsigned int)smb_fname_parent->st.st_ex_uid,
428 strerror(errno) ));
429 } else {
430 DEBUG(10,("change_file_owner_to_parent: changed new file %s to "
431 "parent directory uid %u.\n", fsp_str_dbg(fsp),
432 (unsigned int)smb_fname_parent->st.st_ex_uid));
433 /* Ensure the uid entry is updated. */
434 fsp->fsp_name->st.st_ex_uid = smb_fname_parent->st.st_ex_uid;
437 TALLOC_FREE(smb_fname_parent);
440 NTSTATUS change_dir_owner_to_parent(connection_struct *conn,
441 const char *inherit_from_dir,
442 const char *fname,
443 SMB_STRUCT_STAT *psbuf)
445 struct smb_filename *smb_fname_parent = NULL;
446 struct smb_filename *smb_fname_cwd = NULL;
447 char *saved_dir = NULL;
448 TALLOC_CTX *ctx = talloc_tos();
449 NTSTATUS status = NT_STATUS_OK;
450 int ret;
452 status = create_synthetic_smb_fname(ctx, inherit_from_dir, NULL, NULL,
453 &smb_fname_parent);
454 if (!NT_STATUS_IS_OK(status)) {
455 return status;
458 ret = SMB_VFS_STAT(conn, smb_fname_parent);
459 if (ret == -1) {
460 status = map_nt_error_from_unix(errno);
461 DEBUG(0,("change_dir_owner_to_parent: failed to stat parent "
462 "directory %s. Error was %s\n",
463 smb_fname_str_dbg(smb_fname_parent),
464 strerror(errno)));
465 goto out;
468 /* We've already done an lstat into psbuf, and we know it's a
469 directory. If we can cd into the directory and the dev/ino
470 are the same then we can safely chown without races as
471 we're locking the directory in place by being in it. This
472 should work on any UNIX (thanks tridge :-). JRA.
475 saved_dir = vfs_GetWd(ctx,conn);
476 if (!saved_dir) {
477 status = map_nt_error_from_unix(errno);
478 DEBUG(0,("change_dir_owner_to_parent: failed to get "
479 "current working directory. Error was %s\n",
480 strerror(errno)));
481 goto out;
484 /* Chdir into the new path. */
485 if (vfs_ChDir(conn, fname) == -1) {
486 status = map_nt_error_from_unix(errno);
487 DEBUG(0,("change_dir_owner_to_parent: failed to change "
488 "current working directory to %s. Error "
489 "was %s\n", fname, strerror(errno) ));
490 goto chdir;
493 status = create_synthetic_smb_fname(ctx, ".", NULL, NULL,
494 &smb_fname_cwd);
495 if (!NT_STATUS_IS_OK(status)) {
496 return status;
499 ret = SMB_VFS_STAT(conn, smb_fname_cwd);
500 if (ret == -1) {
501 status = map_nt_error_from_unix(errno);
502 DEBUG(0,("change_dir_owner_to_parent: failed to stat "
503 "directory '.' (%s) Error was %s\n",
504 fname, strerror(errno)));
505 goto chdir;
508 /* Ensure we're pointing at the same place. */
509 if (smb_fname_cwd->st.st_ex_dev != psbuf->st_ex_dev ||
510 smb_fname_cwd->st.st_ex_ino != psbuf->st_ex_ino) {
511 DEBUG(0,("change_dir_owner_to_parent: "
512 "device/inode on directory %s changed. "
513 "Refusing to chown !\n", fname ));
514 status = NT_STATUS_ACCESS_DENIED;
515 goto chdir;
518 if (smb_fname_parent->st.st_ex_uid == smb_fname_cwd->st.st_ex_uid) {
519 /* Already this uid - no need to change. */
520 DEBUG(10,("change_dir_owner_to_parent: directory %s "
521 "is already owned by uid %d\n",
522 fname,
523 (int)smb_fname_cwd->st.st_ex_uid ));
524 status = NT_STATUS_OK;
525 goto chdir;
528 become_root();
529 ret = SMB_VFS_LCHOWN(conn, ".", smb_fname_parent->st.st_ex_uid,
530 (gid_t)-1);
531 unbecome_root();
532 if (ret == -1) {
533 status = map_nt_error_from_unix(errno);
534 DEBUG(10,("change_dir_owner_to_parent: failed to chown "
535 "directory %s to parent directory uid %u. "
536 "Error was %s\n", fname,
537 (unsigned int)smb_fname_parent->st.st_ex_uid,
538 strerror(errno) ));
539 } else {
540 DEBUG(10,("change_dir_owner_to_parent: changed ownership of new "
541 "directory %s to parent directory uid %u.\n",
542 fname, (unsigned int)smb_fname_parent->st.st_ex_uid ));
543 /* Ensure the uid entry is updated. */
544 psbuf->st_ex_uid = smb_fname_parent->st.st_ex_uid;
547 chdir:
548 vfs_ChDir(conn,saved_dir);
549 out:
550 TALLOC_FREE(smb_fname_parent);
551 TALLOC_FREE(smb_fname_cwd);
552 return status;
555 /****************************************************************************
556 Open a file - returning a guaranteed ATOMIC indication of if the
557 file was created or not.
558 ****************************************************************************/
560 static NTSTATUS fd_open_atomic(struct connection_struct *conn,
561 files_struct *fsp,
562 int flags,
563 mode_t mode,
564 bool *file_created)
566 NTSTATUS status = NT_STATUS_UNSUCCESSFUL;
567 bool file_existed = VALID_STAT(fsp->fsp_name->st);
569 *file_created = false;
571 if (!(flags & O_CREAT)) {
573 * We're not creating the file, just pass through.
575 return fd_open(conn, fsp, flags, mode);
578 if (flags & O_EXCL) {
580 * Fail if already exists, just pass through.
582 status = fd_open(conn, fsp, flags, mode);
585 * Here we've opened with O_CREAT|O_EXCL. If that went
586 * NT_STATUS_OK, we *know* we created this file.
588 *file_created = NT_STATUS_IS_OK(status);
590 return status;
594 * Now it gets tricky. We have O_CREAT, but not O_EXCL.
595 * To know absolutely if we created the file or not,
596 * we can never call O_CREAT without O_EXCL. So if
597 * we think the file existed, try without O_CREAT|O_EXCL.
598 * If we think the file didn't exist, try with
599 * O_CREAT|O_EXCL. Keep bouncing between these two
600 * requests until either the file is created, or
601 * opened. Either way, we keep going until we get
602 * a returnable result (error, or open/create).
605 while(1) {
606 int curr_flags = flags;
608 if (file_existed) {
609 /* Just try open, do not create. */
610 curr_flags &= ~(O_CREAT);
611 status = fd_open(conn, fsp, curr_flags, mode);
612 if (NT_STATUS_EQUAL(status,
613 NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
615 * Someone deleted it in the meantime.
616 * Retry with O_EXCL.
618 file_existed = false;
619 DEBUG(10,("fd_open_atomic: file %s existed. "
620 "Retry.\n",
621 smb_fname_str_dbg(fsp->fsp_name)));
622 continue;
624 } else {
625 /* Try create exclusively, fail if it exists. */
626 curr_flags |= O_EXCL;
627 status = fd_open(conn, fsp, curr_flags, mode);
628 if (NT_STATUS_EQUAL(status,
629 NT_STATUS_OBJECT_NAME_COLLISION)) {
631 * Someone created it in the meantime.
632 * Retry without O_CREAT.
634 file_existed = true;
635 DEBUG(10,("fd_open_atomic: file %s "
636 "did not exist. Retry.\n",
637 smb_fname_str_dbg(fsp->fsp_name)));
638 continue;
640 if (NT_STATUS_IS_OK(status)) {
642 * Here we've opened with O_CREAT|O_EXCL
643 * and got success. We *know* we created
644 * this file.
646 *file_created = true;
649 /* Create is done, or failed. */
650 break;
652 return status;
655 /****************************************************************************
656 Open a file.
657 ****************************************************************************/
659 static NTSTATUS open_file(files_struct *fsp,
660 connection_struct *conn,
661 struct smb_request *req,
662 const char *parent_dir,
663 int flags,
664 mode_t unx_mode,
665 uint32 access_mask, /* client requested access mask. */
666 uint32 open_access_mask, /* what we're actually using in the open. */
667 bool *p_file_created)
669 struct smb_filename *smb_fname = fsp->fsp_name;
670 NTSTATUS status = NT_STATUS_OK;
671 int accmode = (flags & O_ACCMODE);
672 int local_flags = flags;
673 bool file_existed = VALID_STAT(fsp->fsp_name->st);
675 fsp->fh->fd = -1;
676 errno = EPERM;
678 /* Check permissions */
681 * This code was changed after seeing a client open request
682 * containing the open mode of (DENY_WRITE/read-only) with
683 * the 'create if not exist' bit set. The previous code
684 * would fail to open the file read only on a read-only share
685 * as it was checking the flags parameter directly against O_RDONLY,
686 * this was failing as the flags parameter was set to O_RDONLY|O_CREAT.
687 * JRA.
690 if (!CAN_WRITE(conn)) {
691 /* It's a read-only share - fail if we wanted to write. */
692 if(accmode != O_RDONLY || (flags & O_TRUNC) || (flags & O_APPEND)) {
693 DEBUG(3,("Permission denied opening %s\n",
694 smb_fname_str_dbg(smb_fname)));
695 return NT_STATUS_ACCESS_DENIED;
697 if (flags & O_CREAT) {
698 /* We don't want to write - but we must make sure that
699 O_CREAT doesn't create the file if we have write
700 access into the directory.
702 flags &= ~(O_CREAT|O_EXCL);
703 local_flags &= ~(O_CREAT|O_EXCL);
708 * This little piece of insanity is inspired by the
709 * fact that an NT client can open a file for O_RDONLY,
710 * but set the create disposition to FILE_EXISTS_TRUNCATE.
711 * If the client *can* write to the file, then it expects to
712 * truncate the file, even though it is opening for readonly.
713 * Quicken uses this stupid trick in backup file creation...
714 * Thanks *greatly* to "David W. Chapman Jr." <dwcjr@inethouston.net>
715 * for helping track this one down. It didn't bite us in 2.0.x
716 * as we always opened files read-write in that release. JRA.
719 if ((accmode == O_RDONLY) && ((flags & O_TRUNC) == O_TRUNC)) {
720 DEBUG(10,("open_file: truncate requested on read-only open "
721 "for file %s\n", smb_fname_str_dbg(smb_fname)));
722 local_flags = (flags & ~O_ACCMODE)|O_RDWR;
725 if ((open_access_mask & (FILE_READ_DATA|FILE_WRITE_DATA|FILE_APPEND_DATA|FILE_EXECUTE)) ||
726 (!file_existed && (local_flags & O_CREAT)) ||
727 ((local_flags & O_TRUNC) == O_TRUNC) ) {
728 const char *wild;
729 int ret;
731 #if defined(O_NONBLOCK) && defined(S_ISFIFO)
733 * We would block on opening a FIFO with no one else on the
734 * other end. Do what we used to do and add O_NONBLOCK to the
735 * open flags. JRA.
738 if (file_existed && S_ISFIFO(smb_fname->st.st_ex_mode)) {
739 local_flags &= ~O_TRUNC; /* Can't truncate a FIFO. */
740 local_flags |= O_NONBLOCK;
742 #endif
744 /* Don't create files with Microsoft wildcard characters. */
745 if (fsp->base_fsp) {
747 * wildcard characters are allowed in stream names
748 * only test the basefilename
750 wild = fsp->base_fsp->fsp_name->base_name;
751 } else {
752 wild = smb_fname->base_name;
754 if ((local_flags & O_CREAT) && !file_existed &&
755 ms_has_wild(wild)) {
756 return NT_STATUS_OBJECT_NAME_INVALID;
759 /* Can we access this file ? */
760 if (!fsp->base_fsp) {
761 /* Only do this check on non-stream open. */
762 if (file_existed) {
763 status = smbd_check_access_rights(conn,
764 smb_fname,
765 false,
766 access_mask);
767 } else if (local_flags & O_CREAT){
768 status = check_parent_access(conn,
769 smb_fname,
770 SEC_DIR_ADD_FILE);
771 } else {
772 /* File didn't exist and no O_CREAT. */
773 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
775 if (!NT_STATUS_IS_OK(status)) {
776 DEBUG(10,("open_file: "
777 "%s on file "
778 "%s returned %s\n",
779 file_existed ?
780 "smbd_check_access_rights" :
781 "check_parent_access",
782 smb_fname_str_dbg(smb_fname),
783 nt_errstr(status) ));
784 return status;
788 /* Actually do the open */
789 status = fd_open_atomic(conn, fsp, local_flags,
790 unx_mode, p_file_created);
791 if (!NT_STATUS_IS_OK(status)) {
792 DEBUG(3,("Error opening file %s (%s) (local_flags=%d) "
793 "(flags=%d)\n", smb_fname_str_dbg(smb_fname),
794 nt_errstr(status),local_flags,flags));
795 return status;
798 ret = SMB_VFS_FSTAT(fsp, &smb_fname->st);
799 if (ret == -1) {
800 /* If we have an fd, this stat should succeed. */
801 DEBUG(0,("Error doing fstat on open file %s "
802 "(%s)\n",
803 smb_fname_str_dbg(smb_fname),
804 strerror(errno) ));
805 status = map_nt_error_from_unix(errno);
806 fd_close(fsp);
807 return status;
810 if (*p_file_created) {
811 /* We created this file. */
813 bool need_re_stat = false;
814 /* Do all inheritance work after we've
815 done a successful fstat call and filled
816 in the stat struct in fsp->fsp_name. */
818 /* Inherit the ACL if required */
819 if (lp_inherit_perms(SNUM(conn))) {
820 inherit_access_posix_acl(conn, parent_dir,
821 smb_fname->base_name,
822 unx_mode);
823 need_re_stat = true;
826 /* Change the owner if required. */
827 if (lp_inherit_owner(SNUM(conn))) {
828 change_file_owner_to_parent(conn, parent_dir,
829 fsp);
830 need_re_stat = true;
833 if (need_re_stat) {
834 ret = SMB_VFS_FSTAT(fsp, &smb_fname->st);
835 /* If we have an fd, this stat should succeed. */
836 if (ret == -1) {
837 DEBUG(0,("Error doing fstat on open file %s "
838 "(%s)\n",
839 smb_fname_str_dbg(smb_fname),
840 strerror(errno) ));
844 notify_fname(conn, NOTIFY_ACTION_ADDED,
845 FILE_NOTIFY_CHANGE_FILE_NAME,
846 smb_fname->base_name);
848 } else {
849 fsp->fh->fd = -1; /* What we used to call a stat open. */
850 if (!file_existed) {
851 /* File must exist for a stat open. */
852 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
855 status = smbd_check_access_rights(conn,
856 smb_fname,
857 false,
858 access_mask);
860 if (NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND) &&
861 fsp->posix_open &&
862 S_ISLNK(smb_fname->st.st_ex_mode)) {
863 /* This is a POSIX stat open for delete
864 * or rename on a symlink that points
865 * nowhere. Allow. */
866 DEBUG(10,("open_file: allowing POSIX "
867 "open on bad symlink %s\n",
868 smb_fname_str_dbg(smb_fname)));
869 status = NT_STATUS_OK;
872 if (!NT_STATUS_IS_OK(status)) {
873 DEBUG(10,("open_file: "
874 "smbd_check_access_rights on file "
875 "%s returned %s\n",
876 smb_fname_str_dbg(smb_fname),
877 nt_errstr(status) ));
878 return status;
883 * POSIX allows read-only opens of directories. We don't
884 * want to do this (we use a different code path for this)
885 * so catch a directory open and return an EISDIR. JRA.
888 if(S_ISDIR(smb_fname->st.st_ex_mode)) {
889 fd_close(fsp);
890 errno = EISDIR;
891 return NT_STATUS_FILE_IS_A_DIRECTORY;
894 fsp->file_id = vfs_file_id_from_sbuf(conn, &smb_fname->st);
895 fsp->vuid = req ? req->vuid : UID_FIELD_INVALID;
896 fsp->file_pid = req ? req->smbpid : 0;
897 fsp->can_lock = True;
898 fsp->can_read = ((access_mask & FILE_READ_DATA) != 0);
899 fsp->can_write =
900 CAN_WRITE(conn) &&
901 ((access_mask & (FILE_WRITE_DATA | FILE_APPEND_DATA)) != 0);
902 fsp->print_file = NULL;
903 fsp->modified = False;
904 fsp->sent_oplock_break = NO_BREAK_SENT;
905 fsp->is_directory = False;
906 if (conn->aio_write_behind_list &&
907 is_in_path(smb_fname->base_name, conn->aio_write_behind_list,
908 conn->case_sensitive)) {
909 fsp->aio_write_behind = True;
912 fsp->wcp = NULL; /* Write cache pointer. */
914 DEBUG(2,("%s opened file %s read=%s write=%s (numopen=%d)\n",
915 conn->session_info->unix_info->unix_name,
916 smb_fname_str_dbg(smb_fname),
917 BOOLSTR(fsp->can_read), BOOLSTR(fsp->can_write),
918 conn->num_files_open));
920 errno = 0;
921 return NT_STATUS_OK;
924 /****************************************************************************
925 Check if we can open a file with a share mode.
926 Returns True if conflict, False if not.
927 ****************************************************************************/
929 static bool share_conflict(struct share_mode_entry *entry,
930 uint32 access_mask,
931 uint32 share_access)
933 DEBUG(10,("share_conflict: entry->access_mask = 0x%x, "
934 "entry->share_access = 0x%x, "
935 "entry->private_options = 0x%x\n",
936 (unsigned int)entry->access_mask,
937 (unsigned int)entry->share_access,
938 (unsigned int)entry->private_options));
940 if (server_id_is_disconnected(&entry->pid)) {
942 * note: cleanup should have been done by
943 * delay_for_batch_oplocks()
945 return false;
948 DEBUG(10,("share_conflict: access_mask = 0x%x, share_access = 0x%x\n",
949 (unsigned int)access_mask, (unsigned int)share_access));
951 if ((entry->access_mask & (FILE_WRITE_DATA|
952 FILE_APPEND_DATA|
953 FILE_READ_DATA|
954 FILE_EXECUTE|
955 DELETE_ACCESS)) == 0) {
956 DEBUG(10,("share_conflict: No conflict due to "
957 "entry->access_mask = 0x%x\n",
958 (unsigned int)entry->access_mask ));
959 return False;
962 if ((access_mask & (FILE_WRITE_DATA|
963 FILE_APPEND_DATA|
964 FILE_READ_DATA|
965 FILE_EXECUTE|
966 DELETE_ACCESS)) == 0) {
967 DEBUG(10,("share_conflict: No conflict due to "
968 "access_mask = 0x%x\n",
969 (unsigned int)access_mask ));
970 return False;
973 #if 1 /* JRA TEST - Superdebug. */
974 #define CHECK_MASK(num, am, right, sa, share) \
975 DEBUG(10,("share_conflict: [%d] am (0x%x) & right (0x%x) = 0x%x\n", \
976 (unsigned int)(num), (unsigned int)(am), \
977 (unsigned int)(right), (unsigned int)(am)&(right) )); \
978 DEBUG(10,("share_conflict: [%d] sa (0x%x) & share (0x%x) = 0x%x\n", \
979 (unsigned int)(num), (unsigned int)(sa), \
980 (unsigned int)(share), (unsigned int)(sa)&(share) )); \
981 if (((am) & (right)) && !((sa) & (share))) { \
982 DEBUG(10,("share_conflict: check %d conflict am = 0x%x, right = 0x%x, \
983 sa = 0x%x, share = 0x%x\n", (num), (unsigned int)(am), (unsigned int)(right), (unsigned int)(sa), \
984 (unsigned int)(share) )); \
985 return True; \
987 #else
988 #define CHECK_MASK(num, am, right, sa, share) \
989 if (((am) & (right)) && !((sa) & (share))) { \
990 DEBUG(10,("share_conflict: check %d conflict am = 0x%x, right = 0x%x, \
991 sa = 0x%x, share = 0x%x\n", (num), (unsigned int)(am), (unsigned int)(right), (unsigned int)(sa), \
992 (unsigned int)(share) )); \
993 return True; \
995 #endif
997 CHECK_MASK(1, entry->access_mask, FILE_WRITE_DATA | FILE_APPEND_DATA,
998 share_access, FILE_SHARE_WRITE);
999 CHECK_MASK(2, access_mask, FILE_WRITE_DATA | FILE_APPEND_DATA,
1000 entry->share_access, FILE_SHARE_WRITE);
1002 CHECK_MASK(3, entry->access_mask, FILE_READ_DATA | FILE_EXECUTE,
1003 share_access, FILE_SHARE_READ);
1004 CHECK_MASK(4, access_mask, FILE_READ_DATA | FILE_EXECUTE,
1005 entry->share_access, FILE_SHARE_READ);
1007 CHECK_MASK(5, entry->access_mask, DELETE_ACCESS,
1008 share_access, FILE_SHARE_DELETE);
1009 CHECK_MASK(6, access_mask, DELETE_ACCESS,
1010 entry->share_access, FILE_SHARE_DELETE);
1012 DEBUG(10,("share_conflict: No conflict.\n"));
1013 return False;
1016 #if defined(DEVELOPER)
1017 static void validate_my_share_entries(struct smbd_server_connection *sconn,
1018 int num,
1019 struct share_mode_entry *share_entry)
1021 struct server_id self = messaging_server_id(sconn->msg_ctx);
1022 files_struct *fsp;
1024 if (!serverid_equal(&self, &share_entry->pid)) {
1025 return;
1028 if (is_deferred_open_entry(share_entry) &&
1029 !open_was_deferred(sconn, share_entry->op_mid))
1031 char *str = talloc_asprintf(talloc_tos(),
1032 "Got a deferred entry without a request: "
1033 "PANIC: %s\n",
1034 share_mode_str(talloc_tos(), num, share_entry));
1035 smb_panic(str);
1038 if (!is_valid_share_mode_entry(share_entry)) {
1039 return;
1042 fsp = file_find_dif(sconn, share_entry->id,
1043 share_entry->share_file_id);
1044 if (!fsp) {
1045 DEBUG(0,("validate_my_share_entries: PANIC : %s\n",
1046 share_mode_str(talloc_tos(), num, share_entry) ));
1047 smb_panic("validate_my_share_entries: Cannot match a "
1048 "share entry with an open file\n");
1051 if (is_deferred_open_entry(share_entry)) {
1052 goto panic;
1055 if ((share_entry->op_type == NO_OPLOCK) &&
1056 (fsp->oplock_type == FAKE_LEVEL_II_OPLOCK))
1058 /* Someone has already written to it, but I haven't yet
1059 * noticed */
1060 return;
1063 if (((uint16)fsp->oplock_type) != share_entry->op_type) {
1064 goto panic;
1067 return;
1069 panic:
1071 char *str;
1072 DEBUG(0,("validate_my_share_entries: PANIC : %s\n",
1073 share_mode_str(talloc_tos(), num, share_entry) ));
1074 str = talloc_asprintf(talloc_tos(),
1075 "validate_my_share_entries: "
1076 "file %s, oplock_type = 0x%x, op_type = 0x%x\n",
1077 fsp->fsp_name->base_name,
1078 (unsigned int)fsp->oplock_type,
1079 (unsigned int)share_entry->op_type );
1080 smb_panic(str);
1083 #endif
1085 bool is_stat_open(uint32 access_mask)
1087 const uint32_t stat_open_bits =
1088 (SYNCHRONIZE_ACCESS|
1089 FILE_READ_ATTRIBUTES|
1090 FILE_WRITE_ATTRIBUTES);
1092 return (((access_mask & stat_open_bits) != 0) &&
1093 ((access_mask & ~stat_open_bits) == 0));
1096 /****************************************************************************
1097 Deal with share modes
1098 Invarient: Share mode must be locked on entry and exit.
1099 Returns -1 on error, or number of share modes on success (may be zero).
1100 ****************************************************************************/
1102 static NTSTATUS open_mode_check(connection_struct *conn,
1103 struct share_mode_lock *lck,
1104 uint32_t name_hash,
1105 uint32 access_mask,
1106 uint32 share_access,
1107 uint32 create_options,
1108 bool *file_existed)
1110 int i;
1112 if(lck->data->num_share_modes == 0) {
1113 return NT_STATUS_OK;
1116 /* A delete on close prohibits everything */
1118 if (is_delete_on_close_set(lck, name_hash)) {
1120 * Check the delete on close token
1121 * is valid. It could have been left
1122 * after a server crash.
1124 for(i = 0; i < lck->data->num_share_modes; i++) {
1125 if (!share_mode_stale_pid(lck->data, i)) {
1127 *file_existed = true;
1129 return NT_STATUS_DELETE_PENDING;
1132 return NT_STATUS_OK;
1135 if (is_stat_open(access_mask)) {
1136 /* Stat open that doesn't trigger oplock breaks or share mode
1137 * checks... ! JRA. */
1138 return NT_STATUS_OK;
1142 * Check if the share modes will give us access.
1145 #if defined(DEVELOPER)
1146 for(i = 0; i < lck->data->num_share_modes; i++) {
1147 validate_my_share_entries(conn->sconn, i,
1148 &lck->data->share_modes[i]);
1150 #endif
1152 /* Now we check the share modes, after any oplock breaks. */
1153 for(i = 0; i < lck->data->num_share_modes; i++) {
1155 if (!is_valid_share_mode_entry(&lck->data->share_modes[i])) {
1156 continue;
1159 /* someone else has a share lock on it, check to see if we can
1160 * too */
1161 if (share_conflict(&lck->data->share_modes[i],
1162 access_mask, share_access)) {
1164 if (share_mode_stale_pid(lck->data, i)) {
1165 continue;
1168 *file_existed = true;
1170 return NT_STATUS_SHARING_VIOLATION;
1174 if (lck->data->num_share_modes != 0) {
1175 *file_existed = true;
1178 return NT_STATUS_OK;
1182 * Send a break message to the oplock holder and delay the open for
1183 * our client.
1186 static NTSTATUS send_break_message(files_struct *fsp,
1187 struct share_mode_entry *exclusive,
1188 uint64_t mid,
1189 int oplock_request)
1191 NTSTATUS status;
1192 char msg[MSG_SMB_SHARE_MODE_ENTRY_SIZE];
1194 DEBUG(10, ("Sending break request to PID %s\n",
1195 procid_str_static(&exclusive->pid)));
1196 exclusive->op_mid = mid;
1198 /* Create the message. */
1199 share_mode_entry_to_message(msg, exclusive);
1201 /* Add in the FORCE_OPLOCK_BREAK_TO_NONE bit in the message if set. We
1202 don't want this set in the share mode struct pointed to by lck. */
1204 if (oplock_request & FORCE_OPLOCK_BREAK_TO_NONE) {
1205 SSVAL(msg,OP_BREAK_MSG_OP_TYPE_OFFSET,
1206 exclusive->op_type | FORCE_OPLOCK_BREAK_TO_NONE);
1209 status = messaging_send_buf(fsp->conn->sconn->msg_ctx, exclusive->pid,
1210 MSG_SMB_BREAK_REQUEST,
1211 (uint8 *)msg,
1212 MSG_SMB_SHARE_MODE_ENTRY_SIZE);
1213 if (!NT_STATUS_IS_OK(status)) {
1214 DEBUG(3, ("Could not send oplock break message: %s\n",
1215 nt_errstr(status)));
1218 return status;
1222 * Return share_mode_entry pointers for :
1223 * 1). Batch oplock entry.
1224 * 2). Batch or exclusive oplock entry (may be identical to #1).
1225 * bool have_level2_oplock
1226 * bool have_no_oplock.
1227 * Do internal consistency checks on the share mode for a file.
1230 static void find_oplock_types(files_struct *fsp,
1231 int oplock_request,
1232 const struct share_mode_lock *lck,
1233 struct share_mode_entry **pp_batch,
1234 struct share_mode_entry **pp_ex_or_batch,
1235 bool *got_level2,
1236 bool *got_no_oplock)
1238 int i;
1240 *pp_batch = NULL;
1241 *pp_ex_or_batch = NULL;
1242 *got_level2 = false;
1243 *got_no_oplock = false;
1245 /* Ignore stat or internal opens, as is done in
1246 delay_for_batch_oplocks() and
1247 delay_for_exclusive_oplocks().
1249 if ((oplock_request & INTERNAL_OPEN_ONLY) || is_stat_open(fsp->access_mask)) {
1250 return;
1253 for (i=0; i<lck->data->num_share_modes; i++) {
1254 if (!is_valid_share_mode_entry(&lck->data->share_modes[i])) {
1255 continue;
1258 if (lck->data->share_modes[i].op_type == NO_OPLOCK &&
1259 is_stat_open(lck->data->share_modes[i].access_mask)) {
1260 /* We ignore stat opens in the table - they
1261 always have NO_OPLOCK and never get or
1262 cause breaks. JRA. */
1263 continue;
1266 if (BATCH_OPLOCK_TYPE(lck->data->share_modes[i].op_type)) {
1267 /* batch - can only be one. */
1268 if (share_mode_stale_pid(lck->data, i)) {
1269 DEBUG(10, ("Found stale batch oplock\n"));
1270 continue;
1272 if (*pp_ex_or_batch || *pp_batch || *got_level2 || *got_no_oplock) {
1273 smb_panic("Bad batch oplock entry.");
1275 *pp_batch = &lck->data->share_modes[i];
1278 if (EXCLUSIVE_OPLOCK_TYPE(lck->data->share_modes[i].op_type)) {
1279 if (share_mode_stale_pid(lck->data, i)) {
1280 DEBUG(10, ("Found stale duplicate oplock\n"));
1281 continue;
1283 /* Exclusive or batch - can only be one. */
1284 if (*pp_ex_or_batch || *got_level2 || *got_no_oplock) {
1285 smb_panic("Bad exclusive or batch oplock entry.");
1287 *pp_ex_or_batch = &lck->data->share_modes[i];
1290 if (LEVEL_II_OPLOCK_TYPE(lck->data->share_modes[i].op_type)) {
1291 if (*pp_batch || *pp_ex_or_batch) {
1292 if (share_mode_stale_pid(lck->data, i)) {
1293 DEBUG(10, ("Found stale LevelII "
1294 "oplock\n"));
1295 continue;
1297 smb_panic("Bad levelII oplock entry.");
1299 *got_level2 = true;
1302 if (lck->data->share_modes[i].op_type == NO_OPLOCK) {
1303 if (*pp_batch || *pp_ex_or_batch) {
1304 if (share_mode_stale_pid(lck->data, i)) {
1305 DEBUG(10, ("Found stale NO_OPLOCK "
1306 "entry\n"));
1307 continue;
1309 smb_panic("Bad no oplock entry.");
1311 *got_no_oplock = true;
1316 static bool delay_for_batch_oplocks(files_struct *fsp,
1317 uint64_t mid,
1318 int oplock_request,
1319 struct share_mode_entry *batch_entry)
1321 if ((oplock_request & INTERNAL_OPEN_ONLY) || is_stat_open(fsp->access_mask)) {
1322 return false;
1324 if (batch_entry == NULL) {
1325 return false;
1328 if (server_id_is_disconnected(&batch_entry->pid)) {
1330 * TODO: clean up.
1331 * This could be achieved by sending a break message
1332 * to ourselves. Special considerations for files
1333 * with delete_on_close flag set!
1335 * For now we keep it simple and do not
1336 * allow delete on close for durable handles.
1338 return false;
1341 /* Found a batch oplock */
1342 send_break_message(fsp, batch_entry, mid, oplock_request);
1343 return true;
1346 static bool delay_for_exclusive_oplocks(files_struct *fsp,
1347 uint64_t mid,
1348 int oplock_request,
1349 struct share_mode_entry *ex_entry)
1351 if ((oplock_request & INTERNAL_OPEN_ONLY) || is_stat_open(fsp->access_mask)) {
1352 return false;
1354 if (ex_entry == NULL) {
1355 return false;
1358 if (server_id_is_disconnected(&ex_entry->pid)) {
1360 * since only durable handles can get disconnected,
1361 * and we can only get durable handles with batch oplocks,
1362 * this should actually never be reached...
1364 return false;
1367 send_break_message(fsp, ex_entry, mid, oplock_request);
1368 return true;
1371 static bool file_has_brlocks(files_struct *fsp)
1373 struct byte_range_lock *br_lck;
1375 br_lck = brl_get_locks_readonly(fsp);
1376 if (!br_lck)
1377 return false;
1379 return br_lck->num_locks > 0 ? true : false;
1382 static void grant_fsp_oplock_type(files_struct *fsp,
1383 int oplock_request,
1384 bool got_level2_oplock,
1385 bool got_a_none_oplock)
1387 bool allow_level2 = (global_client_caps & CAP_LEVEL_II_OPLOCKS) &&
1388 lp_level2_oplocks(SNUM(fsp->conn));
1390 /* Start by granting what the client asked for,
1391 but ensure no SAMBA_PRIVATE bits can be set. */
1392 fsp->oplock_type = (oplock_request & ~SAMBA_PRIVATE_OPLOCK_MASK);
1394 if (oplock_request & INTERNAL_OPEN_ONLY) {
1395 /* No oplocks on internal open. */
1396 fsp->oplock_type = NO_OPLOCK;
1397 DEBUG(10,("grant_fsp_oplock_type: oplock type 0x%x on file %s\n",
1398 fsp->oplock_type, fsp_str_dbg(fsp)));
1399 return;
1402 if (lp_locking(fsp->conn->params) && file_has_brlocks(fsp)) {
1403 DEBUG(10,("grant_fsp_oplock_type: file %s has byte range locks\n",
1404 fsp_str_dbg(fsp)));
1405 fsp->oplock_type = NO_OPLOCK;
1408 if (is_stat_open(fsp->access_mask)) {
1409 /* Leave the value already set. */
1410 DEBUG(10,("grant_fsp_oplock_type: oplock type 0x%x on file %s\n",
1411 fsp->oplock_type, fsp_str_dbg(fsp)));
1412 return;
1416 * Match what was requested (fsp->oplock_type) with
1417 * what was found in the existing share modes.
1420 if (got_a_none_oplock) {
1421 fsp->oplock_type = NO_OPLOCK;
1422 } else if (got_level2_oplock) {
1423 if (fsp->oplock_type == NO_OPLOCK ||
1424 fsp->oplock_type == FAKE_LEVEL_II_OPLOCK) {
1425 /* Store a level2 oplock, but don't tell the client */
1426 fsp->oplock_type = FAKE_LEVEL_II_OPLOCK;
1427 } else {
1428 fsp->oplock_type = LEVEL_II_OPLOCK;
1430 } else {
1431 /* All share_mode_entries are placeholders or deferred.
1432 * Silently upgrade to fake levelII if the client didn't
1433 * ask for an oplock. */
1434 if (fsp->oplock_type == NO_OPLOCK) {
1435 /* Store a level2 oplock, but don't tell the client */
1436 fsp->oplock_type = FAKE_LEVEL_II_OPLOCK;
1441 * Don't grant level2 to clients that don't want them
1442 * or if we've turned them off.
1444 if (fsp->oplock_type == LEVEL_II_OPLOCK && !allow_level2) {
1445 fsp->oplock_type = FAKE_LEVEL_II_OPLOCK;
1448 DEBUG(10,("grant_fsp_oplock_type: oplock type 0x%x on file %s\n",
1449 fsp->oplock_type, fsp_str_dbg(fsp)));
1452 static bool request_timed_out(struct timeval request_time,
1453 struct timeval timeout)
1455 struct timeval now, end_time;
1456 GetTimeOfDay(&now);
1457 end_time = timeval_sum(&request_time, &timeout);
1458 return (timeval_compare(&end_time, &now) < 0);
1461 /****************************************************************************
1462 Handle the 1 second delay in returning a SHARING_VIOLATION error.
1463 ****************************************************************************/
1465 static void defer_open(struct share_mode_lock *lck,
1466 struct timeval request_time,
1467 struct timeval timeout,
1468 struct smb_request *req,
1469 struct deferred_open_record *state)
1471 struct server_id self = messaging_server_id(req->sconn->msg_ctx);
1473 /* Paranoia check */
1475 if (lck) {
1476 int i;
1478 for (i=0; i<lck->data->num_share_modes; i++) {
1479 struct share_mode_entry *e = &lck->data->share_modes[i];
1481 if (is_deferred_open_entry(e) &&
1482 serverid_equal(&self, &e->pid) &&
1483 (e->op_mid == req->mid)) {
1484 DEBUG(0, ("Trying to defer an already deferred "
1485 "request: mid=%llu, exiting\n",
1486 (unsigned long long)req->mid));
1487 TALLOC_FREE(lck);
1488 exit_server("attempt to defer a deferred request");
1493 /* End paranoia check */
1495 DEBUG(10,("defer_open_sharing_error: time [%u.%06u] adding deferred "
1496 "open entry for mid %llu\n",
1497 (unsigned int)request_time.tv_sec,
1498 (unsigned int)request_time.tv_usec,
1499 (unsigned long long)req->mid));
1501 if (!push_deferred_open_message_smb(req, request_time, timeout,
1502 state->id, (char *)state, sizeof(*state))) {
1503 TALLOC_FREE(lck);
1504 exit_server("push_deferred_open_message_smb failed");
1506 if (lck) {
1507 add_deferred_open(lck, req->mid, request_time, self, state->id);
1512 /****************************************************************************
1513 On overwrite open ensure that the attributes match.
1514 ****************************************************************************/
1516 static bool open_match_attributes(connection_struct *conn,
1517 uint32 old_dos_attr,
1518 uint32 new_dos_attr,
1519 mode_t existing_unx_mode,
1520 mode_t new_unx_mode,
1521 mode_t *returned_unx_mode)
1523 uint32 noarch_old_dos_attr, noarch_new_dos_attr;
1525 noarch_old_dos_attr = (old_dos_attr & ~FILE_ATTRIBUTE_ARCHIVE);
1526 noarch_new_dos_attr = (new_dos_attr & ~FILE_ATTRIBUTE_ARCHIVE);
1528 if((noarch_old_dos_attr == 0 && noarch_new_dos_attr != 0) ||
1529 (noarch_old_dos_attr != 0 && ((noarch_old_dos_attr & noarch_new_dos_attr) == noarch_old_dos_attr))) {
1530 *returned_unx_mode = new_unx_mode;
1531 } else {
1532 *returned_unx_mode = (mode_t)0;
1535 DEBUG(10,("open_match_attributes: old_dos_attr = 0x%x, "
1536 "existing_unx_mode = 0%o, new_dos_attr = 0x%x "
1537 "returned_unx_mode = 0%o\n",
1538 (unsigned int)old_dos_attr,
1539 (unsigned int)existing_unx_mode,
1540 (unsigned int)new_dos_attr,
1541 (unsigned int)*returned_unx_mode ));
1543 /* If we're mapping SYSTEM and HIDDEN ensure they match. */
1544 if (lp_map_system(SNUM(conn)) || lp_store_dos_attributes(SNUM(conn))) {
1545 if ((old_dos_attr & FILE_ATTRIBUTE_SYSTEM) &&
1546 !(new_dos_attr & FILE_ATTRIBUTE_SYSTEM)) {
1547 return False;
1550 if (lp_map_hidden(SNUM(conn)) || lp_store_dos_attributes(SNUM(conn))) {
1551 if ((old_dos_attr & FILE_ATTRIBUTE_HIDDEN) &&
1552 !(new_dos_attr & FILE_ATTRIBUTE_HIDDEN)) {
1553 return False;
1556 return True;
1559 /****************************************************************************
1560 Special FCB or DOS processing in the case of a sharing violation.
1561 Try and find a duplicated file handle.
1562 ****************************************************************************/
1564 static NTSTATUS fcb_or_dos_open(struct smb_request *req,
1565 connection_struct *conn,
1566 files_struct *fsp_to_dup_into,
1567 const struct smb_filename *smb_fname,
1568 struct file_id id,
1569 uint16 file_pid,
1570 uint64_t vuid,
1571 uint32 access_mask,
1572 uint32 share_access,
1573 uint32 create_options)
1575 files_struct *fsp;
1577 DEBUG(5,("fcb_or_dos_open: attempting old open semantics for "
1578 "file %s.\n", smb_fname_str_dbg(smb_fname)));
1580 for(fsp = file_find_di_first(conn->sconn, id); fsp;
1581 fsp = file_find_di_next(fsp)) {
1583 DEBUG(10,("fcb_or_dos_open: checking file %s, fd = %d, "
1584 "vuid = %llu, file_pid = %u, private_options = 0x%x "
1585 "access_mask = 0x%x\n", fsp_str_dbg(fsp),
1586 fsp->fh->fd, (unsigned long long)fsp->vuid,
1587 (unsigned int)fsp->file_pid,
1588 (unsigned int)fsp->fh->private_options,
1589 (unsigned int)fsp->access_mask ));
1591 if (fsp != fsp_to_dup_into &&
1592 fsp->fh->fd != -1 &&
1593 fsp->vuid == vuid &&
1594 fsp->file_pid == file_pid &&
1595 (fsp->fh->private_options & (NTCREATEX_OPTIONS_PRIVATE_DENY_DOS |
1596 NTCREATEX_OPTIONS_PRIVATE_DENY_FCB)) &&
1597 (fsp->access_mask & FILE_WRITE_DATA) &&
1598 strequal(fsp->fsp_name->base_name, smb_fname->base_name) &&
1599 strequal(fsp->fsp_name->stream_name,
1600 smb_fname->stream_name)) {
1601 DEBUG(10,("fcb_or_dos_open: file match\n"));
1602 break;
1606 if (!fsp) {
1607 return NT_STATUS_NOT_FOUND;
1610 /* quite an insane set of semantics ... */
1611 if (is_executable(smb_fname->base_name) &&
1612 (fsp->fh->private_options & NTCREATEX_OPTIONS_PRIVATE_DENY_DOS)) {
1613 DEBUG(10,("fcb_or_dos_open: file fail due to is_executable.\n"));
1614 return NT_STATUS_INVALID_PARAMETER;
1617 /* We need to duplicate this fsp. */
1618 return dup_file_fsp(req, fsp, access_mask, share_access,
1619 create_options, fsp_to_dup_into);
1622 static void schedule_defer_open(struct share_mode_lock *lck,
1623 struct timeval request_time,
1624 struct smb_request *req)
1626 struct deferred_open_record state;
1628 /* This is a relative time, added to the absolute
1629 request_time value to get the absolute timeout time.
1630 Note that if this is the second or greater time we enter
1631 this codepath for this particular request mid then
1632 request_time is left as the absolute time of the *first*
1633 time this request mid was processed. This is what allows
1634 the request to eventually time out. */
1636 struct timeval timeout;
1638 /* Normally the smbd we asked should respond within
1639 * OPLOCK_BREAK_TIMEOUT seconds regardless of whether
1640 * the client did, give twice the timeout as a safety
1641 * measure here in case the other smbd is stuck
1642 * somewhere else. */
1644 timeout = timeval_set(OPLOCK_BREAK_TIMEOUT*2, 0);
1646 /* Nothing actually uses state.delayed_for_oplocks
1647 but it's handy to differentiate in debug messages
1648 between a 30 second delay due to oplock break, and
1649 a 1 second delay for share mode conflicts. */
1651 state.delayed_for_oplocks = True;
1652 state.async_open = false;
1653 state.id = lck->data->id;
1655 if (!request_timed_out(request_time, timeout)) {
1656 defer_open(lck, request_time, timeout, req, &state);
1660 /****************************************************************************
1661 Reschedule an open call that went asynchronous.
1662 ****************************************************************************/
1664 static void schedule_async_open(struct timeval request_time,
1665 struct smb_request *req)
1667 struct deferred_open_record state;
1668 struct timeval timeout;
1670 timeout = timeval_set(20, 0);
1672 ZERO_STRUCT(state);
1673 state.delayed_for_oplocks = false;
1674 state.async_open = true;
1676 if (!request_timed_out(request_time, timeout)) {
1677 defer_open(NULL, request_time, timeout, req, &state);
1681 /****************************************************************************
1682 Work out what access_mask to use from what the client sent us.
1683 ****************************************************************************/
1685 static NTSTATUS smbd_calculate_maximum_allowed_access(
1686 connection_struct *conn,
1687 const struct smb_filename *smb_fname,
1688 bool use_privs,
1689 uint32_t *p_access_mask)
1691 struct security_descriptor *sd;
1692 uint32_t access_granted;
1693 NTSTATUS status;
1695 if (!use_privs && (get_current_uid(conn) == (uid_t)0)) {
1696 *p_access_mask |= FILE_GENERIC_ALL;
1697 return NT_STATUS_OK;
1700 status = SMB_VFS_GET_NT_ACL(conn, smb_fname->base_name,
1701 (SECINFO_OWNER |
1702 SECINFO_GROUP |
1703 SECINFO_DACL),
1704 talloc_tos(), &sd);
1706 if (NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
1708 * File did not exist
1710 *p_access_mask = FILE_GENERIC_ALL;
1711 return NT_STATUS_OK;
1713 if (!NT_STATUS_IS_OK(status)) {
1714 DEBUG(10,("Could not get acl on file %s: %s\n",
1715 smb_fname_str_dbg(smb_fname),
1716 nt_errstr(status)));
1717 return NT_STATUS_ACCESS_DENIED;
1721 * If we can access the path to this file, by
1722 * default we have FILE_READ_ATTRIBUTES from the
1723 * containing directory. See the section:
1724 * "Algorithm to Check Access to an Existing File"
1725 * in MS-FSA.pdf.
1727 * se_file_access_check()
1728 * also takes care of owner WRITE_DAC and READ_CONTROL.
1730 status = se_file_access_check(sd,
1731 get_current_nttok(conn),
1732 use_privs,
1733 (*p_access_mask & ~FILE_READ_ATTRIBUTES),
1734 &access_granted);
1736 TALLOC_FREE(sd);
1738 if (!NT_STATUS_IS_OK(status)) {
1739 DEBUG(10, ("Access denied on file %s: "
1740 "when calculating maximum access\n",
1741 smb_fname_str_dbg(smb_fname)));
1742 return NT_STATUS_ACCESS_DENIED;
1744 *p_access_mask = (access_granted | FILE_READ_ATTRIBUTES);
1746 if (!(access_granted & DELETE_ACCESS)) {
1747 if (can_delete_file_in_directory(conn, smb_fname)) {
1748 *p_access_mask |= DELETE_ACCESS;
1752 return NT_STATUS_OK;
1755 NTSTATUS smbd_calculate_access_mask(connection_struct *conn,
1756 const struct smb_filename *smb_fname,
1757 bool use_privs,
1758 uint32_t access_mask,
1759 uint32_t *access_mask_out)
1761 NTSTATUS status;
1762 uint32_t orig_access_mask = access_mask;
1763 uint32_t rejected_share_access;
1766 * Convert GENERIC bits to specific bits.
1769 se_map_generic(&access_mask, &file_generic_mapping);
1771 /* Calculate MAXIMUM_ALLOWED_ACCESS if requested. */
1772 if (access_mask & MAXIMUM_ALLOWED_ACCESS) {
1774 status = smbd_calculate_maximum_allowed_access(
1775 conn, smb_fname, use_privs, &access_mask);
1777 if (!NT_STATUS_IS_OK(status)) {
1778 return status;
1781 access_mask &= conn->share_access;
1784 rejected_share_access = access_mask & ~(conn->share_access);
1786 if (rejected_share_access) {
1787 DEBUG(10, ("smbd_calculate_access_mask: Access denied on "
1788 "file %s: rejected by share access mask[0x%08X] "
1789 "orig[0x%08X] mapped[0x%08X] reject[0x%08X]\n",
1790 smb_fname_str_dbg(smb_fname),
1791 conn->share_access,
1792 orig_access_mask, access_mask,
1793 rejected_share_access));
1794 return NT_STATUS_ACCESS_DENIED;
1797 *access_mask_out = access_mask;
1798 return NT_STATUS_OK;
1801 /****************************************************************************
1802 Remove the deferred open entry under lock.
1803 ****************************************************************************/
1805 void remove_deferred_open_entry(struct file_id id, uint64_t mid,
1806 struct server_id pid)
1808 struct share_mode_lock *lck = get_existing_share_mode_lock(
1809 talloc_tos(), id);
1810 if (lck == NULL) {
1811 DEBUG(0, ("could not get share mode lock\n"));
1812 return;
1814 del_deferred_open_entry(lck, mid, pid);
1815 TALLOC_FREE(lck);
1818 /****************************************************************************
1819 Return true if this is a state pointer to an asynchronous create.
1820 ****************************************************************************/
1822 bool is_deferred_open_async(const void *ptr)
1824 const struct deferred_open_record *state = (const struct deferred_open_record *)ptr;
1826 return state->async_open;
1829 static bool clear_ads(uint32_t create_disposition)
1831 bool ret = false;
1833 switch (create_disposition) {
1834 case FILE_SUPERSEDE:
1835 case FILE_OVERWRITE_IF:
1836 case FILE_OVERWRITE:
1837 ret = true;
1838 break;
1839 default:
1840 break;
1842 return ret;
1845 static int disposition_to_open_flags(uint32_t create_disposition)
1847 int ret = 0;
1850 * Currently we're using FILE_SUPERSEDE as the same as
1851 * FILE_OVERWRITE_IF but they really are
1852 * different. FILE_SUPERSEDE deletes an existing file
1853 * (requiring delete access) then recreates it.
1856 switch (create_disposition) {
1857 case FILE_SUPERSEDE:
1858 case FILE_OVERWRITE_IF:
1860 * If file exists replace/overwrite. If file doesn't
1861 * exist create.
1863 ret = O_CREAT|O_TRUNC;
1864 break;
1866 case FILE_OPEN:
1868 * If file exists open. If file doesn't exist error.
1870 ret = 0;
1871 break;
1873 case FILE_OVERWRITE:
1875 * If file exists overwrite. If file doesn't exist
1876 * error.
1878 ret = O_TRUNC;
1879 break;
1881 case FILE_CREATE:
1883 * If file exists error. If file doesn't exist create.
1885 ret = O_CREAT|O_EXCL;
1886 break;
1888 case FILE_OPEN_IF:
1890 * If file exists open. If file doesn't exist create.
1892 ret = O_CREAT;
1893 break;
1895 return ret;
1898 static int calculate_open_access_flags(uint32_t access_mask,
1899 int oplock_request,
1900 uint32_t private_flags)
1902 bool need_write, need_read;
1905 * Note that we ignore the append flag as append does not
1906 * mean the same thing under DOS and Unix.
1909 need_write =
1910 ((access_mask & (FILE_WRITE_DATA | FILE_APPEND_DATA)) ||
1911 (oplock_request & FORCE_OPLOCK_BREAK_TO_NONE));
1913 if (!need_write) {
1914 return O_RDONLY;
1917 /* DENY_DOS opens are always underlying read-write on the
1918 file handle, no matter what the requested access mask
1919 says. */
1921 need_read =
1922 ((private_flags & NTCREATEX_OPTIONS_PRIVATE_DENY_DOS) ||
1923 access_mask & (FILE_READ_ATTRIBUTES|FILE_READ_DATA|
1924 FILE_READ_EA|FILE_EXECUTE));
1926 if (!need_read) {
1927 return O_WRONLY;
1929 return O_RDWR;
1932 /****************************************************************************
1933 Open a file with a share mode. Passed in an already created files_struct *.
1934 ****************************************************************************/
1936 static NTSTATUS open_file_ntcreate(connection_struct *conn,
1937 struct smb_request *req,
1938 uint32 access_mask, /* access bits (FILE_READ_DATA etc.) */
1939 uint32 share_access, /* share constants (FILE_SHARE_READ etc) */
1940 uint32 create_disposition, /* FILE_OPEN_IF etc. */
1941 uint32 create_options, /* options such as delete on close. */
1942 uint32 new_dos_attributes, /* attributes used for new file. */
1943 int oplock_request, /* internal Samba oplock codes. */
1944 /* Information (FILE_EXISTS etc.) */
1945 uint32_t private_flags, /* Samba specific flags. */
1946 int *pinfo,
1947 files_struct *fsp)
1949 struct smb_filename *smb_fname = fsp->fsp_name;
1950 int flags=0;
1951 int flags2=0;
1952 bool file_existed = VALID_STAT(smb_fname->st);
1953 bool def_acl = False;
1954 bool posix_open = False;
1955 bool new_file_created = False;
1956 bool first_open_attempt = true;
1957 NTSTATUS fsp_open = NT_STATUS_ACCESS_DENIED;
1958 mode_t new_unx_mode = (mode_t)0;
1959 mode_t unx_mode = (mode_t)0;
1960 int info;
1961 uint32 existing_dos_attributes = 0;
1962 struct timeval request_time = timeval_zero();
1963 struct share_mode_lock *lck = NULL;
1964 uint32 open_access_mask = access_mask;
1965 NTSTATUS status;
1966 char *parent_dir;
1967 SMB_STRUCT_STAT saved_stat = smb_fname->st;
1968 struct share_mode_entry *batch_entry = NULL;
1969 struct share_mode_entry *exclusive_entry = NULL;
1970 bool got_level2_oplock = false;
1971 bool got_a_none_oplock = false;
1972 struct timespec old_write_time;
1973 struct file_id id;
1975 if (conn->printer) {
1977 * Printers are handled completely differently.
1978 * Most of the passed parameters are ignored.
1981 if (pinfo) {
1982 *pinfo = FILE_WAS_CREATED;
1985 DEBUG(10, ("open_file_ntcreate: printer open fname=%s\n",
1986 smb_fname_str_dbg(smb_fname)));
1988 if (!req) {
1989 DEBUG(0,("open_file_ntcreate: printer open without "
1990 "an SMB request!\n"));
1991 return NT_STATUS_INTERNAL_ERROR;
1994 return print_spool_open(fsp, smb_fname->base_name,
1995 req->vuid);
1998 if (!parent_dirname(talloc_tos(), smb_fname->base_name, &parent_dir,
1999 NULL)) {
2000 return NT_STATUS_NO_MEMORY;
2003 if (new_dos_attributes & FILE_FLAG_POSIX_SEMANTICS) {
2004 posix_open = True;
2005 unx_mode = (mode_t)(new_dos_attributes & ~FILE_FLAG_POSIX_SEMANTICS);
2006 new_dos_attributes = 0;
2007 } else {
2008 /* Windows allows a new file to be created and
2009 silently removes a FILE_ATTRIBUTE_DIRECTORY
2010 sent by the client. Do the same. */
2012 new_dos_attributes &= ~FILE_ATTRIBUTE_DIRECTORY;
2014 /* We add FILE_ATTRIBUTE_ARCHIVE to this as this mode is only used if the file is
2015 * created new. */
2016 unx_mode = unix_mode(conn, new_dos_attributes | FILE_ATTRIBUTE_ARCHIVE,
2017 smb_fname, parent_dir);
2020 DEBUG(10, ("open_file_ntcreate: fname=%s, dos_attrs=0x%x "
2021 "access_mask=0x%x share_access=0x%x "
2022 "create_disposition = 0x%x create_options=0x%x "
2023 "unix mode=0%o oplock_request=%d private_flags = 0x%x\n",
2024 smb_fname_str_dbg(smb_fname), new_dos_attributes,
2025 access_mask, share_access, create_disposition,
2026 create_options, (unsigned int)unx_mode, oplock_request,
2027 (unsigned int)private_flags));
2029 if ((req == NULL) && ((oplock_request & INTERNAL_OPEN_ONLY) == 0)) {
2030 DEBUG(0, ("No smb request but not an internal only open!\n"));
2031 return NT_STATUS_INTERNAL_ERROR;
2035 * Only non-internal opens can be deferred at all
2038 if (req) {
2039 void *ptr;
2040 if (get_deferred_open_message_state(req,
2041 &request_time,
2042 &ptr)) {
2043 /* Remember the absolute time of the original
2044 request with this mid. We'll use it later to
2045 see if this has timed out. */
2047 /* If it was an async create retry, the file
2048 didn't exist. */
2050 if (is_deferred_open_async(ptr)) {
2051 SET_STAT_INVALID(smb_fname->st);
2052 file_existed = false;
2053 } else {
2054 struct deferred_open_record *state = (struct deferred_open_record *)ptr;
2055 /* Remove the deferred open entry under lock. */
2056 remove_deferred_open_entry(
2057 state->id, req->mid,
2058 messaging_server_id(req->sconn->msg_ctx));
2061 /* Ensure we don't reprocess this message. */
2062 remove_deferred_open_message_smb(req->sconn, req->mid);
2064 first_open_attempt = false;
2068 if (!posix_open) {
2069 new_dos_attributes &= SAMBA_ATTRIBUTES_MASK;
2070 if (file_existed) {
2071 existing_dos_attributes = dos_mode(conn, smb_fname);
2075 /* ignore any oplock requests if oplocks are disabled */
2076 if (!lp_oplocks(SNUM(conn)) ||
2077 IS_VETO_OPLOCK_PATH(conn, smb_fname->base_name)) {
2078 /* Mask off everything except the private Samba bits. */
2079 oplock_request &= SAMBA_PRIVATE_OPLOCK_MASK;
2082 /* this is for OS/2 long file names - say we don't support them */
2083 if (!lp_posix_pathnames() && strstr(smb_fname->base_name,".+,;=[].")) {
2084 /* OS/2 Workplace shell fix may be main code stream in a later
2085 * release. */
2086 DEBUG(5,("open_file_ntcreate: OS/2 long filenames are not "
2087 "supported.\n"));
2088 if (use_nt_status()) {
2089 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
2091 return NT_STATUS_DOS(ERRDOS, ERRcannotopen);
2094 switch( create_disposition ) {
2095 case FILE_OPEN:
2096 /* If file exists open. If file doesn't exist error. */
2097 if (!file_existed) {
2098 DEBUG(5,("open_file_ntcreate: FILE_OPEN "
2099 "requested for file %s and file "
2100 "doesn't exist.\n",
2101 smb_fname_str_dbg(smb_fname)));
2102 errno = ENOENT;
2103 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
2105 break;
2107 case FILE_OVERWRITE:
2108 /* If file exists overwrite. If file doesn't exist
2109 * error. */
2110 if (!file_existed) {
2111 DEBUG(5,("open_file_ntcreate: FILE_OVERWRITE "
2112 "requested for file %s and file "
2113 "doesn't exist.\n",
2114 smb_fname_str_dbg(smb_fname) ));
2115 errno = ENOENT;
2116 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
2118 break;
2120 case FILE_CREATE:
2121 /* If file exists error. If file doesn't exist
2122 * create. */
2123 if (file_existed) {
2124 DEBUG(5,("open_file_ntcreate: FILE_CREATE "
2125 "requested for file %s and file "
2126 "already exists.\n",
2127 smb_fname_str_dbg(smb_fname)));
2128 if (S_ISDIR(smb_fname->st.st_ex_mode)) {
2129 errno = EISDIR;
2130 } else {
2131 errno = EEXIST;
2133 return map_nt_error_from_unix(errno);
2135 break;
2137 case FILE_SUPERSEDE:
2138 case FILE_OVERWRITE_IF:
2139 case FILE_OPEN_IF:
2140 break;
2141 default:
2142 return NT_STATUS_INVALID_PARAMETER;
2145 flags2 = disposition_to_open_flags(create_disposition);
2147 /* We only care about matching attributes on file exists and
2148 * overwrite. */
2150 if (!posix_open && file_existed &&
2151 ((create_disposition == FILE_OVERWRITE) ||
2152 (create_disposition == FILE_OVERWRITE_IF))) {
2153 if (!open_match_attributes(conn, existing_dos_attributes,
2154 new_dos_attributes,
2155 smb_fname->st.st_ex_mode,
2156 unx_mode, &new_unx_mode)) {
2157 DEBUG(5,("open_file_ntcreate: attributes missmatch "
2158 "for file %s (%x %x) (0%o, 0%o)\n",
2159 smb_fname_str_dbg(smb_fname),
2160 existing_dos_attributes,
2161 new_dos_attributes,
2162 (unsigned int)smb_fname->st.st_ex_mode,
2163 (unsigned int)unx_mode ));
2164 errno = EACCES;
2165 return NT_STATUS_ACCESS_DENIED;
2169 status = smbd_calculate_access_mask(conn, smb_fname,
2170 false,
2171 access_mask,
2172 &access_mask);
2173 if (!NT_STATUS_IS_OK(status)) {
2174 DEBUG(10, ("open_file_ntcreate: smbd_calculate_access_mask "
2175 "on file %s returned %s\n",
2176 smb_fname_str_dbg(smb_fname), nt_errstr(status)));
2177 return status;
2180 open_access_mask = access_mask;
2182 if ((flags2 & O_TRUNC) || (oplock_request & FORCE_OPLOCK_BREAK_TO_NONE)) {
2183 open_access_mask |= FILE_WRITE_DATA; /* This will cause oplock breaks. */
2186 DEBUG(10, ("open_file_ntcreate: fname=%s, after mapping "
2187 "access_mask=0x%x\n", smb_fname_str_dbg(smb_fname),
2188 access_mask));
2191 * Note that we ignore the append flag as append does not
2192 * mean the same thing under DOS and Unix.
2195 flags = calculate_open_access_flags(access_mask, oplock_request,
2196 private_flags);
2199 * Currently we only look at FILE_WRITE_THROUGH for create options.
2202 #if defined(O_SYNC)
2203 if ((create_options & FILE_WRITE_THROUGH) && lp_strict_sync(SNUM(conn))) {
2204 flags2 |= O_SYNC;
2206 #endif /* O_SYNC */
2208 if (posix_open && (access_mask & FILE_APPEND_DATA)) {
2209 flags2 |= O_APPEND;
2212 if (!posix_open && !CAN_WRITE(conn)) {
2214 * We should really return a permission denied error if either
2215 * O_CREAT or O_TRUNC are set, but for compatibility with
2216 * older versions of Samba we just AND them out.
2218 flags2 &= ~(O_CREAT|O_TRUNC);
2221 if (first_open_attempt && lp_kernel_oplocks(SNUM(conn))) {
2223 * With kernel oplocks the open breaking an oplock
2224 * blocks until the oplock holder has given up the
2225 * oplock or closed the file. We prevent this by first
2226 * trying to open the file with O_NONBLOCK (see "man
2227 * fcntl" on Linux). For the second try, triggered by
2228 * an oplock break response, we do not need this
2229 * anymore.
2231 * This is true under the assumption that only Samba
2232 * requests kernel oplocks. Once someone else like
2233 * NFSv4 starts to use that API, we will have to
2234 * modify this by communicating with the NFSv4 server.
2236 flags2 |= O_NONBLOCK;
2240 * Ensure we can't write on a read-only share or file.
2243 if (flags != O_RDONLY && file_existed &&
2244 (!CAN_WRITE(conn) || IS_DOS_READONLY(existing_dos_attributes))) {
2245 DEBUG(5,("open_file_ntcreate: write access requested for "
2246 "file %s on read only %s\n",
2247 smb_fname_str_dbg(smb_fname),
2248 !CAN_WRITE(conn) ? "share" : "file" ));
2249 errno = EACCES;
2250 return NT_STATUS_ACCESS_DENIED;
2253 fsp->file_id = vfs_file_id_from_sbuf(conn, &smb_fname->st);
2254 fsp->share_access = share_access;
2255 fsp->fh->private_options = private_flags;
2256 fsp->access_mask = open_access_mask; /* We change this to the
2257 * requested access_mask after
2258 * the open is done. */
2259 fsp->posix_open = posix_open;
2261 /* Ensure no SAMBA_PRIVATE bits can be set. */
2262 fsp->oplock_type = (oplock_request & ~SAMBA_PRIVATE_OPLOCK_MASK);
2264 if (timeval_is_zero(&request_time)) {
2265 request_time = fsp->open_time;
2269 * Ensure we pay attention to default ACLs on directories if required.
2272 if ((flags2 & O_CREAT) && lp_inherit_acls(SNUM(conn)) &&
2273 (def_acl = directory_has_default_acl(conn, parent_dir))) {
2274 unx_mode = (0777 & lp_create_mask(SNUM(conn)));
2277 DEBUG(4,("calling open_file with flags=0x%X flags2=0x%X mode=0%o, "
2278 "access_mask = 0x%x, open_access_mask = 0x%x\n",
2279 (unsigned int)flags, (unsigned int)flags2,
2280 (unsigned int)unx_mode, (unsigned int)access_mask,
2281 (unsigned int)open_access_mask));
2283 fsp_open = open_file(fsp, conn, req, parent_dir,
2284 flags|flags2, unx_mode, access_mask,
2285 open_access_mask, &new_file_created);
2287 if (NT_STATUS_EQUAL(fsp_open, NT_STATUS_NETWORK_BUSY)) {
2288 struct deferred_open_record state;
2291 * EWOULDBLOCK/EAGAIN maps to NETWORK_BUSY.
2293 if (file_existed && S_ISFIFO(fsp->fsp_name->st.st_ex_mode)) {
2294 DEBUG(10, ("FIFO busy\n"));
2295 return NT_STATUS_NETWORK_BUSY;
2297 if (req == NULL) {
2298 DEBUG(10, ("Internal open busy\n"));
2299 return NT_STATUS_NETWORK_BUSY;
2303 * From here on we assume this is an oplock break triggered
2306 lck = get_existing_share_mode_lock(talloc_tos(), fsp->file_id);
2307 if (lck == NULL) {
2308 state.delayed_for_oplocks = false;
2309 state.async_open = false;
2310 state.id = fsp->file_id;
2311 defer_open(NULL, request_time, timeval_set(0, 0),
2312 req, &state);
2313 DEBUG(10, ("No share mode lock found after "
2314 "EWOULDBLOCK, retrying sync\n"));
2315 return NT_STATUS_SHARING_VIOLATION;
2318 find_oplock_types(fsp, 0, lck, &batch_entry, &exclusive_entry,
2319 &got_level2_oplock, &got_a_none_oplock);
2321 if (delay_for_batch_oplocks(fsp, req->mid, 0, batch_entry) ||
2322 delay_for_exclusive_oplocks(fsp, req->mid, 0,
2323 exclusive_entry)) {
2324 schedule_defer_open(lck, request_time, req);
2325 TALLOC_FREE(lck);
2326 DEBUG(10, ("Sent oplock break request to kernel "
2327 "oplock holder\n"));
2328 return NT_STATUS_SHARING_VIOLATION;
2332 * No oplock from Samba around. Immediately retry with
2333 * a blocking open.
2335 state.delayed_for_oplocks = false;
2336 state.async_open = false;
2337 state.id = lck->data->id;
2338 defer_open(lck, request_time, timeval_set(0, 0), req, &state);
2339 TALLOC_FREE(lck);
2340 DEBUG(10, ("No Samba oplock around after EWOULDBLOCK. "
2341 "Retrying sync\n"));
2342 return NT_STATUS_SHARING_VIOLATION;
2345 if (!NT_STATUS_IS_OK(fsp_open)) {
2346 if (NT_STATUS_EQUAL(fsp_open, NT_STATUS_RETRY)) {
2347 schedule_async_open(request_time, req);
2349 TALLOC_FREE(lck);
2350 return fsp_open;
2353 if (file_existed && !check_same_dev_ino(&saved_stat, &smb_fname->st)) {
2355 * The file did exist, but some other (local or NFS)
2356 * process either renamed/unlinked and re-created the
2357 * file with different dev/ino after we walked the path,
2358 * but before we did the open. We could retry the
2359 * open but it's a rare enough case it's easier to
2360 * just fail the open to prevent creating any problems
2361 * in the open file db having the wrong dev/ino key.
2363 TALLOC_FREE(lck);
2364 fd_close(fsp);
2365 DEBUG(1,("open_file_ntcreate: file %s - dev/ino mismatch. "
2366 "Old (dev=0x%llu, ino =0x%llu). "
2367 "New (dev=0x%llu, ino=0x%llu). Failing open "
2368 " with NT_STATUS_ACCESS_DENIED.\n",
2369 smb_fname_str_dbg(smb_fname),
2370 (unsigned long long)saved_stat.st_ex_dev,
2371 (unsigned long long)saved_stat.st_ex_ino,
2372 (unsigned long long)smb_fname->st.st_ex_dev,
2373 (unsigned long long)smb_fname->st.st_ex_ino));
2374 return NT_STATUS_ACCESS_DENIED;
2377 old_write_time = smb_fname->st.st_ex_mtime;
2380 * Deal with the race condition where two smbd's detect the
2381 * file doesn't exist and do the create at the same time. One
2382 * of them will win and set a share mode, the other (ie. this
2383 * one) should check if the requested share mode for this
2384 * create is allowed.
2388 * Now the file exists and fsp is successfully opened,
2389 * fsp->dev and fsp->inode are valid and should replace the
2390 * dev=0,inode=0 from a non existent file. Spotted by
2391 * Nadav Danieli <nadavd@exanet.com>. JRA.
2394 id = fsp->file_id;
2396 lck = get_share_mode_lock(talloc_tos(), id,
2397 conn->connectpath,
2398 smb_fname, &old_write_time);
2400 if (lck == NULL) {
2401 DEBUG(0, ("open_file_ntcreate: Could not get share "
2402 "mode lock for %s\n",
2403 smb_fname_str_dbg(smb_fname)));
2404 fd_close(fsp);
2405 return NT_STATUS_SHARING_VIOLATION;
2408 /* Get the types we need to examine. */
2409 find_oplock_types(fsp,
2410 oplock_request,
2411 lck,
2412 &batch_entry,
2413 &exclusive_entry,
2414 &got_level2_oplock,
2415 &got_a_none_oplock);
2417 /* First pass - send break only on batch oplocks. */
2418 if ((req != NULL) &&
2419 delay_for_batch_oplocks(fsp,
2420 req->mid,
2421 oplock_request,
2422 batch_entry)) {
2423 schedule_defer_open(lck, request_time, req);
2424 TALLOC_FREE(lck);
2425 fd_close(fsp);
2426 return NT_STATUS_SHARING_VIOLATION;
2429 status = open_mode_check(conn, lck, fsp->name_hash,
2430 access_mask, share_access,
2431 create_options, &file_existed);
2433 if (NT_STATUS_IS_OK(status)) {
2434 /* We might be going to allow this open. Check oplock
2435 * status again. */
2436 /* Second pass - send break for both batch or
2437 * exclusive oplocks. */
2438 if ((req != NULL) &&
2439 delay_for_exclusive_oplocks(
2440 fsp,
2441 req->mid,
2442 oplock_request,
2443 exclusive_entry)) {
2444 schedule_defer_open(lck, request_time, req);
2445 TALLOC_FREE(lck);
2446 fd_close(fsp);
2447 return NT_STATUS_SHARING_VIOLATION;
2451 if (NT_STATUS_EQUAL(status, NT_STATUS_DELETE_PENDING)) {
2452 /* DELETE_PENDING is not deferred for a second */
2453 TALLOC_FREE(lck);
2454 fd_close(fsp);
2455 return status;
2458 if (!NT_STATUS_IS_OK(status)) {
2459 uint32 can_access_mask;
2460 bool can_access = True;
2462 SMB_ASSERT(NT_STATUS_EQUAL(status, NT_STATUS_SHARING_VIOLATION));
2464 /* Check if this can be done with the deny_dos and fcb
2465 * calls. */
2466 if (private_flags &
2467 (NTCREATEX_OPTIONS_PRIVATE_DENY_DOS|
2468 NTCREATEX_OPTIONS_PRIVATE_DENY_FCB)) {
2469 if (req == NULL) {
2470 DEBUG(0, ("DOS open without an SMB "
2471 "request!\n"));
2472 TALLOC_FREE(lck);
2473 fd_close(fsp);
2474 return NT_STATUS_INTERNAL_ERROR;
2477 /* Use the client requested access mask here,
2478 * not the one we open with. */
2479 status = fcb_or_dos_open(req,
2480 conn,
2481 fsp,
2482 smb_fname,
2484 req->smbpid,
2485 req->vuid,
2486 access_mask,
2487 share_access,
2488 create_options);
2490 if (NT_STATUS_IS_OK(status)) {
2491 TALLOC_FREE(lck);
2492 if (pinfo) {
2493 *pinfo = FILE_WAS_OPENED;
2495 return NT_STATUS_OK;
2500 * This next line is a subtlety we need for
2501 * MS-Access. If a file open will fail due to share
2502 * permissions and also for security (access) reasons,
2503 * we need to return the access failed error, not the
2504 * share error. We can't open the file due to kernel
2505 * oplock deadlock (it's possible we failed above on
2506 * the open_mode_check()) so use a userspace check.
2509 if (flags & O_RDWR) {
2510 can_access_mask = FILE_READ_DATA|FILE_WRITE_DATA;
2511 } else if (flags & O_WRONLY) {
2512 can_access_mask = FILE_WRITE_DATA;
2513 } else {
2514 can_access_mask = FILE_READ_DATA;
2517 if (((can_access_mask & FILE_WRITE_DATA) &&
2518 !CAN_WRITE(conn)) ||
2519 !NT_STATUS_IS_OK(smbd_check_access_rights(conn,
2520 smb_fname,
2521 false,
2522 can_access_mask))) {
2523 can_access = False;
2527 * If we're returning a share violation, ensure we
2528 * cope with the braindead 1 second delay.
2531 if (!(oplock_request & INTERNAL_OPEN_ONLY) &&
2532 lp_defer_sharing_violations()) {
2533 struct timeval timeout;
2534 struct deferred_open_record state;
2535 int timeout_usecs;
2537 /* this is a hack to speed up torture tests
2538 in 'make test' */
2539 timeout_usecs = lp_parm_int(SNUM(conn),
2540 "smbd","sharedelay",
2541 SHARING_VIOLATION_USEC_WAIT);
2543 /* This is a relative time, added to the absolute
2544 request_time value to get the absolute timeout time.
2545 Note that if this is the second or greater time we enter
2546 this codepath for this particular request mid then
2547 request_time is left as the absolute time of the *first*
2548 time this request mid was processed. This is what allows
2549 the request to eventually time out. */
2551 timeout = timeval_set(0, timeout_usecs);
2553 /* Nothing actually uses state.delayed_for_oplocks
2554 but it's handy to differentiate in debug messages
2555 between a 30 second delay due to oplock break, and
2556 a 1 second delay for share mode conflicts. */
2558 state.delayed_for_oplocks = False;
2559 state.async_open = false;
2560 state.id = id;
2562 if ((req != NULL)
2563 && !request_timed_out(request_time,
2564 timeout)) {
2565 defer_open(lck, request_time, timeout,
2566 req, &state);
2570 TALLOC_FREE(lck);
2571 fd_close(fsp);
2572 if (can_access) {
2574 * We have detected a sharing violation here
2575 * so return the correct error code
2577 status = NT_STATUS_SHARING_VIOLATION;
2578 } else {
2579 status = NT_STATUS_ACCESS_DENIED;
2581 return status;
2584 grant_fsp_oplock_type(fsp,
2585 oplock_request,
2586 got_level2_oplock,
2587 got_a_none_oplock);
2590 * We have the share entry *locked*.....
2593 /* Delete streams if create_disposition requires it */
2594 if (!new_file_created && clear_ads(create_disposition) &&
2595 !is_ntfs_stream_smb_fname(smb_fname)) {
2596 status = delete_all_streams(conn, smb_fname->base_name);
2597 if (!NT_STATUS_IS_OK(status)) {
2598 TALLOC_FREE(lck);
2599 fd_close(fsp);
2600 return status;
2604 /* note that we ignore failure for the following. It is
2605 basically a hack for NFS, and NFS will never set one of
2606 these only read them. Nobody but Samba can ever set a deny
2607 mode and we have already checked our more authoritative
2608 locking database for permission to set this deny mode. If
2609 the kernel refuses the operations then the kernel is wrong.
2610 note that GPFS supports it as well - jmcd */
2612 if (fsp->fh->fd != -1 && lp_kernel_share_modes(SNUM(conn))) {
2613 int ret_flock;
2614 ret_flock = SMB_VFS_KERNEL_FLOCK(fsp, share_access, access_mask);
2615 if(ret_flock == -1 ){
2617 TALLOC_FREE(lck);
2618 fd_close(fsp);
2620 return NT_STATUS_SHARING_VIOLATION;
2625 * At this point onwards, we can guarantee that the share entry
2626 * is locked, whether we created the file or not, and that the
2627 * deny mode is compatible with all current opens.
2631 * According to Samba4, SEC_FILE_READ_ATTRIBUTE is always granted,
2632 * but we don't have to store this - just ignore it on access check.
2634 if (conn->sconn->using_smb2) {
2636 * SMB2 doesn't return it (according to Microsoft tests).
2637 * Test Case: TestSuite_ScenarioNo009GrantedAccessTestS0
2638 * File created with access = 0x7 (Read, Write, Delete)
2639 * Query Info on file returns 0x87 (Read, Write, Delete, Read Attributes)
2641 fsp->access_mask = access_mask;
2642 } else {
2643 /* But SMB1 does. */
2644 fsp->access_mask = access_mask | FILE_READ_ATTRIBUTES;
2647 if (file_existed) {
2648 /* stat opens on existing files don't get oplocks. */
2649 if (is_stat_open(open_access_mask)) {
2650 fsp->oplock_type = NO_OPLOCK;
2654 if (new_file_created) {
2655 info = FILE_WAS_CREATED;
2656 } else {
2657 if (flags2 & O_TRUNC) {
2658 info = FILE_WAS_OVERWRITTEN;
2659 } else {
2660 info = FILE_WAS_OPENED;
2664 if (pinfo) {
2665 *pinfo = info;
2669 * Setup the oplock info in both the shared memory and
2670 * file structs.
2673 status = set_file_oplock(fsp, fsp->oplock_type);
2674 if (!NT_STATUS_IS_OK(status)) {
2676 * Could not get the kernel oplock or there are byte-range
2677 * locks on the file.
2679 fsp->oplock_type = NO_OPLOCK;
2682 set_share_mode(lck, fsp, get_current_uid(conn),
2683 req ? req->mid : 0,
2684 fsp->oplock_type);
2686 /* Handle strange delete on close create semantics. */
2687 if (create_options & FILE_DELETE_ON_CLOSE) {
2689 status = can_set_delete_on_close(fsp, new_dos_attributes);
2691 if (!NT_STATUS_IS_OK(status)) {
2692 /* Remember to delete the mode we just added. */
2693 del_share_mode(lck, fsp);
2694 TALLOC_FREE(lck);
2695 fd_close(fsp);
2696 return status;
2698 /* Note that here we set the *inital* delete on close flag,
2699 not the regular one. The magic gets handled in close. */
2700 fsp->initial_delete_on_close = True;
2703 if (info != FILE_WAS_OPENED) {
2704 /* Files should be initially set as archive */
2705 if (lp_map_archive(SNUM(conn)) ||
2706 lp_store_dos_attributes(SNUM(conn))) {
2707 if (!posix_open) {
2708 if (file_set_dosmode(conn, smb_fname,
2709 new_dos_attributes | FILE_ATTRIBUTE_ARCHIVE,
2710 parent_dir, true) == 0) {
2711 unx_mode = smb_fname->st.st_ex_mode;
2717 /* Determine sparse flag. */
2718 if (posix_open) {
2719 /* POSIX opens are sparse by default. */
2720 fsp->is_sparse = true;
2721 } else {
2722 fsp->is_sparse = (file_existed &&
2723 (existing_dos_attributes & FILE_ATTRIBUTE_SPARSE));
2727 * Take care of inherited ACLs on created files - if default ACL not
2728 * selected.
2731 if (!posix_open && new_file_created && !def_acl) {
2733 int saved_errno = errno; /* We might get ENOSYS in the next
2734 * call.. */
2736 if (SMB_VFS_FCHMOD_ACL(fsp, unx_mode) == -1 &&
2737 errno == ENOSYS) {
2738 errno = saved_errno; /* Ignore ENOSYS */
2741 } else if (new_unx_mode) {
2743 int ret = -1;
2745 /* Attributes need changing. File already existed. */
2748 int saved_errno = errno; /* We might get ENOSYS in the
2749 * next call.. */
2750 ret = SMB_VFS_FCHMOD_ACL(fsp, new_unx_mode);
2752 if (ret == -1 && errno == ENOSYS) {
2753 errno = saved_errno; /* Ignore ENOSYS */
2754 } else {
2755 DEBUG(5, ("open_file_ntcreate: reset "
2756 "attributes of file %s to 0%o\n",
2757 smb_fname_str_dbg(smb_fname),
2758 (unsigned int)new_unx_mode));
2759 ret = 0; /* Don't do the fchmod below. */
2763 if ((ret == -1) &&
2764 (SMB_VFS_FCHMOD(fsp, new_unx_mode) == -1))
2765 DEBUG(5, ("open_file_ntcreate: failed to reset "
2766 "attributes of file %s to 0%o\n",
2767 smb_fname_str_dbg(smb_fname),
2768 (unsigned int)new_unx_mode));
2771 /* If this is a successful open, we must remove any deferred open
2772 * records. */
2773 if (req != NULL) {
2774 del_deferred_open_entry(lck, req->mid,
2775 messaging_server_id(req->sconn->msg_ctx));
2777 TALLOC_FREE(lck);
2779 return NT_STATUS_OK;
2783 /****************************************************************************
2784 Open a file for for write to ensure that we can fchmod it.
2785 ****************************************************************************/
2787 NTSTATUS open_file_fchmod(connection_struct *conn,
2788 struct smb_filename *smb_fname,
2789 files_struct **result)
2791 if (!VALID_STAT(smb_fname->st)) {
2792 return NT_STATUS_INVALID_PARAMETER;
2795 return SMB_VFS_CREATE_FILE(
2796 conn, /* conn */
2797 NULL, /* req */
2798 0, /* root_dir_fid */
2799 smb_fname, /* fname */
2800 FILE_WRITE_DATA, /* access_mask */
2801 (FILE_SHARE_READ | FILE_SHARE_WRITE | /* share_access */
2802 FILE_SHARE_DELETE),
2803 FILE_OPEN, /* create_disposition*/
2804 0, /* create_options */
2805 0, /* file_attributes */
2806 INTERNAL_OPEN_ONLY, /* oplock_request */
2807 0, /* allocation_size */
2808 0, /* private_flags */
2809 NULL, /* sd */
2810 NULL, /* ea_list */
2811 result, /* result */
2812 NULL); /* pinfo */
2815 static NTSTATUS mkdir_internal(connection_struct *conn,
2816 struct smb_filename *smb_dname,
2817 uint32 file_attributes)
2819 mode_t mode;
2820 char *parent_dir = NULL;
2821 NTSTATUS status;
2822 bool posix_open = false;
2823 bool need_re_stat = false;
2824 uint32_t access_mask = SEC_DIR_ADD_SUBDIR;
2826 if (!CAN_WRITE(conn) || (access_mask & ~(conn->share_access))) {
2827 DEBUG(5,("mkdir_internal: failing share access "
2828 "%s\n", lp_servicename(talloc_tos(), SNUM(conn))));
2829 return NT_STATUS_ACCESS_DENIED;
2832 if (!parent_dirname(talloc_tos(), smb_dname->base_name, &parent_dir,
2833 NULL)) {
2834 return NT_STATUS_NO_MEMORY;
2837 if (file_attributes & FILE_FLAG_POSIX_SEMANTICS) {
2838 posix_open = true;
2839 mode = (mode_t)(file_attributes & ~FILE_FLAG_POSIX_SEMANTICS);
2840 } else {
2841 mode = unix_mode(conn, FILE_ATTRIBUTE_DIRECTORY, smb_dname, parent_dir);
2844 status = check_parent_access(conn,
2845 smb_dname,
2846 access_mask);
2847 if(!NT_STATUS_IS_OK(status)) {
2848 DEBUG(5,("mkdir_internal: check_parent_access "
2849 "on directory %s for path %s returned %s\n",
2850 parent_dir,
2851 smb_dname->base_name,
2852 nt_errstr(status) ));
2853 return status;
2856 if (SMB_VFS_MKDIR(conn, smb_dname->base_name, mode) != 0) {
2857 return map_nt_error_from_unix(errno);
2860 /* Ensure we're checking for a symlink here.... */
2861 /* We don't want to get caught by a symlink racer. */
2863 if (SMB_VFS_LSTAT(conn, smb_dname) == -1) {
2864 DEBUG(2, ("Could not stat directory '%s' just created: %s\n",
2865 smb_fname_str_dbg(smb_dname), strerror(errno)));
2866 return map_nt_error_from_unix(errno);
2869 if (!S_ISDIR(smb_dname->st.st_ex_mode)) {
2870 DEBUG(0, ("Directory '%s' just created is not a directory !\n",
2871 smb_fname_str_dbg(smb_dname)));
2872 return NT_STATUS_NOT_A_DIRECTORY;
2875 if (lp_store_dos_attributes(SNUM(conn))) {
2876 if (!posix_open) {
2877 file_set_dosmode(conn, smb_dname,
2878 file_attributes | FILE_ATTRIBUTE_DIRECTORY,
2879 parent_dir, true);
2883 if (lp_inherit_perms(SNUM(conn))) {
2884 inherit_access_posix_acl(conn, parent_dir,
2885 smb_dname->base_name, mode);
2886 need_re_stat = true;
2889 if (!posix_open) {
2891 * Check if high bits should have been set,
2892 * then (if bits are missing): add them.
2893 * Consider bits automagically set by UNIX, i.e. SGID bit from parent
2894 * dir.
2896 if ((mode & ~(S_IRWXU|S_IRWXG|S_IRWXO)) &&
2897 (mode & ~smb_dname->st.st_ex_mode)) {
2898 SMB_VFS_CHMOD(conn, smb_dname->base_name,
2899 (smb_dname->st.st_ex_mode |
2900 (mode & ~smb_dname->st.st_ex_mode)));
2901 need_re_stat = true;
2905 /* Change the owner if required. */
2906 if (lp_inherit_owner(SNUM(conn))) {
2907 change_dir_owner_to_parent(conn, parent_dir,
2908 smb_dname->base_name,
2909 &smb_dname->st);
2910 need_re_stat = true;
2913 if (need_re_stat) {
2914 if (SMB_VFS_LSTAT(conn, smb_dname) == -1) {
2915 DEBUG(2, ("Could not stat directory '%s' just created: %s\n",
2916 smb_fname_str_dbg(smb_dname), strerror(errno)));
2917 return map_nt_error_from_unix(errno);
2921 notify_fname(conn, NOTIFY_ACTION_ADDED, FILE_NOTIFY_CHANGE_DIR_NAME,
2922 smb_dname->base_name);
2924 return NT_STATUS_OK;
2927 /****************************************************************************
2928 Open a directory from an NT SMB call.
2929 ****************************************************************************/
2931 static NTSTATUS open_directory(connection_struct *conn,
2932 struct smb_request *req,
2933 struct smb_filename *smb_dname,
2934 uint32 access_mask,
2935 uint32 share_access,
2936 uint32 create_disposition,
2937 uint32 create_options,
2938 uint32 file_attributes,
2939 int *pinfo,
2940 files_struct **result)
2942 files_struct *fsp = NULL;
2943 bool dir_existed = VALID_STAT(smb_dname->st) ? True : False;
2944 struct share_mode_lock *lck = NULL;
2945 NTSTATUS status;
2946 struct timespec mtimespec;
2947 int info = 0;
2949 if (is_ntfs_stream_smb_fname(smb_dname)) {
2950 DEBUG(2, ("open_directory: %s is a stream name!\n",
2951 smb_fname_str_dbg(smb_dname)));
2952 return NT_STATUS_NOT_A_DIRECTORY;
2955 if (!(file_attributes & FILE_FLAG_POSIX_SEMANTICS)) {
2956 /* Ensure we have a directory attribute. */
2957 file_attributes |= FILE_ATTRIBUTE_DIRECTORY;
2960 DEBUG(5,("open_directory: opening directory %s, access_mask = 0x%x, "
2961 "share_access = 0x%x create_options = 0x%x, "
2962 "create_disposition = 0x%x, file_attributes = 0x%x\n",
2963 smb_fname_str_dbg(smb_dname),
2964 (unsigned int)access_mask,
2965 (unsigned int)share_access,
2966 (unsigned int)create_options,
2967 (unsigned int)create_disposition,
2968 (unsigned int)file_attributes));
2970 status = smbd_calculate_access_mask(conn, smb_dname, false,
2971 access_mask, &access_mask);
2972 if (!NT_STATUS_IS_OK(status)) {
2973 DEBUG(10, ("open_directory: smbd_calculate_access_mask "
2974 "on file %s returned %s\n",
2975 smb_fname_str_dbg(smb_dname),
2976 nt_errstr(status)));
2977 return status;
2980 if ((access_mask & SEC_FLAG_SYSTEM_SECURITY) &&
2981 !security_token_has_privilege(get_current_nttok(conn),
2982 SEC_PRIV_SECURITY)) {
2983 DEBUG(10, ("open_directory: open on %s "
2984 "failed - SEC_FLAG_SYSTEM_SECURITY denied.\n",
2985 smb_fname_str_dbg(smb_dname)));
2986 return NT_STATUS_PRIVILEGE_NOT_HELD;
2989 switch( create_disposition ) {
2990 case FILE_OPEN:
2992 if (!dir_existed) {
2993 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
2996 info = FILE_WAS_OPENED;
2997 break;
2999 case FILE_CREATE:
3001 /* If directory exists error. If directory doesn't
3002 * exist create. */
3004 if (dir_existed) {
3005 status = NT_STATUS_OBJECT_NAME_COLLISION;
3006 DEBUG(2, ("open_directory: unable to create "
3007 "%s. Error was %s\n",
3008 smb_fname_str_dbg(smb_dname),
3009 nt_errstr(status)));
3010 return status;
3013 status = mkdir_internal(conn, smb_dname,
3014 file_attributes);
3016 if (!NT_STATUS_IS_OK(status)) {
3017 DEBUG(2, ("open_directory: unable to create "
3018 "%s. Error was %s\n",
3019 smb_fname_str_dbg(smb_dname),
3020 nt_errstr(status)));
3021 return status;
3024 info = FILE_WAS_CREATED;
3025 break;
3027 case FILE_OPEN_IF:
3029 * If directory exists open. If directory doesn't
3030 * exist create.
3033 if (dir_existed) {
3034 status = NT_STATUS_OK;
3035 info = FILE_WAS_OPENED;
3036 } else {
3037 status = mkdir_internal(conn, smb_dname,
3038 file_attributes);
3040 if (NT_STATUS_IS_OK(status)) {
3041 info = FILE_WAS_CREATED;
3042 } else {
3043 /* Cope with create race. */
3044 if (!NT_STATUS_EQUAL(status,
3045 NT_STATUS_OBJECT_NAME_COLLISION)) {
3046 DEBUG(2, ("open_directory: unable to create "
3047 "%s. Error was %s\n",
3048 smb_fname_str_dbg(smb_dname),
3049 nt_errstr(status)));
3050 return status;
3052 info = FILE_WAS_OPENED;
3056 break;
3058 case FILE_SUPERSEDE:
3059 case FILE_OVERWRITE:
3060 case FILE_OVERWRITE_IF:
3061 default:
3062 DEBUG(5,("open_directory: invalid create_disposition "
3063 "0x%x for directory %s\n",
3064 (unsigned int)create_disposition,
3065 smb_fname_str_dbg(smb_dname)));
3066 return NT_STATUS_INVALID_PARAMETER;
3069 if(!S_ISDIR(smb_dname->st.st_ex_mode)) {
3070 DEBUG(5,("open_directory: %s is not a directory !\n",
3071 smb_fname_str_dbg(smb_dname)));
3072 return NT_STATUS_NOT_A_DIRECTORY;
3075 if (info == FILE_WAS_OPENED) {
3076 status = smbd_check_access_rights(conn,
3077 smb_dname,
3078 false,
3079 access_mask);
3080 if (!NT_STATUS_IS_OK(status)) {
3081 DEBUG(10, ("open_directory: smbd_check_access_rights on "
3082 "file %s failed with %s\n",
3083 smb_fname_str_dbg(smb_dname),
3084 nt_errstr(status)));
3085 return status;
3089 status = file_new(req, conn, &fsp);
3090 if(!NT_STATUS_IS_OK(status)) {
3091 return status;
3095 * Setup the files_struct for it.
3098 fsp->file_id = vfs_file_id_from_sbuf(conn, &smb_dname->st);
3099 fsp->vuid = req ? req->vuid : UID_FIELD_INVALID;
3100 fsp->file_pid = req ? req->smbpid : 0;
3101 fsp->can_lock = False;
3102 fsp->can_read = False;
3103 fsp->can_write = False;
3105 fsp->share_access = share_access;
3106 fsp->fh->private_options = 0;
3108 * According to Samba4, SEC_FILE_READ_ATTRIBUTE is always granted,
3110 fsp->access_mask = access_mask | FILE_READ_ATTRIBUTES;
3111 fsp->print_file = NULL;
3112 fsp->modified = False;
3113 fsp->oplock_type = NO_OPLOCK;
3114 fsp->sent_oplock_break = NO_BREAK_SENT;
3115 fsp->is_directory = True;
3116 fsp->posix_open = (file_attributes & FILE_FLAG_POSIX_SEMANTICS) ? True : False;
3117 status = fsp_set_smb_fname(fsp, smb_dname);
3118 if (!NT_STATUS_IS_OK(status)) {
3119 file_free(req, fsp);
3120 return status;
3123 mtimespec = smb_dname->st.st_ex_mtime;
3125 #ifdef O_DIRECTORY
3126 status = fd_open(conn, fsp, O_RDONLY|O_DIRECTORY, 0);
3127 #else
3128 /* POSIX allows us to open a directory with O_RDONLY. */
3129 status = fd_open(conn, fsp, O_RDONLY, 0);
3130 #endif
3131 if (!NT_STATUS_IS_OK(status)) {
3132 DEBUG(5, ("open_directory: Could not open fd for "
3133 "%s (%s)\n",
3134 smb_fname_str_dbg(smb_dname),
3135 nt_errstr(status)));
3136 file_free(req, fsp);
3137 return status;
3140 status = vfs_stat_fsp(fsp);
3141 if (!NT_STATUS_IS_OK(status)) {
3142 fd_close(fsp);
3143 file_free(req, fsp);
3144 return status;
3147 /* Ensure there was no race condition. */
3148 if (!check_same_stat(&smb_dname->st, &fsp->fsp_name->st)) {
3149 DEBUG(5,("open_directory: stat struct differs for "
3150 "directory %s.\n",
3151 smb_fname_str_dbg(smb_dname)));
3152 fd_close(fsp);
3153 file_free(req, fsp);
3154 return NT_STATUS_ACCESS_DENIED;
3157 lck = get_share_mode_lock(talloc_tos(), fsp->file_id,
3158 conn->connectpath, smb_dname,
3159 &mtimespec);
3161 if (lck == NULL) {
3162 DEBUG(0, ("open_directory: Could not get share mode lock for "
3163 "%s\n", smb_fname_str_dbg(smb_dname)));
3164 fd_close(fsp);
3165 file_free(req, fsp);
3166 return NT_STATUS_SHARING_VIOLATION;
3169 status = open_mode_check(conn, lck, fsp->name_hash,
3170 access_mask, share_access,
3171 create_options, &dir_existed);
3173 if (!NT_STATUS_IS_OK(status)) {
3174 TALLOC_FREE(lck);
3175 fd_close(fsp);
3176 file_free(req, fsp);
3177 return status;
3180 set_share_mode(lck, fsp, get_current_uid(conn),
3181 req ? req->mid : 0, NO_OPLOCK);
3183 /* For directories the delete on close bit at open time seems
3184 always to be honored on close... See test 19 in Samba4 BASE-DELETE. */
3185 if (create_options & FILE_DELETE_ON_CLOSE) {
3186 status = can_set_delete_on_close(fsp, 0);
3187 if (!NT_STATUS_IS_OK(status) && !NT_STATUS_EQUAL(status, NT_STATUS_DIRECTORY_NOT_EMPTY)) {
3188 TALLOC_FREE(lck);
3189 fd_close(fsp);
3190 file_free(req, fsp);
3191 return status;
3194 if (NT_STATUS_IS_OK(status)) {
3195 /* Note that here we set the *inital* delete on close flag,
3196 not the regular one. The magic gets handled in close. */
3197 fsp->initial_delete_on_close = True;
3201 TALLOC_FREE(lck);
3203 if (pinfo) {
3204 *pinfo = info;
3207 *result = fsp;
3208 return NT_STATUS_OK;
3211 NTSTATUS create_directory(connection_struct *conn, struct smb_request *req,
3212 struct smb_filename *smb_dname)
3214 NTSTATUS status;
3215 files_struct *fsp;
3217 status = SMB_VFS_CREATE_FILE(
3218 conn, /* conn */
3219 req, /* req */
3220 0, /* root_dir_fid */
3221 smb_dname, /* fname */
3222 FILE_READ_ATTRIBUTES, /* access_mask */
3223 FILE_SHARE_NONE, /* share_access */
3224 FILE_CREATE, /* create_disposition*/
3225 FILE_DIRECTORY_FILE, /* create_options */
3226 FILE_ATTRIBUTE_DIRECTORY, /* file_attributes */
3227 0, /* oplock_request */
3228 0, /* allocation_size */
3229 0, /* private_flags */
3230 NULL, /* sd */
3231 NULL, /* ea_list */
3232 &fsp, /* result */
3233 NULL); /* pinfo */
3235 if (NT_STATUS_IS_OK(status)) {
3236 close_file(req, fsp, NORMAL_CLOSE);
3239 return status;
3242 /****************************************************************************
3243 Receive notification that one of our open files has been renamed by another
3244 smbd process.
3245 ****************************************************************************/
3247 void msg_file_was_renamed(struct messaging_context *msg,
3248 void *private_data,
3249 uint32_t msg_type,
3250 struct server_id server_id,
3251 DATA_BLOB *data)
3253 files_struct *fsp;
3254 char *frm = (char *)data->data;
3255 struct file_id id;
3256 const char *sharepath;
3257 const char *base_name;
3258 const char *stream_name;
3259 struct smb_filename *smb_fname = NULL;
3260 size_t sp_len, bn_len;
3261 NTSTATUS status;
3262 struct smbd_server_connection *sconn =
3263 talloc_get_type_abort(private_data,
3264 struct smbd_server_connection);
3266 if (data->data == NULL
3267 || data->length < MSG_FILE_RENAMED_MIN_SIZE + 2) {
3268 DEBUG(0, ("msg_file_was_renamed: Got invalid msg len %d\n",
3269 (int)data->length));
3270 return;
3273 /* Unpack the message. */
3274 pull_file_id_24(frm, &id);
3275 sharepath = &frm[24];
3276 sp_len = strlen(sharepath);
3277 base_name = sharepath + sp_len + 1;
3278 bn_len = strlen(base_name);
3279 stream_name = sharepath + sp_len + 1 + bn_len + 1;
3281 /* stream_name must always be NULL if there is no stream. */
3282 if (stream_name[0] == '\0') {
3283 stream_name = NULL;
3286 status = create_synthetic_smb_fname(talloc_tos(), base_name,
3287 stream_name, NULL, &smb_fname);
3288 if (!NT_STATUS_IS_OK(status)) {
3289 return;
3292 DEBUG(10,("msg_file_was_renamed: Got rename message for sharepath %s, new name %s, "
3293 "file_id %s\n",
3294 sharepath, smb_fname_str_dbg(smb_fname),
3295 file_id_string_tos(&id)));
3297 for(fsp = file_find_di_first(sconn, id); fsp;
3298 fsp = file_find_di_next(fsp)) {
3299 if (memcmp(fsp->conn->connectpath, sharepath, sp_len) == 0) {
3301 DEBUG(10,("msg_file_was_renamed: renaming file %s from %s -> %s\n",
3302 fsp_fnum_dbg(fsp), fsp_str_dbg(fsp),
3303 smb_fname_str_dbg(smb_fname)));
3304 status = fsp_set_smb_fname(fsp, smb_fname);
3305 if (!NT_STATUS_IS_OK(status)) {
3306 goto out;
3308 } else {
3309 /* TODO. JRA. */
3310 /* Now we have the complete path we can work out if this is
3311 actually within this share and adjust newname accordingly. */
3312 DEBUG(10,("msg_file_was_renamed: share mismatch (sharepath %s "
3313 "not sharepath %s) "
3314 "%s from %s -> %s\n",
3315 fsp->conn->connectpath,
3316 sharepath,
3317 fsp_fnum_dbg(fsp),
3318 fsp_str_dbg(fsp),
3319 smb_fname_str_dbg(smb_fname)));
3322 out:
3323 TALLOC_FREE(smb_fname);
3324 return;
3328 * If a main file is opened for delete, all streams need to be checked for
3329 * !FILE_SHARE_DELETE. Do this by opening with DELETE_ACCESS.
3330 * If that works, delete them all by setting the delete on close and close.
3333 NTSTATUS open_streams_for_delete(connection_struct *conn,
3334 const char *fname)
3336 struct stream_struct *stream_info = NULL;
3337 files_struct **streams = NULL;
3338 int i;
3339 unsigned int num_streams = 0;
3340 TALLOC_CTX *frame = talloc_stackframe();
3341 NTSTATUS status;
3343 status = vfs_streaminfo(conn, NULL, fname, talloc_tos(),
3344 &num_streams, &stream_info);
3346 if (NT_STATUS_EQUAL(status, NT_STATUS_NOT_IMPLEMENTED)
3347 || NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
3348 DEBUG(10, ("no streams around\n"));
3349 TALLOC_FREE(frame);
3350 return NT_STATUS_OK;
3353 if (!NT_STATUS_IS_OK(status)) {
3354 DEBUG(10, ("vfs_streaminfo failed: %s\n",
3355 nt_errstr(status)));
3356 goto fail;
3359 DEBUG(10, ("open_streams_for_delete found %d streams\n",
3360 num_streams));
3362 if (num_streams == 0) {
3363 TALLOC_FREE(frame);
3364 return NT_STATUS_OK;
3367 streams = talloc_array(talloc_tos(), files_struct *, num_streams);
3368 if (streams == NULL) {
3369 DEBUG(0, ("talloc failed\n"));
3370 status = NT_STATUS_NO_MEMORY;
3371 goto fail;
3374 for (i=0; i<num_streams; i++) {
3375 struct smb_filename *smb_fname = NULL;
3377 if (strequal(stream_info[i].name, "::$DATA")) {
3378 streams[i] = NULL;
3379 continue;
3382 status = create_synthetic_smb_fname(talloc_tos(), fname,
3383 stream_info[i].name,
3384 NULL, &smb_fname);
3385 if (!NT_STATUS_IS_OK(status)) {
3386 goto fail;
3389 if (SMB_VFS_STAT(conn, smb_fname) == -1) {
3390 DEBUG(10, ("Unable to stat stream: %s\n",
3391 smb_fname_str_dbg(smb_fname)));
3394 status = SMB_VFS_CREATE_FILE(
3395 conn, /* conn */
3396 NULL, /* req */
3397 0, /* root_dir_fid */
3398 smb_fname, /* fname */
3399 DELETE_ACCESS, /* access_mask */
3400 (FILE_SHARE_READ | /* share_access */
3401 FILE_SHARE_WRITE | FILE_SHARE_DELETE),
3402 FILE_OPEN, /* create_disposition*/
3403 0, /* create_options */
3404 FILE_ATTRIBUTE_NORMAL, /* file_attributes */
3405 0, /* oplock_request */
3406 0, /* allocation_size */
3407 NTCREATEX_OPTIONS_PRIVATE_STREAM_DELETE, /* private_flags */
3408 NULL, /* sd */
3409 NULL, /* ea_list */
3410 &streams[i], /* result */
3411 NULL); /* pinfo */
3413 if (!NT_STATUS_IS_OK(status)) {
3414 DEBUG(10, ("Could not open stream %s: %s\n",
3415 smb_fname_str_dbg(smb_fname),
3416 nt_errstr(status)));
3418 TALLOC_FREE(smb_fname);
3419 break;
3421 TALLOC_FREE(smb_fname);
3425 * don't touch the variable "status" beyond this point :-)
3428 for (i -= 1 ; i >= 0; i--) {
3429 if (streams[i] == NULL) {
3430 continue;
3433 DEBUG(10, ("Closing stream # %d, %s\n", i,
3434 fsp_str_dbg(streams[i])));
3435 close_file(NULL, streams[i], NORMAL_CLOSE);
3438 fail:
3439 TALLOC_FREE(frame);
3440 return status;
3443 /*********************************************************************
3444 Create a default ACL by inheriting from the parent. If no inheritance
3445 from the parent available, don't set anything. This will leave the actual
3446 permissions the new file or directory already got from the filesystem
3447 as the NT ACL when read.
3448 *********************************************************************/
3450 static NTSTATUS inherit_new_acl(files_struct *fsp)
3452 TALLOC_CTX *frame = talloc_stackframe();
3453 char *parent_name = NULL;
3454 struct security_descriptor *parent_desc = NULL;
3455 NTSTATUS status = NT_STATUS_OK;
3456 struct security_descriptor *psd = NULL;
3457 const struct dom_sid *owner_sid = NULL;
3458 const struct dom_sid *group_sid = NULL;
3459 uint32_t security_info_sent = (SECINFO_OWNER | SECINFO_GROUP | SECINFO_DACL);
3460 struct security_token *token = fsp->conn->session_info->security_token;
3461 bool inherit_owner = lp_inherit_owner(SNUM(fsp->conn));
3462 bool inheritable_components = false;
3463 bool try_builtin_administrators = false;
3464 const struct dom_sid *BA_U_sid = NULL;
3465 size_t size = 0;
3467 if (!parent_dirname(frame, fsp->fsp_name->base_name, &parent_name, NULL)) {
3468 TALLOC_FREE(frame);
3469 return NT_STATUS_NO_MEMORY;
3472 status = SMB_VFS_GET_NT_ACL(fsp->conn,
3473 parent_name,
3474 (SECINFO_OWNER | SECINFO_GROUP | SECINFO_DACL),
3475 frame,
3476 &parent_desc);
3477 if (!NT_STATUS_IS_OK(status)) {
3478 TALLOC_FREE(frame);
3479 return status;
3482 inheritable_components = sd_has_inheritable_components(parent_desc,
3483 fsp->is_directory);
3485 if (!inheritable_components && !inherit_owner) {
3486 TALLOC_FREE(frame);
3487 /* Nothing to inherit and not setting owner. */
3488 return NT_STATUS_OK;
3491 /* Create an inherited descriptor from the parent. */
3493 if (DEBUGLEVEL >= 10) {
3494 DEBUG(10,("inherit_new_acl: parent acl for %s is:\n",
3495 fsp_str_dbg(fsp) ));
3496 NDR_PRINT_DEBUG(security_descriptor, parent_desc);
3499 /* Inherit from parent descriptor if "inherit owner" set. */
3500 if (inherit_owner) {
3501 owner_sid = parent_desc->owner_sid;
3502 group_sid = parent_desc->group_sid;
3505 if (owner_sid == NULL) {
3506 if (security_token_has_builtin_administrators(token)) {
3507 try_builtin_administrators = true;
3508 } else if (security_token_is_system(token)) {
3509 try_builtin_administrators = true;
3513 if (try_builtin_administrators) {
3514 struct unixid ids;
3515 bool ok;
3517 ZERO_STRUCT(ids);
3518 ok = sids_to_unixids(&global_sid_Builtin_Administrators, 1, &ids);
3519 if (ok) {
3520 switch (ids.type) {
3521 case ID_TYPE_BOTH:
3522 BA_U_sid = &global_sid_Builtin_Administrators;
3523 break;
3524 case ID_TYPE_UID:
3525 BA_U_sid = &global_sid_Builtin_Administrators;
3526 break;
3527 default:
3528 break;
3533 if (owner_sid == NULL) {
3534 owner_sid = BA_U_sid;
3537 if (owner_sid == NULL) {
3538 owner_sid = &token->sids[PRIMARY_USER_SID_INDEX];
3540 if (group_sid == NULL) {
3541 group_sid = &token->sids[PRIMARY_GROUP_SID_INDEX];
3544 status = se_create_child_secdesc(frame,
3545 &psd,
3546 &size,
3547 parent_desc,
3548 owner_sid,
3549 group_sid,
3550 fsp->is_directory);
3551 if (!NT_STATUS_IS_OK(status)) {
3552 TALLOC_FREE(frame);
3553 return status;
3556 /* If inheritable_components == false,
3557 se_create_child_secdesc()
3558 creates a security desriptor with a NULL dacl
3559 entry, but with SEC_DESC_DACL_PRESENT. We need
3560 to remove that flag. */
3562 if (!inheritable_components) {
3563 security_info_sent &= ~SECINFO_DACL;
3564 psd->type &= ~SEC_DESC_DACL_PRESENT;
3567 if (DEBUGLEVEL >= 10) {
3568 DEBUG(10,("inherit_new_acl: child acl for %s is:\n",
3569 fsp_str_dbg(fsp) ));
3570 NDR_PRINT_DEBUG(security_descriptor, psd);
3573 if (inherit_owner) {
3574 /* We need to be root to force this. */
3575 become_root();
3577 status = SMB_VFS_FSET_NT_ACL(fsp,
3578 security_info_sent,
3579 psd);
3580 if (inherit_owner) {
3581 unbecome_root();
3583 TALLOC_FREE(frame);
3584 return status;
3588 * Wrapper around open_file_ntcreate and open_directory
3591 static NTSTATUS create_file_unixpath(connection_struct *conn,
3592 struct smb_request *req,
3593 struct smb_filename *smb_fname,
3594 uint32_t access_mask,
3595 uint32_t share_access,
3596 uint32_t create_disposition,
3597 uint32_t create_options,
3598 uint32_t file_attributes,
3599 uint32_t oplock_request,
3600 uint64_t allocation_size,
3601 uint32_t private_flags,
3602 struct security_descriptor *sd,
3603 struct ea_list *ea_list,
3605 files_struct **result,
3606 int *pinfo)
3608 int info = FILE_WAS_OPENED;
3609 files_struct *base_fsp = NULL;
3610 files_struct *fsp = NULL;
3611 NTSTATUS status;
3613 DEBUG(10,("create_file_unixpath: access_mask = 0x%x "
3614 "file_attributes = 0x%x, share_access = 0x%x, "
3615 "create_disposition = 0x%x create_options = 0x%x "
3616 "oplock_request = 0x%x private_flags = 0x%x "
3617 "ea_list = 0x%p, sd = 0x%p, "
3618 "fname = %s\n",
3619 (unsigned int)access_mask,
3620 (unsigned int)file_attributes,
3621 (unsigned int)share_access,
3622 (unsigned int)create_disposition,
3623 (unsigned int)create_options,
3624 (unsigned int)oplock_request,
3625 (unsigned int)private_flags,
3626 ea_list, sd, smb_fname_str_dbg(smb_fname)));
3628 if (create_options & FILE_OPEN_BY_FILE_ID) {
3629 status = NT_STATUS_NOT_SUPPORTED;
3630 goto fail;
3633 if (create_options & NTCREATEX_OPTIONS_INVALID_PARAM_MASK) {
3634 status = NT_STATUS_INVALID_PARAMETER;
3635 goto fail;
3638 if (req == NULL) {
3639 oplock_request |= INTERNAL_OPEN_ONLY;
3642 if ((conn->fs_capabilities & FILE_NAMED_STREAMS)
3643 && (access_mask & DELETE_ACCESS)
3644 && !is_ntfs_stream_smb_fname(smb_fname)) {
3646 * We can't open a file with DELETE access if any of the
3647 * streams is open without FILE_SHARE_DELETE
3649 status = open_streams_for_delete(conn, smb_fname->base_name);
3651 if (!NT_STATUS_IS_OK(status)) {
3652 goto fail;
3656 if ((access_mask & SEC_FLAG_SYSTEM_SECURITY) &&
3657 !security_token_has_privilege(get_current_nttok(conn),
3658 SEC_PRIV_SECURITY)) {
3659 DEBUG(10, ("create_file_unixpath: open on %s "
3660 "failed - SEC_FLAG_SYSTEM_SECURITY denied.\n",
3661 smb_fname_str_dbg(smb_fname)));
3662 status = NT_STATUS_PRIVILEGE_NOT_HELD;
3663 goto fail;
3666 if ((conn->fs_capabilities & FILE_NAMED_STREAMS)
3667 && is_ntfs_stream_smb_fname(smb_fname)
3668 && (!(private_flags & NTCREATEX_OPTIONS_PRIVATE_STREAM_DELETE))) {
3669 uint32 base_create_disposition;
3670 struct smb_filename *smb_fname_base = NULL;
3672 if (create_options & FILE_DIRECTORY_FILE) {
3673 status = NT_STATUS_NOT_A_DIRECTORY;
3674 goto fail;
3677 switch (create_disposition) {
3678 case FILE_OPEN:
3679 base_create_disposition = FILE_OPEN;
3680 break;
3681 default:
3682 base_create_disposition = FILE_OPEN_IF;
3683 break;
3686 /* Create an smb_filename with stream_name == NULL. */
3687 status = create_synthetic_smb_fname(talloc_tos(),
3688 smb_fname->base_name,
3689 NULL, NULL,
3690 &smb_fname_base);
3691 if (!NT_STATUS_IS_OK(status)) {
3692 goto fail;
3695 if (SMB_VFS_STAT(conn, smb_fname_base) == -1) {
3696 DEBUG(10, ("Unable to stat stream: %s\n",
3697 smb_fname_str_dbg(smb_fname_base)));
3700 /* Open the base file. */
3701 status = create_file_unixpath(conn, NULL, smb_fname_base, 0,
3702 FILE_SHARE_READ
3703 | FILE_SHARE_WRITE
3704 | FILE_SHARE_DELETE,
3705 base_create_disposition,
3706 0, 0, 0, 0, 0, NULL, NULL,
3707 &base_fsp, NULL);
3708 TALLOC_FREE(smb_fname_base);
3710 if (!NT_STATUS_IS_OK(status)) {
3711 DEBUG(10, ("create_file_unixpath for base %s failed: "
3712 "%s\n", smb_fname->base_name,
3713 nt_errstr(status)));
3714 goto fail;
3716 /* we don't need to low level fd */
3717 fd_close(base_fsp);
3721 * If it's a request for a directory open, deal with it separately.
3724 if (create_options & FILE_DIRECTORY_FILE) {
3726 if (create_options & FILE_NON_DIRECTORY_FILE) {
3727 status = NT_STATUS_INVALID_PARAMETER;
3728 goto fail;
3731 /* Can't open a temp directory. IFS kit test. */
3732 if (!(file_attributes & FILE_FLAG_POSIX_SEMANTICS) &&
3733 (file_attributes & FILE_ATTRIBUTE_TEMPORARY)) {
3734 status = NT_STATUS_INVALID_PARAMETER;
3735 goto fail;
3739 * We will get a create directory here if the Win32
3740 * app specified a security descriptor in the
3741 * CreateDirectory() call.
3744 oplock_request = 0;
3745 status = open_directory(
3746 conn, req, smb_fname, access_mask, share_access,
3747 create_disposition, create_options, file_attributes,
3748 &info, &fsp);
3749 } else {
3752 * Ordinary file case.
3755 status = file_new(req, conn, &fsp);
3756 if(!NT_STATUS_IS_OK(status)) {
3757 goto fail;
3760 status = fsp_set_smb_fname(fsp, smb_fname);
3761 if (!NT_STATUS_IS_OK(status)) {
3762 goto fail;
3765 if (base_fsp) {
3767 * We're opening the stream element of a
3768 * base_fsp we already opened. Set up the
3769 * base_fsp pointer.
3771 fsp->base_fsp = base_fsp;
3774 if (allocation_size) {
3775 fsp->initial_allocation_size = smb_roundup(fsp->conn,
3776 allocation_size);
3779 status = open_file_ntcreate(conn,
3780 req,
3781 access_mask,
3782 share_access,
3783 create_disposition,
3784 create_options,
3785 file_attributes,
3786 oplock_request,
3787 private_flags,
3788 &info,
3789 fsp);
3791 if(!NT_STATUS_IS_OK(status)) {
3792 file_free(req, fsp);
3793 fsp = NULL;
3796 if (NT_STATUS_EQUAL(status, NT_STATUS_FILE_IS_A_DIRECTORY)) {
3798 /* A stream open never opens a directory */
3800 if (base_fsp) {
3801 status = NT_STATUS_FILE_IS_A_DIRECTORY;
3802 goto fail;
3806 * Fail the open if it was explicitly a non-directory
3807 * file.
3810 if (create_options & FILE_NON_DIRECTORY_FILE) {
3811 status = NT_STATUS_FILE_IS_A_DIRECTORY;
3812 goto fail;
3815 oplock_request = 0;
3816 status = open_directory(
3817 conn, req, smb_fname, access_mask,
3818 share_access, create_disposition,
3819 create_options, file_attributes,
3820 &info, &fsp);
3824 if (!NT_STATUS_IS_OK(status)) {
3825 goto fail;
3828 fsp->base_fsp = base_fsp;
3830 if ((ea_list != NULL) &&
3831 ((info == FILE_WAS_CREATED) || (info == FILE_WAS_OVERWRITTEN))) {
3832 status = set_ea(conn, fsp, fsp->fsp_name, ea_list);
3833 if (!NT_STATUS_IS_OK(status)) {
3834 goto fail;
3838 if (!fsp->is_directory && S_ISDIR(fsp->fsp_name->st.st_ex_mode)) {
3839 status = NT_STATUS_ACCESS_DENIED;
3840 goto fail;
3843 /* Save the requested allocation size. */
3844 if ((info == FILE_WAS_CREATED) || (info == FILE_WAS_OVERWRITTEN)) {
3845 if (allocation_size
3846 && (allocation_size > fsp->fsp_name->st.st_ex_size)) {
3847 fsp->initial_allocation_size = smb_roundup(
3848 fsp->conn, allocation_size);
3849 if (fsp->is_directory) {
3850 /* Can't set allocation size on a directory. */
3851 status = NT_STATUS_ACCESS_DENIED;
3852 goto fail;
3854 if (vfs_allocate_file_space(
3855 fsp, fsp->initial_allocation_size) == -1) {
3856 status = NT_STATUS_DISK_FULL;
3857 goto fail;
3859 } else {
3860 fsp->initial_allocation_size = smb_roundup(
3861 fsp->conn, (uint64_t)fsp->fsp_name->st.st_ex_size);
3863 } else {
3864 fsp->initial_allocation_size = 0;
3867 if ((info == FILE_WAS_CREATED) && lp_nt_acl_support(SNUM(conn)) &&
3868 fsp->base_fsp == NULL) {
3869 if (sd != NULL) {
3871 * According to the MS documentation, the only time the security
3872 * descriptor is applied to the opened file is iff we *created* the
3873 * file; an existing file stays the same.
3875 * Also, it seems (from observation) that you can open the file with
3876 * any access mask but you can still write the sd. We need to override
3877 * the granted access before we call set_sd
3878 * Patch for bug #2242 from Tom Lackemann <cessnatomny@yahoo.com>.
3881 uint32_t sec_info_sent;
3882 uint32_t saved_access_mask = fsp->access_mask;
3884 sec_info_sent = get_sec_info(sd);
3886 fsp->access_mask = FILE_GENERIC_ALL;
3888 if (sec_info_sent & (SECINFO_OWNER|
3889 SECINFO_GROUP|
3890 SECINFO_DACL|
3891 SECINFO_SACL)) {
3892 status = set_sd(fsp, sd, sec_info_sent);
3895 fsp->access_mask = saved_access_mask;
3897 if (!NT_STATUS_IS_OK(status)) {
3898 goto fail;
3900 } else if (lp_inherit_acls(SNUM(conn))) {
3901 /* Inherit from parent. Errors here are not fatal. */
3902 status = inherit_new_acl(fsp);
3903 if (!NT_STATUS_IS_OK(status)) {
3904 DEBUG(10,("inherit_new_acl: failed for %s with %s\n",
3905 fsp_str_dbg(fsp),
3906 nt_errstr(status) ));
3911 DEBUG(10, ("create_file_unixpath: info=%d\n", info));
3913 *result = fsp;
3914 if (pinfo != NULL) {
3915 *pinfo = info;
3918 smb_fname->st = fsp->fsp_name->st;
3920 return NT_STATUS_OK;
3922 fail:
3923 DEBUG(10, ("create_file_unixpath: %s\n", nt_errstr(status)));
3925 if (fsp != NULL) {
3926 if (base_fsp && fsp->base_fsp == base_fsp) {
3928 * The close_file below will close
3929 * fsp->base_fsp.
3931 base_fsp = NULL;
3933 close_file(req, fsp, ERROR_CLOSE);
3934 fsp = NULL;
3936 if (base_fsp != NULL) {
3937 close_file(req, base_fsp, ERROR_CLOSE);
3938 base_fsp = NULL;
3940 return status;
3944 * Calculate the full path name given a relative fid.
3946 NTSTATUS get_relative_fid_filename(connection_struct *conn,
3947 struct smb_request *req,
3948 uint16_t root_dir_fid,
3949 const struct smb_filename *smb_fname,
3950 struct smb_filename **smb_fname_out)
3952 files_struct *dir_fsp;
3953 char *parent_fname = NULL;
3954 char *new_base_name = NULL;
3955 NTSTATUS status;
3957 if (root_dir_fid == 0 || !smb_fname) {
3958 status = NT_STATUS_INTERNAL_ERROR;
3959 goto out;
3962 dir_fsp = file_fsp(req, root_dir_fid);
3964 if (dir_fsp == NULL) {
3965 status = NT_STATUS_INVALID_HANDLE;
3966 goto out;
3969 if (is_ntfs_stream_smb_fname(dir_fsp->fsp_name)) {
3970 status = NT_STATUS_INVALID_HANDLE;
3971 goto out;
3974 if (!dir_fsp->is_directory) {
3977 * Check to see if this is a mac fork of some kind.
3980 if ((conn->fs_capabilities & FILE_NAMED_STREAMS) &&
3981 is_ntfs_stream_smb_fname(smb_fname)) {
3982 status = NT_STATUS_OBJECT_PATH_NOT_FOUND;
3983 goto out;
3987 we need to handle the case when we get a
3988 relative open relative to a file and the
3989 pathname is blank - this is a reopen!
3990 (hint from demyn plantenberg)
3993 status = NT_STATUS_INVALID_HANDLE;
3994 goto out;
3997 if (ISDOT(dir_fsp->fsp_name->base_name)) {
3999 * We're at the toplevel dir, the final file name
4000 * must not contain ./, as this is filtered out
4001 * normally by srvstr_get_path and unix_convert
4002 * explicitly rejects paths containing ./.
4004 parent_fname = talloc_strdup(talloc_tos(), "");
4005 if (parent_fname == NULL) {
4006 status = NT_STATUS_NO_MEMORY;
4007 goto out;
4009 } else {
4010 size_t dir_name_len = strlen(dir_fsp->fsp_name->base_name);
4013 * Copy in the base directory name.
4016 parent_fname = talloc_array(talloc_tos(), char,
4017 dir_name_len+2);
4018 if (parent_fname == NULL) {
4019 status = NT_STATUS_NO_MEMORY;
4020 goto out;
4022 memcpy(parent_fname, dir_fsp->fsp_name->base_name,
4023 dir_name_len+1);
4026 * Ensure it ends in a '/'.
4027 * We used TALLOC_SIZE +2 to add space for the '/'.
4030 if(dir_name_len
4031 && (parent_fname[dir_name_len-1] != '\\')
4032 && (parent_fname[dir_name_len-1] != '/')) {
4033 parent_fname[dir_name_len] = '/';
4034 parent_fname[dir_name_len+1] = '\0';
4038 new_base_name = talloc_asprintf(talloc_tos(), "%s%s", parent_fname,
4039 smb_fname->base_name);
4040 if (new_base_name == NULL) {
4041 status = NT_STATUS_NO_MEMORY;
4042 goto out;
4045 status = filename_convert(req,
4046 conn,
4047 req->flags2 & FLAGS2_DFS_PATHNAMES,
4048 new_base_name,
4050 NULL,
4051 smb_fname_out);
4052 if (!NT_STATUS_IS_OK(status)) {
4053 goto out;
4056 out:
4057 TALLOC_FREE(parent_fname);
4058 TALLOC_FREE(new_base_name);
4059 return status;
4062 NTSTATUS create_file_default(connection_struct *conn,
4063 struct smb_request *req,
4064 uint16_t root_dir_fid,
4065 struct smb_filename *smb_fname,
4066 uint32_t access_mask,
4067 uint32_t share_access,
4068 uint32_t create_disposition,
4069 uint32_t create_options,
4070 uint32_t file_attributes,
4071 uint32_t oplock_request,
4072 uint64_t allocation_size,
4073 uint32_t private_flags,
4074 struct security_descriptor *sd,
4075 struct ea_list *ea_list,
4076 files_struct **result,
4077 int *pinfo)
4079 int info = FILE_WAS_OPENED;
4080 files_struct *fsp = NULL;
4081 NTSTATUS status;
4082 bool stream_name = false;
4084 DEBUG(10,("create_file: access_mask = 0x%x "
4085 "file_attributes = 0x%x, share_access = 0x%x, "
4086 "create_disposition = 0x%x create_options = 0x%x "
4087 "oplock_request = 0x%x "
4088 "private_flags = 0x%x "
4089 "root_dir_fid = 0x%x, ea_list = 0x%p, sd = 0x%p, "
4090 "fname = %s\n",
4091 (unsigned int)access_mask,
4092 (unsigned int)file_attributes,
4093 (unsigned int)share_access,
4094 (unsigned int)create_disposition,
4095 (unsigned int)create_options,
4096 (unsigned int)oplock_request,
4097 (unsigned int)private_flags,
4098 (unsigned int)root_dir_fid,
4099 ea_list, sd, smb_fname_str_dbg(smb_fname)));
4102 * Calculate the filename from the root_dir_if if necessary.
4105 if (root_dir_fid != 0) {
4106 struct smb_filename *smb_fname_out = NULL;
4107 status = get_relative_fid_filename(conn, req, root_dir_fid,
4108 smb_fname, &smb_fname_out);
4109 if (!NT_STATUS_IS_OK(status)) {
4110 goto fail;
4112 smb_fname = smb_fname_out;
4116 * Check to see if this is a mac fork of some kind.
4119 stream_name = is_ntfs_stream_smb_fname(smb_fname);
4120 if (stream_name) {
4121 enum FAKE_FILE_TYPE fake_file_type;
4123 fake_file_type = is_fake_file(smb_fname);
4125 if (fake_file_type != FAKE_FILE_TYPE_NONE) {
4128 * Here we go! support for changing the disk quotas
4129 * --metze
4131 * We need to fake up to open this MAGIC QUOTA file
4132 * and return a valid FID.
4134 * w2k close this file directly after openening xp
4135 * also tries a QUERY_FILE_INFO on the file and then
4136 * close it
4138 status = open_fake_file(req, conn, req->vuid,
4139 fake_file_type, smb_fname,
4140 access_mask, &fsp);
4141 if (!NT_STATUS_IS_OK(status)) {
4142 goto fail;
4145 ZERO_STRUCT(smb_fname->st);
4146 goto done;
4149 if (!(conn->fs_capabilities & FILE_NAMED_STREAMS)) {
4150 status = NT_STATUS_OBJECT_NAME_NOT_FOUND;
4151 goto fail;
4155 if (is_ntfs_default_stream_smb_fname(smb_fname)) {
4156 int ret;
4157 smb_fname->stream_name = NULL;
4158 /* We have to handle this error here. */
4159 if (create_options & FILE_DIRECTORY_FILE) {
4160 status = NT_STATUS_NOT_A_DIRECTORY;
4161 goto fail;
4163 if (lp_posix_pathnames()) {
4164 ret = SMB_VFS_LSTAT(conn, smb_fname);
4165 } else {
4166 ret = SMB_VFS_STAT(conn, smb_fname);
4169 if (ret == 0 && VALID_STAT_OF_DIR(smb_fname->st)) {
4170 status = NT_STATUS_FILE_IS_A_DIRECTORY;
4171 goto fail;
4175 status = create_file_unixpath(
4176 conn, req, smb_fname, access_mask, share_access,
4177 create_disposition, create_options, file_attributes,
4178 oplock_request, allocation_size, private_flags,
4179 sd, ea_list,
4180 &fsp, &info);
4182 if (!NT_STATUS_IS_OK(status)) {
4183 goto fail;
4186 done:
4187 DEBUG(10, ("create_file: info=%d\n", info));
4189 *result = fsp;
4190 if (pinfo != NULL) {
4191 *pinfo = info;
4193 return NT_STATUS_OK;
4195 fail:
4196 DEBUG(10, ("create_file: %s\n", nt_errstr(status)));
4198 if (fsp != NULL) {
4199 close_file(req, fsp, ERROR_CLOSE);
4200 fsp = NULL;
4202 return status;