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