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