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