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