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