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