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