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