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