ldb: Free memory when repacking database
[garming/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         DEBUG(10,("share_conflict: entry->access_mask = 0x%x, "
1465                   "entry->share_access = 0x%x, "
1466                   "entry->private_options = 0x%x\n",
1467                   (unsigned int)entry->access_mask,
1468                   (unsigned int)entry->share_access,
1469                   (unsigned int)entry->private_options));
1470
1471         if (server_id_is_disconnected(&entry->pid)) {
1472                 return false;
1473         }
1474
1475         DEBUG(10,("share_conflict: access_mask = 0x%x, share_access = 0x%x\n",
1476                   (unsigned int)access_mask, (unsigned int)share_access));
1477
1478         if ((entry->access_mask & (FILE_WRITE_DATA|
1479                                    FILE_APPEND_DATA|
1480                                    FILE_READ_DATA|
1481                                    FILE_EXECUTE|
1482                                    DELETE_ACCESS)) == 0) {
1483                 DEBUG(10,("share_conflict: No conflict due to "
1484                           "entry->access_mask = 0x%x\n",
1485                           (unsigned int)entry->access_mask ));
1486                 return False;
1487         }
1488
1489         if ((access_mask & (FILE_WRITE_DATA|
1490                             FILE_APPEND_DATA|
1491                             FILE_READ_DATA|
1492                             FILE_EXECUTE|
1493                             DELETE_ACCESS)) == 0) {
1494                 DEBUG(10,("share_conflict: No conflict due to "
1495                           "access_mask = 0x%x\n",
1496                           (unsigned int)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         /* Now we check the share modes, after any oplock breaks. */
1659         for(i = 0; i < lck->data->num_share_modes; i++) {
1660
1661                 if (!is_valid_share_mode_entry(&lck->data->share_modes[i])) {
1662                         continue;
1663                 }
1664
1665                 /* someone else has a share lock on it, check to see if we can
1666                  * too */
1667                 if (share_conflict(&lck->data->share_modes[i],
1668                                    access_mask, share_access)) {
1669
1670                         if (share_mode_stale_pid(lck->data, i)) {
1671                                 continue;
1672                         }
1673
1674                         return NT_STATUS_SHARING_VIOLATION;
1675                 }
1676         }
1677
1678         return NT_STATUS_OK;
1679 }
1680
1681 /*
1682  * Send a break message to the oplock holder and delay the open for
1683  * our client.
1684  */
1685
1686 NTSTATUS send_break_message(struct messaging_context *msg_ctx,
1687                             const struct file_id *id,
1688                             const struct share_mode_entry *exclusive,
1689                             uint16_t break_to)
1690 {
1691         struct oplock_break_message msg = {
1692                 .id = *id,
1693                 .share_file_id = exclusive->share_file_id,
1694                 .break_to = break_to,
1695         };
1696         enum ndr_err_code ndr_err;
1697         DATA_BLOB blob;
1698         NTSTATUS status;
1699
1700         if (DEBUGLVL(10)) {
1701                 struct server_id_buf buf;
1702                 DBG_DEBUG("Sending break message to %s\n",
1703                           server_id_str_buf(exclusive->pid, &buf));
1704                 NDR_PRINT_DEBUG(oplock_break_message, &msg);
1705         }
1706
1707         ndr_err = ndr_push_struct_blob(
1708                 &blob,
1709                 talloc_tos(),
1710                 &msg,
1711                 (ndr_push_flags_fn_t)ndr_push_oplock_break_message);
1712         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
1713                 DBG_WARNING("ndr_push_oplock_break_message failed: %s\n",
1714                             ndr_errstr(ndr_err));
1715                 return ndr_map_error2ntstatus(ndr_err);
1716         }
1717
1718         status = messaging_send(
1719                 msg_ctx, exclusive->pid, MSG_SMB_BREAK_REQUEST, &blob);
1720         TALLOC_FREE(blob.data);
1721         if (!NT_STATUS_IS_OK(status)) {
1722                 DEBUG(3, ("Could not send oplock break message: %s\n",
1723                           nt_errstr(status)));
1724         }
1725
1726         return status;
1727 }
1728
1729 /*
1730  * Do internal consistency checks on the share mode for a file.
1731  */
1732
1733 static bool validate_oplock_types(struct share_mode_lock *lck)
1734 {
1735         struct share_mode_data *d = lck->data;
1736         bool batch = false;
1737         bool ex_or_batch = false;
1738         bool level2 = false;
1739         bool no_oplock = false;
1740         uint32_t num_non_stat_opens = 0;
1741         uint32_t i;
1742
1743         for (i=0; i<d->num_share_modes; i++) {
1744                 struct share_mode_entry *e = &d->share_modes[i];
1745
1746                 if (!is_valid_share_mode_entry(e)) {
1747                         continue;
1748                 }
1749
1750                 if (e->op_mid == 0) {
1751                         /* INTERNAL_OPEN_ONLY */
1752                         continue;
1753                 }
1754
1755                 if (e->op_type == NO_OPLOCK && is_stat_open(e->access_mask)) {
1756                         /* We ignore stat opens in the table - they
1757                            always have NO_OPLOCK and never get or
1758                            cause breaks. JRA. */
1759                         continue;
1760                 }
1761
1762                 num_non_stat_opens += 1;
1763
1764                 if (BATCH_OPLOCK_TYPE(e->op_type)) {
1765                         /* batch - can only be one. */
1766                         if (share_mode_stale_pid(d, i)) {
1767                                 DEBUG(10, ("Found stale batch oplock\n"));
1768                                 continue;
1769                         }
1770                         if (ex_or_batch || batch || level2 || no_oplock) {
1771                                 DEBUG(0, ("Bad batch oplock entry %u.",
1772                                           (unsigned)i));
1773                                 return false;
1774                         }
1775                         batch = true;
1776                 }
1777
1778                 if (EXCLUSIVE_OPLOCK_TYPE(e->op_type)) {
1779                         if (share_mode_stale_pid(d, i)) {
1780                                 DEBUG(10, ("Found stale duplicate oplock\n"));
1781                                 continue;
1782                         }
1783                         /* Exclusive or batch - can only be one. */
1784                         if (ex_or_batch || level2 || no_oplock) {
1785                                 DEBUG(0, ("Bad exclusive or batch oplock "
1786                                           "entry %u.", (unsigned)i));
1787                                 return false;
1788                         }
1789                         ex_or_batch = true;
1790                 }
1791
1792                 if (LEVEL_II_OPLOCK_TYPE(e->op_type)) {
1793                         if (batch || ex_or_batch) {
1794                                 if (share_mode_stale_pid(d, i)) {
1795                                         DEBUG(10, ("Found stale LevelII "
1796                                                    "oplock\n"));
1797                                         continue;
1798                                 }
1799                                 DEBUG(0, ("Bad levelII oplock entry %u.",
1800                                           (unsigned)i));
1801                                 return false;
1802                         }
1803                         level2 = true;
1804                 }
1805
1806                 if (e->op_type == NO_OPLOCK) {
1807                         if (batch || ex_or_batch) {
1808                                 if (share_mode_stale_pid(d, i)) {
1809                                         DEBUG(10, ("Found stale NO_OPLOCK "
1810                                                    "entry\n"));
1811                                         continue;
1812                                 }
1813                                 DEBUG(0, ("Bad no oplock entry %u.",
1814                                           (unsigned)i));
1815                                 return false;
1816                         }
1817                         no_oplock = true;
1818                 }
1819         }
1820
1821         remove_stale_share_mode_entries(d);
1822
1823         if ((batch || ex_or_batch) && (num_non_stat_opens != 1)) {
1824                 DEBUG(1, ("got batch (%d) or ex (%d) non-exclusively (%d)\n",
1825                           (int)batch, (int)ex_or_batch,
1826                           (int)d->num_share_modes));
1827                 return false;
1828         }
1829
1830         return true;
1831 }
1832
1833 static bool delay_for_oplock(files_struct *fsp,
1834                              int oplock_request,
1835                              const struct smb2_lease *lease,
1836                              struct share_mode_lock *lck,
1837                              bool have_sharing_violation,
1838                              uint32_t create_disposition,
1839                              bool first_open_attempt)
1840 {
1841         struct share_mode_data *d = lck->data;
1842         uint32_t i;
1843         bool delay = false;
1844         bool will_overwrite;
1845         const uint32_t delay_mask = have_sharing_violation ?
1846                 SMB2_LEASE_HANDLE : SMB2_LEASE_WRITE;
1847
1848         if ((oplock_request & INTERNAL_OPEN_ONLY) ||
1849             is_stat_open(fsp->access_mask)) {
1850                 return false;
1851         }
1852
1853         switch (create_disposition) {
1854         case FILE_SUPERSEDE:
1855         case FILE_OVERWRITE:
1856         case FILE_OVERWRITE_IF:
1857                 will_overwrite = true;
1858                 break;
1859         default:
1860                 will_overwrite = false;
1861                 break;
1862         }
1863
1864         for (i=0; i<d->num_share_modes; i++) {
1865                 struct share_mode_entry *e = &d->share_modes[i];
1866                 bool e_is_lease = (e->op_type == LEASE_OPLOCK);
1867                 uint32_t e_lease_type = get_lease_type(d, e);
1868                 uint32_t break_to;
1869                 bool lease_is_breaking = false;
1870
1871                 if (e_is_lease) {
1872                         NTSTATUS status;
1873
1874                         if (lease != NULL) {
1875                                 bool our_lease = smb2_lease_equal(
1876                                         fsp_client_guid(fsp),
1877                                         &lease->lease_key,
1878                                         &e->client_guid,
1879                                         &e->lease_key);
1880                                 if (our_lease) {
1881                                         DBG_DEBUG("Ignoring our own lease\n");
1882                                         continue;
1883                                 }
1884                         }
1885
1886                         status = leases_db_get(
1887                                 &e->client_guid,
1888                                 &e->lease_key,
1889                                 &fsp->file_id,
1890                                 NULL, /* current_state */
1891                                 &lease_is_breaking,
1892                                 NULL, /* breaking_to_requested */
1893                                 NULL, /* breaking_to_required */
1894                                 NULL, /* lease_version */
1895                                 NULL); /* epoch */
1896                         SMB_ASSERT(NT_STATUS_IS_OK(status));
1897                 }
1898
1899                 break_to = e_lease_type & ~delay_mask;
1900
1901                 if (will_overwrite) {
1902                         break_to &= ~(SMB2_LEASE_HANDLE|SMB2_LEASE_READ);
1903                 }
1904
1905                 DEBUG(10, ("entry %u: e_lease_type %u, will_overwrite: %u\n",
1906                            (unsigned)i, (unsigned)e_lease_type,
1907                            (unsigned)will_overwrite));
1908
1909                 if ((e_lease_type & ~break_to) == 0) {
1910                         if (lease_is_breaking) {
1911                                 delay = true;
1912                         }
1913                         continue;
1914                 }
1915
1916                 if (share_mode_stale_pid(d, i)) {
1917                         continue;
1918                 }
1919
1920                 if (will_overwrite) {
1921                         /*
1922                          * If we break anyway break to NONE directly.
1923                          * Otherwise vfs_set_filelen() will trigger the
1924                          * break.
1925                          */
1926                         break_to &= ~(SMB2_LEASE_READ|SMB2_LEASE_WRITE);
1927                 }
1928
1929                 if (!e_is_lease) {
1930                         /*
1931                          * Oplocks only support breaking to R or NONE.
1932                          */
1933                         break_to &= ~(SMB2_LEASE_HANDLE|SMB2_LEASE_WRITE);
1934                 }
1935
1936                 DEBUG(10, ("breaking from %d to %d\n",
1937                            (int)e_lease_type, (int)break_to));
1938                 send_break_message(fsp->conn->sconn->msg_ctx, &fsp->file_id,
1939                                    e, break_to);
1940                 if (e_lease_type & delay_mask) {
1941                         delay = true;
1942                 }
1943                 if (lease_is_breaking && !first_open_attempt) {
1944                         delay = true;
1945                 }
1946         }
1947
1948         return delay;
1949 }
1950
1951 static bool file_has_brlocks(files_struct *fsp)
1952 {
1953         struct byte_range_lock *br_lck;
1954
1955         br_lck = brl_get_locks_readonly(fsp);
1956         if (!br_lck)
1957                 return false;
1958
1959         return (brl_num_locks(br_lck) > 0);
1960 }
1961
1962 struct fsp_lease *find_fsp_lease(struct files_struct *new_fsp,
1963                                  const struct smb2_lease_key *key,
1964                                  uint32_t current_state,
1965                                  uint16_t lease_version,
1966                                  uint16_t lease_epoch)
1967 {
1968         struct files_struct *fsp;
1969
1970         /*
1971          * TODO: Measure how expensive this loop is with thousands of open
1972          * handles...
1973          */
1974
1975         for (fsp = file_find_di_first(new_fsp->conn->sconn, new_fsp->file_id);
1976              fsp != NULL;
1977              fsp = file_find_di_next(fsp)) {
1978
1979                 if (fsp == new_fsp) {
1980                         continue;
1981                 }
1982                 if (fsp->oplock_type != LEASE_OPLOCK) {
1983                         continue;
1984                 }
1985                 if (smb2_lease_key_equal(&fsp->lease->lease.lease_key, key)) {
1986                         fsp->lease->ref_count += 1;
1987                         return fsp->lease;
1988                 }
1989         }
1990
1991         /* Not found - must be leased in another smbd. */
1992         new_fsp->lease = talloc_zero(new_fsp->conn->sconn, struct fsp_lease);
1993         if (new_fsp->lease == NULL) {
1994                 return NULL;
1995         }
1996         new_fsp->lease->ref_count = 1;
1997         new_fsp->lease->sconn = new_fsp->conn->sconn;
1998         new_fsp->lease->lease.lease_key = *key;
1999         new_fsp->lease->lease.lease_state = current_state;
2000         /*
2001          * We internally treat all leases as V2 and update
2002          * the epoch, but when sending breaks it matters if
2003          * the requesting lease was v1 or v2.
2004          */
2005         new_fsp->lease->lease.lease_version = lease_version;
2006         new_fsp->lease->lease.lease_epoch = lease_epoch;
2007         return new_fsp->lease;
2008 }
2009
2010 static NTSTATUS try_lease_upgrade(struct files_struct *fsp,
2011                                   struct share_mode_lock *lck,
2012                                   const struct GUID *client_guid,
2013                                   const struct smb2_lease *lease,
2014                                   uint32_t granted)
2015 {
2016         bool do_upgrade;
2017         uint32_t current_state, breaking_to_requested, breaking_to_required;
2018         bool breaking;
2019         uint16_t lease_version, epoch;
2020         uint32_t existing, requested;
2021         NTSTATUS status;
2022
2023         status = leases_db_get(
2024                 client_guid,
2025                 &lease->lease_key,
2026                 &fsp->file_id,
2027                 &current_state,
2028                 &breaking,
2029                 &breaking_to_requested,
2030                 &breaking_to_required,
2031                 &lease_version,
2032                 &epoch);
2033         if (!NT_STATUS_IS_OK(status)) {
2034                 return status;
2035         }
2036
2037         fsp->lease = find_fsp_lease(
2038                 fsp,
2039                 &lease->lease_key,
2040                 current_state,
2041                 lease_version,
2042                 epoch);
2043         if (fsp->lease == NULL) {
2044                 DEBUG(1, ("Did not find existing lease for file %s\n",
2045                           fsp_str_dbg(fsp)));
2046                 return NT_STATUS_NO_MEMORY;
2047         }
2048
2049         /*
2050          * Upgrade only if the requested lease is a strict upgrade.
2051          */
2052         existing = current_state;
2053         requested = lease->lease_state;
2054
2055         /*
2056          * Tricky: This test makes sure that "requested" is a
2057          * strict bitwise superset of "existing".
2058          */
2059         do_upgrade = ((existing & requested) == existing);
2060
2061         /*
2062          * Upgrade only if there's a change.
2063          */
2064         do_upgrade &= (granted != existing);
2065
2066         /*
2067          * Upgrade only if other leases don't prevent what was asked
2068          * for.
2069          */
2070         do_upgrade &= (granted == requested);
2071
2072         /*
2073          * only upgrade if we are not in breaking state
2074          */
2075         do_upgrade &= !breaking;
2076
2077         DEBUG(10, ("existing=%"PRIu32", requested=%"PRIu32", "
2078                    "granted=%"PRIu32", do_upgrade=%d\n",
2079                    existing, requested, granted, (int)do_upgrade));
2080
2081         if (do_upgrade) {
2082                 NTSTATUS set_status;
2083
2084                 current_state = granted;
2085                 epoch += 1;
2086
2087                 set_status = leases_db_set(
2088                         client_guid,
2089                         &lease->lease_key,
2090                         current_state,
2091                         breaking,
2092                         breaking_to_requested,
2093                         breaking_to_required,
2094                         lease_version,
2095                         epoch);
2096
2097                 if (!NT_STATUS_IS_OK(set_status)) {
2098                         DBG_DEBUG("leases_db_set failed: %s\n",
2099                                   nt_errstr(set_status));
2100                         return set_status;
2101                 }
2102         }
2103
2104         fsp_lease_update(fsp);
2105
2106         return NT_STATUS_OK;
2107 }
2108
2109 static NTSTATUS grant_new_fsp_lease(struct files_struct *fsp,
2110                                     struct share_mode_lock *lck,
2111                                     const struct GUID *client_guid,
2112                                     const struct smb2_lease *lease,
2113                                     uint32_t granted)
2114 {
2115         struct share_mode_data *d = lck->data;
2116         NTSTATUS status;
2117
2118         fsp->lease = talloc_zero(fsp->conn->sconn, struct fsp_lease);
2119         if (fsp->lease == NULL) {
2120                 return NT_STATUS_INSUFFICIENT_RESOURCES;
2121         }
2122         fsp->lease->ref_count = 1;
2123         fsp->lease->sconn = fsp->conn->sconn;
2124         fsp->lease->lease.lease_version = lease->lease_version;
2125         fsp->lease->lease.lease_key = lease->lease_key;
2126         fsp->lease->lease.lease_state = granted;
2127         fsp->lease->lease.lease_epoch = lease->lease_epoch + 1;
2128
2129         status = leases_db_add(client_guid,
2130                                &lease->lease_key,
2131                                &fsp->file_id,
2132                                fsp->lease->lease.lease_state,
2133                                fsp->lease->lease.lease_version,
2134                                fsp->lease->lease.lease_epoch,
2135                                fsp->conn->connectpath,
2136                                fsp->fsp_name->base_name,
2137                                fsp->fsp_name->stream_name);
2138         if (!NT_STATUS_IS_OK(status)) {
2139                 DEBUG(10, ("%s: leases_db_add failed: %s\n", __func__,
2140                            nt_errstr(status)));
2141                 TALLOC_FREE(fsp->lease);
2142                 return NT_STATUS_INSUFFICIENT_RESOURCES;
2143         }
2144
2145         d->modified = true;
2146
2147         return NT_STATUS_OK;
2148 }
2149
2150 static NTSTATUS grant_fsp_lease(struct files_struct *fsp,
2151                                 struct share_mode_lock *lck,
2152                                 const struct smb2_lease *lease,
2153                                 uint32_t granted)
2154 {
2155         const struct GUID *client_guid = fsp_client_guid(fsp);
2156         NTSTATUS status;
2157
2158         status = try_lease_upgrade(fsp, lck, client_guid, lease, granted);
2159
2160         if (NT_STATUS_EQUAL(status, NT_STATUS_NOT_FOUND)) {
2161                 status = grant_new_fsp_lease(
2162                         fsp, lck, client_guid, lease, granted);
2163         }
2164
2165         return status;
2166 }
2167
2168 static bool is_same_lease(const files_struct *fsp,
2169                           const struct share_mode_data *d,
2170                           const struct share_mode_entry *e,
2171                           const struct smb2_lease *lease)
2172 {
2173         if (e->op_type != LEASE_OPLOCK) {
2174                 return false;
2175         }
2176         if (lease == NULL) {
2177                 return false;
2178         }
2179
2180         return smb2_lease_equal(fsp_client_guid(fsp),
2181                                 &lease->lease_key,
2182                                 &e->client_guid,
2183                                 &e->lease_key);
2184 }
2185
2186 static int map_lease_type_to_oplock(uint32_t lease_type)
2187 {
2188         int result = NO_OPLOCK;
2189
2190         switch (lease_type) {
2191         case SMB2_LEASE_READ|SMB2_LEASE_WRITE|SMB2_LEASE_HANDLE:
2192                 result = BATCH_OPLOCK|EXCLUSIVE_OPLOCK;
2193                 break;
2194         case SMB2_LEASE_READ|SMB2_LEASE_WRITE:
2195                 result = EXCLUSIVE_OPLOCK;
2196                 break;
2197         case SMB2_LEASE_READ|SMB2_LEASE_HANDLE:
2198         case SMB2_LEASE_READ:
2199                 result = LEVEL_II_OPLOCK;
2200                 break;
2201         }
2202
2203         return result;
2204 }
2205
2206 static NTSTATUS grant_fsp_oplock_type(struct smb_request *req,
2207                                       struct files_struct *fsp,
2208                                       struct share_mode_lock *lck,
2209                                       int oplock_request,
2210                                       const struct smb2_lease *lease,
2211                                       uint32_t share_access,
2212                                       uint32_t access_mask)
2213 {
2214         struct share_mode_data *d = lck->data;
2215         bool got_handle_lease = false;
2216         bool got_oplock = false;
2217         uint32_t i;
2218         uint32_t granted;
2219         bool ok;
2220         NTSTATUS status;
2221
2222         if (oplock_request & INTERNAL_OPEN_ONLY) {
2223                 /* No oplocks on internal open. */
2224                 oplock_request = NO_OPLOCK;
2225                 DEBUG(10,("grant_fsp_oplock_type: oplock type 0x%x on file %s\n",
2226                         fsp->oplock_type, fsp_str_dbg(fsp)));
2227         }
2228
2229         if (oplock_request == LEASE_OPLOCK) {
2230                 if (lease == NULL) {
2231                         /*
2232                          * The SMB2 layer should have checked this
2233                          */
2234                         return NT_STATUS_INTERNAL_ERROR;
2235                 }
2236
2237                 granted = lease->lease_state;
2238
2239                 if (lp_kernel_oplocks(SNUM(fsp->conn))) {
2240                         DEBUG(10, ("No lease granted because kernel oplocks are enabled\n"));
2241                         granted = SMB2_LEASE_NONE;
2242                 }
2243                 if ((granted & (SMB2_LEASE_READ|SMB2_LEASE_WRITE)) == 0) {
2244                         DEBUG(10, ("No read or write lease requested\n"));
2245                         granted = SMB2_LEASE_NONE;
2246                 }
2247                 if (granted == SMB2_LEASE_WRITE) {
2248                         DEBUG(10, ("pure write lease requested\n"));
2249                         granted = SMB2_LEASE_NONE;
2250                 }
2251                 if (granted == (SMB2_LEASE_WRITE|SMB2_LEASE_HANDLE)) {
2252                         DEBUG(10, ("write and handle lease requested\n"));
2253                         granted = SMB2_LEASE_NONE;
2254                 }
2255         } else {
2256                 granted = map_oplock_to_lease_type(
2257                         oplock_request & ~SAMBA_PRIVATE_OPLOCK_MASK);
2258         }
2259
2260         if (lp_locking(fsp->conn->params) && file_has_brlocks(fsp)) {
2261                 DEBUG(10,("grant_fsp_oplock_type: file %s has byte range locks\n",
2262                         fsp_str_dbg(fsp)));
2263                 granted &= ~SMB2_LEASE_READ;
2264         }
2265
2266         for (i=0; i<d->num_share_modes; i++) {
2267                 struct share_mode_entry *e = &d->share_modes[i];
2268                 uint32_t e_lease_type;
2269
2270                 e_lease_type = get_lease_type(d, e);
2271
2272                 if ((granted & SMB2_LEASE_WRITE) &&
2273                     !is_same_lease(fsp, d, e, lease) &&
2274                     !share_mode_stale_pid(d, i)) {
2275                         /*
2276                          * Can grant only one writer
2277                          */
2278                         granted &= ~SMB2_LEASE_WRITE;
2279                 }
2280
2281                 if ((e_lease_type & SMB2_LEASE_HANDLE) && !got_handle_lease &&
2282                     !share_mode_stale_pid(d, i)) {
2283                         got_handle_lease = true;
2284                 }
2285
2286                 if ((e->op_type != LEASE_OPLOCK) && !got_oplock &&
2287                     !share_mode_stale_pid(d, i)) {
2288                         got_oplock = true;
2289                 }
2290         }
2291
2292         if ((granted & SMB2_LEASE_READ) && !(granted & SMB2_LEASE_WRITE)) {
2293                 bool allow_level2 =
2294                         (global_client_caps & CAP_LEVEL_II_OPLOCKS) &&
2295                         lp_level2_oplocks(SNUM(fsp->conn));
2296
2297                 if (!allow_level2) {
2298                         granted = SMB2_LEASE_NONE;
2299                 }
2300         }
2301
2302         if (oplock_request == LEASE_OPLOCK) {
2303                 if (got_oplock) {
2304                         granted &= ~SMB2_LEASE_HANDLE;
2305                 }
2306
2307                 fsp->oplock_type = LEASE_OPLOCK;
2308
2309                 status = grant_fsp_lease(fsp, lck, lease, granted);
2310                 if (!NT_STATUS_IS_OK(status)) {
2311                         return status;
2312
2313                 }
2314
2315                 DBG_DEBUG("lease_state=%d\n", fsp->lease->lease.lease_state);
2316         } else {
2317                 if (got_handle_lease) {
2318                         granted = SMB2_LEASE_NONE;
2319                 }
2320
2321                 fsp->oplock_type = map_lease_type_to_oplock(granted);
2322
2323                 status = set_file_oplock(fsp);
2324                 if (!NT_STATUS_IS_OK(status)) {
2325                         /*
2326                          * Could not get the kernel oplock
2327                          */
2328                         fsp->oplock_type = NO_OPLOCK;
2329                 }
2330         }
2331
2332         ok = set_share_mode(
2333                 lck,
2334                 fsp,
2335                 get_current_uid(fsp->conn),
2336                 req ? req->mid : 0,
2337                 fsp->oplock_type,
2338                 share_access,
2339                 access_mask);
2340         if (!ok) {
2341                 if (fsp->oplock_type == LEASE_OPLOCK) {
2342                         status = remove_lease_if_stale(
2343                                 lck->data,
2344                                 fsp_client_guid(fsp),
2345                                 &fsp->lease->lease.lease_key);
2346                         if (!NT_STATUS_IS_OK(status)) {
2347                                 DBG_WARNING("remove_lease_if_stale "
2348                                             "failed: %s\n",
2349                                             nt_errstr(status));
2350                         }
2351                 }
2352                 return NT_STATUS_NO_MEMORY;
2353         }
2354
2355         if (granted & SMB2_LEASE_READ) {
2356                 lck->data->flags |= SHARE_MODE_HAS_READ_LEASE;
2357         }
2358
2359         DEBUG(10,("grant_fsp_oplock_type: oplock type 0x%x on file %s\n",
2360                   fsp->oplock_type, fsp_str_dbg(fsp)));
2361
2362         return NT_STATUS_OK;
2363 }
2364
2365 static bool request_timed_out(struct smb_request *req, struct timeval timeout)
2366 {
2367         struct timeval now, end_time;
2368         GetTimeOfDay(&now);
2369         end_time = timeval_sum(&req->request_time, &timeout);
2370         return (timeval_compare(&end_time, &now) < 0);
2371 }
2372
2373 struct defer_open_state {
2374         struct smbXsrv_connection *xconn;
2375         uint64_t mid;
2376 };
2377
2378 static void defer_open_done(struct tevent_req *req);
2379
2380 /**
2381  * Defer an open and watch a locking.tdb record
2382  *
2383  * This defers an open that gets rescheduled once the locking.tdb record watch
2384  * is triggered by a change to the record.
2385  *
2386  * It is used to defer opens that triggered an oplock break and for the SMB1
2387  * sharing violation delay.
2388  **/
2389 static void defer_open(struct share_mode_lock *lck,
2390                        struct timeval timeout,
2391                        struct smb_request *req,
2392                        bool delayed_for_oplocks,
2393                        struct file_id id)
2394 {
2395         struct deferred_open_record *open_rec = NULL;
2396         struct timeval abs_timeout;
2397         struct defer_open_state *watch_state;
2398         struct tevent_req *watch_req;
2399         struct timeval_buf tvbuf1, tvbuf2;
2400         bool ok;
2401
2402         abs_timeout = timeval_sum(&req->request_time, &timeout);
2403
2404         DBG_DEBUG("request time [%s] timeout [%s] mid [%" PRIu64 "] "
2405                   "delayed_for_oplocks [%s] file_id [%s]\n",
2406                   timeval_str_buf(&req->request_time, false, true, &tvbuf1),
2407                   timeval_str_buf(&abs_timeout, false, true, &tvbuf2),
2408                   req->mid,
2409                   delayed_for_oplocks ? "yes" : "no",
2410                   file_id_string_tos(&id));
2411
2412         open_rec = talloc_zero(NULL, struct deferred_open_record);
2413         if (open_rec == NULL) {
2414                 TALLOC_FREE(lck);
2415                 exit_server("talloc failed");
2416         }
2417
2418         watch_state = talloc(open_rec, struct defer_open_state);
2419         if (watch_state == NULL) {
2420                 exit_server("talloc failed");
2421         }
2422         watch_state->xconn = req->xconn;
2423         watch_state->mid = req->mid;
2424
2425         DBG_DEBUG("defering mid %" PRIu64 "\n", req->mid);
2426
2427         watch_req = dbwrap_watched_watch_send(watch_state,
2428                                               req->sconn->ev_ctx,
2429                                               lck->data->record,
2430                                               (struct server_id){0});
2431         if (watch_req == NULL) {
2432                 exit_server("Could not watch share mode record");
2433         }
2434         tevent_req_set_callback(watch_req, defer_open_done, watch_state);
2435
2436         ok = tevent_req_set_endtime(watch_req, req->sconn->ev_ctx, abs_timeout);
2437         if (!ok) {
2438                 exit_server("tevent_req_set_endtime failed");
2439         }
2440
2441         ok = push_deferred_open_message_smb(req, timeout, id, open_rec);
2442         if (!ok) {
2443                 TALLOC_FREE(lck);
2444                 exit_server("push_deferred_open_message_smb failed");
2445         }
2446 }
2447
2448 static void defer_open_done(struct tevent_req *req)
2449 {
2450         struct defer_open_state *state = tevent_req_callback_data(
2451                 req, struct defer_open_state);
2452         NTSTATUS status;
2453         bool ret;
2454
2455         status = dbwrap_watched_watch_recv(req, NULL, NULL);
2456         TALLOC_FREE(req);
2457         if (!NT_STATUS_IS_OK(status)) {
2458                 DEBUG(5, ("dbwrap_watched_watch_recv returned %s\n",
2459                           nt_errstr(status)));
2460                 /*
2461                  * Even if it failed, retry anyway. TODO: We need a way to
2462                  * tell a re-scheduled open about that error.
2463                  */
2464         }
2465
2466         DEBUG(10, ("scheduling mid %llu\n", (unsigned long long)state->mid));
2467
2468         ret = schedule_deferred_open_message_smb(state->xconn, state->mid);
2469         SMB_ASSERT(ret);
2470         TALLOC_FREE(state);
2471 }
2472
2473 /**
2474  * Actually attempt the kernel oplock polling open.
2475  */
2476
2477 static void poll_open_fn(struct tevent_context *ev,
2478                          struct tevent_timer *te,
2479                          struct timeval current_time,
2480                          void *private_data)
2481 {
2482         struct deferred_open_record *open_rec = talloc_get_type_abort(
2483                 private_data, struct deferred_open_record);
2484         bool ok;
2485
2486         ok = schedule_deferred_open_message_smb(
2487                 open_rec->xconn, open_rec->mid);
2488         if (!ok) {
2489                 exit_server("schedule_deferred_open_message_smb failed");
2490         }
2491         DBG_DEBUG("timer fired. Retrying open !\n");
2492 }
2493
2494 /**
2495  * Reschedule an open for 1 second from now, if not timed out.
2496  **/
2497 static bool setup_poll_open(
2498         struct smb_request *req,
2499         struct file_id id,
2500         struct timeval max_timeout,
2501         struct timeval interval)
2502 {
2503
2504         bool ok;
2505         struct deferred_open_record *open_rec = NULL;
2506         struct timeval endtime, next_interval;
2507
2508         if (request_timed_out(req, max_timeout)) {
2509                 return false;
2510         }
2511
2512         open_rec = talloc_zero(NULL, struct deferred_open_record);
2513         if (open_rec == NULL) {
2514                 DBG_WARNING("talloc failed\n");
2515                 return false;
2516         }
2517         open_rec->xconn = req->xconn;
2518         open_rec->mid = req->mid;
2519
2520         /*
2521          * Make sure open_rec->te does not come later than the
2522          * request's maximum endtime.
2523          */
2524
2525         endtime = timeval_sum(&req->request_time, &max_timeout);
2526         next_interval = timeval_current_ofs(interval.tv_sec, interval.tv_usec);
2527         next_interval = timeval_min(&endtime, &next_interval);
2528
2529         open_rec->te = tevent_add_timer(
2530                 req->sconn->ev_ctx,
2531                 open_rec,
2532                 next_interval,
2533                 poll_open_fn,
2534                 open_rec);
2535         if (open_rec->te == NULL) {
2536                 DBG_WARNING("tevent_add_timer failed\n");
2537                 TALLOC_FREE(open_rec);
2538                 return false;
2539         }
2540
2541         ok = push_deferred_open_message_smb(req, max_timeout, id, open_rec);
2542         if (!ok) {
2543                 DBG_WARNING("push_deferred_open_message_smb failed\n");
2544                 TALLOC_FREE(open_rec);
2545                 return false;
2546         }
2547
2548         DBG_DEBUG("poll request time [%s] mid [%" PRIu64 "] file_id [%s]\n",
2549                   timeval_string(talloc_tos(), &req->request_time, false),
2550                   req->mid,
2551                   file_id_string_tos(&id));
2552
2553         return true;
2554 }
2555
2556 bool defer_smb1_sharing_violation(struct smb_request *req)
2557 {
2558         bool ok;
2559         int timeout_usecs;
2560
2561         if (!lp_defer_sharing_violations()) {
2562                 return false;
2563         }
2564
2565         /*
2566          * Try every 200msec up to (by default) one second. To be
2567          * precise, according to behaviour note <247> in [MS-CIFS],
2568          * the server tries 5 times. But up to one second should be
2569          * close enough.
2570          */
2571
2572         timeout_usecs = lp_parm_int(
2573                 SNUM(req->conn),
2574                 "smbd",
2575                 "sharedelay",
2576                 SHARING_VIOLATION_USEC_WAIT);
2577
2578         ok = setup_poll_open(
2579                 req,
2580                 (struct file_id) {0},
2581                 (struct timeval) { .tv_usec = timeout_usecs },
2582                 (struct timeval) { .tv_usec = 200000 });
2583         return ok;
2584 }
2585
2586 /****************************************************************************
2587  On overwrite open ensure that the attributes match.
2588 ****************************************************************************/
2589
2590 static bool open_match_attributes(connection_struct *conn,
2591                                   uint32_t old_dos_attr,
2592                                   uint32_t new_dos_attr,
2593                                   mode_t new_unx_mode,
2594                                   mode_t *returned_unx_mode)
2595 {
2596         uint32_t noarch_old_dos_attr, noarch_new_dos_attr;
2597
2598         noarch_old_dos_attr = (old_dos_attr & ~FILE_ATTRIBUTE_ARCHIVE);
2599         noarch_new_dos_attr = (new_dos_attr & ~FILE_ATTRIBUTE_ARCHIVE);
2600
2601         if((noarch_old_dos_attr == 0 && noarch_new_dos_attr != 0) || 
2602            (noarch_old_dos_attr != 0 && ((noarch_old_dos_attr & noarch_new_dos_attr) == noarch_old_dos_attr))) {
2603                 *returned_unx_mode = new_unx_mode;
2604         } else {
2605                 *returned_unx_mode = (mode_t)0;
2606         }
2607
2608         DEBUG(10,("open_match_attributes: old_dos_attr = 0x%x, "
2609                   "new_dos_attr = 0x%x "
2610                   "returned_unx_mode = 0%o\n",
2611                   (unsigned int)old_dos_attr,
2612                   (unsigned int)new_dos_attr,
2613                   (unsigned int)*returned_unx_mode ));
2614
2615         /* If we're mapping SYSTEM and HIDDEN ensure they match. */
2616         if (lp_map_system(SNUM(conn)) || lp_store_dos_attributes(SNUM(conn))) {
2617                 if ((old_dos_attr & FILE_ATTRIBUTE_SYSTEM) &&
2618                     !(new_dos_attr & FILE_ATTRIBUTE_SYSTEM)) {
2619                         return False;
2620                 }
2621         }
2622         if (lp_map_hidden(SNUM(conn)) || lp_store_dos_attributes(SNUM(conn))) {
2623                 if ((old_dos_attr & FILE_ATTRIBUTE_HIDDEN) &&
2624                     !(new_dos_attr & FILE_ATTRIBUTE_HIDDEN)) {
2625                         return False;
2626                 }
2627         }
2628         return True;
2629 }
2630
2631 static void schedule_defer_open(struct share_mode_lock *lck,
2632                                 struct file_id id,
2633                                 struct smb_request *req)
2634 {
2635         /* This is a relative time, added to the absolute
2636            request_time value to get the absolute timeout time.
2637            Note that if this is the second or greater time we enter
2638            this codepath for this particular request mid then
2639            request_time is left as the absolute time of the *first*
2640            time this request mid was processed. This is what allows
2641            the request to eventually time out. */
2642
2643         struct timeval timeout;
2644
2645         /* Normally the smbd we asked should respond within
2646          * OPLOCK_BREAK_TIMEOUT seconds regardless of whether
2647          * the client did, give twice the timeout as a safety
2648          * measure here in case the other smbd is stuck
2649          * somewhere else. */
2650
2651         timeout = timeval_set(OPLOCK_BREAK_TIMEOUT*2, 0);
2652
2653         if (request_timed_out(req, timeout)) {
2654                 return;
2655         }
2656
2657         defer_open(lck, timeout, req, true, id);
2658 }
2659
2660 /****************************************************************************
2661  Reschedule an open call that went asynchronous.
2662 ****************************************************************************/
2663
2664 static void schedule_async_open_timer(struct tevent_context *ev,
2665                                       struct tevent_timer *te,
2666                                       struct timeval current_time,
2667                                       void *private_data)
2668 {
2669         exit_server("async open timeout");
2670 }
2671
2672 static void schedule_async_open(struct smb_request *req)
2673 {
2674         struct deferred_open_record *open_rec = NULL;
2675         struct timeval timeout = timeval_set(20, 0);
2676         bool ok;
2677
2678         if (request_timed_out(req, timeout)) {
2679                 return;
2680         }
2681
2682         open_rec = talloc_zero(NULL, struct deferred_open_record);
2683         if (open_rec == NULL) {
2684                 exit_server("deferred_open_record_create failed");
2685         }
2686         open_rec->async_open = true;
2687
2688         ok = push_deferred_open_message_smb(
2689                 req, timeout, (struct file_id){0}, open_rec);
2690         if (!ok) {
2691                 exit_server("push_deferred_open_message_smb failed");
2692         }
2693
2694         open_rec->te = tevent_add_timer(req->sconn->ev_ctx,
2695                                         req,
2696                                         timeval_current_ofs(20, 0),
2697                                         schedule_async_open_timer,
2698                                         open_rec);
2699         if (open_rec->te == NULL) {
2700                 exit_server("tevent_add_timer failed");
2701         }
2702 }
2703
2704 /****************************************************************************
2705  Work out what access_mask to use from what the client sent us.
2706 ****************************************************************************/
2707
2708 static NTSTATUS smbd_calculate_maximum_allowed_access(
2709         connection_struct *conn,
2710         const struct smb_filename *smb_fname,
2711         bool use_privs,
2712         uint32_t *p_access_mask)
2713 {
2714         struct security_descriptor *sd;
2715         uint32_t access_granted;
2716         NTSTATUS status;
2717
2718         if (!use_privs && (get_current_uid(conn) == (uid_t)0)) {
2719                 *p_access_mask |= FILE_GENERIC_ALL;
2720                 return NT_STATUS_OK;
2721         }
2722
2723         status = SMB_VFS_GET_NT_ACL(conn, smb_fname,
2724                                     (SECINFO_OWNER |
2725                                      SECINFO_GROUP |
2726                                      SECINFO_DACL),
2727                                     talloc_tos(), &sd);
2728
2729         if (NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
2730                 /*
2731                  * File did not exist
2732                  */
2733                 *p_access_mask = FILE_GENERIC_ALL;
2734                 return NT_STATUS_OK;
2735         }
2736         if (!NT_STATUS_IS_OK(status)) {
2737                 DEBUG(10,("Could not get acl on file %s: %s\n",
2738                           smb_fname_str_dbg(smb_fname),
2739                           nt_errstr(status)));
2740                 return NT_STATUS_ACCESS_DENIED;
2741         }
2742
2743         /*
2744          * If we can access the path to this file, by
2745          * default we have FILE_READ_ATTRIBUTES from the
2746          * containing directory. See the section:
2747          * "Algorithm to Check Access to an Existing File"
2748          * in MS-FSA.pdf.
2749          *
2750          * se_file_access_check()
2751          * also takes care of owner WRITE_DAC and READ_CONTROL.
2752          */
2753         status = se_file_access_check(sd,
2754                                  get_current_nttok(conn),
2755                                  use_privs,
2756                                  (*p_access_mask & ~FILE_READ_ATTRIBUTES),
2757                                  &access_granted);
2758
2759         TALLOC_FREE(sd);
2760
2761         if (!NT_STATUS_IS_OK(status)) {
2762                 DEBUG(10, ("Access denied on file %s: "
2763                            "when calculating maximum access\n",
2764                            smb_fname_str_dbg(smb_fname)));
2765                 return NT_STATUS_ACCESS_DENIED;
2766         }
2767         *p_access_mask = (access_granted | FILE_READ_ATTRIBUTES);
2768
2769         if (!(access_granted & DELETE_ACCESS)) {
2770                 if (can_delete_file_in_directory(conn, smb_fname)) {
2771                         *p_access_mask |= DELETE_ACCESS;
2772                 }
2773         }
2774
2775         return NT_STATUS_OK;
2776 }
2777
2778 NTSTATUS smbd_calculate_access_mask(connection_struct *conn,
2779                                     const struct smb_filename *smb_fname,
2780                                     bool use_privs,
2781                                     uint32_t access_mask,
2782                                     uint32_t *access_mask_out)
2783 {
2784         NTSTATUS status;
2785         uint32_t orig_access_mask = access_mask;
2786         uint32_t rejected_share_access;
2787
2788         if (access_mask & SEC_MASK_INVALID) {
2789                 DBG_DEBUG("access_mask [%8x] contains invalid bits\n",
2790                           access_mask);
2791                 return NT_STATUS_ACCESS_DENIED;
2792         }
2793
2794         /*
2795          * Convert GENERIC bits to specific bits.
2796          */
2797
2798         se_map_generic(&access_mask, &file_generic_mapping);
2799
2800         /* Calculate MAXIMUM_ALLOWED_ACCESS if requested. */
2801         if (access_mask & MAXIMUM_ALLOWED_ACCESS) {
2802
2803                 status = smbd_calculate_maximum_allowed_access(
2804                         conn, smb_fname, use_privs, &access_mask);
2805
2806                 if (!NT_STATUS_IS_OK(status)) {
2807                         return status;
2808                 }
2809
2810                 access_mask &= conn->share_access;
2811         }
2812
2813         rejected_share_access = access_mask & ~(conn->share_access);
2814
2815         if (rejected_share_access) {
2816                 DEBUG(10, ("smbd_calculate_access_mask: Access denied on "
2817                         "file %s: rejected by share access mask[0x%08X] "
2818                         "orig[0x%08X] mapped[0x%08X] reject[0x%08X]\n",
2819                         smb_fname_str_dbg(smb_fname),
2820                         conn->share_access,
2821                         orig_access_mask, access_mask,
2822                         rejected_share_access));
2823                 return NT_STATUS_ACCESS_DENIED;
2824         }
2825
2826         *access_mask_out = access_mask;
2827         return NT_STATUS_OK;
2828 }
2829
2830 /****************************************************************************
2831  Remove the deferred open entry under lock.
2832 ****************************************************************************/
2833
2834 /****************************************************************************
2835  Return true if this is a state pointer to an asynchronous create.
2836 ****************************************************************************/
2837
2838 bool is_deferred_open_async(const struct deferred_open_record *rec)
2839 {
2840         return rec->async_open;
2841 }
2842
2843 static bool clear_ads(uint32_t create_disposition)
2844 {
2845         bool ret = false;
2846
2847         switch (create_disposition) {
2848         case FILE_SUPERSEDE:
2849         case FILE_OVERWRITE_IF:
2850         case FILE_OVERWRITE:
2851                 ret = true;
2852                 break;
2853         default:
2854                 break;
2855         }
2856         return ret;
2857 }
2858
2859 static int disposition_to_open_flags(uint32_t create_disposition)
2860 {
2861         int ret = 0;
2862
2863         /*
2864          * Currently we're using FILE_SUPERSEDE as the same as
2865          * FILE_OVERWRITE_IF but they really are
2866          * different. FILE_SUPERSEDE deletes an existing file
2867          * (requiring delete access) then recreates it.
2868          */
2869
2870         switch (create_disposition) {
2871         case FILE_SUPERSEDE:
2872         case FILE_OVERWRITE_IF:
2873                 /*
2874                  * If file exists replace/overwrite. If file doesn't
2875                  * exist create.
2876                  */
2877                 ret = O_CREAT|O_TRUNC;
2878                 break;
2879
2880         case FILE_OPEN:
2881                 /*
2882                  * If file exists open. If file doesn't exist error.
2883                  */
2884                 ret = 0;
2885                 break;
2886
2887         case FILE_OVERWRITE:
2888                 /*
2889                  * If file exists overwrite. If file doesn't exist
2890                  * error.
2891                  */
2892                 ret = O_TRUNC;
2893                 break;
2894
2895         case FILE_CREATE:
2896                 /*
2897                  * If file exists error. If file doesn't exist create.
2898                  */
2899                 ret = O_CREAT|O_EXCL;
2900                 break;
2901
2902         case FILE_OPEN_IF:
2903                 /*
2904                  * If file exists open. If file doesn't exist create.
2905                  */
2906                 ret = O_CREAT;
2907                 break;
2908         }
2909         return ret;
2910 }
2911
2912 static int calculate_open_access_flags(uint32_t access_mask,
2913                                        uint32_t private_flags)
2914 {
2915         bool need_write, need_read;
2916
2917         /*
2918          * Note that we ignore the append flag as append does not
2919          * mean the same thing under DOS and Unix.
2920          */
2921
2922         need_write = (access_mask & (FILE_WRITE_DATA | FILE_APPEND_DATA));
2923         if (!need_write) {
2924                 return O_RDONLY;
2925         }
2926
2927         /* DENY_DOS opens are always underlying read-write on the
2928            file handle, no matter what the requested access mask
2929            says. */
2930
2931         need_read =
2932                 ((private_flags & NTCREATEX_OPTIONS_PRIVATE_DENY_DOS) ||
2933                  access_mask & (FILE_READ_ATTRIBUTES|FILE_READ_DATA|
2934                                 FILE_READ_EA|FILE_EXECUTE));
2935
2936         if (!need_read) {
2937                 return O_WRONLY;
2938         }
2939         return O_RDWR;
2940 }
2941
2942 /****************************************************************************
2943  Open a file with a share mode. Passed in an already created files_struct *.
2944 ****************************************************************************/
2945
2946 static NTSTATUS open_file_ntcreate(connection_struct *conn,
2947                             struct smb_request *req,
2948                             uint32_t access_mask,               /* access bits (FILE_READ_DATA etc.) */
2949                             uint32_t share_access,      /* share constants (FILE_SHARE_READ etc) */
2950                             uint32_t create_disposition,        /* FILE_OPEN_IF etc. */
2951                             uint32_t create_options,    /* options such as delete on close. */
2952                             uint32_t new_dos_attributes,        /* attributes used for new file. */
2953                             int oplock_request,         /* internal Samba oplock codes. */
2954                             const struct smb2_lease *lease,
2955                                                         /* Information (FILE_EXISTS etc.) */
2956                             uint32_t private_flags,     /* Samba specific flags. */
2957                             int *pinfo,
2958                             files_struct *fsp)
2959 {
2960         struct smb_filename *smb_fname = fsp->fsp_name;
2961         int flags=0;
2962         int flags2=0;
2963         bool file_existed = VALID_STAT(smb_fname->st);
2964         bool def_acl = False;
2965         bool posix_open = False;
2966         bool new_file_created = False;
2967         bool first_open_attempt = true;
2968         NTSTATUS fsp_open = NT_STATUS_ACCESS_DENIED;
2969         mode_t new_unx_mode = (mode_t)0;
2970         mode_t unx_mode = (mode_t)0;
2971         int info;
2972         uint32_t existing_dos_attributes = 0;
2973         struct share_mode_lock *lck = NULL;
2974         uint32_t open_access_mask = access_mask;
2975         NTSTATUS status;
2976         char *parent_dir;
2977         SMB_STRUCT_STAT saved_stat = smb_fname->st;
2978         struct timespec old_write_time;
2979         struct file_id id;
2980
2981         if (conn->printer) {
2982                 /*
2983                  * Printers are handled completely differently.
2984                  * Most of the passed parameters are ignored.
2985                  */
2986
2987                 if (pinfo) {
2988                         *pinfo = FILE_WAS_CREATED;
2989                 }
2990
2991                 DEBUG(10, ("open_file_ntcreate: printer open fname=%s\n",
2992                            smb_fname_str_dbg(smb_fname)));
2993
2994                 if (!req) {
2995                         DEBUG(0,("open_file_ntcreate: printer open without "
2996                                 "an SMB request!\n"));
2997                         return NT_STATUS_INTERNAL_ERROR;
2998                 }
2999
3000                 return print_spool_open(fsp, smb_fname->base_name,
3001                                         req->vuid);
3002         }
3003
3004         if (!parent_dirname(talloc_tos(), smb_fname->base_name, &parent_dir,
3005                             NULL)) {
3006                 return NT_STATUS_NO_MEMORY;
3007         }
3008
3009         if (new_dos_attributes & FILE_FLAG_POSIX_SEMANTICS) {
3010                 posix_open = True;
3011                 unx_mode = (mode_t)(new_dos_attributes & ~FILE_FLAG_POSIX_SEMANTICS);
3012                 new_dos_attributes = 0;
3013         } else {
3014                 /* Windows allows a new file to be created and
3015                    silently removes a FILE_ATTRIBUTE_DIRECTORY
3016                    sent by the client. Do the same. */
3017
3018                 new_dos_attributes &= ~FILE_ATTRIBUTE_DIRECTORY;
3019
3020                 /* We add FILE_ATTRIBUTE_ARCHIVE to this as this mode is only used if the file is
3021                  * created new. */
3022                 unx_mode = unix_mode(conn, new_dos_attributes | FILE_ATTRIBUTE_ARCHIVE,
3023                                      smb_fname, parent_dir);
3024         }
3025
3026         DEBUG(10, ("open_file_ntcreate: fname=%s, dos_attrs=0x%x "
3027                    "access_mask=0x%x share_access=0x%x "
3028                    "create_disposition = 0x%x create_options=0x%x "
3029                    "unix mode=0%o oplock_request=%d private_flags = 0x%x\n",
3030                    smb_fname_str_dbg(smb_fname), new_dos_attributes,
3031                    access_mask, share_access, create_disposition,
3032                    create_options, (unsigned int)unx_mode, oplock_request,
3033                    (unsigned int)private_flags));
3034
3035         if (req == NULL) {
3036                 /* Ensure req == NULL means INTERNAL_OPEN_ONLY */
3037                 SMB_ASSERT(oplock_request == INTERNAL_OPEN_ONLY);
3038         } else {
3039                 /* And req != NULL means no INTERNAL_OPEN_ONLY */
3040                 SMB_ASSERT(((oplock_request & INTERNAL_OPEN_ONLY) == 0));
3041         }
3042
3043         /*
3044          * Only non-internal opens can be deferred at all
3045          */
3046
3047         if (req) {
3048                 struct deferred_open_record *open_rec;
3049                 if (get_deferred_open_message_state(req, NULL, &open_rec)) {
3050
3051                         /* If it was an async create retry, the file
3052                            didn't exist. */
3053
3054                         if (is_deferred_open_async(open_rec)) {
3055                                 SET_STAT_INVALID(smb_fname->st);
3056                                 file_existed = false;
3057                         }
3058
3059                         /* Ensure we don't reprocess this message. */
3060                         remove_deferred_open_message_smb(req->xconn, req->mid);
3061
3062                         first_open_attempt = false;
3063                 }
3064         }
3065
3066         if (!posix_open) {
3067                 new_dos_attributes &= SAMBA_ATTRIBUTES_MASK;
3068                 if (file_existed) {
3069                         /*
3070                          * Only use stored DOS attributes for checks
3071                          * against requested attributes (below via
3072                          * open_match_attributes()), cf bug #11992
3073                          * for details. -slow
3074                          */
3075                         uint32_t attr = 0;
3076
3077                         status = SMB_VFS_GET_DOS_ATTRIBUTES(conn, smb_fname, &attr);
3078                         if (NT_STATUS_IS_OK(status)) {
3079                                 existing_dos_attributes = attr;
3080                         }
3081                 }
3082         }
3083
3084         /* ignore any oplock requests if oplocks are disabled */
3085         if (!lp_oplocks(SNUM(conn)) ||
3086             IS_VETO_OPLOCK_PATH(conn, smb_fname->base_name)) {
3087                 /* Mask off everything except the private Samba bits. */
3088                 oplock_request &= SAMBA_PRIVATE_OPLOCK_MASK;
3089         }
3090
3091         /* this is for OS/2 long file names - say we don't support them */
3092         if (req != NULL && !req->posix_pathnames &&
3093                         strstr(smb_fname->base_name,".+,;=[].")) {
3094                 /* OS/2 Workplace shell fix may be main code stream in a later
3095                  * release. */
3096                 DEBUG(5,("open_file_ntcreate: OS/2 long filenames are not "
3097                          "supported.\n"));
3098                 if (use_nt_status()) {
3099                         return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3100                 }
3101                 return NT_STATUS_DOS(ERRDOS, ERRcannotopen);
3102         }
3103
3104         switch( create_disposition ) {
3105                 case FILE_OPEN:
3106                         /* If file exists open. If file doesn't exist error. */
3107                         if (!file_existed) {
3108                                 DEBUG(5,("open_file_ntcreate: FILE_OPEN "
3109                                          "requested for file %s and file "
3110                                          "doesn't exist.\n",
3111                                          smb_fname_str_dbg(smb_fname)));
3112                                 errno = ENOENT;
3113                                 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3114                         }
3115                         break;
3116
3117                 case FILE_OVERWRITE:
3118                         /* If file exists overwrite. If file doesn't exist
3119                          * error. */
3120                         if (!file_existed) {
3121                                 DEBUG(5,("open_file_ntcreate: FILE_OVERWRITE "
3122                                          "requested for file %s and file "
3123                                          "doesn't exist.\n",
3124                                          smb_fname_str_dbg(smb_fname) ));
3125                                 errno = ENOENT;
3126                                 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3127                         }
3128                         break;
3129
3130                 case FILE_CREATE:
3131                         /* If file exists error. If file doesn't exist
3132                          * create. */
3133                         if (file_existed) {
3134                                 DEBUG(5,("open_file_ntcreate: FILE_CREATE "
3135                                          "requested for file %s and file "
3136                                          "already exists.\n",
3137                                          smb_fname_str_dbg(smb_fname)));
3138                                 if (S_ISDIR(smb_fname->st.st_ex_mode)) {
3139                                         errno = EISDIR;
3140                                 } else {
3141                                         errno = EEXIST;
3142                                 }
3143                                 return map_nt_error_from_unix(errno);
3144                         }
3145                         break;
3146
3147                 case FILE_SUPERSEDE:
3148                 case FILE_OVERWRITE_IF:
3149                 case FILE_OPEN_IF:
3150                         break;
3151                 default:
3152                         return NT_STATUS_INVALID_PARAMETER;
3153         }
3154
3155         flags2 = disposition_to_open_flags(create_disposition);
3156
3157         /* We only care about matching attributes on file exists and
3158          * overwrite. */
3159
3160         if (!posix_open && file_existed &&
3161             ((create_disposition == FILE_OVERWRITE) ||
3162              (create_disposition == FILE_OVERWRITE_IF))) {
3163                 if (!open_match_attributes(conn, existing_dos_attributes,
3164                                            new_dos_attributes,
3165                                            unx_mode, &new_unx_mode)) {
3166                         DEBUG(5,("open_file_ntcreate: attributes mismatch "
3167                                  "for file %s (%x %x) (0%o, 0%o)\n",
3168                                  smb_fname_str_dbg(smb_fname),
3169                                  existing_dos_attributes,
3170                                  new_dos_attributes,
3171                                  (unsigned int)smb_fname->st.st_ex_mode,
3172                                  (unsigned int)unx_mode ));
3173                         errno = EACCES;
3174                         return NT_STATUS_ACCESS_DENIED;
3175                 }
3176         }
3177
3178         status = smbd_calculate_access_mask(conn, smb_fname,
3179                                         false,
3180                                         access_mask,
3181                                         &access_mask); 
3182         if (!NT_STATUS_IS_OK(status)) {
3183                 DEBUG(10, ("open_file_ntcreate: smbd_calculate_access_mask "
3184                         "on file %s returned %s\n",
3185                         smb_fname_str_dbg(smb_fname), nt_errstr(status)));
3186                 return status;
3187         }
3188
3189         open_access_mask = access_mask;
3190
3191         if (flags2 & O_TRUNC) {
3192                 open_access_mask |= FILE_WRITE_DATA; /* This will cause oplock breaks. */
3193         }
3194
3195         DEBUG(10, ("open_file_ntcreate: fname=%s, after mapping "
3196                    "access_mask=0x%x\n", smb_fname_str_dbg(smb_fname),
3197                     access_mask));
3198
3199         /*
3200          * Note that we ignore the append flag as append does not
3201          * mean the same thing under DOS and Unix.
3202          */
3203
3204         flags = calculate_open_access_flags(access_mask, private_flags);
3205
3206         /*
3207          * Currently we only look at FILE_WRITE_THROUGH for create options.
3208          */
3209
3210 #if defined(O_SYNC)
3211         if ((create_options & FILE_WRITE_THROUGH) && lp_strict_sync(SNUM(conn))) {
3212                 flags2 |= O_SYNC;
3213         }
3214 #endif /* O_SYNC */
3215
3216         if (posix_open && (access_mask & FILE_APPEND_DATA)) {
3217                 flags2 |= O_APPEND;
3218         }
3219
3220         if (!posix_open && !CAN_WRITE(conn)) {
3221                 /*
3222                  * We should really return a permission denied error if either
3223                  * O_CREAT or O_TRUNC are set, but for compatibility with
3224                  * older versions of Samba we just AND them out.
3225                  */
3226                 flags2 &= ~(O_CREAT|O_TRUNC);
3227         }
3228
3229         /*
3230          * With kernel oplocks the open breaking an oplock
3231          * blocks until the oplock holder has given up the
3232          * oplock or closed the file. We prevent this by always
3233          * trying to open the file with O_NONBLOCK (see "man
3234          * fcntl" on Linux).
3235          *
3236          * If a process that doesn't use the smbd open files
3237          * database or communication methods holds a kernel
3238          * oplock we must periodically poll for available open
3239          * using O_NONBLOCK.
3240          */
3241         flags2 |= O_NONBLOCK;
3242
3243         /*
3244          * Ensure we can't write on a read-only share or file.
3245          */
3246
3247         if (flags != O_RDONLY && file_existed &&
3248             (!CAN_WRITE(conn) || IS_DOS_READONLY(existing_dos_attributes))) {
3249                 DEBUG(5,("open_file_ntcreate: write access requested for "
3250                          "file %s on read only %s\n",
3251                          smb_fname_str_dbg(smb_fname),
3252                          !CAN_WRITE(conn) ? "share" : "file" ));
3253                 errno = EACCES;
3254                 return NT_STATUS_ACCESS_DENIED;
3255         }
3256
3257         fsp->file_id = vfs_file_id_from_sbuf(conn, &smb_fname->st);
3258         fsp->fh->private_options = private_flags;
3259         fsp->access_mask = open_access_mask; /* We change this to the
3260                                               * requested access_mask after
3261                                               * the open is done. */
3262         if (posix_open) {
3263                 fsp->posix_flags |= FSP_POSIX_FLAGS_ALL;
3264         }
3265
3266         if ((create_options & FILE_DELETE_ON_CLOSE) &&
3267                         (flags2 & O_CREAT) &&
3268                         !file_existed) {
3269                 /* Delete on close semantics for new files. */
3270                 status = can_set_delete_on_close(fsp,
3271                                                 new_dos_attributes);
3272                 if (!NT_STATUS_IS_OK(status)) {
3273                         fd_close(fsp);
3274                         return status;
3275                 }
3276         }
3277
3278         /*
3279          * Ensure we pay attention to default ACLs on directories if required.
3280          */
3281
3282         if ((flags2 & O_CREAT) && lp_inherit_acls(SNUM(conn)) &&
3283             (def_acl = directory_has_default_acl(conn, parent_dir))) {
3284                 unx_mode = (0777 & lp_create_mask(SNUM(conn)));
3285         }
3286
3287         DEBUG(4,("calling open_file with flags=0x%X flags2=0x%X mode=0%o, "
3288                 "access_mask = 0x%x, open_access_mask = 0x%x\n",
3289                  (unsigned int)flags, (unsigned int)flags2,
3290                  (unsigned int)unx_mode, (unsigned int)access_mask,
3291                  (unsigned int)open_access_mask));
3292
3293         fsp_open = open_file(fsp, conn, req, parent_dir,
3294                              flags|flags2, unx_mode, access_mask,
3295                              open_access_mask, &new_file_created);
3296
3297         if (NT_STATUS_EQUAL(fsp_open, NT_STATUS_NETWORK_BUSY)) {
3298                 bool delay;
3299
3300                 /*
3301                  * This handles the kernel oplock case:
3302                  *
3303                  * the file has an active kernel oplock and the open() returned
3304                  * EWOULDBLOCK/EAGAIN which maps to NETWORK_BUSY.
3305                  *
3306                  * "Samba locking.tdb oplocks" are handled below after acquiring
3307                  * the sharemode lock with get_share_mode_lock().
3308                  */
3309                 if (file_existed && S_ISFIFO(fsp->fsp_name->st.st_ex_mode)) {
3310                         DEBUG(10, ("FIFO busy\n"));
3311                         return NT_STATUS_NETWORK_BUSY;
3312                 }
3313                 if (req == NULL) {
3314                         DEBUG(10, ("Internal open busy\n"));
3315                         return NT_STATUS_NETWORK_BUSY;
3316                 }
3317
3318                 /*
3319                  * From here on we assume this is an oplock break triggered
3320                  */
3321
3322                 lck = get_existing_share_mode_lock(talloc_tos(), fsp->file_id);
3323                 if (lck == NULL) {
3324                         /*
3325                          * No oplock from Samba around. Set up a poll every 1
3326                          * second to retry a non-blocking open until the time
3327                          * expires.
3328                          */
3329                         setup_poll_open(
3330                                 req,
3331                                 fsp->file_id,
3332                                 timeval_set(OPLOCK_BREAK_TIMEOUT*2, 0),
3333                                 timeval_set(1, 0));
3334                         DBG_DEBUG("No Samba oplock around after EWOULDBLOCK. "
3335                                 "Retrying with poll\n");
3336                         return NT_STATUS_SHARING_VIOLATION;
3337                 }
3338
3339                 if (!validate_oplock_types(lck)) {
3340                         smb_panic("validate_oplock_types failed");
3341                 }
3342
3343                 delay = delay_for_oplock(fsp, 0, lease, lck, false,
3344                                          create_disposition,
3345                                          first_open_attempt);
3346                 if (delay) {
3347                         schedule_defer_open(lck, fsp->file_id, req);
3348                         TALLOC_FREE(lck);
3349                         DEBUG(10, ("Sent oplock break request to kernel "
3350                                    "oplock holder\n"));
3351                         return NT_STATUS_SHARING_VIOLATION;
3352                 }
3353
3354                 /*
3355                  * No oplock from Samba around. Set up a poll every 1
3356                  * second to retry a non-blocking open until the time
3357                  * expires.
3358                  */
3359                 setup_poll_open(
3360                         req,
3361                         fsp->file_id,
3362                         timeval_set(OPLOCK_BREAK_TIMEOUT*2, 0),
3363                         timeval_set(1, 0));
3364
3365                 TALLOC_FREE(lck);
3366                 DBG_DEBUG("No Samba oplock around after EWOULDBLOCK. "
3367                         "Retrying with poll\n");
3368                 return NT_STATUS_SHARING_VIOLATION;
3369         }
3370
3371         if (!NT_STATUS_IS_OK(fsp_open)) {
3372                 if (NT_STATUS_EQUAL(fsp_open, NT_STATUS_RETRY)) {
3373                         schedule_async_open(req);
3374                 }
3375                 return fsp_open;
3376         }
3377
3378         if (new_file_created) {
3379                 /*
3380                  * As we atomically create using O_CREAT|O_EXCL,
3381                  * then if new_file_created is true, then
3382                  * file_existed *MUST* have been false (even
3383                  * if the file was previously detected as being
3384                  * there).
3385                  */
3386                 file_existed = false;
3387         }
3388
3389         if (file_existed && !check_same_dev_ino(&saved_stat, &smb_fname->st)) {
3390                 /*
3391                  * The file did exist, but some other (local or NFS)
3392                  * process either renamed/unlinked and re-created the
3393                  * file with different dev/ino after we walked the path,
3394                  * but before we did the open. We could retry the
3395                  * open but it's a rare enough case it's easier to
3396                  * just fail the open to prevent creating any problems
3397                  * in the open file db having the wrong dev/ino key.
3398                  */
3399                 fd_close(fsp);
3400                 DBG_WARNING("file %s - dev/ino mismatch. "
3401                             "Old (dev=%ju, ino=%ju). "
3402                             "New (dev=%ju, ino=%ju). Failing open "
3403                             "with NT_STATUS_ACCESS_DENIED.\n",
3404                             smb_fname_str_dbg(smb_fname),
3405                             (uintmax_t)saved_stat.st_ex_dev,
3406                             (uintmax_t)saved_stat.st_ex_ino,
3407                             (uintmax_t)smb_fname->st.st_ex_dev,
3408                             (uintmax_t)smb_fname->st.st_ex_ino);
3409                 return NT_STATUS_ACCESS_DENIED;
3410         }
3411
3412         old_write_time = smb_fname->st.st_ex_mtime;
3413
3414         /*
3415          * Deal with the race condition where two smbd's detect the
3416          * file doesn't exist and do the create at the same time. One
3417          * of them will win and set a share mode, the other (ie. this
3418          * one) should check if the requested share mode for this
3419          * create is allowed.
3420          */
3421
3422         /*
3423          * Now the file exists and fsp is successfully opened,
3424          * fsp->dev and fsp->inode are valid and should replace the
3425          * dev=0,inode=0 from a non existent file. Spotted by
3426          * Nadav Danieli <nadavd@exanet.com>. JRA.
3427          */
3428
3429         id = fsp->file_id;
3430
3431         lck = get_share_mode_lock(talloc_tos(), id,
3432                                   conn->connectpath,
3433                                   smb_fname, &old_write_time);
3434
3435         if (lck == NULL) {
3436                 DEBUG(0, ("open_file_ntcreate: Could not get share "
3437                           "mode lock for %s\n",
3438                           smb_fname_str_dbg(smb_fname)));
3439                 fd_close(fsp);
3440                 return NT_STATUS_SHARING_VIOLATION;
3441         }
3442
3443         /* Get the types we need to examine. */
3444         if (!validate_oplock_types(lck)) {
3445                 smb_panic("validate_oplock_types failed");
3446         }
3447
3448         if (has_delete_on_close(lck, fsp->name_hash)) {
3449                 TALLOC_FREE(lck);
3450                 fd_close(fsp);
3451                 return NT_STATUS_DELETE_PENDING;
3452         }
3453
3454         status = open_mode_check(conn, lck,
3455                                  access_mask, share_access);
3456
3457         if (NT_STATUS_EQUAL(status, NT_STATUS_SHARING_VIOLATION) ||
3458             (lck->data->num_share_modes > 0)) {
3459                 /*
3460                  * This comes from ancient times out of open_mode_check. I
3461                  * have no clue whether this is still necessary. I can't think
3462                  * of a case where this would actually matter further down in
3463                  * this function. I leave it here for further investigation
3464                  * :-)
3465                  */
3466                 file_existed = true;
3467         }
3468
3469         if (req != NULL) {
3470                 /*
3471                  * Handle oplocks, deferring the request if delay_for_oplock()
3472                  * triggered a break message and we have to wait for the break
3473                  * response.
3474                  */
3475                 bool delay;
3476                 bool sharing_violation = NT_STATUS_EQUAL(
3477                         status, NT_STATUS_SHARING_VIOLATION);
3478
3479                 delay = delay_for_oplock(fsp, oplock_request, lease, lck,
3480                                          sharing_violation,
3481                                          create_disposition,
3482                                          first_open_attempt);
3483                 if (delay) {
3484                         schedule_defer_open(lck, fsp->file_id, req);
3485                         TALLOC_FREE(lck);
3486                         fd_close(fsp);
3487                         return NT_STATUS_SHARING_VIOLATION;
3488                 }
3489         }
3490
3491         if (!NT_STATUS_IS_OK(status)) {
3492
3493                 SMB_ASSERT(NT_STATUS_EQUAL(status, NT_STATUS_SHARING_VIOLATION));
3494
3495                 TALLOC_FREE(lck);
3496                 fd_close(fsp);
3497
3498                 return NT_STATUS_SHARING_VIOLATION;
3499         }
3500
3501         /* Should we atomically (to the client at least) truncate ? */
3502         if ((!new_file_created) &&
3503             (flags2 & O_TRUNC) &&
3504             (S_ISREG(fsp->fsp_name->st.st_ex_mode))) {
3505                 int ret;
3506
3507                 ret = SMB_VFS_FTRUNCATE(fsp, 0);
3508                 if (ret != 0) {
3509                         status = map_nt_error_from_unix(errno);
3510                         TALLOC_FREE(lck);
3511                         fd_close(fsp);
3512                         return status;
3513                 }
3514                 notify_fname(fsp->conn, NOTIFY_ACTION_MODIFIED,
3515                              FILE_NOTIFY_CHANGE_SIZE
3516                              | FILE_NOTIFY_CHANGE_ATTRIBUTES,
3517                              fsp->fsp_name->base_name);
3518         }
3519
3520         /*
3521          * We have the share entry *locked*.....
3522          */
3523
3524         /* Delete streams if create_disposition requires it */
3525         if (!new_file_created && clear_ads(create_disposition) &&
3526             !is_ntfs_stream_smb_fname(smb_fname)) {
3527                 status = delete_all_streams(conn, smb_fname);
3528                 if (!NT_STATUS_IS_OK(status)) {
3529                         TALLOC_FREE(lck);
3530                         fd_close(fsp);
3531                         return status;
3532                 }
3533         }
3534
3535         if (fsp->fh->fd != -1 && lp_kernel_share_modes(SNUM(conn))) {
3536                 int ret_flock;
3537                 /*
3538                  * Beware: streams implementing VFS modules may
3539                  * implement streams in a way that fsp will have the
3540                  * basefile open in the fsp fd, so lacking a distinct
3541                  * fd for the stream kernel_flock will apply on the
3542                  * basefile which is wrong. The actual check is
3543                  * deferred to the VFS module implementing the
3544                  * kernel_flock call.
3545                  */
3546                 ret_flock = SMB_VFS_KERNEL_FLOCK(fsp, share_access, access_mask);
3547                 if(ret_flock == -1 ){
3548
3549                         TALLOC_FREE(lck);
3550                         fd_close(fsp);
3551
3552                         return NT_STATUS_SHARING_VIOLATION;
3553                 }
3554
3555                 fsp->kernel_share_modes_taken = true;
3556         }
3557
3558         /*
3559          * At this point onwards, we can guarantee that the share entry
3560          * is locked, whether we created the file or not, and that the
3561          * deny mode is compatible with all current opens.
3562          */
3563
3564         /*
3565          * According to Samba4, SEC_FILE_READ_ATTRIBUTE is always granted,
3566          * but we don't have to store this - just ignore it on access check.
3567          */
3568         if (conn->sconn->using_smb2) {
3569                 /*
3570                  * SMB2 doesn't return it (according to Microsoft tests).
3571                  * Test Case: TestSuite_ScenarioNo009GrantedAccessTestS0
3572                  * File created with access = 0x7 (Read, Write, Delete)
3573                  * Query Info on file returns 0x87 (Read, Write, Delete, Read Attributes)
3574                  */
3575                 fsp->access_mask = access_mask;
3576         } else {
3577                 /* But SMB1 does. */
3578                 fsp->access_mask = access_mask | FILE_READ_ATTRIBUTES;
3579         }
3580
3581         if (file_existed) {
3582                 /*
3583                  * stat opens on existing files don't get oplocks.
3584                  * They can get leases.
3585                  *
3586                  * Note that we check for stat open on the *open_access_mask*,
3587                  * i.e. the access mask we actually used to do the open,
3588                  * not the one the client asked for (which is in
3589                  * fsp->access_mask). This is due to the fact that
3590                  * FILE_OVERWRITE and FILE_OVERWRITE_IF add in O_TRUNC,
3591                  * which adds FILE_WRITE_DATA to open_access_mask.
3592                  */
3593                 if (is_stat_open(open_access_mask) && lease == NULL) {
3594                         oplock_request = NO_OPLOCK;
3595                 }
3596         }
3597
3598         if (new_file_created) {
3599                 info = FILE_WAS_CREATED;
3600         } else {
3601                 if (flags2 & O_TRUNC) {
3602                         info = FILE_WAS_OVERWRITTEN;
3603                 } else {
3604                         info = FILE_WAS_OPENED;
3605                 }
3606         }
3607
3608         if (pinfo) {
3609                 *pinfo = info;
3610         }
3611
3612         /*
3613          * Setup the oplock info in both the shared memory and
3614          * file structs.
3615          */
3616         status = grant_fsp_oplock_type(
3617                 req,
3618                 fsp,
3619                 lck,
3620                 oplock_request,
3621                 lease,
3622                 share_access,
3623                 fsp->access_mask);
3624         if (!NT_STATUS_IS_OK(status)) {
3625                 TALLOC_FREE(lck);
3626                 fd_close(fsp);
3627                 return status;
3628         }
3629
3630         /* Handle strange delete on close create semantics. */
3631         if (create_options & FILE_DELETE_ON_CLOSE) {
3632                 if (!new_file_created) {
3633                         status = can_set_delete_on_close(fsp,
3634                                          existing_dos_attributes);
3635
3636                         if (!NT_STATUS_IS_OK(status)) {
3637                                 /* Remember to delete the mode we just added. */
3638                                 del_share_mode(lck, fsp);
3639                                 TALLOC_FREE(lck);
3640                                 fd_close(fsp);
3641                                 return status;
3642                         }
3643                 }
3644                 /* Note that here we set the *initial* delete on close flag,
3645                    not the regular one. The magic gets handled in close. */
3646                 fsp->initial_delete_on_close = True;
3647         }
3648
3649         if (info == FILE_WAS_CREATED) {
3650                 smb_fname->st.st_ex_iflags &= ~ST_EX_IFLAG_CALCULATED_ITIME;
3651         }
3652
3653         if (info != FILE_WAS_OPENED) {
3654                 /* Overwritten files should be initially set as archive */
3655                 if ((info == FILE_WAS_OVERWRITTEN && lp_map_archive(SNUM(conn))) ||
3656                     lp_store_dos_attributes(SNUM(conn))) {
3657                         if (!posix_open) {
3658                                 if (file_set_dosmode(conn, smb_fname,
3659                                             new_dos_attributes | FILE_ATTRIBUTE_ARCHIVE,
3660                                             parent_dir, true) == 0) {
3661                                         unx_mode = smb_fname->st.st_ex_mode;
3662                                 }
3663                         }
3664                 }
3665         }
3666
3667         /* Determine sparse flag. */
3668         if (posix_open) {
3669                 /* POSIX opens are sparse by default. */
3670                 fsp->is_sparse = true;
3671         } else {
3672                 fsp->is_sparse = (file_existed &&
3673                         (existing_dos_attributes & FILE_ATTRIBUTE_SPARSE));
3674         }
3675
3676         /*
3677          * Take care of inherited ACLs on created files - if default ACL not
3678          * selected.
3679          */
3680
3681         if (!posix_open && new_file_created && !def_acl) {
3682                 if (unx_mode != smb_fname->st.st_ex_mode) {
3683                         int ret = SMB_VFS_FCHMOD(fsp, unx_mode);
3684                         if (ret == -1) {
3685                                 DBG_INFO("failed to reset "
3686                                   "attributes of file %s to 0%o\n",
3687                                   smb_fname_str_dbg(smb_fname),
3688                                   (unsigned int)unx_mode);
3689                         }
3690                 }
3691
3692         } else if (new_unx_mode) {
3693                 /*
3694                  * We only get here in the case of:
3695                  *
3696                  * a). Not a POSIX open.
3697                  * b). File already existed.
3698                  * c). File was overwritten.
3699                  * d). Requested DOS attributes didn't match
3700                  *     the DOS attributes on the existing file.
3701                  *
3702                  * In that case new_unx_mode has been set
3703                  * equal to the calculated mode (including
3704                  * possible inheritance of the mode from the
3705                  * containing directory).
3706                  *
3707                  * Note this mode was calculated with the
3708                  * DOS attribute FILE_ATTRIBUTE_ARCHIVE added,
3709                  * so the mode change here is suitable for
3710                  * an overwritten file.
3711                  */
3712
3713                 if (new_unx_mode != smb_fname->st.st_ex_mode) {
3714                         int ret = SMB_VFS_FCHMOD(fsp, new_unx_mode);
3715                         if (ret == -1) {
3716                                 DBG_INFO("failed to reset "
3717                                   "attributes of file %s to 0%o\n",
3718                                   smb_fname_str_dbg(smb_fname),
3719                                   (unsigned int)new_unx_mode);
3720                         }
3721                 }
3722         }
3723
3724         {
3725                 /*
3726                  * Deal with other opens having a modified write time.
3727                  */
3728                 struct timespec write_time = get_share_mode_write_time(lck);
3729
3730                 if (!null_timespec(write_time)) {
3731                         update_stat_ex_mtime(&fsp->fsp_name->st, write_time);
3732                 }
3733         }
3734
3735         TALLOC_FREE(lck);
3736
3737         return NT_STATUS_OK;
3738 }
3739
3740 static NTSTATUS mkdir_internal(connection_struct *conn,
3741                                struct smb_filename *smb_dname,
3742                                uint32_t file_attributes)
3743 {
3744         mode_t mode;
3745         char *parent_dir = NULL;
3746         NTSTATUS status;
3747         bool posix_open = false;
3748         bool need_re_stat = false;
3749         uint32_t access_mask = SEC_DIR_ADD_SUBDIR;
3750
3751         if (!CAN_WRITE(conn) || (access_mask & ~(conn->share_access))) {
3752                 DEBUG(5,("mkdir_internal: failing share access "
3753                          "%s\n", lp_servicename(talloc_tos(), SNUM(conn))));
3754                 return NT_STATUS_ACCESS_DENIED;
3755         }
3756
3757         if (!parent_dirname(talloc_tos(), smb_dname->base_name, &parent_dir,
3758                             NULL)) {
3759                 return NT_STATUS_NO_MEMORY;
3760         }
3761
3762         if (file_attributes & FILE_FLAG_POSIX_SEMANTICS) {
3763                 posix_open = true;
3764                 mode = (mode_t)(file_attributes & ~FILE_FLAG_POSIX_SEMANTICS);
3765         } else {
3766                 mode = unix_mode(conn, FILE_ATTRIBUTE_DIRECTORY, smb_dname, parent_dir);
3767         }
3768
3769         status = check_parent_access(conn,
3770                                         smb_dname,
3771                                         access_mask);
3772         if(!NT_STATUS_IS_OK(status)) {
3773                 DEBUG(5,("mkdir_internal: check_parent_access "
3774                         "on directory %s for path %s returned %s\n",
3775                         parent_dir,
3776                         smb_dname->base_name,
3777                         nt_errstr(status) ));
3778                 return status;
3779         }
3780
3781         if (SMB_VFS_MKDIR(conn, smb_dname, mode) != 0) {
3782                 return map_nt_error_from_unix(errno);
3783         }
3784
3785         /* Ensure we're checking for a symlink here.... */
3786         /* We don't want to get caught by a symlink racer. */
3787
3788         if (SMB_VFS_LSTAT(conn, smb_dname) == -1) {
3789                 DEBUG(2, ("Could not stat directory '%s' just created: %s\n",
3790                           smb_fname_str_dbg(smb_dname), strerror(errno)));
3791                 return map_nt_error_from_unix(errno);
3792         }
3793
3794         if (!S_ISDIR(smb_dname->st.st_ex_mode)) {
3795                 DEBUG(0, ("Directory '%s' just created is not a directory !\n",
3796                           smb_fname_str_dbg(smb_dname)));
3797                 return NT_STATUS_NOT_A_DIRECTORY;
3798         }
3799
3800         smb_dname->st.st_ex_iflags &= ~ST_EX_IFLAG_CALCULATED_ITIME;
3801
3802         if (lp_store_dos_attributes(SNUM(conn))) {
3803                 if (!posix_open) {
3804                         file_set_dosmode(conn, smb_dname,
3805                                          file_attributes | FILE_ATTRIBUTE_DIRECTORY,
3806                                          parent_dir, true);
3807                 }
3808         }
3809
3810         if (lp_inherit_permissions(SNUM(conn))) {
3811                 inherit_access_posix_acl(conn, parent_dir,
3812                                          smb_dname, mode);
3813                 need_re_stat = true;
3814         }
3815
3816         if (!posix_open) {
3817                 /*
3818                  * Check if high bits should have been set,
3819                  * then (if bits are missing): add them.
3820                  * Consider bits automagically set by UNIX, i.e. SGID bit from parent
3821                  * dir.
3822                  */
3823                 if ((mode & ~(S_IRWXU|S_IRWXG|S_IRWXO)) &&
3824                     (mode & ~smb_dname->st.st_ex_mode)) {
3825                         SMB_VFS_CHMOD(conn, smb_dname,
3826                                       (smb_dname->st.st_ex_mode |
3827                                           (mode & ~smb_dname->st.st_ex_mode)));
3828                         need_re_stat = true;
3829                 }
3830         }
3831
3832         /* Change the owner if required. */
3833         if (lp_inherit_owner(SNUM(conn)) != INHERIT_OWNER_NO) {
3834                 change_dir_owner_to_parent(conn, parent_dir,
3835                                            smb_dname,
3836                                            &smb_dname->st);
3837                 need_re_stat = true;
3838         }
3839
3840         if (need_re_stat) {
3841                 if (SMB_VFS_LSTAT(conn, smb_dname) == -1) {
3842                         DEBUG(2, ("Could not stat directory '%s' just created: %s\n",
3843                           smb_fname_str_dbg(smb_dname), strerror(errno)));
3844                         return map_nt_error_from_unix(errno);
3845                 }
3846         }
3847
3848         notify_fname(conn, NOTIFY_ACTION_ADDED, FILE_NOTIFY_CHANGE_DIR_NAME,
3849                      smb_dname->base_name);
3850
3851         return NT_STATUS_OK;
3852 }
3853
3854 /****************************************************************************
3855  Open a directory from an NT SMB call.
3856 ****************************************************************************/
3857
3858 static NTSTATUS open_directory(connection_struct *conn,
3859                                struct smb_request *req,
3860                                struct smb_filename *smb_dname,
3861                                uint32_t access_mask,
3862                                uint32_t share_access,
3863                                uint32_t create_disposition,
3864                                uint32_t create_options,
3865                                uint32_t file_attributes,
3866                                int *pinfo,
3867                                files_struct **result)
3868 {
3869         files_struct *fsp = NULL;
3870         bool dir_existed = VALID_STAT(smb_dname->st) ? True : False;
3871         struct share_mode_lock *lck = NULL;
3872         NTSTATUS status;
3873         struct timespec mtimespec;
3874         int info = 0;
3875         bool ok;
3876
3877         if (is_ntfs_stream_smb_fname(smb_dname)) {
3878                 DEBUG(2, ("open_directory: %s is a stream name!\n",
3879                           smb_fname_str_dbg(smb_dname)));
3880                 return NT_STATUS_NOT_A_DIRECTORY;
3881         }
3882
3883         if (!(file_attributes & FILE_FLAG_POSIX_SEMANTICS)) {
3884                 /* Ensure we have a directory attribute. */
3885                 file_attributes |= FILE_ATTRIBUTE_DIRECTORY;
3886         }
3887
3888         DEBUG(5,("open_directory: opening directory %s, access_mask = 0x%x, "
3889                  "share_access = 0x%x create_options = 0x%x, "
3890                  "create_disposition = 0x%x, file_attributes = 0x%x\n",
3891                  smb_fname_str_dbg(smb_dname),
3892                  (unsigned int)access_mask,
3893                  (unsigned int)share_access,
3894                  (unsigned int)create_options,
3895                  (unsigned int)create_disposition,
3896                  (unsigned int)file_attributes));
3897
3898         status = smbd_calculate_access_mask(conn, smb_dname, false,
3899                                             access_mask, &access_mask);
3900         if (!NT_STATUS_IS_OK(status)) {
3901                 DEBUG(10, ("open_directory: smbd_calculate_access_mask "
3902                         "on file %s returned %s\n",
3903                         smb_fname_str_dbg(smb_dname),
3904                         nt_errstr(status)));
3905                 return status;
3906         }
3907
3908         if ((access_mask & SEC_FLAG_SYSTEM_SECURITY) &&
3909                         !security_token_has_privilege(get_current_nttok(conn),
3910                                         SEC_PRIV_SECURITY)) {
3911                 DEBUG(10, ("open_directory: open on %s "
3912                         "failed - SEC_FLAG_SYSTEM_SECURITY denied.\n",
3913                         smb_fname_str_dbg(smb_dname)));
3914                 return NT_STATUS_PRIVILEGE_NOT_HELD;
3915         }
3916
3917         switch( create_disposition ) {
3918                 case FILE_OPEN:
3919
3920                         if (!dir_existed) {
3921                                 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3922                         }
3923
3924                         info = FILE_WAS_OPENED;
3925                         break;
3926
3927                 case FILE_CREATE:
3928
3929                         /* If directory exists error. If directory doesn't
3930                          * exist create. */
3931
3932                         if (dir_existed) {
3933                                 status = NT_STATUS_OBJECT_NAME_COLLISION;
3934                                 DEBUG(2, ("open_directory: unable to create "
3935                                           "%s. Error was %s\n",
3936                                           smb_fname_str_dbg(smb_dname),
3937                                           nt_errstr(status)));
3938                                 return status;
3939                         }
3940
3941                         status = mkdir_internal(conn, smb_dname,
3942                                                 file_attributes);
3943
3944                         if (!NT_STATUS_IS_OK(status)) {
3945                                 DEBUG(2, ("open_directory: unable to create "
3946                                           "%s. Error was %s\n",
3947                                           smb_fname_str_dbg(smb_dname),
3948                                           nt_errstr(status)));
3949                                 return status;
3950                         }
3951
3952                         info = FILE_WAS_CREATED;
3953                         break;
3954
3955                 case FILE_OPEN_IF:
3956                         /*
3957                          * If directory exists open. If directory doesn't
3958                          * exist create.
3959                          */
3960
3961                         if (dir_existed) {
3962                                 status = NT_STATUS_OK;
3963                                 info = FILE_WAS_OPENED;
3964                         } else {
3965                                 status = mkdir_internal(conn, smb_dname,
3966                                                 file_attributes);
3967
3968                                 if (NT_STATUS_IS_OK(status)) {
3969                                         info = FILE_WAS_CREATED;
3970                                 } else {
3971                                         /* Cope with create race. */
3972                                         if (!NT_STATUS_EQUAL(status,
3973                                                         NT_STATUS_OBJECT_NAME_COLLISION)) {
3974                                                 DEBUG(2, ("open_directory: unable to create "
3975                                                         "%s. Error was %s\n",
3976                                                         smb_fname_str_dbg(smb_dname),
3977                                                         nt_errstr(status)));
3978                                                 return status;
3979                                         }
3980
3981                                         /*
3982                                          * If mkdir_internal() returned
3983                                          * NT_STATUS_OBJECT_NAME_COLLISION
3984                                          * we still must lstat the path.
3985                                          */
3986
3987                                         if (SMB_VFS_LSTAT(conn, smb_dname)
3988                                                         == -1) {
3989                                                 DEBUG(2, ("Could not stat "
3990                                                         "directory '%s' just "
3991                                                         "opened: %s\n",
3992                                                         smb_fname_str_dbg(
3993                                                                 smb_dname),
3994                                                         strerror(errno)));
3995                                                 return map_nt_error_from_unix(
3996                                                                 errno);
3997                                         }
3998
3999                                         info = FILE_WAS_OPENED;
4000                                 }
4001                         }
4002
4003                         break;
4004
4005                 case FILE_SUPERSEDE:
4006                 case FILE_OVERWRITE:
4007                 case FILE_OVERWRITE_IF:
4008                 default:
4009                         DEBUG(5,("open_directory: invalid create_disposition "
4010                                  "0x%x for directory %s\n",
4011                                  (unsigned int)create_disposition,
4012                                  smb_fname_str_dbg(smb_dname)));
4013                         return NT_STATUS_INVALID_PARAMETER;
4014         }
4015
4016         if(!S_ISDIR(smb_dname->st.st_ex_mode)) {
4017                 DEBUG(5,("open_directory: %s is not a directory !\n",
4018                          smb_fname_str_dbg(smb_dname)));
4019                 return NT_STATUS_NOT_A_DIRECTORY;
4020         }
4021
4022         if (info == FILE_WAS_OPENED) {
4023                 status = smbd_check_access_rights(conn,
4024                                                 smb_dname,
4025                                                 false,
4026                                                 access_mask);
4027                 if (!NT_STATUS_IS_OK(status)) {
4028                         DEBUG(10, ("open_directory: smbd_check_access_rights on "
4029                                 "file %s failed with %s\n",
4030                                 smb_fname_str_dbg(smb_dname),
4031                                 nt_errstr(status)));
4032                         return status;
4033                 }
4034         }
4035
4036         status = file_new(req, conn, &fsp);
4037         if(!NT_STATUS_IS_OK(status)) {
4038                 return status;
4039         }
4040
4041         /*
4042          * Setup the files_struct for it.
4043          */
4044
4045         fsp->file_id = vfs_file_id_from_sbuf(conn, &smb_dname->st);
4046         fsp->vuid = req ? req->vuid : UID_FIELD_INVALID;
4047         fsp->file_pid = req ? req->smbpid : 0;
4048         fsp->can_lock = False;
4049         fsp->can_read = False;
4050         fsp->can_write = False;
4051
4052         fsp->fh->private_options = 0;
4053         /*
4054          * According to Samba4, SEC_FILE_READ_ATTRIBUTE is always granted,
4055          */
4056         fsp->access_mask = access_mask | FILE_READ_ATTRIBUTES;
4057         fsp->print_file = NULL;
4058         fsp->modified = False;
4059         fsp->oplock_type = NO_OPLOCK;
4060         fsp->sent_oplock_break = NO_BREAK_SENT;
4061         fsp->is_directory = True;
4062         if (file_attributes & FILE_FLAG_POSIX_SEMANTICS) {
4063                 fsp->posix_flags |= FSP_POSIX_FLAGS_ALL;
4064         }
4065         status = fsp_set_smb_fname(fsp, smb_dname);
4066         if (!NT_STATUS_IS_OK(status)) {
4067                 file_free(req, fsp);
4068                 return status;
4069         }
4070
4071         /* Don't store old timestamps for directory
4072            handles in the internal database. We don't
4073            update them in there if new objects
4074            are creaded in the directory. Currently
4075            we only update timestamps on file writes.
4076            See bug #9870.
4077         */
4078         ZERO_STRUCT(mtimespec);
4079
4080 #ifdef O_DIRECTORY
4081         status = fd_open(conn, fsp, O_RDONLY|O_DIRECTORY, 0);
4082 #else
4083         /* POSIX allows us to open a directory with O_RDONLY. */
4084         status = fd_open(conn, fsp, O_RDONLY, 0);
4085 #endif
4086         if (!NT_STATUS_IS_OK(status)) {
4087                 DBG_INFO("Could not open fd for "
4088                         "%s (%s)\n",
4089                         smb_fname_str_dbg(smb_dname),
4090                         nt_errstr(status));
4091                 file_free(req, fsp);
4092                 return status;
4093         }
4094
4095         status = vfs_stat_fsp(fsp);
4096         if (!NT_STATUS_IS_OK(status)) {
4097                 fd_close(fsp);
4098                 file_free(req, fsp);
4099                 return status;
4100         }
4101
4102         if(!S_ISDIR(fsp->fsp_name->st.st_ex_mode)) {
4103                 DEBUG(5,("open_directory: %s is not a directory !\n",
4104                          smb_fname_str_dbg(smb_dname)));
4105                 fd_close(fsp);
4106                 file_free(req, fsp);
4107                 return NT_STATUS_NOT_A_DIRECTORY;
4108         }
4109
4110         /* Ensure there was no race condition.  We need to check
4111          * dev/inode but not permissions, as these can change
4112          * legitimately */
4113         if (!check_same_dev_ino(&smb_dname->st, &fsp->fsp_name->st)) {
4114                 DEBUG(5,("open_directory: stat struct differs for "
4115                         "directory %s.\n",
4116                         smb_fname_str_dbg(smb_dname)));
4117                 fd_close(fsp);
4118                 file_free(req, fsp);
4119                 return NT_STATUS_ACCESS_DENIED;
4120         }
4121
4122         lck = get_share_mode_lock(talloc_tos(), fsp->file_id,
4123                                   conn->connectpath, smb_dname,
4124                                   &mtimespec);
4125
4126         if (lck == NULL) {
4127                 DEBUG(0, ("open_directory: Could not get share mode lock for "
4128                           "%s\n", smb_fname_str_dbg(smb_dname)));
4129                 fd_close(fsp);
4130                 file_free(req, fsp);
4131                 return NT_STATUS_SHARING_VIOLATION;
4132         }
4133
4134         if (has_delete_on_close(lck, fsp->name_hash)) {
4135                 TALLOC_FREE(lck);
4136                 fd_close(fsp);
4137                 file_free(req, fsp);
4138                 return NT_STATUS_DELETE_PENDING;
4139         }
4140
4141         status = open_mode_check(conn, lck,
4142                                  access_mask, share_access);
4143
4144         if (!NT_STATUS_IS_OK(status)) {
4145                 TALLOC_FREE(lck);
4146                 fd_close(fsp);
4147                 file_free(req, fsp);
4148                 return status;
4149         }
4150
4151         ok = set_share_mode(
4152                 lck,
4153                 fsp,
4154                 get_current_uid(conn),
4155                 req ? req->mid : 0,
4156                 NO_OPLOCK,
4157                 share_access,
4158                 fsp->access_mask);
4159         if (!ok) {
4160                 TALLOC_FREE(lck);
4161                 fd_close(fsp);
4162                 file_free(req, fsp);
4163                 return NT_STATUS_NO_MEMORY;
4164         }
4165
4166         /* For directories the delete on close bit at open time seems
4167            always to be honored on close... See test 19 in Samba4 BASE-DELETE. */
4168         if (create_options & FILE_DELETE_ON_CLOSE) {
4169                 status = can_set_delete_on_close(fsp, 0);
4170                 if (!NT_STATUS_IS_OK(status) && !NT_STATUS_EQUAL(status, NT_STATUS_DIRECTORY_NOT_EMPTY)) {
4171                         del_share_mode(lck, fsp);
4172                         TALLOC_FREE(lck);
4173                         fd_close(fsp);
4174                         file_free(req, fsp);
4175                         return status;
4176                 }
4177
4178                 if (NT_STATUS_IS_OK(status)) {
4179                         /* Note that here we set the *initial* delete on close flag,
4180                            not the regular one. The magic gets handled in close. */
4181                         fsp->initial_delete_on_close = True;
4182                 }
4183         }
4184
4185         {
4186                 /*
4187                  * Deal with other opens having a modified write time. Is this
4188                  * possible for directories?
4189                  */
4190                 struct timespec write_time = get_share_mode_write_time(lck);
4191
4192                 if (!null_timespec(write_time)) {
4193                         update_stat_ex_mtime(&fsp->fsp_name->st, write_time);
4194                 }
4195         }
4196
4197         TALLOC_FREE(lck);
4198
4199         if (pinfo) {
4200                 *pinfo = info;
4201         }
4202
4203         *result = fsp;
4204         return NT_STATUS_OK;
4205 }
4206
4207 NTSTATUS create_directory(connection_struct *conn, struct smb_request *req,
4208                           struct smb_filename *smb_dname)
4209 {
4210         NTSTATUS status;
4211         files_struct *fsp;
4212
4213         status = SMB_VFS_CREATE_FILE(
4214                 conn,                                   /* conn */
4215                 req,                                    /* req */
4216                 0,                                      /* root_dir_fid */
4217                 smb_dname,                              /* fname */
4218                 FILE_READ_ATTRIBUTES,                   /* access_mask */
4219                 FILE_SHARE_NONE,                        /* share_access */
4220                 FILE_CREATE,                            /* create_disposition*/
4221                 FILE_DIRECTORY_FILE,                    /* create_options */
4222                 FILE_ATTRIBUTE_DIRECTORY,               /* file_attributes */
4223                 0,                                      /* oplock_request */
4224                 NULL,                                   /* lease */
4225                 0,                                      /* allocation_size */
4226                 0,                                      /* private_flags */
4227                 NULL,                                   /* sd */
4228                 NULL,                                   /* ea_list */
4229                 &fsp,                                   /* result */
4230                 NULL,                                   /* pinfo */
4231                 NULL, NULL);                            /* create context */
4232
4233         if (NT_STATUS_IS_OK(status)) {
4234                 close_file(req, fsp, NORMAL_CLOSE);
4235         }
4236
4237         return status;
4238 }
4239
4240 /****************************************************************************
4241  Receive notification that one of our open files has been renamed by another
4242  smbd process.
4243 ****************************************************************************/
4244
4245 void msg_file_was_renamed(struct messaging_context *msg_ctx,
4246                           void *private_data,
4247                           uint32_t msg_type,
4248                           struct server_id src,
4249                           DATA_BLOB *data)
4250 {
4251         struct file_rename_message *msg = NULL;
4252         enum ndr_err_code ndr_err;
4253         files_struct *fsp;
4254         struct smb_filename *smb_fname = NULL;
4255         struct smbd_server_connection *sconn =
4256                 talloc_get_type_abort(private_data,
4257                 struct smbd_server_connection);
4258
4259         msg = talloc(talloc_tos(), struct file_rename_message);
4260         if (msg == NULL) {
4261                 DBG_WARNING("talloc failed\n");
4262                 return;
4263         }
4264
4265         ndr_err = ndr_pull_struct_blob_all(
4266                 data,
4267                 msg,
4268                 msg,
4269                 (ndr_pull_flags_fn_t)ndr_pull_file_rename_message);
4270         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
4271                 DBG_DEBUG("ndr_pull_oplock_break_message failed: %s\n",
4272                           ndr_errstr(ndr_err));
4273                 goto out;
4274         }
4275         if (DEBUGLEVEL >= 10) {
4276                 struct server_id_buf buf;
4277                 DBG_DEBUG("Got rename message from %s\n",
4278                           server_id_str_buf(src, &buf));
4279                 NDR_PRINT_DEBUG(file_rename_message, msg);
4280         }
4281
4282         /* stream_name must always be NULL if there is no stream. */
4283         if ((msg->stream_name != NULL) && (msg->stream_name[0] == '\0')) {
4284                 msg->stream_name = NULL;
4285         }
4286
4287         smb_fname = synthetic_smb_fname(
4288                 msg, msg->base_name, msg->stream_name, NULL, 0);
4289         if (smb_fname == NULL) {
4290                 DBG_DEBUG("synthetic_smb_fname failed\n");
4291                 goto out;
4292         }
4293
4294         fsp = file_find_dif(sconn, msg->id, msg->share_file_id);
4295         if (fsp == NULL) {
4296                 DBG_DEBUG("fsp not found\n");
4297                 goto out;
4298         }
4299
4300         if (strcmp(fsp->conn->connectpath, msg->servicepath) == 0) {
4301                 NTSTATUS status;
4302                 DBG_DEBUG("renaming file %s from %s -> %s\n",
4303                           fsp_fnum_dbg(fsp),
4304                           fsp_str_dbg(fsp),
4305                           smb_fname_str_dbg(smb_fname));
4306                 status = fsp_set_smb_fname(fsp, smb_fname);
4307                 if (!NT_STATUS_IS_OK(status)) {
4308                         DBG_DEBUG("fsp_set_smb_fname failed: %s\n",
4309                                   nt_errstr(status));
4310                 }
4311         } else {
4312                 /* TODO. JRA. */
4313                 /*
4314                  * Now we have the complete path we can work out if
4315                  * this is actually within this share and adjust
4316                  * newname accordingly.
4317                  */
4318                 DBG_DEBUG("share mismatch (sharepath %s not sharepath %s) "
4319                           "%s from %s -> %s\n",
4320                           fsp->conn->connectpath,
4321                           msg->servicepath,
4322                           fsp_fnum_dbg(fsp),
4323                           fsp_str_dbg(fsp),
4324                           smb_fname_str_dbg(smb_fname));
4325         }
4326  out:
4327         TALLOC_FREE(msg);
4328 }
4329
4330 /*
4331  * If a main file is opened for delete, all streams need to be checked for
4332  * !FILE_SHARE_DELETE. Do this by opening with DELETE_ACCESS.
4333  * If that works, delete them all by setting the delete on close and close.
4334  */
4335
4336 static NTSTATUS open_streams_for_delete(connection_struct *conn,
4337                                         const struct smb_filename *smb_fname)
4338 {
4339         struct stream_struct *stream_info = NULL;
4340         files_struct **streams = NULL;
4341         int j;
4342         unsigned int i, num_streams = 0;
4343         TALLOC_CTX *frame = talloc_stackframe();
4344         NTSTATUS status;
4345
4346         status = vfs_streaminfo(conn, NULL, smb_fname, talloc_tos(),
4347                                 &num_streams, &stream_info);
4348
4349         if (NT_STATUS_EQUAL(status, NT_STATUS_NOT_IMPLEMENTED)
4350             || NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
4351                 DEBUG(10, ("no streams around\n"));
4352                 TALLOC_FREE(frame);
4353                 return NT_STATUS_OK;
4354         }
4355
4356         if (!NT_STATUS_IS_OK(status)) {
4357                 DEBUG(10, ("vfs_streaminfo failed: %s\n",
4358                            nt_errstr(status)));
4359                 goto fail;
4360         }
4361
4362         DEBUG(10, ("open_streams_for_delete found %d streams\n",
4363                    num_streams));
4364
4365         if (num_streams == 0) {
4366                 TALLOC_FREE(frame);
4367                 return NT_STATUS_OK;
4368         }
4369
4370         streams = talloc_array(talloc_tos(), files_struct *, num_streams);
4371         if (streams == NULL) {
4372                 DEBUG(0, ("talloc failed\n"));
4373                 status = NT_STATUS_NO_MEMORY;
4374                 goto fail;
4375         }
4376
4377         for (i=0; i<num_streams; i++) {
4378                 struct smb_filename *smb_fname_cp;
4379
4380                 if (strequal(stream_info[i].name, "::$DATA")) {
4381                         streams[i] = NULL;
4382                         continue;
4383                 }
4384
4385                 smb_fname_cp = synthetic_smb_fname(talloc_tos(),
4386                                         smb_fname->base_name,
4387                                         stream_info[i].name,
4388                                         NULL,
4389                                         (smb_fname->flags &
4390                                                 ~SMB_FILENAME_POSIX_PATH));
4391                 if (smb_fname_cp == NULL) {
4392                         status = NT_STATUS_NO_MEMORY;
4393                         goto fail;
4394                 }
4395
4396                 if (SMB_VFS_STAT(conn, smb_fname_cp) == -1) {
4397                         DEBUG(10, ("Unable to stat stream: %s\n",
4398                                    smb_fname_str_dbg(smb_fname_cp)));
4399                 }
4400
4401                 status = SMB_VFS_CREATE_FILE(
4402                          conn,                  /* conn */
4403                          NULL,                  /* req */
4404                          0,                     /* root_dir_fid */
4405                          smb_fname_cp,          /* fname */
4406                          DELETE_ACCESS,         /* access_mask */
4407                          (FILE_SHARE_READ |     /* share_access */
4408                              FILE_SHARE_WRITE | FILE_SHARE_DELETE),
4409                          FILE_OPEN,             /* create_disposition*/
4410                          0,                     /* create_options */
4411                          FILE_ATTRIBUTE_NORMAL, /* file_attributes */
4412                          0,                     /* oplock_request */
4413                          NULL,                  /* lease */
4414                          0,                     /* allocation_size */
4415                          NTCREATEX_OPTIONS_PRIVATE_STREAM_DELETE, /* private_flags */
4416                          NULL,                  /* sd */
4417                          NULL,                  /* ea_list */
4418                          &streams[i],           /* result */
4419                          NULL,                  /* pinfo */
4420                          NULL, NULL);           /* create context */
4421
4422                 if (!NT_STATUS_IS_OK(status)) {
4423                         DEBUG(10, ("Could not open stream %s: %s\n",
4424                                    smb_fname_str_dbg(smb_fname_cp),
4425                                    nt_errstr(status)));
4426
4427                         TALLOC_FREE(smb_fname_cp);
4428                         break;
4429                 }
4430                 TALLOC_FREE(smb_fname_cp);
4431         }
4432
4433         /*
4434          * don't touch the variable "status" beyond this point :-)
4435          */
4436
4437         for (j = i-1 ; j >= 0; j--) {
4438                 if (streams[j] == NULL) {
4439                         continue;
4440                 }
4441
4442                 DEBUG(10, ("Closing stream # %d, %s\n", j,
4443                            fsp_str_dbg(streams[j])));
4444                 close_file(NULL, streams[j], NORMAL_CLOSE);
4445         }
4446
4447  fail:
4448         TALLOC_FREE(frame);
4449         return status;
4450 }
4451
4452 /*********************************************************************
4453  Create a default ACL by inheriting from the parent. If no inheritance
4454  from the parent available, don't set anything. This will leave the actual
4455  permissions the new file or directory already got from the filesystem
4456  as the NT ACL when read.
4457 *********************************************************************/
4458
4459 static NTSTATUS inherit_new_acl(files_struct *fsp)
4460 {
4461         TALLOC_CTX *frame = talloc_stackframe();
4462         char *parent_name = NULL;
4463         struct security_descriptor *parent_desc = NULL;
4464         NTSTATUS status = NT_STATUS_OK;
4465         struct security_descriptor *psd = NULL;
4466         const struct dom_sid *owner_sid = NULL;
4467         const struct dom_sid *group_sid = NULL;
4468         uint32_t security_info_sent = (SECINFO_OWNER | SECINFO_GROUP | SECINFO_DACL);
4469         struct security_token *token = fsp->conn->session_info->security_token;
4470         bool inherit_owner =
4471             (lp_inherit_owner(SNUM(fsp->conn)) == INHERIT_OWNER_WINDOWS_AND_UNIX);
4472         bool inheritable_components = false;
4473         bool try_builtin_administrators = false;
4474         const struct dom_sid *BA_U_sid = NULL;
4475         const struct dom_sid *BA_G_sid = NULL;
4476         bool try_system = false;
4477         const struct dom_sid *SY_U_sid = NULL;
4478         const struct dom_sid *SY_G_sid = NULL;
4479         size_t size = 0;
4480         struct smb_filename *parent_smb_fname = NULL;
4481
4482         if (!parent_dirname(frame, fsp->fsp_name->base_name, &parent_name, NULL)) {
4483                 TALLOC_FREE(frame);
4484                 return NT_STATUS_NO_MEMORY;
4485         }
4486         parent_smb_fname = synthetic_smb_fname(talloc_tos(),
4487                                                 parent_name,
4488                                                 NULL,
4489                                                 NULL,
4490                                                 fsp->fsp_name->flags);
4491
4492         if (parent_smb_fname == NULL) {
4493                 TALLOC_FREE(frame);
4494                 return NT_STATUS_NO_MEMORY;
4495         }
4496
4497         status = SMB_VFS_GET_NT_ACL(fsp->conn,
4498                                     parent_smb_fname,
4499                                     (SECINFO_OWNER | SECINFO_GROUP | SECINFO_DACL),
4500                                     frame,
4501                                     &parent_desc);
4502         if (!NT_STATUS_IS_OK(status)) {
4503                 TALLOC_FREE(frame);
4504                 return status;
4505         }
4506
4507         inheritable_components = sd_has_inheritable_components(parent_desc,
4508                                         fsp->is_directory);
4509
4510         if (!inheritable_components && !inherit_owner) {
4511                 TALLOC_FREE(frame);
4512                 /* Nothing to inherit and not setting owner. */
4513                 return NT_STATUS_OK;
4514         }
4515
4516         /* Create an inherited descriptor from the parent. */
4517
4518         if (DEBUGLEVEL >= 10) {
4519                 DEBUG(10,("inherit_new_acl: parent acl for %s is:\n",
4520                         fsp_str_dbg(fsp) ));
4521                 NDR_PRINT_DEBUG(security_descriptor, parent_desc);
4522         }
4523
4524         /* Inherit from parent descriptor if "inherit owner" set. */
4525         if (inherit_owner) {
4526                 owner_sid = parent_desc->owner_sid;
4527                 group_sid = parent_desc->group_sid;
4528         }
4529
4530         if (owner_sid == NULL) {
4531                 if (security_token_has_builtin_administrators(token)) {
4532                         try_builtin_administrators = true;
4533                 } else if (security_token_is_system(token)) {
4534                         try_builtin_administrators = true;
4535                         try_system = true;
4536                 }
4537         }
4538
4539         if (group_sid == NULL &&
4540             token->num_sids == PRIMARY_GROUP_SID_INDEX)
4541         {
4542                 if (security_token_is_system(token)) {
4543                         try_builtin_administrators = true;
4544                         try_system = true;
4545                 }
4546         }
4547
4548         if (try_builtin_administrators) {
4549                 struct unixid ids;
4550                 bool ok;
4551
4552                 ZERO_STRUCT(ids);
4553                 ok = sids_to_unixids(&global_sid_Builtin_Administrators, 1, &ids);
4554                 if (ok) {
4555                         switch (ids.type) {
4556                         case ID_TYPE_BOTH:
4557                                 BA_U_sid = &global_sid_Builtin_Administrators;
4558                                 BA_G_sid = &global_sid_Builtin_Administrators;
4559                                 break;
4560                         case ID_TYPE_UID:
4561                                 BA_U_sid = &global_sid_Builtin_Administrators;
4562                                 break;
4563                         case ID_TYPE_GID:
4564                                 BA_G_sid = &global_sid_Builtin_Administrators;
4565                                 break;
4566                         default:
4567                                 break;
4568                         }
4569                 }
4570         }
4571
4572         if (try_system) {
4573                 struct unixid ids;
4574                 bool ok;
4575
4576                 ZERO_STRUCT(ids);
4577                 ok = sids_to_unixids(&global_sid_System, 1, &ids);
4578                 if (ok) {
4579                         switch (ids.type) {
4580                         case ID_TYPE_BOTH:
4581                                 SY_U_sid = &global_sid_System;
4582                                 SY_G_sid = &global_sid_System;
4583                                 break;
4584                         case ID_TYPE_UID:
4585                                 SY_U_sid = &global_sid_System;
4586                                 break;
4587                         case ID_TYPE_GID:
4588                                 SY_G_sid = &global_sid_System;
4589                                 break;
4590                         default:
4591                                 break;
4592                         }
4593                 }
4594         }
4595
4596         if (owner_sid == NULL) {
4597                 owner_sid = BA_U_sid;
4598         }
4599
4600         if (owner_sid == NULL) {
4601                 owner_sid = SY_U_sid;
4602         }
4603
4604         if (group_sid == NULL) {
4605                 group_sid = SY_G_sid;
4606         }
4607
4608         if (try_system && group_sid == NULL) {
4609                 group_sid = BA_G_sid;
4610         }
4611
4612         if (owner_sid == NULL) {
4613                 owner_sid = &token->sids[PRIMARY_USER_SID_INDEX];
4614         }
4615         if (group_sid == NULL) {
4616                 if (token->num_sids == PRIMARY_GROUP_SID_INDEX) {
4617                         group_sid = &token->sids[PRIMARY_USER_SID_INDEX];
4618                 } else {
4619                         group_sid = &token->sids[PRIMARY_GROUP_SID_INDEX];
4620                 }
4621         }
4622
4623         status = se_create_child_secdesc(frame,
4624                         &psd,
4625                         &size,
4626                         parent_desc,
4627                         owner_sid,
4628                         group_sid,
4629                         fsp->is_directory);
4630         if (!NT_STATUS_IS_OK(status)) {
4631                 TALLOC_FREE(frame);
4632                 return status;
4633         }
4634
4635         /* If inheritable_components == false,
4636            se_create_child_secdesc()
4637            creates a security descriptor with a NULL dacl
4638            entry, but with SEC_DESC_DACL_PRESENT. We need
4639            to remove that flag. */
4640
4641         if (!inheritable_components) {
4642                 security_info_sent &= ~SECINFO_DACL;
4643                 psd->type &= ~SEC_DESC_DACL_PRESENT;
4644         }
4645
4646         if (DEBUGLEVEL >= 10) {
4647                 DEBUG(10,("inherit_new_acl: child acl for %s is:\n",
4648                         fsp_str_dbg(fsp) ));
4649                 NDR_PRINT_DEBUG(security_descriptor, psd);
4650         }
4651
4652         if (inherit_owner) {
4653                 /* We need to be root to force this. */
4654                 become_root();
4655         }
4656         status = SMB_VFS_FSET_NT_ACL(fsp,
4657                         security_info_sent,
4658                         psd);
4659         if (inherit_owner) {
4660                 unbecome_root();
4661         }
4662         TALLOC_FREE(frame);
4663         return status;
4664 }
4665
4666 /*
4667  * If we already have a lease, it must match the new file id. [MS-SMB2]
4668  * 3.3.5.9.8 speaks about INVALID_PARAMETER if an already used lease key is
4669  * used for a different file name.
4670  */
4671
4672 struct lease_match_state {
4673         /* Input parameters. */
4674         TALLOC_CTX *mem_ctx;
4675         const char *servicepath;
4676         const struct smb_filename *fname;
4677         bool file_existed;
4678         struct file_id id;
4679         /* Return parameters. */
4680         uint32_t num_file_ids;
4681         struct file_id *ids;
4682         NTSTATUS match_status;
4683 };
4684
4685 /*************************************************************
4686  File doesn't exist but this lease key+guid is already in use.
4687
4688  This is only allowable in the dynamic share case where the
4689  service path must be different.
4690
4691  There is a small race condition here in the multi-connection
4692  case where a client sends two create calls on different connections,
4693  where the file doesn't exist and one smbd creates the leases_db
4694  entry first, but this will get fixed by the multichannel cleanup
4695  when all identical client_guids get handled by a single smbd.
4696 **************************************************************/
4697
4698 static void lease_match_parser_new_file(
4699         uint32_t num_files,
4700         const struct leases_db_file *files,
4701         struct lease_match_state *state)
4702 {
4703         uint32_t i;
4704
4705         for (i = 0; i < num_files; i++) {
4706                 const struct leases_db_file *f = &files[i];
4707                 if (strequal(state->servicepath, f->servicepath)) {
4708                         state->match_status = NT_STATUS_INVALID_PARAMETER;
4709                         return;
4710                 }
4711         }
4712
4713         /* Dynamic share case. Break leases on all other files. */
4714         state->match_status = leases_db_copy_file_ids(state->mem_ctx,
4715                                         num_files,
4716                                         files,
4717                                         &state->ids);
4718         if (!NT_STATUS_IS_OK(state->match_status)) {
4719                 return;
4720         }
4721
4722         state->num_file_ids = num_files;
4723         state->match_status = NT_STATUS_OPLOCK_NOT_GRANTED;
4724         return;
4725 }
4726
4727 static void lease_match_parser(
4728         uint32_t num_files,
4729         const struct leases_db_file *files,
4730         void *private_data)
4731 {
4732         struct lease_match_state *state =
4733                 (struct lease_match_state *)private_data;
4734         uint32_t i;
4735
4736         if (!state->file_existed) {
4737                 /*
4738                  * Deal with name mismatch or
4739                  * possible dynamic share case separately
4740                  * to make code clearer.
4741                  */
4742                 lease_match_parser_new_file(num_files,
4743                                                 files,
4744                                                 state);
4745                 return;
4746         }
4747
4748         /* File existed. */
4749         state->match_status = NT_STATUS_OK;
4750
4751         for (i = 0; i < num_files; i++) {
4752                 const struct leases_db_file *f = &files[i];
4753
4754                 /* Everything should be the same. */
4755                 if (!file_id_equal(&state->id, &f->id)) {
4756                         /* This should catch all dynamic share cases. */
4757                         state->match_status = NT_STATUS_OPLOCK_NOT_GRANTED;
4758                         break;
4759                 }
4760                 if (!strequal(f->servicepath, state->servicepath)) {
4761                         state->match_status = NT_STATUS_INVALID_PARAMETER;
4762                         break;
4763                 }
4764                 if (!strequal(f->base_name, state->fname->base_name)) {
4765                         state->match_status = NT_STATUS_INVALID_PARAMETER;
4766                         break;
4767                 }
4768                 if (!strequal(f->stream_name, state->fname->stream_name)) {
4769                         state->match_status = NT_STATUS_INVALID_PARAMETER;
4770                         break;
4771                 }
4772         }
4773
4774         if (NT_STATUS_IS_OK(state->match_status)) {
4775                 /*
4776                  * Common case - just opening another handle on a
4777                  * file on a non-dynamic share.
4778                  */
4779                 return;
4780         }
4781
4782         if (NT_STATUS_EQUAL(state->match_status, NT_STATUS_INVALID_PARAMETER)) {
4783                 /* Mismatched path. Error back to client. */
4784                 return;
4785         }
4786
4787         /*
4788          * File id mismatch. Dynamic share case NT_STATUS_OPLOCK_NOT_GRANTED.
4789          * Don't allow leases.
4790          */
4791
4792         state->match_status = leases_db_copy_file_ids(state->mem_ctx,
4793                                         num_files,
4794                                         files,
4795                                         &state->ids);
4796         if (!NT_STATUS_IS_OK(state->match_status)) {
4797                 return;
4798         }
4799
4800         state->num_file_ids = num_files;
4801         state->match_status = NT_STATUS_OPLOCK_NOT_GRANTED;
4802         return;
4803 }
4804
4805 static NTSTATUS lease_match(connection_struct *conn,
4806                             struct smb_request *req,
4807                             const struct smb2_lease_key *lease_key,
4808                             const char *servicepath,
4809                             const struct smb_filename *fname,
4810                             uint16_t *p_version,
4811                             uint16_t *p_epoch)
4812 {
4813         struct smbd_server_connection *sconn = req->sconn;
4814         TALLOC_CTX *tos = talloc_tos();
4815         struct lease_match_state state = {
4816                 .mem_ctx = tos,
4817                 .servicepath = servicepath,
4818                 .fname = fname,
4819                 .match_status = NT_STATUS_OK
4820         };
4821         uint32_t i;
4822         NTSTATUS status;
4823
4824         state.file_existed = VALID_STAT(fname->st);
4825         if (state.file_existed) {
4826                 state.id = vfs_file_id_from_sbuf(conn, &fname->st);
4827         }
4828
4829         status = leases_db_parse(&sconn->client->connections->smb2.client.guid,
4830                                  lease_key, lease_match_parser, &state);
4831         if (!NT_STATUS_IS_OK(status)) {
4832                 /*
4833                  * Not found or error means okay: We can make the lease pass
4834                  */
4835                 return NT_STATUS_OK;
4836         }
4837         if (!NT_STATUS_EQUAL(state.match_status, NT_STATUS_OPLOCK_NOT_GRANTED)) {
4838                 /*
4839                  * Anything but NT_STATUS_OPLOCK_NOT_GRANTED, let the caller
4840                  * deal with it.
4841                  */
4842                 return state.match_status;
4843         }
4844
4845         /* We have to break all existing leases. */
4846         for (i = 0; i < state.num_file_ids; i++) {
4847                 struct share_mode_lock *lck;
4848                 struct share_mode_data *d;
4849                 struct share_mode_entry *lease_entry = NULL;
4850                 uint32_t j;
4851
4852                 if (file_id_equal(&state.ids[i], &state.id)) {
4853                         /* Don't need to break our own file. */
4854                         continue;
4855                 }
4856
4857                 lck = get_existing_share_mode_lock(talloc_tos(), state.ids[i]);
4858                 if (lck == NULL) {
4859                         /* Race condition - file already closed. */
4860                         continue;
4861                 }
4862                 d = lck->data;
4863                 for (j=0; j<d->num_share_modes; j++) {
4864                         struct share_mode_entry *e = &d->share_modes[j];
4865                         uint32_t e_lease_type = get_lease_type(d, e);
4866
4867                         if (share_mode_stale_pid(d, j)) {
4868                                 continue;
4869                         }
4870
4871                         if (e->op_type == LEASE_OPLOCK) {
4872                                 if (!smb2_lease_key_equal(&e->lease_key,
4873                                                           lease_key)) {
4874                                         continue;
4875                                 }
4876                                 lease_entry = e;
4877                         }
4878
4879                         if (e_lease_type == SMB2_LEASE_NONE) {
4880                                 continue;
4881                         }
4882
4883                         send_break_message(conn->sconn->msg_ctx, &d->id, e,
4884                                            SMB2_LEASE_NONE);
4885
4886                         /*
4887                          * Windows 7 and 8 lease clients
4888                          * are broken in that they will not
4889                          * respond to lease break requests
4890                          * whilst waiting for an outstanding
4891                          * open request on that lease handle
4892                          * on the same TCP connection, due
4893                          * to holding an internal inode lock.
4894                          *
4895                          * This means we can't reschedule
4896                          * ourselves here, but must return
4897                          * from the create.
4898                          *
4899                          * Work around:
4900                          *
4901                          * Send the breaks and then return
4902                          * SMB2_LEASE_NONE in the lease handle
4903                          * to cause them to acknowledge the
4904                          * lease break. Consultation with
4905                          * Microsoft engineering confirmed
4906                          * this approach is safe.
4907                          */
4908
4909                 }
4910
4911                 if (lease_entry != NULL) {
4912                         status = leases_db_get(
4913                                 &lease_entry->client_guid,
4914                                 &lease_entry->lease_key,
4915                                 &d->id,
4916                                 NULL, /* current_state */
4917                                 NULL, /* breaking */
4918                                 NULL, /* breaking_to_requested */
4919                                 NULL, /* breaking_to_required */
4920                                 p_version, /* lease_version */
4921                                 p_epoch); /* epoch */
4922                         if (!NT_STATUS_IS_OK(status)) {
4923                                 DBG_WARNING("Could not find version/epoch: "
4924                                             "%s\n",
4925                                             nt_errstr(status));
4926                         }
4927                 }
4928
4929                 TALLOC_FREE(lck);
4930         }
4931         /*
4932          * Ensure we don't grant anything more so we
4933          * never upgrade.
4934          */
4935         return NT_STATUS_OPLOCK_NOT_GRANTED;
4936 }
4937
4938 /*
4939  * Wrapper around open_file_ntcreate and open_directory
4940  */
4941
4942 static NTSTATUS create_file_unixpath(connection_struct *conn,
4943                                      struct smb_request *req,
4944                                      struct smb_filename *smb_fname,
4945                                      uint32_t access_mask,
4946                                      uint32_t share_access,
4947                                      uint32_t create_disposition,
4948                                      uint32_t create_options,
4949                                      uint32_t file_attributes,
4950                                      uint32_t oplock_request,
4951                                      const struct smb2_lease *lease,
4952                                      uint64_t allocation_size,
4953                                      uint32_t private_flags,
4954                                      struct security_descriptor *sd,
4955                                      struct ea_list *ea_list,
4956
4957                                      files_struct **result,
4958                                      int *pinfo)
4959 {
4960         struct smb2_lease none_lease;
4961         int info = FILE_WAS_OPENED;
4962         files_struct *base_fsp = NULL;
4963         files_struct *fsp = NULL;
4964         NTSTATUS status;
4965
4966         DBG_DEBUG("create_file_unixpath: access_mask = 0x%x "
4967                   "file_attributes = 0x%x, share_access = 0x%x, "
4968                   "create_disposition = 0x%x create_options = 0x%x "
4969                   "oplock_request = 0x%x private_flags = 0x%x "
4970                   "ea_list = %p, sd = %p, "
4971                   "fname = %s\n",
4972                   (unsigned int)access_mask,
4973                   (unsigned int)file_attributes,
4974                   (unsigned int)share_access,
4975                   (unsigned int)create_disposition,
4976                   (unsigned int)create_options,
4977                   (unsigned int)oplock_request,
4978                   (unsigned int)private_flags,
4979                   ea_list, sd, smb_fname_str_dbg(smb_fname));
4980
4981         if (create_options & FILE_OPEN_BY_FILE_ID) {
4982                 status = NT_STATUS_NOT_SUPPORTED;
4983                 goto fail;
4984         }
4985
4986         if (create_options & NTCREATEX_OPTIONS_INVALID_PARAM_MASK) {
4987                 status = NT_STATUS_INVALID_PARAMETER;
4988                 goto fail;
4989         }
4990
4991         if (req == NULL) {
4992                 oplock_request |= INTERNAL_OPEN_ONLY;
4993         }
4994
4995         if (lease != NULL) {
4996                 uint16_t epoch = lease->lease_epoch;
4997                 uint16_t version = lease->lease_version;
4998
4999                 if (req == NULL) {
5000                         DBG_WARNING("Got lease on internal open\n");
5001                         status = NT_STATUS_INTERNAL_ERROR;
5002                         goto fail;
5003                 }
5004
5005                 status = lease_match(conn,
5006                                 req,
5007                                 &lease->lease_key,
5008                                 conn->connectpath,
5009                                 smb_fname,
5010                                 &version,
5011                                 &epoch);
5012                 if (NT_STATUS_EQUAL(status, NT_STATUS_OPLOCK_NOT_GRANTED)) {
5013                         /* Dynamic share file. No leases and update epoch... */
5014                         none_lease = *lease;
5015                         none_lease.lease_state = SMB2_LEASE_NONE;
5016                         none_lease.lease_epoch = epoch;
5017                         none_lease.lease_version = version;
5018                         lease = &none_lease;
5019                 } else if (!NT_STATUS_IS_OK(status)) {
5020                         goto fail;
5021                 }
5022         }
5023
5024         if ((conn->fs_capabilities & FILE_NAMED_STREAMS)
5025             && (access_mask & DELETE_ACCESS)
5026             && !is_ntfs_stream_smb_fname(smb_fname)) {
5027                 /*
5028                  * We can't open a file with DELETE access if any of the
5029                  * streams is open without FILE_SHARE_DELETE
5030                  */
5031                 status = open_streams_for_delete(conn, smb_fname);
5032
5033                 if (!NT_STATUS_IS_OK(status)) {
5034                         goto fail;
5035                 }
5036         }
5037
5038         if ((access_mask & SEC_FLAG_SYSTEM_SECURITY) &&
5039                         !security_token_has_privilege(get_current_nttok(conn),
5040                                         SEC_PRIV_SECURITY)) {
5041                 DEBUG(10, ("create_file_unixpath: open on %s "
5042                         "failed - SEC_FLAG_SYSTEM_SECURITY denied.\n",
5043                         smb_fname_str_dbg(smb_fname)));
5044                 status = NT_STATUS_PRIVILEGE_NOT_HELD;
5045                 goto fail;
5046         }
5047
5048         /*
5049          * Files or directories can't be opened DELETE_ON_CLOSE without
5050          * delete access.
5051          * BUG: https://bugzilla.samba.org/show_bug.cgi?id=13358
5052          */
5053         if (create_options & FILE_DELETE_ON_CLOSE) {
5054                 if ((access_mask & DELETE_ACCESS) == 0) {
5055                         status = NT_STATUS_INVALID_PARAMETER;
5056                         goto fail;
5057                 }
5058         }
5059
5060         if ((conn->fs_capabilities & FILE_NAMED_STREAMS)
5061             && is_ntfs_stream_smb_fname(smb_fname)
5062             && (!(private_flags & NTCREATEX_OPTIONS_PRIVATE_STREAM_DELETE))) {
5063                 uint32_t base_create_disposition;
5064                 struct smb_filename *smb_fname_base = NULL;
5065                 uint32_t base_privflags;
5066
5067                 if (create_options & FILE_DIRECTORY_FILE) {
5068                         status = NT_STATUS_NOT_A_DIRECTORY;
5069                         goto fail;
5070                 }
5071
5072                 switch (create_disposition) {
5073                 case FILE_OPEN:
5074                         base_create_disposition = FILE_OPEN;
5075                         break;
5076                 default:
5077                         base_create_disposition = FILE_OPEN_IF;
5078                         break;
5079                 }
5080
5081                 /* Create an smb_filename with stream_name == NULL. */
5082                 smb_fname_base = synthetic_smb_fname(talloc_tos(),
5083                                                 smb_fname->base_name,
5084                                                 NULL,
5085                                                 NULL,
5086                                                 smb_fname->flags);
5087                 if (smb_fname_base == NULL) {
5088                         status = NT_STATUS_NO_MEMORY;
5089                         goto fail;
5090                 }
5091
5092                 if (SMB_VFS_STAT(conn, smb_fname_base) == -1) {
5093                         DEBUG(10, ("Unable to stat stream: %s\n",
5094                                    smb_fname_str_dbg(smb_fname_base)));
5095                 } else {
5096                         /*
5097                          * https://bugzilla.samba.org/show_bug.cgi?id=10229
5098                          * We need to check if the requested access mask
5099                          * could be used to open the underlying file (if
5100                          * it existed), as we're passing in zero for the
5101                          * access mask to the base filename.
5102                          */
5103                         status = check_base_file_access(conn,
5104                                                         smb_fname_base,
5105                                                         access_mask);
5106
5107                         if (!NT_STATUS_IS_OK(status)) {
5108                                 DEBUG(10, ("Permission check "
5109                                         "for base %s failed: "
5110                                         "%s\n", smb_fname->base_name,
5111                                         nt_errstr(status)));
5112                                 goto fail;
5113                         }
5114                 }
5115
5116                 base_privflags = NTCREATEX_OPTIONS_PRIVATE_STREAM_BASEOPEN;
5117
5118                 /* Open the base file. */
5119                 status = create_file_unixpath(conn, NULL, smb_fname_base, 0,
5120                                               FILE_SHARE_READ
5121                                               | FILE_SHARE_WRITE
5122                                               | FILE_SHARE_DELETE,
5123                                               base_create_disposition,
5124                                               0, 0, 0, NULL, 0,
5125                                               base_privflags,
5126                                               NULL, NULL,
5127                                               &base_fsp, NULL);
5128                 TALLOC_FREE(smb_fname_base);
5129
5130                 if (!NT_STATUS_IS_OK(status)) {
5131                         DEBUG(10, ("create_file_unixpath for base %s failed: "
5132                                    "%s\n", smb_fname->base_name,
5133                                    nt_errstr(status)));
5134                         goto fail;
5135                 }
5136                 /* we don't need the low level fd */
5137                 fd_close(base_fsp);
5138         }
5139
5140         /*
5141          * If it's a request for a directory open, deal with it separately.
5142          */
5143
5144         if (create_options & FILE_DIRECTORY_FILE) {
5145
5146                 if (create_options & FILE_NON_DIRECTORY_FILE) {
5147                         status = NT_STATUS_INVALID_PARAMETER;
5148                         goto fail;
5149                 }
5150
5151                 /* Can't open a temp directory. IFS kit test. */
5152                 if (!(file_attributes & FILE_FLAG_POSIX_SEMANTICS) &&
5153                      (file_attributes & FILE_ATTRIBUTE_TEMPORARY)) {
5154                         status = NT_STATUS_INVALID_PARAMETER;
5155                         goto fail;
5156                 }
5157
5158                 /*
5159                  * We will get a create directory here if the Win32
5160                  * app specified a security descriptor in the
5161                  * CreateDirectory() call.
5162                  */
5163
5164                 oplock_request = 0;
5165                 status = open_directory(
5166                         conn, req, smb_fname, access_mask, share_access,
5167                         create_disposition, create_options, file_attributes,
5168                         &info, &fsp);
5169         } else {
5170
5171                 /*
5172                  * Ordinary file case.
5173                  */
5174
5175                 status = file_new(req, conn, &fsp);
5176                 if(!NT_STATUS_IS_OK(status)) {
5177                         goto fail;
5178                 }
5179
5180                 status = fsp_set_smb_fname(fsp, smb_fname);
5181                 if (!NT_STATUS_IS_OK(status)) {
5182                         goto fail;
5183                 }
5184
5185                 if (base_fsp) {
5186                         /*
5187                          * We're opening the stream element of a
5188                          * base_fsp we already opened. Set up the
5189                          * base_fsp pointer.
5190                          */
5191                         fsp->base_fsp = base_fsp;
5192                 }
5193
5194                 if (allocation_size) {
5195                         fsp->initial_allocation_size = smb_roundup(fsp->conn,
5196                                                         allocation_size);
5197                 }
5198
5199                 status = open_file_ntcreate(conn,
5200                                             req,
5201                                             access_mask,
5202                                             share_access,
5203                                             create_disposition,
5204                                             create_options,
5205                                             file_attributes,
5206                                             oplock_request,
5207                                             lease,
5208                                             private_flags,
5209                                             &info,
5210                                             fsp);
5211
5212                 if(!NT_STATUS_IS_OK(status)) {
5213                         file_free(req, fsp);
5214                         fsp = NULL;
5215                 }
5216
5217                 if (NT_STATUS_EQUAL(status, NT_STATUS_FILE_IS_A_DIRECTORY)) {
5218
5219                         /* A stream open never opens a directory */
5220
5221                         if (base_fsp) {
5222                                 status = NT_STATUS_FILE_IS_A_DIRECTORY;
5223                                 goto fail;
5224                         }
5225
5226                         /*
5227                          * Fail the open if it was explicitly a non-directory
5228                          * file.
5229                          */
5230
5231                         if (create_options & FILE_NON_DIRECTORY_FILE) {
5232                                 status = NT_STATUS_FILE_IS_A_DIRECTORY;
5233                                 goto fail;
5234                         }
5235
5236                         oplock_request = 0;
5237                         status = open_directory(
5238                                 conn, req, smb_fname, access_mask,
5239                                 share_access, create_disposition,
5240                                 create_options, file_attributes,
5241                                 &info, &fsp);
5242                 }
5243         }
5244
5245         if (!NT_STATUS_IS_OK(status)) {
5246                 goto fail;
5247         }
5248
5249         fsp->base_fsp = base_fsp;
5250
5251         if ((ea_list != NULL) &&
5252             ((info == FILE_WAS_CREATED) || (info == FILE_WAS_OVERWRITTEN))) {
5253                 status = set_ea(conn, fsp, fsp->fsp_name, ea_list);
5254                 if (!NT_STATUS_IS_OK(status)) {
5255                         goto fail;
5256                 }
5257         }
5258
5259         if (!fsp->is_directory && S_ISDIR(fsp->fsp_name->st.st_ex_mode)) {
5260                 status = NT_STATUS_ACCESS_DENIED;
5261                 goto fail;
5262         }
5263
5264         /* Save the requested allocation size. */
5265         if ((info == FILE_WAS_CREATED) || (info == FILE_WAS_OVERWRITTEN)) {
5266                 if ((allocation_size > (uint64_t)fsp->fsp_name->st.st_ex_size)
5267                     && !(fsp->is_directory))
5268                 {
5269                         fsp->initial_allocation_size = smb_roundup(
5270                                 fsp->conn, allocation_size);
5271                         if (vfs_allocate_file_space(
5272                                     fsp, fsp->initial_allocation_size) == -1) {
5273                                 status = NT_STATUS_DISK_FULL;
5274                                 goto fail;
5275                         }
5276                 } else {
5277                         fsp->initial_allocation_size = smb_roundup(
5278                                 fsp->conn, (uint64_t)fsp->fsp_name->st.st_ex_size);
5279                 }
5280         } else {
5281                 fsp->initial_allocation_size = 0;
5282         }
5283
5284         if ((info == FILE_WAS_CREATED) && lp_nt_acl_support(SNUM(conn)) &&
5285                                 fsp->base_fsp == NULL) {
5286                 if (sd != NULL) {
5287                         /*
5288                          * According to the MS documentation, the only time the security
5289                          * descriptor is applied to the opened file is iff we *created* the
5290                          * file; an existing file stays the same.
5291                          *
5292                          * Also, it seems (from observation) that you can open the file with
5293                          * any access mask but you can still write the sd. We need to override
5294                          * the granted access before we call set_sd
5295                          * Patch for bug #2242 from Tom Lackemann <cessnatomny@yahoo.com>.
5296                          */
5297
5298                         uint32_t sec_info_sent;
5299                         uint32_t saved_access_mask = fsp->access_mask;
5300
5301                         sec_info_sent = get_sec_info(sd);
5302
5303                         fsp->access_mask = FILE_GENERIC_ALL;
5304
5305                         if (sec_info_sent & (SECINFO_OWNER|
5306                                                 SECINFO_GROUP|
5307                                                 SECINFO_DACL|
5308                                                 SECINFO_SACL)) {
5309                                 status = set_sd(fsp, sd, sec_info_sent);
5310                         }
5311
5312                         fsp->access_mask = saved_access_mask;
5313
5314                         if (!NT_STATUS_IS_OK(status)) {
5315                                 goto fail;
5316                         }
5317                 } else if (lp_inherit_acls(SNUM(conn))) {
5318                         /* Inherit from parent. Errors here are not fatal. */
5319                         status = inherit_new_acl(fsp);
5320                         if (!NT_STATUS_IS_OK(status)) {
5321                                 DEBUG(10,("inherit_new_acl: failed for %s with %s\n",
5322                                         fsp_str_dbg(fsp),
5323                                         nt_errstr(status) ));
5324                         }
5325                 }
5326         }
5327
5328         if ((conn->fs_capabilities & FILE_FILE_COMPRESSION)
5329          && (create_options & FILE_NO_COMPRESSION)
5330          && (info == FILE_WAS_CREATED)) {
5331                 status = SMB_VFS_SET_COMPRESSION(conn, fsp, fsp,
5332                                                  COMPRESSION_FORMAT_NONE);
5333                 if (!NT_STATUS_IS_OK(status)) {
5334                         DEBUG(1, ("failed to disable compression: %s\n",
5335                                   nt_errstr(status)));
5336                 }
5337         }
5338
5339         DEBUG(10, ("create_file_unixpath: info=%d\n", info));
5340
5341         *result = fsp;
5342         if (pinfo != NULL) {
5343                 *pinfo = info;
5344         }
5345
5346         smb_fname->st = fsp->fsp_name->st;
5347
5348         return NT_STATUS_OK;
5349
5350  fail:
5351         DEBUG(10, ("create_file_unixpath: %s\n", nt_errstr(status)));
5352
5353         if (fsp != NULL) {
5354                 if (base_fsp && fsp->base_fsp == base_fsp) {
5355                         /*
5356                          * The close_file below will close
5357                          * fsp->base_fsp.
5358                          */
5359                         base_fsp = NULL;
5360                 }
5361                 close_file(req, fsp, ERROR_CLOSE);
5362                 fsp = NULL;
5363         }
5364         if (base_fsp != NULL) {
5365                 close_file(req, base_fsp, ERROR_CLOSE);
5366                 base_fsp = NULL;
5367         }
5368         return status;
5369 }
5370
5371 /*
5372  * Calculate the full path name given a relative fid.
5373  */
5374 static NTSTATUS get_relative_fid_filename(
5375         connection_struct *conn,
5376         struct smb_request *req,
5377         uint16_t root_dir_fid,
5378         const struct smb_filename *smb_fname,
5379         struct smb_filename **smb_fname_out)
5380 {
5381         files_struct *dir_fsp;
5382         char *parent_fname = NULL;
5383         char *new_base_name = NULL;
5384         uint32_t ucf_flags = ucf_flags_from_smb_request(req);
5385         NTSTATUS status;
5386
5387         if (root_dir_fid == 0 || !smb_fname) {
5388                 status = NT_STATUS_INTERNAL_ERROR;
5389                 goto out;
5390         }
5391
5392         dir_fsp = file_fsp(req, root_dir_fid);
5393
5394         if (dir_fsp == NULL) {
5395                 status = NT_STATUS_INVALID_HANDLE;
5396                 goto out;
5397         }
5398
5399         if (is_ntfs_stream_smb_fname(dir_fsp->fsp_name)) {
5400                 status = NT_STATUS_INVALID_HANDLE;
5401                 goto out;
5402         }
5403
5404         if (!dir_fsp->is_directory) {
5405
5406                 /*
5407                  * Check to see if this is a mac fork of some kind.
5408                  */
5409
5410                 if ((conn->fs_capabilities & FILE_NAMED_STREAMS) &&
5411                     is_ntfs_stream_smb_fname(smb_fname)) {
5412                         status = NT_STATUS_OBJECT_PATH_NOT_FOUND;
5413                         goto out;
5414                 }
5415
5416                 /*
5417                   we need to handle the case when we get a
5418                   relative open relative to a file and the
5419                   pathname is blank - this is a reopen!
5420                   (hint from demyn plantenberg)
5421                 */
5422
5423                 status = NT_STATUS_INVALID_HANDLE;
5424                 goto out;
5425         }
5426
5427         if (ISDOT(dir_fsp->fsp_name->base_name)) {
5428                 /*
5429                  * We're at the toplevel dir, the final file name
5430                  * must not contain ./, as this is filtered out
5431                  * normally by srvstr_get_path and unix_convert
5432                  * explicitly rejects paths containing ./.
5433                  */
5434                 parent_fname = talloc_strdup(talloc_tos(), "");
5435                 if (parent_fname == NULL) {
5436                         status = NT_STATUS_NO_MEMORY;
5437                         goto out;
5438                 }
5439         } else {
5440                 size_t dir_name_len = strlen(dir_fsp->fsp_name->base_name);
5441
5442                 /*
5443                  * Copy in the base directory name.
5444                  */
5445
5446                 parent_fname = talloc_array(talloc_tos(), char,
5447                     dir_name_len+2);
5448                 if (parent_fname == NULL) {
5449                         status = NT_STATUS_NO_MEMORY;
5450                         goto out;
5451                 }
5452                 memcpy(parent_fname, dir_fsp->fsp_name->base_name,
5453                     dir_name_len+1);
5454
5455                 /*
5456                  * Ensure it ends in a '/'.
5457                  * We used TALLOC_SIZE +2 to add space for the '/'.
5458                  */
5459
5460                 if(dir_name_len
5461                     && (parent_fname[dir_name_len-1] != '\\')
5462                     && (parent_fname[dir_name_len-1] != '/')) {
5463                         parent_fname[dir_name_len] = '/';
5464                         parent_fname[dir_name_len+1] = '\0';
5465                 }
5466         }
5467
5468         new_base_name = talloc_asprintf(talloc_tos(), "%s%s", parent_fname,
5469                                         smb_fname->base_name);
5470         if (new_base_name == NULL) {
5471                 status = NT_STATUS_NO_MEMORY;
5472                 goto out;
5473         }
5474
5475         status = filename_convert(req,
5476                                 conn,
5477                                 new_base_name,
5478                                 ucf_flags,
5479                                 NULL,
5480                                 NULL,
5481                                 smb_fname_out);
5482         if (!NT_STATUS_IS_OK(status)) {
5483                 goto out;
5484         }
5485
5486  out:
5487         TALLOC_FREE(parent_fname);
5488         TALLOC_FREE(new_base_name);
5489         return status;
5490 }
5491
5492 NTSTATUS create_file_default(connection_struct *conn,
5493                              struct smb_request *req,
5494                              uint16_t root_dir_fid,
5495                              struct smb_filename *smb_fname,
5496                              uint32_t access_mask,
5497                              uint32_t share_access,
5498                              uint32_t create_disposition,
5499                              uint32_t create_options,
5500                              uint32_t file_attributes,
5501                              uint32_t oplock_request,
5502                              const struct smb2_lease *lease,
5503                              uint64_t allocation_size,
5504                              uint32_t private_flags,
5505                              struct security_descriptor *sd,
5506                              struct ea_list *ea_list,
5507                              files_struct **result,
5508                              int *pinfo,
5509                              const struct smb2_create_blobs *in_context_blobs,
5510                              struct smb2_create_blobs *out_context_blobs)
5511 {
5512         int info = FILE_WAS_OPENED;
5513         files_struct *fsp = NULL;
5514         NTSTATUS status;
5515         bool stream_name = false;
5516
5517         DBG_DEBUG("create_file: access_mask = 0x%x "
5518                   "file_attributes = 0x%x, share_access = 0x%x, "
5519                   "create_disposition = 0x%x create_options = 0x%x "
5520                   "oplock_request = 0x%x "
5521                   "private_flags = 0x%x "
5522                   "root_dir_fid = 0x%x, ea_list = %p, sd = %p, "
5523                   "fname = %s\n",
5524                   (unsigned int)access_mask,
5525                   (unsigned int)file_attributes,
5526                   (unsigned int)share_access,
5527                   (unsigned int)create_disposition,
5528                   (unsigned int)create_options,
5529                   (unsigned int)oplock_request,
5530                   (unsigned int)private_flags,
5531                   (unsigned int)root_dir_fid,
5532                   ea_list, sd, smb_fname_str_dbg(smb_fname));
5533
5534         if (req != NULL) {
5535                 /*
5536                  * Remember the absolute time of the original request
5537                  * with this mid. We'll use it later to see if this
5538                  * has timed out.
5539                  */
5540                 get_deferred_open_message_state(req, &req->request_time, NULL);
5541         }
5542
5543         /*
5544          * Calculate the filename from the root_dir_if if necessary.
5545          */
5546
5547         if (root_dir_fid != 0) {
5548                 struct smb_filename *smb_fname_out = NULL;
5549                 status = get_relative_fid_filename(conn, req, root_dir_fid,
5550                                                    smb_fname, &smb_fname_out);
5551                 if (!NT_STATUS_IS_OK(status)) {
5552                         goto fail;
5553                 }
5554                 smb_fname = smb_fname_out;
5555         }
5556
5557         /*
5558          * Check to see if this is a mac fork of some kind.
5559          */
5560
5561         stream_name = is_ntfs_stream_smb_fname(smb_fname);
5562         if (stream_name) {
5563                 enum FAKE_FILE_TYPE fake_file_type;
5564
5565                 fake_file_type = is_fake_file(smb_fname);
5566
5567                 if (fake_file_type != FAKE_FILE_TYPE_NONE) {
5568
5569                         /*
5570                          * Here we go! support for changing the disk quotas
5571                          * --metze
5572                          *
5573                          * We need to fake up to open this MAGIC QUOTA file
5574                          * and return a valid FID.
5575                          *
5576                          * w2k close this file directly after openening xp
5577                          * also tries a QUERY_FILE_INFO on the file and then
5578                          * close it
5579                          */
5580                         status = open_fake_file(req, conn, req->vuid,
5581                                                 fake_file_type, smb_fname,
5582                                                 access_mask, &fsp);
5583                         if (!NT_STATUS_IS_OK(status)) {
5584                                 goto fail;
5585                         }
5586
5587                         ZERO_STRUCT(smb_fname->st);
5588                         goto done;
5589                 }
5590
5591                 if (!(conn->fs_capabilities & FILE_NAMED_STREAMS)) {
5592                         status = NT_STATUS_OBJECT_NAME_NOT_FOUND;
5593                         goto fail;
5594                 }
5595         }
5596
5597         if (is_ntfs_default_stream_smb_fname(smb_fname)) {
5598                 int ret;
5599                 smb_fname->stream_name = NULL;
5600                 /* We have to handle this error here. */
5601                 if (create_options & FILE_DIRECTORY_FILE) {
5602                         status = NT_STATUS_NOT_A_DIRECTORY;
5603                         goto fail;
5604                 }
5605                 if (req != NULL && req->posix_pathnames) {
5606                         ret = SMB_VFS_LSTAT(conn, smb_fname);
5607                 } else {
5608                         ret = SMB_VFS_STAT(conn, smb_fname);
5609                 }
5610
5611                 if (ret == 0 && VALID_STAT_OF_DIR(smb_fname->st)) {
5612                         status = NT_STATUS_FILE_IS_A_DIRECTORY;
5613                         goto fail;
5614                 }
5615         }
5616
5617         status = create_file_unixpath(
5618                 conn, req, smb_fname, access_mask, share_access,
5619                 create_disposition, create_options, file_attributes,
5620                 oplock_request, lease, allocation_size, private_flags,
5621                 sd, ea_list,
5622                 &fsp, &info);
5623
5624         if (!NT_STATUS_IS_OK(status)) {
5625                 goto fail;
5626         }
5627
5628  done:
5629         DEBUG(10, ("create_file: info=%d\n", info));
5630
5631         *result = fsp;
5632         if (pinfo != NULL) {
5633                 *pinfo = info;
5634         }
5635         return NT_STATUS_OK;
5636
5637  fail:
5638         DEBUG(10, ("create_file: %s\n", nt_errstr(status)));
5639
5640         if (fsp != NULL) {
5641                 close_file(req, fsp, ERROR_CLOSE);
5642                 fsp = NULL;
5643         }
5644         return status;
5645 }