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