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