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