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