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