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