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