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