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