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