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