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