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