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