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