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