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