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