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