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