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