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