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