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