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