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