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