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