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