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