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