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