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