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