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