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