e5503f57f36103a42f066b3caa425cee73372051
[samba.git] / source3 / smbd / open.c
1 /* 
2    Unix SMB/CIFS implementation.
3    file opening and share modes
4    Copyright (C) Andrew Tridgell 1992-1998
5    Copyright (C) Jeremy Allison 2001-2004
6    Copyright (C) Volker Lendecke 2005
7
8    This program is free software; you can redistribute it and/or modify
9    it under the terms of the GNU General Public License as published by
10    the Free Software Foundation; either version 3 of the License, or
11    (at your option) any later version.
12
13    This program is distributed in the hope that it will be useful,
14    but WITHOUT ANY WARRANTY; without even the implied warranty of
15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16    GNU General Public License for more details.
17
18    You should have received a copy of the GNU General Public License
19    along with this program.  If not, see <http://www.gnu.org/licenses/>.
20 */
21
22 #include "includes.h"
23 #include "system/filesys.h"
24 #include "printing.h"
25 #include "smbd/smbd.h"
26 #include "smbd/globals.h"
27 #include "fake_file.h"
28 #include "../libcli/security/security.h"
29 #include "../librpc/gen_ndr/ndr_security.h"
30 #include "../librpc/gen_ndr/open_files.h"
31 #include "../librpc/gen_ndr/idmap.h"
32 #include "../librpc/gen_ndr/ioctl.h"
33 #include "passdb/lookup_sid.h"
34 #include "auth.h"
35 #include "serverid.h"
36 #include "messages.h"
37 #include "source3/lib/dbwrap/dbwrap_watch.h"
38 #include "locking/leases_db.h"
39 #include "librpc/gen_ndr/ndr_leases_db.h"
40
41 extern const struct generic_mapping file_generic_mapping;
42
43 struct deferred_open_record {
44         bool delayed_for_oplocks;
45         bool async_open;
46         struct file_id id;
47 };
48
49 /****************************************************************************
50  If the requester wanted DELETE_ACCESS and was rejected because
51  the file ACL didn't include DELETE_ACCESS, see if the parent ACL
52  overrides this.
53 ****************************************************************************/
54
55 static bool parent_override_delete(connection_struct *conn,
56                                         const struct smb_filename *smb_fname,
57                                         uint32_t access_mask,
58                                         uint32_t rejected_mask)
59 {
60         if ((access_mask & DELETE_ACCESS) &&
61                     (rejected_mask & DELETE_ACCESS) &&
62                     can_delete_file_in_directory(conn, smb_fname)) {
63                 return true;
64         }
65         return false;
66 }
67
68 /****************************************************************************
69  Check if we have open rights.
70 ****************************************************************************/
71
72 NTSTATUS smbd_check_access_rights(struct connection_struct *conn,
73                                 const struct smb_filename *smb_fname,
74                                 bool use_privs,
75                                 uint32_t access_mask)
76 {
77         /* Check if we have rights to open. */
78         NTSTATUS status;
79         struct security_descriptor *sd = NULL;
80         uint32_t rejected_share_access;
81         uint32_t rejected_mask = access_mask;
82         uint32_t do_not_check_mask = 0;
83
84         rejected_share_access = access_mask & ~(conn->share_access);
85
86         if (rejected_share_access) {
87                 DEBUG(10, ("smbd_check_access_rights: rejected share access 0x%x "
88                         "on %s (0x%x)\n",
89                         (unsigned int)access_mask,
90                         smb_fname_str_dbg(smb_fname),
91                         (unsigned int)rejected_share_access ));
92                 return NT_STATUS_ACCESS_DENIED;
93         }
94
95         if (!use_privs && get_current_uid(conn) == (uid_t)0) {
96                 /* I'm sorry sir, I didn't know you were root... */
97                 DEBUG(10,("smbd_check_access_rights: root override "
98                         "on %s. Granting 0x%x\n",
99                         smb_fname_str_dbg(smb_fname),
100                         (unsigned int)access_mask ));
101                 return NT_STATUS_OK;
102         }
103
104         if ((access_mask & DELETE_ACCESS) && !lp_acl_check_permissions(SNUM(conn))) {
105                 DEBUG(10,("smbd_check_access_rights: not checking ACL "
106                         "on DELETE_ACCESS on file %s. Granting 0x%x\n",
107                         smb_fname_str_dbg(smb_fname),
108                         (unsigned int)access_mask ));
109                 return NT_STATUS_OK;
110         }
111
112         if (access_mask == DELETE_ACCESS &&
113                         VALID_STAT(smb_fname->st) &&
114                         S_ISLNK(smb_fname->st.st_ex_mode)) {
115                 /* We can always delete a symlink. */
116                 DEBUG(10,("smbd_check_access_rights: not checking ACL "
117                         "on DELETE_ACCESS on symlink %s.\n",
118                         smb_fname_str_dbg(smb_fname) ));
119                 return NT_STATUS_OK;
120         }
121
122         status = SMB_VFS_GET_NT_ACL(conn, smb_fname,
123                         (SECINFO_OWNER |
124                         SECINFO_GROUP |
125                          SECINFO_DACL), talloc_tos(), &sd);
126
127         if (!NT_STATUS_IS_OK(status)) {
128                 DEBUG(10, ("smbd_check_access_rights: Could not get acl "
129                         "on %s: %s\n",
130                         smb_fname_str_dbg(smb_fname),
131                         nt_errstr(status)));
132
133                 if (NT_STATUS_EQUAL(status, NT_STATUS_ACCESS_DENIED)) {
134                         goto access_denied;
135                 }
136
137                 return status;
138         }
139
140         /*
141          * If we can access the path to this file, by
142          * default we have FILE_READ_ATTRIBUTES from the
143          * containing directory. See the section:
144          * "Algorithm to Check Access to an Existing File"
145          * in MS-FSA.pdf.
146          *
147          * se_file_access_check() also takes care of
148          * owner WRITE_DAC and READ_CONTROL.
149          */
150         do_not_check_mask = FILE_READ_ATTRIBUTES;
151
152         /*
153          * Samba 3.6 and earlier granted execute access even
154          * if the ACL did not contain execute rights.
155          * Samba 4.0 is more correct and checks it.
156          * The compatibilty mode allows one to skip this check
157          * to smoothen upgrades.
158          */
159         if (lp_acl_allow_execute_always(SNUM(conn))) {
160                 do_not_check_mask |= FILE_EXECUTE;
161         }
162
163         status = se_file_access_check(sd,
164                                 get_current_nttok(conn),
165                                 use_privs,
166                                 (access_mask & ~do_not_check_mask),
167                                 &rejected_mask);
168
169         DEBUG(10,("smbd_check_access_rights: file %s requesting "
170                 "0x%x returning 0x%x (%s)\n",
171                 smb_fname_str_dbg(smb_fname),
172                 (unsigned int)access_mask,
173                 (unsigned int)rejected_mask,
174                 nt_errstr(status) ));
175
176         if (!NT_STATUS_IS_OK(status)) {
177                 if (DEBUGLEVEL >= 10) {
178                         DEBUG(10,("smbd_check_access_rights: acl for %s is:\n",
179                                 smb_fname_str_dbg(smb_fname) ));
180                         NDR_PRINT_DEBUG(security_descriptor, sd);
181                 }
182         }
183
184         TALLOC_FREE(sd);
185
186         if (NT_STATUS_IS_OK(status) ||
187                         !NT_STATUS_EQUAL(status, NT_STATUS_ACCESS_DENIED)) {
188                 return status;
189         }
190
191         /* Here we know status == NT_STATUS_ACCESS_DENIED. */
192
193   access_denied:
194
195         if ((access_mask & FILE_WRITE_ATTRIBUTES) &&
196                         (rejected_mask & FILE_WRITE_ATTRIBUTES) &&
197                         !lp_store_dos_attributes(SNUM(conn)) &&
198                         (lp_map_readonly(SNUM(conn)) ||
199                         lp_map_archive(SNUM(conn)) ||
200                         lp_map_hidden(SNUM(conn)) ||
201                         lp_map_system(SNUM(conn)))) {
202                 rejected_mask &= ~FILE_WRITE_ATTRIBUTES;
203
204                 DEBUG(10,("smbd_check_access_rights: "
205                         "overrode "
206                         "FILE_WRITE_ATTRIBUTES "
207                         "on file %s\n",
208                         smb_fname_str_dbg(smb_fname)));
209         }
210
211         if (parent_override_delete(conn,
212                                 smb_fname,
213                                 access_mask,
214                                 rejected_mask)) {
215                 /* Were we trying to do an open
216                  * for delete and didn't get DELETE
217                  * access (only) ? Check if the
218                  * directory allows DELETE_CHILD.
219                  * See here:
220                  * http://blogs.msdn.com/oldnewthing/archive/2004/06/04/148426.aspx
221                  * for details. */
222
223                 rejected_mask &= ~DELETE_ACCESS;
224
225                 DEBUG(10,("smbd_check_access_rights: "
226                         "overrode "
227                         "DELETE_ACCESS on "
228                         "file %s\n",
229                         smb_fname_str_dbg(smb_fname)));
230         }
231
232         if (rejected_mask != 0) {
233                 return NT_STATUS_ACCESS_DENIED;
234         }
235         return NT_STATUS_OK;
236 }
237
238 static NTSTATUS check_parent_access(struct connection_struct *conn,
239                                 struct smb_filename *smb_fname,
240                                 uint32_t access_mask)
241 {
242         NTSTATUS status;
243         char *parent_dir = NULL;
244         struct security_descriptor *parent_sd = NULL;
245         uint32_t access_granted = 0;
246         struct smb_filename *parent_smb_fname = NULL;
247
248         if (!parent_dirname(talloc_tos(),
249                                 smb_fname->base_name,
250                                 &parent_dir,
251                                 NULL)) {
252                 return NT_STATUS_NO_MEMORY;
253         }
254
255         parent_smb_fname = synthetic_smb_fname(talloc_tos(),
256                                 parent_dir,
257                                 NULL,
258                                 NULL);
259         if (parent_smb_fname == NULL) {
260                 return NT_STATUS_NO_MEMORY;
261         }
262
263         if (get_current_uid(conn) == (uid_t)0) {
264                 /* I'm sorry sir, I didn't know you were root... */
265                 DEBUG(10,("check_parent_access: root override "
266                         "on %s. Granting 0x%x\n",
267                         smb_fname_str_dbg(smb_fname),
268                         (unsigned int)access_mask ));
269                 return NT_STATUS_OK;
270         }
271
272         status = SMB_VFS_GET_NT_ACL(conn,
273                                 parent_smb_fname,
274                                 SECINFO_DACL,
275                                     talloc_tos(),
276                                 &parent_sd);
277
278         if (!NT_STATUS_IS_OK(status)) {
279                 DEBUG(5,("check_parent_access: SMB_VFS_GET_NT_ACL failed for "
280                         "%s with error %s\n",
281                         parent_dir,
282                         nt_errstr(status)));
283                 return status;
284         }
285
286         /*
287          * If we can access the path to this file, by
288          * default we have FILE_READ_ATTRIBUTES from the
289          * containing directory. See the section:
290          * "Algorithm to Check Access to an Existing File"
291          * in MS-FSA.pdf.
292          *
293          * se_file_access_check() also takes care of
294          * owner WRITE_DAC and READ_CONTROL.
295          */
296         status = se_file_access_check(parent_sd,
297                                 get_current_nttok(conn),
298                                 false,
299                                 (access_mask & ~FILE_READ_ATTRIBUTES),
300                                 &access_granted);
301         if(!NT_STATUS_IS_OK(status)) {
302                 DEBUG(5,("check_parent_access: access check "
303                         "on directory %s for "
304                         "path %s for mask 0x%x returned (0x%x) %s\n",
305                         parent_dir,
306                         smb_fname->base_name,
307                         access_mask,
308                         access_granted,
309                         nt_errstr(status) ));
310                 return status;
311         }
312
313         return NT_STATUS_OK;
314 }
315
316 /****************************************************************************
317  Ensure when opening a base file for a stream open that we have permissions
318  to do so given the access mask on the base file.
319 ****************************************************************************/
320
321 static NTSTATUS check_base_file_access(struct connection_struct *conn,
322                                 struct smb_filename *smb_fname,
323                                 uint32_t access_mask)
324 {
325         NTSTATUS status;
326
327         status = smbd_calculate_access_mask(conn, smb_fname,
328                                         false,
329                                         access_mask,
330                                         &access_mask);
331         if (!NT_STATUS_IS_OK(status)) {
332                 DEBUG(10, ("smbd_calculate_access_mask "
333                         "on file %s returned %s\n",
334                         smb_fname_str_dbg(smb_fname),
335                         nt_errstr(status)));
336                 return status;
337         }
338
339         if (access_mask & (FILE_WRITE_DATA|FILE_APPEND_DATA)) {
340                 uint32_t dosattrs;
341                 if (!CAN_WRITE(conn)) {
342                         return NT_STATUS_ACCESS_DENIED;
343                 }
344                 dosattrs = dos_mode(conn, smb_fname);
345                 if (IS_DOS_READONLY(dosattrs)) {
346                         return NT_STATUS_ACCESS_DENIED;
347                 }
348         }
349
350         return smbd_check_access_rights(conn,
351                                         smb_fname,
352                                         false,
353                                         access_mask);
354 }
355
356 /****************************************************************************
357  fd support routines - attempt to do a dos_open.
358 ****************************************************************************/
359
360 NTSTATUS fd_open(struct connection_struct *conn,
361                  files_struct *fsp,
362                  int flags,
363                  mode_t mode)
364 {
365         struct smb_filename *smb_fname = fsp->fsp_name;
366         NTSTATUS status = NT_STATUS_OK;
367
368 #ifdef O_NOFOLLOW
369         /* 
370          * Never follow symlinks on a POSIX client. The
371          * client should be doing this.
372          */
373
374         if ((fsp->posix_flags & FSP_POSIX_FLAGS_OPEN) || !lp_follow_symlinks(SNUM(conn))) {
375                 flags |= O_NOFOLLOW;
376         }
377 #endif
378
379         fsp->fh->fd = SMB_VFS_OPEN(conn, smb_fname, fsp, flags, mode);
380         if (fsp->fh->fd == -1) {
381                 int posix_errno = errno;
382 #ifdef O_NOFOLLOW
383 #if defined(ENOTSUP) && defined(OSF1)
384                 /* handle special Tru64 errno */
385                 if (errno == ENOTSUP) {
386                         posix_errno = ELOOP;
387                 }
388 #endif /* ENOTSUP */
389 #ifdef EFTYPE
390                 /* fix broken NetBSD errno */
391                 if (errno == EFTYPE) {
392                         posix_errno = ELOOP;
393                 }
394 #endif /* EFTYPE */
395                 /* fix broken FreeBSD errno */
396                 if (errno == EMLINK) {
397                         posix_errno = ELOOP;
398                 }
399 #endif /* O_NOFOLLOW */
400                 status = map_nt_error_from_unix(posix_errno);
401                 if (errno == EMFILE) {
402                         static time_t last_warned = 0L;
403
404                         if (time((time_t *) NULL) > last_warned) {
405                                 DEBUG(0,("Too many open files, unable "
406                                         "to open more!  smbd's max "
407                                         "open files = %d\n",
408                                         lp_max_open_files()));
409                                 last_warned = time((time_t *) NULL);
410                         }
411                 }
412
413         }
414
415         DEBUG(10,("fd_open: name %s, flags = 0%o mode = 0%o, fd = %d. %s\n",
416                   smb_fname_str_dbg(smb_fname), flags, (int)mode, fsp->fh->fd,
417                 (fsp->fh->fd == -1) ? strerror(errno) : "" ));
418
419         return status;
420 }
421
422 /****************************************************************************
423  Close the file associated with a fsp.
424 ****************************************************************************/
425
426 NTSTATUS fd_close(files_struct *fsp)
427 {
428         int ret;
429
430         if (fsp->dptr) {
431                 dptr_CloseDir(fsp);
432         }
433         if (fsp->fh->fd == -1) {
434                 return NT_STATUS_OK; /* What we used to call a stat open. */
435         }
436         if (fsp->fh->ref_count > 1) {
437                 return NT_STATUS_OK; /* Shared handle. Only close last reference. */
438         }
439
440         ret = SMB_VFS_CLOSE(fsp);
441         fsp->fh->fd = -1;
442         if (ret == -1) {
443                 return map_nt_error_from_unix(errno);
444         }
445         return NT_STATUS_OK;
446 }
447
448 /****************************************************************************
449  Change the ownership of a file to that of the parent directory.
450  Do this by fd if possible.
451 ****************************************************************************/
452
453 void change_file_owner_to_parent(connection_struct *conn,
454                                         const char *inherit_from_dir,
455                                         files_struct *fsp)
456 {
457         struct smb_filename *smb_fname_parent;
458         int ret;
459
460         smb_fname_parent = synthetic_smb_fname(talloc_tos(), inherit_from_dir,
461                                                NULL, NULL);
462         if (smb_fname_parent == NULL) {
463                 return;
464         }
465
466         ret = SMB_VFS_STAT(conn, smb_fname_parent);
467         if (ret == -1) {
468                 DEBUG(0,("change_file_owner_to_parent: failed to stat parent "
469                          "directory %s. Error was %s\n",
470                          smb_fname_str_dbg(smb_fname_parent),
471                          strerror(errno)));
472                 TALLOC_FREE(smb_fname_parent);
473                 return;
474         }
475
476         if (smb_fname_parent->st.st_ex_uid == fsp->fsp_name->st.st_ex_uid) {
477                 /* Already this uid - no need to change. */
478                 DEBUG(10,("change_file_owner_to_parent: file %s "
479                         "is already owned by uid %d\n",
480                         fsp_str_dbg(fsp),
481                         (int)fsp->fsp_name->st.st_ex_uid ));
482                 TALLOC_FREE(smb_fname_parent);
483                 return;
484         }
485
486         become_root();
487         ret = SMB_VFS_FCHOWN(fsp, smb_fname_parent->st.st_ex_uid, (gid_t)-1);
488         unbecome_root();
489         if (ret == -1) {
490                 DEBUG(0,("change_file_owner_to_parent: failed to fchown "
491                          "file %s to parent directory uid %u. Error "
492                          "was %s\n", fsp_str_dbg(fsp),
493                          (unsigned int)smb_fname_parent->st.st_ex_uid,
494                          strerror(errno) ));
495         } else {
496                 DEBUG(10,("change_file_owner_to_parent: changed new file %s to "
497                         "parent directory uid %u.\n", fsp_str_dbg(fsp),
498                         (unsigned int)smb_fname_parent->st.st_ex_uid));
499                 /* Ensure the uid entry is updated. */
500                 fsp->fsp_name->st.st_ex_uid = smb_fname_parent->st.st_ex_uid;
501         }
502
503         TALLOC_FREE(smb_fname_parent);
504 }
505
506 NTSTATUS change_dir_owner_to_parent(connection_struct *conn,
507                                        const char *inherit_from_dir,
508                                        const char *fname,
509                                        SMB_STRUCT_STAT *psbuf)
510 {
511         struct smb_filename *smb_fname_parent;
512         struct smb_filename *smb_fname_cwd = NULL;
513         char *saved_dir = NULL;
514         TALLOC_CTX *ctx = talloc_tos();
515         NTSTATUS status = NT_STATUS_OK;
516         int ret;
517
518         smb_fname_parent = synthetic_smb_fname(ctx, inherit_from_dir,
519                                                NULL, NULL);
520         if (smb_fname_parent == NULL) {
521                 return NT_STATUS_NO_MEMORY;
522         }
523
524         ret = SMB_VFS_STAT(conn, smb_fname_parent);
525         if (ret == -1) {
526                 status = map_nt_error_from_unix(errno);
527                 DEBUG(0,("change_dir_owner_to_parent: failed to stat parent "
528                          "directory %s. Error was %s\n",
529                          smb_fname_str_dbg(smb_fname_parent),
530                          strerror(errno)));
531                 goto out;
532         }
533
534         /* We've already done an lstat into psbuf, and we know it's a
535            directory. If we can cd into the directory and the dev/ino
536            are the same then we can safely chown without races as
537            we're locking the directory in place by being in it.  This
538            should work on any UNIX (thanks tridge :-). JRA.
539         */
540
541         saved_dir = vfs_GetWd(ctx,conn);
542         if (!saved_dir) {
543                 status = map_nt_error_from_unix(errno);
544                 DEBUG(0,("change_dir_owner_to_parent: failed to get "
545                          "current working directory. Error was %s\n",
546                          strerror(errno)));
547                 goto out;
548         }
549
550         /* Chdir into the new path. */
551         if (vfs_ChDir(conn, fname) == -1) {
552                 status = map_nt_error_from_unix(errno);
553                 DEBUG(0,("change_dir_owner_to_parent: failed to change "
554                          "current working directory to %s. Error "
555                          "was %s\n", fname, strerror(errno) ));
556                 goto chdir;
557         }
558
559         smb_fname_cwd = synthetic_smb_fname(ctx, ".", NULL, NULL);
560         if (smb_fname_cwd == NULL) {
561                 status = NT_STATUS_NO_MEMORY;
562                 goto chdir;
563         }
564
565         ret = SMB_VFS_STAT(conn, smb_fname_cwd);
566         if (ret == -1) {
567                 status = map_nt_error_from_unix(errno);
568                 DEBUG(0,("change_dir_owner_to_parent: failed to stat "
569                          "directory '.' (%s) Error was %s\n",
570                          fname, strerror(errno)));
571                 goto chdir;
572         }
573
574         /* Ensure we're pointing at the same place. */
575         if (smb_fname_cwd->st.st_ex_dev != psbuf->st_ex_dev ||
576             smb_fname_cwd->st.st_ex_ino != psbuf->st_ex_ino) {
577                 DEBUG(0,("change_dir_owner_to_parent: "
578                          "device/inode on directory %s changed. "
579                          "Refusing to chown !\n", fname ));
580                 status = NT_STATUS_ACCESS_DENIED;
581                 goto chdir;
582         }
583
584         if (smb_fname_parent->st.st_ex_uid == smb_fname_cwd->st.st_ex_uid) {
585                 /* Already this uid - no need to change. */
586                 DEBUG(10,("change_dir_owner_to_parent: directory %s "
587                         "is already owned by uid %d\n",
588                         fname,
589                         (int)smb_fname_cwd->st.st_ex_uid ));
590                 status = NT_STATUS_OK;
591                 goto chdir;
592         }
593
594         become_root();
595         ret = SMB_VFS_LCHOWN(conn,
596                         smb_fname_cwd,
597                         smb_fname_parent->st.st_ex_uid,
598                         (gid_t)-1);
599         unbecome_root();
600         if (ret == -1) {
601                 status = map_nt_error_from_unix(errno);
602                 DEBUG(10,("change_dir_owner_to_parent: failed to chown "
603                           "directory %s to parent directory uid %u. "
604                           "Error was %s\n", fname,
605                           (unsigned int)smb_fname_parent->st.st_ex_uid,
606                           strerror(errno) ));
607         } else {
608                 DEBUG(10,("change_dir_owner_to_parent: changed ownership of new "
609                         "directory %s to parent directory uid %u.\n",
610                         fname, (unsigned int)smb_fname_parent->st.st_ex_uid ));
611                 /* Ensure the uid entry is updated. */
612                 psbuf->st_ex_uid = smb_fname_parent->st.st_ex_uid;
613         }
614
615  chdir:
616         vfs_ChDir(conn,saved_dir);
617  out:
618         TALLOC_FREE(smb_fname_parent);
619         TALLOC_FREE(smb_fname_cwd);
620         return status;
621 }
622
623 /****************************************************************************
624  Open a file - returning a guaranteed ATOMIC indication of if the
625  file was created or not.
626 ****************************************************************************/
627
628 static NTSTATUS fd_open_atomic(struct connection_struct *conn,
629                         files_struct *fsp,
630                         int flags,
631                         mode_t mode,
632                         bool *file_created)
633 {
634         NTSTATUS status = NT_STATUS_UNSUCCESSFUL;
635         bool file_existed = VALID_STAT(fsp->fsp_name->st);
636
637         *file_created = false;
638
639         if (!(flags & O_CREAT)) {
640                 /*
641                  * We're not creating the file, just pass through.
642                  */
643                 return fd_open(conn, fsp, flags, mode);
644         }
645
646         if (flags & O_EXCL) {
647                 /*
648                  * Fail if already exists, just pass through.
649                  */
650                 status = fd_open(conn, fsp, flags, mode);
651
652                 /*
653                  * Here we've opened with O_CREAT|O_EXCL. If that went
654                  * NT_STATUS_OK, we *know* we created this file.
655                  */
656                 *file_created = NT_STATUS_IS_OK(status);
657
658                 return status;
659         }
660
661         /*
662          * Now it gets tricky. We have O_CREAT, but not O_EXCL.
663          * To know absolutely if we created the file or not,
664          * we can never call O_CREAT without O_EXCL. So if
665          * we think the file existed, try without O_CREAT|O_EXCL.
666          * If we think the file didn't exist, try with
667          * O_CREAT|O_EXCL. Keep bouncing between these two
668          * requests until either the file is created, or
669          * opened. Either way, we keep going until we get
670          * a returnable result (error, or open/create).
671          */
672
673         while(1) {
674                 int curr_flags = flags;
675
676                 if (file_existed) {
677                         /* Just try open, do not create. */
678                         curr_flags &= ~(O_CREAT);
679                         status = fd_open(conn, fsp, curr_flags, mode);
680                         if (NT_STATUS_EQUAL(status,
681                                         NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
682                                 /*
683                                  * Someone deleted it in the meantime.
684                                  * Retry with O_EXCL.
685                                  */
686                                 file_existed = false;
687                                 DEBUG(10,("fd_open_atomic: file %s existed. "
688                                         "Retry.\n",
689                                         smb_fname_str_dbg(fsp->fsp_name)));
690                                         continue;
691                         }
692                 } else {
693                         /* Try create exclusively, fail if it exists. */
694                         curr_flags |= O_EXCL;
695                         status = fd_open(conn, fsp, curr_flags, mode);
696                         if (NT_STATUS_EQUAL(status,
697                                         NT_STATUS_OBJECT_NAME_COLLISION)) {
698                                 /*
699                                  * Someone created it in the meantime.
700                                  * Retry without O_CREAT.
701                                  */
702                                 file_existed = true;
703                                 DEBUG(10,("fd_open_atomic: file %s "
704                                         "did not exist. Retry.\n",
705                                         smb_fname_str_dbg(fsp->fsp_name)));
706                                 continue;
707                         }
708                         if (NT_STATUS_IS_OK(status)) {
709                                 /*
710                                  * Here we've opened with O_CREAT|O_EXCL
711                                  * and got success. We *know* we created
712                                  * this file.
713                                  */
714                                 *file_created = true;
715                         }
716                 }
717                 /* Create is done, or failed. */
718                 break;
719         }
720         return status;
721 }
722
723 /****************************************************************************
724  Open a file.
725 ****************************************************************************/
726
727 static NTSTATUS open_file(files_struct *fsp,
728                           connection_struct *conn,
729                           struct smb_request *req,
730                           const char *parent_dir,
731                           int flags,
732                           mode_t unx_mode,
733                           uint32_t access_mask, /* client requested access mask. */
734                           uint32_t open_access_mask, /* what we're actually using in the open. */
735                           bool *p_file_created)
736 {
737         struct smb_filename *smb_fname = fsp->fsp_name;
738         NTSTATUS status = NT_STATUS_OK;
739         int accmode = (flags & O_ACCMODE);
740         int local_flags = flags;
741         bool file_existed = VALID_STAT(fsp->fsp_name->st);
742
743         fsp->fh->fd = -1;
744         errno = EPERM;
745
746         /* Check permissions */
747
748         /*
749          * This code was changed after seeing a client open request 
750          * containing the open mode of (DENY_WRITE/read-only) with
751          * the 'create if not exist' bit set. The previous code
752          * would fail to open the file read only on a read-only share
753          * as it was checking the flags parameter  directly against O_RDONLY,
754          * this was failing as the flags parameter was set to O_RDONLY|O_CREAT.
755          * JRA.
756          */
757
758         if (!CAN_WRITE(conn)) {
759                 /* It's a read-only share - fail if we wanted to write. */
760                 if(accmode != O_RDONLY || (flags & O_TRUNC) || (flags & O_APPEND)) {
761                         DEBUG(3,("Permission denied opening %s\n",
762                                  smb_fname_str_dbg(smb_fname)));
763                         return NT_STATUS_ACCESS_DENIED;
764                 }
765                 if (flags & O_CREAT) {
766                         /* We don't want to write - but we must make sure that
767                            O_CREAT doesn't create the file if we have write
768                            access into the directory.
769                         */
770                         flags &= ~(O_CREAT|O_EXCL);
771                         local_flags &= ~(O_CREAT|O_EXCL);
772                 }
773         }
774
775         /*
776          * This little piece of insanity is inspired by the
777          * fact that an NT client can open a file for O_RDONLY,
778          * but set the create disposition to FILE_EXISTS_TRUNCATE.
779          * If the client *can* write to the file, then it expects to
780          * truncate the file, even though it is opening for readonly.
781          * Quicken uses this stupid trick in backup file creation...
782          * Thanks *greatly* to "David W. Chapman Jr." <dwcjr@inethouston.net>
783          * for helping track this one down. It didn't bite us in 2.0.x
784          * as we always opened files read-write in that release. JRA.
785          */
786
787         if ((accmode == O_RDONLY) && ((flags & O_TRUNC) == O_TRUNC)) {
788                 DEBUG(10,("open_file: truncate requested on read-only open "
789                           "for file %s\n", smb_fname_str_dbg(smb_fname)));
790                 local_flags = (flags & ~O_ACCMODE)|O_RDWR;
791         }
792
793         if ((open_access_mask & (FILE_READ_DATA|FILE_WRITE_DATA|FILE_APPEND_DATA|FILE_EXECUTE)) ||
794             (!file_existed && (local_flags & O_CREAT)) ||
795             ((local_flags & O_TRUNC) == O_TRUNC) ) {
796                 const char *wild;
797                 int ret;
798
799 #if defined(O_NONBLOCK) && defined(S_ISFIFO)
800                 /*
801                  * We would block on opening a FIFO with no one else on the
802                  * other end. Do what we used to do and add O_NONBLOCK to the
803                  * open flags. JRA.
804                  */
805
806                 if (file_existed && S_ISFIFO(smb_fname->st.st_ex_mode)) {
807                         local_flags &= ~O_TRUNC; /* Can't truncate a FIFO. */
808                         local_flags |= O_NONBLOCK;
809                 }
810 #endif
811
812                 /* Don't create files with Microsoft wildcard characters. */
813                 if (fsp->base_fsp) {
814                         /*
815                          * wildcard characters are allowed in stream names
816                          * only test the basefilename
817                          */
818                         wild = fsp->base_fsp->fsp_name->base_name;
819                 } else {
820                         wild = smb_fname->base_name;
821                 }
822                 if ((local_flags & O_CREAT) && !file_existed &&
823                     !(fsp->posix_flags & FSP_POSIX_FLAGS_PATHNAMES) &&
824                     ms_has_wild(wild))  {
825                         return NT_STATUS_OBJECT_NAME_INVALID;
826                 }
827
828                 /* Can we access this file ? */
829                 if (!fsp->base_fsp) {
830                         /* Only do this check on non-stream open. */
831                         if (file_existed) {
832                                 status = smbd_check_access_rights(conn,
833                                                 smb_fname,
834                                                 false,
835                                                 access_mask);
836
837                                 if (!NT_STATUS_IS_OK(status)) {
838                                         DEBUG(10, ("open_file: "
839                                                    "smbd_check_access_rights "
840                                                    "on file %s returned %s\n",
841                                                    smb_fname_str_dbg(smb_fname),
842                                                    nt_errstr(status)));
843                                 }
844
845                                 if (!NT_STATUS_IS_OK(status) &&
846                                     !NT_STATUS_EQUAL(status,
847                                         NT_STATUS_OBJECT_NAME_NOT_FOUND))
848                                 {
849                                         return status;
850                                 }
851
852                                 if (NT_STATUS_EQUAL(status,
853                                         NT_STATUS_OBJECT_NAME_NOT_FOUND))
854                                 {
855                                         DEBUG(10, ("open_file: "
856                                                 "file %s vanished since we "
857                                                 "checked for existence.\n",
858                                                 smb_fname_str_dbg(smb_fname)));
859                                         file_existed = false;
860                                         SET_STAT_INVALID(fsp->fsp_name->st);
861                                 }
862                         }
863
864                         if (!file_existed) {
865                                 if (!(local_flags & O_CREAT)) {
866                                         /* File didn't exist and no O_CREAT. */
867                                         return NT_STATUS_OBJECT_NAME_NOT_FOUND;
868                                 }
869
870                                 status = check_parent_access(conn,
871                                                              smb_fname,
872                                                              SEC_DIR_ADD_FILE);
873                                 if (!NT_STATUS_IS_OK(status)) {
874                                         DEBUG(10, ("open_file: "
875                                                    "check_parent_access on "
876                                                    "file %s returned %s\n",
877                                                    smb_fname_str_dbg(smb_fname),
878                                                    nt_errstr(status) ));
879                                         return status;
880                                 }
881                         }
882                 }
883
884                 /*
885                  * Actually do the open - if O_TRUNC is needed handle it
886                  * below under the share mode lock.
887                  */
888                 status = fd_open_atomic(conn, fsp, local_flags & ~O_TRUNC,
889                                 unx_mode, p_file_created);
890                 if (!NT_STATUS_IS_OK(status)) {
891                         DEBUG(3,("Error opening file %s (%s) (local_flags=%d) "
892                                  "(flags=%d)\n", smb_fname_str_dbg(smb_fname),
893                                  nt_errstr(status),local_flags,flags));
894                         return status;
895                 }
896
897                 ret = SMB_VFS_FSTAT(fsp, &smb_fname->st);
898                 if (ret == -1) {
899                         /* If we have an fd, this stat should succeed. */
900                         DEBUG(0,("Error doing fstat on open file %s "
901                                 "(%s)\n",
902                                 smb_fname_str_dbg(smb_fname),
903                                 strerror(errno) ));
904                         status = map_nt_error_from_unix(errno);
905                         fd_close(fsp);
906                         return status;
907                 }
908
909                 if (*p_file_created) {
910                         /* We created this file. */
911
912                         bool need_re_stat = false;
913                         /* Do all inheritance work after we've
914                            done a successful fstat call and filled
915                            in the stat struct in fsp->fsp_name. */
916
917                         /* Inherit the ACL if required */
918                         if (lp_inherit_permissions(SNUM(conn))) {
919                                 inherit_access_posix_acl(conn, parent_dir,
920                                                          smb_fname->base_name,
921                                                          unx_mode);
922                                 need_re_stat = true;
923                         }
924
925                         /* Change the owner if required. */
926                         if (lp_inherit_owner(SNUM(conn))) {
927                                 change_file_owner_to_parent(conn, parent_dir,
928                                                             fsp);
929                                 need_re_stat = true;
930                         }
931
932                         if (need_re_stat) {
933                                 ret = SMB_VFS_FSTAT(fsp, &smb_fname->st);
934                                 /* If we have an fd, this stat should succeed. */
935                                 if (ret == -1) {
936                                         DEBUG(0,("Error doing fstat on open file %s "
937                                                  "(%s)\n",
938                                                  smb_fname_str_dbg(smb_fname),
939                                                  strerror(errno) ));
940                                 }
941                         }
942
943                         notify_fname(conn, NOTIFY_ACTION_ADDED,
944                                      FILE_NOTIFY_CHANGE_FILE_NAME,
945                                      smb_fname->base_name);
946                 }
947         } else {
948                 fsp->fh->fd = -1; /* What we used to call a stat open. */
949                 if (!file_existed) {
950                         /* File must exist for a stat open. */
951                         return NT_STATUS_OBJECT_NAME_NOT_FOUND;
952                 }
953
954                 status = smbd_check_access_rights(conn,
955                                 smb_fname,
956                                 false,
957                                 access_mask);
958
959                 if (NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND) &&
960                                 (fsp->posix_flags & FSP_POSIX_FLAGS_OPEN) &&
961                                 S_ISLNK(smb_fname->st.st_ex_mode)) {
962                         /* This is a POSIX stat open for delete
963                          * or rename on a symlink that points
964                          * nowhere. Allow. */
965                         DEBUG(10,("open_file: allowing POSIX "
966                                   "open on bad symlink %s\n",
967                                   smb_fname_str_dbg(smb_fname)));
968                         status = NT_STATUS_OK;
969                 }
970
971                 if (!NT_STATUS_IS_OK(status)) {
972                         DEBUG(10,("open_file: "
973                                 "smbd_check_access_rights on file "
974                                 "%s returned %s\n",
975                                 smb_fname_str_dbg(smb_fname),
976                                 nt_errstr(status) ));
977                         return status;
978                 }
979         }
980
981         /*
982          * POSIX allows read-only opens of directories. We don't
983          * want to do this (we use a different code path for this)
984          * so catch a directory open and return an EISDIR. JRA.
985          */
986
987         if(S_ISDIR(smb_fname->st.st_ex_mode)) {
988                 fd_close(fsp);
989                 errno = EISDIR;
990                 return NT_STATUS_FILE_IS_A_DIRECTORY;
991         }
992
993         fsp->file_id = vfs_file_id_from_sbuf(conn, &smb_fname->st);
994         fsp->vuid = req ? req->vuid : UID_FIELD_INVALID;
995         fsp->file_pid = req ? req->smbpid : 0;
996         fsp->can_lock = True;
997         fsp->can_read = ((access_mask & FILE_READ_DATA) != 0);
998         fsp->can_write =
999                 CAN_WRITE(conn) &&
1000                 ((access_mask & (FILE_WRITE_DATA | FILE_APPEND_DATA)) != 0);
1001         fsp->print_file = NULL;
1002         fsp->modified = False;
1003         fsp->sent_oplock_break = NO_BREAK_SENT;
1004         fsp->is_directory = False;
1005         if (conn->aio_write_behind_list &&
1006             is_in_path(smb_fname->base_name, conn->aio_write_behind_list,
1007                        conn->case_sensitive)) {
1008                 fsp->aio_write_behind = True;
1009         }
1010
1011         fsp->wcp = NULL; /* Write cache pointer. */
1012
1013         DEBUG(2,("%s opened file %s read=%s write=%s (numopen=%d)\n",
1014                  conn->session_info->unix_info->unix_name,
1015                  smb_fname_str_dbg(smb_fname),
1016                  BOOLSTR(fsp->can_read), BOOLSTR(fsp->can_write),
1017                  conn->num_files_open));
1018
1019         errno = 0;
1020         return NT_STATUS_OK;
1021 }
1022
1023 /****************************************************************************
1024  Check if we can open a file with a share mode.
1025  Returns True if conflict, False if not.
1026 ****************************************************************************/
1027
1028 static bool share_conflict(struct share_mode_entry *entry,
1029                            uint32_t access_mask,
1030                            uint32_t share_access)
1031 {
1032         DEBUG(10,("share_conflict: entry->access_mask = 0x%x, "
1033                   "entry->share_access = 0x%x, "
1034                   "entry->private_options = 0x%x\n",
1035                   (unsigned int)entry->access_mask,
1036                   (unsigned int)entry->share_access,
1037                   (unsigned int)entry->private_options));
1038
1039         if (server_id_is_disconnected(&entry->pid)) {
1040                 /*
1041                  * note: cleanup should have been done by
1042                  * delay_for_batch_oplocks()
1043                  */
1044                 return false;
1045         }
1046
1047         DEBUG(10,("share_conflict: access_mask = 0x%x, share_access = 0x%x\n",
1048                   (unsigned int)access_mask, (unsigned int)share_access));
1049
1050         if ((entry->access_mask & (FILE_WRITE_DATA|
1051                                    FILE_APPEND_DATA|
1052                                    FILE_READ_DATA|
1053                                    FILE_EXECUTE|
1054                                    DELETE_ACCESS)) == 0) {
1055                 DEBUG(10,("share_conflict: No conflict due to "
1056                           "entry->access_mask = 0x%x\n",
1057                           (unsigned int)entry->access_mask ));
1058                 return False;
1059         }
1060
1061         if ((access_mask & (FILE_WRITE_DATA|
1062                             FILE_APPEND_DATA|
1063                             FILE_READ_DATA|
1064                             FILE_EXECUTE|
1065                             DELETE_ACCESS)) == 0) {
1066                 DEBUG(10,("share_conflict: No conflict due to "
1067                           "access_mask = 0x%x\n",
1068                           (unsigned int)access_mask ));
1069                 return False;
1070         }
1071
1072 #if 1 /* JRA TEST - Superdebug. */
1073 #define CHECK_MASK(num, am, right, sa, share) \
1074         DEBUG(10,("share_conflict: [%d] am (0x%x) & right (0x%x) = 0x%x\n", \
1075                 (unsigned int)(num), (unsigned int)(am), \
1076                 (unsigned int)(right), (unsigned int)(am)&(right) )); \
1077         DEBUG(10,("share_conflict: [%d] sa (0x%x) & share (0x%x) = 0x%x\n", \
1078                 (unsigned int)(num), (unsigned int)(sa), \
1079                 (unsigned int)(share), (unsigned int)(sa)&(share) )); \
1080         if (((am) & (right)) && !((sa) & (share))) { \
1081                 DEBUG(10,("share_conflict: check %d conflict am = 0x%x, right = 0x%x, \
1082 sa = 0x%x, share = 0x%x\n", (num), (unsigned int)(am), (unsigned int)(right), (unsigned int)(sa), \
1083                         (unsigned int)(share) )); \
1084                 return True; \
1085         }
1086 #else
1087 #define CHECK_MASK(num, am, right, sa, share) \
1088         if (((am) & (right)) && !((sa) & (share))) { \
1089                 DEBUG(10,("share_conflict: check %d conflict am = 0x%x, right = 0x%x, \
1090 sa = 0x%x, share = 0x%x\n", (num), (unsigned int)(am), (unsigned int)(right), (unsigned int)(sa), \
1091                         (unsigned int)(share) )); \
1092                 return True; \
1093         }
1094 #endif
1095
1096         CHECK_MASK(1, entry->access_mask, FILE_WRITE_DATA | FILE_APPEND_DATA,
1097                    share_access, FILE_SHARE_WRITE);
1098         CHECK_MASK(2, access_mask, FILE_WRITE_DATA | FILE_APPEND_DATA,
1099                    entry->share_access, FILE_SHARE_WRITE);
1100
1101         CHECK_MASK(3, entry->access_mask, FILE_READ_DATA | FILE_EXECUTE,
1102                    share_access, FILE_SHARE_READ);
1103         CHECK_MASK(4, access_mask, FILE_READ_DATA | FILE_EXECUTE,
1104                    entry->share_access, FILE_SHARE_READ);
1105
1106         CHECK_MASK(5, entry->access_mask, DELETE_ACCESS,
1107                    share_access, FILE_SHARE_DELETE);
1108         CHECK_MASK(6, access_mask, DELETE_ACCESS,
1109                    entry->share_access, FILE_SHARE_DELETE);
1110
1111         DEBUG(10,("share_conflict: No conflict.\n"));
1112         return False;
1113 }
1114
1115 #if defined(DEVELOPER)
1116 static void validate_my_share_entries(struct smbd_server_connection *sconn,
1117                                       int num,
1118                                       struct share_mode_entry *share_entry)
1119 {
1120         struct server_id self = messaging_server_id(sconn->msg_ctx);
1121         files_struct *fsp;
1122
1123         if (!serverid_equal(&self, &share_entry->pid)) {
1124                 return;
1125         }
1126
1127         if (share_entry->op_mid == 0) {
1128                 /* INTERNAL_OPEN_ONLY */
1129                 return;
1130         }
1131
1132         if (!is_valid_share_mode_entry(share_entry)) {
1133                 return;
1134         }
1135
1136         fsp = file_find_dif(sconn, share_entry->id,
1137                             share_entry->share_file_id);
1138         if (!fsp) {
1139                 DEBUG(0,("validate_my_share_entries: PANIC : %s\n",
1140                          share_mode_str(talloc_tos(), num, share_entry) ));
1141                 smb_panic("validate_my_share_entries: Cannot match a "
1142                           "share entry with an open file\n");
1143         }
1144
1145         if (((uint16_t)fsp->oplock_type) != share_entry->op_type) {
1146                 goto panic;
1147         }
1148
1149         return;
1150
1151  panic:
1152         {
1153                 char *str;
1154                 DEBUG(0,("validate_my_share_entries: PANIC : %s\n",
1155                          share_mode_str(talloc_tos(), num, share_entry) ));
1156                 str = talloc_asprintf(talloc_tos(),
1157                         "validate_my_share_entries: "
1158                         "file %s, oplock_type = 0x%x, op_type = 0x%x\n",
1159                          fsp->fsp_name->base_name,
1160                          (unsigned int)fsp->oplock_type,
1161                          (unsigned int)share_entry->op_type );
1162                 smb_panic(str);
1163         }
1164 }
1165 #endif
1166
1167 bool is_stat_open(uint32_t access_mask)
1168 {
1169         const uint32_t stat_open_bits =
1170                 (SYNCHRONIZE_ACCESS|
1171                  FILE_READ_ATTRIBUTES|
1172                  FILE_WRITE_ATTRIBUTES);
1173
1174         return (((access_mask &  stat_open_bits) != 0) &&
1175                 ((access_mask & ~stat_open_bits) == 0));
1176 }
1177
1178 static bool has_delete_on_close(struct share_mode_lock *lck,
1179                                 uint32_t name_hash)
1180 {
1181         struct share_mode_data *d = lck->data;
1182         uint32_t i;
1183
1184         if (d->num_share_modes == 0) {
1185                 return false;
1186         }
1187         if (!is_delete_on_close_set(lck, name_hash)) {
1188                 return false;
1189         }
1190         for (i=0; i<d->num_share_modes; i++) {
1191                 if (!share_mode_stale_pid(d, i)) {
1192                         return true;
1193                 }
1194         }
1195         return false;
1196 }
1197
1198 /****************************************************************************
1199  Deal with share modes
1200  Invariant: Share mode must be locked on entry and exit.
1201  Returns -1 on error, or number of share modes on success (may be zero).
1202 ****************************************************************************/
1203
1204 static NTSTATUS open_mode_check(connection_struct *conn,
1205                                 struct share_mode_lock *lck,
1206                                 uint32_t access_mask,
1207                                 uint32_t share_access)
1208 {
1209         int i;
1210
1211         if(lck->data->num_share_modes == 0) {
1212                 return NT_STATUS_OK;
1213         }
1214
1215         if (is_stat_open(access_mask)) {
1216                 /* Stat open that doesn't trigger oplock breaks or share mode
1217                  * checks... ! JRA. */
1218                 return NT_STATUS_OK;
1219         }
1220
1221         /*
1222          * Check if the share modes will give us access.
1223          */
1224
1225 #if defined(DEVELOPER)
1226         for(i = 0; i < lck->data->num_share_modes; i++) {
1227                 validate_my_share_entries(conn->sconn, i,
1228                                           &lck->data->share_modes[i]);
1229         }
1230 #endif
1231
1232         /* Now we check the share modes, after any oplock breaks. */
1233         for(i = 0; i < lck->data->num_share_modes; i++) {
1234
1235                 if (!is_valid_share_mode_entry(&lck->data->share_modes[i])) {
1236                         continue;
1237                 }
1238
1239                 /* someone else has a share lock on it, check to see if we can
1240                  * too */
1241                 if (share_conflict(&lck->data->share_modes[i],
1242                                    access_mask, share_access)) {
1243
1244                         if (share_mode_stale_pid(lck->data, i)) {
1245                                 continue;
1246                         }
1247
1248                         return NT_STATUS_SHARING_VIOLATION;
1249                 }
1250         }
1251
1252         return NT_STATUS_OK;
1253 }
1254
1255 /*
1256  * Send a break message to the oplock holder and delay the open for
1257  * our client.
1258  */
1259
1260 NTSTATUS send_break_message(struct messaging_context *msg_ctx,
1261                                    const struct share_mode_entry *exclusive,
1262                                    uint16_t break_to)
1263 {
1264         NTSTATUS status;
1265         char msg[MSG_SMB_SHARE_MODE_ENTRY_SIZE];
1266         struct server_id_buf tmp;
1267
1268         DEBUG(10, ("Sending break request to PID %s\n",
1269                    server_id_str_buf(exclusive->pid, &tmp)));
1270
1271         /* Create the message. */
1272         share_mode_entry_to_message(msg, exclusive);
1273
1274         /* Overload entry->op_type */
1275         /*
1276          * This is a cut from uint32_t to uint16_t, but so far only the lower 3
1277          * bits (LEASE_WRITE/HANDLE/READ are used anyway.
1278          */
1279         SSVAL(msg,OP_BREAK_MSG_OP_TYPE_OFFSET, break_to);
1280
1281         status = messaging_send_buf(msg_ctx, exclusive->pid,
1282                                     MSG_SMB_BREAK_REQUEST,
1283                                     (uint8_t *)msg, sizeof(msg));
1284         if (!NT_STATUS_IS_OK(status)) {
1285                 DEBUG(3, ("Could not send oplock break message: %s\n",
1286                           nt_errstr(status)));
1287         }
1288
1289         return status;
1290 }
1291
1292 /*
1293  * Do internal consistency checks on the share mode for a file.
1294  */
1295
1296 static bool validate_oplock_types(struct share_mode_lock *lck)
1297 {
1298         struct share_mode_data *d = lck->data;
1299         bool batch = false;
1300         bool ex_or_batch = false;
1301         bool level2 = false;
1302         bool no_oplock = false;
1303         uint32_t num_non_stat_opens = 0;
1304         uint32_t i;
1305
1306         for (i=0; i<d->num_share_modes; i++) {
1307                 struct share_mode_entry *e = &d->share_modes[i];
1308
1309                 if (!is_valid_share_mode_entry(e)) {
1310                         continue;
1311                 }
1312
1313                 if (e->op_mid == 0) {
1314                         /* INTERNAL_OPEN_ONLY */
1315                         continue;
1316                 }
1317
1318                 if (e->op_type == NO_OPLOCK && is_stat_open(e->access_mask)) {
1319                         /* We ignore stat opens in the table - they
1320                            always have NO_OPLOCK and never get or
1321                            cause breaks. JRA. */
1322                         continue;
1323                 }
1324
1325                 num_non_stat_opens += 1;
1326
1327                 if (BATCH_OPLOCK_TYPE(e->op_type)) {
1328                         /* batch - can only be one. */
1329                         if (share_mode_stale_pid(d, i)) {
1330                                 DEBUG(10, ("Found stale batch oplock\n"));
1331                                 continue;
1332                         }
1333                         if (ex_or_batch || batch || level2 || no_oplock) {
1334                                 DEBUG(0, ("Bad batch oplock entry %u.",
1335                                           (unsigned)i));
1336                                 return false;
1337                         }
1338                         batch = true;
1339                 }
1340
1341                 if (EXCLUSIVE_OPLOCK_TYPE(e->op_type)) {
1342                         if (share_mode_stale_pid(d, i)) {
1343                                 DEBUG(10, ("Found stale duplicate oplock\n"));
1344                                 continue;
1345                         }
1346                         /* Exclusive or batch - can only be one. */
1347                         if (ex_or_batch || level2 || no_oplock) {
1348                                 DEBUG(0, ("Bad exclusive or batch oplock "
1349                                           "entry %u.", (unsigned)i));
1350                                 return false;
1351                         }
1352                         ex_or_batch = true;
1353                 }
1354
1355                 if (LEVEL_II_OPLOCK_TYPE(e->op_type)) {
1356                         if (batch || ex_or_batch) {
1357                                 if (share_mode_stale_pid(d, i)) {
1358                                         DEBUG(10, ("Found stale LevelII "
1359                                                    "oplock\n"));
1360                                         continue;
1361                                 }
1362                                 DEBUG(0, ("Bad levelII oplock entry %u.",
1363                                           (unsigned)i));
1364                                 return false;
1365                         }
1366                         level2 = true;
1367                 }
1368
1369                 if (e->op_type == NO_OPLOCK) {
1370                         if (batch || ex_or_batch) {
1371                                 if (share_mode_stale_pid(d, i)) {
1372                                         DEBUG(10, ("Found stale NO_OPLOCK "
1373                                                    "entry\n"));
1374                                         continue;
1375                                 }
1376                                 DEBUG(0, ("Bad no oplock entry %u.",
1377                                           (unsigned)i));
1378                                 return false;
1379                         }
1380                         no_oplock = true;
1381                 }
1382         }
1383
1384         remove_stale_share_mode_entries(d);
1385
1386         if ((batch || ex_or_batch) && (num_non_stat_opens != 1)) {
1387                 DEBUG(1, ("got batch (%d) or ex (%d) non-exclusively (%d)\n",
1388                           (int)batch, (int)ex_or_batch,
1389                           (int)d->num_share_modes));
1390                 return false;
1391         }
1392
1393         return true;
1394 }
1395
1396 static bool delay_for_oplock(files_struct *fsp,
1397                              int oplock_request,
1398                              const struct smb2_lease *lease,
1399                              struct share_mode_lock *lck,
1400                              bool have_sharing_violation,
1401                              uint32_t create_disposition,
1402                              bool first_open_attempt)
1403 {
1404         struct share_mode_data *d = lck->data;
1405         uint32_t i;
1406         bool delay = false;
1407         bool will_overwrite;
1408
1409         if ((oplock_request & INTERNAL_OPEN_ONLY) ||
1410             is_stat_open(fsp->access_mask)) {
1411                 return false;
1412         }
1413
1414         switch (create_disposition) {
1415         case FILE_SUPERSEDE:
1416         case FILE_OVERWRITE:
1417         case FILE_OVERWRITE_IF:
1418                 will_overwrite = true;
1419                 break;
1420         default:
1421                 will_overwrite = false;
1422                 break;
1423         }
1424
1425         for (i=0; i<d->num_share_modes; i++) {
1426                 struct share_mode_entry *e = &d->share_modes[i];
1427                 struct share_mode_lease *l = NULL;
1428                 uint32_t e_lease_type = get_lease_type(d, e);
1429                 uint32_t break_to;
1430                 uint32_t delay_mask = 0;
1431
1432                 if (e->op_type == LEASE_OPLOCK) {
1433                         l = &d->leases[e->lease_idx];
1434                 }
1435
1436                 if (have_sharing_violation) {
1437                         delay_mask = SMB2_LEASE_HANDLE;
1438                 } else {
1439                         delay_mask = SMB2_LEASE_WRITE;
1440                 }
1441
1442                 break_to = e_lease_type & ~delay_mask;
1443
1444                 if (will_overwrite) {
1445                         /*
1446                          * we'll decide about SMB2_LEASE_READ later.
1447                          *
1448                          * Maybe the break will be defered
1449                          */
1450                         break_to &= ~SMB2_LEASE_HANDLE;
1451                 }
1452
1453                 DEBUG(10, ("entry %u: e_lease_type %u, will_overwrite: %u\n",
1454                            (unsigned)i, (unsigned)e_lease_type,
1455                            (unsigned)will_overwrite));
1456
1457                 if (lease != NULL && l != NULL) {
1458                         bool ign;
1459
1460                         ign = smb2_lease_equal(fsp_client_guid(fsp),
1461                                                &lease->lease_key,
1462                                                &l->client_guid,
1463                                                &l->lease_key);
1464                         if (ign) {
1465                                 continue;
1466                         }
1467                 }
1468
1469                 if ((e_lease_type & ~break_to) == 0) {
1470                         if (l != NULL && l->breaking) {
1471                                 delay = true;
1472                         }
1473                         continue;
1474                 }
1475
1476                 if (share_mode_stale_pid(d, i)) {
1477                         continue;
1478                 }
1479
1480                 if (will_overwrite) {
1481                         /*
1482                          * If we break anyway break to NONE directly.
1483                          * Otherwise vfs_set_filelen() will trigger the
1484                          * break.
1485                          */
1486                         break_to &= ~(SMB2_LEASE_READ|SMB2_LEASE_WRITE);
1487                 }
1488
1489                 if (e->op_type != LEASE_OPLOCK) {
1490                         /*
1491                          * Oplocks only support breaking to R or NONE.
1492                          */
1493                         break_to &= ~(SMB2_LEASE_HANDLE|SMB2_LEASE_WRITE);
1494                 }
1495
1496                 DEBUG(10, ("breaking from %d to %d\n",
1497                            (int)e_lease_type, (int)break_to));
1498                 send_break_message(fsp->conn->sconn->msg_ctx, e,
1499                                    break_to);
1500                 if (e_lease_type & delay_mask) {
1501                         delay = true;
1502                 }
1503                 if (l != NULL && l->breaking && !first_open_attempt) {
1504                         delay = true;
1505                 }
1506                 continue;
1507         }
1508
1509         return delay;
1510 }
1511
1512 static bool file_has_brlocks(files_struct *fsp)
1513 {
1514         struct byte_range_lock *br_lck;
1515
1516         br_lck = brl_get_locks_readonly(fsp);
1517         if (!br_lck)
1518                 return false;
1519
1520         return (brl_num_locks(br_lck) > 0);
1521 }
1522
1523 int find_share_mode_lease(struct share_mode_data *d,
1524                           const struct GUID *client_guid,
1525                           const struct smb2_lease_key *key)
1526 {
1527         uint32_t i;
1528
1529         for (i=0; i<d->num_leases; i++) {
1530                 struct share_mode_lease *l = &d->leases[i];
1531
1532                 if (smb2_lease_equal(client_guid,
1533                                      key,
1534                                      &l->client_guid,
1535                                      &l->lease_key)) {
1536                         return i;
1537                 }
1538         }
1539
1540         return -1;
1541 }
1542
1543 struct fsp_lease *find_fsp_lease(struct files_struct *new_fsp,
1544                                  const struct smb2_lease_key *key,
1545                                  const struct share_mode_lease *l)
1546 {
1547         struct files_struct *fsp;
1548
1549         /*
1550          * TODO: Measure how expensive this loop is with thousands of open
1551          * handles...
1552          */
1553
1554         for (fsp = file_find_di_first(new_fsp->conn->sconn, new_fsp->file_id);
1555              fsp != NULL;
1556              fsp = file_find_di_next(fsp)) {
1557
1558                 if (fsp == new_fsp) {
1559                         continue;
1560                 }
1561                 if (fsp->oplock_type != LEASE_OPLOCK) {
1562                         continue;
1563                 }
1564                 if (smb2_lease_key_equal(&fsp->lease->lease.lease_key, key)) {
1565                         fsp->lease->ref_count += 1;
1566                         return fsp->lease;
1567                 }
1568         }
1569
1570         /* Not found - must be leased in another smbd. */
1571         new_fsp->lease = talloc_zero(new_fsp->conn->sconn, struct fsp_lease);
1572         if (new_fsp->lease == NULL) {
1573                 return NULL;
1574         }
1575         new_fsp->lease->ref_count = 1;
1576         new_fsp->lease->sconn = new_fsp->conn->sconn;
1577         new_fsp->lease->lease.lease_key = *key;
1578         new_fsp->lease->lease.lease_state = l->current_state;
1579         /*
1580          * We internally treat all leases as V2 and update
1581          * the epoch, but when sending breaks it matters if
1582          * the requesting lease was v1 or v2.
1583          */
1584         new_fsp->lease->lease.lease_version = l->lease_version;
1585         new_fsp->lease->lease.lease_epoch = l->epoch;
1586         return new_fsp->lease;
1587 }
1588
1589 static NTSTATUS grant_fsp_lease(struct files_struct *fsp,
1590                                 struct share_mode_lock *lck,
1591                                 const struct smb2_lease *lease,
1592                                 uint32_t *p_lease_idx,
1593                                 uint32_t granted)
1594 {
1595         struct share_mode_data *d = lck->data;
1596         const struct GUID *client_guid = fsp_client_guid(fsp);
1597         struct share_mode_lease *tmp;
1598         NTSTATUS status;
1599         int idx;
1600
1601         idx = find_share_mode_lease(d, client_guid, &lease->lease_key);
1602
1603         if (idx != -1) {
1604                 struct share_mode_lease *l = &d->leases[idx];
1605                 bool do_upgrade;
1606                 uint32_t existing, requested;
1607
1608                 fsp->lease = find_fsp_lease(fsp, &lease->lease_key, l);
1609                 if (fsp->lease == NULL) {
1610                         DEBUG(1, ("Did not find existing lease for file %s\n",
1611                                   fsp_str_dbg(fsp)));
1612                         return NT_STATUS_NO_MEMORY;
1613                 }
1614
1615                 *p_lease_idx = idx;
1616
1617                 /*
1618                  * Upgrade only if the requested lease is a strict upgrade.
1619                  */
1620                 existing = l->current_state;
1621                 requested = lease->lease_state;
1622
1623                 /*
1624                  * Tricky: This test makes sure that "requested" is a
1625                  * strict bitwise superset of "existing".
1626                  */
1627                 do_upgrade = ((existing & requested) == existing);
1628
1629                 /*
1630                  * Upgrade only if there's a change.
1631                  */
1632                 do_upgrade &= (granted != existing);
1633
1634                 /*
1635                  * Upgrade only if other leases don't prevent what was asked
1636                  * for.
1637                  */
1638                 do_upgrade &= (granted == requested);
1639
1640                 /*
1641                  * only upgrade if we are not in breaking state
1642                  */
1643                 do_upgrade &= !l->breaking;
1644
1645                 DEBUG(10, ("existing=%"PRIu32", requested=%"PRIu32", "
1646                            "granted=%"PRIu32", do_upgrade=%d\n",
1647                            existing, requested, granted, (int)do_upgrade));
1648
1649                 if (do_upgrade) {
1650                         l->current_state = granted;
1651                         l->epoch += 1;
1652                 }
1653
1654                 /* Ensure we're in sync with current lease state. */
1655                 fsp_lease_update(lck, fsp_client_guid(fsp), fsp->lease);
1656                 return NT_STATUS_OK;
1657         }
1658
1659         /*
1660          * Create new lease
1661          */
1662
1663         tmp = talloc_realloc(d, d->leases, struct share_mode_lease,
1664                              d->num_leases+1);
1665         if (tmp == NULL) {
1666                 /*
1667                  * See [MS-SMB2]
1668                  */
1669                 return NT_STATUS_INSUFFICIENT_RESOURCES;
1670         }
1671         d->leases = tmp;
1672
1673         fsp->lease = talloc_zero(fsp->conn->sconn, struct fsp_lease);
1674         if (fsp->lease == NULL) {
1675                 return NT_STATUS_INSUFFICIENT_RESOURCES;
1676         }
1677         fsp->lease->ref_count = 1;
1678         fsp->lease->sconn = fsp->conn->sconn;
1679         fsp->lease->lease.lease_version = lease->lease_version;
1680         fsp->lease->lease.lease_key = lease->lease_key;
1681         fsp->lease->lease.lease_state = granted;
1682         fsp->lease->lease.lease_epoch = lease->lease_epoch + 1;
1683
1684         *p_lease_idx = d->num_leases;
1685
1686         d->leases[d->num_leases] = (struct share_mode_lease) {
1687                 .client_guid = *client_guid,
1688                 .lease_key = fsp->lease->lease.lease_key,
1689                 .current_state = fsp->lease->lease.lease_state,
1690                 .lease_version = fsp->lease->lease.lease_version,
1691                 .epoch = fsp->lease->lease.lease_epoch,
1692         };
1693
1694         status = leases_db_add(client_guid,
1695                                &lease->lease_key,
1696                                &fsp->file_id,
1697                                fsp->conn->connectpath,
1698                                fsp->fsp_name->base_name,
1699                                fsp->fsp_name->stream_name);
1700         if (!NT_STATUS_IS_OK(status)) {
1701                 DEBUG(10, ("%s: leases_db_add failed: %s\n", __func__,
1702                            nt_errstr(status)));
1703                 TALLOC_FREE(fsp->lease);
1704                 return NT_STATUS_INSUFFICIENT_RESOURCES;
1705         }
1706
1707         d->num_leases += 1;
1708         d->modified = true;
1709
1710         return NT_STATUS_OK;
1711 }
1712
1713 static bool is_same_lease(const files_struct *fsp,
1714                           const struct share_mode_data *d,
1715                           const struct share_mode_entry *e,
1716                           const struct smb2_lease *lease)
1717 {
1718         if (e->op_type != LEASE_OPLOCK) {
1719                 return false;
1720         }
1721         if (lease == NULL) {
1722                 return false;
1723         }
1724
1725         return smb2_lease_equal(fsp_client_guid(fsp),
1726                                 &lease->lease_key,
1727                                 &d->leases[e->lease_idx].client_guid,
1728                                 &d->leases[e->lease_idx].lease_key);
1729 }
1730
1731 static NTSTATUS grant_fsp_oplock_type(struct smb_request *req,
1732                                       struct files_struct *fsp,
1733                                       struct share_mode_lock *lck,
1734                                       int oplock_request,
1735                                       struct smb2_lease *lease)
1736 {
1737         struct share_mode_data *d = lck->data;
1738         bool got_handle_lease = false;
1739         bool got_oplock = false;
1740         uint32_t i;
1741         uint32_t granted;
1742         uint32_t lease_idx = UINT32_MAX;
1743         bool ok;
1744         NTSTATUS status;
1745
1746         if (oplock_request & INTERNAL_OPEN_ONLY) {
1747                 /* No oplocks on internal open. */
1748                 oplock_request = NO_OPLOCK;
1749                 DEBUG(10,("grant_fsp_oplock_type: oplock type 0x%x on file %s\n",
1750                         fsp->oplock_type, fsp_str_dbg(fsp)));
1751         }
1752
1753         if (oplock_request == LEASE_OPLOCK) {
1754                 if (lease == NULL) {
1755                         /*
1756                          * The SMB2 layer should have checked this
1757                          */
1758                         return NT_STATUS_INTERNAL_ERROR;
1759                 }
1760
1761                 granted = lease->lease_state;
1762
1763                 if (lp_kernel_oplocks(SNUM(fsp->conn))) {
1764                         DEBUG(10, ("No lease granted because kernel oplocks are enabled\n"));
1765                         granted = SMB2_LEASE_NONE;
1766                 }
1767                 if ((granted & (SMB2_LEASE_READ|SMB2_LEASE_WRITE)) == 0) {
1768                         DEBUG(10, ("No read or write lease requested\n"));
1769                         granted = SMB2_LEASE_NONE;
1770                 }
1771                 if (granted == SMB2_LEASE_WRITE) {
1772                         DEBUG(10, ("pure write lease requested\n"));
1773                         granted = SMB2_LEASE_NONE;
1774                 }
1775                 if (granted == (SMB2_LEASE_WRITE|SMB2_LEASE_HANDLE)) {
1776                         DEBUG(10, ("write and handle lease requested\n"));
1777                         granted = SMB2_LEASE_NONE;
1778                 }
1779         } else {
1780                 granted = map_oplock_to_lease_type(
1781                         oplock_request & ~SAMBA_PRIVATE_OPLOCK_MASK);
1782         }
1783
1784         if (lp_locking(fsp->conn->params) && file_has_brlocks(fsp)) {
1785                 DEBUG(10,("grant_fsp_oplock_type: file %s has byte range locks\n",
1786                         fsp_str_dbg(fsp)));
1787                 granted &= ~SMB2_LEASE_READ;
1788         }
1789
1790         for (i=0; i<d->num_share_modes; i++) {
1791                 struct share_mode_entry *e = &d->share_modes[i];
1792                 uint32_t e_lease_type;
1793
1794                 e_lease_type = get_lease_type(d, e);
1795
1796                 if ((granted & SMB2_LEASE_WRITE) &&
1797                     !is_same_lease(fsp, d, e, lease) &&
1798                     !share_mode_stale_pid(d, i)) {
1799                         /*
1800                          * Can grant only one writer
1801                          */
1802                         granted &= ~SMB2_LEASE_WRITE;
1803                 }
1804
1805                 if ((e_lease_type & SMB2_LEASE_HANDLE) && !got_handle_lease &&
1806                     !share_mode_stale_pid(d, i)) {
1807                         got_handle_lease = true;
1808                 }
1809
1810                 if ((e->op_type != LEASE_OPLOCK) && !got_oplock &&
1811                     !share_mode_stale_pid(d, i)) {
1812                         got_oplock = true;
1813                 }
1814         }
1815
1816         if ((granted & SMB2_LEASE_READ) && !(granted & SMB2_LEASE_WRITE)) {
1817                 bool allow_level2 =
1818                         (global_client_caps & CAP_LEVEL_II_OPLOCKS) &&
1819                         lp_level2_oplocks(SNUM(fsp->conn));
1820
1821                 if (!allow_level2) {
1822                         granted = SMB2_LEASE_NONE;
1823                 }
1824         }
1825
1826         if (oplock_request == LEASE_OPLOCK) {
1827                 if (got_oplock) {
1828                         granted &= ~SMB2_LEASE_HANDLE;
1829                 }
1830
1831                 fsp->oplock_type = LEASE_OPLOCK;
1832
1833                 status = grant_fsp_lease(fsp, lck, lease, &lease_idx,
1834                                          granted);
1835                 if (!NT_STATUS_IS_OK(status)) {
1836                         return status;
1837
1838                 }
1839                 *lease = fsp->lease->lease;
1840                 DEBUG(10, ("lease_state=%d\n", lease->lease_state));
1841         } else {
1842                 if (got_handle_lease) {
1843                         granted = SMB2_LEASE_NONE;
1844                 }
1845
1846                 switch (granted) {
1847                 case SMB2_LEASE_READ|SMB2_LEASE_WRITE|SMB2_LEASE_HANDLE:
1848                         fsp->oplock_type = BATCH_OPLOCK|EXCLUSIVE_OPLOCK;
1849                         break;
1850                 case SMB2_LEASE_READ|SMB2_LEASE_WRITE:
1851                         fsp->oplock_type = EXCLUSIVE_OPLOCK;
1852                         break;
1853                 case SMB2_LEASE_READ|SMB2_LEASE_HANDLE:
1854                 case SMB2_LEASE_READ:
1855                         fsp->oplock_type = LEVEL_II_OPLOCK;
1856                         break;
1857                 default:
1858                         fsp->oplock_type = NO_OPLOCK;
1859                         break;
1860                 }
1861
1862                 status = set_file_oplock(fsp);
1863                 if (!NT_STATUS_IS_OK(status)) {
1864                         /*
1865                          * Could not get the kernel oplock
1866                          */
1867                         fsp->oplock_type = NO_OPLOCK;
1868                 }
1869         }
1870
1871         ok = set_share_mode(lck, fsp, get_current_uid(fsp->conn),
1872                             req ? req->mid : 0,
1873                             fsp->oplock_type,
1874                             lease_idx);
1875         if (!ok) {
1876                 return NT_STATUS_NO_MEMORY;
1877         }
1878
1879         ok = update_num_read_oplocks(fsp, lck);
1880         if (!ok) {
1881                 del_share_mode(lck, fsp);
1882                 return NT_STATUS_INTERNAL_ERROR;
1883         }
1884
1885         DEBUG(10,("grant_fsp_oplock_type: oplock type 0x%x on file %s\n",
1886                   fsp->oplock_type, fsp_str_dbg(fsp)));
1887
1888         return NT_STATUS_OK;
1889 }
1890
1891 static bool request_timed_out(struct timeval request_time,
1892                               struct timeval timeout)
1893 {
1894         struct timeval now, end_time;
1895         GetTimeOfDay(&now);
1896         end_time = timeval_sum(&request_time, &timeout);
1897         return (timeval_compare(&end_time, &now) < 0);
1898 }
1899
1900 struct defer_open_state {
1901         struct smbXsrv_connection *xconn;
1902         uint64_t mid;
1903 };
1904
1905 static void defer_open_done(struct tevent_req *req);
1906
1907 /****************************************************************************
1908  Handle the 1 second delay in returning a SHARING_VIOLATION error.
1909 ****************************************************************************/
1910
1911 static void defer_open(struct share_mode_lock *lck,
1912                        struct timeval request_time,
1913                        struct timeval timeout,
1914                        struct smb_request *req,
1915                        struct deferred_open_record *state)
1916 {
1917         struct deferred_open_record *open_rec;
1918
1919         DEBUG(10,("defer_open_sharing_error: time [%u.%06u] adding deferred "
1920                   "open entry for mid %llu\n",
1921                   (unsigned int)request_time.tv_sec,
1922                   (unsigned int)request_time.tv_usec,
1923                   (unsigned long long)req->mid));
1924
1925         open_rec = talloc(NULL, struct deferred_open_record);
1926         if (open_rec == NULL) {
1927                 TALLOC_FREE(lck);
1928                 exit_server("talloc failed");
1929         }
1930
1931         *open_rec = *state;
1932
1933         if (lck) {
1934                 struct defer_open_state *watch_state;
1935                 struct tevent_req *watch_req;
1936                 bool ret;
1937
1938                 watch_state = talloc(open_rec, struct defer_open_state);
1939                 if (watch_state == NULL) {
1940                         exit_server("talloc failed");
1941                 }
1942                 watch_state->xconn = req->xconn;
1943                 watch_state->mid = req->mid;
1944
1945                 DEBUG(10, ("defering mid %llu\n",
1946                            (unsigned long long)req->mid));
1947
1948                 watch_req = dbwrap_record_watch_send(
1949                         watch_state, req->sconn->ev_ctx, lck->data->record,
1950                         req->sconn->msg_ctx);
1951                 if (watch_req == NULL) {
1952                         exit_server("Could not watch share mode record");
1953                 }
1954                 tevent_req_set_callback(watch_req, defer_open_done,
1955                                         watch_state);
1956
1957                 ret = tevent_req_set_endtime(
1958                         watch_req, req->sconn->ev_ctx,
1959                         timeval_sum(&request_time, &timeout));
1960                 SMB_ASSERT(ret);
1961         }
1962
1963         if (!push_deferred_open_message_smb(req, request_time, timeout,
1964                                             state->id, open_rec)) {
1965                 TALLOC_FREE(lck);
1966                 exit_server("push_deferred_open_message_smb failed");
1967         }
1968 }
1969
1970 static void defer_open_done(struct tevent_req *req)
1971 {
1972         struct defer_open_state *state = tevent_req_callback_data(
1973                 req, struct defer_open_state);
1974         NTSTATUS status;
1975         bool ret;
1976
1977         status = dbwrap_record_watch_recv(req, talloc_tos(), NULL);
1978         TALLOC_FREE(req);
1979         if (!NT_STATUS_IS_OK(status)) {
1980                 DEBUG(5, ("dbwrap_record_watch_recv returned %s\n",
1981                           nt_errstr(status)));
1982                 /*
1983                  * Even if it failed, retry anyway. TODO: We need a way to
1984                  * tell a re-scheduled open about that error.
1985                  */
1986         }
1987
1988         DEBUG(10, ("scheduling mid %llu\n", (unsigned long long)state->mid));
1989
1990         ret = schedule_deferred_open_message_smb(state->xconn, state->mid);
1991         SMB_ASSERT(ret);
1992         TALLOC_FREE(state);
1993 }
1994
1995
1996 /****************************************************************************
1997  On overwrite open ensure that the attributes match.
1998 ****************************************************************************/
1999
2000 static bool open_match_attributes(connection_struct *conn,
2001                                   uint32_t old_dos_attr,
2002                                   uint32_t new_dos_attr,
2003                                   mode_t existing_unx_mode,
2004                                   mode_t new_unx_mode,
2005                                   mode_t *returned_unx_mode)
2006 {
2007         uint32_t noarch_old_dos_attr, noarch_new_dos_attr;
2008
2009         noarch_old_dos_attr = (old_dos_attr & ~FILE_ATTRIBUTE_ARCHIVE);
2010         noarch_new_dos_attr = (new_dos_attr & ~FILE_ATTRIBUTE_ARCHIVE);
2011
2012         if((noarch_old_dos_attr == 0 && noarch_new_dos_attr != 0) || 
2013            (noarch_old_dos_attr != 0 && ((noarch_old_dos_attr & noarch_new_dos_attr) == noarch_old_dos_attr))) {
2014                 *returned_unx_mode = new_unx_mode;
2015         } else {
2016                 *returned_unx_mode = (mode_t)0;
2017         }
2018
2019         DEBUG(10,("open_match_attributes: old_dos_attr = 0x%x, "
2020                   "existing_unx_mode = 0%o, new_dos_attr = 0x%x "
2021                   "returned_unx_mode = 0%o\n",
2022                   (unsigned int)old_dos_attr,
2023                   (unsigned int)existing_unx_mode,
2024                   (unsigned int)new_dos_attr,
2025                   (unsigned int)*returned_unx_mode ));
2026
2027         /* If we're mapping SYSTEM and HIDDEN ensure they match. */
2028         if (lp_map_system(SNUM(conn)) || lp_store_dos_attributes(SNUM(conn))) {
2029                 if ((old_dos_attr & FILE_ATTRIBUTE_SYSTEM) &&
2030                     !(new_dos_attr & FILE_ATTRIBUTE_SYSTEM)) {
2031                         return False;
2032                 }
2033         }
2034         if (lp_map_hidden(SNUM(conn)) || lp_store_dos_attributes(SNUM(conn))) {
2035                 if ((old_dos_attr & FILE_ATTRIBUTE_HIDDEN) &&
2036                     !(new_dos_attr & FILE_ATTRIBUTE_HIDDEN)) {
2037                         return False;
2038                 }
2039         }
2040         return True;
2041 }
2042
2043 /****************************************************************************
2044  Special FCB or DOS processing in the case of a sharing violation.
2045  Try and find a duplicated file handle.
2046 ****************************************************************************/
2047
2048 static NTSTATUS fcb_or_dos_open(struct smb_request *req,
2049                                 connection_struct *conn,
2050                                 files_struct *fsp_to_dup_into,
2051                                 const struct smb_filename *smb_fname,
2052                                 struct file_id id,
2053                                 uint16_t file_pid,
2054                                 uint64_t vuid,
2055                                 uint32_t access_mask,
2056                                 uint32_t share_access,
2057                                 uint32_t create_options)
2058 {
2059         files_struct *fsp;
2060
2061         DEBUG(5,("fcb_or_dos_open: attempting old open semantics for "
2062                  "file %s.\n", smb_fname_str_dbg(smb_fname)));
2063
2064         for(fsp = file_find_di_first(conn->sconn, id); fsp;
2065             fsp = file_find_di_next(fsp)) {
2066
2067                 DEBUG(10,("fcb_or_dos_open: checking file %s, fd = %d, "
2068                           "vuid = %llu, file_pid = %u, private_options = 0x%x "
2069                           "access_mask = 0x%x\n", fsp_str_dbg(fsp),
2070                           fsp->fh->fd, (unsigned long long)fsp->vuid,
2071                           (unsigned int)fsp->file_pid,
2072                           (unsigned int)fsp->fh->private_options,
2073                           (unsigned int)fsp->access_mask ));
2074
2075                 if (fsp != fsp_to_dup_into &&
2076                     fsp->fh->fd != -1 &&
2077                     fsp->vuid == vuid &&
2078                     fsp->file_pid == file_pid &&
2079                     (fsp->fh->private_options & (NTCREATEX_OPTIONS_PRIVATE_DENY_DOS |
2080                                                  NTCREATEX_OPTIONS_PRIVATE_DENY_FCB)) &&
2081                     (fsp->access_mask & FILE_WRITE_DATA) &&
2082                     strequal(fsp->fsp_name->base_name, smb_fname->base_name) &&
2083                     strequal(fsp->fsp_name->stream_name,
2084                              smb_fname->stream_name)) {
2085                         DEBUG(10,("fcb_or_dos_open: file match\n"));
2086                         break;
2087                 }
2088         }
2089
2090         if (!fsp) {
2091                 return NT_STATUS_NOT_FOUND;
2092         }
2093
2094         /* quite an insane set of semantics ... */
2095         if (is_executable(smb_fname->base_name) &&
2096             (fsp->fh->private_options & NTCREATEX_OPTIONS_PRIVATE_DENY_DOS)) {
2097                 DEBUG(10,("fcb_or_dos_open: file fail due to is_executable.\n"));
2098                 return NT_STATUS_INVALID_PARAMETER;
2099         }
2100
2101         /* We need to duplicate this fsp. */
2102         return dup_file_fsp(req, fsp, access_mask, share_access,
2103                             create_options, fsp_to_dup_into);
2104 }
2105
2106 static void schedule_defer_open(struct share_mode_lock *lck,
2107                                 struct file_id id,
2108                                 struct timeval request_time,
2109                                 struct smb_request *req)
2110 {
2111         struct deferred_open_record state;
2112
2113         /* This is a relative time, added to the absolute
2114            request_time value to get the absolute timeout time.
2115            Note that if this is the second or greater time we enter
2116            this codepath for this particular request mid then
2117            request_time is left as the absolute time of the *first*
2118            time this request mid was processed. This is what allows
2119            the request to eventually time out. */
2120
2121         struct timeval timeout;
2122
2123         /* Normally the smbd we asked should respond within
2124          * OPLOCK_BREAK_TIMEOUT seconds regardless of whether
2125          * the client did, give twice the timeout as a safety
2126          * measure here in case the other smbd is stuck
2127          * somewhere else. */
2128
2129         timeout = timeval_set(OPLOCK_BREAK_TIMEOUT*2, 0);
2130
2131         /* Nothing actually uses state.delayed_for_oplocks
2132            but it's handy to differentiate in debug messages
2133            between a 30 second delay due to oplock break, and
2134            a 1 second delay for share mode conflicts. */
2135
2136         state.delayed_for_oplocks = True;
2137         state.async_open = false;
2138         state.id = id;
2139
2140         if (!request_timed_out(request_time, timeout)) {
2141                 defer_open(lck, request_time, timeout, req, &state);
2142         }
2143 }
2144
2145 /****************************************************************************
2146  Reschedule an open call that went asynchronous.
2147 ****************************************************************************/
2148
2149 static void schedule_async_open(struct timeval request_time,
2150                                 struct smb_request *req)
2151 {
2152         struct deferred_open_record state;
2153         struct timeval timeout;
2154
2155         timeout = timeval_set(20, 0);
2156
2157         ZERO_STRUCT(state);
2158         state.delayed_for_oplocks = false;
2159         state.async_open = true;
2160
2161         if (!request_timed_out(request_time, timeout)) {
2162                 defer_open(NULL, request_time, timeout, req, &state);
2163         }
2164 }
2165
2166 /****************************************************************************
2167  Work out what access_mask to use from what the client sent us.
2168 ****************************************************************************/
2169
2170 static NTSTATUS smbd_calculate_maximum_allowed_access(
2171         connection_struct *conn,
2172         const struct smb_filename *smb_fname,
2173         bool use_privs,
2174         uint32_t *p_access_mask)
2175 {
2176         struct security_descriptor *sd;
2177         uint32_t access_granted;
2178         NTSTATUS status;
2179
2180         if (!use_privs && (get_current_uid(conn) == (uid_t)0)) {
2181                 *p_access_mask |= FILE_GENERIC_ALL;
2182                 return NT_STATUS_OK;
2183         }
2184
2185         status = SMB_VFS_GET_NT_ACL(conn, smb_fname,
2186                                     (SECINFO_OWNER |
2187                                      SECINFO_GROUP |
2188                                      SECINFO_DACL),
2189                                     talloc_tos(), &sd);
2190
2191         if (NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
2192                 /*
2193                  * File did not exist
2194                  */
2195                 *p_access_mask = FILE_GENERIC_ALL;
2196                 return NT_STATUS_OK;
2197         }
2198         if (!NT_STATUS_IS_OK(status)) {
2199                 DEBUG(10,("Could not get acl on file %s: %s\n",
2200                           smb_fname_str_dbg(smb_fname),
2201                           nt_errstr(status)));
2202                 return NT_STATUS_ACCESS_DENIED;
2203         }
2204
2205         /*
2206          * If we can access the path to this file, by
2207          * default we have FILE_READ_ATTRIBUTES from the
2208          * containing directory. See the section:
2209          * "Algorithm to Check Access to an Existing File"
2210          * in MS-FSA.pdf.
2211          *
2212          * se_file_access_check()
2213          * also takes care of owner WRITE_DAC and READ_CONTROL.
2214          */
2215         status = se_file_access_check(sd,
2216                                  get_current_nttok(conn),
2217                                  use_privs,
2218                                  (*p_access_mask & ~FILE_READ_ATTRIBUTES),
2219                                  &access_granted);
2220
2221         TALLOC_FREE(sd);
2222
2223         if (!NT_STATUS_IS_OK(status)) {
2224                 DEBUG(10, ("Access denied on file %s: "
2225                            "when calculating maximum access\n",
2226                            smb_fname_str_dbg(smb_fname)));
2227                 return NT_STATUS_ACCESS_DENIED;
2228         }
2229         *p_access_mask = (access_granted | FILE_READ_ATTRIBUTES);
2230
2231         if (!(access_granted & DELETE_ACCESS)) {
2232                 if (can_delete_file_in_directory(conn, smb_fname)) {
2233                         *p_access_mask |= DELETE_ACCESS;
2234                 }
2235         }
2236
2237         return NT_STATUS_OK;
2238 }
2239
2240 NTSTATUS smbd_calculate_access_mask(connection_struct *conn,
2241                                     const struct smb_filename *smb_fname,
2242                                     bool use_privs,
2243                                     uint32_t access_mask,
2244                                     uint32_t *access_mask_out)
2245 {
2246         NTSTATUS status;
2247         uint32_t orig_access_mask = access_mask;
2248         uint32_t rejected_share_access;
2249
2250         /*
2251          * Convert GENERIC bits to specific bits.
2252          */
2253
2254         se_map_generic(&access_mask, &file_generic_mapping);
2255
2256         /* Calculate MAXIMUM_ALLOWED_ACCESS if requested. */
2257         if (access_mask & MAXIMUM_ALLOWED_ACCESS) {
2258
2259                 status = smbd_calculate_maximum_allowed_access(
2260                         conn, smb_fname, use_privs, &access_mask);
2261
2262                 if (!NT_STATUS_IS_OK(status)) {
2263                         return status;
2264                 }
2265
2266                 access_mask &= conn->share_access;
2267         }
2268
2269         rejected_share_access = access_mask & ~(conn->share_access);
2270
2271         if (rejected_share_access) {
2272                 DEBUG(10, ("smbd_calculate_access_mask: Access denied on "
2273                         "file %s: rejected by share access mask[0x%08X] "
2274                         "orig[0x%08X] mapped[0x%08X] reject[0x%08X]\n",
2275                         smb_fname_str_dbg(smb_fname),
2276                         conn->share_access,
2277                         orig_access_mask, access_mask,
2278                         rejected_share_access));
2279                 return NT_STATUS_ACCESS_DENIED;
2280         }
2281
2282         *access_mask_out = access_mask;
2283         return NT_STATUS_OK;
2284 }
2285
2286 /****************************************************************************
2287  Remove the deferred open entry under lock.
2288 ****************************************************************************/
2289
2290 /****************************************************************************
2291  Return true if this is a state pointer to an asynchronous create.
2292 ****************************************************************************/
2293
2294 bool is_deferred_open_async(const struct deferred_open_record *rec)
2295 {
2296         return rec->async_open;
2297 }
2298
2299 static bool clear_ads(uint32_t create_disposition)
2300 {
2301         bool ret = false;
2302
2303         switch (create_disposition) {
2304         case FILE_SUPERSEDE:
2305         case FILE_OVERWRITE_IF:
2306         case FILE_OVERWRITE:
2307                 ret = true;
2308                 break;
2309         default:
2310                 break;
2311         }
2312         return ret;
2313 }
2314
2315 static int disposition_to_open_flags(uint32_t create_disposition)
2316 {
2317         int ret = 0;
2318
2319         /*
2320          * Currently we're using FILE_SUPERSEDE as the same as
2321          * FILE_OVERWRITE_IF but they really are
2322          * different. FILE_SUPERSEDE deletes an existing file
2323          * (requiring delete access) then recreates it.
2324          */
2325
2326         switch (create_disposition) {
2327         case FILE_SUPERSEDE:
2328         case FILE_OVERWRITE_IF:
2329                 /*
2330                  * If file exists replace/overwrite. If file doesn't
2331                  * exist create.
2332                  */
2333                 ret = O_CREAT|O_TRUNC;
2334                 break;
2335
2336         case FILE_OPEN:
2337                 /*
2338                  * If file exists open. If file doesn't exist error.
2339                  */
2340                 ret = 0;
2341                 break;
2342
2343         case FILE_OVERWRITE:
2344                 /*
2345                  * If file exists overwrite. If file doesn't exist
2346                  * error.
2347                  */
2348                 ret = O_TRUNC;
2349                 break;
2350
2351         case FILE_CREATE:
2352                 /*
2353                  * If file exists error. If file doesn't exist create.
2354                  */
2355                 ret = O_CREAT|O_EXCL;
2356                 break;
2357
2358         case FILE_OPEN_IF:
2359                 /*
2360                  * If file exists open. If file doesn't exist create.
2361                  */
2362                 ret = O_CREAT;
2363                 break;
2364         }
2365         return ret;
2366 }
2367
2368 static int calculate_open_access_flags(uint32_t access_mask,
2369                                        uint32_t private_flags)
2370 {
2371         bool need_write, need_read;
2372
2373         /*
2374          * Note that we ignore the append flag as append does not
2375          * mean the same thing under DOS and Unix.
2376          */
2377
2378         need_write = (access_mask & (FILE_WRITE_DATA | FILE_APPEND_DATA));
2379         if (!need_write) {
2380                 return O_RDONLY;
2381         }
2382
2383         /* DENY_DOS opens are always underlying read-write on the
2384            file handle, no matter what the requested access mask
2385            says. */
2386
2387         need_read =
2388                 ((private_flags & NTCREATEX_OPTIONS_PRIVATE_DENY_DOS) ||
2389                  access_mask & (FILE_READ_ATTRIBUTES|FILE_READ_DATA|
2390                                 FILE_READ_EA|FILE_EXECUTE));
2391
2392         if (!need_read) {
2393                 return O_WRONLY;
2394         }
2395         return O_RDWR;
2396 }
2397
2398 /****************************************************************************
2399  Open a file with a share mode. Passed in an already created files_struct *.
2400 ****************************************************************************/
2401
2402 static NTSTATUS open_file_ntcreate(connection_struct *conn,
2403                             struct smb_request *req,
2404                             uint32_t access_mask,               /* access bits (FILE_READ_DATA etc.) */
2405                             uint32_t share_access,      /* share constants (FILE_SHARE_READ etc) */
2406                             uint32_t create_disposition,        /* FILE_OPEN_IF etc. */
2407                             uint32_t create_options,    /* options such as delete on close. */
2408                             uint32_t new_dos_attributes,        /* attributes used for new file. */
2409                             int oplock_request,         /* internal Samba oplock codes. */
2410                             struct smb2_lease *lease,
2411                                                         /* Information (FILE_EXISTS etc.) */
2412                             uint32_t private_flags,     /* Samba specific flags. */
2413                             int *pinfo,
2414                             files_struct *fsp)
2415 {
2416         struct smb_filename *smb_fname = fsp->fsp_name;
2417         int flags=0;
2418         int flags2=0;
2419         bool file_existed = VALID_STAT(smb_fname->st);
2420         bool def_acl = False;
2421         bool posix_open = False;
2422         bool new_file_created = False;
2423         bool first_open_attempt = true;
2424         NTSTATUS fsp_open = NT_STATUS_ACCESS_DENIED;
2425         mode_t new_unx_mode = (mode_t)0;
2426         mode_t unx_mode = (mode_t)0;
2427         int info;
2428         uint32_t existing_dos_attributes = 0;
2429         struct timeval request_time = timeval_zero();
2430         struct share_mode_lock *lck = NULL;
2431         uint32_t open_access_mask = access_mask;
2432         NTSTATUS status;
2433         char *parent_dir;
2434         SMB_STRUCT_STAT saved_stat = smb_fname->st;
2435         struct timespec old_write_time;
2436         struct file_id id;
2437
2438         if (conn->printer) {
2439                 /*
2440                  * Printers are handled completely differently.
2441                  * Most of the passed parameters are ignored.
2442                  */
2443
2444                 if (pinfo) {
2445                         *pinfo = FILE_WAS_CREATED;
2446                 }
2447
2448                 DEBUG(10, ("open_file_ntcreate: printer open fname=%s\n",
2449                            smb_fname_str_dbg(smb_fname)));
2450
2451                 if (!req) {
2452                         DEBUG(0,("open_file_ntcreate: printer open without "
2453                                 "an SMB request!\n"));
2454                         return NT_STATUS_INTERNAL_ERROR;
2455                 }
2456
2457                 return print_spool_open(fsp, smb_fname->base_name,
2458                                         req->vuid);
2459         }
2460
2461         if (!parent_dirname(talloc_tos(), smb_fname->base_name, &parent_dir,
2462                             NULL)) {
2463                 return NT_STATUS_NO_MEMORY;
2464         }
2465
2466         if (new_dos_attributes & FILE_FLAG_POSIX_SEMANTICS) {
2467                 posix_open = True;
2468                 unx_mode = (mode_t)(new_dos_attributes & ~FILE_FLAG_POSIX_SEMANTICS);
2469                 new_dos_attributes = 0;
2470         } else {
2471                 /* Windows allows a new file to be created and
2472                    silently removes a FILE_ATTRIBUTE_DIRECTORY
2473                    sent by the client. Do the same. */
2474
2475                 new_dos_attributes &= ~FILE_ATTRIBUTE_DIRECTORY;
2476
2477                 /* We add FILE_ATTRIBUTE_ARCHIVE to this as this mode is only used if the file is
2478                  * created new. */
2479                 unx_mode = unix_mode(conn, new_dos_attributes | FILE_ATTRIBUTE_ARCHIVE,
2480                                      smb_fname, parent_dir);
2481         }
2482
2483         DEBUG(10, ("open_file_ntcreate: fname=%s, dos_attrs=0x%x "
2484                    "access_mask=0x%x share_access=0x%x "
2485                    "create_disposition = 0x%x create_options=0x%x "
2486                    "unix mode=0%o oplock_request=%d private_flags = 0x%x\n",
2487                    smb_fname_str_dbg(smb_fname), new_dos_attributes,
2488                    access_mask, share_access, create_disposition,
2489                    create_options, (unsigned int)unx_mode, oplock_request,
2490                    (unsigned int)private_flags));
2491
2492         if (req == NULL) {
2493                 /* Ensure req == NULL means INTERNAL_OPEN_ONLY */
2494                 SMB_ASSERT(((oplock_request & INTERNAL_OPEN_ONLY) != 0));
2495         } else {
2496                 /* And req != NULL means no INTERNAL_OPEN_ONLY */
2497                 SMB_ASSERT(((oplock_request & INTERNAL_OPEN_ONLY) == 0));
2498         }
2499
2500         /*
2501          * Only non-internal opens can be deferred at all
2502          */
2503
2504         if (req) {
2505                 struct deferred_open_record *open_rec;
2506                 if (get_deferred_open_message_state(req,
2507                                 &request_time,
2508                                 &open_rec)) {
2509                         /* Remember the absolute time of the original
2510                            request with this mid. We'll use it later to
2511                            see if this has timed out. */
2512
2513                         /* If it was an async create retry, the file
2514                            didn't exist. */
2515
2516                         if (is_deferred_open_async(open_rec)) {
2517                                 SET_STAT_INVALID(smb_fname->st);
2518                                 file_existed = false;
2519                         }
2520
2521                         /* Ensure we don't reprocess this message. */
2522                         remove_deferred_open_message_smb(req->xconn, req->mid);
2523
2524                         first_open_attempt = false;
2525                 }
2526         }
2527
2528         if (!posix_open) {
2529                 new_dos_attributes &= SAMBA_ATTRIBUTES_MASK;
2530                 if (file_existed) {
2531                         existing_dos_attributes = dos_mode(conn, smb_fname);
2532                 }
2533         }
2534
2535         /* ignore any oplock requests if oplocks are disabled */
2536         if (!lp_oplocks(SNUM(conn)) ||
2537             IS_VETO_OPLOCK_PATH(conn, smb_fname->base_name)) {
2538                 /* Mask off everything except the private Samba bits. */
2539                 oplock_request &= SAMBA_PRIVATE_OPLOCK_MASK;
2540         }
2541
2542         /* this is for OS/2 long file names - say we don't support them */
2543         if (req != NULL && !req->posix_pathnames &&
2544                         strstr(smb_fname->base_name,".+,;=[].")) {
2545                 /* OS/2 Workplace shell fix may be main code stream in a later
2546                  * release. */
2547                 DEBUG(5,("open_file_ntcreate: OS/2 long filenames are not "
2548                          "supported.\n"));
2549                 if (use_nt_status()) {
2550                         return NT_STATUS_OBJECT_NAME_NOT_FOUND;
2551                 }
2552                 return NT_STATUS_DOS(ERRDOS, ERRcannotopen);
2553         }
2554
2555         switch( create_disposition ) {
2556                 case FILE_OPEN:
2557                         /* If file exists open. If file doesn't exist error. */
2558                         if (!file_existed) {
2559                                 DEBUG(5,("open_file_ntcreate: FILE_OPEN "
2560                                          "requested for file %s and file "
2561                                          "doesn't exist.\n",
2562                                          smb_fname_str_dbg(smb_fname)));
2563                                 errno = ENOENT;
2564                                 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
2565                         }
2566                         break;
2567
2568                 case FILE_OVERWRITE:
2569                         /* If file exists overwrite. If file doesn't exist
2570                          * error. */
2571                         if (!file_existed) {
2572                                 DEBUG(5,("open_file_ntcreate: FILE_OVERWRITE "
2573                                          "requested for file %s and file "
2574                                          "doesn't exist.\n",
2575                                          smb_fname_str_dbg(smb_fname) ));
2576                                 errno = ENOENT;
2577                                 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
2578                         }
2579                         break;
2580
2581                 case FILE_CREATE:
2582                         /* If file exists error. If file doesn't exist
2583                          * create. */
2584                         if (file_existed) {
2585                                 DEBUG(5,("open_file_ntcreate: FILE_CREATE "
2586                                          "requested for file %s and file "
2587                                          "already exists.\n",
2588                                          smb_fname_str_dbg(smb_fname)));
2589                                 if (S_ISDIR(smb_fname->st.st_ex_mode)) {
2590                                         errno = EISDIR;
2591                                 } else {
2592                                         errno = EEXIST;
2593                                 }
2594                                 return map_nt_error_from_unix(errno);
2595                         }
2596                         break;
2597
2598                 case FILE_SUPERSEDE:
2599                 case FILE_OVERWRITE_IF:
2600                 case FILE_OPEN_IF:
2601                         break;
2602                 default:
2603                         return NT_STATUS_INVALID_PARAMETER;
2604         }
2605
2606         flags2 = disposition_to_open_flags(create_disposition);
2607
2608         /* We only care about matching attributes on file exists and
2609          * overwrite. */
2610
2611         if (!posix_open && file_existed &&
2612             ((create_disposition == FILE_OVERWRITE) ||
2613              (create_disposition == FILE_OVERWRITE_IF))) {
2614                 if (!open_match_attributes(conn, existing_dos_attributes,
2615                                            new_dos_attributes,
2616                                            smb_fname->st.st_ex_mode,
2617                                            unx_mode, &new_unx_mode)) {
2618                         DEBUG(5,("open_file_ntcreate: attributes missmatch "
2619                                  "for file %s (%x %x) (0%o, 0%o)\n",
2620                                  smb_fname_str_dbg(smb_fname),
2621                                  existing_dos_attributes,
2622                                  new_dos_attributes,
2623                                  (unsigned int)smb_fname->st.st_ex_mode,
2624                                  (unsigned int)unx_mode ));
2625                         errno = EACCES;
2626                         return NT_STATUS_ACCESS_DENIED;
2627                 }
2628         }
2629
2630         status = smbd_calculate_access_mask(conn, smb_fname,
2631                                         false,
2632                                         access_mask,
2633                                         &access_mask); 
2634         if (!NT_STATUS_IS_OK(status)) {
2635                 DEBUG(10, ("open_file_ntcreate: smbd_calculate_access_mask "
2636                         "on file %s returned %s\n",
2637                         smb_fname_str_dbg(smb_fname), nt_errstr(status)));
2638                 return status;
2639         }
2640
2641         open_access_mask = access_mask;
2642
2643         if (flags2 & O_TRUNC) {
2644                 open_access_mask |= FILE_WRITE_DATA; /* This will cause oplock breaks. */
2645         }
2646
2647         DEBUG(10, ("open_file_ntcreate: fname=%s, after mapping "
2648                    "access_mask=0x%x\n", smb_fname_str_dbg(smb_fname),
2649                     access_mask));
2650
2651         /*
2652          * Note that we ignore the append flag as append does not
2653          * mean the same thing under DOS and Unix.
2654          */
2655
2656         flags = calculate_open_access_flags(access_mask, private_flags);
2657
2658         /*
2659          * Currently we only look at FILE_WRITE_THROUGH for create options.
2660          */
2661
2662 #if defined(O_SYNC)
2663         if ((create_options & FILE_WRITE_THROUGH) && lp_strict_sync(SNUM(conn))) {
2664                 flags2 |= O_SYNC;
2665         }
2666 #endif /* O_SYNC */
2667
2668         if (posix_open && (access_mask & FILE_APPEND_DATA)) {
2669                 flags2 |= O_APPEND;
2670         }
2671
2672         if (!posix_open && !CAN_WRITE(conn)) {
2673                 /*
2674                  * We should really return a permission denied error if either
2675                  * O_CREAT or O_TRUNC are set, but for compatibility with
2676                  * older versions of Samba we just AND them out.
2677                  */
2678                 flags2 &= ~(O_CREAT|O_TRUNC);
2679         }
2680
2681         if (first_open_attempt && lp_kernel_oplocks(SNUM(conn))) {
2682                 /*
2683                  * With kernel oplocks the open breaking an oplock
2684                  * blocks until the oplock holder has given up the
2685                  * oplock or closed the file. We prevent this by first
2686                  * trying to open the file with O_NONBLOCK (see "man
2687                  * fcntl" on Linux). For the second try, triggered by
2688                  * an oplock break response, we do not need this
2689                  * anymore.
2690                  *
2691                  * This is true under the assumption that only Samba
2692                  * requests kernel oplocks. Once someone else like
2693                  * NFSv4 starts to use that API, we will have to
2694                  * modify this by communicating with the NFSv4 server.
2695                  */
2696                 flags2 |= O_NONBLOCK;
2697         }
2698
2699         /*
2700          * Ensure we can't write on a read-only share or file.
2701          */
2702
2703         if (flags != O_RDONLY && file_existed &&
2704             (!CAN_WRITE(conn) || IS_DOS_READONLY(existing_dos_attributes))) {
2705                 DEBUG(5,("open_file_ntcreate: write access requested for "
2706                          "file %s on read only %s\n",
2707                          smb_fname_str_dbg(smb_fname),
2708                          !CAN_WRITE(conn) ? "share" : "file" ));
2709                 errno = EACCES;
2710                 return NT_STATUS_ACCESS_DENIED;
2711         }
2712
2713         fsp->file_id = vfs_file_id_from_sbuf(conn, &smb_fname->st);
2714         fsp->share_access = share_access;
2715         fsp->fh->private_options = private_flags;
2716         fsp->access_mask = open_access_mask; /* We change this to the
2717                                               * requested access_mask after
2718                                               * the open is done. */
2719         if (posix_open) {
2720                 fsp->posix_flags |= FSP_POSIX_FLAGS_ALL;
2721         }
2722
2723         if (timeval_is_zero(&request_time)) {
2724                 request_time = fsp->open_time;
2725         }
2726
2727         /*
2728          * Ensure we pay attention to default ACLs on directories if required.
2729          */
2730
2731         if ((flags2 & O_CREAT) && lp_inherit_acls(SNUM(conn)) &&
2732             (def_acl = directory_has_default_acl(conn, parent_dir))) {
2733                 unx_mode = (0777 & lp_create_mask(SNUM(conn)));
2734         }
2735
2736         DEBUG(4,("calling open_file with flags=0x%X flags2=0x%X mode=0%o, "
2737                 "access_mask = 0x%x, open_access_mask = 0x%x\n",
2738                  (unsigned int)flags, (unsigned int)flags2,
2739                  (unsigned int)unx_mode, (unsigned int)access_mask,
2740                  (unsigned int)open_access_mask));
2741
2742         fsp_open = open_file(fsp, conn, req, parent_dir,
2743                              flags|flags2, unx_mode, access_mask,
2744                              open_access_mask, &new_file_created);
2745
2746         if (NT_STATUS_EQUAL(fsp_open, NT_STATUS_NETWORK_BUSY)) {
2747                 struct deferred_open_record state;
2748
2749                 /*
2750                  * EWOULDBLOCK/EAGAIN maps to NETWORK_BUSY.
2751                  */
2752                 if (file_existed && S_ISFIFO(fsp->fsp_name->st.st_ex_mode)) {
2753                         DEBUG(10, ("FIFO busy\n"));
2754                         return NT_STATUS_NETWORK_BUSY;
2755                 }
2756                 if (req == NULL) {
2757                         DEBUG(10, ("Internal open busy\n"));
2758                         return NT_STATUS_NETWORK_BUSY;
2759                 }
2760
2761                 /*
2762                  * From here on we assume this is an oplock break triggered
2763                  */
2764
2765                 lck = get_existing_share_mode_lock(talloc_tos(), fsp->file_id);
2766                 if (lck == NULL) {
2767                         state.delayed_for_oplocks = false;
2768                         state.async_open = false;
2769                         state.id = fsp->file_id;
2770                         defer_open(NULL, request_time, timeval_set(0, 0),
2771                                    req, &state);
2772                         DEBUG(10, ("No share mode lock found after "
2773                                    "EWOULDBLOCK, retrying sync\n"));
2774                         return NT_STATUS_SHARING_VIOLATION;
2775                 }
2776
2777                 if (!validate_oplock_types(lck)) {
2778                         smb_panic("validate_oplock_types failed");
2779                 }
2780
2781                 if (delay_for_oplock(fsp, 0, lease, lck, false,
2782                                      create_disposition, first_open_attempt)) {
2783                         schedule_defer_open(lck, fsp->file_id, request_time,
2784                                             req);
2785                         TALLOC_FREE(lck);
2786                         DEBUG(10, ("Sent oplock break request to kernel "
2787                                    "oplock holder\n"));
2788                         return NT_STATUS_SHARING_VIOLATION;
2789                 }
2790
2791                 /*
2792                  * No oplock from Samba around. Immediately retry with
2793                  * a blocking open.
2794                  */
2795                 state.delayed_for_oplocks = false;
2796                 state.async_open = false;
2797                 state.id = fsp->file_id;
2798                 defer_open(lck, request_time, timeval_set(0, 0), req, &state);
2799                 TALLOC_FREE(lck);
2800                 DEBUG(10, ("No Samba oplock around after EWOULDBLOCK. "
2801                            "Retrying sync\n"));
2802                 return NT_STATUS_SHARING_VIOLATION;
2803         }
2804
2805         if (!NT_STATUS_IS_OK(fsp_open)) {
2806                 if (NT_STATUS_EQUAL(fsp_open, NT_STATUS_RETRY)) {
2807                         schedule_async_open(request_time, req);
2808                 }
2809                 return fsp_open;
2810         }
2811
2812         if (new_file_created) {
2813                 /*
2814                  * As we atomically create using O_CREAT|O_EXCL,
2815                  * then if new_file_created is true, then
2816                  * file_existed *MUST* have been false (even
2817                  * if the file was previously detected as being
2818                  * there).
2819                  */
2820                 file_existed = false;
2821         }
2822
2823         if (file_existed && !check_same_dev_ino(&saved_stat, &smb_fname->st)) {
2824                 /*
2825                  * The file did exist, but some other (local or NFS)
2826                  * process either renamed/unlinked and re-created the
2827                  * file with different dev/ino after we walked the path,
2828                  * but before we did the open. We could retry the
2829                  * open but it's a rare enough case it's easier to
2830                  * just fail the open to prevent creating any problems
2831                  * in the open file db having the wrong dev/ino key.
2832                  */
2833                 fd_close(fsp);
2834                 DEBUG(1,("open_file_ntcreate: file %s - dev/ino mismatch. "
2835                         "Old (dev=0x%llu, ino =0x%llu). "
2836                         "New (dev=0x%llu, ino=0x%llu). Failing open "
2837                         " with NT_STATUS_ACCESS_DENIED.\n",
2838                          smb_fname_str_dbg(smb_fname),
2839                          (unsigned long long)saved_stat.st_ex_dev,
2840                          (unsigned long long)saved_stat.st_ex_ino,
2841                          (unsigned long long)smb_fname->st.st_ex_dev,
2842                          (unsigned long long)smb_fname->st.st_ex_ino));
2843                 return NT_STATUS_ACCESS_DENIED;
2844         }
2845
2846         old_write_time = smb_fname->st.st_ex_mtime;
2847
2848         /*
2849          * Deal with the race condition where two smbd's detect the
2850          * file doesn't exist and do the create at the same time. One
2851          * of them will win and set a share mode, the other (ie. this
2852          * one) should check if the requested share mode for this
2853          * create is allowed.
2854          */
2855
2856         /*
2857          * Now the file exists and fsp is successfully opened,
2858          * fsp->dev and fsp->inode are valid and should replace the
2859          * dev=0,inode=0 from a non existent file. Spotted by
2860          * Nadav Danieli <nadavd@exanet.com>. JRA.
2861          */
2862
2863         id = fsp->file_id;
2864
2865         lck = get_share_mode_lock(talloc_tos(), id,
2866                                   conn->connectpath,
2867                                   smb_fname, &old_write_time);
2868
2869         if (lck == NULL) {
2870                 DEBUG(0, ("open_file_ntcreate: Could not get share "
2871                           "mode lock for %s\n",
2872                           smb_fname_str_dbg(smb_fname)));
2873                 fd_close(fsp);
2874                 return NT_STATUS_SHARING_VIOLATION;
2875         }
2876
2877         /* Get the types we need to examine. */
2878         if (!validate_oplock_types(lck)) {
2879                 smb_panic("validate_oplock_types failed");
2880         }
2881
2882         if (has_delete_on_close(lck, fsp->name_hash)) {
2883                 TALLOC_FREE(lck);
2884                 fd_close(fsp);
2885                 return NT_STATUS_DELETE_PENDING;
2886         }
2887
2888         status = open_mode_check(conn, lck,
2889                                  access_mask, share_access);
2890
2891         if (NT_STATUS_EQUAL(status, NT_STATUS_SHARING_VIOLATION) ||
2892             (lck->data->num_share_modes > 0)) {
2893                 /*
2894                  * This comes from ancient times out of open_mode_check. I
2895                  * have no clue whether this is still necessary. I can't think
2896                  * of a case where this would actually matter further down in
2897                  * this function. I leave it here for further investigation
2898                  * :-)
2899                  */
2900                 file_existed = true;
2901         }
2902
2903         if ((req != NULL) &&
2904             delay_for_oplock(
2905                     fsp, oplock_request, lease, lck,
2906                     NT_STATUS_EQUAL(status, NT_STATUS_SHARING_VIOLATION),
2907                     create_disposition, first_open_attempt)) {
2908                 schedule_defer_open(lck, fsp->file_id, request_time, req);
2909                 TALLOC_FREE(lck);
2910                 fd_close(fsp);
2911                 return NT_STATUS_SHARING_VIOLATION;
2912         }
2913
2914         if (!NT_STATUS_IS_OK(status)) {
2915                 uint32_t can_access_mask;
2916                 bool can_access = True;
2917
2918                 SMB_ASSERT(NT_STATUS_EQUAL(status, NT_STATUS_SHARING_VIOLATION));
2919
2920                 /* Check if this can be done with the deny_dos and fcb
2921                  * calls. */
2922                 if (private_flags &
2923                     (NTCREATEX_OPTIONS_PRIVATE_DENY_DOS|
2924                      NTCREATEX_OPTIONS_PRIVATE_DENY_FCB)) {
2925                         if (req == NULL) {
2926                                 DEBUG(0, ("DOS open without an SMB "
2927                                           "request!\n"));
2928                                 TALLOC_FREE(lck);
2929                                 fd_close(fsp);
2930                                 return NT_STATUS_INTERNAL_ERROR;
2931                         }
2932
2933                         /* Use the client requested access mask here,
2934                          * not the one we open with. */
2935                         status = fcb_or_dos_open(req,
2936                                                  conn,
2937                                                  fsp,
2938                                                  smb_fname,
2939                                                  id,
2940                                                  req->smbpid,
2941                                                  req->vuid,
2942                                                  access_mask,
2943                                                  share_access,
2944                                                  create_options);
2945
2946                         if (NT_STATUS_IS_OK(status)) {
2947                                 TALLOC_FREE(lck);
2948                                 if (pinfo) {
2949                                         *pinfo = FILE_WAS_OPENED;
2950                                 }
2951                                 return NT_STATUS_OK;
2952                         }
2953                 }
2954
2955                 /*
2956                  * This next line is a subtlety we need for
2957                  * MS-Access. If a file open will fail due to share
2958                  * permissions and also for security (access) reasons,
2959                  * we need to return the access failed error, not the
2960                  * share error. We can't open the file due to kernel
2961                  * oplock deadlock (it's possible we failed above on
2962                  * the open_mode_check()) so use a userspace check.
2963                  */
2964
2965                 if (flags & O_RDWR) {
2966                         can_access_mask = FILE_READ_DATA|FILE_WRITE_DATA;
2967                 } else if (flags & O_WRONLY) {
2968                         can_access_mask = FILE_WRITE_DATA;
2969                 } else {
2970                         can_access_mask = FILE_READ_DATA;
2971                 }
2972
2973                 if (((can_access_mask & FILE_WRITE_DATA) &&
2974                      !CAN_WRITE(conn)) ||
2975                     !NT_STATUS_IS_OK(smbd_check_access_rights(conn,
2976                                                               smb_fname,
2977                                                               false,
2978                                                               can_access_mask))) {
2979                         can_access = False;
2980                 }
2981
2982                 /*
2983                  * If we're returning a share violation, ensure we
2984                  * cope with the braindead 1 second delay (SMB1 only).
2985                  */
2986
2987                 if (!(oplock_request & INTERNAL_OPEN_ONLY) &&
2988                     !conn->sconn->using_smb2 &&
2989                     lp_defer_sharing_violations()) {
2990                         struct timeval timeout;
2991                         struct deferred_open_record state;
2992                         int timeout_usecs;
2993
2994                         /* this is a hack to speed up torture tests
2995                            in 'make test' */
2996                         timeout_usecs = lp_parm_int(SNUM(conn),
2997                                                     "smbd","sharedelay",
2998                                                     SHARING_VIOLATION_USEC_WAIT);
2999
3000                         /* This is a relative time, added to the absolute
3001                            request_time value to get the absolute timeout time.
3002                            Note that if this is the second or greater time we enter
3003                            this codepath for this particular request mid then
3004                            request_time is left as the absolute time of the *first*
3005                            time this request mid was processed. This is what allows
3006                            the request to eventually time out. */
3007
3008                         timeout = timeval_set(0, timeout_usecs);
3009
3010                         /* Nothing actually uses state.delayed_for_oplocks
3011                            but it's handy to differentiate in debug messages
3012                            between a 30 second delay due to oplock break, and
3013                            a 1 second delay for share mode conflicts. */
3014
3015                         state.delayed_for_oplocks = False;
3016                         state.async_open = false;
3017                         state.id = id;
3018
3019                         if ((req != NULL)
3020                             && !request_timed_out(request_time,
3021                                                   timeout)) {
3022                                 defer_open(lck, request_time, timeout,
3023                                            req, &state);
3024                         }
3025                 }
3026
3027                 TALLOC_FREE(lck);
3028                 fd_close(fsp);
3029                 if (can_access) {
3030                         /*
3031                          * We have detected a sharing violation here
3032                          * so return the correct error code
3033                          */
3034                         status = NT_STATUS_SHARING_VIOLATION;
3035                 } else {
3036                         status = NT_STATUS_ACCESS_DENIED;
3037                 }
3038                 return status;
3039         }
3040
3041         /* Should we atomically (to the client at least) truncate ? */
3042         if ((!new_file_created) &&
3043             (flags2 & O_TRUNC) &&
3044             (!S_ISFIFO(fsp->fsp_name->st.st_ex_mode))) {
3045                 int ret;
3046
3047                 ret = vfs_set_filelen(fsp, 0);
3048                 if (ret != 0) {
3049                         status = map_nt_error_from_unix(errno);
3050                         TALLOC_FREE(lck);
3051                         fd_close(fsp);
3052                         return status;
3053                 }
3054         }
3055
3056         /*
3057          * We have the share entry *locked*.....
3058          */
3059
3060         /* Delete streams if create_disposition requires it */
3061         if (!new_file_created && clear_ads(create_disposition) &&
3062             !is_ntfs_stream_smb_fname(smb_fname)) {
3063                 status = delete_all_streams(conn, smb_fname);
3064                 if (!NT_STATUS_IS_OK(status)) {
3065                         TALLOC_FREE(lck);
3066                         fd_close(fsp);
3067                         return status;
3068                 }
3069         }
3070
3071         /* note that we ignore failure for the following. It is
3072            basically a hack for NFS, and NFS will never set one of
3073            these only read them. Nobody but Samba can ever set a deny
3074            mode and we have already checked our more authoritative
3075            locking database for permission to set this deny mode. If
3076            the kernel refuses the operations then the kernel is wrong.
3077            note that GPFS supports it as well - jmcd */
3078
3079         if (fsp->fh->fd != -1 && lp_kernel_share_modes(SNUM(conn))) {
3080                 int ret_flock;
3081                 /*
3082                  * Beware: streams implementing VFS modules may
3083                  * implement streams in a way that fsp will have the
3084                  * basefile open in the fsp fd, so lacking a distinct
3085                  * fd for the stream kernel_flock will apply on the
3086                  * basefile which is wrong. The actual check is
3087                  * deffered to the VFS module implementing the
3088                  * kernel_flock call.
3089                  */
3090                 ret_flock = SMB_VFS_KERNEL_FLOCK(fsp, share_access, access_mask);
3091                 if(ret_flock == -1 ){
3092
3093                         TALLOC_FREE(lck);
3094                         fd_close(fsp);
3095
3096                         return NT_STATUS_SHARING_VIOLATION;
3097                 }
3098         }
3099
3100         /*
3101          * At this point onwards, we can guarantee that the share entry
3102          * is locked, whether we created the file or not, and that the
3103          * deny mode is compatible with all current opens.
3104          */
3105
3106         /*
3107          * According to Samba4, SEC_FILE_READ_ATTRIBUTE is always granted,
3108          * but we don't have to store this - just ignore it on access check.
3109          */
3110         if (conn->sconn->using_smb2) {
3111                 /*
3112                  * SMB2 doesn't return it (according to Microsoft tests).
3113                  * Test Case: TestSuite_ScenarioNo009GrantedAccessTestS0
3114                  * File created with access = 0x7 (Read, Write, Delete)
3115                  * Query Info on file returns 0x87 (Read, Write, Delete, Read Attributes)
3116                  */
3117                 fsp->access_mask = access_mask;
3118         } else {
3119                 /* But SMB1 does. */
3120                 fsp->access_mask = access_mask | FILE_READ_ATTRIBUTES;
3121         }
3122
3123         if (file_existed) {
3124                 /*
3125                  * stat opens on existing files don't get oplocks.
3126                  * They can get leases.
3127                  *
3128                  * Note that we check for stat open on the *open_access_mask*,
3129                  * i.e. the access mask we actually used to do the open,
3130                  * not the one the client asked for (which is in
3131                  * fsp->access_mask). This is due to the fact that
3132                  * FILE_OVERWRITE and FILE_OVERWRITE_IF add in O_TRUNC,
3133                  * which adds FILE_WRITE_DATA to open_access_mask.
3134                  */
3135                 if (is_stat_open(open_access_mask) && lease == NULL) {
3136                         oplock_request = NO_OPLOCK;
3137                 }
3138         }
3139
3140         if (new_file_created) {
3141                 info = FILE_WAS_CREATED;
3142         } else {
3143                 if (flags2 & O_TRUNC) {
3144                         info = FILE_WAS_OVERWRITTEN;
3145                 } else {
3146                         info = FILE_WAS_OPENED;
3147                 }
3148         }
3149
3150         if (pinfo) {
3151                 *pinfo = info;
3152         }
3153
3154         /*
3155          * Setup the oplock info in both the shared memory and
3156          * file structs.
3157          */
3158         status = grant_fsp_oplock_type(req, fsp, lck, oplock_request, lease);
3159         if (!NT_STATUS_IS_OK(status)) {
3160                 TALLOC_FREE(lck);
3161                 fd_close(fsp);
3162                 return status;
3163         }
3164
3165         /* Handle strange delete on close create semantics. */
3166         if (create_options & FILE_DELETE_ON_CLOSE) {
3167
3168                 status = can_set_delete_on_close(fsp, new_dos_attributes);
3169
3170                 if (!NT_STATUS_IS_OK(status)) {
3171                         /* Remember to delete the mode we just added. */
3172                         del_share_mode(lck, fsp);
3173                         TALLOC_FREE(lck);
3174                         fd_close(fsp);
3175                         return status;
3176                 }
3177                 /* Note that here we set the *inital* delete on close flag,
3178                    not the regular one. The magic gets handled in close. */
3179                 fsp->initial_delete_on_close = True;
3180         }
3181
3182         if (info != FILE_WAS_OPENED) {
3183                 /* Overwritten files should be initially set as archive */
3184                 if ((info == FILE_WAS_OVERWRITTEN && lp_map_archive(SNUM(conn))) ||
3185                     lp_store_dos_attributes(SNUM(conn))) {
3186                         if (!posix_open) {
3187                                 if (file_set_dosmode(conn, smb_fname,
3188                                             new_dos_attributes | FILE_ATTRIBUTE_ARCHIVE,
3189                                             parent_dir, true) == 0) {
3190                                         unx_mode = smb_fname->st.st_ex_mode;
3191                                 }
3192                         }
3193                 }
3194         }
3195
3196         /* Determine sparse flag. */
3197         if (posix_open) {
3198                 /* POSIX opens are sparse by default. */
3199                 fsp->is_sparse = true;
3200         } else {
3201                 fsp->is_sparse = (file_existed &&
3202                         (existing_dos_attributes & FILE_ATTRIBUTE_SPARSE));
3203         }
3204
3205         /*
3206          * Take care of inherited ACLs on created files - if default ACL not
3207          * selected.
3208          */
3209
3210         if (!posix_open && new_file_created && !def_acl) {
3211
3212                 int saved_errno = errno; /* We might get ENOSYS in the next
3213                                           * call.. */
3214
3215                 if (SMB_VFS_FCHMOD_ACL(fsp, unx_mode) == -1 &&
3216                     errno == ENOSYS) {
3217                         errno = saved_errno; /* Ignore ENOSYS */
3218                 }
3219
3220         } else if (new_unx_mode) {
3221
3222                 int ret = -1;
3223
3224                 /* Attributes need changing. File already existed. */
3225
3226                 {
3227                         int saved_errno = errno; /* We might get ENOSYS in the
3228                                                   * next call.. */
3229                         ret = SMB_VFS_FCHMOD_ACL(fsp, new_unx_mode);
3230
3231                         if (ret == -1 && errno == ENOSYS) {
3232                                 errno = saved_errno; /* Ignore ENOSYS */
3233                         } else {
3234                                 DEBUG(5, ("open_file_ntcreate: reset "
3235                                           "attributes of file %s to 0%o\n",
3236                                           smb_fname_str_dbg(smb_fname),
3237                                           (unsigned int)new_unx_mode));
3238                                 ret = 0; /* Don't do the fchmod below. */
3239                         }
3240                 }
3241
3242                 if ((ret == -1) &&
3243                     (SMB_VFS_FCHMOD(fsp, new_unx_mode) == -1))
3244                         DEBUG(5, ("open_file_ntcreate: failed to reset "
3245                                   "attributes of file %s to 0%o\n",
3246                                   smb_fname_str_dbg(smb_fname),
3247                                   (unsigned int)new_unx_mode));
3248         }
3249
3250         {
3251                 /*
3252                  * Deal with other opens having a modified write time.
3253                  */
3254                 struct timespec write_time = get_share_mode_write_time(lck);
3255
3256                 if (!null_timespec(write_time)) {
3257                         update_stat_ex_mtime(&fsp->fsp_name->st, write_time);
3258                 }
3259         }
3260
3261         TALLOC_FREE(lck);
3262
3263         return NT_STATUS_OK;
3264 }
3265
3266 static NTSTATUS mkdir_internal(connection_struct *conn,
3267                                struct smb_filename *smb_dname,
3268                                uint32_t file_attributes)
3269 {
3270         mode_t mode;
3271         char *parent_dir = NULL;
3272         NTSTATUS status;
3273         bool posix_open = false;
3274         bool need_re_stat = false;
3275         uint32_t access_mask = SEC_DIR_ADD_SUBDIR;
3276
3277         if (!CAN_WRITE(conn) || (access_mask & ~(conn->share_access))) {
3278                 DEBUG(5,("mkdir_internal: failing share access "
3279                          "%s\n", lp_servicename(talloc_tos(), SNUM(conn))));
3280                 return NT_STATUS_ACCESS_DENIED;
3281         }
3282
3283         if (!parent_dirname(talloc_tos(), smb_dname->base_name, &parent_dir,
3284                             NULL)) {
3285                 return NT_STATUS_NO_MEMORY;
3286         }
3287
3288         if (file_attributes & FILE_FLAG_POSIX_SEMANTICS) {
3289                 posix_open = true;
3290                 mode = (mode_t)(file_attributes & ~FILE_FLAG_POSIX_SEMANTICS);
3291         } else {
3292                 mode = unix_mode(conn, FILE_ATTRIBUTE_DIRECTORY, smb_dname, parent_dir);
3293         }
3294
3295         status = check_parent_access(conn,
3296                                         smb_dname,
3297                                         access_mask);
3298         if(!NT_STATUS_IS_OK(status)) {
3299                 DEBUG(5,("mkdir_internal: check_parent_access "
3300                         "on directory %s for path %s returned %s\n",
3301                         parent_dir,
3302                         smb_dname->base_name,
3303                         nt_errstr(status) ));
3304                 return status;
3305         }
3306
3307         if (SMB_VFS_MKDIR(conn, smb_dname, mode) != 0) {
3308                 return map_nt_error_from_unix(errno);
3309         }
3310
3311         /* Ensure we're checking for a symlink here.... */
3312         /* We don't want to get caught by a symlink racer. */
3313
3314         if (SMB_VFS_LSTAT(conn, smb_dname) == -1) {
3315                 DEBUG(2, ("Could not stat directory '%s' just created: %s\n",
3316                           smb_fname_str_dbg(smb_dname), strerror(errno)));
3317                 return map_nt_error_from_unix(errno);
3318         }
3319
3320         if (!S_ISDIR(smb_dname->st.st_ex_mode)) {
3321                 DEBUG(0, ("Directory '%s' just created is not a directory !\n",
3322                           smb_fname_str_dbg(smb_dname)));
3323                 return NT_STATUS_NOT_A_DIRECTORY;
3324         }
3325
3326         if (lp_store_dos_attributes(SNUM(conn))) {
3327                 if (!posix_open) {
3328                         file_set_dosmode(conn, smb_dname,
3329                                          file_attributes | FILE_ATTRIBUTE_DIRECTORY,
3330                                          parent_dir, true);
3331                 }
3332         }
3333
3334         if (lp_inherit_permissions(SNUM(conn))) {
3335                 inherit_access_posix_acl(conn, parent_dir,
3336                                          smb_dname->base_name, mode);
3337                 need_re_stat = true;
3338         }
3339
3340         if (!posix_open) {
3341                 /*
3342                  * Check if high bits should have been set,
3343                  * then (if bits are missing): add them.
3344                  * Consider bits automagically set by UNIX, i.e. SGID bit from parent
3345                  * dir.
3346                  */
3347                 if ((mode & ~(S_IRWXU|S_IRWXG|S_IRWXO)) &&
3348                     (mode & ~smb_dname->st.st_ex_mode)) {
3349                         SMB_VFS_CHMOD(conn, smb_dname,
3350                                       (smb_dname->st.st_ex_mode |
3351                                           (mode & ~smb_dname->st.st_ex_mode)));
3352                         need_re_stat = true;
3353                 }
3354         }
3355
3356         /* Change the owner if required. */
3357         if (lp_inherit_owner(SNUM(conn))) {
3358                 change_dir_owner_to_parent(conn, parent_dir,
3359                                            smb_dname->base_name,
3360                                            &smb_dname->st);
3361                 need_re_stat = true;
3362         }
3363
3364         if (need_re_stat) {
3365                 if (SMB_VFS_LSTAT(conn, smb_dname) == -1) {
3366                         DEBUG(2, ("Could not stat directory '%s' just created: %s\n",
3367                           smb_fname_str_dbg(smb_dname), strerror(errno)));
3368                         return map_nt_error_from_unix(errno);
3369                 }
3370         }
3371
3372         notify_fname(conn, NOTIFY_ACTION_ADDED, FILE_NOTIFY_CHANGE_DIR_NAME,
3373                      smb_dname->base_name);
3374
3375         return NT_STATUS_OK;
3376 }
3377
3378 /****************************************************************************
3379  Open a directory from an NT SMB call.
3380 ****************************************************************************/
3381
3382 static NTSTATUS open_directory(connection_struct *conn,
3383                                struct smb_request *req,
3384                                struct smb_filename *smb_dname,
3385                                uint32_t access_mask,
3386                                uint32_t share_access,
3387                                uint32_t create_disposition,
3388                                uint32_t create_options,
3389                                uint32_t file_attributes,
3390                                int *pinfo,
3391                                files_struct **result)
3392 {
3393         files_struct *fsp = NULL;
3394         bool dir_existed = VALID_STAT(smb_dname->st) ? True : False;
3395         struct share_mode_lock *lck = NULL;
3396         NTSTATUS status;
3397         struct timespec mtimespec;
3398         int info = 0;
3399         bool ok;
3400
3401         if (is_ntfs_stream_smb_fname(smb_dname)) {
3402                 DEBUG(2, ("open_directory: %s is a stream name!\n",
3403                           smb_fname_str_dbg(smb_dname)));
3404                 return NT_STATUS_NOT_A_DIRECTORY;
3405         }
3406
3407         if (!(file_attributes & FILE_FLAG_POSIX_SEMANTICS)) {
3408                 /* Ensure we have a directory attribute. */
3409                 file_attributes |= FILE_ATTRIBUTE_DIRECTORY;
3410         }
3411
3412         DEBUG(5,("open_directory: opening directory %s, access_mask = 0x%x, "
3413                  "share_access = 0x%x create_options = 0x%x, "
3414                  "create_disposition = 0x%x, file_attributes = 0x%x\n",
3415                  smb_fname_str_dbg(smb_dname),
3416                  (unsigned int)access_mask,
3417                  (unsigned int)share_access,
3418                  (unsigned int)create_options,
3419                  (unsigned int)create_disposition,
3420                  (unsigned int)file_attributes));
3421
3422         status = smbd_calculate_access_mask(conn, smb_dname, false,
3423                                             access_mask, &access_mask);
3424         if (!NT_STATUS_IS_OK(status)) {
3425                 DEBUG(10, ("open_directory: smbd_calculate_access_mask "
3426                         "on file %s returned %s\n",
3427                         smb_fname_str_dbg(smb_dname),
3428                         nt_errstr(status)));
3429                 return status;
3430         }
3431
3432         if ((access_mask & SEC_FLAG_SYSTEM_SECURITY) &&
3433                         !security_token_has_privilege(get_current_nttok(conn),
3434                                         SEC_PRIV_SECURITY)) {
3435                 DEBUG(10, ("open_directory: open on %s "
3436                         "failed - SEC_FLAG_SYSTEM_SECURITY denied.\n",
3437                         smb_fname_str_dbg(smb_dname)));
3438                 return NT_STATUS_PRIVILEGE_NOT_HELD;
3439         }
3440
3441         switch( create_disposition ) {
3442                 case FILE_OPEN:
3443
3444                         if (!dir_existed) {
3445                                 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3446                         }
3447
3448                         info = FILE_WAS_OPENED;
3449                         break;
3450
3451                 case FILE_CREATE:
3452
3453                         /* If directory exists error. If directory doesn't
3454                          * exist create. */
3455
3456                         if (dir_existed) {
3457                                 status = NT_STATUS_OBJECT_NAME_COLLISION;
3458                                 DEBUG(2, ("open_directory: unable to create "
3459                                           "%s. Error was %s\n",
3460                                           smb_fname_str_dbg(smb_dname),
3461                                           nt_errstr(status)));
3462                                 return status;
3463                         }
3464
3465                         status = mkdir_internal(conn, smb_dname,
3466                                                 file_attributes);
3467
3468                         if (!NT_STATUS_IS_OK(status)) {
3469                                 DEBUG(2, ("open_directory: unable to create "
3470                                           "%s. Error was %s\n",
3471                                           smb_fname_str_dbg(smb_dname),
3472                                           nt_errstr(status)));
3473                                 return status;
3474                         }
3475
3476                         info = FILE_WAS_CREATED;
3477                         break;
3478
3479                 case FILE_OPEN_IF:
3480                         /*
3481                          * If directory exists open. If directory doesn't
3482                          * exist create.
3483                          */
3484
3485                         if (dir_existed) {
3486                                 status = NT_STATUS_OK;
3487                                 info = FILE_WAS_OPENED;
3488                         } else {
3489                                 status = mkdir_internal(conn, smb_dname,
3490                                                 file_attributes);
3491
3492                                 if (NT_STATUS_IS_OK(status)) {
3493                                         info = FILE_WAS_CREATED;
3494                                 } else {
3495                                         /* Cope with create race. */
3496                                         if (!NT_STATUS_EQUAL(status,
3497                                                         NT_STATUS_OBJECT_NAME_COLLISION)) {
3498                                                 DEBUG(2, ("open_directory: unable to create "
3499                                                         "%s. Error was %s\n",
3500                                                         smb_fname_str_dbg(smb_dname),
3501                                                         nt_errstr(status)));
3502                                                 return status;
3503                                         }
3504
3505                                         /*
3506                                          * If mkdir_internal() returned
3507                                          * NT_STATUS_OBJECT_NAME_COLLISION
3508                                          * we still must lstat the path.
3509                                          */
3510
3511                                         if (SMB_VFS_LSTAT(conn, smb_dname)
3512                                                         == -1) {
3513                                                 DEBUG(2, ("Could not stat "
3514                                                         "directory '%s' just "
3515                                                         "opened: %s\n",
3516                                                         smb_fname_str_dbg(
3517                                                                 smb_dname),
3518                                                         strerror(errno)));
3519                                                 return map_nt_error_from_unix(
3520                                                                 errno);
3521                                         }
3522
3523                                         info = FILE_WAS_OPENED;
3524                                 }
3525                         }
3526
3527                         break;
3528
3529                 case FILE_SUPERSEDE:
3530                 case FILE_OVERWRITE:
3531                 case FILE_OVERWRITE_IF:
3532                 default:
3533                         DEBUG(5,("open_directory: invalid create_disposition "
3534                                  "0x%x for directory %s\n",
3535                                  (unsigned int)create_disposition,
3536                                  smb_fname_str_dbg(smb_dname)));
3537                         return NT_STATUS_INVALID_PARAMETER;
3538         }
3539
3540         if(!S_ISDIR(smb_dname->st.st_ex_mode)) {
3541                 DEBUG(5,("open_directory: %s is not a directory !\n",
3542                          smb_fname_str_dbg(smb_dname)));
3543                 return NT_STATUS_NOT_A_DIRECTORY;
3544         }
3545
3546         if (info == FILE_WAS_OPENED) {
3547                 status = smbd_check_access_rights(conn,
3548                                                 smb_dname,
3549                                                 false,
3550                                                 access_mask);
3551                 if (!NT_STATUS_IS_OK(status)) {
3552                         DEBUG(10, ("open_directory: smbd_check_access_rights on "
3553                                 "file %s failed with %s\n",
3554                                 smb_fname_str_dbg(smb_dname),
3555                                 nt_errstr(status)));
3556                         return status;
3557                 }
3558         }
3559
3560         status = file_new(req, conn, &fsp);
3561         if(!NT_STATUS_IS_OK(status)) {
3562                 return status;
3563         }
3564
3565         /*
3566          * Setup the files_struct for it.
3567          */
3568
3569         fsp->file_id = vfs_file_id_from_sbuf(conn, &smb_dname->st);
3570         fsp->vuid = req ? req->vuid : UID_FIELD_INVALID;
3571         fsp->file_pid = req ? req->smbpid : 0;
3572         fsp->can_lock = False;
3573         fsp->can_read = False;
3574         fsp->can_write = False;
3575
3576         fsp->share_access = share_access;
3577         fsp->fh->private_options = 0;
3578         /*
3579          * According to Samba4, SEC_FILE_READ_ATTRIBUTE is always granted,
3580          */
3581         fsp->access_mask = access_mask | FILE_READ_ATTRIBUTES;
3582         fsp->print_file = NULL;
3583         fsp->modified = False;
3584         fsp->oplock_type = NO_OPLOCK;
3585         fsp->sent_oplock_break = NO_BREAK_SENT;
3586         fsp->is_directory = True;
3587         if (file_attributes & FILE_FLAG_POSIX_SEMANTICS) {
3588                 fsp->posix_flags |= FSP_POSIX_FLAGS_ALL;
3589         }
3590         status = fsp_set_smb_fname(fsp, smb_dname);
3591         if (!NT_STATUS_IS_OK(status)) {
3592                 file_free(req, fsp);
3593                 return status;
3594         }
3595
3596         /* Don't store old timestamps for directory
3597            handles in the internal database. We don't
3598            update them in there if new objects
3599            are creaded in the directory. Currently
3600            we only update timestamps on file writes.
3601            See bug #9870.
3602         */
3603         ZERO_STRUCT(mtimespec);
3604
3605         if (access_mask & (FILE_LIST_DIRECTORY|
3606                            FILE_ADD_FILE|
3607                            FILE_ADD_SUBDIRECTORY|
3608                            FILE_TRAVERSE|
3609                            DELETE_ACCESS|
3610                            FILE_DELETE_CHILD)) {
3611 #ifdef O_DIRECTORY
3612                 status = fd_open(conn, fsp, O_RDONLY|O_DIRECTORY, 0);
3613 #else
3614                 /* POSIX allows us to open a directory with O_RDONLY. */
3615                 status = fd_open(conn, fsp, O_RDONLY, 0);
3616 #endif
3617                 if (!NT_STATUS_IS_OK(status)) {
3618                         DEBUG(5, ("open_directory: Could not open fd for "
3619                                 "%s (%s)\n",
3620                                 smb_fname_str_dbg(smb_dname),
3621                                 nt_errstr(status)));
3622                         file_free(req, fsp);
3623                         return status;
3624                 }
3625         } else {
3626                 fsp->fh->fd = -1;
3627                 DEBUG(10, ("Not opening Directory %s\n",
3628                         smb_fname_str_dbg(smb_dname)));
3629         }
3630
3631         status = vfs_stat_fsp(fsp);
3632         if (!NT_STATUS_IS_OK(status)) {
3633                 fd_close(fsp);
3634                 file_free(req, fsp);
3635                 return status;
3636         }
3637
3638         if(!S_ISDIR(fsp->fsp_name->st.st_ex_mode)) {
3639                 DEBUG(5,("open_directory: %s is not a directory !\n",
3640                          smb_fname_str_dbg(smb_dname)));
3641                 fd_close(fsp);
3642                 file_free(req, fsp);
3643                 return NT_STATUS_NOT_A_DIRECTORY;
3644         }
3645
3646         /* Ensure there was no race condition.  We need to check
3647          * dev/inode but not permissions, as these can change
3648          * legitimately */
3649         if (!check_same_dev_ino(&smb_dname->st, &fsp->fsp_name->st)) {
3650                 DEBUG(5,("open_directory: stat struct differs for "
3651                         "directory %s.\n",
3652                         smb_fname_str_dbg(smb_dname)));
3653                 fd_close(fsp);
3654                 file_free(req, fsp);
3655                 return NT_STATUS_ACCESS_DENIED;
3656         }
3657
3658         lck = get_share_mode_lock(talloc_tos(), fsp->file_id,
3659                                   conn->connectpath, smb_dname,
3660                                   &mtimespec);
3661
3662         if (lck == NULL) {
3663                 DEBUG(0, ("open_directory: Could not get share mode lock for "
3664                           "%s\n", smb_fname_str_dbg(smb_dname)));
3665                 fd_close(fsp);
3666                 file_free(req, fsp);
3667                 return NT_STATUS_SHARING_VIOLATION;
3668         }
3669