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