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