]> git.ipfire.org Git - thirdparty/samba.git/blob
20b5a3e294c
[thirdparty/samba.git] /
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
7 Copyright (C) Ralph Boehme 2017
8
9 This program is free software; you can redistribute it and/or modify
10 it under the terms of the GNU General Public License as published by
11 the Free Software Foundation; either version 3 of the License, or
12 (at your option) any later version.
13
14 This program is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 GNU General Public License for more details.
18
19 You should have received a copy of the GNU General Public License
20 along with this program. If not, see <http://www.gnu.org/licenses/>.
21 */
22
23 #include "includes.h"
24 #include "smb1_utils.h"
25 #include "system/filesys.h"
26 #include "lib/util/server_id.h"
27 #include "printing.h"
28 #include "smbd/smbd.h"
29 #include "smbd/globals.h"
30 #include "fake_file.h"
31 #include "../libcli/security/security.h"
32 #include "../librpc/gen_ndr/ndr_security.h"
33 #include "../librpc/gen_ndr/ndr_open_files.h"
34 #include "../librpc/gen_ndr/idmap.h"
35 #include "../librpc/gen_ndr/ioctl.h"
36 #include "passdb/lookup_sid.h"
37 #include "auth.h"
38 #include "serverid.h"
39 #include "messages.h"
40 #include "source3/lib/dbwrap/dbwrap_watch.h"
41 #include "locking/leases_db.h"
42 #include "librpc/gen_ndr/ndr_leases_db.h"
43 #include "lib/util/time_basic.h"
44
45 extern const struct generic_mapping file_generic_mapping;
46
47 struct deferred_open_record {
48 struct smbXsrv_connection *xconn;
49 uint64_t mid;
50
51 bool async_open;
52
53 /*
54 * Timer for async opens, needed because they don't use a watch on
55 * a locking.tdb record. This is currently only used for real async
56 * opens and just terminates smbd if the async open times out.
57 */
58 struct tevent_timer *te;
59
60 /*
61 * For the samba kernel oplock case we use both a timeout and
62 * a watch on locking.tdb. This way in case it's smbd holding
63 * the kernel oplock we get directly notified for the retry
64 * once the kernel oplock is properly broken. Store the req
65 * here so that it can be timely discarded once the timer
66 * above fires.
67 */
68 struct tevent_req *watch_req;
69 };
70
71 /****************************************************************************
72 If the requester wanted DELETE_ACCESS and was rejected because
73 the file ACL didn't include DELETE_ACCESS, see if the parent ACL
74 overrides this.
75 ****************************************************************************/
76
77 static bool parent_override_delete(connection_struct *conn,
78 const struct smb_filename *smb_fname,
79 uint32_t access_mask,
80 uint32_t rejected_mask)
81 {
82 if ((access_mask & DELETE_ACCESS) &&
83 (rejected_mask & DELETE_ACCESS) &&
84 can_delete_file_in_directory(conn, smb_fname)) {
85 return true;
86 }
87 return false;
88 }
89
90 /****************************************************************************
91 Check if we have open rights.
92 ****************************************************************************/
93
94 NTSTATUS smbd_check_access_rights(struct connection_struct *conn,
95 const struct smb_filename *smb_fname,
96 bool use_privs,
97 uint32_t access_mask)
98 {
99 /* Check if we have rights to open. */
100 NTSTATUS status;
101 struct security_descriptor *sd = NULL;
102 uint32_t rejected_share_access;
103 uint32_t rejected_mask = access_mask;
104 uint32_t do_not_check_mask = 0;
105
106 rejected_share_access = access_mask & ~(conn->share_access);
107
108 if (rejected_share_access) {
109 DEBUG(10, ("smbd_check_access_rights: rejected share access 0x%x "
110 "on %s (0x%x)\n",
111 (unsigned int)access_mask,
112 smb_fname_str_dbg(smb_fname),
113 (unsigned int)rejected_share_access ));
114 return NT_STATUS_ACCESS_DENIED;
115 }
116
117 if (!use_privs && get_current_uid(conn) == (uid_t)0) {
118 /* I'm sorry sir, I didn't know you were root... */
119 DEBUG(10,("smbd_check_access_rights: root override "
120 "on %s. Granting 0x%x\n",
121 smb_fname_str_dbg(smb_fname),
122 (unsigned int)access_mask ));
123 return NT_STATUS_OK;
124 }
125
126 if ((access_mask & DELETE_ACCESS) && !lp_acl_check_permissions(SNUM(conn))) {
127 DEBUG(10,("smbd_check_access_rights: not checking ACL "
128 "on DELETE_ACCESS on file %s. Granting 0x%x\n",
129 smb_fname_str_dbg(smb_fname),
130 (unsigned int)access_mask ));
131 return NT_STATUS_OK;
132 }
133
134 if (access_mask == DELETE_ACCESS &&
135 VALID_STAT(smb_fname->st) &&
136 S_ISLNK(smb_fname->st.st_ex_mode)) {
137 /* We can always delete a symlink. */
138 DEBUG(10,("smbd_check_access_rights: not checking ACL "
139 "on DELETE_ACCESS on symlink %s.\n",
140 smb_fname_str_dbg(smb_fname) ));
141 return NT_STATUS_OK;
142 }
143
144 status = SMB_VFS_GET_NT_ACL(conn, smb_fname,
145 (SECINFO_OWNER |
146 SECINFO_GROUP |
147 SECINFO_DACL), talloc_tos(), &sd);
148
149 if (!NT_STATUS_IS_OK(status)) {
150 DEBUG(10, ("smbd_check_access_rights: Could not get acl "
151 "on %s: %s\n",
152 smb_fname_str_dbg(smb_fname),
153 nt_errstr(status)));
154
155 if (NT_STATUS_EQUAL(status, NT_STATUS_ACCESS_DENIED)) {
156 goto access_denied;
157 }
158
159 return status;
160 }
161
162 /*
163 * If we can access the path to this file, by
164 * default we have FILE_READ_ATTRIBUTES from the
165 * containing directory. See the section:
166 * "Algorithm to Check Access to an Existing File"
167 * in MS-FSA.pdf.
168 *
169 * se_file_access_check() also takes care of
170 * owner WRITE_DAC and READ_CONTROL.
171 */
172 do_not_check_mask = FILE_READ_ATTRIBUTES;
173
174 /*
175 * Samba 3.6 and earlier granted execute access even
176 * if the ACL did not contain execute rights.
177 * Samba 4.0 is more correct and checks it.
178 * The compatibilty mode allows one to skip this check
179 * to smoothen upgrades.
180 */
181 if (lp_acl_allow_execute_always(SNUM(conn))) {
182 do_not_check_mask |= FILE_EXECUTE;
183 }
184
185 status = se_file_access_check(sd,
186 get_current_nttok(conn),
187 use_privs,
188 (access_mask & ~do_not_check_mask),
189 &rejected_mask);
190
191 DEBUG(10,("smbd_check_access_rights: file %s requesting "
192 "0x%x returning 0x%x (%s)\n",
193 smb_fname_str_dbg(smb_fname),
194 (unsigned int)access_mask,
195 (unsigned int)rejected_mask,
196 nt_errstr(status) ));
197
198 if (!NT_STATUS_IS_OK(status)) {
199 if (DEBUGLEVEL >= 10) {
200 DEBUG(10,("smbd_check_access_rights: acl for %s is:\n",
201 smb_fname_str_dbg(smb_fname) ));
202 NDR_PRINT_DEBUG(security_descriptor, sd);
203 }
204 }
205
206 TALLOC_FREE(sd);
207
208 if (NT_STATUS_IS_OK(status) ||
209 !NT_STATUS_EQUAL(status, NT_STATUS_ACCESS_DENIED)) {
210 return status;
211 }
212
213 /* Here we know status == NT_STATUS_ACCESS_DENIED. */
214
215 access_denied:
216
217 if ((access_mask & FILE_WRITE_ATTRIBUTES) &&
218 (rejected_mask & FILE_WRITE_ATTRIBUTES) &&
219 !lp_store_dos_attributes(SNUM(conn)) &&
220 (lp_map_readonly(SNUM(conn)) ||
221 lp_map_archive(SNUM(conn)) ||
222 lp_map_hidden(SNUM(conn)) ||
223 lp_map_system(SNUM(conn)))) {
224 rejected_mask &= ~FILE_WRITE_ATTRIBUTES;
225
226 DEBUG(10,("smbd_check_access_rights: "
227 "overrode "
228 "FILE_WRITE_ATTRIBUTES "
229 "on file %s\n",
230 smb_fname_str_dbg(smb_fname)));
231 }
232
233 if (parent_override_delete(conn,
234 smb_fname,
235 access_mask,
236 rejected_mask)) {
237 /* Were we trying to do an open
238 * for delete and didn't get DELETE
239 * access (only) ? Check if the
240 * directory allows DELETE_CHILD.
241 * See here:
242 * http://blogs.msdn.com/oldnewthing/archive/2004/06/04/148426.aspx
243 * for details. */
244
245 rejected_mask &= ~DELETE_ACCESS;
246
247 DEBUG(10,("smbd_check_access_rights: "
248 "overrode "
249 "DELETE_ACCESS on "
250 "file %s\n",
251 smb_fname_str_dbg(smb_fname)));
252 }
253
254 if (rejected_mask != 0) {
255 return NT_STATUS_ACCESS_DENIED;
256 }
257 return NT_STATUS_OK;
258 }
259
260 NTSTATUS check_parent_access(struct connection_struct *conn,
261 struct smb_filename *smb_fname,
262 uint32_t access_mask)
263 {
264 NTSTATUS status;
265 char *parent_dir = NULL;
266 struct security_descriptor *parent_sd = NULL;
267 uint32_t access_granted = 0;
268 struct smb_filename *parent_smb_fname = NULL;
269 struct share_mode_lock *lck = NULL;
270 struct file_id id = {0};
271 uint32_t name_hash;
272 bool delete_on_close_set;
273 int ret;
274 TALLOC_CTX *frame = talloc_stackframe();
275
276 if (!parent_dirname(frame,
277 smb_fname->base_name,
278 &parent_dir,
279 NULL)) {
280 status = NT_STATUS_NO_MEMORY;
281 goto out;
282 }
283
284 parent_smb_fname = synthetic_smb_fname(frame,
285 parent_dir,
286 NULL,
287 NULL,
288 smb_fname->flags);
289 if (parent_smb_fname == NULL) {
290 status = NT_STATUS_NO_MEMORY;
291 goto out;
292 }
293
294 if (get_current_uid(conn) == (uid_t)0) {
295 /* I'm sorry sir, I didn't know you were root... */
296 DEBUG(10,("check_parent_access: root override "
297 "on %s. Granting 0x%x\n",
298 smb_fname_str_dbg(smb_fname),
299 (unsigned int)access_mask ));
300 status = NT_STATUS_OK;
301 goto out;
302 }
303
304 status = SMB_VFS_GET_NT_ACL(conn,
305 parent_smb_fname,
306 SECINFO_DACL,
307 frame,
308 &parent_sd);
309
310 if (!NT_STATUS_IS_OK(status)) {
311 DEBUG(5,("check_parent_access: SMB_VFS_GET_NT_ACL failed for "
312 "%s with error %s\n",
313 parent_dir,
314 nt_errstr(status)));
315 goto out;
316 }
317
318 /*
319 * If we can access the path to this file, by
320 * default we have FILE_READ_ATTRIBUTES from the
321 * containing directory. See the section:
322 * "Algorithm to Check Access to an Existing File"
323 * in MS-FSA.pdf.
324 *
325 * se_file_access_check() also takes care of
326 * owner WRITE_DAC and READ_CONTROL.
327 */
328 status = se_file_access_check(parent_sd,
329 get_current_nttok(conn),
330 false,
331 (access_mask & ~FILE_READ_ATTRIBUTES),
332 &access_granted);
333 if(!NT_STATUS_IS_OK(status)) {
334 DEBUG(5,("check_parent_access: access check "
335 "on directory %s for "
336 "path %s for mask 0x%x returned (0x%x) %s\n",
337 parent_dir,
338 smb_fname->base_name,
339 access_mask,
340 access_granted,
341 nt_errstr(status) ));
342 goto out;
343 }
344
345 if (!(access_mask & (SEC_DIR_ADD_FILE | SEC_DIR_ADD_SUBDIR))) {
346 status = NT_STATUS_OK;
347 goto out;
348 }
349 if (!lp_check_parent_directory_delete_on_close(SNUM(conn))) {
350 status = NT_STATUS_OK;
351 goto out;
352 }
353
354 /* Check if the directory has delete-on-close set */
355 ret = SMB_VFS_STAT(conn, parent_smb_fname);
356 if (ret != 0) {
357 status = map_nt_error_from_unix(errno);
358 goto out;
359 }
360
361 id = SMB_VFS_FILE_ID_CREATE(conn, &parent_smb_fname->st);
362
363 status = file_name_hash(conn, parent_smb_fname->base_name, &name_hash);
364 if (!NT_STATUS_IS_OK(status)) {
365 goto out;
366 }
367
368 lck = get_existing_share_mode_lock(frame, id);
369 if (lck == NULL) {
370 status = NT_STATUS_OK;
371 goto out;
372 }
373
374 delete_on_close_set = is_delete_on_close_set(lck, name_hash);
375 if (delete_on_close_set) {
376 status = NT_STATUS_DELETE_PENDING;
377 goto out;
378 }
379
380 status = NT_STATUS_OK;
381
382 out:
383 TALLOC_FREE(frame);
384 return status;
385 }
386
387 /****************************************************************************
388 Ensure when opening a base file for a stream open that we have permissions
389 to do so given the access mask on the base file.
390 ****************************************************************************/
391
392 static NTSTATUS check_base_file_access(struct connection_struct *conn,
393 struct smb_filename *smb_fname,
394 uint32_t access_mask)
395 {
396 NTSTATUS status;
397
398 status = smbd_calculate_access_mask(conn, smb_fname,
399 false,
400 access_mask,
401 &access_mask);
402 if (!NT_STATUS_IS_OK(status)) {
403 DEBUG(10, ("smbd_calculate_access_mask "
404 "on file %s returned %s\n",
405 smb_fname_str_dbg(smb_fname),
406 nt_errstr(status)));
407 return status;
408 }
409
410 if (access_mask & (FILE_WRITE_DATA|FILE_APPEND_DATA)) {
411 uint32_t dosattrs;
412 if (!CAN_WRITE(conn)) {
413 return NT_STATUS_ACCESS_DENIED;
414 }
415 dosattrs = dos_mode(conn, smb_fname);
416 if (IS_DOS_READONLY(dosattrs)) {
417 return NT_STATUS_ACCESS_DENIED;
418 }
419 }
420
421 return smbd_check_access_rights(conn,
422 smb_fname,
423 false,
424 access_mask);
425 }
426
427 /****************************************************************************
428 Handle differing symlink errno's
429 ****************************************************************************/
430
431 static int link_errno_convert(int err)
432 {
433 #if defined(ENOTSUP) && defined(OSF1)
434 /* handle special Tru64 errno */
435 if (err == ENOTSUP) {
436 err = ELOOP;
437 }
438 #endif /* ENOTSUP */
439 #ifdef EFTYPE
440 /* fix broken NetBSD errno */
441 if (err == EFTYPE) {
442 err = ELOOP;
443 }
444 #endif /* EFTYPE */
445 /* fix broken FreeBSD errno */
446 if (err == EMLINK) {
447 err = ELOOP;
448 }
449 return err;
450 }
451
452 static int non_widelink_open(struct connection_struct *conn,
453 const struct smb_filename *conn_rootdir_fname,
454 files_struct *fsp,
455 struct smb_filename *smb_fname,
456 int flags,
457 mode_t mode,
458 unsigned int link_depth);
459
460 /****************************************************************************
461 Follow a symlink in userspace.
462 ****************************************************************************/
463
464 static int process_symlink_open(struct connection_struct *conn,
465 const struct smb_filename *conn_rootdir_fname,
466 files_struct *fsp,
467 struct smb_filename *smb_fname,
468 int flags,
469 mode_t mode,
470 unsigned int link_depth)
471 {
472 int fd = -1;
473 char *link_target = NULL;
474 struct smb_filename target_fname = {0};
475 int link_len = -1;
476 struct smb_filename *oldwd_fname = NULL;
477 size_t rootdir_len = 0;
478 struct smb_filename *resolved_fname = NULL;
479 char *resolved_name = NULL;
480 bool matched = false;
481 int saved_errno = 0;
482
483 /*
484 * Ensure we don't get stuck in a symlink loop.
485 */
486 link_depth++;
487 if (link_depth >= 20) {
488 errno = ELOOP;
489 goto out;
490 }
491
492 /* Allocate space for the link target. */
493 link_target = talloc_array(talloc_tos(), char, PATH_MAX);
494 if (link_target == NULL) {
495 errno = ENOMEM;
496 goto out;
497 }
498
499 /* Read the link target. */
500 link_len = SMB_VFS_READLINKAT(conn,
501 conn->cwd_fsp,
502 smb_fname,
503 link_target,
504 PATH_MAX - 1);
505 if (link_len == -1) {
506 goto out;
507 }
508
509 /* Ensure it's at least null terminated. */
510 link_target[link_len] = '\0';
511 target_fname = (struct smb_filename){ .base_name = link_target };
512
513 /* Convert to an absolute path. */
514 resolved_fname = SMB_VFS_REALPATH(conn, talloc_tos(), &target_fname);
515 if (resolved_fname == NULL) {
516 goto out;
517 }
518 resolved_name = resolved_fname->base_name;
519
520 /*
521 * We know conn_rootdir starts with '/' and
522 * does not end in '/'. FIXME ! Should we
523 * smb_assert this ?
524 */
525 rootdir_len = strlen(conn_rootdir_fname->base_name);
526
527 matched = (strncmp(conn_rootdir_fname->base_name,
528 resolved_name,
529 rootdir_len) == 0);
530 if (!matched) {
531 errno = EACCES;
532 goto out;
533 }
534
535 /*
536 * Turn into a path relative to the share root.
537 */
538 if (resolved_name[rootdir_len] == '\0') {
539 /* Link to the root of the share. */
540 TALLOC_FREE(smb_fname->base_name);
541 smb_fname->base_name = talloc_strdup(smb_fname, ".");
542 } else if (resolved_name[rootdir_len] == '/') {
543 TALLOC_FREE(smb_fname->base_name);
544 smb_fname->base_name = talloc_strdup(smb_fname,
545 &resolved_name[rootdir_len+1]);
546 } else {
547 errno = EACCES;
548 goto out;
549 }
550
551 if (smb_fname->base_name == NULL) {
552 errno = ENOMEM;
553 goto out;
554 }
555
556 oldwd_fname = vfs_GetWd(talloc_tos(), conn);
557 if (oldwd_fname == NULL) {
558 goto out;
559 }
560
561 /* Ensure we operate from the root of the share. */
562 if (vfs_ChDir(conn, conn_rootdir_fname) == -1) {
563 goto out;
564 }
565
566 /* And do it all again.. */
567 fd = non_widelink_open(conn,
568 conn_rootdir_fname,
569 fsp,
570 smb_fname,
571 flags,
572 mode,
573 link_depth);
574 if (fd == -1) {
575 saved_errno = errno;
576 }
577
578 out:
579
580 TALLOC_FREE(resolved_fname);
581 TALLOC_FREE(link_target);
582 if (oldwd_fname != NULL) {
583 int ret = vfs_ChDir(conn, oldwd_fname);
584 if (ret == -1) {
585 smb_panic("unable to get back to old directory\n");
586 }
587 TALLOC_FREE(oldwd_fname);
588 }
589 if (saved_errno != 0) {
590 errno = saved_errno;
591 }
592 return fd;
593 }
594
595 /****************************************************************************
596 Non-widelink open.
597 ****************************************************************************/
598
599 static int non_widelink_open(struct connection_struct *conn,
600 const struct smb_filename *conn_rootdir_fname,
601 files_struct *fsp,
602 struct smb_filename *smb_fname,
603 int flags,
604 mode_t mode,
605 unsigned int link_depth)
606 {
607 NTSTATUS status;
608 int fd = -1;
609 struct smb_filename *smb_fname_rel = NULL;
610 int saved_errno = 0;
611 struct smb_filename *oldwd_fname = NULL;
612 char *parent_dir = NULL;
613 struct smb_filename parent_dir_fname = {0};
614 const char *final_component = NULL;
615 bool is_directory = false;
616 bool ok;
617
618 #ifdef O_DIRECTORY
619 if (flags & O_DIRECTORY) {
620 is_directory = true;
621 }
622 #endif
623
624 if (is_directory) {
625 parent_dir = talloc_strdup(talloc_tos(), smb_fname->base_name);
626 if (parent_dir == NULL) {
627 saved_errno = errno;
628 goto out;
629 }
630
631 final_component = ".";
632 } else {
633 ok = parent_dirname(talloc_tos(),
634 smb_fname->base_name,
635 &parent_dir,
636 &final_component);
637 if (!ok) {
638 saved_errno = errno;
639 goto out;
640 }
641 }
642
643 parent_dir_fname = (struct smb_filename) { .base_name = parent_dir };
644
645 oldwd_fname = vfs_GetWd(talloc_tos(), conn);
646 if (oldwd_fname == NULL) {
647 goto out;
648 }
649
650 /* Pin parent directory in place. */
651 if (vfs_ChDir(conn, &parent_dir_fname) == -1) {
652 goto out;
653 }
654
655 smb_fname_rel = synthetic_smb_fname(talloc_tos(),
656 final_component,
657 smb_fname->stream_name,
658 &smb_fname->st,
659 smb_fname->flags);
660 if (smb_fname_rel == NULL) {
661 saved_errno = ENOMEM;
662 goto out;
663 }
664
665 /* Ensure the relative path is below the share. */
666 status = check_reduced_name(conn, &parent_dir_fname, smb_fname_rel);
667 if (!NT_STATUS_IS_OK(status)) {
668 saved_errno = map_errno_from_nt_status(status);
669 goto out;
670 }
671
672 flags |= O_NOFOLLOW;
673
674 {
675 struct smb_filename *tmp_name = fsp->fsp_name;
676 fsp->fsp_name = smb_fname_rel;
677 fd = SMB_VFS_OPEN(conn, smb_fname_rel, fsp, flags, mode);
678 fsp->fsp_name = tmp_name;
679 }
680
681 if (fd == -1) {
682 saved_errno = link_errno_convert(errno);
683 /*
684 * Trying to open a symlink to a directory with O_NOFOLLOW and
685 * O_DIRECTORY can return either of ELOOP and ENOTDIR. So
686 * ENOTDIR really means: might be a symlink, but we're not sure.
687 * In this case, we just assume there's a symlink. If we were
688 * wrong, process_symlink_open() will return EINVAL. We check
689 * this below, and fall back to returning the initial
690 * saved_errno.
691 *
692 * BUG: https://bugzilla.samba.org/show_bug.cgi?id=12860
693 */
694 if (saved_errno == ELOOP || saved_errno == ENOTDIR) {
695 if (fsp->posix_flags & FSP_POSIX_FLAGS_OPEN) {
696 /* Never follow symlinks on posix open. */
697 goto out;
698 }
699 if (!lp_follow_symlinks(SNUM(conn))) {
700 /* Explicitly no symlinks. */
701 goto out;
702 }
703 /*
704 * We may have a symlink. Follow in userspace
705 * to ensure it's under the share definition.
706 */
707 fd = process_symlink_open(conn,
708 conn_rootdir_fname,
709 fsp,
710 smb_fname_rel,
711 flags,
712 mode,
713 link_depth);
714 if (fd == -1) {
715 if (saved_errno == ENOTDIR &&
716 errno == EINVAL) {
717 /*
718 * O_DIRECTORY on neither a directory,
719 * nor a symlink. Just return
720 * saved_errno from initial open()
721 */
722 goto out;
723 }
724 saved_errno =
725 link_errno_convert(errno);
726 }
727 }
728 }
729
730 out:
731
732 TALLOC_FREE(parent_dir);
733 TALLOC_FREE(smb_fname_rel);
734
735 if (oldwd_fname != NULL) {
736 int ret = vfs_ChDir(conn, oldwd_fname);
737 if (ret == -1) {
738 smb_panic("unable to get back to old directory\n");
739 }
740 TALLOC_FREE(oldwd_fname);
741 }
742 if (saved_errno != 0) {
743 errno = saved_errno;
744 }
745 return fd;
746 }
747
748 /****************************************************************************
749 fd support routines - attempt to do a dos_open.
750 ****************************************************************************/
751
752 NTSTATUS fd_open(struct connection_struct *conn,
753 files_struct *fsp,
754 int flags,
755 mode_t mode)
756 {
757 struct smb_filename *smb_fname = fsp->fsp_name;
758 NTSTATUS status = NT_STATUS_OK;
759
760 /*
761 * Never follow symlinks on a POSIX client. The
762 * client should be doing this.
763 */
764
765 if ((fsp->posix_flags & FSP_POSIX_FLAGS_OPEN) || !lp_follow_symlinks(SNUM(conn))) {
766 flags |= O_NOFOLLOW;
767 }
768
769 /* Ensure path is below share definition. */
770 if (!lp_widelinks(SNUM(conn))) {
771 struct smb_filename *conn_rootdir_fname = NULL;
772 const char *conn_rootdir = SMB_VFS_CONNECTPATH(conn,
773 smb_fname);
774 int saved_errno = 0;
775
776 if (conn_rootdir == NULL) {
777 return NT_STATUS_NO_MEMORY;
778 }
779 conn_rootdir_fname = synthetic_smb_fname(talloc_tos(),
780 conn_rootdir,
781 NULL,
782 NULL,
783 0);
784 if (conn_rootdir_fname == NULL) {
785 return NT_STATUS_NO_MEMORY;
786 }
787
788 /*
789 * Only follow symlinks within a share
790 * definition.
791 */
792 fsp->fh->fd = non_widelink_open(conn,
793 conn_rootdir_fname,
794 fsp,
795 smb_fname,
796 flags,
797 mode,
798 0);
799 if (fsp->fh->fd == -1) {
800 saved_errno = errno;
801 }
802 TALLOC_FREE(conn_rootdir_fname);
803 if (saved_errno != 0) {
804 errno = saved_errno;
805 }
806 } else {
807 fsp->fh->fd = SMB_VFS_OPEN(conn, smb_fname, fsp, flags, mode);
808 }
809
810 if (fsp->fh->fd == -1) {
811 int posix_errno = link_errno_convert(errno);
812 status = map_nt_error_from_unix(posix_errno);
813 if (errno == EMFILE) {
814 static time_t last_warned = 0L;
815
816 if (time((time_t *) NULL) > last_warned) {
817 DEBUG(0,("Too many open files, unable "
818 "to open more! smbd's max "
819 "open files = %d\n",
820 lp_max_open_files()));
821 last_warned = time((time_t *) NULL);
822 }
823 }
824
825 }
826
827 DEBUG(10,("fd_open: name %s, flags = 0%o mode = 0%o, fd = %d. %s\n",
828 smb_fname_str_dbg(smb_fname), flags, (int)mode, fsp->fh->fd,
829 (fsp->fh->fd == -1) ? strerror(errno) : "" ));
830
831 return status;
832 }
833
834 /****************************************************************************
835 Close the file associated with a fsp.
836 ****************************************************************************/
837
838 NTSTATUS fd_close(files_struct *fsp)
839 {
840 int ret;
841
842 if (fsp->dptr) {
843 dptr_CloseDir(fsp);
844 }
845 if (fsp->fh->fd == -1) {
846 /*
847 * Either a directory where the dptr_CloseDir() already closed
848 * the fd or a stat open.
849 */
850 return NT_STATUS_OK;
851 }
852 if (fsp->fh->ref_count > 1) {
853 return NT_STATUS_OK; /* Shared handle. Only close last reference. */
854 }
855
856 ret = SMB_VFS_CLOSE(fsp);
857 fsp->fh->fd = -1;
858 if (ret == -1) {
859 return map_nt_error_from_unix(errno);
860 }
861 return NT_STATUS_OK;
862 }
863
864 /****************************************************************************
865 Change the ownership of a file to that of the parent directory.
866 Do this by fd if possible.
867 ****************************************************************************/
868
869 void change_file_owner_to_parent(connection_struct *conn,
870 const char *inherit_from_dir,
871 files_struct *fsp)
872 {
873 struct smb_filename *smb_fname_parent;
874 int ret;
875
876 smb_fname_parent = synthetic_smb_fname(talloc_tos(),
877 inherit_from_dir,
878 NULL,
879 NULL,
880 0);
881 if (smb_fname_parent == NULL) {
882 return;
883 }
884
885 ret = SMB_VFS_STAT(conn, smb_fname_parent);
886 if (ret == -1) {
887 DEBUG(0,("change_file_owner_to_parent: failed to stat parent "
888 "directory %s. Error was %s\n",
889 smb_fname_str_dbg(smb_fname_parent),
890 strerror(errno)));
891 TALLOC_FREE(smb_fname_parent);
892 return;
893 }
894
895 if (smb_fname_parent->st.st_ex_uid == fsp->fsp_name->st.st_ex_uid) {
896 /* Already this uid - no need to change. */
897 DEBUG(10,("change_file_owner_to_parent: file %s "
898 "is already owned by uid %d\n",
899 fsp_str_dbg(fsp),
900 (int)fsp->fsp_name->st.st_ex_uid ));
901 TALLOC_FREE(smb_fname_parent);
902 return;
903 }
904
905 become_root();
906 ret = SMB_VFS_FCHOWN(fsp, smb_fname_parent->st.st_ex_uid, (gid_t)-1);
907 unbecome_root();
908 if (ret == -1) {
909 DEBUG(0,("change_file_owner_to_parent: failed to fchown "
910 "file %s to parent directory uid %u. Error "
911 "was %s\n", fsp_str_dbg(fsp),
912 (unsigned int)smb_fname_parent->st.st_ex_uid,
913 strerror(errno) ));
914 } else {
915 DEBUG(10,("change_file_owner_to_parent: changed new file %s to "
916 "parent directory uid %u.\n", fsp_str_dbg(fsp),
917 (unsigned int)smb_fname_parent->st.st_ex_uid));
918 /* Ensure the uid entry is updated. */
919 fsp->fsp_name->st.st_ex_uid = smb_fname_parent->st.st_ex_uid;
920 }
921
922 TALLOC_FREE(smb_fname_parent);
923 }
924
925 static NTSTATUS change_dir_owner_to_parent(connection_struct *conn,
926 const char *inherit_from_dir,
927 struct smb_filename *smb_dname,
928 SMB_STRUCT_STAT *psbuf)
929 {
930 struct smb_filename *smb_fname_parent;
931 struct smb_filename *smb_fname_cwd = NULL;
932 struct smb_filename *saved_dir_fname = NULL;
933 TALLOC_CTX *ctx = talloc_tos();
934 NTSTATUS status = NT_STATUS_OK;
935 int ret;
936
937 smb_fname_parent = synthetic_smb_fname(ctx,
938 inherit_from_dir,
939 NULL,
940 NULL,
941 0);
942 if (smb_fname_parent == NULL) {
943 return NT_STATUS_NO_MEMORY;
944 }
945
946 ret = SMB_VFS_STAT(conn, smb_fname_parent);
947 if (ret == -1) {
948 status = map_nt_error_from_unix(errno);
949 DEBUG(0,("change_dir_owner_to_parent: failed to stat parent "
950 "directory %s. Error was %s\n",
951 smb_fname_str_dbg(smb_fname_parent),
952 strerror(errno)));
953 goto out;
954 }
955
956 /* We've already done an lstat into psbuf, and we know it's a
957 directory. If we can cd into the directory and the dev/ino
958 are the same then we can safely chown without races as
959 we're locking the directory in place by being in it. This
960 should work on any UNIX (thanks tridge :-). JRA.
961 */
962
963 saved_dir_fname = vfs_GetWd(ctx,conn);
964 if (!saved_dir_fname) {
965 status = map_nt_error_from_unix(errno);
966 DEBUG(0,("change_dir_owner_to_parent: failed to get "
967 "current working directory. Error was %s\n",
968 strerror(errno)));
969 goto out;
970 }
971
972 /* Chdir into the new path. */
973 if (vfs_ChDir(conn, smb_dname) == -1) {
974 status = map_nt_error_from_unix(errno);
975 DEBUG(0,("change_dir_owner_to_parent: failed to change "
976 "current working directory to %s. Error "
977 "was %s\n", smb_dname->base_name, strerror(errno) ));
978 goto chdir;
979 }
980
981 smb_fname_cwd = synthetic_smb_fname(ctx, ".", NULL, NULL, 0);
982 if (smb_fname_cwd == NULL) {
983 status = NT_STATUS_NO_MEMORY;
984 goto chdir;
985 }
986
987 ret = SMB_VFS_STAT(conn, smb_fname_cwd);
988 if (ret == -1) {
989 status = map_nt_error_from_unix(errno);
990 DEBUG(0,("change_dir_owner_to_parent: failed to stat "
991 "directory '.' (%s) Error was %s\n",
992 smb_dname->base_name, strerror(errno)));
993 goto chdir;
994 }
995
996 /* Ensure we're pointing at the same place. */
997 if (smb_fname_cwd->st.st_ex_dev != psbuf->st_ex_dev ||
998 smb_fname_cwd->st.st_ex_ino != psbuf->st_ex_ino) {
999 DEBUG(0,("change_dir_owner_to_parent: "
1000 "device/inode on directory %s changed. "
1001 "Refusing to chown !\n",
1002 smb_dname->base_name ));
1003 status = NT_STATUS_ACCESS_DENIED;
1004 goto chdir;
1005 }
1006
1007 if (smb_fname_parent->st.st_ex_uid == smb_fname_cwd->st.st_ex_uid) {
1008 /* Already this uid - no need to change. */
1009 DEBUG(10,("change_dir_owner_to_parent: directory %s "
1010 "is already owned by uid %d\n",
1011 smb_dname->base_name,
1012 (int)smb_fname_cwd->st.st_ex_uid ));
1013 status = NT_STATUS_OK;
1014 goto chdir;
1015 }
1016
1017 become_root();
1018 ret = SMB_VFS_LCHOWN(conn,
1019 smb_fname_cwd,
1020 smb_fname_parent->st.st_ex_uid,
1021 (gid_t)-1);
1022 unbecome_root();
1023 if (ret == -1) {
1024 status = map_nt_error_from_unix(errno);
1025 DEBUG(10,("change_dir_owner_to_parent: failed to chown "
1026 "directory %s to parent directory uid %u. "
1027 "Error was %s\n",
1028 smb_dname->base_name,
1029 (unsigned int)smb_fname_parent->st.st_ex_uid,
1030 strerror(errno) ));
1031 } else {
1032 DEBUG(10,("change_dir_owner_to_parent: changed ownership of new "
1033 "directory %s to parent directory uid %u.\n",
1034 smb_dname->base_name,
1035 (unsigned int)smb_fname_parent->st.st_ex_uid ));
1036 /* Ensure the uid entry is updated. */
1037 psbuf->st_ex_uid = smb_fname_parent->st.st_ex_uid;
1038 }
1039
1040 chdir:
1041 vfs_ChDir(conn, saved_dir_fname);
1042 out:
1043 TALLOC_FREE(saved_dir_fname);
1044 TALLOC_FREE(smb_fname_parent);
1045 TALLOC_FREE(smb_fname_cwd);
1046 return status;
1047 }
1048
1049 /****************************************************************************
1050 Open a file - returning a guaranteed ATOMIC indication of if the
1051 file was created or not.
1052 ****************************************************************************/
1053
1054 static NTSTATUS fd_open_atomic(struct connection_struct *conn,
1055 files_struct *fsp,
1056 int flags,
1057 mode_t mode,
1058 bool *file_created)
1059 {
1060 NTSTATUS status = NT_STATUS_UNSUCCESSFUL;
1061 NTSTATUS retry_status;
1062 bool file_existed = VALID_STAT(fsp->fsp_name->st);
1063 int curr_flags;
1064
1065 if (!(flags & O_CREAT)) {
1066 /*
1067 * We're not creating the file, just pass through.
1068 */
1069 status = fd_open(conn, fsp, flags, mode);
1070 *file_created = false;
1071 return status;
1072 }
1073
1074 if (flags & O_EXCL) {
1075 /*
1076 * Fail if already exists, just pass through.
1077 */
1078 status = fd_open(conn, fsp, flags, mode);
1079
1080 /*
1081 * Here we've opened with O_CREAT|O_EXCL. If that went
1082 * NT_STATUS_OK, we *know* we created this file.
1083 */
1084 *file_created = NT_STATUS_IS_OK(status);
1085
1086 return status;
1087 }
1088
1089 /*
1090 * Now it gets tricky. We have O_CREAT, but not O_EXCL.
1091 * To know absolutely if we created the file or not,
1092 * we can never call O_CREAT without O_EXCL. So if
1093 * we think the file existed, try without O_CREAT|O_EXCL.
1094 * If we think the file didn't exist, try with
1095 * O_CREAT|O_EXCL.
1096 *
1097 * The big problem here is dangling symlinks. Opening
1098 * without O_NOFOLLOW means both bad symlink
1099 * and missing path return -1, ENOENT from open(). As POSIX
1100 * is pathname based it's not possible to tell
1101 * the difference between these two cases in a
1102 * non-racy way, so change to try only two attempts before
1103 * giving up.
1104 *
1105 * We don't have this problem for the O_NOFOLLOW
1106 * case as it just returns NT_STATUS_OBJECT_PATH_NOT_FOUND
1107 * mapped from the ELOOP POSIX error.
1108 */
1109
1110 if (file_existed) {
1111 curr_flags = flags & ~(O_CREAT);
1112 retry_status = NT_STATUS_OBJECT_NAME_NOT_FOUND;
1113 } else {
1114 curr_flags = flags | O_EXCL;
1115 retry_status = NT_STATUS_OBJECT_NAME_COLLISION;
1116 }
1117
1118 status = fd_open(conn, fsp, curr_flags, mode);
1119 if (NT_STATUS_IS_OK(status)) {
1120 *file_created = !file_existed;
1121 return NT_STATUS_OK;
1122 }
1123 if (NT_STATUS_EQUAL(status, retry_status)) {
1124
1125 file_existed = !file_existed;
1126
1127 DBG_DEBUG("File %s %s. Retry.\n",
1128 fsp_str_dbg(fsp),
1129 file_existed ? "existed" : "did not exist");
1130
1131 if (file_existed) {
1132 curr_flags = flags & ~(O_CREAT);
1133 } else {
1134 curr_flags = flags | O_EXCL;
1135 }
1136
1137 status = fd_open(conn, fsp, curr_flags, mode);
1138 }
1139
1140 *file_created = (NT_STATUS_IS_OK(status) && !file_existed);
1141 return status;
1142 }
1143
1144 /****************************************************************************
1145 Open a file.
1146 ****************************************************************************/
1147
1148 static NTSTATUS open_file(files_struct *fsp,
1149 connection_struct *conn,
1150 struct smb_request *req,
1151 const char *parent_dir,
1152 int flags,
1153 mode_t unx_mode,
1154 uint32_t access_mask, /* client requested access mask. */
1155 uint32_t open_access_mask, /* what we're actually using in the open. */
1156 bool *p_file_created)
1157 {
1158 struct smb_filename *smb_fname = fsp->fsp_name;
1159 NTSTATUS status = NT_STATUS_OK;
1160 int accmode = (flags & O_ACCMODE);
1161 int local_flags = flags;
1162 bool file_existed = VALID_STAT(fsp->fsp_name->st);
1163
1164 fsp->fh->fd = -1;
1165 errno = EPERM;
1166
1167 /* Check permissions */
1168
1169 /*
1170 * This code was changed after seeing a client open request
1171 * containing the open mode of (DENY_WRITE/read-only) with
1172 * the 'create if not exist' bit set. The previous code
1173 * would fail to open the file read only on a read-only share
1174 * as it was checking the flags parameter directly against O_RDONLY,
1175 * this was failing as the flags parameter was set to O_RDONLY|O_CREAT.
1176 * JRA.
1177 */
1178
1179 if (!CAN_WRITE(conn)) {
1180 /* It's a read-only share - fail if we wanted to write. */
1181 if(accmode != O_RDONLY || (flags & O_TRUNC) || (flags & O_APPEND)) {
1182 DEBUG(3,("Permission denied opening %s\n",
1183 smb_fname_str_dbg(smb_fname)));
1184 return NT_STATUS_ACCESS_DENIED;
1185 }
1186 if (flags & O_CREAT) {
1187 /* We don't want to write - but we must make sure that
1188 O_CREAT doesn't create the file if we have write
1189 access into the directory.
1190 */
1191 flags &= ~(O_CREAT|O_EXCL);
1192 local_flags &= ~(O_CREAT|O_EXCL);
1193 }
1194 }
1195
1196 /*
1197 * This little piece of insanity is inspired by the
1198 * fact that an NT client can open a file for O_RDONLY,
1199 * but set the create disposition to FILE_EXISTS_TRUNCATE.
1200 * If the client *can* write to the file, then it expects to
1201 * truncate the file, even though it is opening for readonly.
1202 * Quicken uses this stupid trick in backup file creation...
1203 * Thanks *greatly* to "David W. Chapman Jr." <dwcjr@inethouston.net>
1204 * for helping track this one down. It didn't bite us in 2.0.x
1205 * as we always opened files read-write in that release. JRA.
1206 */
1207
1208 if ((accmode == O_RDONLY) && ((flags & O_TRUNC) == O_TRUNC)) {
1209 DEBUG(10,("open_file: truncate requested on read-only open "
1210 "for file %s\n", smb_fname_str_dbg(smb_fname)));
1211 local_flags = (flags & ~O_ACCMODE)|O_RDWR;
1212 }
1213
1214 if ((open_access_mask & (FILE_READ_DATA|FILE_WRITE_DATA|
1215 FILE_APPEND_DATA|FILE_EXECUTE|
1216 WRITE_DAC_ACCESS|WRITE_OWNER_ACCESS|
1217 READ_CONTROL_ACCESS))||
1218 (!file_existed && (local_flags & O_CREAT)) ||
1219 ((local_flags & O_TRUNC) == O_TRUNC) ) {
1220 const char *wild;
1221 int ret;
1222
1223 #if defined(O_NONBLOCK) && defined(S_ISFIFO)
1224 /*
1225 * We would block on opening a FIFO with no one else on the
1226 * other end. Do what we used to do and add O_NONBLOCK to the
1227 * open flags. JRA.
1228 */
1229
1230 if (file_existed && S_ISFIFO(smb_fname->st.st_ex_mode)) {
1231 local_flags &= ~O_TRUNC; /* Can't truncate a FIFO. */
1232 local_flags |= O_NONBLOCK;
1233 }
1234 #endif
1235
1236 /* Don't create files with Microsoft wildcard characters. */
1237 if (fsp->base_fsp) {
1238 /*
1239 * wildcard characters are allowed in stream names
1240 * only test the basefilename
1241 */
1242 wild = fsp->base_fsp->fsp_name->base_name;
1243 } else {
1244 wild = smb_fname->base_name;
1245 }
1246 if ((local_flags & O_CREAT) && !file_existed &&
1247 !(fsp->posix_flags & FSP_POSIX_FLAGS_PATHNAMES) &&
1248 ms_has_wild(wild)) {
1249 return NT_STATUS_OBJECT_NAME_INVALID;
1250 }
1251
1252 /* Can we access this file ? */
1253 if (!fsp->base_fsp) {
1254 /* Only do this check on non-stream open. */
1255 if (file_existed) {
1256 status = smbd_check_access_rights(conn,
1257 smb_fname,
1258 false,
1259 access_mask);
1260
1261 if (!NT_STATUS_IS_OK(status)) {
1262 DEBUG(10, ("open_file: "
1263 "smbd_check_access_rights "
1264 "on file %s returned %s\n",
1265 smb_fname_str_dbg(smb_fname),
1266 nt_errstr(status)));
1267 }
1268
1269 if (!NT_STATUS_IS_OK(status) &&
1270 !NT_STATUS_EQUAL(status,
1271 NT_STATUS_OBJECT_NAME_NOT_FOUND))
1272 {
1273 return status;
1274 }
1275
1276 if (NT_STATUS_EQUAL(status,
1277 NT_STATUS_OBJECT_NAME_NOT_FOUND))
1278 {
1279 DEBUG(10, ("open_file: "
1280 "file %s vanished since we "
1281 "checked for existence.\n",
1282 smb_fname_str_dbg(smb_fname)));
1283 file_existed = false;
1284 SET_STAT_INVALID(fsp->fsp_name->st);
1285 }
1286 }
1287
1288 if (!file_existed) {
1289 if (!(local_flags & O_CREAT)) {
1290 /* File didn't exist and no O_CREAT. */
1291 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
1292 }
1293
1294 status = check_parent_access(conn,
1295 smb_fname,
1296 SEC_DIR_ADD_FILE);
1297 if (!NT_STATUS_IS_OK(status)) {
1298 DEBUG(10, ("open_file: "
1299 "check_parent_access on "
1300 "file %s returned %s\n",
1301 smb_fname_str_dbg(smb_fname),
1302 nt_errstr(status) ));
1303 return status;
1304 }
1305 }
1306 }
1307
1308 /*
1309 * Actually do the open - if O_TRUNC is needed handle it
1310 * below under the share mode lock.
1311 */
1312 status = fd_open_atomic(conn, fsp, local_flags & ~O_TRUNC,
1313 unx_mode, p_file_created);
1314 if (!NT_STATUS_IS_OK(status)) {
1315 DEBUG(3,("Error opening file %s (%s) (local_flags=%d) "
1316 "(flags=%d)\n", smb_fname_str_dbg(smb_fname),
1317 nt_errstr(status),local_flags,flags));
1318 return status;
1319 }
1320
1321 if (local_flags & O_NONBLOCK) {
1322 /*
1323 * GPFS can return ETIMEDOUT for pread on
1324 * nonblocking file descriptors when files
1325 * migrated to tape need to be recalled. I
1326 * could imagine this happens elsewhere
1327 * too. With blocking file descriptors this
1328 * does not happen.
1329 */
1330 ret = set_blocking(fsp->fh->fd, true);
1331 if (ret == -1) {
1332 status = map_nt_error_from_unix(errno);
1333 DBG_WARNING("Could not set fd to blocking: "
1334 "%s\n", strerror(errno));
1335 fd_close(fsp);
1336 return status;
1337 }
1338 }
1339
1340 ret = SMB_VFS_FSTAT(fsp, &smb_fname->st);
1341 if (ret == -1) {
1342 /* If we have an fd, this stat should succeed. */
1343 DEBUG(0,("Error doing fstat on open file %s "
1344 "(%s)\n",
1345 smb_fname_str_dbg(smb_fname),
1346 strerror(errno) ));
1347 status = map_nt_error_from_unix(errno);
1348 fd_close(fsp);
1349 return status;
1350 }
1351
1352 if (*p_file_created) {
1353 /* We created this file. */
1354
1355 bool need_re_stat = false;
1356 /* Do all inheritance work after we've
1357 done a successful fstat call and filled
1358 in the stat struct in fsp->fsp_name. */
1359
1360 /* Inherit the ACL if required */
1361 if (lp_inherit_permissions(SNUM(conn))) {
1362 inherit_access_posix_acl(conn, parent_dir,
1363 smb_fname,
1364 unx_mode);
1365 need_re_stat = true;
1366 }
1367
1368 /* Change the owner if required. */
1369 if (lp_inherit_owner(SNUM(conn)) != INHERIT_OWNER_NO) {
1370 change_file_owner_to_parent(conn, parent_dir,
1371 fsp);
1372 need_re_stat = true;
1373 }
1374
1375 if (need_re_stat) {
1376 ret = SMB_VFS_FSTAT(fsp, &smb_fname->st);
1377 /* If we have an fd, this stat should succeed. */
1378 if (ret == -1) {
1379 DEBUG(0,("Error doing fstat on open file %s "
1380 "(%s)\n",
1381 smb_fname_str_dbg(smb_fname),
1382 strerror(errno) ));
1383 }
1384 }
1385
1386 notify_fname(conn, NOTIFY_ACTION_ADDED,
1387 FILE_NOTIFY_CHANGE_FILE_NAME,
1388 smb_fname->base_name);
1389 }
1390 } else {
1391 fsp->fh->fd = -1; /* What we used to call a stat open. */
1392 if (!file_existed) {
1393 /* File must exist for a stat open. */
1394 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
1395 }
1396
1397 status = smbd_check_access_rights(conn,
1398 smb_fname,
1399 false,
1400 access_mask);
1401
1402 if (NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND) &&
1403 (fsp->posix_flags & FSP_POSIX_FLAGS_OPEN) &&
1404 S_ISLNK(smb_fname->st.st_ex_mode)) {
1405 /* This is a POSIX stat open for delete
1406 * or rename on a symlink that points
1407 * nowhere. Allow. */
1408 DEBUG(10,("open_file: allowing POSIX "
1409 "open on bad symlink %s\n",
1410 smb_fname_str_dbg(smb_fname)));
1411 status = NT_STATUS_OK;
1412 }
1413
1414 if (!NT_STATUS_IS_OK(status)) {
1415 DEBUG(10,("open_file: "
1416 "smbd_check_access_rights on file "
1417 "%s returned %s\n",
1418 smb_fname_str_dbg(smb_fname),
1419 nt_errstr(status) ));
1420 return status;
1421 }
1422 }
1423
1424 /*
1425 * POSIX allows read-only opens of directories. We don't
1426 * want to do this (we use a different code path for this)
1427 * so catch a directory open and return an EISDIR. JRA.
1428 */
1429
1430 if(S_ISDIR(smb_fname->st.st_ex_mode)) {
1431 fd_close(fsp);
1432 errno = EISDIR;
1433 return NT_STATUS_FILE_IS_A_DIRECTORY;
1434 }
1435
1436 fsp->file_id = vfs_file_id_from_sbuf(conn, &smb_fname->st);
1437 fsp->vuid = req ? req->vuid : UID_FIELD_INVALID;
1438 fsp->file_pid = req ? req->smbpid : 0;
1439 fsp->can_lock = True;
1440 fsp->can_read = ((access_mask & FILE_READ_DATA) != 0);
1441 fsp->can_write =
1442 CAN_WRITE(conn) &&
1443 ((access_mask & (FILE_WRITE_DATA | FILE_APPEND_DATA)) != 0);
1444 fsp->print_file = NULL;
1445 fsp->modified = False;
1446 fsp->sent_oplock_break = NO_BREAK_SENT;
1447 fsp->is_directory = False;
1448 if (conn->aio_write_behind_list &&
1449 is_in_path(smb_fname->base_name, conn->aio_write_behind_list,
1450 conn->case_sensitive)) {
1451 fsp->aio_write_behind = True;
1452 }
1453
1454 fsp->wcp = NULL; /* Write cache pointer. */
1455
1456 DEBUG(2,("%s opened file %s read=%s write=%s (numopen=%d)\n",
1457 conn->session_info->unix_info->unix_name,
1458 smb_fname_str_dbg(smb_fname),
1459 BOOLSTR(fsp->can_read), BOOLSTR(fsp->can_write),
1460 conn->num_files_open));
1461
1462 errno = 0;
1463 return NT_STATUS_OK;
1464 }
1465
1466 static bool mask_conflict(
1467 uint32_t new_access,
1468 uint32_t existing_access,
1469 uint32_t access_mask,
1470 uint32_t new_sharemode,
1471 uint32_t existing_sharemode,
1472 uint32_t sharemode_mask)
1473 {
1474 bool want_access = (new_access & access_mask);
1475 bool allow_existing = (existing_sharemode & sharemode_mask);
1476 bool have_access = (existing_access & access_mask);
1477 bool allow_new = (new_sharemode & sharemode_mask);
1478
1479 if (want_access && !allow_existing) {
1480 DBG_DEBUG("Access request 0x%"PRIx32"/0x%"PRIx32" conflicts "
1481 "with existing sharemode 0x%"PRIx32"/0x%"PRIx32"\n",
1482 new_access,
1483 access_mask,
1484 existing_sharemode,
1485 sharemode_mask);
1486 return true;
1487 }
1488 if (have_access && !allow_new) {
1489 DBG_DEBUG("Sharemode request 0x%"PRIx32"/0x%"PRIx32" conflicts "
1490 "with existing access 0x%"PRIx32"/0x%"PRIx32"\n",
1491 new_sharemode,
1492 sharemode_mask,
1493 existing_access,
1494 access_mask);
1495 return true;
1496 }
1497 return false;
1498 }
1499
1500 /****************************************************************************
1501 Check if we can open a file with a share mode.
1502 Returns True if conflict, False if not.
1503 ****************************************************************************/
1504
1505 static bool share_conflict(uint32_t e_access_mask,
1506 uint32_t e_share_access,
1507 uint32_t access_mask,
1508 uint32_t share_access)
1509 {
1510 const uint32_t conflicting_access =
1511 FILE_WRITE_DATA|
1512 FILE_APPEND_DATA|
1513 FILE_READ_DATA|
1514 FILE_EXECUTE|
1515 DELETE_ACCESS;
1516 bool conflict;
1517
1518 DBG_DEBUG("existing access_mask = 0x%"PRIx32", "
1519 "existing share access = 0x%"PRIx32", "
1520 "access_mask = 0x%"PRIx32", "
1521 "share_access = 0x%"PRIx32"\n",
1522 e_access_mask,
1523 e_share_access,
1524 access_mask,
1525 share_access);
1526
1527 if ((e_access_mask & conflicting_access) == 0) {
1528 DBG_DEBUG("No conflict due to "
1529 "existing access_mask = 0x%"PRIx32"\n",
1530 e_access_mask);
1531 return false;
1532 }
1533 if ((access_mask & conflicting_access) == 0) {
1534 DBG_DEBUG("No conflict due to access_mask = 0x%"PRIx32"\n",
1535 access_mask);
1536 return false;
1537 }
1538
1539 conflict = mask_conflict(
1540 access_mask, e_access_mask, FILE_WRITE_DATA | FILE_APPEND_DATA,
1541 share_access, e_share_access, FILE_SHARE_WRITE);
1542 conflict |= mask_conflict(
1543 access_mask, e_access_mask, FILE_READ_DATA | FILE_EXECUTE,
1544 share_access, e_share_access, FILE_SHARE_READ);
1545 conflict |= mask_conflict(
1546 access_mask, e_access_mask, DELETE_ACCESS,
1547 share_access, e_share_access, FILE_SHARE_DELETE);
1548
1549 DBG_DEBUG("conflict=%s\n", conflict ? "true" : "false");
1550 return conflict;
1551 }
1552
1553 #if defined(DEVELOPER)
1554
1555 struct validate_my_share_entries_state {
1556 struct smbd_server_connection *sconn;
1557 struct file_id fid;
1558 struct server_id self;
1559 };
1560
1561 static bool validate_my_share_entries_fn(
1562 struct share_mode_entry *e,
1563 bool *modified,
1564 void *private_data)
1565 {
1566 struct validate_my_share_entries_state *state = private_data;
1567 files_struct *fsp;
1568
1569 if (!serverid_equal(&state->self, &e->pid)) {
1570 return false;
1571 }
1572
1573 if (e->op_mid == 0) {
1574 /* INTERNAL_OPEN_ONLY */
1575 return false;
1576 }
1577
1578 fsp = file_find_dif(state->sconn, state->fid, e->share_file_id);
1579 if (!fsp) {
1580 DBG_ERR("PANIC : %s\n",
1581 share_mode_str(talloc_tos(), 0, &state->fid, e));
1582 smb_panic("validate_my_share_entries: Cannot match a "
1583 "share entry with an open file\n");
1584 }
1585
1586 if (((uint16_t)fsp->oplock_type) != e->op_type) {
1587 goto panic;
1588 }
1589
1590 return false;
1591
1592 panic:
1593 {
1594 char *str;
1595 DBG_ERR("validate_my_share_entries: PANIC : %s\n",
1596 share_mode_str(talloc_tos(), 0, &state->fid, e));
1597 str = talloc_asprintf(talloc_tos(),
1598 "validate_my_share_entries: "
1599 "file %s, oplock_type = 0x%x, op_type = 0x%x\n",
1600 fsp->fsp_name->base_name,
1601 (unsigned int)fsp->oplock_type,
1602 (unsigned int)e->op_type);
1603 smb_panic(str);
1604 }
1605
1606 return false;
1607 }
1608 #endif
1609
1610 bool is_stat_open(uint32_t access_mask)
1611 {
1612 const uint32_t stat_open_bits =
1613 (SYNCHRONIZE_ACCESS|
1614 FILE_READ_ATTRIBUTES|
1615 FILE_WRITE_ATTRIBUTES);
1616
1617 return (((access_mask & stat_open_bits) != 0) &&
1618 ((access_mask & ~stat_open_bits) == 0));
1619 }
1620
1621 struct has_delete_on_close_state {
1622 bool ret;
1623 };
1624
1625 static bool has_delete_on_close_fn(
1626 struct share_mode_entry *e,
1627 bool *modified,
1628 void *private_data)
1629 {
1630 struct has_delete_on_close_state *state = private_data;
1631 state->ret = !share_entry_stale_pid(e);
1632 return state->ret;
1633 }
1634
1635 static bool has_delete_on_close(struct share_mode_lock *lck,
1636 uint32_t name_hash)
1637 {
1638 struct has_delete_on_close_state state = { .ret = false };
1639 bool ok;
1640
1641 if (!is_delete_on_close_set(lck, name_hash)) {
1642 return false;
1643 }
1644
1645 ok= share_mode_forall_entries(lck, has_delete_on_close_fn, &state);
1646 if (!ok) {
1647 DBG_DEBUG("share_mode_forall_entries failed\n");
1648 return false;
1649 }
1650 return state.ret;
1651 }
1652
1653 static void share_mode_flags_get(
1654 uint16_t flags,
1655 uint32_t *access_mask,
1656 uint32_t *share_mode,
1657 uint32_t *lease_type)
1658 {
1659 if (access_mask != NULL) {
1660 *access_mask =
1661 ((flags & SHARE_MODE_ACCESS_READ) ?
1662 FILE_READ_DATA : 0) |
1663 ((flags & SHARE_MODE_ACCESS_WRITE) ?
1664 FILE_WRITE_DATA : 0) |
1665 ((flags & SHARE_MODE_ACCESS_DELETE) ?
1666 DELETE_ACCESS : 0);
1667 }
1668 if (share_mode != NULL) {
1669 *share_mode =
1670 ((flags & SHARE_MODE_SHARE_READ) ?
1671 FILE_SHARE_READ : 0) |
1672 ((flags & SHARE_MODE_SHARE_WRITE) ?
1673 FILE_SHARE_WRITE : 0) |
1674 ((flags & SHARE_MODE_SHARE_DELETE) ?
1675 FILE_SHARE_DELETE : 0);
1676 }
1677 if (lease_type != NULL) {
1678 *lease_type =
1679 ((flags & SHARE_MODE_LEASE_READ) ?
1680 SMB2_LEASE_READ : 0) |
1681 ((flags & SHARE_MODE_LEASE_WRITE) ?
1682 SMB2_LEASE_WRITE : 0) |
1683 ((flags & SHARE_MODE_LEASE_HANDLE) ?
1684 SMB2_LEASE_HANDLE : 0);
1685 }
1686 }
1687
1688 static uint16_t share_mode_flags_set(
1689 uint16_t flags,
1690 uint32_t access_mask,
1691 uint32_t share_mode,
1692 uint32_t lease_type)
1693 {
1694 if (access_mask != UINT32_MAX) {
1695 flags &= ~(SHARE_MODE_ACCESS_READ|
1696 SHARE_MODE_ACCESS_WRITE|
1697 SHARE_MODE_ACCESS_DELETE);
1698 flags |= (access_mask & (FILE_READ_DATA | FILE_EXECUTE)) ?
1699 SHARE_MODE_ACCESS_READ : 0;
1700 flags |= (access_mask & (FILE_WRITE_DATA | FILE_APPEND_DATA)) ?
1701 SHARE_MODE_ACCESS_WRITE : 0;
1702 flags |= (access_mask & (DELETE_ACCESS)) ?
1703 SHARE_MODE_ACCESS_DELETE : 0;
1704 }
1705 if (share_mode != UINT32_MAX) {
1706 flags &= ~(SHARE_MODE_SHARE_READ|
1707 SHARE_MODE_SHARE_WRITE|
1708 SHARE_MODE_SHARE_DELETE);
1709 flags |= (share_mode & FILE_SHARE_READ) ?
1710 SHARE_MODE_SHARE_READ : 0;
1711 flags |= (share_mode & FILE_SHARE_WRITE) ?
1712 SHARE_MODE_SHARE_WRITE : 0;
1713 flags |= (share_mode & FILE_SHARE_DELETE) ?
1714 SHARE_MODE_SHARE_DELETE : 0;
1715 }
1716 if (lease_type != UINT32_MAX) {
1717 flags &= ~(SHARE_MODE_LEASE_READ|
1718 SHARE_MODE_LEASE_WRITE|
1719 SHARE_MODE_LEASE_HANDLE);
1720 flags |= (lease_type & SMB2_LEASE_READ) ?
1721 SHARE_MODE_LEASE_READ : 0;
1722 flags |= (lease_type & SMB2_LEASE_WRITE) ?
1723 SHARE_MODE_LEASE_WRITE : 0;
1724 flags |= (lease_type & SMB2_LEASE_HANDLE) ?
1725 SHARE_MODE_LEASE_HANDLE : 0;
1726 }
1727
1728 return flags;
1729 }
1730
1731 static uint16_t share_mode_flags_restrict(
1732 uint16_t flags,
1733 uint32_t access_mask,
1734 uint32_t share_mode,
1735 uint32_t lease_type)
1736 {
1737 uint32_t existing_access_mask, existing_share_mode;
1738 uint32_t existing_lease_type;
1739 uint16_t ret;
1740
1741 share_mode_flags_get(
1742 flags,
1743 &existing_access_mask,
1744 &existing_share_mode,
1745 &existing_lease_type);
1746
1747 existing_access_mask |= access_mask;
1748 existing_share_mode &= share_mode;
1749 existing_lease_type |= lease_type;
1750
1751 ret = share_mode_flags_set(
1752 flags,
1753 existing_access_mask,
1754 existing_share_mode,
1755 existing_lease_type);
1756 return ret;
1757 }
1758
1759 /****************************************************************************
1760 Deal with share modes
1761 Invariant: Share mode must be locked on entry and exit.
1762 Returns -1 on error, or number of share modes on success (may be zero).
1763 ****************************************************************************/
1764
1765 struct open_mode_check_state {
1766 struct file_id fid;
1767 uint32_t access_mask;
1768 uint32_t share_access;
1769 uint32_t lease_type;
1770 };
1771
1772 static bool open_mode_check_fn(
1773 struct share_mode_entry *e,
1774 bool *modified,
1775 void *private_data)
1776 {
1777 struct open_mode_check_state *state = private_data;
1778 bool disconnected, stale;
1779 uint32_t access_mask, share_access, lease_type;
1780
1781 disconnected = server_id_is_disconnected(&e->pid);
1782 if (disconnected) {
1783 return false;
1784 }
1785
1786 access_mask = state->access_mask | e->access_mask;
1787 share_access = state->share_access & e->share_access;
1788 lease_type = state->lease_type | get_lease_type(e, state->fid);
1789
1790 if ((access_mask == state->access_mask) &&
1791 (share_access == state->share_access) &&
1792 (lease_type == state->lease_type)) {
1793 return false;
1794 }
1795
1796 stale = share_entry_stale_pid(e);
1797 if (stale) {
1798 return false;
1799 }
1800
1801 state->access_mask = access_mask;
1802 state->share_access = share_access;
1803 state->lease_type = lease_type;
1804
1805 return false;
1806 }
1807
1808 static NTSTATUS open_mode_check(connection_struct *conn,
1809 struct share_mode_lock *lck,
1810 uint32_t access_mask,
1811 uint32_t share_access)
1812 {
1813 struct share_mode_data *d = lck->data;
1814 struct open_mode_check_state state;
1815 uint16_t new_flags;
1816 bool ok, conflict;
1817
1818 if (is_stat_open(access_mask)) {
1819 /* Stat open that doesn't trigger oplock breaks or share mode
1820 * checks... ! JRA. */
1821 return NT_STATUS_OK;
1822 }
1823
1824 /*
1825 * Check if the share modes will give us access.
1826 */
1827
1828 #if defined(DEVELOPER)
1829 {
1830 struct validate_my_share_entries_state validate_state = {
1831 .sconn = conn->sconn,
1832 .fid = d->id,
1833 .self = messaging_server_id(conn->sconn->msg_ctx),
1834 };
1835 ok = share_mode_forall_entries(
1836 lck, validate_my_share_entries_fn, &validate_state);
1837 SMB_ASSERT(ok);
1838 }
1839 #endif
1840
1841 if (d->num_share_modes == 0) {
1842 return NT_STATUS_OK;
1843 }
1844
1845 share_mode_flags_get(
1846 d->flags, &state.access_mask, &state.share_access, NULL);
1847
1848 conflict = share_conflict(
1849 state.access_mask,
1850 state.share_access,
1851 access_mask,
1852 share_access);
1853 if (!conflict) {
1854 DBG_DEBUG("No conflict due to share_mode_flags access\n");
1855 return NT_STATUS_OK;
1856 }
1857
1858 state = (struct open_mode_check_state) {
1859 .fid = d->id,
1860 .share_access = (FILE_SHARE_READ|
1861 FILE_SHARE_WRITE|
1862 FILE_SHARE_DELETE),
1863 };
1864
1865 /*
1866 * Walk the share mode array to recalculate d->flags
1867 */
1868
1869 ok = share_mode_forall_entries(lck, open_mode_check_fn, &state);
1870 if (!ok) {
1871 DBG_DEBUG("share_mode_forall_entries failed\n");
1872 return NT_STATUS_INTERNAL_ERROR;
1873 }
1874
1875 new_flags = share_mode_flags_set(
1876 0, state.access_mask, state.share_access, state.lease_type);
1877 if (new_flags == d->flags) {
1878 /*
1879 * We only end up here if we had a sharing violation
1880 * from d->flags and have recalculated it.
1881 */
1882 return NT_STATUS_SHARING_VIOLATION;
1883 }
1884
1885 d->flags = new_flags;
1886 d->modified = true;
1887
1888 conflict = share_conflict(
1889 state.access_mask,
1890 state.share_access,
1891 access_mask,
1892 share_access);
1893 if (!conflict) {
1894 DBG_DEBUG("No conflict due to share_mode_flags access\n");
1895 return NT_STATUS_OK;
1896 }
1897
1898 return NT_STATUS_SHARING_VIOLATION;
1899 }
1900
1901 /*
1902 * Send a break message to the oplock holder and delay the open for
1903 * our client.
1904 */
1905
1906 NTSTATUS send_break_message(struct messaging_context *msg_ctx,
1907 const struct file_id *id,
1908 const struct share_mode_entry *exclusive,
1909 uint16_t break_to)
1910 {
1911 struct oplock_break_message msg = {
1912 .id = *id,
1913 .share_file_id = exclusive->share_file_id,
1914 .break_to = break_to,
1915 };
1916 enum ndr_err_code ndr_err;
1917 DATA_BLOB blob;
1918 NTSTATUS status;
1919
1920 if (DEBUGLVL(10)) {
1921 struct server_id_buf buf;
1922 DBG_DEBUG("Sending break message to %s\n",
1923 server_id_str_buf(exclusive->pid, &buf));
1924 NDR_PRINT_DEBUG(oplock_break_message, &msg);
1925 }
1926
1927 ndr_err = ndr_push_struct_blob(
1928 &blob,
1929 talloc_tos(),
1930 &msg,
1931 (ndr_push_flags_fn_t)ndr_push_oplock_break_message);
1932 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
1933 DBG_WARNING("ndr_push_oplock_break_message failed: %s\n",
1934 ndr_errstr(ndr_err));
1935 return ndr_map_error2ntstatus(ndr_err);
1936 }
1937
1938 status = messaging_send(
1939 msg_ctx, exclusive->pid, MSG_SMB_BREAK_REQUEST, &blob);
1940 TALLOC_FREE(blob.data);
1941 if (!NT_STATUS_IS_OK(status)) {
1942 DEBUG(3, ("Could not send oplock break message: %s\n",
1943 nt_errstr(status)));
1944 }
1945
1946 return status;
1947 }
1948
1949 struct validate_oplock_types_state {
1950 bool valid;
1951 bool batch;
1952 bool ex_or_batch;
1953 bool level2;
1954 bool no_oplock;
1955 uint32_t num_non_stat_opens;
1956 };
1957
1958 static bool validate_oplock_types_fn(
1959 struct share_mode_entry *e,
1960 bool *modified,
1961 void *private_data)
1962 {
1963 struct validate_oplock_types_state *state = private_data;
1964
1965 if (e->op_mid == 0) {
1966 /* INTERNAL_OPEN_ONLY */
1967 return false;
1968 }
1969
1970 if (e->op_type == NO_OPLOCK && is_stat_open(e->access_mask)) {
1971 /*
1972 * We ignore stat opens in the table - they always
1973 * have NO_OPLOCK and never get or cause breaks. JRA.
1974 */
1975 return false;
1976 }
1977
1978 state->num_non_stat_opens += 1;
1979
1980 if (BATCH_OPLOCK_TYPE(e->op_type)) {
1981 /* batch - can only be one. */
1982 if (share_entry_stale_pid(e)) {
1983 DBG_DEBUG("Found stale batch oplock\n");
1984 return false;
1985 }
1986 if (state->ex_or_batch ||
1987 state->batch ||
1988 state->level2 ||
1989 state->no_oplock) {
1990 DBG_ERR("Bad batch oplock entry\n");
1991 state->valid = false;
1992 return true;
1993 }
1994 state->batch = true;
1995 }
1996
1997 if (EXCLUSIVE_OPLOCK_TYPE(e->op_type)) {
1998 if (share_entry_stale_pid(e)) {
1999 DBG_DEBUG("Found stale duplicate oplock\n");
2000 return false;
2001 }
2002 /* Exclusive or batch - can only be one. */
2003 if (state->ex_or_batch ||
2004 state->level2 ||
2005 state->no_oplock) {
2006 DBG_ERR("Bad exclusive or batch oplock entry\n");
2007 state->valid = false;
2008 return true;
2009 }
2010 state->ex_or_batch = true;
2011 }
2012
2013 if (LEVEL_II_OPLOCK_TYPE(e->op_type)) {
2014 if (state->batch || state->ex_or_batch) {
2015 if (share_entry_stale_pid(e)) {
2016 DBG_DEBUG("Found stale LevelII oplock\n");
2017 return false;
2018 }
2019 DBG_DEBUG("Bad levelII oplock entry\n");
2020 state->valid = false;
2021 return true;
2022 }
2023 state->level2 = true;
2024 }
2025
2026 if (e->op_type == NO_OPLOCK) {
2027 if (state->batch || state->ex_or_batch) {
2028 if (share_entry_stale_pid(e)) {
2029 DBG_DEBUG("Found stale NO_OPLOCK entry\n");
2030 return false;
2031 }
2032 DBG_ERR("Bad no oplock entry\n");
2033 state->valid = false;
2034 return true;
2035 }
2036 state->no_oplock = true;
2037 }
2038
2039 return false;
2040 }
2041
2042 /*
2043 * Do internal consistency checks on the share mode for a file.
2044 */
2045
2046 static bool validate_oplock_types(struct share_mode_lock *lck)
2047 {
2048 struct validate_oplock_types_state state = { .valid = true };
2049 bool ok;
2050
2051 ok = share_mode_forall_entries(lck, validate_oplock_types_fn, &state);
2052 if (!ok) {
2053 DBG_DEBUG("share_mode_forall_entries failed\n");
2054 return false;
2055 }
2056 if (!state.valid) {
2057 DBG_DEBUG("Got invalid oplock configuration\n");
2058 return false;
2059 }
2060
2061 if ((state.batch || state.ex_or_batch) &&
2062 (state.num_non_stat_opens != 1)) {
2063 DBG_WARNING("got batch (%d) or ex (%d) non-exclusively "
2064 "(%"PRIu32")\n",
2065 (int)state.batch,
2066 (int)state.ex_or_batch,
2067 state.num_non_stat_opens);
2068 return false;
2069 }
2070
2071 return true;
2072 }
2073
2074 static bool is_same_lease(const files_struct *fsp,
2075 const struct share_mode_entry *e,
2076 const struct smb2_lease *lease)
2077 {
2078 if (e->op_type != LEASE_OPLOCK) {
2079 return false;
2080 }
2081 if (lease == NULL) {
2082 return false;
2083 }
2084
2085 return smb2_lease_equal(fsp_client_guid(fsp),
2086 &lease->lease_key,
2087 &e->client_guid,
2088 &e->lease_key);
2089 }
2090
2091 static bool file_has_brlocks(files_struct *fsp)
2092 {
2093 struct byte_range_lock *br_lck;
2094
2095 br_lck = brl_get_locks_readonly(fsp);
2096 if (!br_lck)
2097 return false;
2098
2099 return (brl_num_locks(br_lck) > 0);
2100 }
2101
2102 struct fsp_lease *find_fsp_lease(struct files_struct *new_fsp,
2103 const struct smb2_lease_key *key,
2104 uint32_t current_state,
2105 uint16_t lease_version,
2106 uint16_t lease_epoch)
2107 {
2108 struct files_struct *fsp;
2109
2110 /*
2111 * TODO: Measure how expensive this loop is with thousands of open
2112 * handles...
2113 */
2114
2115 for (fsp = file_find_di_first(new_fsp->conn->sconn, new_fsp->file_id);
2116 fsp != NULL;
2117 fsp = file_find_di_next(fsp)) {
2118
2119 if (fsp == new_fsp) {
2120 continue;
2121 }
2122 if (fsp->oplock_type != LEASE_OPLOCK) {
2123 continue;
2124 }
2125 if (smb2_lease_key_equal(&fsp->lease->lease.lease_key, key)) {
2126 fsp->lease->ref_count += 1;
2127 return fsp->lease;
2128 }
2129 }
2130
2131 /* Not found - must be leased in another smbd. */
2132 new_fsp->lease = talloc_zero(new_fsp->conn->sconn, struct fsp_lease);
2133 if (new_fsp->lease == NULL) {
2134 return NULL;
2135 }
2136 new_fsp->lease->ref_count = 1;
2137 new_fsp->lease->sconn = new_fsp->conn->sconn;
2138 new_fsp->lease->lease.lease_key = *key;
2139 new_fsp->lease->lease.lease_state = current_state;
2140 /*
2141 * We internally treat all leases as V2 and update
2142 * the epoch, but when sending breaks it matters if
2143 * the requesting lease was v1 or v2.
2144 */
2145 new_fsp->lease->lease.lease_version = lease_version;
2146 new_fsp->lease->lease.lease_epoch = lease_epoch;
2147 return new_fsp->lease;
2148 }
2149
2150 static NTSTATUS try_lease_upgrade(struct files_struct *fsp,
2151 struct share_mode_lock *lck,
2152 const struct GUID *client_guid,
2153 const struct smb2_lease *lease,
2154 uint32_t granted)
2155 {
2156 bool do_upgrade;
2157 uint32_t current_state, breaking_to_requested, breaking_to_required;
2158 bool breaking;
2159 uint16_t lease_version, epoch;
2160 uint32_t existing, requested;
2161 NTSTATUS status;
2162
2163 status = leases_db_get(
2164 client_guid,
2165 &lease->lease_key,
2166 &fsp->file_id,
2167 &current_state,
2168 &breaking,
2169 &breaking_to_requested,
2170 &breaking_to_required,
2171 &lease_version,
2172 &epoch);
2173 if (!NT_STATUS_IS_OK(status)) {
2174 return status;
2175 }
2176
2177 fsp->lease = find_fsp_lease(
2178 fsp,
2179 &lease->lease_key,
2180 current_state,
2181 lease_version,
2182 epoch);
2183 if (fsp->lease == NULL) {
2184 DEBUG(1, ("Did not find existing lease for file %s\n",
2185 fsp_str_dbg(fsp)));
2186 return NT_STATUS_NO_MEMORY;
2187 }
2188
2189 /*
2190 * Upgrade only if the requested lease is a strict upgrade.
2191 */
2192 existing = current_state;
2193 requested = lease->lease_state;
2194
2195 /*
2196 * Tricky: This test makes sure that "requested" is a
2197 * strict bitwise superset of "existing".
2198 */
2199 do_upgrade = ((existing & requested) == existing);
2200
2201 /*
2202 * Upgrade only if there's a change.
2203 */
2204 do_upgrade &= (granted != existing);
2205
2206 /*
2207 * Upgrade only if other leases don't prevent what was asked
2208 * for.
2209 */
2210 do_upgrade &= (granted == requested);
2211
2212 /*
2213 * only upgrade if we are not in breaking state
2214 */
2215 do_upgrade &= !breaking;
2216
2217 DEBUG(10, ("existing=%"PRIu32", requested=%"PRIu32", "
2218 "granted=%"PRIu32", do_upgrade=%d\n",
2219 existing, requested, granted, (int)do_upgrade));
2220
2221 if (do_upgrade) {
2222 NTSTATUS set_status;
2223
2224 current_state = granted;
2225 epoch += 1;
2226
2227 set_status = leases_db_set(
2228 client_guid,
2229 &lease->lease_key,
2230 current_state,
2231 breaking,
2232 breaking_to_requested,
2233 breaking_to_required,
2234 lease_version,
2235 epoch);
2236
2237 if (!NT_STATUS_IS_OK(set_status)) {
2238 DBG_DEBUG("leases_db_set failed: %s\n",
2239 nt_errstr(set_status));
2240 return set_status;
2241 }
2242 }
2243
2244 fsp_lease_update(fsp);
2245
2246 return NT_STATUS_OK;
2247 }
2248
2249 static NTSTATUS grant_new_fsp_lease(struct files_struct *fsp,
2250 struct share_mode_lock *lck,
2251 const struct GUID *client_guid,
2252 const struct smb2_lease *lease,
2253 uint32_t granted)
2254 {
2255 struct share_mode_data *d = lck->data;
2256 NTSTATUS status;
2257
2258 fsp->lease = talloc_zero(fsp->conn->sconn, struct fsp_lease);
2259 if (fsp->lease == NULL) {
2260 return NT_STATUS_INSUFFICIENT_RESOURCES;
2261 }
2262 fsp->lease->ref_count = 1;
2263 fsp->lease->sconn = fsp->conn->sconn;
2264 fsp->lease->lease.lease_version = lease->lease_version;
2265 fsp->lease->lease.lease_key = lease->lease_key;
2266 fsp->lease->lease.lease_state = granted;
2267 fsp->lease->lease.lease_epoch = lease->lease_epoch + 1;
2268
2269 status = leases_db_add(client_guid,
2270 &lease->lease_key,
2271 &fsp->file_id,
2272 fsp->lease->lease.lease_state,
2273 fsp->lease->lease.lease_version,
2274 fsp->lease->lease.lease_epoch,
2275 fsp->conn->connectpath,
2276 fsp->fsp_name->base_name,
2277 fsp->fsp_name->stream_name);
2278 if (!NT_STATUS_IS_OK(status)) {
2279 DEBUG(10, ("%s: leases_db_add failed: %s\n", __func__,
2280 nt_errstr(status)));
2281 TALLOC_FREE(fsp->lease);
2282 return NT_STATUS_INSUFFICIENT_RESOURCES;
2283 }
2284
2285 d->modified = true;
2286
2287 return NT_STATUS_OK;
2288 }
2289
2290 static NTSTATUS grant_fsp_lease(struct files_struct *fsp,
2291 struct share_mode_lock *lck,
2292 const struct smb2_lease *lease,
2293 uint32_t granted)
2294 {
2295 const struct GUID *client_guid = fsp_client_guid(fsp);
2296 NTSTATUS status;
2297
2298 status = try_lease_upgrade(fsp, lck, client_guid, lease, granted);
2299
2300 if (NT_STATUS_EQUAL(status, NT_STATUS_NOT_FOUND)) {
2301 status = grant_new_fsp_lease(
2302 fsp, lck, client_guid, lease, granted);
2303 }
2304
2305 return status;
2306 }
2307
2308 static int map_lease_type_to_oplock(uint32_t lease_type)
2309 {
2310 int result = NO_OPLOCK;
2311
2312 switch (lease_type) {
2313 case SMB2_LEASE_READ|SMB2_LEASE_WRITE|SMB2_LEASE_HANDLE:
2314 result = BATCH_OPLOCK|EXCLUSIVE_OPLOCK;
2315 break;
2316 case SMB2_LEASE_READ|SMB2_LEASE_WRITE:
2317 result = EXCLUSIVE_OPLOCK;
2318 break;
2319 case SMB2_LEASE_READ|SMB2_LEASE_HANDLE:
2320 case SMB2_LEASE_READ:
2321 result = LEVEL_II_OPLOCK;
2322 break;
2323 }
2324
2325 return result;
2326 }
2327
2328 struct delay_for_oplock_state {
2329 struct files_struct *fsp;
2330 const struct smb2_lease *lease;
2331 bool will_overwrite;
2332 uint32_t delay_mask;
2333 bool first_open_attempt;
2334 bool got_handle_lease;
2335 bool got_oplock;
2336 bool have_other_lease;
2337 bool delay;
2338 };
2339
2340 static bool delay_for_oplock_fn(
2341 struct share_mode_entry *e,
2342 bool *modified,
2343 void *private_data)
2344 {
2345 struct delay_for_oplock_state *state = private_data;
2346 struct files_struct *fsp = state->fsp;
2347 const struct smb2_lease *lease = state->lease;
2348 bool e_is_lease = (e->op_type == LEASE_OPLOCK);
2349 uint32_t e_lease_type = get_lease_type(e, fsp->file_id);
2350 uint32_t break_to;
2351 bool lease_is_breaking = false;
2352
2353 if (e_is_lease) {
2354 NTSTATUS status;
2355
2356 if (lease != NULL) {
2357 bool our_lease = is_same_lease(fsp, e, lease);
2358 if (our_lease) {
2359 DBG_DEBUG("Ignoring our own lease\n");
2360 return false;
2361 }
2362 }
2363
2364 status = leases_db_get(
2365 &e->client_guid,
2366 &e->lease_key,
2367 &fsp->file_id,
2368 NULL, /* current_state */
2369 &lease_is_breaking,
2370 NULL, /* breaking_to_requested */
2371 NULL, /* breaking_to_required */
2372 NULL, /* lease_version */
2373 NULL); /* epoch */
2374 SMB_ASSERT(NT_STATUS_IS_OK(status));
2375 }
2376
2377 if (!state->got_handle_lease &&
2378 ((e_lease_type & SMB2_LEASE_HANDLE) != 0) &&
2379 !share_entry_stale_pid(e)) {
2380 state->got_handle_lease = true;
2381 }
2382
2383 if (!state->got_oplock &&
2384 (e->op_type != LEASE_OPLOCK) &&
2385 !share_entry_stale_pid(e)) {
2386 state->got_oplock = true;
2387 }
2388
2389 if (!state->have_other_lease &&
2390 !is_same_lease(fsp, e, lease) &&
2391 !share_entry_stale_pid(e)) {
2392 state->have_other_lease = true;
2393 }
2394
2395 break_to = e_lease_type & ~state->delay_mask;
2396
2397 if (state->will_overwrite) {
2398 break_to &= ~(SMB2_LEASE_HANDLE|SMB2_LEASE_READ);
2399 }
2400
2401 DBG_DEBUG("e_lease_type %u, will_overwrite: %u\n",
2402 (unsigned)e_lease_type,
2403 (unsigned)state->will_overwrite);
2404
2405 if ((e_lease_type & ~break_to) == 0) {
2406 if (lease_is_breaking) {
2407 state->delay = true;
2408 }
2409 return false;
2410 }
2411
2412 if (share_entry_stale_pid(e)) {
2413 return false;
2414 }
2415
2416 if (state->will_overwrite) {
2417 /*
2418 * If we break anyway break to NONE directly.
2419 * Otherwise vfs_set_filelen() will trigger the
2420 * break.
2421 */
2422 break_to &= ~(SMB2_LEASE_READ|SMB2_LEASE_WRITE);
2423 }
2424
2425 if (!e_is_lease) {
2426 /*
2427 * Oplocks only support breaking to R or NONE.
2428 */
2429 break_to &= ~(SMB2_LEASE_HANDLE|SMB2_LEASE_WRITE);
2430 }
2431
2432 DBG_DEBUG("breaking from %d to %d\n",
2433 (int)e_lease_type,
2434 (int)break_to);
2435 send_break_message(
2436 fsp->conn->sconn->msg_ctx, &fsp->file_id, e, break_to);
2437 if (e_lease_type & state->delay_mask) {
2438 state->delay = true;
2439 }
2440 if (lease_is_breaking && !state->first_open_attempt) {
2441 state->delay = true;
2442 }
2443
2444 return false;
2445 };
2446
2447 static NTSTATUS delay_for_oplock(files_struct *fsp,
2448 int oplock_request,
2449 const struct smb2_lease *lease,
2450 struct share_mode_lock *lck,
2451 bool have_sharing_violation,
2452 uint32_t create_disposition,
2453 bool first_open_attempt)
2454 {
2455 struct delay_for_oplock_state state = {
2456 .fsp = fsp,
2457 .lease = lease,
2458 .first_open_attempt = first_open_attempt,
2459 };
2460 uint32_t granted;
2461 NTSTATUS status;
2462 bool ok;
2463
2464 if (is_stat_open(fsp->access_mask)) {
2465 goto grant;
2466 }
2467
2468 state.delay_mask = have_sharing_violation ?
2469 SMB2_LEASE_HANDLE : SMB2_LEASE_WRITE;
2470
2471 switch (create_disposition) {
2472 case FILE_SUPERSEDE:
2473 case FILE_OVERWRITE:
2474 case FILE_OVERWRITE_IF:
2475 state.will_overwrite = true;
2476 break;
2477 default:
2478 state.will_overwrite = false;
2479 break;
2480 }
2481
2482 ok = share_mode_forall_entries(lck, delay_for_oplock_fn, &state);
2483 if (!ok) {
2484 return NT_STATUS_INTERNAL_ERROR;
2485 }
2486
2487 if (state.delay) {
2488 return NT_STATUS_RETRY;
2489 }
2490
2491 grant:
2492 if (have_sharing_violation) {
2493 return NT_STATUS_SHARING_VIOLATION;
2494 }
2495
2496 if (oplock_request == LEASE_OPLOCK) {
2497 if (lease == NULL) {
2498 /*
2499 * The SMB2 layer should have checked this
2500 */
2501 return NT_STATUS_INTERNAL_ERROR;
2502 }
2503
2504 granted = lease->lease_state;
2505
2506 if (lp_kernel_oplocks(SNUM(fsp->conn))) {
2507 DEBUG(10, ("No lease granted because kernel oplocks are enabled\n"));
2508 granted = SMB2_LEASE_NONE;
2509 }
2510 if ((granted & (SMB2_LEASE_READ|SMB2_LEASE_WRITE)) == 0) {
2511 DEBUG(10, ("No read or write lease requested\n"));
2512 granted = SMB2_LEASE_NONE;
2513 }
2514 if (granted == SMB2_LEASE_WRITE) {
2515 DEBUG(10, ("pure write lease requested\n"));
2516 granted = SMB2_LEASE_NONE;
2517 }
2518 if (granted == (SMB2_LEASE_WRITE|SMB2_LEASE_HANDLE)) {
2519 DEBUG(10, ("write and handle lease requested\n"));
2520 granted = SMB2_LEASE_NONE;
2521 }
2522 } else {
2523 granted = map_oplock_to_lease_type(
2524 oplock_request & ~SAMBA_PRIVATE_OPLOCK_MASK);
2525 }
2526
2527 if (lp_locking(fsp->conn->params) && file_has_brlocks(fsp)) {
2528 DBG_DEBUG("file %s has byte range locks\n",
2529 fsp_str_dbg(fsp));
2530 granted &= ~SMB2_LEASE_READ;
2531 }
2532
2533 if (state.have_other_lease) {
2534 /*
2535 * Can grant only one writer
2536 */
2537 granted &= ~SMB2_LEASE_WRITE;
2538 }
2539
2540 if ((granted & SMB2_LEASE_READ) && !(granted & SMB2_LEASE_WRITE)) {
2541 bool allow_level2 =
2542 (global_client_caps & CAP_LEVEL_II_OPLOCKS) &&
2543 lp_level2_oplocks(SNUM(fsp->conn));
2544
2545 if (!allow_level2) {
2546 granted = SMB2_LEASE_NONE;
2547 }
2548 }
2549
2550 if (oplock_request == LEASE_OPLOCK) {
2551 if (state.got_oplock) {
2552 granted &= ~SMB2_LEASE_HANDLE;
2553 }
2554
2555 fsp->oplock_type = LEASE_OPLOCK;
2556
2557 status = grant_fsp_lease(fsp, lck, lease, granted);
2558 if (!NT_STATUS_IS_OK(status)) {
2559 return status;
2560
2561 }
2562
2563 DBG_DEBUG("lease_state=%d\n", fsp->lease->lease.lease_state);
2564 } else {
2565 if (state.got_handle_lease) {
2566 granted = SMB2_LEASE_NONE;
2567 }
2568
2569 fsp->oplock_type = map_lease_type_to_oplock(granted);
2570
2571 status = set_file_oplock(fsp);
2572 if (!NT_STATUS_IS_OK(status)) {
2573 /*
2574 * Could not get the kernel oplock
2575 */
2576 fsp->oplock_type = NO_OPLOCK;
2577 }
2578 }
2579
2580 if (granted & SMB2_LEASE_READ) {
2581 lck->data->flags |= SHARE_MODE_LEASE_READ;
2582 }
2583
2584 DBG_DEBUG("oplock type 0x%x on file %s\n",
2585 fsp->oplock_type, fsp_str_dbg(fsp));
2586
2587 return NT_STATUS_OK;
2588 }
2589
2590 static NTSTATUS handle_share_mode_lease(
2591 files_struct *fsp,
2592 struct share_mode_lock *lck,
2593 uint32_t create_disposition,
2594 uint32_t access_mask,
2595 uint32_t share_access,
2596 int oplock_request,
2597 const struct smb2_lease *lease,
2598 bool first_open_attempt)
2599 {
2600 bool sharing_violation = false;
2601 NTSTATUS status;
2602
2603 status = open_mode_check(
2604 fsp->conn, lck, access_mask, share_access);
2605 if (NT_STATUS_EQUAL(status, NT_STATUS_SHARING_VIOLATION)) {
2606 sharing_violation = true;
2607 status = NT_STATUS_OK; /* handled later */
2608 }
2609
2610 if (!NT_STATUS_IS_OK(status)) {
2611 return status;
2612 }
2613
2614 if (oplock_request == INTERNAL_OPEN_ONLY) {
2615 if (sharing_violation) {
2616 DBG_DEBUG("Sharing violation for internal open\n");
2617 return NT_STATUS_SHARING_VIOLATION;
2618 }
2619
2620 /*
2621 * Internal opens never do oplocks or leases. We don't
2622 * need to go through delay_for_oplock().
2623 */
2624 fsp->oplock_type = NO_OPLOCK;
2625
2626 return NT_STATUS_OK;
2627 }
2628
2629 status = delay_for_oplock(
2630 fsp,
2631 oplock_request,
2632 lease,
2633 lck,
2634 sharing_violation,
2635 create_disposition,
2636 first_open_attempt);
2637 if (!NT_STATUS_IS_OK(status)) {
2638 return status;
2639 }
2640
2641 return NT_STATUS_OK;
2642 }
2643
2644 static bool request_timed_out(struct smb_request *req, struct timeval timeout)
2645 {
2646 struct timeval now, end_time;
2647 GetTimeOfDay(&now);
2648 end_time = timeval_sum(&req->request_time, &timeout);
2649 return (timeval_compare(&end_time, &now) < 0);
2650 }
2651
2652 struct defer_open_state {
2653 struct smbXsrv_connection *xconn;
2654 uint64_t mid;
2655 };
2656
2657 static void defer_open_done(struct tevent_req *req);
2658
2659 /**
2660 * Defer an open and watch a locking.tdb record
2661 *
2662 * This defers an open that gets rescheduled once the locking.tdb record watch
2663 * is triggered by a change to the record.
2664 *
2665 * It is used to defer opens that triggered an oplock break and for the SMB1
2666 * sharing violation delay.
2667 **/
2668 static void defer_open(struct share_mode_lock *lck,
2669 struct timeval timeout,
2670 struct smb_request *req,
2671 bool delayed_for_oplocks,
2672 struct file_id id)
2673 {
2674 struct deferred_open_record *open_rec = NULL;
2675 struct timeval abs_timeout;
2676 struct defer_open_state *watch_state;
2677 struct tevent_req *watch_req;
2678 struct timeval_buf tvbuf1, tvbuf2;
2679 struct file_id_buf fbuf;
2680 bool ok;
2681
2682 abs_timeout = timeval_sum(&req->request_time, &timeout);
2683
2684 DBG_DEBUG("request time [%s] timeout [%s] mid [%" PRIu64 "] "
2685 "delayed_for_oplocks [%s] file_id [%s]\n",
2686 timeval_str_buf(&req->request_time, false, true, &tvbuf1),
2687 timeval_str_buf(&abs_timeout, false, true, &tvbuf2),
2688 req->mid,
2689 delayed_for_oplocks ? "yes" : "no",
2690 file_id_str_buf(id, &fbuf));
2691
2692 open_rec = talloc_zero(NULL, struct deferred_open_record);
2693 if (open_rec == NULL) {
2694 TALLOC_FREE(lck);
2695 exit_server("talloc failed");
2696 }
2697
2698 watch_state = talloc(open_rec, struct defer_open_state);
2699 if (watch_state == NULL) {
2700 exit_server("talloc failed");
2701 }
2702 watch_state->xconn = req->xconn;
2703 watch_state->mid = req->mid;
2704
2705 DBG_DEBUG("defering mid %" PRIu64 "\n", req->mid);
2706
2707 watch_req = dbwrap_watched_watch_send(watch_state,
2708 req->sconn->ev_ctx,
2709 lck->data->record,
2710 (struct server_id){0});
2711 if (watch_req == NULL) {
2712 exit_server("Could not watch share mode record");
2713 }
2714 tevent_req_set_callback(watch_req, defer_open_done, watch_state);
2715
2716 ok = tevent_req_set_endtime(watch_req, req->sconn->ev_ctx, abs_timeout);
2717 if (!ok) {
2718 exit_server("tevent_req_set_endtime failed");
2719 }
2720
2721 ok = push_deferred_open_message_smb(req, timeout, id, open_rec);
2722 if (!ok) {
2723 TALLOC_FREE(lck);
2724 exit_server("push_deferred_open_message_smb failed");
2725 }
2726 }
2727
2728 static void defer_open_done(struct tevent_req *req)
2729 {
2730 struct defer_open_state *state = tevent_req_callback_data(
2731 req, struct defer_open_state);
2732 NTSTATUS status;
2733 bool ret;
2734
2735 status = dbwrap_watched_watch_recv(req, NULL, NULL);
2736 TALLOC_FREE(req);
2737 if (!NT_STATUS_IS_OK(status)) {
2738 DEBUG(5, ("dbwrap_watched_watch_recv returned %s\n",
2739 nt_errstr(status)));
2740 /*
2741 * Even if it failed, retry anyway. TODO: We need a way to
2742 * tell a re-scheduled open about that error.
2743 */
2744 }
2745
2746 DEBUG(10, ("scheduling mid %llu\n", (unsigned long long)state->mid));
2747
2748 ret = schedule_deferred_open_message_smb(state->xconn, state->mid);
2749 SMB_ASSERT(ret);
2750 TALLOC_FREE(state);
2751 }
2752
2753 /**
2754 * Actually attempt the kernel oplock polling open.
2755 */
2756
2757 static void poll_open_fn(struct tevent_context *ev,
2758 struct tevent_timer *te,
2759 struct timeval current_time,
2760 void *private_data)
2761 {
2762 struct deferred_open_record *open_rec = talloc_get_type_abort(
2763 private_data, struct deferred_open_record);
2764 bool ok;
2765
2766 TALLOC_FREE(open_rec->watch_req);
2767
2768 ok = schedule_deferred_open_message_smb(
2769 open_rec->xconn, open_rec->mid);
2770 if (!ok) {
2771 exit_server("schedule_deferred_open_message_smb failed");
2772 }
2773 DBG_DEBUG("timer fired. Retrying open !\n");
2774 }
2775
2776 static void poll_open_done(struct tevent_req *subreq);
2777
2778 /**
2779 * Reschedule an open for 1 second from now, if not timed out.
2780 **/
2781 static bool setup_poll_open(
2782 struct smb_request *req,
2783 struct share_mode_lock *lck,
2784 struct file_id id,
2785 struct timeval max_timeout,
2786 struct timeval interval)
2787 {
2788 bool ok;
2789 struct deferred_open_record *open_rec = NULL;
2790 struct timeval endtime, next_interval;
2791 struct file_id_buf ftmp;
2792
2793 if (request_timed_out(req, max_timeout)) {
2794 return false;
2795 }
2796
2797 open_rec = talloc_zero(NULL, struct deferred_open_record);
2798 if (open_rec == NULL) {
2799 DBG_WARNING("talloc failed\n");
2800 return false;
2801 }
2802 open_rec->xconn = req->xconn;
2803 open_rec->mid = req->mid;
2804
2805 /*
2806 * Make sure open_rec->te does not come later than the
2807 * request's maximum endtime.
2808 */
2809
2810 endtime = timeval_sum(&req->request_time, &max_timeout);
2811 next_interval = timeval_current_ofs(interval.tv_sec, interval.tv_usec);
2812 next_interval = timeval_min(&endtime, &next_interval);
2813
2814 open_rec->te = tevent_add_timer(
2815 req->sconn->ev_ctx,
2816 open_rec,
2817 next_interval,
2818 poll_open_fn,
2819 open_rec);
2820 if (open_rec->te == NULL) {
2821 DBG_WARNING("tevent_add_timer failed\n");
2822 TALLOC_FREE(open_rec);
2823 return false;
2824 }
2825
2826 if (lck != NULL) {
2827 open_rec->watch_req = dbwrap_watched_watch_send(
2828 open_rec,
2829 req->sconn->ev_ctx,
2830 lck->data->record,
2831 (struct server_id) {0});
2832 if (open_rec->watch_req == NULL) {
2833 DBG_WARNING("dbwrap_watched_watch_send failed\n");
2834 TALLOC_FREE(open_rec);
2835 return false;
2836 }
2837 tevent_req_set_callback(
2838 open_rec->watch_req, poll_open_done, open_rec);
2839 }
2840
2841 ok = push_deferred_open_message_smb(req, max_timeout, id, open_rec);
2842 if (!ok) {
2843 DBG_WARNING("push_deferred_open_message_smb failed\n");
2844 TALLOC_FREE(open_rec);
2845 return false;
2846 }
2847
2848 DBG_DEBUG("poll request time [%s] mid [%" PRIu64 "] file_id [%s]\n",
2849 timeval_string(talloc_tos(), &req->request_time, false),
2850 req->mid,
2851 file_id_str_buf(id, &ftmp));
2852
2853 return true;
2854 }
2855
2856 static void poll_open_done(struct tevent_req *subreq)
2857 {
2858 struct deferred_open_record *open_rec = tevent_req_callback_data(
2859 subreq, struct deferred_open_record);
2860 NTSTATUS status;
2861 bool ok;
2862
2863 status = dbwrap_watched_watch_recv(subreq, NULL, NULL);
2864 TALLOC_FREE(subreq);
2865 DBG_DEBUG("dbwrap_watched_watch_recv returned %s\n",
2866 nt_errstr(status));
2867
2868 ok = schedule_deferred_open_message_smb(
2869 open_rec->xconn, open_rec->mid);
2870 if (!ok) {
2871 exit_server("schedule_deferred_open_message_smb failed");
2872 }
2873 }
2874
2875 bool defer_smb1_sharing_violation(struct smb_request *req)
2876 {
2877 bool ok;
2878 int timeout_usecs;
2879
2880 if (!lp_defer_sharing_violations()) {
2881 return false;
2882 }
2883
2884 /*
2885 * Try every 200msec up to (by default) one second. To be
2886 * precise, according to behaviour note <247> in [MS-CIFS],
2887 * the server tries 5 times. But up to one second should be
2888 * close enough.
2889 */
2890
2891 timeout_usecs = lp_parm_int(
2892 SNUM(req->conn),
2893 "smbd",
2894 "sharedelay",
2895 SHARING_VIOLATION_USEC_WAIT);
2896
2897 ok = setup_poll_open(
2898 req,
2899 NULL,
2900 (struct file_id) {0},
2901 (struct timeval) { .tv_usec = timeout_usecs },
2902 (struct timeval) { .tv_usec = 200000 });
2903 return ok;
2904 }
2905
2906 /****************************************************************************
2907 On overwrite open ensure that the attributes match.
2908 ****************************************************************************/
2909
2910 static bool open_match_attributes(connection_struct *conn,
2911 uint32_t old_dos_attr,
2912 uint32_t new_dos_attr,
2913 mode_t new_unx_mode,
2914 mode_t *returned_unx_mode)
2915 {
2916 uint32_t noarch_old_dos_attr, noarch_new_dos_attr;
2917
2918 noarch_old_dos_attr = (old_dos_attr & ~FILE_ATTRIBUTE_ARCHIVE);
2919 noarch_new_dos_attr = (new_dos_attr & ~FILE_ATTRIBUTE_ARCHIVE);
2920
2921 if((noarch_old_dos_attr == 0 && noarch_new_dos_attr != 0) ||
2922 (noarch_old_dos_attr != 0 && ((noarch_old_dos_attr & noarch_new_dos_attr) == noarch_old_dos_attr))) {
2923 *returned_unx_mode = new_unx_mode;
2924 } else {
2925 *returned_unx_mode = (mode_t)0;
2926 }
2927
2928 DEBUG(10,("open_match_attributes: old_dos_attr = 0x%x, "
2929 "new_dos_attr = 0x%x "
2930 "returned_unx_mode = 0%o\n",
2931 (unsigned int)old_dos_attr,
2932 (unsigned int)new_dos_attr,
2933 (unsigned int)*returned_unx_mode ));
2934
2935 /* If we're mapping SYSTEM and HIDDEN ensure they match. */
2936 if (lp_map_system(SNUM(conn)) || lp_store_dos_attributes(SNUM(conn))) {
2937 if ((old_dos_attr & FILE_ATTRIBUTE_SYSTEM) &&
2938 !(new_dos_attr & FILE_ATTRIBUTE_SYSTEM)) {
2939 return False;
2940 }
2941 }
2942 if (lp_map_hidden(SNUM(conn)) || lp_store_dos_attributes(SNUM(conn))) {
2943 if ((old_dos_attr & FILE_ATTRIBUTE_HIDDEN) &&
2944 !(new_dos_attr & FILE_ATTRIBUTE_HIDDEN)) {
2945 return False;
2946 }
2947 }
2948 return True;
2949 }
2950
2951 static void schedule_defer_open(struct share_mode_lock *lck,
2952 struct file_id id,
2953 struct smb_request *req)
2954 {
2955 /* This is a relative time, added to the absolute
2956 request_time value to get the absolute timeout time.
2957 Note that if this is the second or greater time we enter
2958 this codepath for this particular request mid then
2959 request_time is left as the absolute time of the *first*
2960 time this request mid was processed. This is what allows
2961 the request to eventually time out. */
2962
2963 struct timeval timeout;
2964
2965 /* Normally the smbd we asked should respond within
2966 * OPLOCK_BREAK_TIMEOUT seconds regardless of whether
2967 * the client did, give twice the timeout as a safety
2968 * measure here in case the other smbd is stuck
2969 * somewhere else. */
2970
2971 timeout = timeval_set(OPLOCK_BREAK_TIMEOUT*2, 0);
2972
2973 if (request_timed_out(req, timeout)) {
2974 return;
2975 }
2976
2977 defer_open(lck, timeout, req, true, id);
2978 }
2979
2980 /****************************************************************************
2981 Reschedule an open call that went asynchronous.
2982 ****************************************************************************/
2983
2984 static void schedule_async_open_timer(struct tevent_context *ev,
2985 struct tevent_timer *te,
2986 struct timeval current_time,
2987 void *private_data)
2988 {
2989 exit_server("async open timeout");
2990 }
2991
2992 static void schedule_async_open(struct smb_request *req)
2993 {
2994 struct deferred_open_record *open_rec = NULL;
2995 struct timeval timeout = timeval_set(20, 0);
2996 bool ok;
2997
2998 if (request_timed_out(req, timeout)) {
2999 return;
3000 }
3001
3002 open_rec = talloc_zero(NULL, struct deferred_open_record);
3003 if (open_rec == NULL) {
3004 exit_server("deferred_open_record_create failed");
3005 }
3006 open_rec->async_open = true;
3007
3008 ok = push_deferred_open_message_smb(
3009 req, timeout, (struct file_id){0}, open_rec);
3010 if (!ok) {
3011 exit_server("push_deferred_open_message_smb failed");
3012 }
3013
3014 open_rec->te = tevent_add_timer(req->sconn->ev_ctx,
3015 req,
3016 timeval_current_ofs(20, 0),
3017 schedule_async_open_timer,
3018 open_rec);
3019 if (open_rec->te == NULL) {
3020 exit_server("tevent_add_timer failed");
3021 }
3022 }
3023
3024 /****************************************************************************
3025 Work out what access_mask to use from what the client sent us.
3026 ****************************************************************************/
3027
3028 static NTSTATUS smbd_calculate_maximum_allowed_access(
3029 connection_struct *conn,
3030 const struct smb_filename *smb_fname,
3031 bool use_privs,
3032 uint32_t *p_access_mask)
3033 {
3034 struct security_descriptor *sd;
3035 uint32_t access_granted;
3036 NTSTATUS status;
3037
3038 if (!use_privs && (get_current_uid(conn) == (uid_t)0)) {
3039 *p_access_mask |= FILE_GENERIC_ALL;
3040 return NT_STATUS_OK;
3041 }
3042
3043 status = SMB_VFS_GET_NT_ACL(conn, smb_fname,
3044 (SECINFO_OWNER |
3045 SECINFO_GROUP |
3046 SECINFO_DACL),
3047 talloc_tos(), &sd);
3048
3049 if (NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
3050 /*
3051 * File did not exist
3052 */
3053 *p_access_mask = FILE_GENERIC_ALL;
3054 return NT_STATUS_OK;
3055 }
3056 if (!NT_STATUS_IS_OK(status)) {
3057 DEBUG(10,("Could not get acl on file %s: %s\n",
3058 smb_fname_str_dbg(smb_fname),
3059 nt_errstr(status)));
3060 return NT_STATUS_ACCESS_DENIED;
3061 }
3062
3063 /*
3064 * If we can access the path to this file, by
3065 * default we have FILE_READ_ATTRIBUTES from the
3066 * containing directory. See the section:
3067 * "Algorithm to Check Access to an Existing File"
3068 * in MS-FSA.pdf.
3069 *
3070 * se_file_access_check()
3071 * also takes care of owner WRITE_DAC and READ_CONTROL.
3072 */
3073 status = se_file_access_check(sd,
3074 get_current_nttok(conn),
3075 use_privs,
3076 (*p_access_mask & ~FILE_READ_ATTRIBUTES),
3077 &access_granted);
3078
3079 TALLOC_FREE(sd);
3080
3081 if (!NT_STATUS_IS_OK(status)) {
3082 DEBUG(10, ("Access denied on file %s: "
3083 "when calculating maximum access\n",
3084 smb_fname_str_dbg(smb_fname)));
3085 return NT_STATUS_ACCESS_DENIED;
3086 }
3087 *p_access_mask = (access_granted | FILE_READ_ATTRIBUTES);
3088
3089 if (!(access_granted & DELETE_ACCESS)) {
3090 if (can_delete_file_in_directory(conn, smb_fname)) {
3091 *p_access_mask |= DELETE_ACCESS;
3092 }
3093 }
3094
3095 return NT_STATUS_OK;
3096 }
3097
3098 NTSTATUS smbd_calculate_access_mask(connection_struct *conn,
3099 const struct smb_filename *smb_fname,
3100 bool use_privs,
3101 uint32_t access_mask,
3102 uint32_t *access_mask_out)
3103 {
3104 NTSTATUS status;
3105 uint32_t orig_access_mask = access_mask;
3106 uint32_t rejected_share_access;
3107
3108 if (access_mask & SEC_MASK_INVALID) {
3109 DBG_DEBUG("access_mask [%8x] contains invalid bits\n",
3110 access_mask);
3111 return NT_STATUS_ACCESS_DENIED;
3112 }
3113
3114 /*
3115 * Convert GENERIC bits to specific bits.
3116 */
3117
3118 se_map_generic(&access_mask, &file_generic_mapping);
3119
3120 /* Calculate MAXIMUM_ALLOWED_ACCESS if requested. */
3121 if (access_mask & MAXIMUM_ALLOWED_ACCESS) {
3122
3123 status = smbd_calculate_maximum_allowed_access(
3124 conn, smb_fname, use_privs, &access_mask);
3125
3126 if (!NT_STATUS_IS_OK(status)) {
3127 return status;
3128 }
3129
3130 access_mask &= conn->share_access;
3131 }
3132
3133 rejected_share_access = access_mask & ~(conn->share_access);
3134
3135 if (rejected_share_access) {
3136 DEBUG(10, ("smbd_calculate_access_mask: Access denied on "
3137 "file %s: rejected by share access mask[0x%08X] "
3138 "orig[0x%08X] mapped[0x%08X] reject[0x%08X]\n",
3139 smb_fname_str_dbg(smb_fname),
3140 conn->share_access,
3141 orig_access_mask, access_mask,
3142 rejected_share_access));
3143 return NT_STATUS_ACCESS_DENIED;
3144 }
3145
3146 *access_mask_out = access_mask;
3147 return NT_STATUS_OK;
3148 }
3149
3150 /****************************************************************************
3151 Remove the deferred open entry under lock.
3152 ****************************************************************************/
3153
3154 /****************************************************************************
3155 Return true if this is a state pointer to an asynchronous create.
3156 ****************************************************************************/
3157
3158 bool is_deferred_open_async(const struct deferred_open_record *rec)
3159 {
3160 return rec->async_open;
3161 }
3162
3163 static bool clear_ads(uint32_t create_disposition)
3164 {
3165 bool ret = false;
3166
3167 switch (create_disposition) {
3168 case FILE_SUPERSEDE:
3169 case FILE_OVERWRITE_IF:
3170 case FILE_OVERWRITE:
3171 ret = true;
3172 break;
3173 default:
3174 break;
3175 }
3176 return ret;
3177 }
3178
3179 static int disposition_to_open_flags(uint32_t create_disposition)
3180 {
3181 int ret = 0;
3182
3183 /*
3184 * Currently we're using FILE_SUPERSEDE as the same as
3185 * FILE_OVERWRITE_IF but they really are
3186 * different. FILE_SUPERSEDE deletes an existing file
3187 * (requiring delete access) then recreates it.
3188 */
3189
3190 switch (create_disposition) {
3191 case FILE_SUPERSEDE:
3192 case FILE_OVERWRITE_IF:
3193 /*
3194 * If file exists replace/overwrite. If file doesn't
3195 * exist create.
3196 */
3197 ret = O_CREAT|O_TRUNC;
3198 break;
3199
3200 case FILE_OPEN:
3201 /*
3202 * If file exists open. If file doesn't exist error.
3203 */
3204 ret = 0;
3205 break;
3206
3207 case FILE_OVERWRITE:
3208 /*
3209 * If file exists overwrite. If file doesn't exist
3210 * error.
3211 */
3212 ret = O_TRUNC;
3213 break;
3214
3215 case FILE_CREATE:
3216 /*
3217 * If file exists error. If file doesn't exist create.
3218 */
3219 ret = O_CREAT|O_EXCL;
3220 break;
3221
3222 case FILE_OPEN_IF:
3223 /*
3224 * If file exists open. If file doesn't exist create.
3225 */
3226 ret = O_CREAT;
3227 break;
3228 }
3229 return ret;
3230 }
3231
3232 static int calculate_open_access_flags(uint32_t access_mask,
3233 uint32_t private_flags)
3234 {
3235 bool need_write, need_read;
3236
3237 /*
3238 * Note that we ignore the append flag as append does not
3239 * mean the same thing under DOS and Unix.
3240 */
3241
3242 need_write = (access_mask & (FILE_WRITE_DATA | FILE_APPEND_DATA));
3243 if (!need_write) {
3244 return O_RDONLY;
3245 }
3246
3247 /* DENY_DOS opens are always underlying read-write on the
3248 file handle, no matter what the requested access mask
3249 says. */
3250
3251 need_read =
3252 ((private_flags & NTCREATEX_OPTIONS_PRIVATE_DENY_DOS) ||
3253 access_mask & (FILE_READ_ATTRIBUTES|FILE_READ_DATA|
3254 FILE_READ_EA|FILE_EXECUTE));
3255
3256 if (!need_read) {
3257 return O_WRONLY;
3258 }
3259 return O_RDWR;
3260 }
3261
3262 /****************************************************************************
3263 Open a file with a share mode. Passed in an already created files_struct *.
3264 ****************************************************************************/
3265
3266 static NTSTATUS open_file_ntcreate(connection_struct *conn,
3267 struct smb_request *req,
3268 uint32_t access_mask, /* access bits (FILE_READ_DATA etc.) */
3269 uint32_t share_access, /* share constants (FILE_SHARE_READ etc) */
3270 uint32_t create_disposition, /* FILE_OPEN_IF etc. */
3271 uint32_t create_options, /* options such as delete on close. */
3272 uint32_t new_dos_attributes, /* attributes used for new file. */
3273 int oplock_request, /* internal Samba oplock codes. */
3274 const struct smb2_lease *lease,
3275 /* Information (FILE_EXISTS etc.) */
3276 uint32_t private_flags, /* Samba specific flags. */
3277 int *pinfo,
3278 files_struct *fsp)
3279 {
3280 struct smb_filename *smb_fname = fsp->fsp_name;
3281 int flags=0;
3282 int flags2=0;
3283 bool file_existed = VALID_STAT(smb_fname->st);
3284 bool def_acl = False;
3285 bool posix_open = False;
3286 bool new_file_created = False;
3287 bool first_open_attempt = true;
3288 NTSTATUS fsp_open = NT_STATUS_ACCESS_DENIED;
3289 mode_t new_unx_mode = (mode_t)0;
3290 mode_t unx_mode = (mode_t)0;
3291 int info;
3292 uint32_t existing_dos_attributes = 0;
3293 struct share_mode_lock *lck = NULL;
3294 uint32_t open_access_mask = access_mask;
3295 NTSTATUS status;
3296 char *parent_dir;
3297 SMB_STRUCT_STAT saved_stat = smb_fname->st;
3298 struct timespec old_write_time;
3299 struct file_id id;
3300 bool ok;
3301
3302 if (conn->printer) {
3303 /*
3304 * Printers are handled completely differently.
3305 * Most of the passed parameters are ignored.
3306 */
3307
3308 if (pinfo) {
3309 *pinfo = FILE_WAS_CREATED;
3310 }
3311
3312 DEBUG(10, ("open_file_ntcreate: printer open fname=%s\n",
3313 smb_fname_str_dbg(smb_fname)));
3314
3315 if (!req) {
3316 DEBUG(0,("open_file_ntcreate: printer open without "
3317 "an SMB request!\n"));
3318 return NT_STATUS_INTERNAL_ERROR;
3319 }
3320
3321 return print_spool_open(fsp, smb_fname->base_name,
3322 req->vuid);
3323 }
3324
3325 if (!parent_dirname(talloc_tos(), smb_fname->base_name, &parent_dir,
3326 NULL)) {
3327 return NT_STATUS_NO_MEMORY;
3328 }
3329
3330 if (new_dos_attributes & FILE_FLAG_POSIX_SEMANTICS) {
3331 posix_open = True;
3332 unx_mode = (mode_t)(new_dos_attributes & ~FILE_FLAG_POSIX_SEMANTICS);
3333 new_dos_attributes = 0;
3334 } else {
3335 /* Windows allows a new file to be created and
3336 silently removes a FILE_ATTRIBUTE_DIRECTORY
3337 sent by the client. Do the same. */
3338
3339 new_dos_attributes &= ~FILE_ATTRIBUTE_DIRECTORY;
3340
3341 /* We add FILE_ATTRIBUTE_ARCHIVE to this as this mode is only used if the file is
3342 * created new. */
3343 unx_mode = unix_mode(conn, new_dos_attributes | FILE_ATTRIBUTE_ARCHIVE,
3344 smb_fname, parent_dir);
3345 }
3346
3347 DEBUG(10, ("open_file_ntcreate: fname=%s, dos_attrs=0x%x "
3348 "access_mask=0x%x share_access=0x%x "
3349 "create_disposition = 0x%x create_options=0x%x "
3350 "unix mode=0%o oplock_request=%d private_flags = 0x%x\n",
3351 smb_fname_str_dbg(smb_fname), new_dos_attributes,
3352 access_mask, share_access, create_disposition,
3353 create_options, (unsigned int)unx_mode, oplock_request,
3354 (unsigned int)private_flags));
3355
3356 if (req == NULL) {
3357 /* Ensure req == NULL means INTERNAL_OPEN_ONLY */
3358 SMB_ASSERT(oplock_request == INTERNAL_OPEN_ONLY);
3359 } else {
3360 /* And req != NULL means no INTERNAL_OPEN_ONLY */
3361 SMB_ASSERT(((oplock_request & INTERNAL_OPEN_ONLY) == 0));
3362 }
3363
3364 /*
3365 * Only non-internal opens can be deferred at all
3366 */
3367
3368 if (req) {
3369 struct deferred_open_record *open_rec;
3370 if (get_deferred_open_message_state(req, NULL, &open_rec)) {
3371
3372 /* If it was an async create retry, the file
3373 didn't exist. */
3374
3375 if (is_deferred_open_async(open_rec)) {
3376 SET_STAT_INVALID(smb_fname->st);
3377 file_existed = false;
3378 }
3379
3380 /* Ensure we don't reprocess this message. */
3381 remove_deferred_open_message_smb(req->xconn, req->mid);
3382
3383 first_open_attempt = false;
3384 }
3385 }
3386
3387 if (!posix_open) {
3388 new_dos_attributes &= SAMBA_ATTRIBUTES_MASK;
3389 if (file_existed) {
3390 /*
3391 * Only use stored DOS attributes for checks
3392 * against requested attributes (below via
3393 * open_match_attributes()), cf bug #11992
3394 * for details. -slow
3395 */
3396 uint32_t attr = 0;
3397
3398 status = SMB_VFS_GET_DOS_ATTRIBUTES(conn, smb_fname, &attr);
3399 if (NT_STATUS_IS_OK(status)) {
3400 existing_dos_attributes = attr;
3401 }
3402 }
3403 }
3404
3405 /* ignore any oplock requests if oplocks are disabled */
3406 if (!lp_oplocks(SNUM(conn)) ||
3407 IS_VETO_OPLOCK_PATH(conn, smb_fname->base_name)) {
3408 /* Mask off everything except the private Samba bits. */
3409 oplock_request &= SAMBA_PRIVATE_OPLOCK_MASK;
3410 }
3411
3412 /* this is for OS/2 long file names - say we don't support them */
3413 if (req != NULL && !req->posix_pathnames &&
3414 strstr(smb_fname->base_name,".+,;=[].")) {
3415 /* OS/2 Workplace shell fix may be main code stream in a later
3416 * release. */
3417 DEBUG(5,("open_file_ntcreate: OS/2 long filenames are not "
3418 "supported.\n"));
3419 if (use_nt_status()) {
3420 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3421 }
3422 return NT_STATUS_DOS(ERRDOS, ERRcannotopen);
3423 }
3424
3425 switch( create_disposition ) {
3426 case FILE_OPEN:
3427 /* If file exists open. If file doesn't exist error. */
3428 if (!file_existed) {
3429 DEBUG(5,("open_file_ntcreate: FILE_OPEN "
3430 "requested for file %s and file "
3431 "doesn't exist.\n",
3432 smb_fname_str_dbg(smb_fname)));
3433 errno = ENOENT;
3434 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3435 }
3436 break;
3437
3438 case FILE_OVERWRITE:
3439 /* If file exists overwrite. If file doesn't exist
3440 * error. */
3441 if (!file_existed) {
3442 DEBUG(5,("open_file_ntcreate: FILE_OVERWRITE "
3443 "requested for file %s and file "
3444 "doesn't exist.\n",
3445 smb_fname_str_dbg(smb_fname) ));
3446 errno = ENOENT;
3447 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3448 }
3449 break;
3450
3451 case FILE_CREATE:
3452 /* If file exists error. If file doesn't exist
3453 * create. */
3454 if (file_existed) {
3455 DEBUG(5,("open_file_ntcreate: FILE_CREATE "
3456 "requested for file %s and file "
3457 "already exists.\n",
3458 smb_fname_str_dbg(smb_fname)));
3459 if (S_ISDIR(smb_fname->st.st_ex_mode)) {
3460 errno = EISDIR;
3461 } else {
3462 errno = EEXIST;
3463 }
3464 return map_nt_error_from_unix(errno);
3465 }
3466 break;
3467
3468 case FILE_SUPERSEDE:
3469 case FILE_OVERWRITE_IF:
3470 case FILE_OPEN_IF:
3471 break;
3472 default:
3473 return NT_STATUS_INVALID_PARAMETER;
3474 }
3475
3476 flags2 = disposition_to_open_flags(create_disposition);
3477
3478 /* We only care about matching attributes on file exists and
3479 * overwrite. */
3480
3481 if (!posix_open && file_existed &&
3482 ((create_disposition == FILE_OVERWRITE) ||
3483 (create_disposition == FILE_OVERWRITE_IF))) {
3484 if (!open_match_attributes(conn, existing_dos_attributes,
3485 new_dos_attributes,
3486 unx_mode, &new_unx_mode)) {
3487 DEBUG(5,("open_file_ntcreate: attributes mismatch "
3488 "for file %s (%x %x) (0%o, 0%o)\n",
3489 smb_fname_str_dbg(smb_fname),
3490 existing_dos_attributes,
3491 new_dos_attributes,
3492 (unsigned int)smb_fname->st.st_ex_mode,
3493 (unsigned int)unx_mode ));
3494 errno = EACCES;
3495 return NT_STATUS_ACCESS_DENIED;
3496 }
3497 }
3498
3499 status = smbd_calculate_access_mask(conn, smb_fname,
3500 false,
3501 access_mask,
3502 &access_mask);
3503 if (!NT_STATUS_IS_OK(status)) {
3504 DEBUG(10, ("open_file_ntcreate: smbd_calculate_access_mask "
3505 "on file %s returned %s\n",
3506 smb_fname_str_dbg(smb_fname), nt_errstr(status)));
3507 return status;
3508 }
3509
3510 open_access_mask = access_mask;
3511
3512 if (flags2 & O_TRUNC) {
3513 open_access_mask |= FILE_WRITE_DATA; /* This will cause oplock breaks. */
3514 }
3515
3516 if (file_existed) {
3517 /*
3518 * stat opens on existing files don't get oplocks.
3519 * They can get leases.
3520 *
3521 * Note that we check for stat open on the *open_access_mask*,
3522 * i.e. the access mask we actually used to do the open,
3523 * not the one the client asked for (which is in
3524 * fsp->access_mask). This is due to the fact that
3525 * FILE_OVERWRITE and FILE_OVERWRITE_IF add in O_TRUNC,
3526 * which adds FILE_WRITE_DATA to open_access_mask.
3527 */
3528 if (is_stat_open(open_access_mask) && lease == NULL) {
3529 oplock_request = NO_OPLOCK;
3530 }
3531 }
3532
3533 DEBUG(10, ("open_file_ntcreate: fname=%s, after mapping "
3534 "access_mask=0x%x\n", smb_fname_str_dbg(smb_fname),
3535 access_mask));
3536
3537 /*
3538 * Note that we ignore the append flag as append does not
3539 * mean the same thing under DOS and Unix.
3540 */
3541
3542 flags = calculate_open_access_flags(access_mask, private_flags);
3543
3544 /*
3545 * Currently we only look at FILE_WRITE_THROUGH for create options.
3546 */
3547
3548 #if defined(O_SYNC)
3549 if ((create_options & FILE_WRITE_THROUGH) && lp_strict_sync(SNUM(conn))) {
3550 flags2 |= O_SYNC;
3551 }
3552 #endif /* O_SYNC */
3553
3554 if (posix_open && (access_mask & FILE_APPEND_DATA)) {
3555 flags2 |= O_APPEND;
3556 }
3557
3558 if (!posix_open && !CAN_WRITE(conn)) {
3559 /*
3560 * We should really return a permission denied error if either
3561 * O_CREAT or O_TRUNC are set, but for compatibility with
3562 * older versions of Samba we just AND them out.
3563 */
3564 flags2 &= ~(O_CREAT|O_TRUNC);
3565 }
3566
3567 /*
3568 * With kernel oplocks the open breaking an oplock
3569 * blocks until the oplock holder has given up the
3570 * oplock or closed the file. We prevent this by always
3571 * trying to open the file with O_NONBLOCK (see "man
3572 * fcntl" on Linux).
3573 *
3574 * If a process that doesn't use the smbd open files
3575 * database or communication methods holds a kernel
3576 * oplock we must periodically poll for available open
3577 * using O_NONBLOCK.
3578 */
3579 flags2 |= O_NONBLOCK;
3580
3581 /*
3582 * Ensure we can't write on a read-only share or file.
3583 */
3584
3585 if (flags != O_RDONLY && file_existed &&
3586 (!CAN_WRITE(conn) || IS_DOS_READONLY(existing_dos_attributes))) {
3587 DEBUG(5,("open_file_ntcreate: write access requested for "
3588 "file %s on read only %s\n",
3589 smb_fname_str_dbg(smb_fname),
3590 !CAN_WRITE(conn) ? "share" : "file" ));
3591 errno = EACCES;
3592 return NT_STATUS_ACCESS_DENIED;
3593 }
3594
3595 fsp->file_id = vfs_file_id_from_sbuf(conn, &smb_fname->st);
3596 fsp->fh->private_options = private_flags;
3597 fsp->access_mask = open_access_mask; /* We change this to the
3598 * requested access_mask after
3599 * the open is done. */
3600 if (posix_open) {
3601 fsp->posix_flags |= FSP_POSIX_FLAGS_ALL;
3602 }
3603
3604 if ((create_options & FILE_DELETE_ON_CLOSE) &&
3605 (flags2 & O_CREAT) &&
3606 !file_existed) {
3607 /* Delete on close semantics for new files. */
3608 status = can_set_delete_on_close(fsp,
3609 new_dos_attributes);
3610 if (!NT_STATUS_IS_OK(status)) {
3611 fd_close(fsp);
3612 return status;
3613 }
3614 }
3615
3616 /*
3617 * Ensure we pay attention to default ACLs on directories if required.
3618 */
3619
3620 if ((flags2 & O_CREAT) && lp_inherit_acls(SNUM(conn)) &&
3621 (def_acl = directory_has_default_acl(conn, parent_dir))) {
3622 unx_mode = (0777 & lp_create_mask(SNUM(conn)));
3623 }
3624
3625 DEBUG(4,("calling open_file with flags=0x%X flags2=0x%X mode=0%o, "
3626 "access_mask = 0x%x, open_access_mask = 0x%x\n",
3627 (unsigned int)flags, (unsigned int)flags2,
3628 (unsigned int)unx_mode, (unsigned int)access_mask,
3629 (unsigned int)open_access_mask));
3630
3631 fsp_open = open_file(fsp, conn, req, parent_dir,
3632 flags|flags2, unx_mode, access_mask,
3633 open_access_mask, &new_file_created);
3634
3635 if (NT_STATUS_EQUAL(fsp_open, NT_STATUS_NETWORK_BUSY)) {
3636 /*
3637 * This handles the kernel oplock case:
3638 *
3639 * the file has an active kernel oplock and the open() returned
3640 * EWOULDBLOCK/EAGAIN which maps to NETWORK_BUSY.
3641 *
3642 * "Samba locking.tdb oplocks" are handled below after acquiring
3643 * the sharemode lock with get_share_mode_lock().
3644 */
3645 if (file_existed && S_ISFIFO(fsp->fsp_name->st.st_ex_mode)) {
3646 DEBUG(10, ("FIFO busy\n"));
3647 return NT_STATUS_NETWORK_BUSY;
3648 }
3649 if (req == NULL) {
3650 DEBUG(10, ("Internal open busy\n"));
3651 return NT_STATUS_NETWORK_BUSY;
3652 }
3653
3654 /*
3655 * From here on we assume this is an oplock break triggered
3656 */
3657
3658 lck = get_existing_share_mode_lock(talloc_tos(), fsp->file_id);
3659
3660 if ((lck != NULL) && !validate_oplock_types(lck)) {
3661 smb_panic("validate_oplock_types failed");
3662 }
3663
3664 /*
3665 * Retry once a second. If there's a share_mode_lock
3666 * around, also wait for it in case it was smbd
3667 * holding that kernel oplock that can quickly tell us
3668 * the oplock got removed.
3669 */
3670
3671 setup_poll_open(
3672 req,
3673 lck,
3674 fsp->file_id,
3675 timeval_set(OPLOCK_BREAK_TIMEOUT*2, 0),
3676 timeval_set(1, 0));
3677
3678 TALLOC_FREE(lck);
3679
3680 return NT_STATUS_SHARING_VIOLATION;
3681 }
3682
3683 if (!NT_STATUS_IS_OK(fsp_open)) {
3684 if (NT_STATUS_EQUAL(fsp_open, NT_STATUS_RETRY)) {
3685 schedule_async_open(req);
3686 }
3687 return fsp_open;
3688 }
3689
3690 if (new_file_created) {
3691 /*
3692 * As we atomically create using O_CREAT|O_EXCL,
3693 * then if new_file_created is true, then
3694 * file_existed *MUST* have been false (even
3695 * if the file was previously detected as being
3696 * there).
3697 */
3698 file_existed = false;
3699 }
3700
3701 if (file_existed && !check_same_dev_ino(&saved_stat, &smb_fname->st)) {
3702 /*
3703 * The file did exist, but some other (local or NFS)
3704 * process either renamed/unlinked and re-created the
3705 * file with different dev/ino after we walked the path,
3706 * but before we did the open. We could retry the
3707 * open but it's a rare enough case it's easier to
3708 * just fail the open to prevent creating any problems
3709 * in the open file db having the wrong dev/ino key.
3710 */
3711 fd_close(fsp);
3712 DBG_WARNING("file %s - dev/ino mismatch. "
3713 "Old (dev=%ju, ino=%ju). "
3714 "New (dev=%ju, ino=%ju). Failing open "
3715 "with NT_STATUS_ACCESS_DENIED.\n",
3716 smb_fname_str_dbg(smb_fname),
3717 (uintmax_t)saved_stat.st_ex_dev,
3718 (uintmax_t)saved_stat.st_ex_ino,
3719 (uintmax_t)smb_fname->st.st_ex_dev,
3720 (uintmax_t)smb_fname->st.st_ex_ino);
3721 return NT_STATUS_ACCESS_DENIED;
3722 }
3723
3724 old_write_time = smb_fname->st.st_ex_mtime;
3725
3726 /*
3727 * Deal with the race condition where two smbd's detect the
3728 * file doesn't exist and do the create at the same time. One
3729 * of them will win and set a share mode, the other (ie. this
3730 * one) should check if the requested share mode for this
3731 * create is allowed.
3732 */
3733
3734 /*
3735 * Now the file exists and fsp is successfully opened,
3736 * fsp->dev and fsp->inode are valid and should replace the
3737 * dev=0,inode=0 from a non existent file. Spotted by
3738 * Nadav Danieli <nadavd@exanet.com>. JRA.
3739 */
3740
3741 id = fsp->file_id;
3742
3743 lck = get_share_mode_lock(talloc_tos(), id,
3744 conn->connectpath,
3745 smb_fname, &old_write_time);
3746
3747 if (lck == NULL) {
3748 DEBUG(0, ("open_file_ntcreate: Could not get share "
3749 "mode lock for %s\n",
3750 smb_fname_str_dbg(smb_fname)));
3751 fd_close(fsp);
3752 return NT_STATUS_SHARING_VIOLATION;
3753 }
3754
3755 /* Get the types we need to examine. */
3756 if (!validate_oplock_types(lck)) {
3757 smb_panic("validate_oplock_types failed");
3758 }
3759
3760 if (has_delete_on_close(lck, fsp->name_hash)) {
3761 TALLOC_FREE(lck);
3762 fd_close(fsp);
3763 return NT_STATUS_DELETE_PENDING;
3764 }
3765
3766 status = handle_share_mode_lease(
3767 fsp,
3768 lck,
3769 create_disposition,
3770 access_mask,
3771 share_access,
3772 oplock_request,
3773 lease,
3774 first_open_attempt);
3775
3776 if (NT_STATUS_EQUAL(status, NT_STATUS_RETRY)) {
3777 schedule_defer_open(lck, fsp->file_id, req);
3778 TALLOC_FREE(lck);
3779 fd_close(fsp);
3780 return NT_STATUS_SHARING_VIOLATION;
3781 }
3782
3783 if (!NT_STATUS_IS_OK(status)) {
3784 TALLOC_FREE(lck);
3785 fd_close(fsp);
3786 return status;
3787 }
3788
3789 {
3790 struct share_mode_data *d = lck->data;
3791 uint16_t new_flags = share_mode_flags_restrict(
3792 d->flags, access_mask, share_access, UINT32_MAX);
3793
3794 if (new_flags != d->flags) {
3795 d->flags = new_flags;
3796 d->modified = true;
3797 }
3798 }
3799
3800 ok = set_share_mode(
3801 lck,
3802 fsp,
3803 get_current_uid(fsp->conn),
3804 req ? req->mid : 0,
3805 fsp->oplock_type,
3806 share_access,
3807 access_mask);
3808 if (!ok) {
3809 if (fsp->oplock_type == LEASE_OPLOCK) {
3810 status = remove_lease_if_stale(
3811 lck,
3812 fsp_client_guid(fsp),
3813 &fsp->lease->lease.lease_key);
3814 if (!NT_STATUS_IS_OK(status)) {
3815 DBG_WARNING("remove_lease_if_stale "
3816 "failed: %s\n",
3817 nt_errstr(status));
3818 }
3819 }
3820 return NT_STATUS_NO_MEMORY;
3821 }
3822
3823 /* Should we atomically (to the client at least) truncate ? */
3824 if ((!new_file_created) &&
3825 (flags2 & O_TRUNC) &&
3826 (S_ISREG(fsp->fsp_name->st.st_ex_mode))) {
3827 int ret;
3828
3829 ret = SMB_VFS_FTRUNCATE(fsp, 0);
3830 if (ret != 0) {
3831 status = map_nt_error_from_unix(errno);
3832 del_share_mode(lck, fsp);
3833 TALLOC_FREE(lck);
3834 fd_close(fsp);
3835 return status;
3836 }
3837 notify_fname(fsp->conn, NOTIFY_ACTION_MODIFIED,
3838 FILE_NOTIFY_CHANGE_SIZE
3839 | FILE_NOTIFY_CHANGE_ATTRIBUTES,
3840 fsp->fsp_name->base_name);
3841 }
3842
3843 /*
3844 * We have the share entry *locked*.....
3845 */
3846
3847 /* Delete streams if create_disposition requires it */
3848 if (!new_file_created && clear_ads(create_disposition) &&
3849 !is_ntfs_stream_smb_fname(smb_fname)) {
3850 status = delete_all_streams(conn, smb_fname);
3851 if (!NT_STATUS_IS_OK(status)) {
3852 del_share_mode(lck, fsp);
3853 TALLOC_FREE(lck);
3854 fd_close(fsp);
3855 return status;
3856 }
3857 }
3858
3859 if (fsp->fh->fd != -1 && lp_kernel_share_modes(SNUM(conn))) {
3860 int ret_flock;
3861 /*
3862 * Beware: streams implementing VFS modules may
3863 * implement streams in a way that fsp will have the
3864 * basefile open in the fsp fd, so lacking a distinct
3865 * fd for the stream kernel_flock will apply on the
3866 * basefile which is wrong. The actual check is
3867 * deferred to the VFS module implementing the
3868 * kernel_flock call.
3869 */
3870 ret_flock = SMB_VFS_KERNEL_FLOCK(fsp, share_access, access_mask);
3871 if(ret_flock == -1 ){
3872
3873 del_share_mode(lck, fsp);
3874 TALLOC_FREE(lck);
3875 fd_close(fsp);
3876
3877 return NT_STATUS_SHARING_VIOLATION;
3878 }
3879
3880 fsp->kernel_share_modes_taken = true;
3881 }
3882
3883 /*
3884 * At this point onwards, we can guarantee that the share entry
3885 * is locked, whether we created the file or not, and that the
3886 * deny mode is compatible with all current opens.
3887 */
3888
3889 /*
3890 * According to Samba4, SEC_FILE_READ_ATTRIBUTE is always granted,
3891 * but we don't have to store this - just ignore it on access check.
3892 */
3893 if (conn->sconn->using_smb2) {
3894 /*
3895 * SMB2 doesn't return it (according to Microsoft tests).
3896 * Test Case: TestSuite_ScenarioNo009GrantedAccessTestS0
3897 * File created with access = 0x7 (Read, Write, Delete)
3898 * Query Info on file returns 0x87 (Read, Write, Delete, Read Attributes)
3899 */
3900 fsp->access_mask = access_mask;
3901 } else {
3902 /* But SMB1 does. */
3903 fsp->access_mask = access_mask | FILE_READ_ATTRIBUTES;
3904 }
3905
3906 if (new_file_created) {
3907 info = FILE_WAS_CREATED;
3908 } else {
3909 if (flags2 & O_TRUNC) {
3910 info = FILE_WAS_OVERWRITTEN;
3911 } else {
3912 info = FILE_WAS_OPENED;
3913 }
3914 }
3915
3916 if (pinfo) {
3917 *pinfo = info;
3918 }
3919
3920 /* Handle strange delete on close create semantics. */
3921 if (create_options & FILE_DELETE_ON_CLOSE) {
3922 if (!new_file_created) {
3923 status = can_set_delete_on_close(fsp,
3924 existing_dos_attributes);
3925
3926 if (!NT_STATUS_IS_OK(status)) {
3927 /* Remember to delete the mode we just added. */
3928 del_share_mode(lck, fsp);
3929 TALLOC_FREE(lck);
3930 fd_close(fsp);
3931 return status;
3932 }
3933 }
3934 /* Note that here we set the *initial* delete on close flag,
3935 not the regular one. The magic gets handled in close. */
3936 fsp->initial_delete_on_close = True;
3937 }
3938
3939 if (info == FILE_WAS_CREATED) {
3940 smb_fname->st.st_ex_iflags &= ~ST_EX_IFLAG_CALCULATED_ITIME;
3941
3942 if (lp_store_dos_attributes(SNUM(conn)) &&
3943 smb_fname->st.st_ex_iflags & ST_EX_IFLAG_CALCULATED_FILE_ID)
3944 {
3945 uint64_t file_id;
3946
3947 file_id = make_file_id_from_itime(&smb_fname->st);
3948 update_stat_ex_file_id(&smb_fname->st, file_id);
3949 }
3950 }
3951
3952 if (info != FILE_WAS_OPENED) {
3953 /* Overwritten files should be initially set as archive */
3954 if ((info == FILE_WAS_OVERWRITTEN && lp_map_archive(SNUM(conn))) ||
3955 lp_store_dos_attributes(SNUM(conn))) {
3956 if (!posix_open) {
3957 if (file_set_dosmode(conn, smb_fname,
3958 new_dos_attributes | FILE_ATTRIBUTE_ARCHIVE,
3959 parent_dir, true) == 0) {
3960 unx_mode = smb_fname->st.st_ex_mode;
3961 }
3962 }
3963 }
3964 }
3965
3966 /* Determine sparse flag. */
3967 if (posix_open) {
3968 /* POSIX opens are sparse by default. */
3969 fsp->is_sparse = true;
3970 } else {
3971 fsp->is_sparse =
3972 (existing_dos_attributes & FILE_ATTRIBUTE_SPARSE);
3973 }
3974
3975 /*
3976 * Take care of inherited ACLs on created files - if default ACL not
3977 * selected.
3978 */
3979
3980 if (!posix_open && new_file_created && !def_acl) {
3981 if (unx_mode != smb_fname->st.st_ex_mode) {
3982 int ret = SMB_VFS_FCHMOD(fsp, unx_mode);
3983 if (ret == -1) {
3984 DBG_INFO("failed to reset "
3985 "attributes of file %s to 0%o\n",
3986 smb_fname_str_dbg(smb_fname),
3987 (unsigned int)unx_mode);
3988 }
3989 }
3990
3991 } else if (new_unx_mode) {
3992 /*
3993 * We only get here in the case of:
3994 *
3995 * a). Not a POSIX open.
3996 * b). File already existed.
3997 * c). File was overwritten.
3998 * d). Requested DOS attributes didn't match
3999 * the DOS attributes on the existing file.
4000 *
4001 * In that case new_unx_mode has been set
4002 * equal to the calculated mode (including
4003 * possible inheritance of the mode from the
4004 * containing directory).
4005 *
4006 * Note this mode was calculated with the
4007 * DOS attribute FILE_ATTRIBUTE_ARCHIVE added,
4008 * so the mode change here is suitable for
4009 * an overwritten file.
4010 */
4011
4012 if (new_unx_mode != smb_fname->st.st_ex_mode) {
4013 int ret = SMB_VFS_FCHMOD(fsp, new_unx_mode);
4014 if (ret == -1) {
4015 DBG_INFO("failed to reset "
4016 "attributes of file %s to 0%o\n",
4017 smb_fname_str_dbg(smb_fname),
4018 (unsigned int)new_unx_mode);
4019 }
4020 }
4021 }
4022
4023 {
4024 /*
4025 * Deal with other opens having a modified write time.
4026 */
4027 struct timespec write_time = get_share_mode_write_time(lck);
4028
4029 if (!null_timespec(write_time)) {
4030 update_stat_ex_mtime(&fsp->fsp_name->st, write_time);
4031 }
4032 }
4033
4034 TALLOC_FREE(lck);
4035
4036 return NT_STATUS_OK;
4037 }
4038
4039 static NTSTATUS mkdir_internal(connection_struct *conn,
4040 struct smb_filename *smb_dname,
4041 uint32_t file_attributes)
4042 {
4043 mode_t mode;
4044 char *parent_dir = NULL;
4045 NTSTATUS status;
4046 bool posix_open = false;
4047 bool need_re_stat = false;
4048 uint32_t access_mask = SEC_DIR_ADD_SUBDIR;
4049 int ret;
4050
4051 if (!CAN_WRITE(conn) || (access_mask & ~(conn->share_access))) {
4052 DEBUG(5,("mkdir_internal: failing share access "
4053 "%s\n", lp_servicename(talloc_tos(), SNUM(conn))));
4054 return NT_STATUS_ACCESS_DENIED;
4055 }
4056
4057 if (!parent_dirname(talloc_tos(), smb_dname->base_name, &parent_dir,
4058 NULL)) {
4059 return NT_STATUS_NO_MEMORY;
4060 }
4061
4062 if (file_attributes & FILE_FLAG_POSIX_SEMANTICS) {
4063 posix_open = true;
4064 mode = (mode_t)(file_attributes & ~FILE_FLAG_POSIX_SEMANTICS);
4065 } else {
4066 mode = unix_mode(conn, FILE_ATTRIBUTE_DIRECTORY, smb_dname, parent_dir);
4067 }
4068
4069 status = check_parent_access(conn,
4070 smb_dname,
4071 access_mask);
4072 if(!NT_STATUS_IS_OK(status)) {
4073 DEBUG(5,("mkdir_internal: check_parent_access "
4074 "on directory %s for path %s returned %s\n",
4075 parent_dir,
4076 smb_dname->base_name,
4077 nt_errstr(status) ));
4078 return status;
4079 }
4080
4081 ret = SMB_VFS_MKDIRAT(conn,
4082 conn->cwd_fsp,
4083 smb_dname,
4084 mode);
4085 if (ret != 0) {
4086 return map_nt_error_from_unix(errno);
4087 }
4088
4089 /* Ensure we're checking for a symlink here.... */
4090 /* We don't want to get caught by a symlink racer. */
4091
4092 if (SMB_VFS_LSTAT(conn, smb_dname) == -1) {
4093 DEBUG(2, ("Could not stat directory '%s' just created: %s\n",
4094 smb_fname_str_dbg(smb_dname), strerror(errno)));
4095 return map_nt_error_from_unix(errno);
4096 }
4097
4098 if (!S_ISDIR(smb_dname->st.st_ex_mode)) {
4099 DEBUG(0, ("Directory '%s' just created is not a directory !\n",
4100 smb_fname_str_dbg(smb_dname)));
4101 return NT_STATUS_NOT_A_DIRECTORY;
4102 }
4103
4104 smb_dname->st.st_ex_iflags &= ~ST_EX_IFLAG_CALCULATED_ITIME;
4105
4106 if (lp_store_dos_attributes(SNUM(conn))) {
4107 if (smb_dname->st.st_ex_iflags & ST_EX_IFLAG_CALCULATED_FILE_ID)
4108 {
4109 uint64_t file_id;
4110
4111 file_id = make_file_id_from_itime(&smb_dname->st);
4112 update_stat_ex_file_id(&smb_dname->st, file_id);
4113 }
4114
4115 if (!posix_open) {
4116 file_set_dosmode(conn, smb_dname,
4117 file_attributes | FILE_ATTRIBUTE_DIRECTORY,
4118 parent_dir, true);
4119 }
4120 }
4121
4122 if (lp_inherit_permissions(SNUM(conn))) {
4123 inherit_access_posix_acl(conn, parent_dir,
4124 smb_dname, mode);
4125 need_re_stat = true;
4126 }
4127
4128 if (!posix_open) {
4129 /*
4130 * Check if high bits should have been set,
4131 * then (if bits are missing): add them.
4132 * Consider bits automagically set by UNIX, i.e. SGID bit from parent
4133 * dir.
4134 */
4135 if ((mode & ~(S_IRWXU|S_IRWXG|S_IRWXO)) &&
4136 (mode & ~smb_dname->st.st_ex_mode)) {
4137 SMB_VFS_CHMOD(conn, smb_dname,
4138 (smb_dname->st.st_ex_mode |
4139 (mode & ~smb_dname->st.st_ex_mode)));
4140 need_re_stat = true;
4141 }
4142 }
4143
4144 /* Change the owner if required. */
4145 if (lp_inherit_owner(SNUM(conn)) != INHERIT_OWNER_NO) {
4146 change_dir_owner_to_parent(conn, parent_dir,
4147 smb_dname,
4148 &smb_dname->st);
4149 need_re_stat = true;
4150 }
4151
4152 if (need_re_stat) {
4153 if (SMB_VFS_LSTAT(conn, smb_dname) == -1) {
4154 DEBUG(2, ("Could not stat directory '%s' just created: %s\n",
4155 smb_fname_str_dbg(smb_dname), strerror(errno)));
4156 return map_nt_error_from_unix(errno);
4157 }
4158 }
4159
4160 notify_fname(conn, NOTIFY_ACTION_ADDED, FILE_NOTIFY_CHANGE_DIR_NAME,
4161 smb_dname->base_name);
4162
4163 return NT_STATUS_OK;
4164 }
4165
4166 /****************************************************************************
4167 Open a directory from an NT SMB call.
4168 ****************************************************************************/
4169
4170 static NTSTATUS open_directory(connection_struct *conn,
4171 struct smb_request *req,
4172 struct smb_filename *smb_dname,
4173 uint32_t access_mask,
4174 uint32_t share_access,
4175 uint32_t create_disposition,
4176 uint32_t create_options,
4177 uint32_t file_attributes,
4178 int *pinfo,
4179 files_struct **result)
4180 {
4181 files_struct *fsp = NULL;
4182 bool dir_existed = VALID_STAT(smb_dname->st) ? True : False;
4183 struct share_mode_lock *lck = NULL;
4184 NTSTATUS status;
4185 struct timespec mtimespec;
4186 int info = 0;
4187 bool ok;
4188
4189 if (is_ntfs_stream_smb_fname(smb_dname)) {
4190 DEBUG(2, ("open_directory: %s is a stream name!\n",
4191 smb_fname_str_dbg(smb_dname)));
4192 return NT_STATUS_NOT_A_DIRECTORY;
4193 }
4194
4195 if (!(file_attributes & FILE_FLAG_POSIX_SEMANTICS)) {
4196 /* Ensure we have a directory attribute. */
4197 file_attributes |= FILE_ATTRIBUTE_DIRECTORY;
4198 }
4199
4200 DEBUG(5,("open_directory: opening directory %s, access_mask = 0x%x, "
4201 "share_access = 0x%x create_options = 0x%x, "
4202 "create_disposition = 0x%x, file_attributes = 0x%x\n",
4203 smb_fname_str_dbg(smb_dname),
4204 (unsigned int)access_mask,
4205 (unsigned int)share_access,
4206 (unsigned int)create_options,
4207 (unsigned int)create_disposition,
4208 (unsigned int)file_attributes));
4209
4210 status = smbd_calculate_access_mask(conn, smb_dname, false,
4211 access_mask, &access_mask);
4212 if (!NT_STATUS_IS_OK(status)) {
4213 DEBUG(10, ("open_directory: smbd_calculate_access_mask "
4214 "on file %s returned %s\n",
4215 smb_fname_str_dbg(smb_dname),
4216 nt_errstr(status)));
4217 return status;
4218 }
4219
4220 if ((access_mask & SEC_FLAG_SYSTEM_SECURITY) &&
4221 !security_token_has_privilege(get_current_nttok(conn),
4222 SEC_PRIV_SECURITY)) {
4223 DEBUG(10, ("open_directory: open on %s "
4224 "failed - SEC_FLAG_SYSTEM_SECURITY denied.\n",
4225 smb_fname_str_dbg(smb_dname)));
4226 return NT_STATUS_PRIVILEGE_NOT_HELD;
4227 }
4228
4229 switch( create_disposition ) {
4230 case FILE_OPEN:
4231
4232 if (!dir_existed) {
4233 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
4234 }
4235
4236 info = FILE_WAS_OPENED;
4237 break;
4238
4239 case FILE_CREATE:
4240
4241 /* If directory exists error. If directory doesn't
4242 * exist create. */
4243
4244 if (dir_existed) {
4245 status = NT_STATUS_OBJECT_NAME_COLLISION;
4246 DEBUG(2, ("open_directory: unable to create "
4247 "%s. Error was %s\n",
4248 smb_fname_str_dbg(smb_dname),
4249 nt_errstr(status)));
4250 return status;
4251 }
4252
4253 status = mkdir_internal(conn, smb_dname,
4254 file_attributes);
4255
4256 if (!NT_STATUS_IS_OK(status)) {
4257 DEBUG(2, ("open_directory: unable to create "
4258 "%s. Error was %s\n",
4259 smb_fname_str_dbg(smb_dname),
4260 nt_errstr(status)));
4261 return status;
4262 }
4263
4264 info = FILE_WAS_CREATED;
4265 break;
4266
4267 case FILE_OPEN_IF:
4268 /*
4269 * If directory exists open. If directory doesn't
4270 * exist create.
4271 */
4272
4273 if (dir_existed) {
4274 status = NT_STATUS_OK;
4275 info = FILE_WAS_OPENED;
4276 } else {
4277 status = mkdir_internal(conn, smb_dname,
4278 file_attributes);
4279
4280 if (NT_STATUS_IS_OK(status)) {
4281 info = FILE_WAS_CREATED;
4282 } else {
4283 /* Cope with create race. */
4284 if (!NT_STATUS_EQUAL(status,
4285 NT_STATUS_OBJECT_NAME_COLLISION)) {
4286 DEBUG(2, ("open_directory: unable to create "
4287 "%s. Error was %s\n",
4288 smb_fname_str_dbg(smb_dname),
4289 nt_errstr(status)));
4290 return status;
4291 }
4292
4293 /*
4294 * If mkdir_internal() returned
4295 * NT_STATUS_OBJECT_NAME_COLLISION
4296 * we still must lstat the path.
4297 */
4298
4299 if (SMB_VFS_LSTAT(conn, smb_dname)
4300 == -1) {
4301 DEBUG(2, ("Could not stat "
4302 "directory '%s' just "
4303 "opened: %s\n",
4304 smb_fname_str_dbg(
4305 smb_dname),
4306 strerror(errno)));
4307 return map_nt_error_from_unix(
4308 errno);
4309 }
4310
4311 info = FILE_WAS_OPENED;
4312 }
4313 }
4314
4315 break;
4316
4317 case FILE_SUPERSEDE:
4318 case FILE_OVERWRITE:
4319 case FILE_OVERWRITE_IF:
4320 default:
4321 DEBUG(5,("open_directory: invalid create_disposition "
4322 "0x%x for directory %s\n",
4323 (unsigned int)create_disposition,
4324 smb_fname_str_dbg(smb_dname)));
4325 return NT_STATUS_INVALID_PARAMETER;
4326 }
4327
4328 if(!S_ISDIR(smb_dname->st.st_ex_mode)) {
4329 DEBUG(5,("open_directory: %s is not a directory !\n",
4330 smb_fname_str_dbg(smb_dname)));
4331 return NT_STATUS_NOT_A_DIRECTORY;
4332 }
4333
4334 if (info == FILE_WAS_OPENED) {
4335 status = smbd_check_access_rights(conn,
4336 smb_dname,
4337 false,
4338 access_mask);
4339 if (!NT_STATUS_IS_OK(status)) {
4340 DEBUG(10, ("open_directory: smbd_check_access_rights on "
4341 "file %s failed with %s\n",
4342 smb_fname_str_dbg(smb_dname),
4343 nt_errstr(status)));
4344 return status;
4345 }
4346 }
4347
4348 status = file_new(req, conn, &fsp);
4349 if(!NT_STATUS_IS_OK(status)) {
4350 return status;
4351 }
4352
4353 /*
4354 * Setup the files_struct for it.
4355 */
4356
4357 fsp->file_id = vfs_file_id_from_sbuf(conn, &smb_dname->st);
4358 fsp->vuid = req ? req->vuid : UID_FIELD_INVALID;
4359 fsp->file_pid = req ? req->smbpid : 0;
4360 fsp->can_lock = False;
4361 fsp->can_read = False;
4362 fsp->can_write = False;
4363
4364 fsp->fh->private_options = 0;
4365 /*
4366 * According to Samba4, SEC_FILE_READ_ATTRIBUTE is always granted,
4367 */
4368 fsp->access_mask = access_mask | FILE_READ_ATTRIBUTES;
4369 fsp->print_file = NULL;
4370 fsp->modified = False;
4371 fsp->oplock_type = NO_OPLOCK;
4372 fsp->sent_oplock_break = NO_BREAK_SENT;
4373 fsp->is_directory = True;
4374 if (file_attributes & FILE_FLAG_POSIX_SEMANTICS) {
4375 fsp->posix_flags |= FSP_POSIX_FLAGS_ALL;
4376 }
4377 status = fsp_set_smb_fname(fsp, smb_dname);
4378 if (!NT_STATUS_IS_OK(status)) {
4379 file_free(req, fsp);
4380 return status;
4381 }
4382
4383 /* Don't store old timestamps for directory
4384 handles in the internal database. We don't
4385 update them in there if new objects
4386 are creaded in the directory. Currently
4387 we only update timestamps on file writes.
4388 See bug #9870.
4389 */
4390 ZERO_STRUCT(mtimespec);
4391
4392 #ifdef O_DIRECTORY
4393 status = fd_open(conn, fsp, O_RDONLY|O_DIRECTORY, 0);
4394 #else
4395 /* POSIX allows us to open a directory with O_RDONLY. */
4396 status = fd_open(conn, fsp, O_RDONLY, 0);
4397 #endif
4398 if (!NT_STATUS_IS_OK(status)) {
4399 DBG_INFO("Could not open fd for "
4400 "%s (%s)\n",
4401 smb_fname_str_dbg(smb_dname),
4402 nt_errstr(status));
4403 file_free(req, fsp);
4404 return status;
4405 }
4406
4407 status = vfs_stat_fsp(fsp);
4408 if (!NT_STATUS_IS_OK(status)) {
4409 fd_close(fsp);
4410 file_free(req, fsp);
4411 return status;
4412 }
4413
4414 if(!S_ISDIR(fsp->fsp_name->st.st_ex_mode)) {
4415 DEBUG(5,("open_directory: %s is not a directory !\n",
4416 smb_fname_str_dbg(smb_dname)));
4417 fd_close(fsp);
4418 file_free(req, fsp);
4419 return NT_STATUS_NOT_A_DIRECTORY;
4420 }
4421
4422 /* Ensure there was no race condition. We need to check
4423 * dev/inode but not permissions, as these can change
4424 * legitimately */
4425 if (!check_same_dev_ino(&smb_dname->st, &fsp->fsp_name->st)) {
4426 DEBUG(5,("open_directory: stat struct differs for "
4427 "directory %s.\n",
4428 smb_fname_str_dbg(smb_dname)));
4429 fd_close(fsp);
4430 file_free(req, fsp);
4431 return NT_STATUS_ACCESS_DENIED;
4432 }
4433
4434 lck = get_share_mode_lock(talloc_tos(), fsp->file_id,
4435 conn->connectpath, smb_dname,
4436 &mtimespec);
4437
4438 if (lck == NULL) {
4439 DEBUG(0, ("open_directory: Could not get share mode lock for "
4440 "%s\n", smb_fname_str_dbg(smb_dname)));
4441 fd_close(fsp);
4442 file_free(req, fsp);
4443 return NT_STATUS_SHARING_VIOLATION;
4444 }
4445
4446 if (has_delete_on_close(lck, fsp->name_hash)) {
4447 TALLOC_FREE(lck);
4448 fd_close(fsp);
4449 file_free(req, fsp);
4450 return NT_STATUS_DELETE_PENDING;
4451 }
4452
4453 status = open_mode_check(conn, lck,
4454 access_mask, share_access);
4455
4456 if (!NT_STATUS_IS_OK(status)) {
4457 TALLOC_FREE(lck);
4458 fd_close(fsp);
4459 file_free(req, fsp);
4460 return status;
4461 }
4462
4463 {
4464 struct share_mode_data *d = lck->data;
4465 uint16_t new_flags = share_mode_flags_restrict(
4466 d->flags, access_mask, share_access, UINT32_MAX);
4467
4468 if (new_flags != d->flags) {
4469 d->flags = new_flags;
4470 d->modified = true;
4471 }
4472 }
4473
4474 ok = set_share_mode(
4475 lck,
4476 fsp,
4477 get_current_uid(conn),
4478 req ? req->mid : 0,
4479 NO_OPLOCK,
4480 share_access,
4481 fsp->access_mask);
4482 if (!ok) {
4483 TALLOC_FREE(lck);
4484 fd_close(fsp);
4485 file_free(req, fsp);
4486 return NT_STATUS_NO_MEMORY;
4487 }
4488
4489 /* For directories the delete on close bit at open time seems
4490 always to be honored on close... See test 19 in Samba4 BASE-DELETE. */
4491 if (create_options & FILE_DELETE_ON_CLOSE) {
4492 status = can_set_delete_on_close(fsp, 0);
4493 if (!NT_STATUS_IS_OK(status) && !NT_STATUS_EQUAL(status, NT_STATUS_DIRECTORY_NOT_EMPTY)) {
4494 del_share_mode(lck, fsp);
4495 TALLOC_FREE(lck);
4496 fd_close(fsp);
4497 file_free(req, fsp);
4498 return status;
4499 }
4500
4501 if (NT_STATUS_IS_OK(status)) {
4502 /* Note that here we set the *initial* delete on close flag,
4503 not the regular one. The magic gets handled in close. */
4504 fsp->initial_delete_on_close = True;
4505 }
4506 }
4507
4508 {
4509 /*
4510 * Deal with other opens having a modified write time. Is this
4511 * possible for directories?
4512 */
4513 struct timespec write_time = get_share_mode_write_time(lck);
4514
4515 if (!null_timespec(write_time)) {
4516 update_stat_ex_mtime(&fsp->fsp_name->st, write_time);
4517 }
4518 }
4519
4520 TALLOC_FREE(lck);
4521
4522 if (pinfo) {
4523 *pinfo = info;
4524 }
4525
4526 *result = fsp;
4527 return NT_STATUS_OK;
4528 }
4529
4530 NTSTATUS create_directory(connection_struct *conn, struct smb_request *req,
4531 struct smb_filename *smb_dname)
4532 {
4533 NTSTATUS status;
4534 files_struct *fsp;
4535
4536 status = SMB_VFS_CREATE_FILE(
4537 conn, /* conn */
4538 req, /* req */
4539 0, /* root_dir_fid */
4540 smb_dname, /* fname */
4541 FILE_READ_ATTRIBUTES, /* access_mask */
4542 FILE_SHARE_NONE, /* share_access */
4543 FILE_CREATE, /* create_disposition*/
4544 FILE_DIRECTORY_FILE, /* create_options */
4545 FILE_ATTRIBUTE_DIRECTORY, /* file_attributes */
4546 0, /* oplock_request */
4547 NULL, /* lease */
4548 0, /* allocation_size */
4549 0, /* private_flags */
4550 NULL, /* sd */
4551 NULL, /* ea_list */
4552 &fsp, /* result */
4553 NULL, /* pinfo */
4554 NULL, NULL); /* create context */
4555
4556 if (NT_STATUS_IS_OK(status)) {
4557 close_file(req, fsp, NORMAL_CLOSE);
4558 }
4559
4560 return status;
4561 }
4562
4563 /****************************************************************************
4564 Receive notification that one of our open files has been renamed by another
4565 smbd process.
4566 ****************************************************************************/
4567
4568 void msg_file_was_renamed(struct messaging_context *msg_ctx,
4569 void *private_data,
4570 uint32_t msg_type,
4571 struct server_id src,
4572 DATA_BLOB *data)
4573 {
4574 struct file_rename_message *msg = NULL;
4575 enum ndr_err_code ndr_err;
4576 files_struct *fsp;
4577 struct smb_filename *smb_fname = NULL;
4578 struct smbd_server_connection *sconn =
4579 talloc_get_type_abort(private_data,
4580 struct smbd_server_connection);
4581
4582 msg = talloc(talloc_tos(), struct file_rename_message);
4583 if (msg == NULL) {
4584 DBG_WARNING("talloc failed\n");
4585 return;
4586 }
4587
4588 ndr_err = ndr_pull_struct_blob_all(
4589 data,
4590 msg,
4591 msg,
4592 (ndr_pull_flags_fn_t)ndr_pull_file_rename_message);
4593 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
4594 DBG_DEBUG("ndr_pull_oplock_break_message failed: %s\n",
4595 ndr_errstr(ndr_err));
4596 goto out;
4597 }
4598 if (DEBUGLEVEL >= 10) {
4599 struct server_id_buf buf;
4600 DBG_DEBUG("Got rename message from %s\n",
4601 server_id_str_buf(src, &buf));
4602 NDR_PRINT_DEBUG(file_rename_message, msg);
4603 }
4604
4605 /* stream_name must always be NULL if there is no stream. */
4606 if ((msg->stream_name != NULL) && (msg->stream_name[0] == '\0')) {
4607 msg->stream_name = NULL;
4608 }
4609
4610 smb_fname = synthetic_smb_fname(
4611 msg, msg->base_name, msg->stream_name, NULL, 0);
4612 if (smb_fname == NULL) {
4613 DBG_DEBUG("synthetic_smb_fname failed\n");
4614 goto out;
4615 }
4616
4617 fsp = file_find_dif(sconn, msg->id, msg->share_file_id);
4618 if (fsp == NULL) {
4619 DBG_DEBUG("fsp not found\n");
4620 goto out;
4621 }
4622
4623 if (strcmp(fsp->conn->connectpath, msg->servicepath) == 0) {
4624 NTSTATUS status;
4625 DBG_DEBUG("renaming file %s from %s -> %s\n",
4626 fsp_fnum_dbg(fsp),
4627 fsp_str_dbg(fsp),
4628 smb_fname_str_dbg(smb_fname));
4629 status = fsp_set_smb_fname(fsp, smb_fname);
4630 if (!NT_STATUS_IS_OK(status)) {
4631 DBG_DEBUG("fsp_set_smb_fname failed: %s\n",
4632 nt_errstr(status));
4633 }
4634 } else {
4635 /* TODO. JRA. */
4636 /*
4637 * Now we have the complete path we can work out if
4638 * this is actually within this share and adjust
4639 * newname accordingly.
4640 */
4641 DBG_DEBUG("share mismatch (sharepath %s not sharepath %s) "
4642 "%s from %s -> %s\n",
4643 fsp->conn->connectpath,
4644 msg->servicepath,
4645 fsp_fnum_dbg(fsp),
4646 fsp_str_dbg(fsp),
4647 smb_fname_str_dbg(smb_fname));
4648 }
4649 out:
4650 TALLOC_FREE(msg);
4651 }
4652
4653 /*
4654 * If a main file is opened for delete, all streams need to be checked for
4655 * !FILE_SHARE_DELETE. Do this by opening with DELETE_ACCESS.
4656 * If that works, delete them all by setting the delete on close and close.
4657 */
4658
4659 static NTSTATUS open_streams_for_delete(connection_struct *conn,
4660 const struct smb_filename *smb_fname)
4661 {
4662 struct stream_struct *stream_info = NULL;
4663 files_struct **streams = NULL;
4664 int j;
4665 unsigned int i, num_streams = 0;
4666 TALLOC_CTX *frame = talloc_stackframe();
4667 NTSTATUS status;
4668
4669 status = vfs_streaminfo(conn, NULL, smb_fname, talloc_tos(),
4670 &num_streams, &stream_info);
4671
4672 if (NT_STATUS_EQUAL(status, NT_STATUS_NOT_IMPLEMENTED)
4673 || NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
4674 DEBUG(10, ("no streams around\n"));
4675 TALLOC_FREE(frame);
4676 return NT_STATUS_OK;
4677 }
4678
4679 if (!NT_STATUS_IS_OK(status)) {
4680 DEBUG(10, ("vfs_streaminfo failed: %s\n",
4681 nt_errstr(status)));
4682 goto fail;
4683 }
4684
4685 DEBUG(10, ("open_streams_for_delete found %d streams\n",
4686 num_streams));
4687
4688 if (num_streams == 0) {
4689 TALLOC_FREE(frame);
4690 return NT_STATUS_OK;
4691 }
4692
4693 streams = talloc_array(talloc_tos(), files_struct *, num_streams);
4694 if (streams == NULL) {
4695 DEBUG(0, ("talloc failed\n"));
4696 status = NT_STATUS_NO_MEMORY;
4697 goto fail;
4698 }
4699
4700 for (i=0; i<num_streams; i++) {
4701 struct smb_filename *smb_fname_cp;
4702
4703 if (strequal(stream_info[i].name, "::$DATA")) {
4704 streams[i] = NULL;
4705 continue;
4706 }
4707
4708 smb_fname_cp = synthetic_smb_fname(talloc_tos(),
4709 smb_fname->base_name,
4710 stream_info[i].name,
4711 NULL,
4712 (smb_fname->flags &
4713 ~SMB_FILENAME_POSIX_PATH));
4714 if (smb_fname_cp == NULL) {
4715 status = NT_STATUS_NO_MEMORY;
4716 goto fail;
4717 }
4718
4719 if (SMB_VFS_STAT(conn, smb_fname_cp) == -1) {
4720 DEBUG(10, ("Unable to stat stream: %s\n",
4721 smb_fname_str_dbg(smb_fname_cp)));
4722 }
4723
4724 status = SMB_VFS_CREATE_FILE(
4725 conn, /* conn */
4726 NULL, /* req */
4727 0, /* root_dir_fid */
4728 smb_fname_cp, /* fname */
4729 DELETE_ACCESS, /* access_mask */
4730 (FILE_SHARE_READ | /* share_access */
4731 FILE_SHARE_WRITE | FILE_SHARE_DELETE),
4732 FILE_OPEN, /* create_disposition*/
4733 0, /* create_options */
4734 FILE_ATTRIBUTE_NORMAL, /* file_attributes */
4735 0, /* oplock_request */
4736 NULL, /* lease */
4737 0, /* allocation_size */
4738 NTCREATEX_OPTIONS_PRIVATE_STREAM_DELETE, /* private_flags */
4739 NULL, /* sd */
4740 NULL, /* ea_list */
4741 &streams[i], /* result */
4742 NULL, /* pinfo */
4743 NULL, NULL); /* create context */
4744
4745 if (!NT_STATUS_IS_OK(status)) {
4746 DEBUG(10, ("Could not open stream %s: %s\n",
4747 smb_fname_str_dbg(smb_fname_cp),
4748 nt_errstr(status)));
4749
4750 TALLOC_FREE(smb_fname_cp);
4751 break;
4752 }
4753 TALLOC_FREE(smb_fname_cp);
4754 }
4755
4756 /*
4757 * don't touch the variable "status" beyond this point :-)
4758 */
4759
4760 for (j = i-1 ; j >= 0; j--) {
4761 if (streams[j] == NULL) {
4762 continue;
4763 }
4764
4765 DEBUG(10, ("Closing stream # %d, %s\n", j,
4766 fsp_str_dbg(streams[j])));
4767 close_file(NULL, streams[j], NORMAL_CLOSE);
4768 }
4769
4770 fail:
4771 TALLOC_FREE(frame);
4772 return status;
4773 }
4774
4775 /*********************************************************************
4776 Create a default ACL by inheriting from the parent. If no inheritance
4777 from the parent available, don't set anything. This will leave the actual
4778 permissions the new file or directory already got from the filesystem
4779 as the NT ACL when read.
4780 *********************************************************************/
4781
4782 static NTSTATUS inherit_new_acl(files_struct *fsp)
4783 {
4784 TALLOC_CTX *frame = talloc_stackframe();
4785 char *parent_name = NULL;
4786 struct security_descriptor *parent_desc = NULL;
4787 NTSTATUS status = NT_STATUS_OK;
4788 struct security_descriptor *psd = NULL;
4789 const struct dom_sid *owner_sid = NULL;
4790 const struct dom_sid *group_sid = NULL;
4791 uint32_t security_info_sent = (SECINFO_OWNER | SECINFO_GROUP | SECINFO_DACL);
4792 struct security_token *token = fsp->conn->session_info->security_token;
4793 bool inherit_owner =
4794 (lp_inherit_owner(SNUM(fsp->conn)) == INHERIT_OWNER_WINDOWS_AND_UNIX);
4795 bool inheritable_components = false;
4796 bool try_builtin_administrators = false;
4797 const struct dom_sid *BA_U_sid = NULL;
4798 const struct dom_sid *BA_G_sid = NULL;
4799 bool try_system = false;
4800 const struct dom_sid *SY_U_sid = NULL;
4801 const struct dom_sid *SY_G_sid = NULL;
4802 size_t size = 0;
4803 struct smb_filename *parent_smb_fname = NULL;
4804
4805 if (!parent_dirname(frame, fsp->fsp_name->base_name, &parent_name, NULL)) {
4806 TALLOC_FREE(frame);
4807 return NT_STATUS_NO_MEMORY;
4808 }
4809 parent_smb_fname = synthetic_smb_fname(talloc_tos(),
4810 parent_name,
4811 NULL,
4812 NULL,
4813 fsp->fsp_name->flags);
4814
4815 if (parent_smb_fname == NULL) {
4816 TALLOC_FREE(frame);
4817 return NT_STATUS_NO_MEMORY;
4818 }
4819
4820 status = SMB_VFS_GET_NT_ACL(fsp->conn,
4821 parent_smb_fname,
4822 (SECINFO_OWNER | SECINFO_GROUP | SECINFO_DACL),
4823 frame,
4824 &parent_desc);
4825 if (!NT_STATUS_IS_OK(status)) {
4826 TALLOC_FREE(frame);
4827 return status;
4828 }
4829
4830 inheritable_components = sd_has_inheritable_components(parent_desc,
4831 fsp->is_directory);
4832
4833 if (!inheritable_components && !inherit_owner) {
4834 TALLOC_FREE(frame);
4835 /* Nothing to inherit and not setting owner. */
4836 return NT_STATUS_OK;
4837 }
4838
4839 /* Create an inherited descriptor from the parent. */
4840
4841 if (DEBUGLEVEL >= 10) {
4842 DEBUG(10,("inherit_new_acl: parent acl for %s is:\n",
4843 fsp_str_dbg(fsp) ));
4844 NDR_PRINT_DEBUG(security_descriptor, parent_desc);
4845 }
4846
4847 /* Inherit from parent descriptor if "inherit owner" set. */
4848 if (inherit_owner) {
4849 owner_sid = parent_desc->owner_sid;
4850 group_sid = parent_desc->group_sid;
4851 }
4852
4853 if (owner_sid == NULL) {
4854 if (security_token_has_builtin_administrators(token)) {
4855 try_builtin_administrators = true;
4856 } else if (security_token_is_system(token)) {
4857 try_builtin_administrators = true;
4858 try_system = true;
4859 }
4860 }
4861
4862 if (group_sid == NULL &&
4863 token->num_sids == PRIMARY_GROUP_SID_INDEX)
4864 {
4865 if (security_token_is_system(token)) {
4866 try_builtin_administrators = true;
4867 try_system = true;
4868 }
4869 }
4870
4871 if (try_builtin_administrators) {
4872 struct unixid ids;
4873 bool ok;
4874
4875 ZERO_STRUCT(ids);
4876 ok = sids_to_unixids(&global_sid_Builtin_Administrators, 1, &ids);
4877 if (ok) {
4878 switch (ids.type) {
4879 case ID_TYPE_BOTH:
4880 BA_U_sid = &global_sid_Builtin_Administrators;
4881 BA_G_sid = &global_sid_Builtin_Administrators;
4882 break;
4883 case ID_TYPE_UID:
4884 BA_U_sid = &global_sid_Builtin_Administrators;
4885 break;
4886 case ID_TYPE_GID:
4887 BA_G_sid = &global_sid_Builtin_Administrators;
4888 break;
4889 default:
4890 break;
4891 }
4892 }
4893 }
4894
4895 if (try_system) {
4896 struct unixid ids;
4897 bool ok;
4898
4899 ZERO_STRUCT(ids);
4900 ok = sids_to_unixids(&global_sid_System, 1, &ids);
4901 if (ok) {
4902 switch (ids.type) {
4903 case ID_TYPE_BOTH:
4904 SY_U_sid = &global_sid_System;
4905 SY_G_sid = &global_sid_System;
4906 break;
4907 case ID_TYPE_UID:
4908 SY_U_sid = &global_sid_System;
4909 break;
4910 case ID_TYPE_GID:
4911 SY_G_sid = &global_sid_System;
4912 break;
4913 default:
4914 break;
4915 }
4916 }
4917 }
4918
4919 if (owner_sid == NULL) {
4920 owner_sid = BA_U_sid;
4921 }
4922
4923 if (owner_sid == NULL) {
4924 owner_sid = SY_U_sid;
4925 }
4926
4927 if (group_sid == NULL) {
4928 group_sid = SY_G_sid;
4929 }
4930
4931 if (try_system && group_sid == NULL) {
4932 group_sid = BA_G_sid;
4933 }
4934
4935 if (owner_sid == NULL) {
4936 owner_sid = &token->sids[PRIMARY_USER_SID_INDEX];
4937 }
4938 if (group_sid == NULL) {
4939 if (token->num_sids == PRIMARY_GROUP_SID_INDEX) {
4940 group_sid = &token->sids[PRIMARY_USER_SID_INDEX];
4941 } else {
4942 group_sid = &token->sids[PRIMARY_GROUP_SID_INDEX];
4943 }
4944 }
4945
4946 status = se_create_child_secdesc(frame,
4947 &psd,
4948 &size,
4949 parent_desc,
4950 owner_sid,
4951 group_sid,
4952 fsp->is_directory);
4953 if (!NT_STATUS_IS_OK(status)) {
4954 TALLOC_FREE(frame);
4955 return status;
4956 }
4957
4958 /* If inheritable_components == false,
4959 se_create_child_secdesc()
4960 creates a security descriptor with a NULL dacl
4961 entry, but with SEC_DESC_DACL_PRESENT. We need
4962 to remove that flag. */
4963
4964 if (!inheritable_components) {
4965 security_info_sent &= ~SECINFO_DACL;
4966 psd->type &= ~SEC_DESC_DACL_PRESENT;
4967 }
4968
4969 if (DEBUGLEVEL >= 10) {
4970 DEBUG(10,("inherit_new_acl: child acl for %s is:\n",
4971 fsp_str_dbg(fsp) ));
4972 NDR_PRINT_DEBUG(security_descriptor, psd);
4973 }
4974
4975 if (inherit_owner) {
4976 /* We need to be root to force this. */
4977 become_root();
4978 }
4979 status = SMB_VFS_FSET_NT_ACL(fsp,
4980 security_info_sent,
4981 psd);
4982 if (inherit_owner) {
4983 unbecome_root();
4984 }
4985 TALLOC_FREE(frame);
4986 return status;
4987 }
4988
4989 /*
4990 * If we already have a lease, it must match the new file id. [MS-SMB2]
4991 * 3.3.5.9.8 speaks about INVALID_PARAMETER if an already used lease key is
4992 * used for a different file name.
4993 */
4994
4995 struct lease_match_state {
4996 /* Input parameters. */
4997 TALLOC_CTX *mem_ctx;
4998 const char *servicepath;
4999 const struct smb_filename *fname;
5000 bool file_existed;
5001 struct file_id id;
5002 /* Return parameters. */
5003 uint32_t num_file_ids;
5004 struct file_id *ids;
5005 NTSTATUS match_status;
5006 };
5007
5008 /*************************************************************
5009 File doesn't exist but this lease key+guid is already in use.
5010
5011 This is only allowable in the dynamic share case where the
5012 service path must be different.
5013
5014 There is a small race condition here in the multi-connection
5015 case where a client sends two create calls on different connections,
5016 where the file doesn't exist and one smbd creates the leases_db
5017 entry first, but this will get fixed by the multichannel cleanup
5018 when all identical client_guids get handled by a single smbd.
5019 **************************************************************/
5020
5021 static void lease_match_parser_new_file(
5022 uint32_t num_files,
5023 const struct leases_db_file *files,
5024 struct lease_match_state *state)
5025 {
5026 uint32_t i;
5027
5028 for (i = 0; i < num_files; i++) {
5029 const struct leases_db_file *f = &files[i];
5030 if (strequal(state->servicepath, f->servicepath)) {
5031 state->match_status = NT_STATUS_INVALID_PARAMETER;
5032 return;
5033 }
5034 }
5035
5036 /* Dynamic share case. Break leases on all other files. */
5037 state->match_status = leases_db_copy_file_ids(state->mem_ctx,
5038 num_files,
5039 files,
5040 &state->ids);
5041 if (!NT_STATUS_IS_OK(state->match_status)) {
5042 return;
5043 }
5044
5045 state->num_file_ids = num_files;
5046 state->match_status = NT_STATUS_OPLOCK_NOT_GRANTED;
5047 return;
5048 }
5049
5050 static void lease_match_parser(
5051 uint32_t num_files,
5052 const struct leases_db_file *files,
5053 void *private_data)
5054 {
5055 struct lease_match_state *state =
5056 (struct lease_match_state *)private_data;
5057 uint32_t i;
5058
5059 if (!state->file_existed) {
5060 /*
5061 * Deal with name mismatch or
5062 * possible dynamic share case separately
5063 * to make code clearer.
5064 */
5065 lease_match_parser_new_file(num_files,
5066 files,
5067 state);
5068 return;
5069 }
5070
5071 /* File existed. */
5072 state->match_status = NT_STATUS_OK;
5073
5074 for (i = 0; i < num_files; i++) {
5075 const struct leases_db_file *f = &files[i];
5076
5077 /* Everything should be the same. */
5078 if (!file_id_equal(&state->id, &f->id)) {
5079 /* This should catch all dynamic share cases. */
5080 state->match_status = NT_STATUS_OPLOCK_NOT_GRANTED;
5081 break;
5082 }
5083 if (!strequal(f->servicepath, state->servicepath)) {
5084 state->match_status = NT_STATUS_INVALID_PARAMETER;
5085 break;
5086 }
5087 if (!strequal(f->base_name, state->fname->base_name)) {
5088 state->match_status = NT_STATUS_INVALID_PARAMETER;
5089 break;
5090 }
5091 if (!strequal(f->stream_name, state->fname->stream_name)) {
5092 state->match_status = NT_STATUS_INVALID_PARAMETER;
5093 break;
5094 }
5095 }
5096
5097 if (NT_STATUS_IS_OK(state->match_status)) {
5098 /*
5099 * Common case - just opening another handle on a
5100 * file on a non-dynamic share.
5101 */
5102 return;
5103 }
5104
5105 if (NT_STATUS_EQUAL(state->match_status, NT_STATUS_INVALID_PARAMETER)) {
5106 /* Mismatched path. Error back to client. */
5107 return;
5108 }
5109
5110 /*
5111 * File id mismatch. Dynamic share case NT_STATUS_OPLOCK_NOT_GRANTED.
5112 * Don't allow leases.
5113 */
5114
5115 state->match_status = leases_db_copy_file_ids(state->mem_ctx,
5116 num_files,
5117 files,
5118 &state->ids);
5119 if (!NT_STATUS_IS_OK(state->match_status)) {
5120 return;
5121 }
5122
5123 state->num_file_ids = num_files;
5124 state->match_status = NT_STATUS_OPLOCK_NOT_GRANTED;
5125 return;
5126 }
5127
5128 struct lease_match_break_state {
5129 struct messaging_context *msg_ctx;
5130 const struct smb2_lease_key *lease_key;
5131 struct file_id id;
5132
5133 bool found_lease;
5134 uint16_t version;
5135 uint16_t epoch;
5136 };
5137
5138 static bool lease_match_break_fn(
5139 struct share_mode_entry *e,
5140 void *private_data)
5141 {
5142 struct lease_match_break_state *state = private_data;
5143 bool stale, equal;
5144 uint32_t e_lease_type;
5145 NTSTATUS status;
5146
5147 stale = share_entry_stale_pid(e);
5148 if (stale) {
5149 return false;
5150 }
5151
5152 equal = smb2_lease_key_equal(&e->lease_key, state->lease_key);
5153 if (!equal) {
5154 return false;
5155 }
5156
5157 status = leases_db_get(
5158 &e->client_guid,
5159 &e->lease_key,
5160 &state->id,
5161 NULL, /* current_state */
5162 NULL, /* breaking */
5163 NULL, /* breaking_to_requested */
5164 NULL, /* breaking_to_required */
5165 &state->version, /* lease_version */
5166 &state->epoch); /* epoch */
5167 if (NT_STATUS_IS_OK(status)) {
5168 state->found_lease = true;
5169 } else {
5170 DBG_WARNING("Could not find version/epoch: %s\n",
5171 nt_errstr(status));
5172 }
5173
5174 e_lease_type = get_lease_type(e, state->id);
5175 if (e_lease_type == SMB2_LEASE_NONE) {
5176 return false;
5177 }
5178 send_break_message(state->msg_ctx, &state->id, e, SMB2_LEASE_NONE);
5179
5180 /*
5181 * Windows 7 and 8 lease clients are broken in that they will
5182 * not respond to lease break requests whilst waiting for an
5183 * outstanding open request on that lease handle on the same
5184 * TCP connection, due to holding an internal inode lock.
5185 *
5186 * This means we can't reschedule ourselves here, but must
5187 * return from the create.
5188 *
5189 * Work around:
5190 *
5191 * Send the breaks and then return SMB2_LEASE_NONE in the
5192 * lease handle to cause them to acknowledge the lease
5193 * break. Consultation with Microsoft engineering confirmed
5194 * this approach is safe.
5195 */
5196
5197 return false;
5198 }
5199
5200 static NTSTATUS lease_match(connection_struct *conn,
5201 struct smb_request *req,
5202 const struct smb2_lease_key *lease_key,
5203 const char *servicepath,
5204 const struct smb_filename *fname,
5205 uint16_t *p_version,
5206 uint16_t *p_epoch)
5207 {
5208 struct smbd_server_connection *sconn = req->sconn;
5209 TALLOC_CTX *tos = talloc_tos();
5210 struct lease_match_state state = {
5211 .mem_ctx = tos,
5212 .servicepath = servicepath,
5213 .fname = fname,
5214 .match_status = NT_STATUS_OK
5215 };
5216 uint32_t i;
5217 NTSTATUS status;
5218
5219 state.file_existed = VALID_STAT(fname->st);
5220 if (state.file_existed) {
5221 state.id = vfs_file_id_from_sbuf(conn, &fname->st);
5222 }
5223
5224 status = leases_db_parse(&sconn->client->connections->smb2.client.guid,
5225 lease_key, lease_match_parser, &state);
5226 if (!NT_STATUS_IS_OK(status)) {
5227 /*
5228 * Not found or error means okay: We can make the lease pass
5229 */
5230 return NT_STATUS_OK;
5231 }
5232 if (!NT_STATUS_EQUAL(state.match_status, NT_STATUS_OPLOCK_NOT_GRANTED)) {
5233 /*
5234 * Anything but NT_STATUS_OPLOCK_NOT_GRANTED, let the caller
5235 * deal with it.
5236 */
5237 return state.match_status;
5238 }
5239
5240 /* We have to break all existing leases. */
5241 for (i = 0; i < state.num_file_ids; i++) {
5242 struct lease_match_break_state break_state = {
5243 .msg_ctx = conn->sconn->msg_ctx,
5244 .lease_key = lease_key,
5245 };
5246 struct share_mode_lock *lck;
5247 bool ok;
5248
5249 if (file_id_equal(&state.ids[i], &state.id)) {
5250 /* Don't need to break our own file. */
5251 continue;
5252 }
5253
5254 break_state.id = state.ids[i];
5255
5256 lck = get_existing_share_mode_lock(
5257 talloc_tos(), break_state.id);
5258 if (lck == NULL) {
5259 /* Race condition - file already closed. */
5260 continue;
5261 }
5262
5263 ok = share_mode_forall_leases(
5264 lck, lease_match_break_fn, &break_state);
5265 if (!ok) {
5266 DBG_DEBUG("share_mode_forall_leases failed\n");
5267 continue;
5268 }
5269
5270 TALLOC_FREE(lck);
5271
5272 if (break_state.found_lease) {
5273 *p_version = break_state.version;
5274 *p_epoch = break_state.epoch;
5275 }
5276 }
5277 /*
5278 * Ensure we don't grant anything more so we
5279 * never upgrade.
5280 */
5281 return NT_STATUS_OPLOCK_NOT_GRANTED;
5282 }
5283
5284 /*
5285 * Wrapper around open_file_ntcreate and open_directory
5286 */
5287
5288 static NTSTATUS create_file_unixpath(connection_struct *conn,
5289 struct smb_request *req,
5290 struct smb_filename *smb_fname,
5291 uint32_t access_mask,
5292 uint32_t share_access,
5293 uint32_t create_disposition,
5294 uint32_t create_options,
5295 uint32_t file_attributes,
5296 uint32_t oplock_request,
5297 const struct smb2_lease *lease,
5298 uint64_t allocation_size,
5299 uint32_t private_flags,
5300 struct security_descriptor *sd,
5301 struct ea_list *ea_list,
5302
5303 files_struct **result,
5304 int *pinfo)
5305 {
5306 struct smb2_lease none_lease;
5307 int info = FILE_WAS_OPENED;
5308 files_struct *base_fsp = NULL;
5309 files_struct *fsp = NULL;
5310 NTSTATUS status;
5311
5312 DBG_DEBUG("create_file_unixpath: access_mask = 0x%x "
5313 "file_attributes = 0x%x, share_access = 0x%x, "
5314 "create_disposition = 0x%x create_options = 0x%x "
5315 "oplock_request = 0x%x private_flags = 0x%x "
5316 "ea_list = %p, sd = %p, "
5317 "fname = %s\n",
5318 (unsigned int)access_mask,
5319 (unsigned int)file_attributes,
5320 (unsigned int)share_access,
5321 (unsigned int)create_disposition,
5322 (unsigned int)create_options,
5323 (unsigned int)oplock_request,
5324 (unsigned int)private_flags,
5325 ea_list, sd, smb_fname_str_dbg(smb_fname));
5326
5327 if (create_options & FILE_OPEN_BY_FILE_ID) {
5328 status = NT_STATUS_NOT_SUPPORTED;
5329 goto fail;
5330 }
5331
5332 if (create_options & NTCREATEX_OPTIONS_INVALID_PARAM_MASK) {
5333 status = NT_STATUS_INVALID_PARAMETER;
5334 goto fail;
5335 }
5336
5337 if (req == NULL) {
5338 oplock_request |= INTERNAL_OPEN_ONLY;
5339 }
5340
5341 if (lease != NULL) {
5342 uint16_t epoch = lease->lease_epoch;
5343 uint16_t version = lease->lease_version;
5344
5345 if (req == NULL) {
5346 DBG_WARNING("Got lease on internal open\n");
5347 status = NT_STATUS_INTERNAL_ERROR;
5348 goto fail;
5349 }
5350
5351 status = lease_match(conn,
5352 req,
5353 &lease->lease_key,
5354 conn->connectpath,
5355 smb_fname,
5356 &version,
5357 &epoch);
5358 if (NT_STATUS_EQUAL(status, NT_STATUS_OPLOCK_NOT_GRANTED)) {
5359 /* Dynamic share file. No leases and update epoch... */
5360 none_lease = *lease;
5361 none_lease.lease_state = SMB2_LEASE_NONE;
5362 none_lease.lease_epoch = epoch;
5363 none_lease.lease_version = version;
5364 lease = &none_lease;
5365 } else if (!NT_STATUS_IS_OK(status)) {
5366 goto fail;
5367 }
5368 }
5369
5370 if ((conn->fs_capabilities & FILE_NAMED_STREAMS)
5371 && (access_mask & DELETE_ACCESS)
5372 && !is_ntfs_stream_smb_fname(smb_fname)) {
5373 /*
5374 * We can't open a file with DELETE access if any of the
5375 * streams is open without FILE_SHARE_DELETE
5376 */
5377 status = open_streams_for_delete(conn, smb_fname);
5378
5379 if (!NT_STATUS_IS_OK(status)) {
5380 goto fail;
5381 }
5382 }
5383
5384 if ((access_mask & SEC_FLAG_SYSTEM_SECURITY) &&
5385 !security_token_has_privilege(get_current_nttok(conn),
5386 SEC_PRIV_SECURITY)) {
5387 DEBUG(10, ("create_file_unixpath: open on %s "
5388 "failed - SEC_FLAG_SYSTEM_SECURITY denied.\n",
5389 smb_fname_str_dbg(smb_fname)));
5390 status = NT_STATUS_PRIVILEGE_NOT_HELD;
5391 goto fail;
5392 }
5393
5394 /*
5395 * Files or directories can't be opened DELETE_ON_CLOSE without
5396 * delete access.
5397 * BUG: https://bugzilla.samba.org/show_bug.cgi?id=13358
5398 */
5399 if (create_options & FILE_DELETE_ON_CLOSE) {
5400 if ((access_mask & DELETE_ACCESS) == 0) {
5401 status = NT_STATUS_INVALID_PARAMETER;
5402 goto fail;
5403 }
5404 }
5405
5406 if ((conn->fs_capabilities & FILE_NAMED_STREAMS)
5407 && is_ntfs_stream_smb_fname(smb_fname)
5408 && (!(private_flags & NTCREATEX_OPTIONS_PRIVATE_STREAM_DELETE))) {
5409 uint32_t base_create_disposition;
5410 struct smb_filename *smb_fname_base = NULL;
5411 uint32_t base_privflags;
5412
5413 if (create_options & FILE_DIRECTORY_FILE) {
5414 status = NT_STATUS_NOT_A_DIRECTORY;
5415 goto fail;
5416 }
5417
5418 switch (create_disposition) {
5419 case FILE_OPEN:
5420 base_create_disposition = FILE_OPEN;
5421 break;
5422 default:
5423 base_create_disposition = FILE_OPEN_IF;
5424 break;
5425 }
5426
5427 /* Create an smb_filename with stream_name == NULL. */
5428 smb_fname_base = synthetic_smb_fname(talloc_tos(),
5429 smb_fname->base_name,
5430 NULL,
5431 NULL,
5432 smb_fname->flags);
5433 if (smb_fname_base == NULL) {
5434 status = NT_STATUS_NO_MEMORY;
5435 goto fail;
5436 }
5437
5438 if (SMB_VFS_STAT(conn, smb_fname_base) == -1) {
5439 DEBUG(10, ("Unable to stat stream: %s\n",
5440 smb_fname_str_dbg(smb_fname_base)));
5441 } else {
5442 /*
5443 * https://bugzilla.samba.org/show_bug.cgi?id=10229
5444 * We need to check if the requested access mask
5445 * could be used to open the underlying file (if
5446 * it existed), as we're passing in zero for the
5447 * access mask to the base filename.
5448 */
5449 status = check_base_file_access(conn,
5450 smb_fname_base,
5451 access_mask);
5452
5453 if (!NT_STATUS_IS_OK(status)) {
5454 DEBUG(10, ("Permission check "
5455 "for base %s failed: "
5456 "%s\n", smb_fname->base_name,
5457 nt_errstr(status)));
5458 goto fail;
5459 }
5460 }
5461
5462 base_privflags = NTCREATEX_OPTIONS_PRIVATE_STREAM_BASEOPEN;
5463
5464 /* Open the base file. */
5465 status = create_file_unixpath(conn, NULL, smb_fname_base, 0,
5466 FILE_SHARE_READ
5467 | FILE_SHARE_WRITE
5468 | FILE_SHARE_DELETE,
5469 base_create_disposition,
5470 0, 0, 0, NULL, 0,
5471 base_privflags,
5472 NULL, NULL,
5473 &base_fsp, NULL);
5474 TALLOC_FREE(smb_fname_base);
5475
5476 if (!NT_STATUS_IS_OK(status)) {
5477 DEBUG(10, ("create_file_unixpath for base %s failed: "
5478 "%s\n", smb_fname->base_name,
5479 nt_errstr(status)));
5480 goto fail;
5481 }
5482 /* we don't need the low level fd */
5483 fd_close(base_fsp);
5484 }
5485
5486 /*
5487 * If it's a request for a directory open, deal with it separately.
5488 */
5489
5490 if (create_options & FILE_DIRECTORY_FILE) {
5491
5492 if (create_options & FILE_NON_DIRECTORY_FILE) {
5493 status = NT_STATUS_INVALID_PARAMETER;
5494 goto fail;
5495 }
5496
5497 /* Can't open a temp directory. IFS kit test. */
5498 if (!(file_attributes & FILE_FLAG_POSIX_SEMANTICS) &&
5499 (file_attributes & FILE_ATTRIBUTE_TEMPORARY)) {
5500 status = NT_STATUS_INVALID_PARAMETER;
5501 goto fail;
5502 }
5503
5504 /*
5505 * We will get a create directory here if the Win32
5506 * app specified a security descriptor in the
5507 * CreateDirectory() call.
5508 */
5509
5510 oplock_request = 0;
5511 status = open_directory(
5512 conn, req, smb_fname, access_mask, share_access,
5513 create_disposition, create_options, file_attributes,
5514 &info, &fsp);
5515 } else {
5516
5517 /*
5518 * Ordinary file case.
5519 */
5520
5521 status = file_new(req, conn, &fsp);
5522 if(!NT_STATUS_IS_OK(status)) {
5523 goto fail;
5524 }
5525
5526 status = fsp_set_smb_fname(fsp, smb_fname);
5527 if (!NT_STATUS_IS_OK(status)) {
5528 goto fail;
5529 }
5530
5531 if (base_fsp) {
5532 /*
5533 * We're opening the stream element of a
5534 * base_fsp we already opened. Set up the
5535 * base_fsp pointer.
5536 */
5537 fsp->base_fsp = base_fsp;
5538 }
5539
5540 if (allocation_size) {
5541 fsp->initial_allocation_size = smb_roundup(fsp->conn,
5542 allocation_size);
5543 }
5544
5545 status = open_file_ntcreate(conn,
5546 req,
5547 access_mask,
5548 share_access,
5549 create_disposition,
5550 create_options,
5551 file_attributes,
5552 oplock_request,
5553 lease,
5554 private_flags,
5555 &info,
5556 fsp);
5557
5558 if(!NT_STATUS_IS_OK(status)) {
5559 file_free(req, fsp);
5560 fsp = NULL;
5561 }
5562
5563 if (NT_STATUS_EQUAL(status, NT_STATUS_FILE_IS_A_DIRECTORY)) {
5564
5565 /* A stream open never opens a directory */
5566
5567 if (base_fsp) {
5568 status = NT_STATUS_FILE_IS_A_DIRECTORY;
5569 goto fail;
5570 }
5571
5572 /*
5573 * Fail the open if it was explicitly a non-directory
5574 * file.
5575 */
5576
5577 if (create_options & FILE_NON_DIRECTORY_FILE) {
5578 status = NT_STATUS_FILE_IS_A_DIRECTORY;
5579 goto fail;
5580 }
5581
5582 oplock_request = 0;
5583 status = open_directory(
5584 conn, req, smb_fname, access_mask,
5585 share_access, create_disposition,
5586 create_options, file_attributes,
5587 &info, &fsp);
5588 }
5589 }
5590
5591 if (!NT_STATUS_IS_OK(status)) {
5592 goto fail;
5593 }
5594
5595 fsp->base_fsp = base_fsp;
5596
5597 if ((ea_list != NULL) &&
5598 ((info == FILE_WAS_CREATED) || (info == FILE_WAS_OVERWRITTEN))) {
5599 status = set_ea(conn, fsp, fsp->fsp_name, ea_list);
5600 if (!NT_STATUS_IS_OK(status)) {
5601 goto fail;
5602 }
5603 }
5604
5605 if (!fsp->is_directory && S_ISDIR(fsp->fsp_name->st.st_ex_mode)) {
5606 status = NT_STATUS_ACCESS_DENIED;
5607 goto fail;
5608 }
5609
5610 /* Save the requested allocation size. */
5611 if ((info == FILE_WAS_CREATED) || (info == FILE_WAS_OVERWRITTEN)) {
5612 if ((allocation_size > (uint64_t)fsp->fsp_name->st.st_ex_size)
5613 && !(fsp->is_directory))
5614 {
5615 fsp->initial_allocation_size = smb_roundup(
5616 fsp->conn, allocation_size);
5617 if (vfs_allocate_file_space(
5618 fsp, fsp->initial_allocation_size) == -1) {
5619 status = NT_STATUS_DISK_FULL;
5620 goto fail;
5621 }
5622 } else {
5623 fsp->initial_allocation_size = smb_roundup(
5624 fsp->conn, (uint64_t)fsp->fsp_name->st.st_ex_size);
5625 }
5626 } else {
5627 fsp->initial_allocation_size = 0;
5628 }
5629
5630 if ((info == FILE_WAS_CREATED) && lp_nt_acl_support(SNUM(conn)) &&
5631 fsp->base_fsp == NULL) {
5632 if (sd != NULL) {
5633 /*
5634 * According to the MS documentation, the only time the security
5635 * descriptor is applied to the opened file is iff we *created* the
5636 * file; an existing file stays the same.
5637 *
5638 * Also, it seems (from observation) that you can open the file with
5639 * any access mask but you can still write the sd. We need to override
5640 * the granted access before we call set_sd
5641 * Patch for bug #2242 from Tom Lackemann <cessnatomny@yahoo.com>.
5642 */
5643
5644 uint32_t sec_info_sent;
5645 uint32_t saved_access_mask = fsp->access_mask;
5646
5647 sec_info_sent = get_sec_info(sd);
5648
5649 fsp->access_mask = FILE_GENERIC_ALL;
5650
5651 if (sec_info_sent & (SECINFO_OWNER|
5652 SECINFO_GROUP|
5653 SECINFO_DACL|
5654 SECINFO_SACL)) {
5655 status = set_sd(fsp, sd, sec_info_sent);
5656 }
5657
5658 fsp->access_mask = saved_access_mask;
5659
5660 if (!NT_STATUS_IS_OK(status)) {
5661 goto fail;
5662 }
5663 } else if (lp_inherit_acls(SNUM(conn))) {
5664 /* Inherit from parent. Errors here are not fatal. */
5665 status = inherit_new_acl(fsp);
5666 if (!NT_STATUS_IS_OK(status)) {
5667 DEBUG(10,("inherit_new_acl: failed for %s with %s\n",
5668 fsp_str_dbg(fsp),
5669 nt_errstr(status) ));
5670 }
5671 }
5672 }
5673
5674 if ((conn->fs_capabilities & FILE_FILE_COMPRESSION)
5675 && (create_options & FILE_NO_COMPRESSION)
5676 && (info == FILE_WAS_CREATED)) {
5677 status = SMB_VFS_SET_COMPRESSION(conn, fsp, fsp,
5678 COMPRESSION_FORMAT_NONE);
5679 if (!NT_STATUS_IS_OK(status)) {
5680 DEBUG(1, ("failed to disable compression: %s\n",
5681 nt_errstr(status)));
5682 }
5683 }
5684
5685 DEBUG(10, ("create_file_unixpath: info=%d\n", info));
5686
5687 *result = fsp;
5688 if (pinfo != NULL) {
5689 *pinfo = info;
5690 }
5691
5692 smb_fname->st = fsp->fsp_name->st;
5693
5694 return NT_STATUS_OK;
5695
5696 fail:
5697 DEBUG(10, ("create_file_unixpath: %s\n", nt_errstr(status)));
5698
5699 if (fsp != NULL) {
5700 if (base_fsp && fsp->base_fsp == base_fsp) {
5701 /*
5702 * The close_file below will close
5703 * fsp->base_fsp.
5704 */
5705 base_fsp = NULL;
5706 }
5707 close_file(req, fsp, ERROR_CLOSE);
5708 fsp = NULL;
5709 }
5710 if (base_fsp != NULL) {
5711 close_file(req, base_fsp, ERROR_CLOSE);
5712 base_fsp = NULL;
5713 }
5714 return status;
5715 }
5716
5717 /*
5718 * Calculate the full path name given a relative fid.
5719 */
5720 static NTSTATUS get_relative_fid_filename(
5721 connection_struct *conn,
5722 struct smb_request *req,
5723 uint16_t root_dir_fid,
5724 const struct smb_filename *smb_fname,
5725 struct smb_filename **smb_fname_out)
5726 {
5727 files_struct *dir_fsp;
5728 char *parent_fname = NULL;
5729 char *new_base_name = NULL;
5730 uint32_t ucf_flags = ucf_flags_from_smb_request(req);
5731 NTSTATUS status;
5732
5733 if (root_dir_fid == 0 || !smb_fname) {
5734 status = NT_STATUS_INTERNAL_ERROR;
5735 goto out;
5736 }
5737
5738 dir_fsp = file_fsp(req, root_dir_fid);
5739
5740 if (dir_fsp == NULL) {
5741 status = NT_STATUS_INVALID_HANDLE;
5742 goto out;
5743 }
5744
5745 if (is_ntfs_stream_smb_fname(dir_fsp->fsp_name)) {
5746 status = NT_STATUS_INVALID_HANDLE;
5747 goto out;
5748 }
5749
5750 if (!dir_fsp->is_directory) {
5751
5752 /*
5753 * Check to see if this is a mac fork of some kind.
5754 */
5755
5756 if ((conn->fs_capabilities & FILE_NAMED_STREAMS) &&
5757 is_ntfs_stream_smb_fname(smb_fname)) {
5758 status = NT_STATUS_OBJECT_PATH_NOT_FOUND;
5759 goto out;
5760 }
5761
5762 /*
5763 we need to handle the case when we get a
5764 relative open relative to a file and the
5765 pathname is blank - this is a reopen!
5766 (hint from demyn plantenberg)
5767 */
5768
5769 status = NT_STATUS_INVALID_HANDLE;
5770 goto out;
5771 }
5772
5773 if (ISDOT(dir_fsp->fsp_name->base_name)) {
5774 /*
5775 * We're at the toplevel dir, the final file name
5776 * must not contain ./, as this is filtered out
5777 * normally by srvstr_get_path and unix_convert
5778 * explicitly rejects paths containing ./.
5779 */
5780 parent_fname = talloc_strdup(talloc_tos(), "");
5781 if (parent_fname == NULL) {
5782 status = NT_STATUS_NO_MEMORY;
5783 goto out;
5784 }
5785 } else {
5786 size_t dir_name_len = strlen(dir_fsp->fsp_name->base_name);
5787
5788 /*
5789 * Copy in the base directory name.
5790 */
5791
5792 parent_fname = talloc_array(talloc_tos(), char,
5793 dir_name_len+2);
5794 if (parent_fname == NULL) {
5795 status = NT_STATUS_NO_MEMORY;
5796 goto out;
5797 }
5798 memcpy(parent_fname, dir_fsp->fsp_name->base_name,
5799 dir_name_len+1);
5800
5801 /*
5802 * Ensure it ends in a '/'.
5803 * We used TALLOC_SIZE +2 to add space for the '/'.
5804 */
5805
5806 if(dir_name_len
5807 && (parent_fname[dir_name_len-1] != '\\')
5808 && (parent_fname[dir_name_len-1] != '/')) {
5809 parent_fname[dir_name_len] = '/';
5810 parent_fname[dir_name_len+1] = '\0';
5811 }
5812 }
5813
5814 new_base_name = talloc_asprintf(talloc_tos(), "%s%s", parent_fname,
5815 smb_fname->base_name);
5816 if (new_base_name == NULL) {
5817 status = NT_STATUS_NO_MEMORY;
5818 goto out;
5819 }
5820
5821 status = filename_convert(req,
5822 conn,
5823 new_base_name,
5824 ucf_flags,
5825 NULL,
5826 NULL,
5827 smb_fname_out);
5828 if (!NT_STATUS_IS_OK(status)) {
5829 goto out;
5830 }
5831
5832 out:
5833 TALLOC_FREE(parent_fname);
5834 TALLOC_FREE(new_base_name);
5835 return status;
5836 }
5837
5838 NTSTATUS create_file_default(connection_struct *conn,
5839 struct smb_request *req,
5840 uint16_t root_dir_fid,
5841 struct smb_filename *smb_fname,
5842 uint32_t access_mask,
5843 uint32_t share_access,
5844 uint32_t create_disposition,
5845 uint32_t create_options,
5846 uint32_t file_attributes,
5847 uint32_t oplock_request,
5848 const struct smb2_lease *lease,
5849 uint64_t allocation_size,
5850 uint32_t private_flags,
5851 struct security_descriptor *sd,
5852 struct ea_list *ea_list,
5853 files_struct **result,
5854 int *pinfo,
5855 const struct smb2_create_blobs *in_context_blobs,
5856 struct smb2_create_blobs *out_context_blobs)
5857 {
5858 int info = FILE_WAS_OPENED;
5859 files_struct *fsp = NULL;
5860 NTSTATUS status;
5861 bool stream_name = false;
5862
5863 DBG_DEBUG("create_file: access_mask = 0x%x "
5864 "file_attributes = 0x%x, share_access = 0x%x, "
5865 "create_disposition = 0x%x create_options = 0x%x "
5866 "oplock_request = 0x%x "
5867 "private_flags = 0x%x "
5868 "root_dir_fid = 0x%x, ea_list = %p, sd = %p, "
5869 "fname = %s\n",
5870 (unsigned int)access_mask,
5871 (unsigned int)file_attributes,
5872 (unsigned int)share_access,
5873 (unsigned int)create_disposition,
5874 (unsigned int)create_options,
5875 (unsigned int)oplock_request,
5876 (unsigned int)private_flags,
5877 (unsigned int)root_dir_fid,
5878 ea_list, sd, smb_fname_str_dbg(smb_fname));
5879
5880 if (req != NULL) {
5881 /*
5882 * Remember the absolute time of the original request
5883 * with this mid. We'll use it later to see if this
5884 * has timed out.
5885 */
5886 get_deferred_open_message_state(req, &req->request_time, NULL);
5887 }
5888
5889 /*
5890 * Calculate the filename from the root_dir_if if necessary.
5891 */
5892
5893 if (root_dir_fid != 0) {
5894 struct smb_filename *smb_fname_out = NULL;
5895 status = get_relative_fid_filename(conn, req, root_dir_fid,
5896 smb_fname, &smb_fname_out);
5897 if (!NT_STATUS_IS_OK(status)) {
5898 goto fail;
5899 }
5900 smb_fname = smb_fname_out;
5901 }
5902
5903 /*
5904 * Check to see if this is a mac fork of some kind.
5905 */
5906
5907 stream_name = is_ntfs_stream_smb_fname(smb_fname);
5908 if (stream_name) {
5909 enum FAKE_FILE_TYPE fake_file_type;
5910
5911 fake_file_type = is_fake_file(smb_fname);
5912
5913 if (fake_file_type != FAKE_FILE_TYPE_NONE) {
5914
5915 /*
5916 * Here we go! support for changing the disk quotas
5917 * --metze
5918 *
5919 * We need to fake up to open this MAGIC QUOTA file
5920 * and return a valid FID.
5921 *
5922 * w2k close this file directly after openening xp
5923 * also tries a QUERY_FILE_INFO on the file and then
5924 * close it
5925 */
5926 status = open_fake_file(req, conn, req->vuid,
5927 fake_file_type, smb_fname,
5928 access_mask, &fsp);
5929 if (!NT_STATUS_IS_OK(status)) {
5930 goto fail;
5931 }
5932
5933 ZERO_STRUCT(smb_fname->st);
5934 goto done;
5935 }
5936
5937 if (!(conn->fs_capabilities & FILE_NAMED_STREAMS)) {
5938 status = NT_STATUS_OBJECT_NAME_NOT_FOUND;
5939 goto fail;
5940 }
5941 }
5942
5943 if (is_ntfs_default_stream_smb_fname(smb_fname)) {
5944 int ret;
5945 smb_fname->stream_name = NULL;
5946 /* We have to handle this error here. */
5947 if (create_options & FILE_DIRECTORY_FILE) {
5948 status = NT_STATUS_NOT_A_DIRECTORY;
5949 goto fail;
5950 }
5951 if (req != NULL && req->posix_pathnames) {
5952 ret = SMB_VFS_LSTAT(conn, smb_fname);
5953 } else {
5954 ret = SMB_VFS_STAT(conn, smb_fname);
5955 }
5956
5957 if (ret == 0 && VALID_STAT_OF_DIR(smb_fname->st)) {
5958 status = NT_STATUS_FILE_IS_A_DIRECTORY;
5959 goto fail;
5960 }
5961 }
5962
5963 status = create_file_unixpath(
5964 conn, req, smb_fname, access_mask, share_access,
5965 create_disposition, create_options, file_attributes,
5966 oplock_request, lease, allocation_size, private_flags,
5967 sd, ea_list,
5968 &fsp, &info);
5969
5970 if (!NT_STATUS_IS_OK(status)) {
5971 goto fail;
5972 }
5973
5974 done:
5975 DEBUG(10, ("create_file: info=%d\n", info));
5976
5977 *result = fsp;
5978 if (pinfo != NULL) {
5979 *pinfo = info;
5980 }
5981 return NT_STATUS_OK;
5982
5983 fail:
5984 DEBUG(10, ("create_file: %s\n", nt_errstr(status)));
5985
5986 if (fsp != NULL) {
5987 close_file(req, fsp, ERROR_CLOSE);
5988 fsp = NULL;
5989 }
5990 return status;
5991 }