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