docs: man ndrdump: Add missing meta data.
[Samba/gebeck_regimport.git] / source3 / smbd / open.c
blobd736f4f795bb05d935afff6060f326e9e7c5761d
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 "auth.h"
32 #include "serverid.h"
33 #include "messages.h"
35 extern const struct generic_mapping file_generic_mapping;
37 struct deferred_open_record {
38 bool delayed_for_oplocks;
39 bool async_open;
40 struct file_id id;
43 /****************************************************************************
44 If the requester wanted DELETE_ACCESS and was rejected because
45 the file ACL didn't include DELETE_ACCESS, see if the parent ACL
46 overrides this.
47 ****************************************************************************/
49 static bool parent_override_delete(connection_struct *conn,
50 const struct smb_filename *smb_fname,
51 uint32_t access_mask,
52 uint32_t rejected_mask)
54 if ((access_mask & DELETE_ACCESS) &&
55 (rejected_mask & DELETE_ACCESS) &&
56 can_delete_file_in_directory(conn, smb_fname)) {
57 return true;
59 return false;
62 /****************************************************************************
63 Check if we have open rights.
64 ****************************************************************************/
66 NTSTATUS smbd_check_access_rights(struct connection_struct *conn,
67 const struct smb_filename *smb_fname,
68 bool use_privs,
69 uint32_t access_mask)
71 /* Check if we have rights to open. */
72 NTSTATUS status;
73 struct security_descriptor *sd = NULL;
74 uint32_t rejected_share_access;
75 uint32_t rejected_mask = access_mask;
77 rejected_share_access = access_mask & ~(conn->share_access);
79 if (rejected_share_access) {
80 DEBUG(10, ("smbd_check_access_rights: rejected share access 0x%x "
81 "on %s (0x%x)\n",
82 (unsigned int)access_mask,
83 smb_fname_str_dbg(smb_fname),
84 (unsigned int)rejected_share_access ));
85 return NT_STATUS_ACCESS_DENIED;
88 if (!use_privs && get_current_uid(conn) == (uid_t)0) {
89 /* I'm sorry sir, I didn't know you were root... */
90 DEBUG(10,("smbd_check_access_rights: root override "
91 "on %s. Granting 0x%x\n",
92 smb_fname_str_dbg(smb_fname),
93 (unsigned int)access_mask ));
94 return NT_STATUS_OK;
97 if ((access_mask & DELETE_ACCESS) && !lp_acl_check_permissions(SNUM(conn))) {
98 DEBUG(10,("smbd_check_access_rights: not checking ACL "
99 "on DELETE_ACCESS on file %s. Granting 0x%x\n",
100 smb_fname_str_dbg(smb_fname),
101 (unsigned int)access_mask ));
102 return NT_STATUS_OK;
105 if (access_mask == DELETE_ACCESS &&
106 VALID_STAT(smb_fname->st) &&
107 S_ISLNK(smb_fname->st.st_ex_mode)) {
108 /* We can always delete a symlink. */
109 DEBUG(10,("smbd_check_access_rights: not checking ACL "
110 "on DELETE_ACCESS on symlink %s.\n",
111 smb_fname_str_dbg(smb_fname) ));
112 return NT_STATUS_OK;
115 status = SMB_VFS_GET_NT_ACL(conn, smb_fname->base_name,
116 (SECINFO_OWNER |
117 SECINFO_GROUP |
118 SECINFO_DACL), talloc_tos(), &sd);
120 if (!NT_STATUS_IS_OK(status)) {
121 DEBUG(10, ("smbd_check_access_rights: Could not get acl "
122 "on %s: %s\n",
123 smb_fname_str_dbg(smb_fname),
124 nt_errstr(status)));
126 if (NT_STATUS_EQUAL(status, NT_STATUS_ACCESS_DENIED)) {
127 goto access_denied;
130 return status;
134 * If we can access the path to this file, by
135 * default we have FILE_READ_ATTRIBUTES from the
136 * containing directory. See the section:
137 * "Algorithm to Check Access to an Existing File"
138 * in MS-FSA.pdf.
140 * se_file_access_check() also takes care of
141 * owner WRITE_DAC and READ_CONTROL.
143 status = se_file_access_check(sd,
144 get_current_nttok(conn),
145 use_privs,
146 (access_mask & ~FILE_READ_ATTRIBUTES),
147 &rejected_mask);
149 DEBUG(10,("smbd_check_access_rights: file %s requesting "
150 "0x%x returning 0x%x (%s)\n",
151 smb_fname_str_dbg(smb_fname),
152 (unsigned int)access_mask,
153 (unsigned int)rejected_mask,
154 nt_errstr(status) ));
156 if (!NT_STATUS_IS_OK(status)) {
157 if (DEBUGLEVEL >= 10) {
158 DEBUG(10,("smbd_check_access_rights: acl for %s is:\n",
159 smb_fname_str_dbg(smb_fname) ));
160 NDR_PRINT_DEBUG(security_descriptor, sd);
164 TALLOC_FREE(sd);
166 if (NT_STATUS_IS_OK(status) ||
167 !NT_STATUS_EQUAL(status, NT_STATUS_ACCESS_DENIED)) {
168 return status;
171 /* Here we know status == NT_STATUS_ACCESS_DENIED. */
173 access_denied:
175 if ((access_mask & FILE_WRITE_ATTRIBUTES) &&
176 (rejected_mask & FILE_WRITE_ATTRIBUTES) &&
177 !lp_store_dos_attributes(SNUM(conn)) &&
178 (lp_map_readonly(SNUM(conn)) ||
179 lp_map_archive(SNUM(conn)) ||
180 lp_map_hidden(SNUM(conn)) ||
181 lp_map_system(SNUM(conn)))) {
182 rejected_mask &= ~FILE_WRITE_ATTRIBUTES;
184 DEBUG(10,("smbd_check_access_rights: "
185 "overrode "
186 "FILE_WRITE_ATTRIBUTES "
187 "on file %s\n",
188 smb_fname_str_dbg(smb_fname)));
191 if (parent_override_delete(conn,
192 smb_fname,
193 access_mask,
194 rejected_mask)) {
195 /* Were we trying to do an open
196 * for delete and didn't get DELETE
197 * access (only) ? Check if the
198 * directory allows DELETE_CHILD.
199 * See here:
200 * http://blogs.msdn.com/oldnewthing/archive/2004/06/04/148426.aspx
201 * for details. */
203 rejected_mask &= ~DELETE_ACCESS;
205 DEBUG(10,("smbd_check_access_rights: "
206 "overrode "
207 "DELETE_ACCESS on "
208 "file %s\n",
209 smb_fname_str_dbg(smb_fname)));
212 if (rejected_mask != 0) {
213 return NT_STATUS_ACCESS_DENIED;
215 return NT_STATUS_OK;
218 static NTSTATUS check_parent_access(struct connection_struct *conn,
219 struct smb_filename *smb_fname,
220 uint32_t access_mask)
222 NTSTATUS status;
223 char *parent_dir = NULL;
224 struct security_descriptor *parent_sd = NULL;
225 uint32_t access_granted = 0;
227 if (!parent_dirname(talloc_tos(),
228 smb_fname->base_name,
229 &parent_dir,
230 NULL)) {
231 return NT_STATUS_NO_MEMORY;
234 if (get_current_uid(conn) == (uid_t)0) {
235 /* I'm sorry sir, I didn't know you were root... */
236 DEBUG(10,("check_parent_access: root override "
237 "on %s. Granting 0x%x\n",
238 smb_fname_str_dbg(smb_fname),
239 (unsigned int)access_mask ));
240 return NT_STATUS_OK;
243 status = SMB_VFS_GET_NT_ACL(conn,
244 parent_dir,
245 SECINFO_DACL,
246 talloc_tos(),
247 &parent_sd);
249 if (!NT_STATUS_IS_OK(status)) {
250 DEBUG(5,("check_parent_access: SMB_VFS_GET_NT_ACL failed for "
251 "%s with error %s\n",
252 parent_dir,
253 nt_errstr(status)));
254 return status;
258 * If we can access the path to this file, by
259 * default we have FILE_READ_ATTRIBUTES from the
260 * containing directory. See the section:
261 * "Algorithm to Check Access to an Existing File"
262 * in MS-FSA.pdf.
264 * se_file_access_check() also takes care of
265 * owner WRITE_DAC and READ_CONTROL.
267 status = se_file_access_check(parent_sd,
268 get_current_nttok(conn),
269 false,
270 (access_mask & ~FILE_READ_ATTRIBUTES),
271 &access_granted);
272 if(!NT_STATUS_IS_OK(status)) {
273 DEBUG(5,("check_parent_access: access check "
274 "on directory %s for "
275 "path %s for mask 0x%x returned (0x%x) %s\n",
276 parent_dir,
277 smb_fname->base_name,
278 access_mask,
279 access_granted,
280 nt_errstr(status) ));
281 return status;
284 return NT_STATUS_OK;
287 /****************************************************************************
288 fd support routines - attempt to do a dos_open.
289 ****************************************************************************/
291 NTSTATUS fd_open(struct connection_struct *conn,
292 files_struct *fsp,
293 int flags,
294 mode_t mode)
296 struct smb_filename *smb_fname = fsp->fsp_name;
297 NTSTATUS status = NT_STATUS_OK;
299 #ifdef O_NOFOLLOW
301 * Never follow symlinks on a POSIX client. The
302 * client should be doing this.
305 if (fsp->posix_open || !lp_symlinks(SNUM(conn))) {
306 flags |= O_NOFOLLOW;
308 #endif
310 fsp->fh->fd = SMB_VFS_OPEN(conn, smb_fname, fsp, flags, mode);
311 if (fsp->fh->fd == -1) {
312 int posix_errno = errno;
313 #ifdef O_NOFOLLOW
314 #if defined(ENOTSUP) && defined(OSF1)
315 /* handle special Tru64 errno */
316 if (errno == ENOTSUP) {
317 posix_errno = ELOOP;
319 #endif /* ENOTSUP */
320 #ifdef EFTYPE
321 /* fix broken NetBSD errno */
322 if (errno == EFTYPE) {
323 posix_errno = ELOOP;
325 #endif /* EFTYPE */
326 /* fix broken FreeBSD errno */
327 if (errno == EMLINK) {
328 posix_errno = ELOOP;
330 #endif /* O_NOFOLLOW */
331 status = map_nt_error_from_unix(posix_errno);
332 if (errno == EMFILE) {
333 static time_t last_warned = 0L;
335 if (time((time_t *) NULL) > last_warned) {
336 DEBUG(0,("Too many open files, unable "
337 "to open more! smbd's max "
338 "open files = %d\n",
339 lp_max_open_files()));
340 last_warned = time((time_t *) NULL);
346 DEBUG(10,("fd_open: name %s, flags = 0%o mode = 0%o, fd = %d. %s\n",
347 smb_fname_str_dbg(smb_fname), flags, (int)mode, fsp->fh->fd,
348 (fsp->fh->fd == -1) ? strerror(errno) : "" ));
350 return status;
353 /****************************************************************************
354 Close the file associated with a fsp.
355 ****************************************************************************/
357 NTSTATUS fd_close(files_struct *fsp)
359 int ret;
361 if (fsp->dptr) {
362 dptr_CloseDir(fsp);
364 if (fsp->fh->fd == -1) {
365 return NT_STATUS_OK; /* What we used to call a stat open. */
367 if (fsp->fh->ref_count > 1) {
368 return NT_STATUS_OK; /* Shared handle. Only close last reference. */
371 ret = SMB_VFS_CLOSE(fsp);
372 fsp->fh->fd = -1;
373 if (ret == -1) {
374 return map_nt_error_from_unix(errno);
376 return NT_STATUS_OK;
379 /****************************************************************************
380 Change the ownership of a file to that of the parent directory.
381 Do this by fd if possible.
382 ****************************************************************************/
384 void change_file_owner_to_parent(connection_struct *conn,
385 const char *inherit_from_dir,
386 files_struct *fsp)
388 struct smb_filename *smb_fname_parent = NULL;
389 NTSTATUS status;
390 int ret;
392 status = create_synthetic_smb_fname(talloc_tos(), inherit_from_dir,
393 NULL, NULL, &smb_fname_parent);
394 if (!NT_STATUS_IS_OK(status)) {
395 return;
398 ret = SMB_VFS_STAT(conn, smb_fname_parent);
399 if (ret == -1) {
400 DEBUG(0,("change_file_owner_to_parent: failed to stat parent "
401 "directory %s. Error was %s\n",
402 smb_fname_str_dbg(smb_fname_parent),
403 strerror(errno)));
404 TALLOC_FREE(smb_fname_parent);
405 return;
408 if (smb_fname_parent->st.st_ex_uid == fsp->fsp_name->st.st_ex_uid) {
409 /* Already this uid - no need to change. */
410 DEBUG(10,("change_file_owner_to_parent: file %s "
411 "is already owned by uid %d\n",
412 fsp_str_dbg(fsp),
413 (int)fsp->fsp_name->st.st_ex_uid ));
414 TALLOC_FREE(smb_fname_parent);
415 return;
418 become_root();
419 ret = SMB_VFS_FCHOWN(fsp, smb_fname_parent->st.st_ex_uid, (gid_t)-1);
420 unbecome_root();
421 if (ret == -1) {
422 DEBUG(0,("change_file_owner_to_parent: failed to fchown "
423 "file %s to parent directory uid %u. Error "
424 "was %s\n", fsp_str_dbg(fsp),
425 (unsigned int)smb_fname_parent->st.st_ex_uid,
426 strerror(errno) ));
427 } else {
428 DEBUG(10,("change_file_owner_to_parent: changed new file %s to "
429 "parent directory uid %u.\n", fsp_str_dbg(fsp),
430 (unsigned int)smb_fname_parent->st.st_ex_uid));
431 /* Ensure the uid entry is updated. */
432 fsp->fsp_name->st.st_ex_uid = smb_fname_parent->st.st_ex_uid;
435 TALLOC_FREE(smb_fname_parent);
438 NTSTATUS change_dir_owner_to_parent(connection_struct *conn,
439 const char *inherit_from_dir,
440 const char *fname,
441 SMB_STRUCT_STAT *psbuf)
443 struct smb_filename *smb_fname_parent = NULL;
444 struct smb_filename *smb_fname_cwd = NULL;
445 char *saved_dir = NULL;
446 TALLOC_CTX *ctx = talloc_tos();
447 NTSTATUS status = NT_STATUS_OK;
448 int ret;
450 status = create_synthetic_smb_fname(ctx, inherit_from_dir, NULL, NULL,
451 &smb_fname_parent);
452 if (!NT_STATUS_IS_OK(status)) {
453 return status;
456 ret = SMB_VFS_STAT(conn, smb_fname_parent);
457 if (ret == -1) {
458 status = map_nt_error_from_unix(errno);
459 DEBUG(0,("change_dir_owner_to_parent: failed to stat parent "
460 "directory %s. Error was %s\n",
461 smb_fname_str_dbg(smb_fname_parent),
462 strerror(errno)));
463 goto out;
466 /* We've already done an lstat into psbuf, and we know it's a
467 directory. If we can cd into the directory and the dev/ino
468 are the same then we can safely chown without races as
469 we're locking the directory in place by being in it. This
470 should work on any UNIX (thanks tridge :-). JRA.
473 saved_dir = vfs_GetWd(ctx,conn);
474 if (!saved_dir) {
475 status = map_nt_error_from_unix(errno);
476 DEBUG(0,("change_dir_owner_to_parent: failed to get "
477 "current working directory. Error was %s\n",
478 strerror(errno)));
479 goto out;
482 /* Chdir into the new path. */
483 if (vfs_ChDir(conn, fname) == -1) {
484 status = map_nt_error_from_unix(errno);
485 DEBUG(0,("change_dir_owner_to_parent: failed to change "
486 "current working directory to %s. Error "
487 "was %s\n", fname, strerror(errno) ));
488 goto chdir;
491 status = create_synthetic_smb_fname(ctx, ".", NULL, NULL,
492 &smb_fname_cwd);
493 if (!NT_STATUS_IS_OK(status)) {
494 return status;
497 ret = SMB_VFS_STAT(conn, smb_fname_cwd);
498 if (ret == -1) {
499 status = map_nt_error_from_unix(errno);
500 DEBUG(0,("change_dir_owner_to_parent: failed to stat "
501 "directory '.' (%s) Error was %s\n",
502 fname, strerror(errno)));
503 goto chdir;
506 /* Ensure we're pointing at the same place. */
507 if (smb_fname_cwd->st.st_ex_dev != psbuf->st_ex_dev ||
508 smb_fname_cwd->st.st_ex_ino != psbuf->st_ex_ino) {
509 DEBUG(0,("change_dir_owner_to_parent: "
510 "device/inode on directory %s changed. "
511 "Refusing to chown !\n", fname ));
512 status = NT_STATUS_ACCESS_DENIED;
513 goto chdir;
516 if (smb_fname_parent->st.st_ex_uid == smb_fname_cwd->st.st_ex_uid) {
517 /* Already this uid - no need to change. */
518 DEBUG(10,("change_dir_owner_to_parent: directory %s "
519 "is already owned by uid %d\n",
520 fname,
521 (int)smb_fname_cwd->st.st_ex_uid ));
522 status = NT_STATUS_OK;
523 goto chdir;
526 become_root();
527 ret = SMB_VFS_LCHOWN(conn, ".", smb_fname_parent->st.st_ex_uid,
528 (gid_t)-1);
529 unbecome_root();
530 if (ret == -1) {
531 status = map_nt_error_from_unix(errno);
532 DEBUG(10,("change_dir_owner_to_parent: failed to chown "
533 "directory %s to parent directory uid %u. "
534 "Error was %s\n", fname,
535 (unsigned int)smb_fname_parent->st.st_ex_uid,
536 strerror(errno) ));
537 } else {
538 DEBUG(10,("change_dir_owner_to_parent: changed ownership of new "
539 "directory %s to parent directory uid %u.\n",
540 fname, (unsigned int)smb_fname_parent->st.st_ex_uid ));
541 /* Ensure the uid entry is updated. */
542 psbuf->st_ex_uid = smb_fname_parent->st.st_ex_uid;
545 chdir:
546 vfs_ChDir(conn,saved_dir);
547 out:
548 TALLOC_FREE(smb_fname_parent);
549 TALLOC_FREE(smb_fname_cwd);
550 return status;
553 /****************************************************************************
554 Open a file - returning a guaranteed ATOMIC indication of if the
555 file was created or not.
556 ****************************************************************************/
558 static NTSTATUS fd_open_atomic(struct connection_struct *conn,
559 files_struct *fsp,
560 int flags,
561 mode_t mode,
562 bool *file_created)
564 NTSTATUS status = NT_STATUS_UNSUCCESSFUL;
565 bool file_existed = VALID_STAT(fsp->fsp_name->st);
567 *file_created = false;
569 if (!(flags & O_CREAT)) {
571 * We're not creating the file, just pass through.
573 return fd_open(conn, fsp, flags, mode);
576 if (flags & O_EXCL) {
578 * Fail if already exists, just pass through.
580 status = fd_open(conn, fsp, flags, mode);
583 * Here we've opened with O_CREAT|O_EXCL. If that went
584 * NT_STATUS_OK, we *know* we created this file.
586 *file_created = NT_STATUS_IS_OK(status);
588 return status;
592 * Now it gets tricky. We have O_CREAT, but not O_EXCL.
593 * To know absolutely if we created the file or not,
594 * we can never call O_CREAT without O_EXCL. So if
595 * we think the file existed, try without O_CREAT|O_EXCL.
596 * If we think the file didn't exist, try with
597 * O_CREAT|O_EXCL. Keep bouncing between these two
598 * requests until either the file is created, or
599 * opened. Either way, we keep going until we get
600 * a returnable result (error, or open/create).
603 while(1) {
604 int curr_flags = flags;
606 if (file_existed) {
607 /* Just try open, do not create. */
608 curr_flags &= ~(O_CREAT);
609 status = fd_open(conn, fsp, curr_flags, mode);
610 if (NT_STATUS_EQUAL(status,
611 NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
613 * Someone deleted it in the meantime.
614 * Retry with O_EXCL.
616 file_existed = false;
617 DEBUG(10,("fd_open_atomic: file %s existed. "
618 "Retry.\n",
619 smb_fname_str_dbg(fsp->fsp_name)));
620 continue;
622 } else {
623 /* Try create exclusively, fail if it exists. */
624 curr_flags |= O_EXCL;
625 status = fd_open(conn, fsp, curr_flags, mode);
626 if (NT_STATUS_EQUAL(status,
627 NT_STATUS_OBJECT_NAME_COLLISION)) {
629 * Someone created it in the meantime.
630 * Retry without O_CREAT.
632 file_existed = true;
633 DEBUG(10,("fd_open_atomic: file %s "
634 "did not exist. Retry.\n",
635 smb_fname_str_dbg(fsp->fsp_name)));
636 continue;
638 if (NT_STATUS_IS_OK(status)) {
640 * Here we've opened with O_CREAT|O_EXCL
641 * and got success. We *know* we created
642 * this file.
644 *file_created = true;
647 /* Create is done, or failed. */
648 break;
650 return status;
653 /****************************************************************************
654 Open a file.
655 ****************************************************************************/
657 static NTSTATUS open_file(files_struct *fsp,
658 connection_struct *conn,
659 struct smb_request *req,
660 const char *parent_dir,
661 int flags,
662 mode_t unx_mode,
663 uint32 access_mask, /* client requested access mask. */
664 uint32 open_access_mask, /* what we're actually using in the open. */
665 bool *p_file_created)
667 struct smb_filename *smb_fname = fsp->fsp_name;
668 NTSTATUS status = NT_STATUS_OK;
669 int accmode = (flags & O_ACCMODE);
670 int local_flags = flags;
671 bool file_existed = VALID_STAT(fsp->fsp_name->st);
673 fsp->fh->fd = -1;
674 errno = EPERM;
676 /* Check permissions */
679 * This code was changed after seeing a client open request
680 * containing the open mode of (DENY_WRITE/read-only) with
681 * the 'create if not exist' bit set. The previous code
682 * would fail to open the file read only on a read-only share
683 * as it was checking the flags parameter directly against O_RDONLY,
684 * this was failing as the flags parameter was set to O_RDONLY|O_CREAT.
685 * JRA.
688 if (!CAN_WRITE(conn)) {
689 /* It's a read-only share - fail if we wanted to write. */
690 if(accmode != O_RDONLY || (flags & O_TRUNC) || (flags & O_APPEND)) {
691 DEBUG(3,("Permission denied opening %s\n",
692 smb_fname_str_dbg(smb_fname)));
693 return NT_STATUS_ACCESS_DENIED;
695 if (flags & O_CREAT) {
696 /* We don't want to write - but we must make sure that
697 O_CREAT doesn't create the file if we have write
698 access into the directory.
700 flags &= ~(O_CREAT|O_EXCL);
701 local_flags &= ~(O_CREAT|O_EXCL);
706 * This little piece of insanity is inspired by the
707 * fact that an NT client can open a file for O_RDONLY,
708 * but set the create disposition to FILE_EXISTS_TRUNCATE.
709 * If the client *can* write to the file, then it expects to
710 * truncate the file, even though it is opening for readonly.
711 * Quicken uses this stupid trick in backup file creation...
712 * Thanks *greatly* to "David W. Chapman Jr." <dwcjr@inethouston.net>
713 * for helping track this one down. It didn't bite us in 2.0.x
714 * as we always opened files read-write in that release. JRA.
717 if ((accmode == O_RDONLY) && ((flags & O_TRUNC) == O_TRUNC)) {
718 DEBUG(10,("open_file: truncate requested on read-only open "
719 "for file %s\n", smb_fname_str_dbg(smb_fname)));
720 local_flags = (flags & ~O_ACCMODE)|O_RDWR;
723 if ((open_access_mask & (FILE_READ_DATA|FILE_WRITE_DATA|FILE_APPEND_DATA|FILE_EXECUTE)) ||
724 (!file_existed && (local_flags & O_CREAT)) ||
725 ((local_flags & O_TRUNC) == O_TRUNC) ) {
726 const char *wild;
727 int ret;
729 #if defined(O_NONBLOCK) && defined(S_ISFIFO)
731 * We would block on opening a FIFO with no one else on the
732 * other end. Do what we used to do and add O_NONBLOCK to the
733 * open flags. JRA.
736 if (file_existed && S_ISFIFO(smb_fname->st.st_ex_mode)) {
737 local_flags &= ~O_TRUNC; /* Can't truncate a FIFO. */
738 local_flags |= O_NONBLOCK;
740 #endif
742 /* Don't create files with Microsoft wildcard characters. */
743 if (fsp->base_fsp) {
745 * wildcard characters are allowed in stream names
746 * only test the basefilename
748 wild = fsp->base_fsp->fsp_name->base_name;
749 } else {
750 wild = smb_fname->base_name;
752 if ((local_flags & O_CREAT) && !file_existed &&
753 ms_has_wild(wild)) {
754 return NT_STATUS_OBJECT_NAME_INVALID;
757 /* Can we access this file ? */
758 if (!fsp->base_fsp) {
759 /* Only do this check on non-stream open. */
760 if (file_existed) {
761 status = smbd_check_access_rights(conn,
762 smb_fname,
763 false,
764 access_mask);
765 } else if (local_flags & O_CREAT){
766 status = check_parent_access(conn,
767 smb_fname,
768 SEC_DIR_ADD_FILE);
769 } else {
770 /* File didn't exist and no O_CREAT. */
771 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
773 if (!NT_STATUS_IS_OK(status)) {
774 DEBUG(10,("open_file: "
775 "%s on file "
776 "%s returned %s\n",
777 file_existed ?
778 "smbd_check_access_rights" :
779 "check_parent_access",
780 smb_fname_str_dbg(smb_fname),
781 nt_errstr(status) ));
782 return status;
786 /* Actually do the open */
787 status = fd_open_atomic(conn, fsp, local_flags,
788 unx_mode, p_file_created);
789 if (!NT_STATUS_IS_OK(status)) {
790 DEBUG(3,("Error opening file %s (%s) (local_flags=%d) "
791 "(flags=%d)\n", smb_fname_str_dbg(smb_fname),
792 nt_errstr(status),local_flags,flags));
793 return status;
796 ret = SMB_VFS_FSTAT(fsp, &smb_fname->st);
797 if (ret == -1) {
798 /* If we have an fd, this stat should succeed. */
799 DEBUG(0,("Error doing fstat on open file %s "
800 "(%s)\n",
801 smb_fname_str_dbg(smb_fname),
802 strerror(errno) ));
803 status = map_nt_error_from_unix(errno);
804 fd_close(fsp);
805 return status;
808 if (*p_file_created) {
809 /* We created this file. */
811 bool need_re_stat = false;
812 /* Do all inheritance work after we've
813 done a successful fstat call and filled
814 in the stat struct in fsp->fsp_name. */
816 /* Inherit the ACL if required */
817 if (lp_inherit_perms(SNUM(conn))) {
818 inherit_access_posix_acl(conn, parent_dir,
819 smb_fname->base_name,
820 unx_mode);
821 need_re_stat = true;
824 /* Change the owner if required. */
825 if (lp_inherit_owner(SNUM(conn))) {
826 change_file_owner_to_parent(conn, parent_dir,
827 fsp);
828 need_re_stat = true;
831 if (need_re_stat) {
832 ret = SMB_VFS_FSTAT(fsp, &smb_fname->st);
833 /* If we have an fd, this stat should succeed. */
834 if (ret == -1) {
835 DEBUG(0,("Error doing fstat on open file %s "
836 "(%s)\n",
837 smb_fname_str_dbg(smb_fname),
838 strerror(errno) ));
842 notify_fname(conn, NOTIFY_ACTION_ADDED,
843 FILE_NOTIFY_CHANGE_FILE_NAME,
844 smb_fname->base_name);
846 } else {
847 fsp->fh->fd = -1; /* What we used to call a stat open. */
848 if (!file_existed) {
849 /* File must exist for a stat open. */
850 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
853 status = smbd_check_access_rights(conn,
854 smb_fname,
855 false,
856 access_mask);
858 if (NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND) &&
859 fsp->posix_open &&
860 S_ISLNK(smb_fname->st.st_ex_mode)) {
861 /* This is a POSIX stat open for delete
862 * or rename on a symlink that points
863 * nowhere. Allow. */
864 DEBUG(10,("open_file: allowing POSIX "
865 "open on bad symlink %s\n",
866 smb_fname_str_dbg(smb_fname)));
867 status = NT_STATUS_OK;
870 if (!NT_STATUS_IS_OK(status)) {
871 DEBUG(10,("open_file: "
872 "smbd_check_access_rights on file "
873 "%s returned %s\n",
874 smb_fname_str_dbg(smb_fname),
875 nt_errstr(status) ));
876 return status;
881 * POSIX allows read-only opens of directories. We don't
882 * want to do this (we use a different code path for this)
883 * so catch a directory open and return an EISDIR. JRA.
886 if(S_ISDIR(smb_fname->st.st_ex_mode)) {
887 fd_close(fsp);
888 errno = EISDIR;
889 return NT_STATUS_FILE_IS_A_DIRECTORY;
892 fsp->file_id = vfs_file_id_from_sbuf(conn, &smb_fname->st);
893 fsp->vuid = req ? req->vuid : UID_FIELD_INVALID;
894 fsp->file_pid = req ? req->smbpid : 0;
895 fsp->can_lock = True;
896 fsp->can_read = ((access_mask & FILE_READ_DATA) != 0);
897 fsp->can_write =
898 CAN_WRITE(conn) &&
899 ((access_mask & (FILE_WRITE_DATA | FILE_APPEND_DATA)) != 0);
900 fsp->print_file = NULL;
901 fsp->modified = False;
902 fsp->sent_oplock_break = NO_BREAK_SENT;
903 fsp->is_directory = False;
904 if (conn->aio_write_behind_list &&
905 is_in_path(smb_fname->base_name, conn->aio_write_behind_list,
906 conn->case_sensitive)) {
907 fsp->aio_write_behind = True;
910 fsp->wcp = NULL; /* Write cache pointer. */
912 DEBUG(2,("%s opened file %s read=%s write=%s (numopen=%d)\n",
913 conn->session_info->unix_info->unix_name,
914 smb_fname_str_dbg(smb_fname),
915 BOOLSTR(fsp->can_read), BOOLSTR(fsp->can_write),
916 conn->num_files_open));
918 errno = 0;
919 return NT_STATUS_OK;
922 /****************************************************************************
923 Check if we can open a file with a share mode.
924 Returns True if conflict, False if not.
925 ****************************************************************************/
927 static bool share_conflict(struct share_mode_entry *entry,
928 uint32 access_mask,
929 uint32 share_access)
931 DEBUG(10,("share_conflict: entry->access_mask = 0x%x, "
932 "entry->share_access = 0x%x, "
933 "entry->private_options = 0x%x\n",
934 (unsigned int)entry->access_mask,
935 (unsigned int)entry->share_access,
936 (unsigned int)entry->private_options));
938 if (server_id_is_disconnected(&entry->pid)) {
940 * note: cleanup should have been done by
941 * delay_for_batch_oplocks()
943 return false;
946 DEBUG(10,("share_conflict: access_mask = 0x%x, share_access = 0x%x\n",
947 (unsigned int)access_mask, (unsigned int)share_access));
949 if ((entry->access_mask & (FILE_WRITE_DATA|
950 FILE_APPEND_DATA|
951 FILE_READ_DATA|
952 FILE_EXECUTE|
953 DELETE_ACCESS)) == 0) {
954 DEBUG(10,("share_conflict: No conflict due to "
955 "entry->access_mask = 0x%x\n",
956 (unsigned int)entry->access_mask ));
957 return False;
960 if ((access_mask & (FILE_WRITE_DATA|
961 FILE_APPEND_DATA|
962 FILE_READ_DATA|
963 FILE_EXECUTE|
964 DELETE_ACCESS)) == 0) {
965 DEBUG(10,("share_conflict: No conflict due to "
966 "access_mask = 0x%x\n",
967 (unsigned int)access_mask ));
968 return False;
971 #if 1 /* JRA TEST - Superdebug. */
972 #define CHECK_MASK(num, am, right, sa, share) \
973 DEBUG(10,("share_conflict: [%d] am (0x%x) & right (0x%x) = 0x%x\n", \
974 (unsigned int)(num), (unsigned int)(am), \
975 (unsigned int)(right), (unsigned int)(am)&(right) )); \
976 DEBUG(10,("share_conflict: [%d] sa (0x%x) & share (0x%x) = 0x%x\n", \
977 (unsigned int)(num), (unsigned int)(sa), \
978 (unsigned int)(share), (unsigned int)(sa)&(share) )); \
979 if (((am) & (right)) && !((sa) & (share))) { \
980 DEBUG(10,("share_conflict: check %d conflict am = 0x%x, right = 0x%x, \
981 sa = 0x%x, share = 0x%x\n", (num), (unsigned int)(am), (unsigned int)(right), (unsigned int)(sa), \
982 (unsigned int)(share) )); \
983 return True; \
985 #else
986 #define CHECK_MASK(num, am, right, sa, share) \
987 if (((am) & (right)) && !((sa) & (share))) { \
988 DEBUG(10,("share_conflict: check %d conflict am = 0x%x, right = 0x%x, \
989 sa = 0x%x, share = 0x%x\n", (num), (unsigned int)(am), (unsigned int)(right), (unsigned int)(sa), \
990 (unsigned int)(share) )); \
991 return True; \
993 #endif
995 CHECK_MASK(1, entry->access_mask, FILE_WRITE_DATA | FILE_APPEND_DATA,
996 share_access, FILE_SHARE_WRITE);
997 CHECK_MASK(2, access_mask, FILE_WRITE_DATA | FILE_APPEND_DATA,
998 entry->share_access, FILE_SHARE_WRITE);
1000 CHECK_MASK(3, entry->access_mask, FILE_READ_DATA | FILE_EXECUTE,
1001 share_access, FILE_SHARE_READ);
1002 CHECK_MASK(4, access_mask, FILE_READ_DATA | FILE_EXECUTE,
1003 entry->share_access, FILE_SHARE_READ);
1005 CHECK_MASK(5, entry->access_mask, DELETE_ACCESS,
1006 share_access, FILE_SHARE_DELETE);
1007 CHECK_MASK(6, access_mask, DELETE_ACCESS,
1008 entry->share_access, FILE_SHARE_DELETE);
1010 DEBUG(10,("share_conflict: No conflict.\n"));
1011 return False;
1014 #if defined(DEVELOPER)
1015 static void validate_my_share_entries(struct smbd_server_connection *sconn,
1016 int num,
1017 struct share_mode_entry *share_entry)
1019 struct server_id self = messaging_server_id(sconn->msg_ctx);
1020 files_struct *fsp;
1022 if (!serverid_equal(&self, &share_entry->pid)) {
1023 return;
1026 if (is_deferred_open_entry(share_entry) &&
1027 !open_was_deferred(sconn, share_entry->op_mid))
1029 char *str = talloc_asprintf(talloc_tos(),
1030 "Got a deferred entry without a request: "
1031 "PANIC: %s\n",
1032 share_mode_str(talloc_tos(), num, share_entry));
1033 smb_panic(str);
1036 if (!is_valid_share_mode_entry(share_entry)) {
1037 return;
1040 fsp = file_find_dif(sconn, share_entry->id,
1041 share_entry->share_file_id);
1042 if (!fsp) {
1043 DEBUG(0,("validate_my_share_entries: PANIC : %s\n",
1044 share_mode_str(talloc_tos(), num, share_entry) ));
1045 smb_panic("validate_my_share_entries: Cannot match a "
1046 "share entry with an open file\n");
1049 if (is_deferred_open_entry(share_entry)) {
1050 goto panic;
1053 if ((share_entry->op_type == NO_OPLOCK) &&
1054 (fsp->oplock_type == FAKE_LEVEL_II_OPLOCK))
1056 /* Someone has already written to it, but I haven't yet
1057 * noticed */
1058 return;
1061 if (((uint16)fsp->oplock_type) != share_entry->op_type) {
1062 goto panic;
1065 return;
1067 panic:
1069 char *str;
1070 DEBUG(0,("validate_my_share_entries: PANIC : %s\n",
1071 share_mode_str(talloc_tos(), num, share_entry) ));
1072 str = talloc_asprintf(talloc_tos(),
1073 "validate_my_share_entries: "
1074 "file %s, oplock_type = 0x%x, op_type = 0x%x\n",
1075 fsp->fsp_name->base_name,
1076 (unsigned int)fsp->oplock_type,
1077 (unsigned int)share_entry->op_type );
1078 smb_panic(str);
1081 #endif
1083 bool is_stat_open(uint32 access_mask)
1085 const uint32_t stat_open_bits =
1086 (SYNCHRONIZE_ACCESS|
1087 FILE_READ_ATTRIBUTES|
1088 FILE_WRITE_ATTRIBUTES);
1090 return (((access_mask & stat_open_bits) != 0) &&
1091 ((access_mask & ~stat_open_bits) == 0));
1094 /****************************************************************************
1095 Deal with share modes
1096 Invarient: Share mode must be locked on entry and exit.
1097 Returns -1 on error, or number of share modes on success (may be zero).
1098 ****************************************************************************/
1100 static NTSTATUS open_mode_check(connection_struct *conn,
1101 struct share_mode_lock *lck,
1102 uint32_t name_hash,
1103 uint32 access_mask,
1104 uint32 share_access,
1105 uint32 create_options,
1106 bool *file_existed)
1108 int i;
1110 if(lck->data->num_share_modes == 0) {
1111 return NT_STATUS_OK;
1114 /* A delete on close prohibits everything */
1116 if (is_delete_on_close_set(lck, name_hash)) {
1118 * Check the delete on close token
1119 * is valid. It could have been left
1120 * after a server crash.
1122 for(i = 0; i < lck->data->num_share_modes; i++) {
1123 if (!share_mode_stale_pid(lck->data, i)) {
1125 *file_existed = true;
1127 return NT_STATUS_DELETE_PENDING;
1130 return NT_STATUS_OK;
1133 if (is_stat_open(access_mask)) {
1134 /* Stat open that doesn't trigger oplock breaks or share mode
1135 * checks... ! JRA. */
1136 return NT_STATUS_OK;
1140 * Check if the share modes will give us access.
1143 #if defined(DEVELOPER)
1144 for(i = 0; i < lck->data->num_share_modes; i++) {
1145 validate_my_share_entries(conn->sconn, i,
1146 &lck->data->share_modes[i]);
1148 #endif
1150 /* Now we check the share modes, after any oplock breaks. */
1151 for(i = 0; i < lck->data->num_share_modes; i++) {
1153 if (!is_valid_share_mode_entry(&lck->data->share_modes[i])) {
1154 continue;
1157 /* someone else has a share lock on it, check to see if we can
1158 * too */
1159 if (share_conflict(&lck->data->share_modes[i],
1160 access_mask, share_access)) {
1162 if (share_mode_stale_pid(lck->data, i)) {
1163 continue;
1166 *file_existed = true;
1168 return NT_STATUS_SHARING_VIOLATION;
1172 if (lck->data->num_share_modes != 0) {
1173 *file_existed = true;
1176 return NT_STATUS_OK;
1180 * Send a break message to the oplock holder and delay the open for
1181 * our client.
1184 static NTSTATUS send_break_message(files_struct *fsp,
1185 struct share_mode_entry *exclusive,
1186 uint64_t mid,
1187 int oplock_request)
1189 NTSTATUS status;
1190 char msg[MSG_SMB_SHARE_MODE_ENTRY_SIZE];
1192 DEBUG(10, ("Sending break request to PID %s\n",
1193 procid_str_static(&exclusive->pid)));
1194 exclusive->op_mid = mid;
1196 /* Create the message. */
1197 share_mode_entry_to_message(msg, exclusive);
1199 /* Add in the FORCE_OPLOCK_BREAK_TO_NONE bit in the message if set. We
1200 don't want this set in the share mode struct pointed to by lck. */
1202 if (oplock_request & FORCE_OPLOCK_BREAK_TO_NONE) {
1203 SSVAL(msg,OP_BREAK_MSG_OP_TYPE_OFFSET,
1204 exclusive->op_type | FORCE_OPLOCK_BREAK_TO_NONE);
1207 status = messaging_send_buf(fsp->conn->sconn->msg_ctx, exclusive->pid,
1208 MSG_SMB_BREAK_REQUEST,
1209 (uint8 *)msg,
1210 MSG_SMB_SHARE_MODE_ENTRY_SIZE);
1211 if (!NT_STATUS_IS_OK(status)) {
1212 DEBUG(3, ("Could not send oplock break message: %s\n",
1213 nt_errstr(status)));
1216 return status;
1220 * Return share_mode_entry pointers for :
1221 * 1). Batch oplock entry.
1222 * 2). Batch or exclusive oplock entry (may be identical to #1).
1223 * bool have_level2_oplock
1224 * bool have_no_oplock.
1225 * Do internal consistency checks on the share mode for a file.
1228 static void find_oplock_types(files_struct *fsp,
1229 int oplock_request,
1230 const struct share_mode_lock *lck,
1231 struct share_mode_entry **pp_batch,
1232 struct share_mode_entry **pp_ex_or_batch,
1233 bool *got_level2,
1234 bool *got_no_oplock)
1236 int i;
1238 *pp_batch = NULL;
1239 *pp_ex_or_batch = NULL;
1240 *got_level2 = false;
1241 *got_no_oplock = false;
1243 /* Ignore stat or internal opens, as is done in
1244 delay_for_batch_oplocks() and
1245 delay_for_exclusive_oplocks().
1247 if ((oplock_request & INTERNAL_OPEN_ONLY) || is_stat_open(fsp->access_mask)) {
1248 return;
1251 for (i=0; i<lck->data->num_share_modes; i++) {
1252 if (!is_valid_share_mode_entry(&lck->data->share_modes[i])) {
1253 continue;
1256 if (lck->data->share_modes[i].op_type == NO_OPLOCK &&
1257 is_stat_open(lck->data->share_modes[i].access_mask)) {
1258 /* We ignore stat opens in the table - they
1259 always have NO_OPLOCK and never get or
1260 cause breaks. JRA. */
1261 continue;
1264 if (BATCH_OPLOCK_TYPE(lck->data->share_modes[i].op_type)) {
1265 /* batch - can only be one. */
1266 if (share_mode_stale_pid(lck->data, i)) {
1267 DEBUG(10, ("Found stale batch oplock\n"));
1268 continue;
1270 if (*pp_ex_or_batch || *pp_batch || *got_level2 || *got_no_oplock) {
1271 smb_panic("Bad batch oplock entry.");
1273 *pp_batch = &lck->data->share_modes[i];
1276 if (EXCLUSIVE_OPLOCK_TYPE(lck->data->share_modes[i].op_type)) {
1277 if (share_mode_stale_pid(lck->data, i)) {
1278 DEBUG(10, ("Found stale duplicate oplock\n"));
1279 continue;
1281 /* Exclusive or batch - can only be one. */
1282 if (*pp_ex_or_batch || *got_level2 || *got_no_oplock) {
1283 smb_panic("Bad exclusive or batch oplock entry.");
1285 *pp_ex_or_batch = &lck->data->share_modes[i];
1288 if (LEVEL_II_OPLOCK_TYPE(lck->data->share_modes[i].op_type)) {
1289 if (*pp_batch || *pp_ex_or_batch) {
1290 if (share_mode_stale_pid(lck->data, i)) {
1291 DEBUG(10, ("Found stale LevelII "
1292 "oplock\n"));
1293 continue;
1295 smb_panic("Bad levelII oplock entry.");
1297 *got_level2 = true;
1300 if (lck->data->share_modes[i].op_type == NO_OPLOCK) {
1301 if (*pp_batch || *pp_ex_or_batch) {
1302 if (share_mode_stale_pid(lck->data, i)) {
1303 DEBUG(10, ("Found stale NO_OPLOCK "
1304 "entry\n"));
1305 continue;
1307 smb_panic("Bad no oplock entry.");
1309 *got_no_oplock = true;
1314 static bool delay_for_batch_oplocks(files_struct *fsp,
1315 uint64_t mid,
1316 int oplock_request,
1317 struct share_mode_entry *batch_entry)
1319 if ((oplock_request & INTERNAL_OPEN_ONLY) || is_stat_open(fsp->access_mask)) {
1320 return false;
1322 if (batch_entry == NULL) {
1323 return false;
1326 if (server_id_is_disconnected(&batch_entry->pid)) {
1328 * TODO: clean up.
1329 * This could be achieved by sending a break message
1330 * to ourselves. Special considerations for files
1331 * with delete_on_close flag set!
1333 * For now we keep it simple and do not
1334 * allow delete on close for durable handles.
1336 return false;
1339 /* Found a batch oplock */
1340 send_break_message(fsp, batch_entry, mid, oplock_request);
1341 return true;
1344 static bool delay_for_exclusive_oplocks(files_struct *fsp,
1345 uint64_t mid,
1346 int oplock_request,
1347 struct share_mode_entry *ex_entry)
1349 if ((oplock_request & INTERNAL_OPEN_ONLY) || is_stat_open(fsp->access_mask)) {
1350 return false;
1352 if (ex_entry == NULL) {
1353 return false;
1356 if (server_id_is_disconnected(&ex_entry->pid)) {
1358 * since only durable handles can get disconnected,
1359 * and we can only get durable handles with batch oplocks,
1360 * this should actually never be reached...
1362 return false;
1365 send_break_message(fsp, ex_entry, mid, oplock_request);
1366 return true;
1369 static bool file_has_brlocks(files_struct *fsp)
1371 struct byte_range_lock *br_lck;
1373 br_lck = brl_get_locks_readonly(fsp);
1374 if (!br_lck)
1375 return false;
1377 return br_lck->num_locks > 0 ? true : false;
1380 static void grant_fsp_oplock_type(files_struct *fsp,
1381 int oplock_request,
1382 bool got_level2_oplock,
1383 bool got_a_none_oplock)
1385 bool allow_level2 = (global_client_caps & CAP_LEVEL_II_OPLOCKS) &&
1386 lp_level2_oplocks(SNUM(fsp->conn));
1388 /* Start by granting what the client asked for,
1389 but ensure no SAMBA_PRIVATE bits can be set. */
1390 fsp->oplock_type = (oplock_request & ~SAMBA_PRIVATE_OPLOCK_MASK);
1392 if (oplock_request & INTERNAL_OPEN_ONLY) {
1393 /* No oplocks on internal open. */
1394 fsp->oplock_type = NO_OPLOCK;
1395 DEBUG(10,("grant_fsp_oplock_type: oplock type 0x%x on file %s\n",
1396 fsp->oplock_type, fsp_str_dbg(fsp)));
1397 return;
1400 if (lp_locking(fsp->conn->params) && file_has_brlocks(fsp)) {
1401 DEBUG(10,("grant_fsp_oplock_type: file %s has byte range locks\n",
1402 fsp_str_dbg(fsp)));
1403 fsp->oplock_type = NO_OPLOCK;
1406 if (is_stat_open(fsp->access_mask)) {
1407 /* Leave the value already set. */
1408 DEBUG(10,("grant_fsp_oplock_type: oplock type 0x%x on file %s\n",
1409 fsp->oplock_type, fsp_str_dbg(fsp)));
1410 return;
1414 * Match what was requested (fsp->oplock_type) with
1415 * what was found in the existing share modes.
1418 if (got_a_none_oplock) {
1419 fsp->oplock_type = NO_OPLOCK;
1420 } else if (got_level2_oplock) {
1421 if (fsp->oplock_type == NO_OPLOCK ||
1422 fsp->oplock_type == FAKE_LEVEL_II_OPLOCK) {
1423 /* Store a level2 oplock, but don't tell the client */
1424 fsp->oplock_type = FAKE_LEVEL_II_OPLOCK;
1425 } else {
1426 fsp->oplock_type = LEVEL_II_OPLOCK;
1428 } else {
1429 /* All share_mode_entries are placeholders or deferred.
1430 * Silently upgrade to fake levelII if the client didn't
1431 * ask for an oplock. */
1432 if (fsp->oplock_type == NO_OPLOCK) {
1433 /* Store a level2 oplock, but don't tell the client */
1434 fsp->oplock_type = FAKE_LEVEL_II_OPLOCK;
1439 * Don't grant level2 to clients that don't want them
1440 * or if we've turned them off.
1442 if (fsp->oplock_type == LEVEL_II_OPLOCK && !allow_level2) {
1443 fsp->oplock_type = FAKE_LEVEL_II_OPLOCK;
1446 DEBUG(10,("grant_fsp_oplock_type: oplock type 0x%x on file %s\n",
1447 fsp->oplock_type, fsp_str_dbg(fsp)));
1450 static bool request_timed_out(struct timeval request_time,
1451 struct timeval timeout)
1453 struct timeval now, end_time;
1454 GetTimeOfDay(&now);
1455 end_time = timeval_sum(&request_time, &timeout);
1456 return (timeval_compare(&end_time, &now) < 0);
1459 /****************************************************************************
1460 Handle the 1 second delay in returning a SHARING_VIOLATION error.
1461 ****************************************************************************/
1463 static void defer_open(struct share_mode_lock *lck,
1464 struct timeval request_time,
1465 struct timeval timeout,
1466 struct smb_request *req,
1467 struct deferred_open_record *state)
1469 struct server_id self = messaging_server_id(req->sconn->msg_ctx);
1471 /* Paranoia check */
1473 if (lck) {
1474 int i;
1476 for (i=0; i<lck->data->num_share_modes; i++) {
1477 struct share_mode_entry *e = &lck->data->share_modes[i];
1479 if (is_deferred_open_entry(e) &&
1480 serverid_equal(&self, &e->pid) &&
1481 (e->op_mid == req->mid)) {
1482 DEBUG(0, ("Trying to defer an already deferred "
1483 "request: mid=%llu, exiting\n",
1484 (unsigned long long)req->mid));
1485 TALLOC_FREE(lck);
1486 exit_server("attempt to defer a deferred request");
1491 /* End paranoia check */
1493 DEBUG(10,("defer_open_sharing_error: time [%u.%06u] adding deferred "
1494 "open entry for mid %llu\n",
1495 (unsigned int)request_time.tv_sec,
1496 (unsigned int)request_time.tv_usec,
1497 (unsigned long long)req->mid));
1499 if (!push_deferred_open_message_smb(req, request_time, timeout,
1500 state->id, (char *)state, sizeof(*state))) {
1501 TALLOC_FREE(lck);
1502 exit_server("push_deferred_open_message_smb failed");
1504 if (lck) {
1505 add_deferred_open(lck, req->mid, request_time, self, state->id);
1510 /****************************************************************************
1511 On overwrite open ensure that the attributes match.
1512 ****************************************************************************/
1514 static bool open_match_attributes(connection_struct *conn,
1515 uint32 old_dos_attr,
1516 uint32 new_dos_attr,
1517 mode_t existing_unx_mode,
1518 mode_t new_unx_mode,
1519 mode_t *returned_unx_mode)
1521 uint32 noarch_old_dos_attr, noarch_new_dos_attr;
1523 noarch_old_dos_attr = (old_dos_attr & ~FILE_ATTRIBUTE_ARCHIVE);
1524 noarch_new_dos_attr = (new_dos_attr & ~FILE_ATTRIBUTE_ARCHIVE);
1526 if((noarch_old_dos_attr == 0 && noarch_new_dos_attr != 0) ||
1527 (noarch_old_dos_attr != 0 && ((noarch_old_dos_attr & noarch_new_dos_attr) == noarch_old_dos_attr))) {
1528 *returned_unx_mode = new_unx_mode;
1529 } else {
1530 *returned_unx_mode = (mode_t)0;
1533 DEBUG(10,("open_match_attributes: old_dos_attr = 0x%x, "
1534 "existing_unx_mode = 0%o, new_dos_attr = 0x%x "
1535 "returned_unx_mode = 0%o\n",
1536 (unsigned int)old_dos_attr,
1537 (unsigned int)existing_unx_mode,
1538 (unsigned int)new_dos_attr,
1539 (unsigned int)*returned_unx_mode ));
1541 /* If we're mapping SYSTEM and HIDDEN ensure they match. */
1542 if (lp_map_system(SNUM(conn)) || lp_store_dos_attributes(SNUM(conn))) {
1543 if ((old_dos_attr & FILE_ATTRIBUTE_SYSTEM) &&
1544 !(new_dos_attr & FILE_ATTRIBUTE_SYSTEM)) {
1545 return False;
1548 if (lp_map_hidden(SNUM(conn)) || lp_store_dos_attributes(SNUM(conn))) {
1549 if ((old_dos_attr & FILE_ATTRIBUTE_HIDDEN) &&
1550 !(new_dos_attr & FILE_ATTRIBUTE_HIDDEN)) {
1551 return False;
1554 return True;
1557 /****************************************************************************
1558 Special FCB or DOS processing in the case of a sharing violation.
1559 Try and find a duplicated file handle.
1560 ****************************************************************************/
1562 static NTSTATUS fcb_or_dos_open(struct smb_request *req,
1563 connection_struct *conn,
1564 files_struct *fsp_to_dup_into,
1565 const struct smb_filename *smb_fname,
1566 struct file_id id,
1567 uint16 file_pid,
1568 uint64_t vuid,
1569 uint32 access_mask,
1570 uint32 share_access,
1571 uint32 create_options)
1573 files_struct *fsp;
1575 DEBUG(5,("fcb_or_dos_open: attempting old open semantics for "
1576 "file %s.\n", smb_fname_str_dbg(smb_fname)));
1578 for(fsp = file_find_di_first(conn->sconn, id); fsp;
1579 fsp = file_find_di_next(fsp)) {
1581 DEBUG(10,("fcb_or_dos_open: checking file %s, fd = %d, "
1582 "vuid = %llu, file_pid = %u, private_options = 0x%x "
1583 "access_mask = 0x%x\n", fsp_str_dbg(fsp),
1584 fsp->fh->fd, (unsigned long long)fsp->vuid,
1585 (unsigned int)fsp->file_pid,
1586 (unsigned int)fsp->fh->private_options,
1587 (unsigned int)fsp->access_mask ));
1589 if (fsp != fsp_to_dup_into &&
1590 fsp->fh->fd != -1 &&
1591 fsp->vuid == vuid &&
1592 fsp->file_pid == file_pid &&
1593 (fsp->fh->private_options & (NTCREATEX_OPTIONS_PRIVATE_DENY_DOS |
1594 NTCREATEX_OPTIONS_PRIVATE_DENY_FCB)) &&
1595 (fsp->access_mask & FILE_WRITE_DATA) &&
1596 strequal(fsp->fsp_name->base_name, smb_fname->base_name) &&
1597 strequal(fsp->fsp_name->stream_name,
1598 smb_fname->stream_name)) {
1599 DEBUG(10,("fcb_or_dos_open: file match\n"));
1600 break;
1604 if (!fsp) {
1605 return NT_STATUS_NOT_FOUND;
1608 /* quite an insane set of semantics ... */
1609 if (is_executable(smb_fname->base_name) &&
1610 (fsp->fh->private_options & NTCREATEX_OPTIONS_PRIVATE_DENY_DOS)) {
1611 DEBUG(10,("fcb_or_dos_open: file fail due to is_executable.\n"));
1612 return NT_STATUS_INVALID_PARAMETER;
1615 /* We need to duplicate this fsp. */
1616 return dup_file_fsp(req, fsp, access_mask, share_access,
1617 create_options, fsp_to_dup_into);
1620 static void schedule_defer_open(struct share_mode_lock *lck,
1621 struct timeval request_time,
1622 struct smb_request *req)
1624 struct deferred_open_record state;
1626 /* This is a relative time, added to the absolute
1627 request_time value to get the absolute timeout time.
1628 Note that if this is the second or greater time we enter
1629 this codepath for this particular request mid then
1630 request_time is left as the absolute time of the *first*
1631 time this request mid was processed. This is what allows
1632 the request to eventually time out. */
1634 struct timeval timeout;
1636 /* Normally the smbd we asked should respond within
1637 * OPLOCK_BREAK_TIMEOUT seconds regardless of whether
1638 * the client did, give twice the timeout as a safety
1639 * measure here in case the other smbd is stuck
1640 * somewhere else. */
1642 timeout = timeval_set(OPLOCK_BREAK_TIMEOUT*2, 0);
1644 /* Nothing actually uses state.delayed_for_oplocks
1645 but it's handy to differentiate in debug messages
1646 between a 30 second delay due to oplock break, and
1647 a 1 second delay for share mode conflicts. */
1649 state.delayed_for_oplocks = True;
1650 state.async_open = false;
1651 state.id = lck->data->id;
1653 if (!request_timed_out(request_time, timeout)) {
1654 defer_open(lck, request_time, timeout, req, &state);
1658 /****************************************************************************
1659 Reschedule an open call that went asynchronous.
1660 ****************************************************************************/
1662 static void schedule_async_open(struct timeval request_time,
1663 struct smb_request *req)
1665 struct deferred_open_record state;
1666 struct timeval timeout;
1668 timeout = timeval_set(20, 0);
1670 ZERO_STRUCT(state);
1671 state.delayed_for_oplocks = false;
1672 state.async_open = true;
1674 if (!request_timed_out(request_time, timeout)) {
1675 defer_open(NULL, request_time, timeout, req, &state);
1679 /****************************************************************************
1680 Work out what access_mask to use from what the client sent us.
1681 ****************************************************************************/
1683 static NTSTATUS smbd_calculate_maximum_allowed_access(
1684 connection_struct *conn,
1685 const struct smb_filename *smb_fname,
1686 bool use_privs,
1687 uint32_t *p_access_mask)
1689 struct security_descriptor *sd;
1690 uint32_t access_granted;
1691 NTSTATUS status;
1693 if (!use_privs && (get_current_uid(conn) == (uid_t)0)) {
1694 *p_access_mask |= FILE_GENERIC_ALL;
1695 return NT_STATUS_OK;
1698 status = SMB_VFS_GET_NT_ACL(conn, smb_fname->base_name,
1699 (SECINFO_OWNER |
1700 SECINFO_GROUP |
1701 SECINFO_DACL),
1702 talloc_tos(), &sd);
1704 if (NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
1706 * File did not exist
1708 *p_access_mask = FILE_GENERIC_ALL;
1709 return NT_STATUS_OK;
1711 if (!NT_STATUS_IS_OK(status)) {
1712 DEBUG(10,("Could not get acl on file %s: %s\n",
1713 smb_fname_str_dbg(smb_fname),
1714 nt_errstr(status)));
1715 return NT_STATUS_ACCESS_DENIED;
1719 * If we can access the path to this file, by
1720 * default we have FILE_READ_ATTRIBUTES from the
1721 * containing directory. See the section:
1722 * "Algorithm to Check Access to an Existing File"
1723 * in MS-FSA.pdf.
1725 * se_file_access_check()
1726 * also takes care of owner WRITE_DAC and READ_CONTROL.
1728 status = se_file_access_check(sd,
1729 get_current_nttok(conn),
1730 use_privs,
1731 (*p_access_mask & ~FILE_READ_ATTRIBUTES),
1732 &access_granted);
1734 TALLOC_FREE(sd);
1736 if (!NT_STATUS_IS_OK(status)) {
1737 DEBUG(10, ("Access denied on file %s: "
1738 "when calculating maximum access\n",
1739 smb_fname_str_dbg(smb_fname)));
1740 return NT_STATUS_ACCESS_DENIED;
1742 *p_access_mask = (access_granted | FILE_READ_ATTRIBUTES);
1744 if (!(access_granted & DELETE_ACCESS)) {
1745 if (can_delete_file_in_directory(conn, smb_fname)) {
1746 *p_access_mask |= DELETE_ACCESS;
1750 return NT_STATUS_OK;
1753 NTSTATUS smbd_calculate_access_mask(connection_struct *conn,
1754 const struct smb_filename *smb_fname,
1755 bool use_privs,
1756 uint32_t access_mask,
1757 uint32_t *access_mask_out)
1759 NTSTATUS status;
1760 uint32_t orig_access_mask = access_mask;
1761 uint32_t rejected_share_access;
1764 * Convert GENERIC bits to specific bits.
1767 se_map_generic(&access_mask, &file_generic_mapping);
1769 /* Calculate MAXIMUM_ALLOWED_ACCESS if requested. */
1770 if (access_mask & MAXIMUM_ALLOWED_ACCESS) {
1772 status = smbd_calculate_maximum_allowed_access(
1773 conn, smb_fname, use_privs, &access_mask);
1775 if (!NT_STATUS_IS_OK(status)) {
1776 return status;
1779 access_mask &= conn->share_access;
1782 rejected_share_access = access_mask & ~(conn->share_access);
1784 if (rejected_share_access) {
1785 DEBUG(10, ("smbd_calculate_access_mask: Access denied on "
1786 "file %s: rejected by share access mask[0x%08X] "
1787 "orig[0x%08X] mapped[0x%08X] reject[0x%08X]\n",
1788 smb_fname_str_dbg(smb_fname),
1789 conn->share_access,
1790 orig_access_mask, access_mask,
1791 rejected_share_access));
1792 return NT_STATUS_ACCESS_DENIED;
1795 *access_mask_out = access_mask;
1796 return NT_STATUS_OK;
1799 /****************************************************************************
1800 Remove the deferred open entry under lock.
1801 ****************************************************************************/
1803 void remove_deferred_open_entry(struct file_id id, uint64_t mid,
1804 struct server_id pid)
1806 struct share_mode_lock *lck = get_existing_share_mode_lock(
1807 talloc_tos(), id);
1808 if (lck == NULL) {
1809 DEBUG(0, ("could not get share mode lock\n"));
1810 return;
1812 del_deferred_open_entry(lck, mid, pid);
1813 TALLOC_FREE(lck);
1816 /****************************************************************************
1817 Return true if this is a state pointer to an asynchronous create.
1818 ****************************************************************************/
1820 bool is_deferred_open_async(const void *ptr)
1822 const struct deferred_open_record *state = (const struct deferred_open_record *)ptr;
1824 return state->async_open;
1827 static bool clear_ads(uint32_t create_disposition)
1829 bool ret = false;
1831 switch (create_disposition) {
1832 case FILE_SUPERSEDE:
1833 case FILE_OVERWRITE_IF:
1834 case FILE_OVERWRITE:
1835 ret = true;
1836 break;
1837 default:
1838 break;
1840 return ret;
1843 static int disposition_to_open_flags(uint32_t create_disposition)
1845 int ret = 0;
1848 * Currently we're using FILE_SUPERSEDE as the same as
1849 * FILE_OVERWRITE_IF but they really are
1850 * different. FILE_SUPERSEDE deletes an existing file
1851 * (requiring delete access) then recreates it.
1854 switch (create_disposition) {
1855 case FILE_SUPERSEDE:
1856 case FILE_OVERWRITE_IF:
1858 * If file exists replace/overwrite. If file doesn't
1859 * exist create.
1861 ret = O_CREAT|O_TRUNC;
1862 break;
1864 case FILE_OPEN:
1866 * If file exists open. If file doesn't exist error.
1868 ret = 0;
1869 break;
1871 case FILE_OVERWRITE:
1873 * If file exists overwrite. If file doesn't exist
1874 * error.
1876 ret = O_TRUNC;
1877 break;
1879 case FILE_CREATE:
1881 * If file exists error. If file doesn't exist create.
1883 ret = O_CREAT|O_EXCL;
1884 break;
1886 case FILE_OPEN_IF:
1888 * If file exists open. If file doesn't exist create.
1890 ret = O_CREAT;
1891 break;
1893 return ret;
1896 static int calculate_open_access_flags(uint32_t access_mask,
1897 int oplock_request,
1898 uint32_t private_flags)
1900 bool need_write, need_read;
1903 * Note that we ignore the append flag as append does not
1904 * mean the same thing under DOS and Unix.
1907 need_write =
1908 ((access_mask & (FILE_WRITE_DATA | FILE_APPEND_DATA)) ||
1909 (oplock_request & FORCE_OPLOCK_BREAK_TO_NONE));
1911 if (!need_write) {
1912 return O_RDONLY;
1915 /* DENY_DOS opens are always underlying read-write on the
1916 file handle, no matter what the requested access mask
1917 says. */
1919 need_read =
1920 ((private_flags & NTCREATEX_OPTIONS_PRIVATE_DENY_DOS) ||
1921 access_mask & (FILE_READ_ATTRIBUTES|FILE_READ_DATA|
1922 FILE_READ_EA|FILE_EXECUTE));
1924 if (!need_read) {
1925 return O_WRONLY;
1927 return O_RDWR;
1930 /****************************************************************************
1931 Open a file with a share mode. Passed in an already created files_struct *.
1932 ****************************************************************************/
1934 static NTSTATUS open_file_ntcreate(connection_struct *conn,
1935 struct smb_request *req,
1936 uint32 access_mask, /* access bits (FILE_READ_DATA etc.) */
1937 uint32 share_access, /* share constants (FILE_SHARE_READ etc) */
1938 uint32 create_disposition, /* FILE_OPEN_IF etc. */
1939 uint32 create_options, /* options such as delete on close. */
1940 uint32 new_dos_attributes, /* attributes used for new file. */
1941 int oplock_request, /* internal Samba oplock codes. */
1942 /* Information (FILE_EXISTS etc.) */
1943 uint32_t private_flags, /* Samba specific flags. */
1944 int *pinfo,
1945 files_struct *fsp)
1947 struct smb_filename *smb_fname = fsp->fsp_name;
1948 int flags=0;
1949 int flags2=0;
1950 bool file_existed = VALID_STAT(smb_fname->st);
1951 bool def_acl = False;
1952 bool posix_open = False;
1953 bool new_file_created = False;
1954 bool first_open_attempt = true;
1955 NTSTATUS fsp_open = NT_STATUS_ACCESS_DENIED;
1956 mode_t new_unx_mode = (mode_t)0;
1957 mode_t unx_mode = (mode_t)0;
1958 int info;
1959 uint32 existing_dos_attributes = 0;
1960 struct timeval request_time = timeval_zero();
1961 struct share_mode_lock *lck = NULL;
1962 uint32 open_access_mask = access_mask;
1963 NTSTATUS status;
1964 char *parent_dir;
1965 SMB_STRUCT_STAT saved_stat = smb_fname->st;
1966 struct share_mode_entry *batch_entry = NULL;
1967 struct share_mode_entry *exclusive_entry = NULL;
1968 bool got_level2_oplock = false;
1969 bool got_a_none_oplock = false;
1970 struct timespec old_write_time;
1971 struct file_id id;
1973 if (conn->printer) {
1975 * Printers are handled completely differently.
1976 * Most of the passed parameters are ignored.
1979 if (pinfo) {
1980 *pinfo = FILE_WAS_CREATED;
1983 DEBUG(10, ("open_file_ntcreate: printer open fname=%s\n",
1984 smb_fname_str_dbg(smb_fname)));
1986 if (!req) {
1987 DEBUG(0,("open_file_ntcreate: printer open without "
1988 "an SMB request!\n"));
1989 return NT_STATUS_INTERNAL_ERROR;
1992 return print_spool_open(fsp, smb_fname->base_name,
1993 req->vuid);
1996 if (!parent_dirname(talloc_tos(), smb_fname->base_name, &parent_dir,
1997 NULL)) {
1998 return NT_STATUS_NO_MEMORY;
2001 if (new_dos_attributes & FILE_FLAG_POSIX_SEMANTICS) {
2002 posix_open = True;
2003 unx_mode = (mode_t)(new_dos_attributes & ~FILE_FLAG_POSIX_SEMANTICS);
2004 new_dos_attributes = 0;
2005 } else {
2006 /* Windows allows a new file to be created and
2007 silently removes a FILE_ATTRIBUTE_DIRECTORY
2008 sent by the client. Do the same. */
2010 new_dos_attributes &= ~FILE_ATTRIBUTE_DIRECTORY;
2012 /* We add FILE_ATTRIBUTE_ARCHIVE to this as this mode is only used if the file is
2013 * created new. */
2014 unx_mode = unix_mode(conn, new_dos_attributes | FILE_ATTRIBUTE_ARCHIVE,
2015 smb_fname, parent_dir);
2018 DEBUG(10, ("open_file_ntcreate: fname=%s, dos_attrs=0x%x "
2019 "access_mask=0x%x share_access=0x%x "
2020 "create_disposition = 0x%x create_options=0x%x "
2021 "unix mode=0%o oplock_request=%d private_flags = 0x%x\n",
2022 smb_fname_str_dbg(smb_fname), new_dos_attributes,
2023 access_mask, share_access, create_disposition,
2024 create_options, (unsigned int)unx_mode, oplock_request,
2025 (unsigned int)private_flags));
2027 if ((req == NULL) && ((oplock_request & INTERNAL_OPEN_ONLY) == 0)) {
2028 DEBUG(0, ("No smb request but not an internal only open!\n"));
2029 return NT_STATUS_INTERNAL_ERROR;
2033 * Only non-internal opens can be deferred at all
2036 if (req) {
2037 void *ptr;
2038 if (get_deferred_open_message_state(req,
2039 &request_time,
2040 &ptr)) {
2041 /* Remember the absolute time of the original
2042 request with this mid. We'll use it later to
2043 see if this has timed out. */
2045 /* If it was an async create retry, the file
2046 didn't exist. */
2048 if (is_deferred_open_async(ptr)) {
2049 SET_STAT_INVALID(smb_fname->st);
2050 file_existed = false;
2051 } else {
2052 struct deferred_open_record *state = (struct deferred_open_record *)ptr;
2053 /* Remove the deferred open entry under lock. */
2054 remove_deferred_open_entry(
2055 state->id, req->mid,
2056 messaging_server_id(req->sconn->msg_ctx));
2059 /* Ensure we don't reprocess this message. */
2060 remove_deferred_open_message_smb(req->sconn, req->mid);
2062 first_open_attempt = false;
2066 if (!posix_open) {
2067 new_dos_attributes &= SAMBA_ATTRIBUTES_MASK;
2068 if (file_existed) {
2069 existing_dos_attributes = dos_mode(conn, smb_fname);
2073 /* ignore any oplock requests if oplocks are disabled */
2074 if (!lp_oplocks(SNUM(conn)) ||
2075 IS_VETO_OPLOCK_PATH(conn, smb_fname->base_name)) {
2076 /* Mask off everything except the private Samba bits. */
2077 oplock_request &= SAMBA_PRIVATE_OPLOCK_MASK;
2080 /* this is for OS/2 long file names - say we don't support them */
2081 if (!lp_posix_pathnames() && strstr(smb_fname->base_name,".+,;=[].")) {
2082 /* OS/2 Workplace shell fix may be main code stream in a later
2083 * release. */
2084 DEBUG(5,("open_file_ntcreate: OS/2 long filenames are not "
2085 "supported.\n"));
2086 if (use_nt_status()) {
2087 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
2089 return NT_STATUS_DOS(ERRDOS, ERRcannotopen);
2092 switch( create_disposition ) {
2093 case FILE_OPEN:
2094 /* If file exists open. If file doesn't exist error. */
2095 if (!file_existed) {
2096 DEBUG(5,("open_file_ntcreate: FILE_OPEN "
2097 "requested for file %s and file "
2098 "doesn't exist.\n",
2099 smb_fname_str_dbg(smb_fname)));
2100 errno = ENOENT;
2101 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
2103 break;
2105 case FILE_OVERWRITE:
2106 /* If file exists overwrite. If file doesn't exist
2107 * error. */
2108 if (!file_existed) {
2109 DEBUG(5,("open_file_ntcreate: FILE_OVERWRITE "
2110 "requested for file %s and file "
2111 "doesn't exist.\n",
2112 smb_fname_str_dbg(smb_fname) ));
2113 errno = ENOENT;
2114 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
2116 break;
2118 case FILE_CREATE:
2119 /* If file exists error. If file doesn't exist
2120 * create. */
2121 if (file_existed) {
2122 DEBUG(5,("open_file_ntcreate: FILE_CREATE "
2123 "requested for file %s and file "
2124 "already exists.\n",
2125 smb_fname_str_dbg(smb_fname)));
2126 if (S_ISDIR(smb_fname->st.st_ex_mode)) {
2127 errno = EISDIR;
2128 } else {
2129 errno = EEXIST;
2131 return map_nt_error_from_unix(errno);
2133 break;
2135 case FILE_SUPERSEDE:
2136 case FILE_OVERWRITE_IF:
2137 case FILE_OPEN_IF:
2138 break;
2139 default:
2140 return NT_STATUS_INVALID_PARAMETER;
2143 flags2 = disposition_to_open_flags(create_disposition);
2145 /* We only care about matching attributes on file exists and
2146 * overwrite. */
2148 if (!posix_open && file_existed &&
2149 ((create_disposition == FILE_OVERWRITE) ||
2150 (create_disposition == FILE_OVERWRITE_IF))) {
2151 if (!open_match_attributes(conn, existing_dos_attributes,
2152 new_dos_attributes,
2153 smb_fname->st.st_ex_mode,
2154 unx_mode, &new_unx_mode)) {
2155 DEBUG(5,("open_file_ntcreate: attributes missmatch "
2156 "for file %s (%x %x) (0%o, 0%o)\n",
2157 smb_fname_str_dbg(smb_fname),
2158 existing_dos_attributes,
2159 new_dos_attributes,
2160 (unsigned int)smb_fname->st.st_ex_mode,
2161 (unsigned int)unx_mode ));
2162 errno = EACCES;
2163 return NT_STATUS_ACCESS_DENIED;
2167 status = smbd_calculate_access_mask(conn, smb_fname,
2168 false,
2169 access_mask,
2170 &access_mask);
2171 if (!NT_STATUS_IS_OK(status)) {
2172 DEBUG(10, ("open_file_ntcreate: smbd_calculate_access_mask "
2173 "on file %s returned %s\n",
2174 smb_fname_str_dbg(smb_fname), nt_errstr(status)));
2175 return status;
2178 open_access_mask = access_mask;
2180 if ((flags2 & O_TRUNC) || (oplock_request & FORCE_OPLOCK_BREAK_TO_NONE)) {
2181 open_access_mask |= FILE_WRITE_DATA; /* This will cause oplock breaks. */
2184 DEBUG(10, ("open_file_ntcreate: fname=%s, after mapping "
2185 "access_mask=0x%x\n", smb_fname_str_dbg(smb_fname),
2186 access_mask));
2189 * Note that we ignore the append flag as append does not
2190 * mean the same thing under DOS and Unix.
2193 flags = calculate_open_access_flags(access_mask, oplock_request,
2194 private_flags);
2197 * Currently we only look at FILE_WRITE_THROUGH for create options.
2200 #if defined(O_SYNC)
2201 if ((create_options & FILE_WRITE_THROUGH) && lp_strict_sync(SNUM(conn))) {
2202 flags2 |= O_SYNC;
2204 #endif /* O_SYNC */
2206 if (posix_open && (access_mask & FILE_APPEND_DATA)) {
2207 flags2 |= O_APPEND;
2210 if (!posix_open && !CAN_WRITE(conn)) {
2212 * We should really return a permission denied error if either
2213 * O_CREAT or O_TRUNC are set, but for compatibility with
2214 * older versions of Samba we just AND them out.
2216 flags2 &= ~(O_CREAT|O_TRUNC);
2219 if (first_open_attempt && lp_kernel_oplocks(SNUM(conn))) {
2221 * With kernel oplocks the open breaking an oplock
2222 * blocks until the oplock holder has given up the
2223 * oplock or closed the file. We prevent this by first
2224 * trying to open the file with O_NONBLOCK (see "man
2225 * fcntl" on Linux). For the second try, triggered by
2226 * an oplock break response, we do not need this
2227 * anymore.
2229 * This is true under the assumption that only Samba
2230 * requests kernel oplocks. Once someone else like
2231 * NFSv4 starts to use that API, we will have to
2232 * modify this by communicating with the NFSv4 server.
2234 flags2 |= O_NONBLOCK;
2238 * Ensure we can't write on a read-only share or file.
2241 if (flags != O_RDONLY && file_existed &&
2242 (!CAN_WRITE(conn) || IS_DOS_READONLY(existing_dos_attributes))) {
2243 DEBUG(5,("open_file_ntcreate: write access requested for "
2244 "file %s on read only %s\n",
2245 smb_fname_str_dbg(smb_fname),
2246 !CAN_WRITE(conn) ? "share" : "file" ));
2247 errno = EACCES;
2248 return NT_STATUS_ACCESS_DENIED;
2251 fsp->file_id = vfs_file_id_from_sbuf(conn, &smb_fname->st);
2252 fsp->share_access = share_access;
2253 fsp->fh->private_options = private_flags;
2254 fsp->access_mask = open_access_mask; /* We change this to the
2255 * requested access_mask after
2256 * the open is done. */
2257 fsp->posix_open = posix_open;
2259 /* Ensure no SAMBA_PRIVATE bits can be set. */
2260 fsp->oplock_type = (oplock_request & ~SAMBA_PRIVATE_OPLOCK_MASK);
2262 if (timeval_is_zero(&request_time)) {
2263 request_time = fsp->open_time;
2267 * Ensure we pay attention to default ACLs on directories if required.
2270 if ((flags2 & O_CREAT) && lp_inherit_acls(SNUM(conn)) &&
2271 (def_acl = directory_has_default_acl(conn, parent_dir))) {
2272 unx_mode = (0777 & lp_create_mask(SNUM(conn)));
2275 DEBUG(4,("calling open_file with flags=0x%X flags2=0x%X mode=0%o, "
2276 "access_mask = 0x%x, open_access_mask = 0x%x\n",
2277 (unsigned int)flags, (unsigned int)flags2,
2278 (unsigned int)unx_mode, (unsigned int)access_mask,
2279 (unsigned int)open_access_mask));
2281 fsp_open = open_file(fsp, conn, req, parent_dir,
2282 flags|flags2, unx_mode, access_mask,
2283 open_access_mask, &new_file_created);
2285 if (NT_STATUS_EQUAL(fsp_open, NT_STATUS_NETWORK_BUSY)) {
2286 struct deferred_open_record state;
2289 * EWOULDBLOCK/EAGAIN maps to NETWORK_BUSY.
2291 if (file_existed && S_ISFIFO(fsp->fsp_name->st.st_ex_mode)) {
2292 DEBUG(10, ("FIFO busy\n"));
2293 return NT_STATUS_NETWORK_BUSY;
2295 if (req == NULL) {
2296 DEBUG(10, ("Internal open busy\n"));
2297 return NT_STATUS_NETWORK_BUSY;
2301 * From here on we assume this is an oplock break triggered
2304 lck = get_existing_share_mode_lock(talloc_tos(), fsp->file_id);
2305 if (lck == NULL) {
2306 state.delayed_for_oplocks = false;
2307 state.async_open = false;
2308 state.id = fsp->file_id;
2309 defer_open(NULL, request_time, timeval_set(0, 0),
2310 req, &state);
2311 DEBUG(10, ("No share mode lock found after "
2312 "EWOULDBLOCK, retrying sync\n"));
2313 return NT_STATUS_SHARING_VIOLATION;
2316 find_oplock_types(fsp, 0, lck, &batch_entry, &exclusive_entry,
2317 &got_level2_oplock, &got_a_none_oplock);
2319 if (delay_for_batch_oplocks(fsp, req->mid, 0, batch_entry) ||
2320 delay_for_exclusive_oplocks(fsp, req->mid, 0,
2321 exclusive_entry)) {
2322 schedule_defer_open(lck, request_time, req);
2323 TALLOC_FREE(lck);
2324 DEBUG(10, ("Sent oplock break request to kernel "
2325 "oplock holder\n"));
2326 return NT_STATUS_SHARING_VIOLATION;
2330 * No oplock from Samba around. Immediately retry with
2331 * a blocking open.
2333 state.delayed_for_oplocks = false;
2334 state.async_open = false;
2335 state.id = lck->data->id;
2336 defer_open(lck, request_time, timeval_set(0, 0), req, &state);
2337 TALLOC_FREE(lck);
2338 DEBUG(10, ("No Samba oplock around after EWOULDBLOCK. "
2339 "Retrying sync\n"));
2340 return NT_STATUS_SHARING_VIOLATION;
2343 if (!NT_STATUS_IS_OK(fsp_open)) {
2344 if (NT_STATUS_EQUAL(fsp_open, NT_STATUS_RETRY)) {
2345 schedule_async_open(request_time, req);
2347 TALLOC_FREE(lck);
2348 return fsp_open;
2351 if (file_existed && !check_same_dev_ino(&saved_stat, &smb_fname->st)) {
2353 * The file did exist, but some other (local or NFS)
2354 * process either renamed/unlinked and re-created the
2355 * file with different dev/ino after we walked the path,
2356 * but before we did the open. We could retry the
2357 * open but it's a rare enough case it's easier to
2358 * just fail the open to prevent creating any problems
2359 * in the open file db having the wrong dev/ino key.
2361 TALLOC_FREE(lck);
2362 fd_close(fsp);
2363 DEBUG(1,("open_file_ntcreate: file %s - dev/ino mismatch. "
2364 "Old (dev=0x%llu, ino =0x%llu). "
2365 "New (dev=0x%llu, ino=0x%llu). Failing open "
2366 " with NT_STATUS_ACCESS_DENIED.\n",
2367 smb_fname_str_dbg(smb_fname),
2368 (unsigned long long)saved_stat.st_ex_dev,
2369 (unsigned long long)saved_stat.st_ex_ino,
2370 (unsigned long long)smb_fname->st.st_ex_dev,
2371 (unsigned long long)smb_fname->st.st_ex_ino));
2372 return NT_STATUS_ACCESS_DENIED;
2375 old_write_time = smb_fname->st.st_ex_mtime;
2378 * Deal with the race condition where two smbd's detect the
2379 * file doesn't exist and do the create at the same time. One
2380 * of them will win and set a share mode, the other (ie. this
2381 * one) should check if the requested share mode for this
2382 * create is allowed.
2386 * Now the file exists and fsp is successfully opened,
2387 * fsp->dev and fsp->inode are valid and should replace the
2388 * dev=0,inode=0 from a non existent file. Spotted by
2389 * Nadav Danieli <nadavd@exanet.com>. JRA.
2392 id = fsp->file_id;
2394 lck = get_share_mode_lock(talloc_tos(), id,
2395 conn->connectpath,
2396 smb_fname, &old_write_time);
2398 if (lck == NULL) {
2399 DEBUG(0, ("open_file_ntcreate: Could not get share "
2400 "mode lock for %s\n",
2401 smb_fname_str_dbg(smb_fname)));
2402 fd_close(fsp);
2403 return NT_STATUS_SHARING_VIOLATION;
2406 /* Get the types we need to examine. */
2407 find_oplock_types(fsp,
2408 oplock_request,
2409 lck,
2410 &batch_entry,
2411 &exclusive_entry,
2412 &got_level2_oplock,
2413 &got_a_none_oplock);
2415 /* First pass - send break only on batch oplocks. */
2416 if ((req != NULL) &&
2417 delay_for_batch_oplocks(fsp,
2418 req->mid,
2419 oplock_request,
2420 batch_entry)) {
2421 schedule_defer_open(lck, request_time, req);
2422 TALLOC_FREE(lck);
2423 fd_close(fsp);
2424 return NT_STATUS_SHARING_VIOLATION;
2427 status = open_mode_check(conn, lck, fsp->name_hash,
2428 access_mask, share_access,
2429 create_options, &file_existed);
2431 if (NT_STATUS_IS_OK(status)) {
2432 /* We might be going to allow this open. Check oplock
2433 * status again. */
2434 /* Second pass - send break for both batch or
2435 * exclusive oplocks. */
2436 if ((req != NULL) &&
2437 delay_for_exclusive_oplocks(
2438 fsp,
2439 req->mid,
2440 oplock_request,
2441 exclusive_entry)) {
2442 schedule_defer_open(lck, request_time, req);
2443 TALLOC_FREE(lck);
2444 fd_close(fsp);
2445 return NT_STATUS_SHARING_VIOLATION;
2449 if (NT_STATUS_EQUAL(status, NT_STATUS_DELETE_PENDING)) {
2450 /* DELETE_PENDING is not deferred for a second */
2451 TALLOC_FREE(lck);
2452 fd_close(fsp);
2453 return status;
2456 if (!NT_STATUS_IS_OK(status)) {
2457 uint32 can_access_mask;
2458 bool can_access = True;
2460 SMB_ASSERT(NT_STATUS_EQUAL(status, NT_STATUS_SHARING_VIOLATION));
2462 /* Check if this can be done with the deny_dos and fcb
2463 * calls. */
2464 if (private_flags &
2465 (NTCREATEX_OPTIONS_PRIVATE_DENY_DOS|
2466 NTCREATEX_OPTIONS_PRIVATE_DENY_FCB)) {
2467 if (req == NULL) {
2468 DEBUG(0, ("DOS open without an SMB "
2469 "request!\n"));
2470 TALLOC_FREE(lck);
2471 fd_close(fsp);
2472 return NT_STATUS_INTERNAL_ERROR;
2475 /* Use the client requested access mask here,
2476 * not the one we open with. */
2477 status = fcb_or_dos_open(req,
2478 conn,
2479 fsp,
2480 smb_fname,
2482 req->smbpid,
2483 req->vuid,
2484 access_mask,
2485 share_access,
2486 create_options);
2488 if (NT_STATUS_IS_OK(status)) {
2489 TALLOC_FREE(lck);
2490 if (pinfo) {
2491 *pinfo = FILE_WAS_OPENED;
2493 return NT_STATUS_OK;
2498 * This next line is a subtlety we need for
2499 * MS-Access. If a file open will fail due to share
2500 * permissions and also for security (access) reasons,
2501 * we need to return the access failed error, not the
2502 * share error. We can't open the file due to kernel
2503 * oplock deadlock (it's possible we failed above on
2504 * the open_mode_check()) so use a userspace check.
2507 if (flags & O_RDWR) {
2508 can_access_mask = FILE_READ_DATA|FILE_WRITE_DATA;
2509 } else if (flags & O_WRONLY) {
2510 can_access_mask = FILE_WRITE_DATA;
2511 } else {
2512 can_access_mask = FILE_READ_DATA;
2515 if (((can_access_mask & FILE_WRITE_DATA) &&
2516 !CAN_WRITE(conn)) ||
2517 !NT_STATUS_IS_OK(smbd_check_access_rights(conn,
2518 smb_fname,
2519 false,
2520 can_access_mask))) {
2521 can_access = False;
2525 * If we're returning a share violation, ensure we
2526 * cope with the braindead 1 second delay.
2529 if (!(oplock_request & INTERNAL_OPEN_ONLY) &&
2530 lp_defer_sharing_violations()) {
2531 struct timeval timeout;
2532 struct deferred_open_record state;
2533 int timeout_usecs;
2535 /* this is a hack to speed up torture tests
2536 in 'make test' */
2537 timeout_usecs = lp_parm_int(SNUM(conn),
2538 "smbd","sharedelay",
2539 SHARING_VIOLATION_USEC_WAIT);
2541 /* This is a relative time, added to the absolute
2542 request_time value to get the absolute timeout time.
2543 Note that if this is the second or greater time we enter
2544 this codepath for this particular request mid then
2545 request_time is left as the absolute time of the *first*
2546 time this request mid was processed. This is what allows
2547 the request to eventually time out. */
2549 timeout = timeval_set(0, timeout_usecs);
2551 /* Nothing actually uses state.delayed_for_oplocks
2552 but it's handy to differentiate in debug messages
2553 between a 30 second delay due to oplock break, and
2554 a 1 second delay for share mode conflicts. */
2556 state.delayed_for_oplocks = False;
2557 state.async_open = false;
2558 state.id = id;
2560 if ((req != NULL)
2561 && !request_timed_out(request_time,
2562 timeout)) {
2563 defer_open(lck, request_time, timeout,
2564 req, &state);
2568 TALLOC_FREE(lck);
2569 fd_close(fsp);
2570 if (can_access) {
2572 * We have detected a sharing violation here
2573 * so return the correct error code
2575 status = NT_STATUS_SHARING_VIOLATION;
2576 } else {
2577 status = NT_STATUS_ACCESS_DENIED;
2579 return status;
2582 grant_fsp_oplock_type(fsp,
2583 oplock_request,
2584 got_level2_oplock,
2585 got_a_none_oplock);
2588 * We have the share entry *locked*.....
2591 /* Delete streams if create_disposition requires it */
2592 if (!new_file_created && clear_ads(create_disposition) &&
2593 !is_ntfs_stream_smb_fname(smb_fname)) {
2594 status = delete_all_streams(conn, smb_fname->base_name);
2595 if (!NT_STATUS_IS_OK(status)) {
2596 TALLOC_FREE(lck);
2597 fd_close(fsp);
2598 return status;
2602 /* note that we ignore failure for the following. It is
2603 basically a hack for NFS, and NFS will never set one of
2604 these only read them. Nobody but Samba can ever set a deny
2605 mode and we have already checked our more authoritative
2606 locking database for permission to set this deny mode. If
2607 the kernel refuses the operations then the kernel is wrong.
2608 note that GPFS supports it as well - jmcd */
2610 if (fsp->fh->fd != -1 && lp_kernel_share_modes(SNUM(conn))) {
2611 int ret_flock;
2612 ret_flock = SMB_VFS_KERNEL_FLOCK(fsp, share_access, access_mask);
2613 if(ret_flock == -1 ){
2615 TALLOC_FREE(lck);
2616 fd_close(fsp);
2618 return NT_STATUS_SHARING_VIOLATION;
2623 * At this point onwards, we can guarantee that the share entry
2624 * is locked, whether we created the file or not, and that the
2625 * deny mode is compatible with all current opens.
2629 * According to Samba4, SEC_FILE_READ_ATTRIBUTE is always granted,
2630 * but we don't have to store this - just ignore it on access check.
2632 if (conn->sconn->using_smb2) {
2634 * SMB2 doesn't return it (according to Microsoft tests).
2635 * Test Case: TestSuite_ScenarioNo009GrantedAccessTestS0
2636 * File created with access = 0x7 (Read, Write, Delete)
2637 * Query Info on file returns 0x87 (Read, Write, Delete, Read Attributes)
2639 fsp->access_mask = access_mask;
2640 } else {
2641 /* But SMB1 does. */
2642 fsp->access_mask = access_mask | FILE_READ_ATTRIBUTES;
2645 if (file_existed) {
2646 /* stat opens on existing files don't get oplocks. */
2647 if (is_stat_open(open_access_mask)) {
2648 fsp->oplock_type = NO_OPLOCK;
2652 if (new_file_created) {
2653 info = FILE_WAS_CREATED;
2654 } else {
2655 if (flags2 & O_TRUNC) {
2656 info = FILE_WAS_OVERWRITTEN;
2657 } else {
2658 info = FILE_WAS_OPENED;
2662 if (pinfo) {
2663 *pinfo = info;
2667 * Setup the oplock info in both the shared memory and
2668 * file structs.
2671 status = set_file_oplock(fsp, fsp->oplock_type);
2672 if (!NT_STATUS_IS_OK(status)) {
2674 * Could not get the kernel oplock or there are byte-range
2675 * locks on the file.
2677 fsp->oplock_type = NO_OPLOCK;
2680 set_share_mode(lck, fsp, get_current_uid(conn),
2681 req ? req->mid : 0,
2682 fsp->oplock_type);
2684 /* Handle strange delete on close create semantics. */
2685 if (create_options & FILE_DELETE_ON_CLOSE) {
2687 status = can_set_delete_on_close(fsp, new_dos_attributes);
2689 if (!NT_STATUS_IS_OK(status)) {
2690 /* Remember to delete the mode we just added. */
2691 del_share_mode(lck, fsp);
2692 TALLOC_FREE(lck);
2693 fd_close(fsp);
2694 return status;
2696 /* Note that here we set the *inital* delete on close flag,
2697 not the regular one. The magic gets handled in close. */
2698 fsp->initial_delete_on_close = True;
2701 if (info != FILE_WAS_OPENED) {
2702 /* Files should be initially set as archive */
2703 if (lp_map_archive(SNUM(conn)) ||
2704 lp_store_dos_attributes(SNUM(conn))) {
2705 if (!posix_open) {
2706 if (file_set_dosmode(conn, smb_fname,
2707 new_dos_attributes | FILE_ATTRIBUTE_ARCHIVE,
2708 parent_dir, true) == 0) {
2709 unx_mode = smb_fname->st.st_ex_mode;
2715 /* Determine sparse flag. */
2716 if (posix_open) {
2717 /* POSIX opens are sparse by default. */
2718 fsp->is_sparse = true;
2719 } else {
2720 fsp->is_sparse = (file_existed &&
2721 (existing_dos_attributes & FILE_ATTRIBUTE_SPARSE));
2725 * Take care of inherited ACLs on created files - if default ACL not
2726 * selected.
2729 if (!posix_open && new_file_created && !def_acl) {
2731 int saved_errno = errno; /* We might get ENOSYS in the next
2732 * call.. */
2734 if (SMB_VFS_FCHMOD_ACL(fsp, unx_mode) == -1 &&
2735 errno == ENOSYS) {
2736 errno = saved_errno; /* Ignore ENOSYS */
2739 } else if (new_unx_mode) {
2741 int ret = -1;
2743 /* Attributes need changing. File already existed. */
2746 int saved_errno = errno; /* We might get ENOSYS in the
2747 * next call.. */
2748 ret = SMB_VFS_FCHMOD_ACL(fsp, new_unx_mode);
2750 if (ret == -1 && errno == ENOSYS) {
2751 errno = saved_errno; /* Ignore ENOSYS */
2752 } else {
2753 DEBUG(5, ("open_file_ntcreate: reset "
2754 "attributes of file %s to 0%o\n",
2755 smb_fname_str_dbg(smb_fname),
2756 (unsigned int)new_unx_mode));
2757 ret = 0; /* Don't do the fchmod below. */
2761 if ((ret == -1) &&
2762 (SMB_VFS_FCHMOD(fsp, new_unx_mode) == -1))
2763 DEBUG(5, ("open_file_ntcreate: failed to reset "
2764 "attributes of file %s to 0%o\n",
2765 smb_fname_str_dbg(smb_fname),
2766 (unsigned int)new_unx_mode));
2769 /* If this is a successful open, we must remove any deferred open
2770 * records. */
2771 if (req != NULL) {
2772 del_deferred_open_entry(lck, req->mid,
2773 messaging_server_id(req->sconn->msg_ctx));
2775 TALLOC_FREE(lck);
2777 return NT_STATUS_OK;
2781 /****************************************************************************
2782 Open a file for for write to ensure that we can fchmod it.
2783 ****************************************************************************/
2785 NTSTATUS open_file_fchmod(connection_struct *conn,
2786 struct smb_filename *smb_fname,
2787 files_struct **result)
2789 if (!VALID_STAT(smb_fname->st)) {
2790 return NT_STATUS_INVALID_PARAMETER;
2793 return SMB_VFS_CREATE_FILE(
2794 conn, /* conn */
2795 NULL, /* req */
2796 0, /* root_dir_fid */
2797 smb_fname, /* fname */
2798 FILE_WRITE_DATA, /* access_mask */
2799 (FILE_SHARE_READ | FILE_SHARE_WRITE | /* share_access */
2800 FILE_SHARE_DELETE),
2801 FILE_OPEN, /* create_disposition*/
2802 0, /* create_options */
2803 0, /* file_attributes */
2804 INTERNAL_OPEN_ONLY, /* oplock_request */
2805 0, /* allocation_size */
2806 0, /* private_flags */
2807 NULL, /* sd */
2808 NULL, /* ea_list */
2809 result, /* result */
2810 NULL); /* pinfo */
2813 static NTSTATUS mkdir_internal(connection_struct *conn,
2814 struct smb_filename *smb_dname,
2815 uint32 file_attributes)
2817 mode_t mode;
2818 char *parent_dir = NULL;
2819 NTSTATUS status;
2820 bool posix_open = false;
2821 bool need_re_stat = false;
2822 uint32_t access_mask = SEC_DIR_ADD_SUBDIR;
2824 if (!CAN_WRITE(conn) || (access_mask & ~(conn->share_access))) {
2825 DEBUG(5,("mkdir_internal: failing share access "
2826 "%s\n", lp_servicename(talloc_tos(), SNUM(conn))));
2827 return NT_STATUS_ACCESS_DENIED;
2830 if (!parent_dirname(talloc_tos(), smb_dname->base_name, &parent_dir,
2831 NULL)) {
2832 return NT_STATUS_NO_MEMORY;
2835 if (file_attributes & FILE_FLAG_POSIX_SEMANTICS) {
2836 posix_open = true;
2837 mode = (mode_t)(file_attributes & ~FILE_FLAG_POSIX_SEMANTICS);
2838 } else {
2839 mode = unix_mode(conn, FILE_ATTRIBUTE_DIRECTORY, smb_dname, parent_dir);
2842 status = check_parent_access(conn,
2843 smb_dname,
2844 access_mask);
2845 if(!NT_STATUS_IS_OK(status)) {
2846 DEBUG(5,("mkdir_internal: check_parent_access "
2847 "on directory %s for path %s returned %s\n",
2848 parent_dir,
2849 smb_dname->base_name,
2850 nt_errstr(status) ));
2851 return status;
2854 if (SMB_VFS_MKDIR(conn, smb_dname->base_name, mode) != 0) {
2855 return map_nt_error_from_unix(errno);
2858 /* Ensure we're checking for a symlink here.... */
2859 /* We don't want to get caught by a symlink racer. */
2861 if (SMB_VFS_LSTAT(conn, smb_dname) == -1) {
2862 DEBUG(2, ("Could not stat directory '%s' just created: %s\n",
2863 smb_fname_str_dbg(smb_dname), strerror(errno)));
2864 return map_nt_error_from_unix(errno);
2867 if (!S_ISDIR(smb_dname->st.st_ex_mode)) {
2868 DEBUG(0, ("Directory '%s' just created is not a directory !\n",
2869 smb_fname_str_dbg(smb_dname)));
2870 return NT_STATUS_NOT_A_DIRECTORY;
2873 if (lp_store_dos_attributes(SNUM(conn))) {
2874 if (!posix_open) {
2875 file_set_dosmode(conn, smb_dname,
2876 file_attributes | FILE_ATTRIBUTE_DIRECTORY,
2877 parent_dir, true);
2881 if (lp_inherit_perms(SNUM(conn))) {
2882 inherit_access_posix_acl(conn, parent_dir,
2883 smb_dname->base_name, mode);
2884 need_re_stat = true;
2887 if (!posix_open) {
2889 * Check if high bits should have been set,
2890 * then (if bits are missing): add them.
2891 * Consider bits automagically set by UNIX, i.e. SGID bit from parent
2892 * dir.
2894 if ((mode & ~(S_IRWXU|S_IRWXG|S_IRWXO)) &&
2895 (mode & ~smb_dname->st.st_ex_mode)) {
2896 SMB_VFS_CHMOD(conn, smb_dname->base_name,
2897 (smb_dname->st.st_ex_mode |
2898 (mode & ~smb_dname->st.st_ex_mode)));
2899 need_re_stat = true;
2903 /* Change the owner if required. */
2904 if (lp_inherit_owner(SNUM(conn))) {
2905 change_dir_owner_to_parent(conn, parent_dir,
2906 smb_dname->base_name,
2907 &smb_dname->st);
2908 need_re_stat = true;
2911 if (need_re_stat) {
2912 if (SMB_VFS_LSTAT(conn, smb_dname) == -1) {
2913 DEBUG(2, ("Could not stat directory '%s' just created: %s\n",
2914 smb_fname_str_dbg(smb_dname), strerror(errno)));
2915 return map_nt_error_from_unix(errno);
2919 notify_fname(conn, NOTIFY_ACTION_ADDED, FILE_NOTIFY_CHANGE_DIR_NAME,
2920 smb_dname->base_name);
2922 return NT_STATUS_OK;
2925 /****************************************************************************
2926 Open a directory from an NT SMB call.
2927 ****************************************************************************/
2929 static NTSTATUS open_directory(connection_struct *conn,
2930 struct smb_request *req,
2931 struct smb_filename *smb_dname,
2932 uint32 access_mask,
2933 uint32 share_access,
2934 uint32 create_disposition,
2935 uint32 create_options,
2936 uint32 file_attributes,
2937 int *pinfo,
2938 files_struct **result)
2940 files_struct *fsp = NULL;
2941 bool dir_existed = VALID_STAT(smb_dname->st) ? True : False;
2942 struct share_mode_lock *lck = NULL;
2943 NTSTATUS status;
2944 struct timespec mtimespec;
2945 int info = 0;
2947 if (is_ntfs_stream_smb_fname(smb_dname)) {
2948 DEBUG(2, ("open_directory: %s is a stream name!\n",
2949 smb_fname_str_dbg(smb_dname)));
2950 return NT_STATUS_NOT_A_DIRECTORY;
2953 if (!(file_attributes & FILE_FLAG_POSIX_SEMANTICS)) {
2954 /* Ensure we have a directory attribute. */
2955 file_attributes |= FILE_ATTRIBUTE_DIRECTORY;
2958 DEBUG(5,("open_directory: opening directory %s, access_mask = 0x%x, "
2959 "share_access = 0x%x create_options = 0x%x, "
2960 "create_disposition = 0x%x, file_attributes = 0x%x\n",
2961 smb_fname_str_dbg(smb_dname),
2962 (unsigned int)access_mask,
2963 (unsigned int)share_access,
2964 (unsigned int)create_options,
2965 (unsigned int)create_disposition,
2966 (unsigned int)file_attributes));
2968 status = smbd_calculate_access_mask(conn, smb_dname, false,
2969 access_mask, &access_mask);
2970 if (!NT_STATUS_IS_OK(status)) {
2971 DEBUG(10, ("open_directory: smbd_calculate_access_mask "
2972 "on file %s returned %s\n",
2973 smb_fname_str_dbg(smb_dname),
2974 nt_errstr(status)));
2975 return status;
2978 if ((access_mask & SEC_FLAG_SYSTEM_SECURITY) &&
2979 !security_token_has_privilege(get_current_nttok(conn),
2980 SEC_PRIV_SECURITY)) {
2981 DEBUG(10, ("open_directory: open on %s "
2982 "failed - SEC_FLAG_SYSTEM_SECURITY denied.\n",
2983 smb_fname_str_dbg(smb_dname)));
2984 return NT_STATUS_PRIVILEGE_NOT_HELD;
2987 switch( create_disposition ) {
2988 case FILE_OPEN:
2990 if (!dir_existed) {
2991 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
2994 info = FILE_WAS_OPENED;
2995 break;
2997 case FILE_CREATE:
2999 /* If directory exists error. If directory doesn't
3000 * exist create. */
3002 if (dir_existed) {
3003 status = NT_STATUS_OBJECT_NAME_COLLISION;
3004 DEBUG(2, ("open_directory: unable to create "
3005 "%s. Error was %s\n",
3006 smb_fname_str_dbg(smb_dname),
3007 nt_errstr(status)));
3008 return status;
3011 status = mkdir_internal(conn, smb_dname,
3012 file_attributes);
3014 if (!NT_STATUS_IS_OK(status)) {
3015 DEBUG(2, ("open_directory: unable to create "
3016 "%s. Error was %s\n",
3017 smb_fname_str_dbg(smb_dname),
3018 nt_errstr(status)));
3019 return status;
3022 info = FILE_WAS_CREATED;
3023 break;
3025 case FILE_OPEN_IF:
3027 * If directory exists open. If directory doesn't
3028 * exist create.
3031 if (dir_existed) {
3032 status = NT_STATUS_OK;
3033 info = FILE_WAS_OPENED;
3034 } else {
3035 status = mkdir_internal(conn, smb_dname,
3036 file_attributes);
3038 if (NT_STATUS_IS_OK(status)) {
3039 info = FILE_WAS_CREATED;
3040 } else {
3041 /* Cope with create race. */
3042 if (!NT_STATUS_EQUAL(status,
3043 NT_STATUS_OBJECT_NAME_COLLISION)) {
3044 DEBUG(2, ("open_directory: unable to create "
3045 "%s. Error was %s\n",
3046 smb_fname_str_dbg(smb_dname),
3047 nt_errstr(status)));
3048 return status;
3050 info = FILE_WAS_OPENED;
3054 break;
3056 case FILE_SUPERSEDE:
3057 case FILE_OVERWRITE:
3058 case FILE_OVERWRITE_IF:
3059 default:
3060 DEBUG(5,("open_directory: invalid create_disposition "
3061 "0x%x for directory %s\n",
3062 (unsigned int)create_disposition,
3063 smb_fname_str_dbg(smb_dname)));
3064 return NT_STATUS_INVALID_PARAMETER;
3067 if(!S_ISDIR(smb_dname->st.st_ex_mode)) {
3068 DEBUG(5,("open_directory: %s is not a directory !\n",
3069 smb_fname_str_dbg(smb_dname)));
3070 return NT_STATUS_NOT_A_DIRECTORY;
3073 if (info == FILE_WAS_OPENED) {
3074 status = smbd_check_access_rights(conn,
3075 smb_dname,
3076 false,
3077 access_mask);
3078 if (!NT_STATUS_IS_OK(status)) {
3079 DEBUG(10, ("open_directory: smbd_check_access_rights on "
3080 "file %s failed with %s\n",
3081 smb_fname_str_dbg(smb_dname),
3082 nt_errstr(status)));
3083 return status;
3087 status = file_new(req, conn, &fsp);
3088 if(!NT_STATUS_IS_OK(status)) {
3089 return status;
3093 * Setup the files_struct for it.
3096 fsp->file_id = vfs_file_id_from_sbuf(conn, &smb_dname->st);
3097 fsp->vuid = req ? req->vuid : UID_FIELD_INVALID;
3098 fsp->file_pid = req ? req->smbpid : 0;
3099 fsp->can_lock = False;
3100 fsp->can_read = False;
3101 fsp->can_write = False;
3103 fsp->share_access = share_access;
3104 fsp->fh->private_options = 0;
3106 * According to Samba4, SEC_FILE_READ_ATTRIBUTE is always granted,
3108 fsp->access_mask = access_mask | FILE_READ_ATTRIBUTES;
3109 fsp->print_file = NULL;
3110 fsp->modified = False;
3111 fsp->oplock_type = NO_OPLOCK;
3112 fsp->sent_oplock_break = NO_BREAK_SENT;
3113 fsp->is_directory = True;
3114 fsp->posix_open = (file_attributes & FILE_FLAG_POSIX_SEMANTICS) ? True : False;
3115 status = fsp_set_smb_fname(fsp, smb_dname);
3116 if (!NT_STATUS_IS_OK(status)) {
3117 file_free(req, fsp);
3118 return status;
3121 mtimespec = smb_dname->st.st_ex_mtime;
3123 #ifdef O_DIRECTORY
3124 status = fd_open(conn, fsp, O_RDONLY|O_DIRECTORY, 0);
3125 #else
3126 /* POSIX allows us to open a directory with O_RDONLY. */
3127 status = fd_open(conn, fsp, O_RDONLY, 0);
3128 #endif
3129 if (!NT_STATUS_IS_OK(status)) {
3130 DEBUG(5, ("open_directory: Could not open fd for "
3131 "%s (%s)\n",
3132 smb_fname_str_dbg(smb_dname),
3133 nt_errstr(status)));
3134 file_free(req, fsp);
3135 return status;
3138 status = vfs_stat_fsp(fsp);
3139 if (!NT_STATUS_IS_OK(status)) {
3140 fd_close(fsp);
3141 file_free(req, fsp);
3142 return status;
3145 /* Ensure there was no race condition. */
3146 if (!check_same_stat(&smb_dname->st, &fsp->fsp_name->st)) {
3147 DEBUG(5,("open_directory: stat struct differs for "
3148 "directory %s.\n",
3149 smb_fname_str_dbg(smb_dname)));
3150 fd_close(fsp);
3151 file_free(req, fsp);
3152 return NT_STATUS_ACCESS_DENIED;
3155 lck = get_share_mode_lock(talloc_tos(), fsp->file_id,
3156 conn->connectpath, smb_dname,
3157 &mtimespec);
3159 if (lck == NULL) {
3160 DEBUG(0, ("open_directory: Could not get share mode lock for "
3161 "%s\n", smb_fname_str_dbg(smb_dname)));
3162 fd_close(fsp);
3163 file_free(req, fsp);
3164 return NT_STATUS_SHARING_VIOLATION;
3167 status = open_mode_check(conn, lck, fsp->name_hash,
3168 access_mask, share_access,
3169 create_options, &dir_existed);
3171 if (!NT_STATUS_IS_OK(status)) {
3172 TALLOC_FREE(lck);
3173 fd_close(fsp);
3174 file_free(req, fsp);
3175 return status;
3178 set_share_mode(lck, fsp, get_current_uid(conn),
3179 req ? req->mid : 0, NO_OPLOCK);
3181 /* For directories the delete on close bit at open time seems
3182 always to be honored on close... See test 19 in Samba4 BASE-DELETE. */
3183 if (create_options & FILE_DELETE_ON_CLOSE) {
3184 status = can_set_delete_on_close(fsp, 0);
3185 if (!NT_STATUS_IS_OK(status) && !NT_STATUS_EQUAL(status, NT_STATUS_DIRECTORY_NOT_EMPTY)) {
3186 TALLOC_FREE(lck);
3187 fd_close(fsp);
3188 file_free(req, fsp);
3189 return status;
3192 if (NT_STATUS_IS_OK(status)) {
3193 /* Note that here we set the *inital* delete on close flag,
3194 not the regular one. The magic gets handled in close. */
3195 fsp->initial_delete_on_close = True;
3199 TALLOC_FREE(lck);
3201 if (pinfo) {
3202 *pinfo = info;
3205 *result = fsp;
3206 return NT_STATUS_OK;
3209 NTSTATUS create_directory(connection_struct *conn, struct smb_request *req,
3210 struct smb_filename *smb_dname)
3212 NTSTATUS status;
3213 files_struct *fsp;
3215 status = SMB_VFS_CREATE_FILE(
3216 conn, /* conn */
3217 req, /* req */
3218 0, /* root_dir_fid */
3219 smb_dname, /* fname */
3220 FILE_READ_ATTRIBUTES, /* access_mask */
3221 FILE_SHARE_NONE, /* share_access */
3222 FILE_CREATE, /* create_disposition*/
3223 FILE_DIRECTORY_FILE, /* create_options */
3224 FILE_ATTRIBUTE_DIRECTORY, /* file_attributes */
3225 0, /* oplock_request */
3226 0, /* allocation_size */
3227 0, /* private_flags */
3228 NULL, /* sd */
3229 NULL, /* ea_list */
3230 &fsp, /* result */
3231 NULL); /* pinfo */
3233 if (NT_STATUS_IS_OK(status)) {
3234 close_file(req, fsp, NORMAL_CLOSE);
3237 return status;
3240 /****************************************************************************
3241 Receive notification that one of our open files has been renamed by another
3242 smbd process.
3243 ****************************************************************************/
3245 void msg_file_was_renamed(struct messaging_context *msg,
3246 void *private_data,
3247 uint32_t msg_type,
3248 struct server_id server_id,
3249 DATA_BLOB *data)
3251 files_struct *fsp;
3252 char *frm = (char *)data->data;
3253 struct file_id id;
3254 const char *sharepath;
3255 const char *base_name;
3256 const char *stream_name;
3257 struct smb_filename *smb_fname = NULL;
3258 size_t sp_len, bn_len;
3259 NTSTATUS status;
3260 struct smbd_server_connection *sconn =
3261 talloc_get_type_abort(private_data,
3262 struct smbd_server_connection);
3264 if (data->data == NULL
3265 || data->length < MSG_FILE_RENAMED_MIN_SIZE + 2) {
3266 DEBUG(0, ("msg_file_was_renamed: Got invalid msg len %d\n",
3267 (int)data->length));
3268 return;
3271 /* Unpack the message. */
3272 pull_file_id_24(frm, &id);
3273 sharepath = &frm[24];
3274 sp_len = strlen(sharepath);
3275 base_name = sharepath + sp_len + 1;
3276 bn_len = strlen(base_name);
3277 stream_name = sharepath + sp_len + 1 + bn_len + 1;
3279 /* stream_name must always be NULL if there is no stream. */
3280 if (stream_name[0] == '\0') {
3281 stream_name = NULL;
3284 status = create_synthetic_smb_fname(talloc_tos(), base_name,
3285 stream_name, NULL, &smb_fname);
3286 if (!NT_STATUS_IS_OK(status)) {
3287 return;
3290 DEBUG(10,("msg_file_was_renamed: Got rename message for sharepath %s, new name %s, "
3291 "file_id %s\n",
3292 sharepath, smb_fname_str_dbg(smb_fname),
3293 file_id_string_tos(&id)));
3295 for(fsp = file_find_di_first(sconn, id); fsp;
3296 fsp = file_find_di_next(fsp)) {
3297 if (memcmp(fsp->conn->connectpath, sharepath, sp_len) == 0) {
3299 DEBUG(10,("msg_file_was_renamed: renaming file %s from %s -> %s\n",
3300 fsp_fnum_dbg(fsp), fsp_str_dbg(fsp),
3301 smb_fname_str_dbg(smb_fname)));
3302 status = fsp_set_smb_fname(fsp, smb_fname);
3303 if (!NT_STATUS_IS_OK(status)) {
3304 goto out;
3306 } else {
3307 /* TODO. JRA. */
3308 /* Now we have the complete path we can work out if this is
3309 actually within this share and adjust newname accordingly. */
3310 DEBUG(10,("msg_file_was_renamed: share mismatch (sharepath %s "
3311 "not sharepath %s) "
3312 "%s from %s -> %s\n",
3313 fsp->conn->connectpath,
3314 sharepath,
3315 fsp_fnum_dbg(fsp),
3316 fsp_str_dbg(fsp),
3317 smb_fname_str_dbg(smb_fname)));
3320 out:
3321 TALLOC_FREE(smb_fname);
3322 return;
3326 * If a main file is opened for delete, all streams need to be checked for
3327 * !FILE_SHARE_DELETE. Do this by opening with DELETE_ACCESS.
3328 * If that works, delete them all by setting the delete on close and close.
3331 NTSTATUS open_streams_for_delete(connection_struct *conn,
3332 const char *fname)
3334 struct stream_struct *stream_info = NULL;
3335 files_struct **streams = NULL;
3336 int i;
3337 unsigned int num_streams = 0;
3338 TALLOC_CTX *frame = talloc_stackframe();
3339 NTSTATUS status;
3341 status = vfs_streaminfo(conn, NULL, fname, talloc_tos(),
3342 &num_streams, &stream_info);
3344 if (NT_STATUS_EQUAL(status, NT_STATUS_NOT_IMPLEMENTED)
3345 || NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
3346 DEBUG(10, ("no streams around\n"));
3347 TALLOC_FREE(frame);
3348 return NT_STATUS_OK;
3351 if (!NT_STATUS_IS_OK(status)) {
3352 DEBUG(10, ("vfs_streaminfo failed: %s\n",
3353 nt_errstr(status)));
3354 goto fail;
3357 DEBUG(10, ("open_streams_for_delete found %d streams\n",
3358 num_streams));
3360 if (num_streams == 0) {
3361 TALLOC_FREE(frame);
3362 return NT_STATUS_OK;
3365 streams = talloc_array(talloc_tos(), files_struct *, num_streams);
3366 if (streams == NULL) {
3367 DEBUG(0, ("talloc failed\n"));
3368 status = NT_STATUS_NO_MEMORY;
3369 goto fail;
3372 for (i=0; i<num_streams; i++) {
3373 struct smb_filename *smb_fname = NULL;
3375 if (strequal(stream_info[i].name, "::$DATA")) {
3376 streams[i] = NULL;
3377 continue;
3380 status = create_synthetic_smb_fname(talloc_tos(), fname,
3381 stream_info[i].name,
3382 NULL, &smb_fname);
3383 if (!NT_STATUS_IS_OK(status)) {
3384 goto fail;
3387 if (SMB_VFS_STAT(conn, smb_fname) == -1) {
3388 DEBUG(10, ("Unable to stat stream: %s\n",
3389 smb_fname_str_dbg(smb_fname)));
3392 status = SMB_VFS_CREATE_FILE(
3393 conn, /* conn */
3394 NULL, /* req */
3395 0, /* root_dir_fid */
3396 smb_fname, /* fname */
3397 DELETE_ACCESS, /* access_mask */
3398 (FILE_SHARE_READ | /* share_access */
3399 FILE_SHARE_WRITE | FILE_SHARE_DELETE),
3400 FILE_OPEN, /* create_disposition*/
3401 0, /* create_options */
3402 FILE_ATTRIBUTE_NORMAL, /* file_attributes */
3403 0, /* oplock_request */
3404 0, /* allocation_size */
3405 NTCREATEX_OPTIONS_PRIVATE_STREAM_DELETE, /* private_flags */
3406 NULL, /* sd */
3407 NULL, /* ea_list */
3408 &streams[i], /* result */
3409 NULL); /* pinfo */
3411 if (!NT_STATUS_IS_OK(status)) {
3412 DEBUG(10, ("Could not open stream %s: %s\n",
3413 smb_fname_str_dbg(smb_fname),
3414 nt_errstr(status)));
3416 TALLOC_FREE(smb_fname);
3417 break;
3419 TALLOC_FREE(smb_fname);
3423 * don't touch the variable "status" beyond this point :-)
3426 for (i -= 1 ; i >= 0; i--) {
3427 if (streams[i] == NULL) {
3428 continue;
3431 DEBUG(10, ("Closing stream # %d, %s\n", i,
3432 fsp_str_dbg(streams[i])));
3433 close_file(NULL, streams[i], NORMAL_CLOSE);
3436 fail:
3437 TALLOC_FREE(frame);
3438 return status;
3441 /*********************************************************************
3442 Create a default ACL by inheriting from the parent. If no inheritance
3443 from the parent available, don't set anything. This will leave the actual
3444 permissions the new file or directory already got from the filesystem
3445 as the NT ACL when read.
3446 *********************************************************************/
3448 static NTSTATUS inherit_new_acl(files_struct *fsp)
3450 TALLOC_CTX *frame = talloc_stackframe();
3451 char *parent_name = NULL;
3452 struct security_descriptor *parent_desc = NULL;
3453 NTSTATUS status = NT_STATUS_OK;
3454 struct security_descriptor *psd = NULL;
3455 struct dom_sid *owner_sid = NULL;
3456 struct dom_sid *group_sid = NULL;
3457 uint32_t security_info_sent = (SECINFO_OWNER | SECINFO_GROUP | SECINFO_DACL);
3458 bool inherit_owner = lp_inherit_owner(SNUM(fsp->conn));
3459 bool inheritable_components = false;
3460 size_t size = 0;
3462 if (!parent_dirname(frame, fsp->fsp_name->base_name, &parent_name, NULL)) {
3463 TALLOC_FREE(frame);
3464 return NT_STATUS_NO_MEMORY;
3467 status = SMB_VFS_GET_NT_ACL(fsp->conn,
3468 parent_name,
3469 (SECINFO_OWNER | SECINFO_GROUP | SECINFO_DACL),
3470 frame,
3471 &parent_desc);
3472 if (!NT_STATUS_IS_OK(status)) {
3473 TALLOC_FREE(frame);
3474 return status;
3477 inheritable_components = sd_has_inheritable_components(parent_desc,
3478 fsp->is_directory);
3480 if (!inheritable_components && !inherit_owner) {
3481 TALLOC_FREE(frame);
3482 /* Nothing to inherit and not setting owner. */
3483 return NT_STATUS_OK;
3486 /* Create an inherited descriptor from the parent. */
3488 if (DEBUGLEVEL >= 10) {
3489 DEBUG(10,("inherit_new_acl: parent acl for %s is:\n",
3490 fsp_str_dbg(fsp) ));
3491 NDR_PRINT_DEBUG(security_descriptor, parent_desc);
3494 /* Inherit from parent descriptor if "inherit owner" set. */
3495 if (inherit_owner) {
3496 owner_sid = parent_desc->owner_sid;
3497 group_sid = parent_desc->group_sid;
3500 if (owner_sid == NULL) {
3501 owner_sid = &fsp->conn->session_info->security_token->sids[PRIMARY_USER_SID_INDEX];
3503 if (group_sid == NULL) {
3504 group_sid = &fsp->conn->session_info->security_token->sids[PRIMARY_GROUP_SID_INDEX];
3507 status = se_create_child_secdesc(frame,
3508 &psd,
3509 &size,
3510 parent_desc,
3511 owner_sid,
3512 group_sid,
3513 fsp->is_directory);
3514 if (!NT_STATUS_IS_OK(status)) {
3515 TALLOC_FREE(frame);
3516 return status;
3519 /* If inheritable_components == false,
3520 se_create_child_secdesc()
3521 creates a security desriptor with a NULL dacl
3522 entry, but with SEC_DESC_DACL_PRESENT. We need
3523 to remove that flag. */
3525 if (!inheritable_components) {
3526 security_info_sent &= ~SECINFO_DACL;
3527 psd->type &= ~SEC_DESC_DACL_PRESENT;
3530 if (DEBUGLEVEL >= 10) {
3531 DEBUG(10,("inherit_new_acl: child acl for %s is:\n",
3532 fsp_str_dbg(fsp) ));
3533 NDR_PRINT_DEBUG(security_descriptor, psd);
3536 if (inherit_owner) {
3537 /* We need to be root to force this. */
3538 become_root();
3540 status = SMB_VFS_FSET_NT_ACL(fsp,
3541 security_info_sent,
3542 psd);
3543 if (inherit_owner) {
3544 unbecome_root();
3546 TALLOC_FREE(frame);
3547 return status;
3551 * Wrapper around open_file_ntcreate and open_directory
3554 static NTSTATUS create_file_unixpath(connection_struct *conn,
3555 struct smb_request *req,
3556 struct smb_filename *smb_fname,
3557 uint32_t access_mask,
3558 uint32_t share_access,
3559 uint32_t create_disposition,
3560 uint32_t create_options,
3561 uint32_t file_attributes,
3562 uint32_t oplock_request,
3563 uint64_t allocation_size,
3564 uint32_t private_flags,
3565 struct security_descriptor *sd,
3566 struct ea_list *ea_list,
3568 files_struct **result,
3569 int *pinfo)
3571 int info = FILE_WAS_OPENED;
3572 files_struct *base_fsp = NULL;
3573 files_struct *fsp = NULL;
3574 NTSTATUS status;
3576 DEBUG(10,("create_file_unixpath: access_mask = 0x%x "
3577 "file_attributes = 0x%x, share_access = 0x%x, "
3578 "create_disposition = 0x%x create_options = 0x%x "
3579 "oplock_request = 0x%x private_flags = 0x%x "
3580 "ea_list = 0x%p, sd = 0x%p, "
3581 "fname = %s\n",
3582 (unsigned int)access_mask,
3583 (unsigned int)file_attributes,
3584 (unsigned int)share_access,
3585 (unsigned int)create_disposition,
3586 (unsigned int)create_options,
3587 (unsigned int)oplock_request,
3588 (unsigned int)private_flags,
3589 ea_list, sd, smb_fname_str_dbg(smb_fname)));
3591 if (create_options & FILE_OPEN_BY_FILE_ID) {
3592 status = NT_STATUS_NOT_SUPPORTED;
3593 goto fail;
3596 if (create_options & NTCREATEX_OPTIONS_INVALID_PARAM_MASK) {
3597 status = NT_STATUS_INVALID_PARAMETER;
3598 goto fail;
3601 if (req == NULL) {
3602 oplock_request |= INTERNAL_OPEN_ONLY;
3605 if ((conn->fs_capabilities & FILE_NAMED_STREAMS)
3606 && (access_mask & DELETE_ACCESS)
3607 && !is_ntfs_stream_smb_fname(smb_fname)) {
3609 * We can't open a file with DELETE access if any of the
3610 * streams is open without FILE_SHARE_DELETE
3612 status = open_streams_for_delete(conn, smb_fname->base_name);
3614 if (!NT_STATUS_IS_OK(status)) {
3615 goto fail;
3619 if ((access_mask & SEC_FLAG_SYSTEM_SECURITY) &&
3620 !security_token_has_privilege(get_current_nttok(conn),
3621 SEC_PRIV_SECURITY)) {
3622 DEBUG(10, ("create_file_unixpath: open on %s "
3623 "failed - SEC_FLAG_SYSTEM_SECURITY denied.\n",
3624 smb_fname_str_dbg(smb_fname)));
3625 status = NT_STATUS_PRIVILEGE_NOT_HELD;
3626 goto fail;
3629 if ((conn->fs_capabilities & FILE_NAMED_STREAMS)
3630 && is_ntfs_stream_smb_fname(smb_fname)
3631 && (!(private_flags & NTCREATEX_OPTIONS_PRIVATE_STREAM_DELETE))) {
3632 uint32 base_create_disposition;
3633 struct smb_filename *smb_fname_base = NULL;
3635 if (create_options & FILE_DIRECTORY_FILE) {
3636 status = NT_STATUS_NOT_A_DIRECTORY;
3637 goto fail;
3640 switch (create_disposition) {
3641 case FILE_OPEN:
3642 base_create_disposition = FILE_OPEN;
3643 break;
3644 default:
3645 base_create_disposition = FILE_OPEN_IF;
3646 break;
3649 /* Create an smb_filename with stream_name == NULL. */
3650 status = create_synthetic_smb_fname(talloc_tos(),
3651 smb_fname->base_name,
3652 NULL, NULL,
3653 &smb_fname_base);
3654 if (!NT_STATUS_IS_OK(status)) {
3655 goto fail;
3658 if (SMB_VFS_STAT(conn, smb_fname_base) == -1) {
3659 DEBUG(10, ("Unable to stat stream: %s\n",
3660 smb_fname_str_dbg(smb_fname_base)));
3663 /* Open the base file. */
3664 status = create_file_unixpath(conn, NULL, smb_fname_base, 0,
3665 FILE_SHARE_READ
3666 | FILE_SHARE_WRITE
3667 | FILE_SHARE_DELETE,
3668 base_create_disposition,
3669 0, 0, 0, 0, 0, NULL, NULL,
3670 &base_fsp, NULL);
3671 TALLOC_FREE(smb_fname_base);
3673 if (!NT_STATUS_IS_OK(status)) {
3674 DEBUG(10, ("create_file_unixpath for base %s failed: "
3675 "%s\n", smb_fname->base_name,
3676 nt_errstr(status)));
3677 goto fail;
3679 /* we don't need to low level fd */
3680 fd_close(base_fsp);
3684 * If it's a request for a directory open, deal with it separately.
3687 if (create_options & FILE_DIRECTORY_FILE) {
3689 if (create_options & FILE_NON_DIRECTORY_FILE) {
3690 status = NT_STATUS_INVALID_PARAMETER;
3691 goto fail;
3694 /* Can't open a temp directory. IFS kit test. */
3695 if (!(file_attributes & FILE_FLAG_POSIX_SEMANTICS) &&
3696 (file_attributes & FILE_ATTRIBUTE_TEMPORARY)) {
3697 status = NT_STATUS_INVALID_PARAMETER;
3698 goto fail;
3702 * We will get a create directory here if the Win32
3703 * app specified a security descriptor in the
3704 * CreateDirectory() call.
3707 oplock_request = 0;
3708 status = open_directory(
3709 conn, req, smb_fname, access_mask, share_access,
3710 create_disposition, create_options, file_attributes,
3711 &info, &fsp);
3712 } else {
3715 * Ordinary file case.
3718 status = file_new(req, conn, &fsp);
3719 if(!NT_STATUS_IS_OK(status)) {
3720 goto fail;
3723 status = fsp_set_smb_fname(fsp, smb_fname);
3724 if (!NT_STATUS_IS_OK(status)) {
3725 goto fail;
3728 if (base_fsp) {
3730 * We're opening the stream element of a
3731 * base_fsp we already opened. Set up the
3732 * base_fsp pointer.
3734 fsp->base_fsp = base_fsp;
3737 if (allocation_size) {
3738 fsp->initial_allocation_size = smb_roundup(fsp->conn,
3739 allocation_size);
3742 status = open_file_ntcreate(conn,
3743 req,
3744 access_mask,
3745 share_access,
3746 create_disposition,
3747 create_options,
3748 file_attributes,
3749 oplock_request,
3750 private_flags,
3751 &info,
3752 fsp);
3754 if(!NT_STATUS_IS_OK(status)) {
3755 file_free(req, fsp);
3756 fsp = NULL;
3759 if (NT_STATUS_EQUAL(status, NT_STATUS_FILE_IS_A_DIRECTORY)) {
3761 /* A stream open never opens a directory */
3763 if (base_fsp) {
3764 status = NT_STATUS_FILE_IS_A_DIRECTORY;
3765 goto fail;
3769 * Fail the open if it was explicitly a non-directory
3770 * file.
3773 if (create_options & FILE_NON_DIRECTORY_FILE) {
3774 status = NT_STATUS_FILE_IS_A_DIRECTORY;
3775 goto fail;
3778 oplock_request = 0;
3779 status = open_directory(
3780 conn, req, smb_fname, access_mask,
3781 share_access, create_disposition,
3782 create_options, file_attributes,
3783 &info, &fsp);
3787 if (!NT_STATUS_IS_OK(status)) {
3788 goto fail;
3791 fsp->base_fsp = base_fsp;
3793 if ((ea_list != NULL) &&
3794 ((info == FILE_WAS_CREATED) || (info == FILE_WAS_OVERWRITTEN))) {
3795 status = set_ea(conn, fsp, fsp->fsp_name, ea_list);
3796 if (!NT_STATUS_IS_OK(status)) {
3797 goto fail;
3801 if (!fsp->is_directory && S_ISDIR(fsp->fsp_name->st.st_ex_mode)) {
3802 status = NT_STATUS_ACCESS_DENIED;
3803 goto fail;
3806 /* Save the requested allocation size. */
3807 if ((info == FILE_WAS_CREATED) || (info == FILE_WAS_OVERWRITTEN)) {
3808 if (allocation_size
3809 && (allocation_size > fsp->fsp_name->st.st_ex_size)) {
3810 fsp->initial_allocation_size = smb_roundup(
3811 fsp->conn, allocation_size);
3812 if (fsp->is_directory) {
3813 /* Can't set allocation size on a directory. */
3814 status = NT_STATUS_ACCESS_DENIED;
3815 goto fail;
3817 if (vfs_allocate_file_space(
3818 fsp, fsp->initial_allocation_size) == -1) {
3819 status = NT_STATUS_DISK_FULL;
3820 goto fail;
3822 } else {
3823 fsp->initial_allocation_size = smb_roundup(
3824 fsp->conn, (uint64_t)fsp->fsp_name->st.st_ex_size);
3826 } else {
3827 fsp->initial_allocation_size = 0;
3830 if ((info == FILE_WAS_CREATED) && lp_nt_acl_support(SNUM(conn)) &&
3831 fsp->base_fsp == NULL) {
3832 if (sd != NULL) {
3834 * According to the MS documentation, the only time the security
3835 * descriptor is applied to the opened file is iff we *created* the
3836 * file; an existing file stays the same.
3838 * Also, it seems (from observation) that you can open the file with
3839 * any access mask but you can still write the sd. We need to override
3840 * the granted access before we call set_sd
3841 * Patch for bug #2242 from Tom Lackemann <cessnatomny@yahoo.com>.
3844 uint32_t sec_info_sent;
3845 uint32_t saved_access_mask = fsp->access_mask;
3847 sec_info_sent = get_sec_info(sd);
3849 fsp->access_mask = FILE_GENERIC_ALL;
3851 if (sec_info_sent & (SECINFO_OWNER|
3852 SECINFO_GROUP|
3853 SECINFO_DACL|
3854 SECINFO_SACL)) {
3855 status = set_sd(fsp, sd, sec_info_sent);
3858 fsp->access_mask = saved_access_mask;
3860 if (!NT_STATUS_IS_OK(status)) {
3861 goto fail;
3863 } else if (lp_inherit_acls(SNUM(conn))) {
3864 /* Inherit from parent. Errors here are not fatal. */
3865 status = inherit_new_acl(fsp);
3866 if (!NT_STATUS_IS_OK(status)) {
3867 DEBUG(10,("inherit_new_acl: failed for %s with %s\n",
3868 fsp_str_dbg(fsp),
3869 nt_errstr(status) ));
3874 DEBUG(10, ("create_file_unixpath: info=%d\n", info));
3876 *result = fsp;
3877 if (pinfo != NULL) {
3878 *pinfo = info;
3881 smb_fname->st = fsp->fsp_name->st;
3883 return NT_STATUS_OK;
3885 fail:
3886 DEBUG(10, ("create_file_unixpath: %s\n", nt_errstr(status)));
3888 if (fsp != NULL) {
3889 if (base_fsp && fsp->base_fsp == base_fsp) {
3891 * The close_file below will close
3892 * fsp->base_fsp.
3894 base_fsp = NULL;
3896 close_file(req, fsp, ERROR_CLOSE);
3897 fsp = NULL;
3899 if (base_fsp != NULL) {
3900 close_file(req, base_fsp, ERROR_CLOSE);
3901 base_fsp = NULL;
3903 return status;
3907 * Calculate the full path name given a relative fid.
3909 NTSTATUS get_relative_fid_filename(connection_struct *conn,
3910 struct smb_request *req,
3911 uint16_t root_dir_fid,
3912 const struct smb_filename *smb_fname,
3913 struct smb_filename **smb_fname_out)
3915 files_struct *dir_fsp;
3916 char *parent_fname = NULL;
3917 char *new_base_name = NULL;
3918 NTSTATUS status;
3920 if (root_dir_fid == 0 || !smb_fname) {
3921 status = NT_STATUS_INTERNAL_ERROR;
3922 goto out;
3925 dir_fsp = file_fsp(req, root_dir_fid);
3927 if (dir_fsp == NULL) {
3928 status = NT_STATUS_INVALID_HANDLE;
3929 goto out;
3932 if (is_ntfs_stream_smb_fname(dir_fsp->fsp_name)) {
3933 status = NT_STATUS_INVALID_HANDLE;
3934 goto out;
3937 if (!dir_fsp->is_directory) {
3940 * Check to see if this is a mac fork of some kind.
3943 if ((conn->fs_capabilities & FILE_NAMED_STREAMS) &&
3944 is_ntfs_stream_smb_fname(smb_fname)) {
3945 status = NT_STATUS_OBJECT_PATH_NOT_FOUND;
3946 goto out;
3950 we need to handle the case when we get a
3951 relative open relative to a file and the
3952 pathname is blank - this is a reopen!
3953 (hint from demyn plantenberg)
3956 status = NT_STATUS_INVALID_HANDLE;
3957 goto out;
3960 if (ISDOT(dir_fsp->fsp_name->base_name)) {
3962 * We're at the toplevel dir, the final file name
3963 * must not contain ./, as this is filtered out
3964 * normally by srvstr_get_path and unix_convert
3965 * explicitly rejects paths containing ./.
3967 parent_fname = talloc_strdup(talloc_tos(), "");
3968 if (parent_fname == NULL) {
3969 status = NT_STATUS_NO_MEMORY;
3970 goto out;
3972 } else {
3973 size_t dir_name_len = strlen(dir_fsp->fsp_name->base_name);
3976 * Copy in the base directory name.
3979 parent_fname = talloc_array(talloc_tos(), char,
3980 dir_name_len+2);
3981 if (parent_fname == NULL) {
3982 status = NT_STATUS_NO_MEMORY;
3983 goto out;
3985 memcpy(parent_fname, dir_fsp->fsp_name->base_name,
3986 dir_name_len+1);
3989 * Ensure it ends in a '/'.
3990 * We used TALLOC_SIZE +2 to add space for the '/'.
3993 if(dir_name_len
3994 && (parent_fname[dir_name_len-1] != '\\')
3995 && (parent_fname[dir_name_len-1] != '/')) {
3996 parent_fname[dir_name_len] = '/';
3997 parent_fname[dir_name_len+1] = '\0';
4001 new_base_name = talloc_asprintf(talloc_tos(), "%s%s", parent_fname,
4002 smb_fname->base_name);
4003 if (new_base_name == NULL) {
4004 status = NT_STATUS_NO_MEMORY;
4005 goto out;
4008 status = filename_convert(req,
4009 conn,
4010 req->flags2 & FLAGS2_DFS_PATHNAMES,
4011 new_base_name,
4013 NULL,
4014 smb_fname_out);
4015 if (!NT_STATUS_IS_OK(status)) {
4016 goto out;
4019 out:
4020 TALLOC_FREE(parent_fname);
4021 TALLOC_FREE(new_base_name);
4022 return status;
4025 NTSTATUS create_file_default(connection_struct *conn,
4026 struct smb_request *req,
4027 uint16_t root_dir_fid,
4028 struct smb_filename *smb_fname,
4029 uint32_t access_mask,
4030 uint32_t share_access,
4031 uint32_t create_disposition,
4032 uint32_t create_options,
4033 uint32_t file_attributes,
4034 uint32_t oplock_request,
4035 uint64_t allocation_size,
4036 uint32_t private_flags,
4037 struct security_descriptor *sd,
4038 struct ea_list *ea_list,
4039 files_struct **result,
4040 int *pinfo)
4042 int info = FILE_WAS_OPENED;
4043 files_struct *fsp = NULL;
4044 NTSTATUS status;
4045 bool stream_name = false;
4047 DEBUG(10,("create_file: access_mask = 0x%x "
4048 "file_attributes = 0x%x, share_access = 0x%x, "
4049 "create_disposition = 0x%x create_options = 0x%x "
4050 "oplock_request = 0x%x "
4051 "private_flags = 0x%x "
4052 "root_dir_fid = 0x%x, ea_list = 0x%p, sd = 0x%p, "
4053 "fname = %s\n",
4054 (unsigned int)access_mask,
4055 (unsigned int)file_attributes,
4056 (unsigned int)share_access,
4057 (unsigned int)create_disposition,
4058 (unsigned int)create_options,
4059 (unsigned int)oplock_request,
4060 (unsigned int)private_flags,
4061 (unsigned int)root_dir_fid,
4062 ea_list, sd, smb_fname_str_dbg(smb_fname)));
4065 * Calculate the filename from the root_dir_if if necessary.
4068 if (root_dir_fid != 0) {
4069 struct smb_filename *smb_fname_out = NULL;
4070 status = get_relative_fid_filename(conn, req, root_dir_fid,
4071 smb_fname, &smb_fname_out);
4072 if (!NT_STATUS_IS_OK(status)) {
4073 goto fail;
4075 smb_fname = smb_fname_out;
4079 * Check to see if this is a mac fork of some kind.
4082 stream_name = is_ntfs_stream_smb_fname(smb_fname);
4083 if (stream_name) {
4084 enum FAKE_FILE_TYPE fake_file_type;
4086 fake_file_type = is_fake_file(smb_fname);
4088 if (fake_file_type != FAKE_FILE_TYPE_NONE) {
4091 * Here we go! support for changing the disk quotas
4092 * --metze
4094 * We need to fake up to open this MAGIC QUOTA file
4095 * and return a valid FID.
4097 * w2k close this file directly after openening xp
4098 * also tries a QUERY_FILE_INFO on the file and then
4099 * close it
4101 status = open_fake_file(req, conn, req->vuid,
4102 fake_file_type, smb_fname,
4103 access_mask, &fsp);
4104 if (!NT_STATUS_IS_OK(status)) {
4105 goto fail;
4108 ZERO_STRUCT(smb_fname->st);
4109 goto done;
4112 if (!(conn->fs_capabilities & FILE_NAMED_STREAMS)) {
4113 status = NT_STATUS_OBJECT_NAME_NOT_FOUND;
4114 goto fail;
4118 if (is_ntfs_default_stream_smb_fname(smb_fname)) {
4119 int ret;
4120 smb_fname->stream_name = NULL;
4121 /* We have to handle this error here. */
4122 if (create_options & FILE_DIRECTORY_FILE) {
4123 status = NT_STATUS_NOT_A_DIRECTORY;
4124 goto fail;
4126 if (lp_posix_pathnames()) {
4127 ret = SMB_VFS_LSTAT(conn, smb_fname);
4128 } else {
4129 ret = SMB_VFS_STAT(conn, smb_fname);
4132 if (ret == 0 && VALID_STAT_OF_DIR(smb_fname->st)) {
4133 status = NT_STATUS_FILE_IS_A_DIRECTORY;
4134 goto fail;
4138 status = create_file_unixpath(
4139 conn, req, smb_fname, access_mask, share_access,
4140 create_disposition, create_options, file_attributes,
4141 oplock_request, allocation_size, private_flags,
4142 sd, ea_list,
4143 &fsp, &info);
4145 if (!NT_STATUS_IS_OK(status)) {
4146 goto fail;
4149 done:
4150 DEBUG(10, ("create_file: info=%d\n", info));
4152 *result = fsp;
4153 if (pinfo != NULL) {
4154 *pinfo = info;
4156 return NT_STATUS_OK;
4158 fail:
4159 DEBUG(10, ("create_file: %s\n", nt_errstr(status)));
4161 if (fsp != NULL) {
4162 close_file(req, fsp, ERROR_CLOSE);
4163 fsp = NULL;
4165 return status;