40ba319bf3d995115c3ebf06be5b7b5db6b17b3a
[vlendec/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
262         if (!parent_dirname(talloc_tos(),
263                                 smb_fname->base_name,
264                                 &parent_dir,
265                                 NULL)) {
266                 return NT_STATUS_NO_MEMORY;
267         }
268
269         parent_smb_fname = synthetic_smb_fname(talloc_tos(),
270                                 parent_dir,
271                                 NULL,
272                                 NULL,
273                                 smb_fname->flags);
274         if (parent_smb_fname == NULL) {
275                 return NT_STATUS_NO_MEMORY;
276         }
277
278         if (get_current_uid(conn) == (uid_t)0) {
279                 /* I'm sorry sir, I didn't know you were root... */
280                 DEBUG(10,("check_parent_access: root override "
281                         "on %s. Granting 0x%x\n",
282                         smb_fname_str_dbg(smb_fname),
283                         (unsigned int)access_mask ));
284                 return NT_STATUS_OK;
285         }
286
287         status = SMB_VFS_GET_NT_ACL(conn,
288                                 parent_smb_fname,
289                                 SECINFO_DACL,
290                                     talloc_tos(),
291                                 &parent_sd);
292
293         if (!NT_STATUS_IS_OK(status)) {
294                 DEBUG(5,("check_parent_access: SMB_VFS_GET_NT_ACL failed for "
295                         "%s with error %s\n",
296                         parent_dir,
297                         nt_errstr(status)));
298                 return status;
299         }
300
301         /*
302          * If we can access the path to this file, by
303          * default we have FILE_READ_ATTRIBUTES from the
304          * containing directory. See the section:
305          * "Algorithm to Check Access to an Existing File"
306          * in MS-FSA.pdf.
307          *
308          * se_file_access_check() also takes care of
309          * owner WRITE_DAC and READ_CONTROL.
310          */
311         status = se_file_access_check(parent_sd,
312                                 get_current_nttok(conn),
313                                 false,
314                                 (access_mask & ~FILE_READ_ATTRIBUTES),
315                                 &access_granted);
316         if(!NT_STATUS_IS_OK(status)) {
317                 DEBUG(5,("check_parent_access: access check "
318                         "on directory %s for "
319                         "path %s for mask 0x%x returned (0x%x) %s\n",
320                         parent_dir,
321                         smb_fname->base_name,
322                         access_mask,
323                         access_granted,
324                         nt_errstr(status) ));
325                 return status;
326         }
327
328         if (!(access_mask & (SEC_DIR_ADD_FILE | SEC_DIR_ADD_SUBDIR))) {
329                 return NT_STATUS_OK;
330         }
331         if (!lp_check_parent_directory_delete_on_close(SNUM(conn))) {
332                 return NT_STATUS_OK;
333         }
334
335         /* Check if the directory has delete-on-close set */
336         ret = SMB_VFS_STAT(conn, parent_smb_fname);
337         if (ret != 0) {
338                 status = map_nt_error_from_unix(errno);
339                 goto out;
340         }
341
342         id = SMB_VFS_FILE_ID_CREATE(conn, &parent_smb_fname->st);
343
344         status = file_name_hash(conn, parent_smb_fname->base_name, &name_hash);
345         if (!NT_STATUS_IS_OK(status)) {
346                 goto out;
347         }
348
349         lck = get_existing_share_mode_lock(talloc_tos(), id);
350         if (lck == NULL) {
351                 status = NT_STATUS_OK;
352                 goto out;
353         }
354
355         delete_on_close_set = is_delete_on_close_set(lck, name_hash);
356         if (delete_on_close_set) {
357                 status = NT_STATUS_DELETE_PENDING;
358                 goto out;
359         }
360
361         status = NT_STATUS_OK;
362
363 out:
364         TALLOC_FREE(lck);
365         TALLOC_FREE(parent_smb_fname);
366         return status;
367 }
368
369 /****************************************************************************
370  Ensure when opening a base file for a stream open that we have permissions
371  to do so given the access mask on the base file.
372 ****************************************************************************/
373
374 static NTSTATUS check_base_file_access(struct connection_struct *conn,
375                                 struct smb_filename *smb_fname,
376                                 uint32_t access_mask)
377 {
378         NTSTATUS status;
379
380         status = smbd_calculate_access_mask(conn, smb_fname,
381                                         false,
382                                         access_mask,
383                                         &access_mask);
384         if (!NT_STATUS_IS_OK(status)) {
385                 DEBUG(10, ("smbd_calculate_access_mask "
386                         "on file %s returned %s\n",
387                         smb_fname_str_dbg(smb_fname),
388                         nt_errstr(status)));
389                 return status;
390         }
391
392         if (access_mask & (FILE_WRITE_DATA|FILE_APPEND_DATA)) {
393                 uint32_t dosattrs;
394                 if (!CAN_WRITE(conn)) {
395                         return NT_STATUS_ACCESS_DENIED;
396                 }
397                 dosattrs = dos_mode(conn, smb_fname);
398                 if (IS_DOS_READONLY(dosattrs)) {
399                         return NT_STATUS_ACCESS_DENIED;
400                 }
401         }
402
403         return smbd_check_access_rights(conn,
404                                         smb_fname,
405                                         false,
406                                         access_mask);
407 }
408
409 /****************************************************************************
410  Handle differing symlink errno's
411 ****************************************************************************/
412
413 static int link_errno_convert(int err)
414 {
415 #if defined(ENOTSUP) && defined(OSF1)
416         /* handle special Tru64 errno */
417         if (err == ENOTSUP) {
418                 err = ELOOP;
419         }
420 #endif /* ENOTSUP */
421 #ifdef EFTYPE
422         /* fix broken NetBSD errno */
423         if (err == EFTYPE) {
424                 err = ELOOP;
425         }
426 #endif /* EFTYPE */
427         /* fix broken FreeBSD errno */
428         if (err == EMLINK) {
429                 err = ELOOP;
430         }
431         return err;
432 }
433
434 static int non_widelink_open(struct connection_struct *conn,
435                         const struct smb_filename *conn_rootdir_fname,
436                         files_struct *fsp,
437                         struct smb_filename *smb_fname,
438                         int flags,
439                         mode_t mode,
440                         unsigned int link_depth);
441
442 /****************************************************************************
443  Follow a symlink in userspace.
444 ****************************************************************************/
445
446 static int process_symlink_open(struct connection_struct *conn,
447                         const struct smb_filename *conn_rootdir_fname,
448                         files_struct *fsp,
449                         struct smb_filename *smb_fname,
450                         int flags,
451                         mode_t mode,
452                         unsigned int link_depth)
453 {
454         int fd = -1;
455         char *link_target = NULL;
456         struct smb_filename target_fname = {0};
457         int link_len = -1;
458         struct smb_filename *oldwd_fname = NULL;
459         size_t rootdir_len = 0;
460         struct smb_filename *resolved_fname = NULL;
461         char *resolved_name = NULL;
462         bool matched = false;
463         int saved_errno = 0;
464
465         /*
466          * Ensure we don't get stuck in a symlink loop.
467          */
468         link_depth++;
469         if (link_depth >= 20) {
470                 errno = ELOOP;
471                 goto out;
472         }
473
474         /* Allocate space for the link target. */
475         link_target = talloc_array(talloc_tos(), char, PATH_MAX);
476         if (link_target == NULL) {
477                 errno = ENOMEM;
478                 goto out;
479         }
480
481         /* Read the link target. */
482         link_len = SMB_VFS_READLINK(conn,
483                                 smb_fname,
484                                 link_target,
485                                 PATH_MAX - 1);
486         if (link_len == -1) {
487                 goto out;
488         }
489
490         /* Ensure it's at least null terminated. */
491         link_target[link_len] = '\0';
492         target_fname = (struct smb_filename){ .base_name = link_target };
493
494         /* Convert to an absolute path. */
495         resolved_fname = SMB_VFS_REALPATH(conn, talloc_tos(), &target_fname);
496         if (resolved_fname == NULL) {
497                 goto out;
498         }
499         resolved_name = resolved_fname->base_name;
500
501         /*
502          * We know conn_rootdir starts with '/' and
503          * does not end in '/'. FIXME ! Should we
504          * smb_assert this ?
505          */
506         rootdir_len = strlen(conn_rootdir_fname->base_name);
507
508         matched = (strncmp(conn_rootdir_fname->base_name,
509                                 resolved_name,
510                                 rootdir_len) == 0);
511         if (!matched) {
512                 errno = EACCES;
513                 goto out;
514         }
515
516         /*
517          * Turn into a path relative to the share root.
518          */
519         if (resolved_name[rootdir_len] == '\0') {
520                 /* Link to the root of the share. */
521                 TALLOC_FREE(smb_fname->base_name);
522                 smb_fname->base_name = talloc_strdup(smb_fname, ".");
523         } else if (resolved_name[rootdir_len] == '/') {
524                 TALLOC_FREE(smb_fname->base_name);
525                 smb_fname->base_name = talloc_strdup(smb_fname,
526                                         &resolved_name[rootdir_len+1]);
527         } else {
528                 errno = EACCES;
529                 goto out;
530         }
531
532         if (smb_fname->base_name == NULL) {
533                 errno = ENOMEM;
534                 goto out;
535         }
536
537         oldwd_fname = vfs_GetWd(talloc_tos(), conn);
538         if (oldwd_fname == NULL) {
539                 goto out;
540         }
541
542         /* Ensure we operate from the root of the share. */
543         if (vfs_ChDir(conn, conn_rootdir_fname) == -1) {
544                 goto out;
545         }
546
547         /* And do it all again.. */
548         fd = non_widelink_open(conn,
549                                 conn_rootdir_fname,
550                                 fsp,
551                                 smb_fname,
552                                 flags,
553                                 mode,
554                                 link_depth);
555         if (fd == -1) {
556                 saved_errno = errno;
557         }
558
559   out:
560
561         TALLOC_FREE(resolved_fname);
562         TALLOC_FREE(link_target);
563         if (oldwd_fname != NULL) {
564                 int ret = vfs_ChDir(conn, oldwd_fname);
565                 if (ret == -1) {
566                         smb_panic("unable to get back to old directory\n");
567                 }
568                 TALLOC_FREE(oldwd_fname);
569         }
570         if (saved_errno != 0) {
571                 errno = saved_errno;
572         }
573         return fd;
574 }
575
576 /****************************************************************************
577  Non-widelink open.
578 ****************************************************************************/
579
580 static int non_widelink_open(struct connection_struct *conn,
581                         const struct smb_filename *conn_rootdir_fname,
582                         files_struct *fsp,
583                         struct smb_filename *smb_fname,
584                         int flags,
585                         mode_t mode,
586                         unsigned int link_depth)
587 {
588         NTSTATUS status;
589         int fd = -1;
590         struct smb_filename *smb_fname_rel = NULL;
591         int saved_errno = 0;
592         struct smb_filename *oldwd_fname = NULL;
593         char *parent_dir = NULL;
594         struct smb_filename parent_dir_fname = {0};
595         const char *final_component = NULL;
596         bool is_directory = false;
597         bool ok;
598
599 #ifdef O_DIRECTORY
600         if (flags & O_DIRECTORY) {
601                 is_directory = true;
602         }
603 #endif
604
605         if (is_directory) {
606                 parent_dir = talloc_strdup(talloc_tos(), smb_fname->base_name);
607                 if (parent_dir == NULL) {
608                         saved_errno = errno;
609                         goto out;
610                 }
611
612                 final_component = ".";
613         } else {
614                 ok = parent_dirname(talloc_tos(),
615                                     smb_fname->base_name,
616                                     &parent_dir,
617                                     &final_component);
618                 if (!ok) {
619                         saved_errno = errno;
620                         goto out;
621                 }
622         }
623
624         parent_dir_fname = (struct smb_filename) { .base_name = parent_dir };
625
626         oldwd_fname = vfs_GetWd(talloc_tos(), conn);
627         if (oldwd_fname == NULL) {
628                 goto out;
629         }
630
631         /* Pin parent directory in place. */
632         if (vfs_ChDir(conn, &parent_dir_fname) == -1) {
633                 goto out;
634         }
635
636         smb_fname_rel = synthetic_smb_fname(talloc_tos(),
637                                 final_component,
638                                 smb_fname->stream_name,
639                                 &smb_fname->st,
640                                 smb_fname->flags);
641         if (smb_fname_rel == NULL) {
642                 saved_errno = ENOMEM;
643                 goto out;
644         }
645
646         /* Ensure the relative path is below the share. */
647         status = check_reduced_name(conn, &parent_dir_fname, smb_fname_rel);
648         if (!NT_STATUS_IS_OK(status)) {
649                 saved_errno = map_errno_from_nt_status(status);
650                 goto out;
651         }
652
653         flags |= O_NOFOLLOW;
654
655         {
656                 struct smb_filename *tmp_name = fsp->fsp_name;
657                 fsp->fsp_name = smb_fname_rel;
658                 fd = SMB_VFS_OPEN(conn, smb_fname_rel, fsp, flags, mode);
659                 fsp->fsp_name = tmp_name;
660         }
661
662         if (fd == -1) {
663                 saved_errno = link_errno_convert(errno);
664                 /*
665                  * Trying to open a symlink to a directory with O_NOFOLLOW and
666                  * O_DIRECTORY can return either of ELOOP and ENOTDIR. So
667                  * ENOTDIR really means: might be a symlink, but we're not sure.
668                  * In this case, we just assume there's a symlink. If we were
669                  * wrong, process_symlink_open() will return EINVAL. We check
670                  * this below, and fall back to returning the initial
671                  * saved_errno.
672                  *
673                  * BUG: https://bugzilla.samba.org/show_bug.cgi?id=12860
674                  */
675                 if (saved_errno == ELOOP || saved_errno == ENOTDIR) {
676                         if (fsp->posix_flags & FSP_POSIX_FLAGS_OPEN) {
677                                 /* Never follow symlinks on posix open. */
678                                 goto out;
679                         }
680                         if (!lp_follow_symlinks(SNUM(conn))) {
681                                 /* Explicitly no symlinks. */
682                                 goto out;
683                         }
684                         /*
685                          * We may have a symlink. Follow in userspace
686                          * to ensure it's under the share definition.
687                          */
688                         fd = process_symlink_open(conn,
689                                         conn_rootdir_fname,
690                                         fsp,
691                                         smb_fname_rel,
692                                         flags,
693                                         mode,
694                                         link_depth);
695                         if (fd == -1) {
696                                 if (saved_errno == ENOTDIR &&
697                                                 errno == EINVAL) {
698                                         /*
699                                          * O_DIRECTORY on neither a directory,
700                                          * nor a symlink. Just return
701                                          * saved_errno from initial open()
702                                          */
703                                         goto out;
704                                 }
705                                 saved_errno =
706                                         link_errno_convert(errno);
707                         }
708                 }
709         }
710
711   out:
712
713         TALLOC_FREE(parent_dir);
714         TALLOC_FREE(smb_fname_rel);
715
716         if (oldwd_fname != NULL) {
717                 int ret = vfs_ChDir(conn, oldwd_fname);
718                 if (ret == -1) {
719                         smb_panic("unable to get back to old directory\n");
720                 }
721                 TALLOC_FREE(oldwd_fname);
722         }
723         if (saved_errno != 0) {
724                 errno = saved_errno;
725         }
726         return fd;
727 }
728
729 /****************************************************************************
730  fd support routines - attempt to do a dos_open.
731 ****************************************************************************/
732
733 NTSTATUS fd_open(struct connection_struct *conn,
734                  files_struct *fsp,
735                  int flags,
736                  mode_t mode)
737 {
738         struct smb_filename *smb_fname = fsp->fsp_name;
739         NTSTATUS status = NT_STATUS_OK;
740
741         /*
742          * Never follow symlinks on a POSIX client. The
743          * client should be doing this.
744          */
745
746         if ((fsp->posix_flags & FSP_POSIX_FLAGS_OPEN) || !lp_follow_symlinks(SNUM(conn))) {
747                 flags |= O_NOFOLLOW;
748         }
749
750         /* Ensure path is below share definition. */
751         if (!lp_widelinks(SNUM(conn))) {
752                 struct smb_filename *conn_rootdir_fname = NULL;
753                 const char *conn_rootdir = SMB_VFS_CONNECTPATH(conn,
754                                                 smb_fname);
755                 int saved_errno = 0;
756
757                 if (conn_rootdir == NULL) {
758                         return NT_STATUS_NO_MEMORY;
759                 }
760                 conn_rootdir_fname = synthetic_smb_fname(talloc_tos(),
761                                                 conn_rootdir,
762                                                 NULL,
763                                                 NULL,
764                                                 0);
765                 if (conn_rootdir_fname == NULL) {
766                         return NT_STATUS_NO_MEMORY;
767                 }
768
769                 /*
770                  * Only follow symlinks within a share
771                  * definition.
772                  */
773                 fsp->fh->fd = non_widelink_open(conn,
774                                         conn_rootdir_fname,
775                                         fsp,
776                                         smb_fname,
777                                         flags,
778                                         mode,
779                                         0);
780                 if (fsp->fh->fd == -1) {
781                         saved_errno = errno;
782                 }
783                 TALLOC_FREE(conn_rootdir_fname);
784                 if (saved_errno != 0) {
785                         errno = saved_errno;
786                 }
787         } else {
788                 fsp->fh->fd = SMB_VFS_OPEN(conn, smb_fname, fsp, flags, mode);
789         }
790
791         if (fsp->fh->fd == -1) {
792                 int posix_errno = link_errno_convert(errno);
793                 status = map_nt_error_from_unix(posix_errno);
794                 if (errno == EMFILE) {
795                         static time_t last_warned = 0L;
796
797                         if (time((time_t *) NULL) > last_warned) {
798                                 DEBUG(0,("Too many open files, unable "
799                                         "to open more!  smbd's max "
800                                         "open files = %d\n",
801                                         lp_max_open_files()));
802                                 last_warned = time((time_t *) NULL);
803                         }
804                 }
805
806         }
807
808         DEBUG(10,("fd_open: name %s, flags = 0%o mode = 0%o, fd = %d. %s\n",
809                   smb_fname_str_dbg(smb_fname), flags, (int)mode, fsp->fh->fd,
810                 (fsp->fh->fd == -1) ? strerror(errno) : "" ));
811
812         return status;
813 }
814
815 /****************************************************************************
816  Close the file associated with a fsp.
817 ****************************************************************************/
818
819 NTSTATUS fd_close(files_struct *fsp)
820 {
821         int ret;
822
823         if (fsp->dptr) {
824                 dptr_CloseDir(fsp);
825         }
826         if (fsp->fh->fd == -1) {
827                 return NT_STATUS_OK; /* What we used to call a stat open. */
828         }
829         if (fsp->fh->ref_count > 1) {
830                 return NT_STATUS_OK; /* Shared handle. Only close last reference. */
831         }
832
833         ret = SMB_VFS_CLOSE(fsp);
834         fsp->fh->fd = -1;
835         if (ret == -1) {
836                 return map_nt_error_from_unix(errno);
837         }
838         return NT_STATUS_OK;
839 }
840
841 /****************************************************************************
842  Change the ownership of a file to that of the parent directory.
843  Do this by fd if possible.
844 ****************************************************************************/
845
846 void change_file_owner_to_parent(connection_struct *conn,
847                                         const char *inherit_from_dir,
848                                         files_struct *fsp)
849 {
850         struct smb_filename *smb_fname_parent;
851         int ret;
852
853         smb_fname_parent = synthetic_smb_fname(talloc_tos(),
854                                         inherit_from_dir,
855                                         NULL,
856                                         NULL,
857                                         0);
858         if (smb_fname_parent == NULL) {
859                 return;
860         }
861
862         ret = SMB_VFS_STAT(conn, smb_fname_parent);
863         if (ret == -1) {
864                 DEBUG(0,("change_file_owner_to_parent: failed to stat parent "
865                          "directory %s. Error was %s\n",
866                          smb_fname_str_dbg(smb_fname_parent),
867                          strerror(errno)));
868                 TALLOC_FREE(smb_fname_parent);
869                 return;
870         }
871
872         if (smb_fname_parent->st.st_ex_uid == fsp->fsp_name->st.st_ex_uid) {
873                 /* Already this uid - no need to change. */
874                 DEBUG(10,("change_file_owner_to_parent: file %s "
875                         "is already owned by uid %d\n",
876                         fsp_str_dbg(fsp),
877                         (int)fsp->fsp_name->st.st_ex_uid ));
878                 TALLOC_FREE(smb_fname_parent);
879                 return;
880         }
881
882         become_root();
883         ret = SMB_VFS_FCHOWN(fsp, smb_fname_parent->st.st_ex_uid, (gid_t)-1);
884         unbecome_root();
885         if (ret == -1) {
886                 DEBUG(0,("change_file_owner_to_parent: failed to fchown "
887                          "file %s to parent directory uid %u. Error "
888                          "was %s\n", fsp_str_dbg(fsp),
889                          (unsigned int)smb_fname_parent->st.st_ex_uid,
890                          strerror(errno) ));
891         } else {
892                 DEBUG(10,("change_file_owner_to_parent: changed new file %s to "
893                         "parent directory uid %u.\n", fsp_str_dbg(fsp),
894                         (unsigned int)smb_fname_parent->st.st_ex_uid));
895                 /* Ensure the uid entry is updated. */
896                 fsp->fsp_name->st.st_ex_uid = smb_fname_parent->st.st_ex_uid;
897         }
898
899         TALLOC_FREE(smb_fname_parent);
900 }
901
902 static NTSTATUS change_dir_owner_to_parent(connection_struct *conn,
903                                         const char *inherit_from_dir,
904                                         struct smb_filename *smb_dname,
905                                         SMB_STRUCT_STAT *psbuf)
906 {
907         struct smb_filename *smb_fname_parent;
908         struct smb_filename *smb_fname_cwd = NULL;
909         struct smb_filename *saved_dir_fname = NULL;
910         TALLOC_CTX *ctx = talloc_tos();
911         NTSTATUS status = NT_STATUS_OK;
912         int ret;
913
914         smb_fname_parent = synthetic_smb_fname(ctx,
915                                         inherit_from_dir,
916                                         NULL,
917                                         NULL,
918                                         0);
919         if (smb_fname_parent == NULL) {
920                 return NT_STATUS_NO_MEMORY;
921         }
922
923         ret = SMB_VFS_STAT(conn, smb_fname_parent);
924         if (ret == -1) {
925                 status = map_nt_error_from_unix(errno);
926                 DEBUG(0,("change_dir_owner_to_parent: failed to stat parent "
927                          "directory %s. Error was %s\n",
928                          smb_fname_str_dbg(smb_fname_parent),
929                          strerror(errno)));
930                 goto out;
931         }
932
933         /* We've already done an lstat into psbuf, and we know it's a
934            directory. If we can cd into the directory and the dev/ino
935            are the same then we can safely chown without races as
936            we're locking the directory in place by being in it.  This
937            should work on any UNIX (thanks tridge :-). JRA.
938         */
939
940         saved_dir_fname = vfs_GetWd(ctx,conn);
941         if (!saved_dir_fname) {
942                 status = map_nt_error_from_unix(errno);
943                 DEBUG(0,("change_dir_owner_to_parent: failed to get "
944                          "current working directory. Error was %s\n",
945                          strerror(errno)));
946                 goto out;
947         }
948
949         /* Chdir into the new path. */
950         if (vfs_ChDir(conn, smb_dname) == -1) {
951                 status = map_nt_error_from_unix(errno);
952                 DEBUG(0,("change_dir_owner_to_parent: failed to change "
953                          "current working directory to %s. Error "
954                          "was %s\n", smb_dname->base_name, strerror(errno) ));
955                 goto chdir;
956         }
957
958         smb_fname_cwd = synthetic_smb_fname(ctx, ".", NULL, NULL, 0);
959         if (smb_fname_cwd == NULL) {
960                 status = NT_STATUS_NO_MEMORY;
961                 goto chdir;
962         }
963
964         ret = SMB_VFS_STAT(conn, smb_fname_cwd);
965         if (ret == -1) {
966                 status = map_nt_error_from_unix(errno);
967                 DEBUG(0,("change_dir_owner_to_parent: failed to stat "
968                          "directory '.' (%s) Error was %s\n",
969                          smb_dname->base_name, strerror(errno)));
970                 goto chdir;
971         }
972
973         /* Ensure we're pointing at the same place. */
974         if (smb_fname_cwd->st.st_ex_dev != psbuf->st_ex_dev ||
975             smb_fname_cwd->st.st_ex_ino != psbuf->st_ex_ino) {
976                 DEBUG(0,("change_dir_owner_to_parent: "
977                          "device/inode on directory %s changed. "
978                          "Refusing to chown !\n",
979                         smb_dname->base_name ));
980                 status = NT_STATUS_ACCESS_DENIED;
981                 goto chdir;
982         }
983
984         if (smb_fname_parent->st.st_ex_uid == smb_fname_cwd->st.st_ex_uid) {
985                 /* Already this uid - no need to change. */
986                 DEBUG(10,("change_dir_owner_to_parent: directory %s "
987                         "is already owned by uid %d\n",
988                         smb_dname->base_name,
989                         (int)smb_fname_cwd->st.st_ex_uid ));
990                 status = NT_STATUS_OK;
991                 goto chdir;
992         }
993
994         become_root();
995         ret = SMB_VFS_LCHOWN(conn,
996                         smb_fname_cwd,
997                         smb_fname_parent->st.st_ex_uid,
998                         (gid_t)-1);
999         unbecome_root();
1000         if (ret == -1) {
1001                 status = map_nt_error_from_unix(errno);
1002                 DEBUG(10,("change_dir_owner_to_parent: failed to chown "
1003                           "directory %s to parent directory uid %u. "
1004                           "Error was %s\n",
1005                           smb_dname->base_name,
1006                           (unsigned int)smb_fname_parent->st.st_ex_uid,
1007                           strerror(errno) ));
1008         } else {
1009                 DEBUG(10,("change_dir_owner_to_parent: changed ownership of new "
1010                         "directory %s to parent directory uid %u.\n",
1011                         smb_dname->base_name,
1012                         (unsigned int)smb_fname_parent->st.st_ex_uid ));
1013                 /* Ensure the uid entry is updated. */
1014                 psbuf->st_ex_uid = smb_fname_parent->st.st_ex_uid;
1015         }
1016
1017  chdir:
1018         vfs_ChDir(conn, saved_dir_fname);
1019  out:
1020         TALLOC_FREE(saved_dir_fname);
1021         TALLOC_FREE(smb_fname_parent);
1022         TALLOC_FREE(smb_fname_cwd);
1023         return status;
1024 }
1025
1026 /****************************************************************************
1027  Open a file - returning a guaranteed ATOMIC indication of if the
1028  file was created or not.
1029 ****************************************************************************/
1030
1031 static NTSTATUS fd_open_atomic(struct connection_struct *conn,
1032                         files_struct *fsp,
1033                         int flags,
1034                         mode_t mode,
1035                         bool *file_created)
1036 {
1037         NTSTATUS status = NT_STATUS_UNSUCCESSFUL;
1038         NTSTATUS retry_status;
1039         bool file_existed = VALID_STAT(fsp->fsp_name->st);
1040         int curr_flags;
1041
1042         *file_created = false;
1043
1044         if (!(flags & O_CREAT)) {
1045                 /*
1046                  * We're not creating the file, just pass through.
1047                  */
1048                 return fd_open(conn, fsp, flags, mode);
1049         }
1050
1051         if (flags & O_EXCL) {
1052                 /*
1053                  * Fail if already exists, just pass through.
1054                  */
1055                 status = fd_open(conn, fsp, flags, mode);
1056
1057                 /*
1058                  * Here we've opened with O_CREAT|O_EXCL. If that went
1059                  * NT_STATUS_OK, we *know* we created this file.
1060                  */
1061                 *file_created = NT_STATUS_IS_OK(status);
1062
1063                 return status;
1064         }
1065
1066         /*
1067          * Now it gets tricky. We have O_CREAT, but not O_EXCL.
1068          * To know absolutely if we created the file or not,
1069          * we can never call O_CREAT without O_EXCL. So if
1070          * we think the file existed, try without O_CREAT|O_EXCL.
1071          * If we think the file didn't exist, try with
1072          * O_CREAT|O_EXCL.
1073          *
1074          * The big problem here is dangling symlinks. Opening
1075          * without O_NOFOLLOW means both bad symlink
1076          * and missing path return -1, ENOENT from open(). As POSIX
1077          * is pathname based it's not possible to tell
1078          * the difference between these two cases in a
1079          * non-racy way, so change to try only two attempts before
1080          * giving up.
1081          *
1082          * We don't have this problem for the O_NOFOLLOW
1083          * case as it just returns NT_STATUS_OBJECT_PATH_NOT_FOUND
1084          * mapped from the ELOOP POSIX error.
1085          */
1086
1087         curr_flags = flags;
1088
1089         if (file_existed) {
1090                 curr_flags &= ~(O_CREAT);
1091                 retry_status = NT_STATUS_OBJECT_NAME_NOT_FOUND;
1092         } else {
1093                 curr_flags |= O_EXCL;
1094                 retry_status = NT_STATUS_OBJECT_NAME_COLLISION;
1095         }
1096
1097         status = fd_open(conn, fsp, curr_flags, mode);
1098         if (NT_STATUS_IS_OK(status)) {
1099                 if (!file_existed) {
1100                         *file_created = true;
1101                 }
1102                 return NT_STATUS_OK;
1103         }
1104         if (!NT_STATUS_EQUAL(status, retry_status)) {
1105                 return status;
1106         }
1107
1108         curr_flags = flags;
1109
1110         /*
1111          * Keep file_existed up to date for clarity.
1112          */
1113         if (NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
1114                 file_existed = false;
1115                 curr_flags |= O_EXCL;
1116                 DBG_DEBUG("file %s did not exist. Retry.\n",
1117                         smb_fname_str_dbg(fsp->fsp_name));
1118         } else {
1119                 file_existed = true;
1120                 curr_flags &= ~(O_CREAT);
1121                 DBG_DEBUG("file %s existed. Retry.\n",
1122                         smb_fname_str_dbg(fsp->fsp_name));
1123         }
1124
1125         status = fd_open(conn, fsp, curr_flags, mode);
1126
1127         if (NT_STATUS_IS_OK(status) && (!file_existed)) {
1128                 *file_created = true;
1129         }
1130
1131         return status;
1132 }
1133
1134 /****************************************************************************
1135  Open a file.
1136 ****************************************************************************/
1137
1138 static NTSTATUS open_file(files_struct *fsp,
1139                           connection_struct *conn,
1140                           struct smb_request *req,
1141                           const char *parent_dir,
1142                           int flags,
1143                           mode_t unx_mode,
1144                           uint32_t access_mask, /* client requested access mask. */
1145                           uint32_t open_access_mask, /* what we're actually using in the open. */
1146                           bool *p_file_created)
1147 {
1148         struct smb_filename *smb_fname = fsp->fsp_name;
1149         NTSTATUS status = NT_STATUS_OK;
1150         int accmode = (flags & O_ACCMODE);
1151         int local_flags = flags;
1152         bool file_existed = VALID_STAT(fsp->fsp_name->st);
1153
1154         fsp->fh->fd = -1;
1155         errno = EPERM;
1156
1157         /* Check permissions */
1158
1159         /*
1160          * This code was changed after seeing a client open request 
1161          * containing the open mode of (DENY_WRITE/read-only) with
1162          * the 'create if not exist' bit set. The previous code
1163          * would fail to open the file read only on a read-only share
1164          * as it was checking the flags parameter  directly against O_RDONLY,
1165          * this was failing as the flags parameter was set to O_RDONLY|O_CREAT.
1166          * JRA.
1167          */
1168
1169         if (!CAN_WRITE(conn)) {
1170                 /* It's a read-only share - fail if we wanted to write. */
1171                 if(accmode != O_RDONLY || (flags & O_TRUNC) || (flags & O_APPEND)) {
1172                         DEBUG(3,("Permission denied opening %s\n",
1173                                  smb_fname_str_dbg(smb_fname)));
1174                         return NT_STATUS_ACCESS_DENIED;
1175                 }
1176                 if (flags & O_CREAT) {
1177                         /* We don't want to write - but we must make sure that
1178                            O_CREAT doesn't create the file if we have write
1179                            access into the directory.
1180                         */
1181                         flags &= ~(O_CREAT|O_EXCL);
1182                         local_flags &= ~(O_CREAT|O_EXCL);
1183                 }
1184         }
1185
1186         /*
1187          * This little piece of insanity is inspired by the
1188          * fact that an NT client can open a file for O_RDONLY,
1189          * but set the create disposition to FILE_EXISTS_TRUNCATE.
1190          * If the client *can* write to the file, then it expects to
1191          * truncate the file, even though it is opening for readonly.
1192          * Quicken uses this stupid trick in backup file creation...
1193          * Thanks *greatly* to "David W. Chapman Jr." <dwcjr@inethouston.net>
1194          * for helping track this one down. It didn't bite us in 2.0.x
1195          * as we always opened files read-write in that release. JRA.
1196          */
1197
1198         if ((accmode == O_RDONLY) && ((flags & O_TRUNC) == O_TRUNC)) {
1199                 DEBUG(10,("open_file: truncate requested on read-only open "
1200                           "for file %s\n", smb_fname_str_dbg(smb_fname)));
1201                 local_flags = (flags & ~O_ACCMODE)|O_RDWR;
1202         }
1203
1204         if ((open_access_mask & (FILE_READ_DATA|FILE_WRITE_DATA|FILE_APPEND_DATA|FILE_EXECUTE)) ||
1205             (!file_existed && (local_flags & O_CREAT)) ||
1206             ((local_flags & O_TRUNC) == O_TRUNC) ) {
1207                 const char *wild;
1208                 int ret;
1209
1210 #if defined(O_NONBLOCK) && defined(S_ISFIFO)
1211                 /*
1212                  * We would block on opening a FIFO with no one else on the
1213                  * other end. Do what we used to do and add O_NONBLOCK to the
1214                  * open flags. JRA.
1215                  */
1216
1217                 if (file_existed && S_ISFIFO(smb_fname->st.st_ex_mode)) {
1218                         local_flags &= ~O_TRUNC; /* Can't truncate a FIFO. */
1219                         local_flags |= O_NONBLOCK;
1220                 }
1221 #endif
1222
1223                 /* Don't create files with Microsoft wildcard characters. */
1224                 if (fsp->base_fsp) {
1225                         /*
1226                          * wildcard characters are allowed in stream names
1227                          * only test the basefilename
1228                          */
1229                         wild = fsp->base_fsp->fsp_name->base_name;
1230                 } else {
1231                         wild = smb_fname->base_name;
1232                 }
1233                 if ((local_flags & O_CREAT) && !file_existed &&
1234                     !(fsp->posix_flags & FSP_POSIX_FLAGS_PATHNAMES) &&
1235                     ms_has_wild(wild))  {
1236                         return NT_STATUS_OBJECT_NAME_INVALID;
1237                 }
1238
1239                 /* Can we access this file ? */
1240                 if (!fsp->base_fsp) {
1241                         /* Only do this check on non-stream open. */
1242                         if (file_existed) {
1243                                 status = smbd_check_access_rights(conn,
1244                                                 smb_fname,
1245                                                 false,
1246                                                 access_mask);
1247
1248                                 if (!NT_STATUS_IS_OK(status)) {
1249                                         DEBUG(10, ("open_file: "
1250                                                    "smbd_check_access_rights "
1251                                                    "on file %s returned %s\n",
1252                                                    smb_fname_str_dbg(smb_fname),
1253                                                    nt_errstr(status)));
1254                                 }
1255
1256                                 if (!NT_STATUS_IS_OK(status) &&
1257                                     !NT_STATUS_EQUAL(status,
1258                                         NT_STATUS_OBJECT_NAME_NOT_FOUND))
1259                                 {
1260                                         return status;
1261                                 }
1262
1263                                 if (NT_STATUS_EQUAL(status,
1264                                         NT_STATUS_OBJECT_NAME_NOT_FOUND))
1265                                 {
1266                                         DEBUG(10, ("open_file: "
1267                                                 "file %s vanished since we "
1268                                                 "checked for existence.\n",
1269                                                 smb_fname_str_dbg(smb_fname)));
1270                                         file_existed = false;
1271                                         SET_STAT_INVALID(fsp->fsp_name->st);
1272                                 }
1273                         }
1274
1275                         if (!file_existed) {
1276                                 if (!(local_flags & O_CREAT)) {
1277                                         /* File didn't exist and no O_CREAT. */
1278                                         return NT_STATUS_OBJECT_NAME_NOT_FOUND;
1279                                 }
1280
1281                                 status = check_parent_access(conn,
1282                                                              smb_fname,
1283                                                              SEC_DIR_ADD_FILE);
1284                                 if (!NT_STATUS_IS_OK(status)) {
1285                                         DEBUG(10, ("open_file: "
1286                                                    "check_parent_access on "
1287                                                    "file %s returned %s\n",
1288                                                    smb_fname_str_dbg(smb_fname),
1289                                                    nt_errstr(status) ));
1290                                         return status;
1291                                 }
1292                         }
1293                 }
1294
1295                 /*
1296                  * Actually do the open - if O_TRUNC is needed handle it
1297                  * below under the share mode lock.
1298                  */
1299                 status = fd_open_atomic(conn, fsp, local_flags & ~O_TRUNC,
1300                                 unx_mode, p_file_created);
1301                 if (!NT_STATUS_IS_OK(status)) {
1302                         DEBUG(3,("Error opening file %s (%s) (local_flags=%d) "
1303                                  "(flags=%d)\n", smb_fname_str_dbg(smb_fname),
1304                                  nt_errstr(status),local_flags,flags));
1305                         return status;
1306                 }
1307
1308                 if (local_flags & O_NONBLOCK) {
1309                         /*
1310                          * GPFS can return ETIMEDOUT for pread on
1311                          * nonblocking file descriptors when files
1312                          * migrated to tape need to be recalled. I
1313                          * could imagine this happens elsehwere
1314                          * too. With blocking file descriptors this
1315                          * does not happen.
1316                          */
1317                         ret = set_blocking(fsp->fh->fd, true);
1318                         if (ret == -1) {
1319                                 status = map_nt_error_from_unix(errno);
1320                                 DBG_WARNING("Could not set fd to blocking: "
1321                                             "%s\n", strerror(errno));
1322                                 fd_close(fsp);
1323                                 return status;
1324                         }
1325                 }
1326
1327                 ret = SMB_VFS_FSTAT(fsp, &smb_fname->st);
1328                 if (ret == -1) {
1329                         /* If we have an fd, this stat should succeed. */
1330                         DEBUG(0,("Error doing fstat on open file %s "
1331                                 "(%s)\n",
1332                                 smb_fname_str_dbg(smb_fname),
1333                                 strerror(errno) ));
1334                         status = map_nt_error_from_unix(errno);
1335                         fd_close(fsp);
1336                         return status;
1337                 }
1338
1339                 if (*p_file_created) {
1340                         /* We created this file. */
1341
1342                         bool need_re_stat = false;
1343                         /* Do all inheritance work after we've
1344                            done a successful fstat call and filled
1345                            in the stat struct in fsp->fsp_name. */
1346
1347                         /* Inherit the ACL if required */
1348                         if (lp_inherit_permissions(SNUM(conn))) {
1349                                 inherit_access_posix_acl(conn, parent_dir,
1350                                                          smb_fname,
1351                                                          unx_mode);
1352                                 need_re_stat = true;
1353                         }
1354
1355                         /* Change the owner if required. */
1356                         if (lp_inherit_owner(SNUM(conn)) != INHERIT_OWNER_NO) {
1357                                 change_file_owner_to_parent(conn, parent_dir,
1358                                                             fsp);
1359                                 need_re_stat = true;
1360                         }
1361
1362                         if (need_re_stat) {
1363                                 ret = SMB_VFS_FSTAT(fsp, &smb_fname->st);
1364                                 /* If we have an fd, this stat should succeed. */
1365                                 if (ret == -1) {
1366                                         DEBUG(0,("Error doing fstat on open file %s "
1367                                                  "(%s)\n",
1368                                                  smb_fname_str_dbg(smb_fname),
1369                                                  strerror(errno) ));
1370                                 }
1371                         }
1372
1373                         notify_fname(conn, NOTIFY_ACTION_ADDED,
1374                                      FILE_NOTIFY_CHANGE_FILE_NAME,
1375                                      smb_fname->base_name);
1376                 }
1377         } else {
1378                 fsp->fh->fd = -1; /* What we used to call a stat open. */
1379                 if (!file_existed) {
1380                         /* File must exist for a stat open. */
1381                         return NT_STATUS_OBJECT_NAME_NOT_FOUND;
1382                 }
1383
1384                 status = smbd_check_access_rights(conn,
1385                                 smb_fname,
1386                                 false,
1387                                 access_mask);
1388
1389                 if (NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND) &&
1390                                 (fsp->posix_flags & FSP_POSIX_FLAGS_OPEN) &&
1391                                 S_ISLNK(smb_fname->st.st_ex_mode)) {
1392                         /* This is a POSIX stat open for delete
1393                          * or rename on a symlink that points
1394                          * nowhere. Allow. */
1395                         DEBUG(10,("open_file: allowing POSIX "
1396                                   "open on bad symlink %s\n",
1397                                   smb_fname_str_dbg(smb_fname)));
1398                         status = NT_STATUS_OK;
1399                 }
1400
1401                 if (!NT_STATUS_IS_OK(status)) {
1402                         DEBUG(10,("open_file: "
1403                                 "smbd_check_access_rights on file "
1404                                 "%s returned %s\n",
1405                                 smb_fname_str_dbg(smb_fname),
1406                                 nt_errstr(status) ));
1407                         return status;
1408                 }
1409         }
1410
1411         /*
1412          * POSIX allows read-only opens of directories. We don't
1413          * want to do this (we use a different code path for this)
1414          * so catch a directory open and return an EISDIR. JRA.
1415          */
1416
1417         if(S_ISDIR(smb_fname->st.st_ex_mode)) {
1418                 fd_close(fsp);
1419                 errno = EISDIR;
1420                 return NT_STATUS_FILE_IS_A_DIRECTORY;
1421         }
1422
1423         fsp->file_id = vfs_file_id_from_sbuf(conn, &smb_fname->st);
1424         fsp->vuid = req ? req->vuid : UID_FIELD_INVALID;
1425         fsp->file_pid = req ? req->smbpid : 0;
1426         fsp->can_lock = True;
1427         fsp->can_read = ((access_mask & FILE_READ_DATA) != 0);
1428         fsp->can_write =
1429                 CAN_WRITE(conn) &&
1430                 ((access_mask & (FILE_WRITE_DATA | FILE_APPEND_DATA)) != 0);
1431         fsp->print_file = NULL;
1432         fsp->modified = False;
1433         fsp->sent_oplock_break = NO_BREAK_SENT;
1434         fsp->is_directory = False;
1435         if (conn->aio_write_behind_list &&
1436             is_in_path(smb_fname->base_name, conn->aio_write_behind_list,
1437                        conn->case_sensitive)) {
1438                 fsp->aio_write_behind = True;
1439         }
1440
1441         fsp->wcp = NULL; /* Write cache pointer. */
1442
1443         DEBUG(2,("%s opened file %s read=%s write=%s (numopen=%d)\n",
1444                  conn->session_info->unix_info->unix_name,
1445                  smb_fname_str_dbg(smb_fname),
1446                  BOOLSTR(fsp->can_read), BOOLSTR(fsp->can_write),
1447                  conn->num_files_open));
1448
1449         errno = 0;
1450         return NT_STATUS_OK;
1451 }
1452
1453 /****************************************************************************
1454  Check if we can open a file with a share mode.
1455  Returns True if conflict, False if not.
1456 ****************************************************************************/
1457
1458 static bool share_conflict(struct share_mode_entry *entry,
1459                            uint32_t access_mask,
1460                            uint32_t share_access)
1461 {
1462         DEBUG(10,("share_conflict: entry->access_mask = 0x%x, "
1463                   "entry->share_access = 0x%x, "
1464                   "entry->private_options = 0x%x\n",
1465                   (unsigned int)entry->access_mask,
1466                   (unsigned int)entry->share_access,
1467                   (unsigned int)entry->private_options));
1468
1469         if (server_id_is_disconnected(&entry->pid)) {
1470                 /*
1471                  * note: cleanup should have been done by
1472                  * delay_for_batch_oplocks()
1473                  */
1474                 return false;
1475         }
1476
1477         DEBUG(10,("share_conflict: access_mask = 0x%x, share_access = 0x%x\n",
1478                   (unsigned int)access_mask, (unsigned int)share_access));
1479
1480         if ((entry->access_mask & (FILE_WRITE_DATA|
1481                                    FILE_APPEND_DATA|
1482                                    FILE_READ_DATA|
1483                                    FILE_EXECUTE|
1484                                    DELETE_ACCESS)) == 0) {
1485                 DEBUG(10,("share_conflict: No conflict due to "
1486                           "entry->access_mask = 0x%x\n",
1487                           (unsigned int)entry->access_mask ));
1488                 return False;
1489         }
1490
1491         if ((access_mask & (FILE_WRITE_DATA|
1492                             FILE_APPEND_DATA|
1493                             FILE_READ_DATA|
1494                             FILE_EXECUTE|
1495                             DELETE_ACCESS)) == 0) {
1496                 DEBUG(10,("share_conflict: No conflict due to "
1497                           "access_mask = 0x%x\n",
1498                           (unsigned int)access_mask ));
1499                 return False;
1500         }
1501
1502 #if 1 /* JRA TEST - Superdebug. */
1503 #define CHECK_MASK(num, am, right, sa, share) \
1504         DEBUG(10,("share_conflict: [%d] am (0x%x) & right (0x%x) = 0x%x\n", \
1505                 (unsigned int)(num), (unsigned int)(am), \
1506                 (unsigned int)(right), (unsigned int)(am)&(right) )); \
1507         DEBUG(10,("share_conflict: [%d] sa (0x%x) & share (0x%x) = 0x%x\n", \
1508                 (unsigned int)(num), (unsigned int)(sa), \
1509                 (unsigned int)(share), (unsigned int)(sa)&(share) )); \
1510         if (((am) & (right)) && !((sa) & (share))) { \
1511                 DEBUG(10,("share_conflict: check %d conflict am = 0x%x, right = 0x%x, \
1512 sa = 0x%x, share = 0x%x\n", (num), (unsigned int)(am), (unsigned int)(right), (unsigned int)(sa), \
1513                         (unsigned int)(share) )); \
1514                 return True; \
1515         }
1516 #else
1517 #define CHECK_MASK(num, am, right, sa, share) \
1518         if (((am) & (right)) && !((sa) & (share))) { \
1519                 DEBUG(10,("share_conflict: check %d conflict am = 0x%x, right = 0x%x, \
1520 sa = 0x%x, share = 0x%x\n", (num), (unsigned int)(am), (unsigned int)(right), (unsigned int)(sa), \
1521                         (unsigned int)(share) )); \
1522                 return True; \
1523         }
1524 #endif
1525
1526         CHECK_MASK(1, entry->access_mask, FILE_WRITE_DATA | FILE_APPEND_DATA,
1527                    share_access, FILE_SHARE_WRITE);
1528         CHECK_MASK(2, access_mask, FILE_WRITE_DATA | FILE_APPEND_DATA,
1529                    entry->share_access, FILE_SHARE_WRITE);
1530
1531         CHECK_MASK(3, entry->access_mask, FILE_READ_DATA | FILE_EXECUTE,
1532                    share_access, FILE_SHARE_READ);
1533         CHECK_MASK(4, access_mask, FILE_READ_DATA | FILE_EXECUTE,
1534                    entry->share_access, FILE_SHARE_READ);
1535
1536         CHECK_MASK(5, entry->access_mask, DELETE_ACCESS,
1537                    share_access, FILE_SHARE_DELETE);
1538         CHECK_MASK(6, access_mask, DELETE_ACCESS,
1539                    entry->share_access, FILE_SHARE_DELETE);
1540
1541         DEBUG(10,("share_conflict: No conflict.\n"));
1542         return False;
1543 }
1544
1545 #if defined(DEVELOPER)
1546 static void validate_my_share_entries(struct smbd_server_connection *sconn,
1547                                       const struct file_id id,
1548                                       int num,
1549                                       struct share_mode_entry *share_entry)
1550 {
1551         struct server_id self = messaging_server_id(sconn->msg_ctx);
1552         files_struct *fsp;
1553
1554         if (!serverid_equal(&self, &share_entry->pid)) {
1555                 return;
1556         }
1557
1558         if (share_entry->op_mid == 0) {
1559                 /* INTERNAL_OPEN_ONLY */
1560                 return;
1561         }
1562
1563         if (!is_valid_share_mode_entry(share_entry)) {
1564                 return;
1565         }
1566
1567         fsp = file_find_dif(sconn, id, share_entry->share_file_id);
1568         if (!fsp) {
1569                 DBG_ERR("PANIC : %s\n",
1570                         share_mode_str(talloc_tos(), num, &id,
1571                                        share_entry));
1572                 smb_panic("validate_my_share_entries: Cannot match a "
1573                           "share entry with an open file\n");
1574         }
1575
1576         if (((uint16_t)fsp->oplock_type) != share_entry->op_type) {
1577                 goto panic;
1578         }
1579
1580         return;
1581
1582  panic:
1583         {
1584                 char *str;
1585                 DBG_ERR("validate_my_share_entries: PANIC : %s\n",
1586                         share_mode_str(talloc_tos(), num, &id,
1587                                        share_entry));
1588                 str = talloc_asprintf(talloc_tos(),
1589                         "validate_my_share_entries: "
1590                         "file %s, oplock_type = 0x%x, op_type = 0x%x\n",
1591                          fsp->fsp_name->base_name,
1592                          (unsigned int)fsp->oplock_type,
1593                          (unsigned int)share_entry->op_type );
1594                 smb_panic(str);
1595         }
1596 }
1597 #endif
1598
1599 bool is_stat_open(uint32_t access_mask)
1600 {
1601         const uint32_t stat_open_bits =
1602                 (SYNCHRONIZE_ACCESS|
1603                  FILE_READ_ATTRIBUTES|
1604                  FILE_WRITE_ATTRIBUTES);
1605
1606         return (((access_mask &  stat_open_bits) != 0) &&
1607                 ((access_mask & ~stat_open_bits) == 0));
1608 }
1609
1610 static bool has_delete_on_close(struct share_mode_lock *lck,
1611                                 uint32_t name_hash)
1612 {
1613         struct share_mode_data *d = lck->data;
1614         uint32_t i;
1615
1616         if (d->num_share_modes == 0) {
1617                 return false;
1618         }
1619         if (!is_delete_on_close_set(lck, name_hash)) {
1620                 return false;
1621         }
1622         for (i=0; i<d->num_share_modes; i++) {
1623                 if (!share_mode_stale_pid(d, i)) {
1624                         return true;
1625                 }
1626         }
1627         return false;
1628 }
1629
1630 /****************************************************************************
1631  Deal with share modes
1632  Invariant: Share mode must be locked on entry and exit.
1633  Returns -1 on error, or number of share modes on success (may be zero).
1634 ****************************************************************************/
1635
1636 static NTSTATUS open_mode_check(connection_struct *conn,
1637                                 struct share_mode_lock *lck,
1638                                 uint32_t access_mask,
1639                                 uint32_t share_access)
1640 {
1641         uint32_t i;
1642
1643         if(lck->data->num_share_modes == 0) {
1644                 return NT_STATUS_OK;
1645         }
1646
1647         if (is_stat_open(access_mask)) {
1648                 /* Stat open that doesn't trigger oplock breaks or share mode
1649                  * checks... ! JRA. */
1650                 return NT_STATUS_OK;
1651         }
1652
1653         /*
1654          * Check if the share modes will give us access.
1655          */
1656
1657 #if defined(DEVELOPER)
1658         for(i = 0; i < lck->data->num_share_modes; i++) {
1659                 validate_my_share_entries(conn->sconn, lck->data->id, i,
1660                                           &lck->data->share_modes[i]);
1661         }
1662 #endif
1663
1664         /* Now we check the share modes, after any oplock breaks. */
1665         for(i = 0; i < lck->data->num_share_modes; i++) {
1666
1667                 if (!is_valid_share_mode_entry(&lck->data->share_modes[i])) {
1668                         continue;
1669                 }
1670
1671                 /* someone else has a share lock on it, check to see if we can
1672                  * too */
1673                 if (share_conflict(&lck->data->share_modes[i],
1674                                    access_mask, share_access)) {
1675
1676                         if (share_mode_stale_pid(lck->data, i)) {
1677                                 continue;
1678                         }
1679
1680                         return NT_STATUS_SHARING_VIOLATION;
1681                 }
1682         }
1683
1684         return NT_STATUS_OK;
1685 }
1686
1687 /*
1688  * Send a break message to the oplock holder and delay the open for
1689  * our client.
1690  */
1691
1692 NTSTATUS send_break_message(struct messaging_context *msg_ctx,
1693                             const struct file_id *id,
1694                             const struct share_mode_entry *exclusive,
1695                             uint16_t break_to)
1696 {
1697         NTSTATUS status;
1698         char msg[MSG_SMB_SHARE_MODE_ENTRY_SIZE];
1699         struct server_id_buf tmp;
1700
1701         DEBUG(10, ("Sending break request to PID %s\n",
1702                    server_id_str_buf(exclusive->pid, &tmp)));
1703
1704         /* Create the message. */
1705         share_mode_entry_to_message(msg, id, exclusive);
1706
1707         /* Overload entry->op_type */
1708         /*
1709          * This is a cut from uint32_t to uint16_t, but so far only the lower 3
1710          * bits (LEASE_WRITE/HANDLE/READ are used anyway.
1711          */
1712         SSVAL(msg,OP_BREAK_MSG_OP_TYPE_OFFSET, break_to);
1713
1714         status = messaging_send_buf(msg_ctx, exclusive->pid,
1715                                     MSG_SMB_BREAK_REQUEST,
1716                                     (uint8_t *)msg, sizeof(msg));
1717         if (!NT_STATUS_IS_OK(status)) {
1718                 DEBUG(3, ("Could not send oplock break message: %s\n",
1719                           nt_errstr(status)));
1720         }
1721
1722         return status;
1723 }
1724
1725 /*
1726  * Do internal consistency checks on the share mode for a file.
1727  */
1728
1729 static bool validate_oplock_types(struct share_mode_lock *lck)
1730 {
1731         struct share_mode_data *d = lck->data;
1732         bool batch = false;
1733         bool ex_or_batch = false;
1734         bool level2 = false;
1735         bool no_oplock = false;
1736         uint32_t num_non_stat_opens = 0;
1737         uint32_t i;
1738
1739         for (i=0; i<d->num_share_modes; i++) {
1740                 struct share_mode_entry *e = &d->share_modes[i];
1741
1742                 if (!is_valid_share_mode_entry(e)) {
1743                         continue;
1744                 }
1745
1746                 if (e->op_mid == 0) {
1747                         /* INTERNAL_OPEN_ONLY */
1748                         continue;
1749                 }
1750
1751                 if (e->op_type == NO_OPLOCK && is_stat_open(e->access_mask)) {
1752                         /* We ignore stat opens in the table - they
1753                            always have NO_OPLOCK and never get or
1754                            cause breaks. JRA. */
1755                         continue;
1756                 }
1757
1758                 num_non_stat_opens += 1;
1759
1760                 if (BATCH_OPLOCK_TYPE(e->op_type)) {
1761                         /* batch - can only be one. */
1762                         if (share_mode_stale_pid(d, i)) {
1763                                 DEBUG(10, ("Found stale batch oplock\n"));
1764                                 continue;
1765                         }
1766                         if (ex_or_batch || batch || level2 || no_oplock) {
1767                                 DEBUG(0, ("Bad batch oplock entry %u.",
1768                                           (unsigned)i));
1769                                 return false;
1770                         }
1771                         batch = true;
1772                 }
1773
1774                 if (EXCLUSIVE_OPLOCK_TYPE(e->op_type)) {
1775                         if (share_mode_stale_pid(d, i)) {
1776                                 DEBUG(10, ("Found stale duplicate oplock\n"));
1777                                 continue;
1778                         }
1779                         /* Exclusive or batch - can only be one. */
1780                         if (ex_or_batch || level2 || no_oplock) {
1781                                 DEBUG(0, ("Bad exclusive or batch oplock "
1782                                           "entry %u.", (unsigned)i));
1783                                 return false;
1784                         }
1785                         ex_or_batch = true;
1786                 }
1787
1788                 if (LEVEL_II_OPLOCK_TYPE(e->op_type)) {
1789                         if (batch || ex_or_batch) {
1790                                 if (share_mode_stale_pid(d, i)) {
1791                                         DEBUG(10, ("Found stale LevelII "
1792                                                    "oplock\n"));
1793                                         continue;
1794                                 }
1795                                 DEBUG(0, ("Bad levelII oplock entry %u.",
1796                                           (unsigned)i));
1797                                 return false;
1798                         }
1799                         level2 = true;
1800                 }
1801
1802                 if (e->op_type == NO_OPLOCK) {
1803                         if (batch || ex_or_batch) {
1804                                 if (share_mode_stale_pid(d, i)) {
1805                                         DEBUG(10, ("Found stale NO_OPLOCK "
1806                                                    "entry\n"));
1807                                         continue;
1808                                 }
1809                                 DEBUG(0, ("Bad no oplock entry %u.",
1810                                           (unsigned)i));
1811                                 return false;
1812                         }
1813                         no_oplock = true;
1814                 }
1815         }
1816
1817         remove_stale_share_mode_entries(d);
1818
1819         if ((batch || ex_or_batch) && (num_non_stat_opens != 1)) {
1820                 DEBUG(1, ("got batch (%d) or ex (%d) non-exclusively (%d)\n",
1821                           (int)batch, (int)ex_or_batch,
1822                           (int)d->num_share_modes));
1823                 return false;
1824         }
1825
1826         return true;
1827 }
1828
1829 static bool delay_for_oplock(files_struct *fsp,
1830                              int oplock_request,
1831                              const struct smb2_lease *lease,
1832                              struct share_mode_lock *lck,
1833                              bool have_sharing_violation,
1834                              uint32_t create_disposition,
1835                              bool first_open_attempt)
1836 {
1837         struct share_mode_data *d = lck->data;
1838         uint32_t i;
1839         bool delay = false;
1840         bool will_overwrite;
1841
1842         if ((oplock_request & INTERNAL_OPEN_ONLY) ||
1843             is_stat_open(fsp->access_mask)) {
1844                 return false;
1845         }
1846
1847         switch (create_disposition) {
1848         case FILE_SUPERSEDE:
1849         case FILE_OVERWRITE:
1850         case FILE_OVERWRITE_IF:
1851                 will_overwrite = true;
1852                 break;
1853         default:
1854                 will_overwrite = false;
1855                 break;
1856         }
1857
1858         for (i=0; i<d->num_share_modes; i++) {
1859                 struct share_mode_entry *e = &d->share_modes[i];
1860                 struct share_mode_lease *l = NULL;
1861                 uint32_t e_lease_type = get_lease_type(d, e);
1862                 uint32_t break_to;
1863                 uint32_t delay_mask = 0;
1864
1865                 if (e->op_type == LEASE_OPLOCK) {
1866                         l = &d->leases[e->lease_idx];
1867                 }
1868
1869                 if (have_sharing_violation) {
1870                         delay_mask = SMB2_LEASE_HANDLE;
1871                 } else {
1872                         delay_mask = SMB2_LEASE_WRITE;
1873                 }
1874
1875                 break_to = e_lease_type & ~delay_mask;
1876
1877                 if (will_overwrite) {
1878                         /*
1879                          * we'll decide about SMB2_LEASE_READ later.
1880                          *
1881                          * Maybe the break will be deferred
1882                          */
1883                         break_to &= ~SMB2_LEASE_HANDLE;
1884                 }
1885
1886                 DEBUG(10, ("entry %u: e_lease_type %u, will_overwrite: %u\n",
1887                            (unsigned)i, (unsigned)e_lease_type,
1888                            (unsigned)will_overwrite));
1889
1890                 if (lease != NULL && l != NULL) {
1891                         bool ign;
1892
1893                         ign = smb2_lease_equal(fsp_client_guid(fsp),
1894                                                &lease->lease_key,
1895                                                &l->client_guid,
1896                                                &l->lease_key);
1897                         if (ign) {
1898                                 continue;
1899                         }
1900                 }
1901
1902                 if ((e_lease_type & ~break_to) == 0) {
1903                         if (l != NULL && l->breaking) {
1904                                 delay = true;
1905                         }
1906                         continue;
1907                 }
1908
1909                 if (share_mode_stale_pid(d, i)) {
1910                         continue;
1911                 }
1912
1913                 if (will_overwrite) {
1914                         /*
1915                          * If we break anyway break to NONE directly.
1916                          * Otherwise vfs_set_filelen() will trigger the
1917                          * break.
1918                          */
1919                         break_to &= ~(SMB2_LEASE_READ|SMB2_LEASE_WRITE);
1920                 }
1921
1922                 if (e->op_type != LEASE_OPLOCK) {
1923                         /*
1924                          * Oplocks only support breaking to R or NONE.
1925                          */
1926                         break_to &= ~(SMB2_LEASE_HANDLE|SMB2_LEASE_WRITE);
1927                 }
1928
1929                 DEBUG(10, ("breaking from %d to %d\n",
1930                            (int)e_lease_type, (int)break_to));
1931                 send_break_message(fsp->conn->sconn->msg_ctx, &fsp->file_id,
1932                                    e, break_to);
1933                 if (e_lease_type & delay_mask) {
1934                         delay = true;
1935                 }
1936                 if (l != NULL && l->breaking && !first_open_attempt) {
1937                         delay = true;
1938                 }
1939                 continue;
1940         }
1941
1942         return delay;
1943 }
1944
1945 static bool file_has_brlocks(files_struct *fsp)
1946 {
1947         struct byte_range_lock *br_lck;
1948
1949         br_lck = brl_get_locks_readonly(fsp);
1950         if (!br_lck)
1951                 return false;
1952
1953         return (brl_num_locks(br_lck) > 0);
1954 }
1955
1956 int find_share_mode_lease(struct share_mode_data *d,
1957                           const struct GUID *client_guid,
1958                           const struct smb2_lease_key *key)
1959 {
1960         uint32_t i;
1961
1962         for (i=0; i<d->num_leases; i++) {
1963                 struct share_mode_lease *l = &d->leases[i];
1964
1965                 if (smb2_lease_equal(client_guid,
1966                                      key,
1967                                      &l->client_guid,
1968                                      &l->lease_key)) {
1969                         return i;
1970                 }
1971         }
1972
1973         return -1;
1974 }
1975
1976 struct fsp_lease *find_fsp_lease(struct files_struct *new_fsp,
1977                                  const struct smb2_lease_key *key,
1978                                  const struct share_mode_lease *l)
1979 {
1980         struct files_struct *fsp;
1981
1982         /*
1983          * TODO: Measure how expensive this loop is with thousands of open
1984          * handles...
1985          */
1986
1987         for (fsp = file_find_di_first(new_fsp->conn->sconn, new_fsp->file_id);
1988              fsp != NULL;
1989              fsp = file_find_di_next(fsp)) {
1990
1991                 if (fsp == new_fsp) {
1992                         continue;
1993                 }
1994                 if (fsp->oplock_type != LEASE_OPLOCK) {
1995                         continue;
1996                 }
1997                 if (smb2_lease_key_equal(&fsp->lease->lease.lease_key, key)) {
1998                         fsp->lease->ref_count += 1;
1999                         return fsp->lease;
2000                 }
2001         }
2002
2003         /* Not found - must be leased in another smbd. */
2004         new_fsp->lease = talloc_zero(new_fsp->conn->sconn, struct fsp_lease);
2005         if (new_fsp->lease == NULL) {
2006                 return NULL;
2007         }
2008         new_fsp->lease->ref_count = 1;
2009         new_fsp->lease->sconn = new_fsp->conn->sconn;
2010         new_fsp->lease->lease.lease_key = *key;
2011         new_fsp->lease->lease.lease_state = l->current_state;
2012         /*
2013          * We internally treat all leases as V2 and update
2014          * the epoch, but when sending breaks it matters if
2015          * the requesting lease was v1 or v2.
2016          */
2017         new_fsp->lease->lease.lease_version = l->lease_version;
2018         new_fsp->lease->lease.lease_epoch = l->epoch;
2019         return new_fsp->lease;
2020 }
2021
2022 static NTSTATUS grant_fsp_lease(struct files_struct *fsp,
2023                                 struct share_mode_lock *lck,
2024                                 const struct smb2_lease *lease,
2025                                 uint32_t *p_lease_idx,
2026                                 uint32_t granted)
2027 {
2028         struct share_mode_data *d = lck->data;
2029         const struct GUID *client_guid = fsp_client_guid(fsp);
2030         struct share_mode_lease *tmp;
2031         NTSTATUS status;
2032         int idx;
2033
2034         idx = find_share_mode_lease(d, client_guid, &lease->lease_key);
2035
2036         if (idx != -1) {
2037                 struct share_mode_lease *l = &d->leases[idx];
2038                 bool do_upgrade;
2039                 uint32_t existing, requested;
2040
2041                 fsp->lease = find_fsp_lease(fsp, &lease->lease_key, l);
2042                 if (fsp->lease == NULL) {
2043                         DEBUG(1, ("Did not find existing lease for file %s\n",
2044                                   fsp_str_dbg(fsp)));
2045                         return NT_STATUS_NO_MEMORY;
2046                 }
2047
2048                 *p_lease_idx = idx;
2049
2050                 /*
2051                  * Upgrade only if the requested lease is a strict upgrade.
2052                  */
2053                 existing = l->current_state;
2054                 requested = lease->lease_state;
2055
2056                 /*
2057                  * Tricky: This test makes sure that "requested" is a
2058                  * strict bitwise superset of "existing".
2059                  */
2060                 do_upgrade = ((existing & requested) == existing);
2061
2062                 /*
2063                  * Upgrade only if there's a change.
2064                  */
2065                 do_upgrade &= (granted != existing);
2066
2067                 /*
2068                  * Upgrade only if other leases don't prevent what was asked
2069                  * for.
2070                  */
2071                 do_upgrade &= (granted == requested);
2072
2073                 /*
2074                  * only upgrade if we are not in breaking state
2075                  */
2076                 do_upgrade &= !l->breaking;
2077
2078                 DEBUG(10, ("existing=%"PRIu32", requested=%"PRIu32", "
2079                            "granted=%"PRIu32", do_upgrade=%d\n",
2080                            existing, requested, granted, (int)do_upgrade));
2081
2082                 if (do_upgrade) {
2083                         l->current_state = granted;
2084                         l->epoch += 1;
2085                 }
2086
2087                 /* Ensure we're in sync with current lease state. */
2088                 fsp_lease_update(lck, fsp_client_guid(fsp), fsp->lease);
2089                 return NT_STATUS_OK;
2090         }
2091
2092         /*
2093          * Create new lease
2094          */
2095
2096         tmp = talloc_realloc(d, d->leases, struct share_mode_lease,
2097                              d->num_leases+1);
2098         if (tmp == NULL) {
2099                 /*
2100                  * See [MS-SMB2]
2101                  */
2102                 return NT_STATUS_INSUFFICIENT_RESOURCES;
2103         }
2104         d->leases = tmp;
2105
2106         fsp->lease = talloc_zero(fsp->conn->sconn, struct fsp_lease);
2107         if (fsp->lease == NULL) {
2108                 return NT_STATUS_INSUFFICIENT_RESOURCES;
2109         }
2110         fsp->lease->ref_count = 1;
2111         fsp->lease->sconn = fsp->conn->sconn;
2112         fsp->lease->lease.lease_version = lease->lease_version;
2113         fsp->lease->lease.lease_key = lease->lease_key;
2114         fsp->lease->lease.lease_state = granted;
2115         fsp->lease->lease.lease_epoch = lease->lease_epoch + 1;
2116
2117         *p_lease_idx = d->num_leases;
2118
2119         d->leases[d->num_leases] = (struct share_mode_lease) {
2120                 .client_guid = *client_guid,
2121                 .lease_key = fsp->lease->lease.lease_key,
2122                 .current_state = fsp->lease->lease.lease_state,
2123                 .lease_version = fsp->lease->lease.lease_version,
2124                 .epoch = fsp->lease->lease.lease_epoch,
2125         };
2126
2127         status = leases_db_add(client_guid,
2128                                &lease->lease_key,
2129                                &fsp->file_id,
2130                                fsp->conn->connectpath,
2131                                fsp->fsp_name->base_name,
2132                                fsp->fsp_name->stream_name);
2133         if (!NT_STATUS_IS_OK(status)) {
2134                 DEBUG(10, ("%s: leases_db_add failed: %s\n", __func__,
2135                            nt_errstr(status)));
2136                 TALLOC_FREE(fsp->lease);
2137                 return NT_STATUS_INSUFFICIENT_RESOURCES;
2138         }
2139
2140         d->num_leases += 1;
2141         d->modified = true;
2142
2143         return NT_STATUS_OK;
2144 }
2145
2146 static bool is_same_lease(const files_struct *fsp,
2147                           const struct share_mode_data *d,
2148                           const struct share_mode_entry *e,
2149                           const struct smb2_lease *lease)
2150 {
2151         if (e->op_type != LEASE_OPLOCK) {
2152                 return false;
2153         }
2154         if (lease == NULL) {
2155                 return false;
2156         }
2157
2158         return smb2_lease_equal(fsp_client_guid(fsp),
2159                                 &lease->lease_key,
2160                                 &d->leases[e->lease_idx].client_guid,
2161                                 &d->leases[e->lease_idx].lease_key);
2162 }
2163
2164 static NTSTATUS grant_fsp_oplock_type(struct smb_request *req,
2165                                       struct files_struct *fsp,
2166                                       struct share_mode_lock *lck,
2167                                       int oplock_request,
2168                                       struct smb2_lease *lease)
2169 {
2170         struct share_mode_data *d = lck->data;
2171         bool got_handle_lease = false;
2172         bool got_oplock = false;
2173         uint32_t i;
2174         uint32_t granted;
2175         uint32_t lease_idx = UINT32_MAX;
2176         bool ok;
2177         NTSTATUS status;
2178
2179         if (oplock_request & INTERNAL_OPEN_ONLY) {
2180                 /* No oplocks on internal open. */
2181                 oplock_request = NO_OPLOCK;
2182                 DEBUG(10,("grant_fsp_oplock_type: oplock type 0x%x on file %s\n",
2183                         fsp->oplock_type, fsp_str_dbg(fsp)));
2184         }
2185
2186         if (oplock_request == LEASE_OPLOCK) {
2187                 if (lease == NULL) {
2188                         /*
2189                          * The SMB2 layer should have checked this
2190                          */
2191                         return NT_STATUS_INTERNAL_ERROR;
2192                 }
2193
2194                 granted = lease->lease_state;
2195
2196                 if (lp_kernel_oplocks(SNUM(fsp->conn))) {
2197                         DEBUG(10, ("No lease granted because kernel oplocks are enabled\n"));
2198                         granted = SMB2_LEASE_NONE;
2199                 }
2200                 if ((granted & (SMB2_LEASE_READ|SMB2_LEASE_WRITE)) == 0) {
2201                         DEBUG(10, ("No read or write lease requested\n"));
2202                         granted = SMB2_LEASE_NONE;
2203                 }
2204                 if (granted == SMB2_LEASE_WRITE) {
2205                         DEBUG(10, ("pure write lease requested\n"));
2206                         granted = SMB2_LEASE_NONE;
2207                 }
2208                 if (granted == (SMB2_LEASE_WRITE|SMB2_LEASE_HANDLE)) {
2209                         DEBUG(10, ("write and handle lease requested\n"));
2210                         granted = SMB2_LEASE_NONE;
2211                 }
2212         } else {
2213                 granted = map_oplock_to_lease_type(
2214                         oplock_request & ~SAMBA_PRIVATE_OPLOCK_MASK);
2215         }
2216
2217         if (lp_locking(fsp->conn->params) && file_has_brlocks(fsp)) {
2218                 DEBUG(10,("grant_fsp_oplock_type: file %s has byte range locks\n",
2219                         fsp_str_dbg(fsp)));
2220                 granted &= ~SMB2_LEASE_READ;
2221         }
2222
2223         for (i=0; i<d->num_share_modes; i++) {
2224                 struct share_mode_entry *e = &d->share_modes[i];
2225                 uint32_t e_lease_type;
2226
2227                 e_lease_type = get_lease_type(d, e);
2228
2229                 if ((granted & SMB2_LEASE_WRITE) &&
2230                     !is_same_lease(fsp, d, e, lease) &&
2231                     !share_mode_stale_pid(d, i)) {
2232                         /*
2233                          * Can grant only one writer
2234                          */
2235                         granted &= ~SMB2_LEASE_WRITE;
2236                 }
2237
2238                 if ((e_lease_type & SMB2_LEASE_HANDLE) && !got_handle_lease &&
2239                     !share_mode_stale_pid(d, i)) {
2240                         got_handle_lease = true;
2241                 }
2242
2243                 if ((e->op_type != LEASE_OPLOCK) && !got_oplock &&
2244                     !share_mode_stale_pid(d, i)) {
2245                         got_oplock = true;
2246                 }
2247         }
2248
2249         if ((granted & SMB2_LEASE_READ) && !(granted & SMB2_LEASE_WRITE)) {
2250                 bool allow_level2 =
2251                         (global_client_caps & CAP_LEVEL_II_OPLOCKS) &&
2252                         lp_level2_oplocks(SNUM(fsp->conn));
2253
2254                 if (!allow_level2) {
2255                         granted = SMB2_LEASE_NONE;
2256                 }
2257         }
2258
2259         if (oplock_request == LEASE_OPLOCK) {
2260                 if (got_oplock) {
2261                         granted &= ~SMB2_LEASE_HANDLE;
2262                 }
2263
2264                 fsp->oplock_type = LEASE_OPLOCK;
2265
2266                 status = grant_fsp_lease(fsp, lck, lease, &lease_idx,
2267                                          granted);
2268                 if (!NT_STATUS_IS_OK(status)) {
2269                         return status;
2270
2271                 }
2272                 *lease = fsp->lease->lease;
2273                 DEBUG(10, ("lease_state=%d\n", lease->lease_state));
2274         } else {
2275                 if (got_handle_lease) {
2276                         granted = SMB2_LEASE_NONE;
2277                 }
2278
2279                 switch (granted) {
2280                 case SMB2_LEASE_READ|SMB2_LEASE_WRITE|SMB2_LEASE_HANDLE:
2281                         fsp->oplock_type = BATCH_OPLOCK|EXCLUSIVE_OPLOCK;
2282                         break;
2283                 case SMB2_LEASE_READ|SMB2_LEASE_WRITE:
2284                         fsp->oplock_type = EXCLUSIVE_OPLOCK;
2285                         break;
2286                 case SMB2_LEASE_READ|SMB2_LEASE_HANDLE:
2287                 case SMB2_LEASE_READ:
2288                         fsp->oplock_type = LEVEL_II_OPLOCK;
2289                         break;
2290                 default:
2291                         fsp->oplock_type = NO_OPLOCK;
2292                         break;
2293                 }
2294
2295                 status = set_file_oplock(fsp);
2296                 if (!NT_STATUS_IS_OK(status)) {
2297                         /*
2298                          * Could not get the kernel oplock
2299                          */
2300                         fsp->oplock_type = NO_OPLOCK;
2301                 }
2302         }
2303
2304         ok = set_share_mode(lck, fsp, get_current_uid(fsp->conn),
2305                             req ? req->mid : 0,
2306                             fsp->oplock_type,
2307                             lease_idx);
2308         if (!ok) {
2309                 return NT_STATUS_NO_MEMORY;
2310         }
2311
2312         ok = update_num_read_oplocks(fsp, lck);
2313         if (!ok) {
2314                 del_share_mode(lck, fsp);
2315                 return NT_STATUS_INTERNAL_ERROR;
2316         }
2317
2318         DEBUG(10,("grant_fsp_oplock_type: oplock type 0x%x on file %s\n",
2319                   fsp->oplock_type, fsp_str_dbg(fsp)));
2320
2321         return NT_STATUS_OK;
2322 }
2323
2324 static bool request_timed_out(struct timeval request_time,
2325                               struct timeval timeout)
2326 {
2327         struct timeval now, end_time;
2328         GetTimeOfDay(&now);
2329         end_time = timeval_sum(&request_time, &timeout);
2330         return (timeval_compare(&end_time, &now) < 0);
2331 }
2332
2333 static struct deferred_open_record *deferred_open_record_create(
2334         bool delayed_for_oplocks,
2335         bool async_open,
2336         struct file_id id)
2337 {
2338         struct deferred_open_record *record = NULL;
2339
2340         record = talloc(NULL, struct deferred_open_record);
2341         if (record == NULL) {
2342                 return NULL;
2343         }
2344
2345         *record = (struct deferred_open_record) {
2346                 .delayed_for_oplocks = delayed_for_oplocks,
2347                 .async_open = async_open,
2348                 .id = id,
2349         };
2350
2351         return record;
2352 }
2353
2354 struct defer_open_state {
2355         struct smbXsrv_connection *xconn;
2356         uint64_t mid;
2357 };
2358
2359 static void defer_open_done(struct tevent_req *req);
2360
2361 /**
2362  * Defer an open and watch a locking.tdb record
2363  *
2364  * This defers an open that gets rescheduled once the locking.tdb record watch
2365  * is triggered by a change to the record.
2366  *
2367  * It is used to defer opens that triggered an oplock break and for the SMB1
2368  * sharing violation delay.
2369  **/
2370 static void defer_open(struct share_mode_lock *lck,
2371                        struct timeval request_time,
2372                        struct timeval timeout,
2373                        struct smb_request *req,
2374                        bool delayed_for_oplocks,
2375                        struct file_id id)
2376 {
2377         struct deferred_open_record *open_rec = NULL;
2378         struct timeval abs_timeout;
2379         struct defer_open_state *watch_state;
2380         struct tevent_req *watch_req;
2381         bool ok;
2382
2383         abs_timeout = timeval_sum(&request_time, &timeout);
2384
2385         DBG_DEBUG("request time [%s] timeout [%s] mid [%" PRIu64 "] "
2386                   "delayed_for_oplocks [%s] file_id [%s]\n",
2387                   timeval_string(talloc_tos(), &request_time, false),
2388                   timeval_string(talloc_tos(), &abs_timeout, false),
2389                   req->mid,
2390                   delayed_for_oplocks ? "yes" : "no",
2391                   file_id_string_tos(&id));
2392
2393         open_rec = deferred_open_record_create(delayed_for_oplocks,
2394                                                false,
2395                                                id);
2396         if (open_rec == NULL) {
2397                 TALLOC_FREE(lck);
2398                 exit_server("talloc failed");
2399         }
2400
2401         watch_state = talloc(open_rec, struct defer_open_state);
2402         if (watch_state == NULL) {
2403                 exit_server("talloc failed");
2404         }
2405         watch_state->xconn = req->xconn;
2406         watch_state->mid = req->mid;
2407
2408         DBG_DEBUG("defering mid %" PRIu64 "\n", req->mid);
2409
2410         watch_req = dbwrap_watched_watch_send(watch_state,
2411                                               req->ev_ctx,
2412                                               lck->data->record,
2413                                               (struct server_id){0});
2414         if (watch_req == NULL) {
2415                 exit_server("Could not watch share mode record");
2416         }
2417         tevent_req_set_callback(watch_req, defer_open_done, watch_state);
2418
2419         ok = tevent_req_set_endtime(watch_req, req->ev_ctx, abs_timeout);
2420         if (!ok) {
2421                 exit_server("tevent_req_set_endtime failed");
2422         }
2423
2424         ok = push_deferred_open_message_smb(req, request_time, timeout,
2425                                             open_rec->id, open_rec);
2426         if (!ok) {
2427                 TALLOC_FREE(lck);
2428                 exit_server("push_deferred_open_message_smb failed");
2429         }
2430 }
2431
2432 static void defer_open_done(struct tevent_req *req)
2433 {
2434         struct defer_open_state *state = tevent_req_callback_data(
2435                 req, struct defer_open_state);
2436         NTSTATUS status;
2437         bool ret;
2438
2439         status = dbwrap_watched_watch_recv(req, NULL, NULL);
2440         TALLOC_FREE(req);
2441         if (!NT_STATUS_IS_OK(status)) {
2442                 DEBUG(5, ("dbwrap_watched_watch_recv returned %s\n",
2443                           nt_errstr(status)));
2444                 /*
2445                  * Even if it failed, retry anyway. TODO: We need a way to
2446                  * tell a re-scheduled open about that error.
2447                  */
2448         }
2449
2450         DEBUG(10, ("scheduling mid %llu\n", (unsigned long long)state->mid));
2451
2452         ret = schedule_deferred_open_message_smb(state->xconn, state->mid);
2453         SMB_ASSERT(ret);
2454         TALLOC_FREE(state);
2455 }
2456
2457 /**
2458  * Actually attempt the kernel oplock polling open.
2459  */
2460
2461 static void kernel_oplock_poll_open_timer(struct tevent_context *ev,
2462                                       struct tevent_timer *te,
2463                                       struct timeval current_time,
2464                                       void *private_data)
2465 {
2466         bool ok;
2467         struct smb_request *req = (struct smb_request *)private_data;
2468
2469         ok = schedule_deferred_open_message_smb(req->xconn, req->mid);
2470         if (!ok) {
2471                 exit_server("schedule_deferred_open_message_smb failed");
2472         }
2473         DBG_DEBUG("kernel_oplock_poll_open_timer fired. Retying open !\n");
2474 }
2475
2476 /**
2477  * Reschedule an open for 1 second from now, if not timed out.
2478  **/
2479 static void setup_kernel_oplock_poll_open(struct timeval request_time,
2480                        struct smb_request *req,
2481                        struct file_id id)
2482 {
2483
2484         bool ok;
2485         struct deferred_open_record *open_rec = NULL;
2486         /* Maximum wait time. */
2487         struct timeval timeout = timeval_set(OPLOCK_BREAK_TIMEOUT*2, 0);
2488
2489         if (request_timed_out(request_time, timeout)) {
2490                 return;
2491         }
2492
2493         open_rec = deferred_open_record_create(false, false, id);
2494         if (open_rec == NULL) {
2495                 exit_server("talloc failed");
2496         }
2497
2498         ok = push_deferred_open_message_smb(req,
2499                                             request_time,
2500                                             timeout,
2501                                             id,
2502                                             open_rec);
2503         if (!ok) {
2504                 exit_server("push_deferred_open_message_smb failed");
2505         }
2506
2507         /*
2508          * As this timer event is owned by req, it will
2509          * disappear if req it talloc_freed.
2510          */
2511         open_rec->te = tevent_add_timer(req->ev_ctx,
2512                                         req,
2513                                         timeval_current_ofs(1, 0),
2514                                         kernel_oplock_poll_open_timer,
2515                                         req);
2516         if (open_rec->te == NULL) {
2517                 exit_server("tevent_add_timer failed");
2518         }
2519
2520         DBG_DEBUG("poll request time [%s] mid [%" PRIu64 "] file_id [%s]\n",
2521                   timeval_string(talloc_tos(), &request_time, false),
2522                   req->mid,
2523                   file_id_string_tos(&id));
2524 }
2525
2526 /****************************************************************************
2527  On overwrite open ensure that the attributes match.
2528 ****************************************************************************/
2529
2530 static bool open_match_attributes(connection_struct *conn,
2531                                   uint32_t old_dos_attr,
2532                                   uint32_t new_dos_attr,
2533                                   mode_t new_unx_mode,
2534                                   mode_t *returned_unx_mode)
2535 {
2536         uint32_t noarch_old_dos_attr, noarch_new_dos_attr;
2537
2538         noarch_old_dos_attr = (old_dos_attr & ~FILE_ATTRIBUTE_ARCHIVE);
2539         noarch_new_dos_attr = (new_dos_attr & ~FILE_ATTRIBUTE_ARCHIVE);
2540
2541         if((noarch_old_dos_attr == 0 && noarch_new_dos_attr != 0) || 
2542            (noarch_old_dos_attr != 0 && ((noarch_old_dos_attr & noarch_new_dos_attr) == noarch_old_dos_attr))) {
2543                 *returned_unx_mode = new_unx_mode;
2544         } else {
2545                 *returned_unx_mode = (mode_t)0;
2546         }
2547
2548         DEBUG(10,("open_match_attributes: old_dos_attr = 0x%x, "
2549                   "new_dos_attr = 0x%x "
2550                   "returned_unx_mode = 0%o\n",
2551                   (unsigned int)old_dos_attr,
2552                   (unsigned int)new_dos_attr,
2553                   (unsigned int)*returned_unx_mode ));
2554
2555         /* If we're mapping SYSTEM and HIDDEN ensure they match. */
2556         if (lp_map_system(SNUM(conn)) || lp_store_dos_attributes(SNUM(conn))) {
2557                 if ((old_dos_attr & FILE_ATTRIBUTE_SYSTEM) &&
2558                     !(new_dos_attr & FILE_ATTRIBUTE_SYSTEM)) {
2559                         return False;
2560                 }
2561         }
2562         if (lp_map_hidden(SNUM(conn)) || lp_store_dos_attributes(SNUM(conn))) {
2563                 if ((old_dos_attr & FILE_ATTRIBUTE_HIDDEN) &&
2564                     !(new_dos_attr & FILE_ATTRIBUTE_HIDDEN)) {
2565                         return False;
2566                 }
2567         }
2568         return True;
2569 }
2570
2571 /****************************************************************************
2572  Special FCB or DOS processing in the case of a sharing violation.
2573  Try and find a duplicated file handle.
2574 ****************************************************************************/
2575
2576 static NTSTATUS fcb_or_dos_open(struct smb_request *req,
2577                                 connection_struct *conn,
2578                                 files_struct *fsp_to_dup_into,
2579                                 const struct smb_filename *smb_fname,
2580                                 struct file_id id,
2581                                 uint16_t file_pid,
2582                                 uint64_t vuid,
2583                                 uint32_t access_mask,
2584                                 uint32_t share_access,
2585                                 uint32_t create_options)
2586 {
2587         files_struct *fsp;
2588
2589         DEBUG(5,("fcb_or_dos_open: attempting old open semantics for "
2590                  "file %s.\n", smb_fname_str_dbg(smb_fname)));
2591
2592         for(fsp = file_find_di_first(conn->sconn, id); fsp;
2593             fsp = file_find_di_next(fsp)) {
2594
2595                 DEBUG(10,("fcb_or_dos_open: checking file %s, fd = %d, "
2596                           "vuid = %llu, file_pid = %u, private_options = 0x%x "
2597                           "access_mask = 0x%x\n", fsp_str_dbg(fsp),
2598                           fsp->fh->fd, (unsigned long long)fsp->vuid,
2599                           (unsigned int)fsp->file_pid,
2600                           (unsigned int)fsp->fh->private_options,
2601                           (unsigned int)fsp->access_mask ));
2602
2603                 if (fsp != fsp_to_dup_into &&
2604                     fsp->fh->fd != -1 &&
2605                     fsp->vuid == vuid &&
2606                     fsp->file_pid == file_pid &&
2607                     (fsp->fh->private_options & (NTCREATEX_OPTIONS_PRIVATE_DENY_DOS |
2608                                                  NTCREATEX_OPTIONS_PRIVATE_DENY_FCB)) &&
2609                     (fsp->access_mask & FILE_WRITE_DATA) &&
2610                     strequal(fsp->fsp_name->base_name, smb_fname->base_name) &&
2611                     strequal(fsp->fsp_name->stream_name,
2612                              smb_fname->stream_name)) {
2613                         DEBUG(10,("fcb_or_dos_open: file match\n"));
2614                         break;
2615                 }
2616         }
2617
2618         if (!fsp) {
2619                 return NT_STATUS_NOT_FOUND;
2620         }
2621
2622         /* quite an insane set of semantics ... */
2623         if (is_executable(smb_fname->base_name) &&
2624             (fsp->fh->private_options & NTCREATEX_OPTIONS_PRIVATE_DENY_DOS)) {
2625                 DEBUG(10,("fcb_or_dos_open: file fail due to is_executable.\n"));
2626                 return NT_STATUS_INVALID_PARAMETER;
2627         }
2628
2629         /* We need to duplicate this fsp. */
2630         return dup_file_fsp(req, fsp, access_mask, share_access,
2631                             create_options, fsp_to_dup_into);
2632 }
2633
2634 static void schedule_defer_open(struct share_mode_lock *lck,
2635                                 struct file_id id,
2636                                 struct timeval request_time,
2637                                 struct smb_request *req)
2638 {
2639         /* This is a relative time, added to the absolute
2640            request_time value to get the absolute timeout time.
2641            Note that if this is the second or greater time we enter
2642            this codepath for this particular request mid then
2643            request_time is left as the absolute time of the *first*
2644            time this request mid was processed. This is what allows
2645            the request to eventually time out. */
2646
2647         struct timeval timeout;
2648
2649         /* Normally the smbd we asked should respond within
2650          * OPLOCK_BREAK_TIMEOUT seconds regardless of whether
2651          * the client did, give twice the timeout as a safety
2652          * measure here in case the other smbd is stuck
2653          * somewhere else. */
2654
2655         timeout = timeval_set(OPLOCK_BREAK_TIMEOUT*2, 0);
2656
2657         if (request_timed_out(request_time, timeout)) {
2658                 return;
2659         }
2660
2661         defer_open(lck, request_time, timeout, req, true, id);
2662 }
2663
2664 /****************************************************************************
2665  Reschedule an open call that went asynchronous.
2666 ****************************************************************************/
2667
2668 static void schedule_async_open_timer(struct tevent_context *ev,
2669                                       struct tevent_timer *te,
2670                                       struct timeval current_time,
2671                                       void *private_data)
2672 {
2673         exit_server("async open timeout");
2674 }
2675
2676 static void schedule_async_open(struct timeval request_time,
2677                                 struct smb_request *req)
2678 {
2679         struct deferred_open_record *open_rec = NULL;
2680         struct timeval timeout = timeval_set(20, 0);
2681         bool ok;
2682
2683         if (request_timed_out(request_time, timeout)) {
2684                 return;
2685         }
2686
2687         open_rec = deferred_open_record_create(false, true, (struct file_id){0});
2688         if (open_rec == NULL) {
2689                 exit_server("deferred_open_record_create failed");
2690         }
2691
2692         ok = push_deferred_open_message_smb(req, request_time, timeout,
2693                                             (struct file_id){0}, open_rec);
2694         if (!ok) {
2695                 exit_server("push_deferred_open_message_smb failed");
2696         }
2697
2698         open_rec->te = tevent_add_timer(req->ev_ctx,
2699                                         req,
2700                                         timeval_current_ofs(20, 0),
2701                                         schedule_async_open_timer,
2702                                         open_rec);
2703         if (open_rec->te == NULL) {
2704                 exit_server("tevent_add_timer failed");
2705         }
2706 }
2707
2708 /****************************************************************************
2709  Work out what access_mask to use from what the client sent us.
2710 ****************************************************************************/
2711
2712 static NTSTATUS smbd_calculate_maximum_allowed_access(
2713         connection_struct *conn,
2714         const struct smb_filename *smb_fname,
2715         bool use_privs,
2716         uint32_t *p_access_mask)
2717 {
2718         struct security_descriptor *sd;
2719         uint32_t access_granted;
2720         NTSTATUS status;
2721
2722         if (!use_privs && (get_current_uid(conn) == (uid_t)0)) {
2723                 *p_access_mask |= FILE_GENERIC_ALL;
2724                 return NT_STATUS_OK;
2725         }
2726
2727         status = SMB_VFS_GET_NT_ACL(conn, smb_fname,
2728                                     (SECINFO_OWNER |
2729                                      SECINFO_GROUP |
2730                                      SECINFO_DACL),
2731                                     talloc_tos(), &sd);
2732
2733         if (NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
2734                 /*
2735                  * File did not exist
2736                  */
2737                 *p_access_mask = FILE_GENERIC_ALL;
2738                 return NT_STATUS_OK;
2739         }
2740         if (!NT_STATUS_IS_OK(status)) {
2741                 DEBUG(10,("Could not get acl on file %s: %s\n",
2742                           smb_fname_str_dbg(smb_fname),
2743                           nt_errstr(status)));
2744                 return NT_STATUS_ACCESS_DENIED;
2745         }
2746
2747         /*
2748          * If we can access the path to this file, by
2749          * default we have FILE_READ_ATTRIBUTES from the
2750          * containing directory. See the section:
2751          * "Algorithm to Check Access to an Existing File"
2752          * in MS-FSA.pdf.
2753          *
2754          * se_file_access_check()
2755          * also takes care of owner WRITE_DAC and READ_CONTROL.
2756          */
2757         status = se_file_access_check(sd,
2758                                  get_current_nttok(conn),
2759                                  use_privs,
2760                                  (*p_access_mask & ~FILE_READ_ATTRIBUTES),
2761                                  &access_granted);
2762
2763         TALLOC_FREE(sd);
2764
2765         if (!NT_STATUS_IS_OK(status)) {
2766                 DEBUG(10, ("Access denied on file %s: "
2767                            "when calculating maximum access\n",
2768                            smb_fname_str_dbg(smb_fname)));
2769                 return NT_STATUS_ACCESS_DENIED;
2770         }
2771         *p_access_mask = (access_granted | FILE_READ_ATTRIBUTES);
2772
2773         if (!(access_granted & DELETE_ACCESS)) {
2774                 if (can_delete_file_in_directory(conn, smb_fname)) {
2775                         *p_access_mask |= DELETE_ACCESS;
2776                 }
2777         }
2778
2779         return NT_STATUS_OK;
2780 }
2781
2782 NTSTATUS smbd_calculate_access_mask(connection_struct *conn,
2783                                     const struct smb_filename *smb_fname,
2784                                     bool use_privs,
2785                                     uint32_t access_mask,
2786                                     uint32_t *access_mask_out)
2787 {
2788         NTSTATUS status;
2789         uint32_t orig_access_mask = access_mask;
2790         uint32_t rejected_share_access;
2791
2792         if (access_mask & SEC_MASK_INVALID) {
2793                 DBG_DEBUG("access_mask [%8x] contains invalid bits\n",
2794                           access_mask);
2795                 return NT_STATUS_ACCESS_DENIED;
2796         }
2797
2798         /*
2799          * Convert GENERIC bits to specific bits.
2800          */
2801
2802         se_map_generic(&access_mask, &file_generic_mapping);
2803
2804         /* Calculate MAXIMUM_ALLOWED_ACCESS if requested. */
2805         if (access_mask & MAXIMUM_ALLOWED_ACCESS) {
2806
2807                 status = smbd_calculate_maximum_allowed_access(
2808                         conn, smb_fname, use_privs, &access_mask);
2809
2810                 if (!NT_STATUS_IS_OK(status)) {
2811                         return status;
2812                 }
2813
2814                 access_mask &= conn->share_access;
2815         }
2816
2817         rejected_share_access = access_mask & ~(conn->share_access);
2818
2819         if (rejected_share_access) {
2820                 DEBUG(10, ("smbd_calculate_access_mask: Access denied on "
2821                         "file %s: rejected by share access mask[0x%08X] "
2822                         "orig[0x%08X] mapped[0x%08X] reject[0x%08X]\n",
2823                         smb_fname_str_dbg(smb_fname),
2824                         conn->share_access,
2825                         orig_access_mask, access_mask,
2826                         rejected_share_access));
2827                 return NT_STATUS_ACCESS_DENIED;
2828         }
2829
2830         *access_mask_out = access_mask;
2831         return NT_STATUS_OK;
2832 }
2833
2834 /****************************************************************************
2835  Remove the deferred open entry under lock.
2836 ****************************************************************************/
2837
2838 /****************************************************************************
2839  Return true if this is a state pointer to an asynchronous create.
2840 ****************************************************************************/
2841
2842 bool is_deferred_open_async(const struct deferred_open_record *rec)
2843 {
2844         return rec->async_open;
2845 }
2846
2847 static bool clear_ads(uint32_t create_disposition)
2848 {
2849         bool ret = false;
2850
2851         switch (create_disposition) {
2852         case FILE_SUPERSEDE:
2853         case FILE_OVERWRITE_IF:
2854         case FILE_OVERWRITE:
2855                 ret = true;
2856                 break;
2857         default:
2858                 break;
2859         }
2860         return ret;
2861 }
2862
2863 static int disposition_to_open_flags(uint32_t create_disposition)
2864 {
2865         int ret = 0;
2866
2867         /*
2868          * Currently we're using FILE_SUPERSEDE as the same as
2869          * FILE_OVERWRITE_IF but they really are
2870          * different. FILE_SUPERSEDE deletes an existing file
2871          * (requiring delete access) then recreates it.
2872          */
2873
2874         switch (create_disposition) {
2875         case FILE_SUPERSEDE:
2876         case FILE_OVERWRITE_IF:
2877                 /*
2878                  * If file exists replace/overwrite. If file doesn't
2879                  * exist create.
2880                  */
2881                 ret = O_CREAT|O_TRUNC;
2882                 break;
2883
2884         case FILE_OPEN:
2885                 /*
2886                  * If file exists open. If file doesn't exist error.
2887                  */
2888                 ret = 0;
2889                 break;
2890
2891         case FILE_OVERWRITE:
2892                 /*
2893                  * If file exists overwrite. If file doesn't exist
2894                  * error.
2895                  */
2896                 ret = O_TRUNC;
2897                 break;
2898
2899         case FILE_CREATE:
2900                 /*
2901                  * If file exists error. If file doesn't exist create.
2902                  */
2903                 ret = O_CREAT|O_EXCL;
2904                 break;
2905
2906         case FILE_OPEN_IF:
2907                 /*
2908                  * If file exists open. If file doesn't exist create.
2909                  */
2910                 ret = O_CREAT;
2911                 break;
2912         }
2913         return ret;
2914 }
2915
2916 static int calculate_open_access_flags(uint32_t access_mask,
2917                                        uint32_t private_flags)
2918 {
2919         bool need_write, need_read;
2920
2921         /*
2922          * Note that we ignore the append flag as append does not
2923          * mean the same thing under DOS and Unix.
2924          */
2925
2926         need_write = (access_mask & (FILE_WRITE_DATA | FILE_APPEND_DATA));
2927         if (!need_write) {
2928                 return O_RDONLY;
2929         }
2930
2931         /* DENY_DOS opens are always underlying read-write on the
2932            file handle, no matter what the requested access mask
2933            says. */
2934
2935         need_read =
2936                 ((private_flags & NTCREATEX_OPTIONS_PRIVATE_DENY_DOS) ||
2937                  access_mask & (FILE_READ_ATTRIBUTES|FILE_READ_DATA|
2938                                 FILE_READ_EA|FILE_EXECUTE));
2939
2940         if (!need_read) {
2941                 return O_WRONLY;
2942         }
2943         return O_RDWR;
2944 }
2945
2946 /****************************************************************************
2947  Open a file with a share mode. Passed in an already created files_struct *.
2948 ****************************************************************************/
2949
2950 static NTSTATUS open_file_ntcreate(connection_struct *conn,
2951                             struct smb_request *req,
2952                             uint32_t access_mask,               /* access bits (FILE_READ_DATA etc.) */
2953                             uint32_t share_access,      /* share constants (FILE_SHARE_READ etc) */
2954                             uint32_t create_disposition,        /* FILE_OPEN_IF etc. */
2955                             uint32_t create_options,    /* options such as delete on close. */
2956                             uint32_t new_dos_attributes,        /* attributes used for new file. */
2957                             int oplock_request,         /* internal Samba oplock codes. */
2958                             struct smb2_lease *lease,
2959                                                         /* Information (FILE_EXISTS etc.) */
2960                             uint32_t private_flags,     /* Samba specific flags. */
2961                             int *pinfo,
2962                             files_struct *fsp)
2963 {
2964         struct smb_filename *smb_fname = fsp->fsp_name;
2965         int flags=0;
2966         int flags2=0;
2967         bool file_existed = VALID_STAT(smb_fname->st);
2968         bool def_acl = False;
2969         bool posix_open = False;
2970         bool new_file_created = False;
2971         bool first_open_attempt = true;
2972         NTSTATUS fsp_open = NT_STATUS_ACCESS_DENIED;
2973         mode_t new_unx_mode = (mode_t)0;
2974         mode_t unx_mode = (mode_t)0;
2975         int info;
2976         uint32_t existing_dos_attributes = 0;
2977         struct timeval request_time = timeval_zero();
2978         struct share_mode_lock *lck = NULL;
2979         uint32_t open_access_mask = access_mask;
2980         NTSTATUS status;
2981         char *parent_dir;
2982         SMB_STRUCT_STAT saved_stat = smb_fname->st;
2983         struct timespec old_write_time;
2984         struct file_id id;
2985
2986         if (conn->printer) {
2987                 /*
2988                  * Printers are handled completely differently.
2989                  * Most of the passed parameters are ignored.
2990                  */
2991
2992                 if (pinfo) {
2993                         *pinfo = FILE_WAS_CREATED;
2994                 }
2995
2996                 DEBUG(10, ("open_file_ntcreate: printer open fname=%s\n",
2997                            smb_fname_str_dbg(smb_fname)));
2998
2999                 if (!req) {
3000                         DEBUG(0,("open_file_ntcreate: printer open without "
3001                                 "an SMB request!\n"));
3002                         return NT_STATUS_INTERNAL_ERROR;
3003                 }
3004
3005                 return print_spool_open(fsp, smb_fname->base_name,
3006                                         req->vuid);
3007         }
3008
3009         if (!parent_dirname(talloc_tos(), smb_fname->base_name, &parent_dir,
3010                             NULL)) {
3011                 return NT_STATUS_NO_MEMORY;
3012         }
3013
3014         if (new_dos_attributes & FILE_FLAG_POSIX_SEMANTICS) {
3015                 posix_open = True;
3016                 unx_mode = (mode_t)(new_dos_attributes & ~FILE_FLAG_POSIX_SEMANTICS);
3017                 new_dos_attributes = 0;
3018         } else {
3019                 /* Windows allows a new file to be created and
3020                    silently removes a FILE_ATTRIBUTE_DIRECTORY
3021                    sent by the client. Do the same. */
3022
3023                 new_dos_attributes &= ~FILE_ATTRIBUTE_DIRECTORY;
3024
3025                 /* We add FILE_ATTRIBUTE_ARCHIVE to this as this mode is only used if the file is
3026                  * created new. */
3027                 unx_mode = unix_mode(conn, new_dos_attributes | FILE_ATTRIBUTE_ARCHIVE,
3028                                      smb_fname, parent_dir);
3029         }
3030
3031         DEBUG(10, ("open_file_ntcreate: fname=%s, dos_attrs=0x%x "
3032                    "access_mask=0x%x share_access=0x%x "
3033                    "create_disposition = 0x%x create_options=0x%x "
3034                    "unix mode=0%o oplock_request=%d private_flags = 0x%x\n",
3035                    smb_fname_str_dbg(smb_fname), new_dos_attributes,
3036                    access_mask, share_access, create_disposition,
3037                    create_options, (unsigned int)unx_mode, oplock_request,
3038                    (unsigned int)private_flags));
3039
3040         if (req == NULL) {
3041                 /* Ensure req == NULL means INTERNAL_OPEN_ONLY */
3042                 SMB_ASSERT(((oplock_request & INTERNAL_OPEN_ONLY) != 0));
3043         } else {
3044                 /* And req != NULL means no INTERNAL_OPEN_ONLY */
3045                 SMB_ASSERT(((oplock_request & INTERNAL_OPEN_ONLY) == 0));
3046         }
3047
3048         /*
3049          * Only non-internal opens can be deferred at all
3050          */
3051
3052         if (req) {
3053                 struct deferred_open_record *open_rec;
3054                 if (get_deferred_open_message_state(req,
3055                                 &request_time,
3056                                 &open_rec)) {
3057                         /* Remember the absolute time of the original
3058                            request with this mid. We'll use it later to
3059                            see if this has timed out. */
3060
3061                         /* If it was an async create retry, the file
3062                            didn't exist. */
3063
3064                         if (is_deferred_open_async(open_rec)) {
3065                                 SET_STAT_INVALID(smb_fname->st);
3066                                 file_existed = false;
3067                         }
3068
3069                         /* Ensure we don't reprocess this message. */
3070                         remove_deferred_open_message_smb(req->xconn, req->mid);
3071
3072                         first_open_attempt = false;
3073                 }
3074         }
3075
3076         if (!posix_open) {
3077                 new_dos_attributes &= SAMBA_ATTRIBUTES_MASK;
3078                 if (file_existed) {
3079                         /*
3080                          * Only use strored DOS attributes for checks
3081                          * against requested attributes (below via
3082                          * open_match_attributes()), cf bug #11992
3083                          * for details. -slow
3084                          */
3085                         uint32_t attr = 0;
3086
3087                         status = SMB_VFS_GET_DOS_ATTRIBUTES(conn, smb_fname, &attr);
3088                         if (NT_STATUS_IS_OK(status)) {
3089                                 existing_dos_attributes = attr;
3090                         }
3091                 }
3092         }
3093
3094         /* ignore any oplock requests if oplocks are disabled */
3095         if (!lp_oplocks(SNUM(conn)) ||
3096             IS_VETO_OPLOCK_PATH(conn, smb_fname->base_name)) {
3097                 /* Mask off everything except the private Samba bits. */
3098                 oplock_request &= SAMBA_PRIVATE_OPLOCK_MASK;
3099         }
3100
3101         /* this is for OS/2 long file names - say we don't support them */
3102         if (req != NULL && !req->posix_pathnames &&
3103                         strstr(smb_fname->base_name,".+,;=[].")) {
3104                 /* OS/2 Workplace shell fix may be main code stream in a later
3105                  * release. */
3106                 DEBUG(5,("open_file_ntcreate: OS/2 long filenames are not "
3107                          "supported.\n"));
3108                 if (use_nt_status()) {
3109                         return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3110                 }
3111                 return NT_STATUS_DOS(ERRDOS, ERRcannotopen);
3112         }
3113
3114         switch( create_disposition ) {
3115                 case FILE_OPEN:
3116                         /* If file exists open. If file doesn't exist error. */
3117                         if (!file_existed) {
3118                                 DEBUG(5,("open_file_ntcreate: FILE_OPEN "
3119                                          "requested for file %s and file "
3120                                          "doesn't exist.\n",
3121                                          smb_fname_str_dbg(smb_fname)));
3122                                 errno = ENOENT;
3123                                 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3124                         }
3125                         break;
3126
3127                 case FILE_OVERWRITE:
3128                         /* If file exists overwrite. If file doesn't exist
3129                          * error. */
3130                         if (!file_existed) {
3131                                 DEBUG(5,("open_file_ntcreate: FILE_OVERWRITE "
3132                                          "requested for file %s and file "
3133                                          "doesn't exist.\n",
3134                                          smb_fname_str_dbg(smb_fname) ));
3135                                 errno = ENOENT;
3136                                 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3137                         }
3138                         break;
3139
3140                 case FILE_CREATE:
3141                         /* If file exists error. If file doesn't exist
3142                          * create. */
3143                         if (file_existed) {
3144                                 DEBUG(5,("open_file_ntcreate: FILE_CREATE "
3145                                          "requested for file %s and file "
3146                                          "already exists.\n",
3147                                          smb_fname_str_dbg(smb_fname)));
3148                                 if (S_ISDIR(smb_fname->st.st_ex_mode)) {
3149                                         errno = EISDIR;
3150                                 } else {
3151                                         errno = EEXIST;
3152                                 }
3153                                 return map_nt_error_from_unix(errno);
3154                         }
3155                         break;
3156
3157                 case FILE_SUPERSEDE:
3158                 case FILE_OVERWRITE_IF:
3159                 case FILE_OPEN_IF:
3160                         break;
3161                 default:
3162                         return NT_STATUS_INVALID_PARAMETER;
3163         }
3164
3165         flags2 = disposition_to_open_flags(create_disposition);
3166
3167         /* We only care about matching attributes on file exists and
3168          * overwrite. */
3169
3170         if (!posix_open && file_existed &&
3171             ((create_disposition == FILE_OVERWRITE) ||
3172              (create_disposition == FILE_OVERWRITE_IF))) {
3173                 if (!open_match_attributes(conn, existing_dos_attributes,
3174                                            new_dos_attributes,
3175                                            unx_mode, &new_unx_mode)) {
3176                         DEBUG(5,("open_file_ntcreate: attributes mismatch "
3177                                  "for file %s (%x %x) (0%o, 0%o)\n",
3178                                  smb_fname_str_dbg(smb_fname),
3179                                  existing_dos_attributes,
3180                                  new_dos_attributes,
3181                                  (unsigned int)smb_fname->st.st_ex_mode,
3182                                  (unsigned int)unx_mode ));
3183                         errno = EACCES;
3184                         return NT_STATUS_ACCESS_DENIED;
3185                 }
3186         }
3187
3188         status = smbd_calculate_access_mask(conn, smb_fname,
3189                                         false,
3190                                         access_mask,
3191                                         &access_mask); 
3192         if (!NT_STATUS_IS_OK(status)) {
3193                 DEBUG(10, ("open_file_ntcreate: smbd_calculate_access_mask "
3194                         "on file %s returned %s\n",
3195                         smb_fname_str_dbg(smb_fname), nt_errstr(status)));
3196                 return status;
3197         }
3198
3199         open_access_mask = access_mask;
3200
3201         if (flags2 & O_TRUNC) {
3202                 open_access_mask |= FILE_WRITE_DATA; /* This will cause oplock breaks. */
3203         }
3204
3205         DEBUG(10, ("open_file_ntcreate: fname=%s, after mapping "
3206                    "access_mask=0x%x\n", smb_fname_str_dbg(smb_fname),
3207                     access_mask));
3208
3209         /*
3210          * Note that we ignore the append flag as append does not
3211          * mean the same thing under DOS and Unix.
3212          */
3213
3214         flags = calculate_open_access_flags(access_mask, private_flags);
3215
3216         /*
3217          * Currently we only look at FILE_WRITE_THROUGH for create options.
3218          */
3219
3220 #if defined(O_SYNC)
3221         if ((create_options & FILE_WRITE_THROUGH) && lp_strict_sync(SNUM(conn))) {
3222                 flags2 |= O_SYNC;
3223         }
3224 #endif /* O_SYNC */
3225
3226         if (posix_open && (access_mask & FILE_APPEND_DATA)) {
3227                 flags2 |= O_APPEND;
3228         }
3229
3230         if (!posix_open && !CAN_WRITE(conn)) {
3231                 /*
3232                  * We should really return a permission denied error if either
3233                  * O_CREAT or O_TRUNC are set, but for compatibility with
3234                  * older versions of Samba we just AND them out.
3235                  */
3236                 flags2 &= ~(O_CREAT|O_TRUNC);
3237         }
3238
3239         if (lp_kernel_oplocks(SNUM(conn))) {
3240                 /*
3241                  * With kernel oplocks the open breaking an oplock
3242                  * blocks until the oplock holder has given up the
3243                  * oplock or closed the file. We prevent this by always
3244                  * trying to open the file with O_NONBLOCK (see "man
3245                  * fcntl" on Linux).
3246                  *
3247                  * If a process that doesn't use the smbd open files
3248                  * database or communication methods holds a kernel
3249                  * oplock we must periodically poll for available open
3250                  * using O_NONBLOCK.
3251                  */
3252                 flags2 |= O_NONBLOCK;
3253         }
3254
3255         /*
3256          * Ensure we can't write on a read-only share or file.
3257          */
3258
3259         if (flags != O_RDONLY && file_existed &&
3260             (!CAN_WRITE(conn) || IS_DOS_READONLY(existing_dos_attributes))) {
3261                 DEBUG(5,("open_file_ntcreate: write access requested for "
3262                          "file %s on read only %s\n",
3263                          smb_fname_str_dbg(smb_fname),
3264                          !CAN_WRITE(conn) ? "share" : "file" ));
3265                 errno = EACCES;
3266                 return NT_STATUS_ACCESS_DENIED;
3267         }
3268
3269         fsp->file_id = vfs_file_id_from_sbuf(conn, &smb_fname->st);
3270         fsp->share_access = share_access;
3271         fsp->fh->private_options = private_flags;
3272         fsp->access_mask = open_access_mask; /* We change this to the
3273                                               * requested access_mask after
3274                                               * the open is done. */
3275         if (posix_open) {
3276                 fsp->posix_flags |= FSP_POSIX_FLAGS_ALL;
3277         }
3278
3279         if (timeval_is_zero(&request_time)) {
3280                 request_time = fsp->open_time;
3281         }
3282
3283         if ((create_options & FILE_DELETE_ON_CLOSE) &&
3284                         (flags2 & O_CREAT) &&
3285                         !file_existed) {
3286                 /* Delete on close semantics for new files. */
3287                 status = can_set_delete_on_close(fsp,
3288                                                 new_dos_attributes);
3289                 if (!NT_STATUS_IS_OK(status)) {
3290                         fd_close(fsp);
3291                         return status;
3292                 }
3293         }
3294
3295         /*
3296          * Ensure we pay attention to default ACLs on directories if required.
3297          */
3298
3299         if ((flags2 & O_CREAT) && lp_inherit_acls(SNUM(conn)) &&
3300             (def_acl = directory_has_default_acl(conn, parent_dir))) {
3301                 unx_mode = (0777 & lp_create_mask(SNUM(conn)));
3302         }
3303
3304         DEBUG(4,("calling open_file with flags=0x%X flags2=0x%X mode=0%o, "
3305                 "access_mask = 0x%x, open_access_mask = 0x%x\n",
3306                  (unsigned int)flags, (unsigned int)flags2,
3307                  (unsigned int)unx_mode, (unsigned int)access_mask,
3308                  (unsigned int)open_access_mask));
3309
3310         fsp_open = open_file(fsp, conn, req, parent_dir,
3311                              flags|flags2, unx_mode, access_mask,
3312                              open_access_mask, &new_file_created);
3313
3314         if (NT_STATUS_EQUAL(fsp_open, NT_STATUS_NETWORK_BUSY)) {
3315                 bool delay;
3316
3317                 /*
3318                  * This handles the kernel oplock case:
3319                  *
3320                  * the file has an active kernel oplock and the open() returned
3321                  * EWOULDBLOCK/EAGAIN which maps to NETWORK_BUSY.
3322                  *
3323                  * "Samba locking.tdb oplocks" are handled below after acquiring
3324                  * the sharemode lock with get_share_mode_lock().
3325                  */
3326                 if (file_existed && S_ISFIFO(fsp->fsp_name->st.st_ex_mode)) {
3327                         DEBUG(10, ("FIFO busy\n"));
3328                         return NT_STATUS_NETWORK_BUSY;
3329                 }
3330                 if (req == NULL) {
3331                         DEBUG(10, ("Internal open busy\n"));
3332                         return NT_STATUS_NETWORK_BUSY;
3333                 }
3334
3335                 /*
3336                  * From here on we assume this is an oplock break triggered
3337                  */
3338
3339                 lck = get_existing_share_mode_lock(talloc_tos(), fsp->file_id);
3340                 if (lck == NULL) {
3341                         /*
3342                          * No oplock from Samba around. Set up a poll every 1
3343                          * second to retry a non-blocking open until the time
3344                          * expires.
3345                          */
3346                         setup_kernel_oplock_poll_open(request_time,
3347                                                 req,
3348                                                 fsp->file_id);
3349                         DBG_DEBUG("No Samba oplock around after EWOULDBLOCK. "
3350                                 "Retrying with poll\n");
3351                         return NT_STATUS_SHARING_VIOLATION;
3352                 }
3353
3354                 if (!validate_oplock_types(lck)) {
3355                         smb_panic("validate_oplock_types failed");
3356                 }
3357
3358                 delay = delay_for_oplock(fsp, 0, lease, lck, false,
3359                                          create_disposition,
3360                                          first_open_attempt);
3361                 if (delay) {
3362                         schedule_defer_open(lck, fsp->file_id, request_time,
3363                                             req);
3364                         TALLOC_FREE(lck);
3365                         DEBUG(10, ("Sent oplock break request to kernel "
3366                                    "oplock holder\n"));
3367                         return NT_STATUS_SHARING_VIOLATION;
3368                 }
3369
3370                 /*
3371                  * No oplock from Samba around. Set up a poll every 1
3372                  * second to retry a non-blocking open until the time
3373                  * expires.
3374                  */
3375                 setup_kernel_oplock_poll_open(request_time, req, fsp->file_id);
3376
3377                 TALLOC_FREE(lck);
3378                 DBG_DEBUG("No Samba oplock around after EWOULDBLOCK. "
3379                         "Retrying with poll\n");
3380                 return NT_STATUS_SHARING_VIOLATION;
3381         }
3382
3383         if (!NT_STATUS_IS_OK(fsp_open)) {
3384                 if (NT_STATUS_EQUAL(fsp_open, NT_STATUS_RETRY)) {
3385                         schedule_async_open(request_time, req);
3386                 }
3387                 return fsp_open;
3388         }
3389
3390         if (new_file_created) {
3391                 /*
3392                  * As we atomically create using O_CREAT|O_EXCL,
3393                  * then if new_file_created is true, then