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