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