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