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