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