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