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