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