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