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