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