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