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