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