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