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