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