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