s3: handle non-POSIX compliant Tru64, NetBSD and FreeBSD errno on O_NOFOLLOW symlink...
[kai/samba.git] / source3 / smbd / open.c
1 /* 
2    Unix SMB/CIFS implementation.
3    file opening and share modes
4    Copyright (C) Andrew Tridgell 1992-1998
5    Copyright (C) Jeremy Allison 2001-2004
6    Copyright (C) Volker Lendecke 2005
7
8    This program is free software; you can redistribute it and/or modify
9    it under the terms of the GNU General Public License as published by
10    the Free Software Foundation; either version 3 of the License, or
11    (at your option) any later version.
12
13    This program is distributed in the hope that it will be useful,
14    but WITHOUT ANY WARRANTY; without even the implied warranty of
15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16    GNU General Public License for more details.
17
18    You should have received a copy of the GNU General Public License
19    along with this program.  If not, see <http://www.gnu.org/licenses/>.
20 */
21
22 #include "includes.h"
23 #include "system/filesys.h"
24 #include "printing.h"
25 #include "smbd/smbd.h"
26 #include "smbd/globals.h"
27 #include "fake_file.h"
28 #include "../libcli/security/security.h"
29 #include "../librpc/gen_ndr/ndr_security.h"
30 #include "../librpc/gen_ndr/open_files.h"
31 #include "auth.h"
32 #include "messages.h"
33
34 extern const struct generic_mapping file_generic_mapping;
35
36 struct deferred_open_record {
37         bool delayed_for_oplocks;
38         struct file_id id;
39 };
40
41 /****************************************************************************
42  If the requester wanted DELETE_ACCESS and was rejected because
43  the file ACL didn't include DELETE_ACCESS, see if the parent ACL
44  overrides this.
45 ****************************************************************************/
46
47 static bool parent_override_delete(connection_struct *conn,
48                                         const struct smb_filename *smb_fname,
49                                         uint32_t access_mask,
50                                         uint32_t rejected_mask)
51 {
52         if ((access_mask & DELETE_ACCESS) &&
53                     (rejected_mask & DELETE_ACCESS) &&
54                     can_delete_file_in_directory(conn, smb_fname)) {
55                 return true;
56         }
57         return false;
58 }
59
60 /****************************************************************************
61  Check if we have open rights.
62 ****************************************************************************/
63
64 NTSTATUS smbd_check_access_rights(struct connection_struct *conn,
65                                 const struct smb_filename *smb_fname,
66                                 uint32_t access_mask)
67 {
68         /* Check if we have rights to open. */
69         NTSTATUS status;
70         struct security_descriptor *sd = NULL;
71         uint32_t rejected_share_access;
72         uint32_t rejected_mask = access_mask;
73
74         rejected_share_access = access_mask & ~(conn->share_access);
75
76         if (rejected_share_access) {
77                 DEBUG(10, ("smbd_check_access_rights: rejected share access 0x%x "
78                         "on %s (0x%x)\n",
79                         (unsigned int)access_mask,
80                         smb_fname_str_dbg(smb_fname),
81                         (unsigned int)rejected_share_access ));
82                 return NT_STATUS_ACCESS_DENIED;
83         }
84
85         if (get_current_uid(conn) == (uid_t)0) {
86                 /* I'm sorry sir, I didn't know you were root... */
87                 DEBUG(10,("smbd_check_access_rights: root override "
88                         "on %s. Granting 0x%x\n",
89                         smb_fname_str_dbg(smb_fname),
90                         (unsigned int)access_mask ));
91                 return NT_STATUS_OK;
92         }
93
94         if ((access_mask & DELETE_ACCESS) && !lp_acl_check_permissions(SNUM(conn))) {
95                 DEBUG(10,("smbd_check_access_rights: not checking ACL "
96                         "on DELETE_ACCESS on file %s. Granting 0x%x\n",
97                         smb_fname_str_dbg(smb_fname),
98                         (unsigned int)access_mask ));
99                 return NT_STATUS_OK;
100         }
101
102         if (access_mask == DELETE_ACCESS &&
103                         VALID_STAT(smb_fname->st) &&
104                         S_ISLNK(smb_fname->st.st_ex_mode)) {
105                 /* We can always delete a symlink. */
106                 DEBUG(10,("smbd_check_access_rights: not checking ACL "
107                         "on DELETE_ACCESS on symlink %s.\n",
108                         smb_fname_str_dbg(smb_fname) ));
109                 return NT_STATUS_OK;
110         }
111
112         status = SMB_VFS_GET_NT_ACL(conn, smb_fname->base_name,
113                         (SECINFO_OWNER |
114                         SECINFO_GROUP |
115                         SECINFO_DACL),&sd);
116
117         if (!NT_STATUS_IS_OK(status)) {
118                 DEBUG(10, ("smbd_check_access_rights: Could not get acl "
119                         "on %s: %s\n",
120                         smb_fname_str_dbg(smb_fname),
121                         nt_errstr(status)));
122
123                 if (NT_STATUS_EQUAL(status, NT_STATUS_ACCESS_DENIED)) {
124                         goto access_denied;
125                 }
126
127                 return status;
128         }
129
130         /*
131          * Never test FILE_READ_ATTRIBUTES. se_access_check() also takes care of
132          * owner WRITE_DAC and READ_CONTROL.
133          */
134         status = se_access_check(sd,
135                                 get_current_nttok(conn),
136                                 (access_mask & ~FILE_READ_ATTRIBUTES),
137                                 &rejected_mask);
138
139         DEBUG(10,("smbd_check_access_rights: file %s requesting "
140                 "0x%x returning 0x%x (%s)\n",
141                 smb_fname_str_dbg(smb_fname),
142                 (unsigned int)access_mask,
143                 (unsigned int)rejected_mask,
144                 nt_errstr(status) ));
145
146         if (!NT_STATUS_IS_OK(status)) {
147                 if (DEBUGLEVEL >= 10) {
148                         DEBUG(10,("smbd_check_access_rights: acl for %s is:\n",
149                                 smb_fname_str_dbg(smb_fname) ));
150                         NDR_PRINT_DEBUG(security_descriptor, sd);
151                 }
152         }
153
154         TALLOC_FREE(sd);
155
156         if (NT_STATUS_IS_OK(status) ||
157                         !NT_STATUS_EQUAL(status, NT_STATUS_ACCESS_DENIED)) {
158                 return status;
159         }
160
161         /* Here we know status == NT_STATUS_ACCESS_DENIED. */
162
163   access_denied:
164
165         if ((access_mask & FILE_WRITE_ATTRIBUTES) &&
166                         (rejected_mask & FILE_WRITE_ATTRIBUTES) &&
167                         !lp_store_dos_attributes(SNUM(conn)) &&
168                         (lp_map_readonly(SNUM(conn)) ||
169                         lp_map_archive(SNUM(conn)) ||
170                         lp_map_hidden(SNUM(conn)) ||
171                         lp_map_system(SNUM(conn)))) {
172                 rejected_mask &= ~FILE_WRITE_ATTRIBUTES;
173
174                 DEBUG(10,("smbd_check_access_rights: "
175                         "overrode "
176                         "FILE_WRITE_ATTRIBUTES "
177                         "on file %s\n",
178                         smb_fname_str_dbg(smb_fname)));
179         }
180
181         if (parent_override_delete(conn,
182                                 smb_fname,
183                                 access_mask,
184                                 rejected_mask)) {
185                 /* Were we trying to do an open
186                  * for delete and didn't get DELETE
187                  * access (only) ? Check if the
188                  * directory allows DELETE_CHILD.
189                  * See here:
190                  * http://blogs.msdn.com/oldnewthing/archive/2004/06/04/148426.aspx
191                  * for details. */
192
193                 rejected_mask &= ~DELETE_ACCESS;
194
195                 DEBUG(10,("smbd_check_access_rights: "
196                         "overrode "
197                         "DELETE_ACCESS on "
198                         "file %s\n",
199                         smb_fname_str_dbg(smb_fname)));
200         }
201
202         if (rejected_mask != 0) {
203                 return NT_STATUS_ACCESS_DENIED;
204         }
205         return NT_STATUS_OK;
206 }
207
208 static NTSTATUS check_parent_access(struct connection_struct *conn,
209                                 struct smb_filename *smb_fname,
210                                 uint32_t access_mask)
211 {
212         NTSTATUS status;
213         char *parent_dir = NULL;
214         struct security_descriptor *parent_sd = NULL;
215         uint32_t access_granted = 0;
216
217         if (!parent_dirname(talloc_tos(),
218                                 smb_fname->base_name,
219                                 &parent_dir,
220                                 NULL)) {
221                 return NT_STATUS_NO_MEMORY;
222         }
223
224         if (get_current_uid(conn) == (uid_t)0) {
225                 /* I'm sorry sir, I didn't know you were root... */
226                 DEBUG(10,("check_parent_access: root override "
227                         "on %s. Granting 0x%x\n",
228                         smb_fname_str_dbg(smb_fname),
229                         (unsigned int)access_mask ));
230                 return NT_STATUS_OK;
231         }
232
233         status = SMB_VFS_GET_NT_ACL(conn,
234                                 parent_dir,
235                                 SECINFO_DACL,
236                                 &parent_sd);
237
238         if (!NT_STATUS_IS_OK(status)) {
239                 DEBUG(5,("check_parent_access: SMB_VFS_GET_NT_ACL failed for "
240                         "%s with error %s\n",
241                         parent_dir,
242                         nt_errstr(status)));
243                 return status;
244         }
245
246         /*
247          * Never test FILE_READ_ATTRIBUTES. se_access_check() also takes care of
248          * owner WRITE_DAC and READ_CONTROL.
249          */
250         status = se_access_check(parent_sd,
251                                 get_current_nttok(conn),
252                                 (access_mask & ~FILE_READ_ATTRIBUTES),
253                                 &access_granted);
254         if(!NT_STATUS_IS_OK(status)) {
255                 DEBUG(5,("check_parent_access: access check "
256                         "on directory %s for "
257                         "path %s for mask 0x%x returned (0x%x) %s\n",
258                         parent_dir,
259                         smb_fname->base_name,
260                         access_mask,
261                         access_granted,
262                         nt_errstr(status) ));
263                 return status;
264         }
265
266         return NT_STATUS_OK;
267 }
268
269 /****************************************************************************
270  fd support routines - attempt to do a dos_open.
271 ****************************************************************************/
272
273 static NTSTATUS fd_open(struct connection_struct *conn,
274                     files_struct *fsp,
275                     int flags,
276                     mode_t mode)
277 {
278         struct smb_filename *smb_fname = fsp->fsp_name;
279         NTSTATUS status = NT_STATUS_OK;
280
281 #ifdef O_NOFOLLOW
282         /* 
283          * Never follow symlinks on a POSIX client. The
284          * client should be doing this.
285          */
286
287         if (fsp->posix_open || !lp_symlinks(SNUM(conn))) {
288                 flags |= O_NOFOLLOW;
289         }
290 #endif
291
292         fsp->fh->fd = SMB_VFS_OPEN(conn, smb_fname, fsp, flags, mode);
293         if (fsp->fh->fd == -1) {
294 #ifdef O_NOFOLLOW
295                 int posix_errno = errno;
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 (!procid_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         } else if (lp_locking(fsp->conn->params) && file_has_brlocks(fsp)) {
1287                 DEBUG(10,("grant_fsp_oplock_type: file %s has byte range locks\n",
1288                         fsp_str_dbg(fsp)));
1289                 fsp->oplock_type = NO_OPLOCK;
1290         }
1291
1292         if (is_stat_open(fsp->access_mask)) {
1293                 /* Leave the value already set. */
1294                 DEBUG(10,("grant_fsp_oplock_type: oplock type 0x%x on file %s\n",
1295                         fsp->oplock_type, fsp_str_dbg(fsp)));
1296                 return;
1297         }
1298
1299         /*
1300          * Match what was requested (fsp->oplock_type) with
1301          * what was found in the existing share modes.
1302          */
1303
1304         if (got_a_none_oplock) {
1305                 fsp->oplock_type = NO_OPLOCK;
1306         } else if (got_level2_oplock) {
1307                 if (fsp->oplock_type == NO_OPLOCK ||
1308                                 fsp->oplock_type == FAKE_LEVEL_II_OPLOCK) {
1309                         /* Store a level2 oplock, but don't tell the client */
1310                         fsp->oplock_type = FAKE_LEVEL_II_OPLOCK;
1311                 } else {
1312                         fsp->oplock_type = LEVEL_II_OPLOCK;
1313                 }
1314         } else {
1315                 /* All share_mode_entries are placeholders or deferred.
1316                  * Silently upgrade to fake levelII if the client didn't
1317                  * ask for an oplock. */
1318                 if (fsp->oplock_type == NO_OPLOCK) {
1319                         /* Store a level2 oplock, but don't tell the client */
1320                         fsp->oplock_type = FAKE_LEVEL_II_OPLOCK;
1321                 }
1322         }
1323
1324         /*
1325          * Don't grant level2 to clients that don't want them
1326          * or if we've turned them off.
1327          */
1328         if (fsp->oplock_type == LEVEL_II_OPLOCK && !allow_level2) {
1329                 fsp->oplock_type = FAKE_LEVEL_II_OPLOCK;
1330         }
1331
1332         DEBUG(10,("grant_fsp_oplock_type: oplock type 0x%x on file %s\n",
1333                   fsp->oplock_type, fsp_str_dbg(fsp)));
1334 }
1335
1336 bool request_timed_out(struct timeval request_time,
1337                        struct timeval timeout)
1338 {
1339         struct timeval now, end_time;
1340         GetTimeOfDay(&now);
1341         end_time = timeval_sum(&request_time, &timeout);
1342         return (timeval_compare(&end_time, &now) < 0);
1343 }
1344
1345 /****************************************************************************
1346  Handle the 1 second delay in returning a SHARING_VIOLATION error.
1347 ****************************************************************************/
1348
1349 static void defer_open(struct share_mode_lock *lck,
1350                        struct timeval request_time,
1351                        struct timeval timeout,
1352                        struct smb_request *req,
1353                        struct deferred_open_record *state)
1354 {
1355         struct server_id self = messaging_server_id(req->sconn->msg_ctx);
1356         int i;
1357
1358         /* Paranoia check */
1359
1360         for (i=0; i<lck->data->num_share_modes; i++) {
1361                 struct share_mode_entry *e = &lck->data->share_modes[i];
1362
1363                 if (is_deferred_open_entry(e) &&
1364                     procid_equal(&self, &e->pid) &&
1365                     (e->op_mid == req->mid)) {
1366                         DEBUG(0, ("Trying to defer an already deferred "
1367                                 "request: mid=%llu, exiting\n",
1368                                 (unsigned long long)req->mid));
1369                         exit_server("attempt to defer a deferred request");
1370                 }
1371         }
1372
1373         /* End paranoia check */
1374
1375         DEBUG(10,("defer_open_sharing_error: time [%u.%06u] adding deferred "
1376                   "open entry for mid %llu\n",
1377                   (unsigned int)request_time.tv_sec,
1378                   (unsigned int)request_time.tv_usec,
1379                   (unsigned long long)req->mid));
1380
1381         if (!push_deferred_open_message_smb(req, request_time, timeout,
1382                                        state->id, (char *)state, sizeof(*state))) {
1383                 exit_server("push_deferred_open_message_smb failed");
1384         }
1385         add_deferred_open(lck, req->mid, request_time, self, state->id);
1386 }
1387
1388
1389 /****************************************************************************
1390  On overwrite open ensure that the attributes match.
1391 ****************************************************************************/
1392
1393 bool open_match_attributes(connection_struct *conn,
1394                            uint32 old_dos_attr,
1395                            uint32 new_dos_attr,
1396                            mode_t existing_unx_mode,
1397                            mode_t new_unx_mode,
1398                            mode_t *returned_unx_mode)
1399 {
1400         uint32 noarch_old_dos_attr, noarch_new_dos_attr;
1401
1402         noarch_old_dos_attr = (old_dos_attr & ~FILE_ATTRIBUTE_ARCHIVE);
1403         noarch_new_dos_attr = (new_dos_attr & ~FILE_ATTRIBUTE_ARCHIVE);
1404
1405         if((noarch_old_dos_attr == 0 && noarch_new_dos_attr != 0) || 
1406            (noarch_old_dos_attr != 0 && ((noarch_old_dos_attr & noarch_new_dos_attr) == noarch_old_dos_attr))) {
1407                 *returned_unx_mode = new_unx_mode;
1408         } else {
1409                 *returned_unx_mode = (mode_t)0;
1410         }
1411
1412         DEBUG(10,("open_match_attributes: old_dos_attr = 0x%x, "
1413                   "existing_unx_mode = 0%o, new_dos_attr = 0x%x "
1414                   "returned_unx_mode = 0%o\n",
1415                   (unsigned int)old_dos_attr,
1416                   (unsigned int)existing_unx_mode,
1417                   (unsigned int)new_dos_attr,
1418                   (unsigned int)*returned_unx_mode ));
1419
1420         /* If we're mapping SYSTEM and HIDDEN ensure they match. */
1421         if (lp_map_system(SNUM(conn)) || lp_store_dos_attributes(SNUM(conn))) {
1422                 if ((old_dos_attr & FILE_ATTRIBUTE_SYSTEM) &&
1423                     !(new_dos_attr & FILE_ATTRIBUTE_SYSTEM)) {
1424                         return False;
1425                 }
1426         }
1427         if (lp_map_hidden(SNUM(conn)) || lp_store_dos_attributes(SNUM(conn))) {
1428                 if ((old_dos_attr & FILE_ATTRIBUTE_HIDDEN) &&
1429                     !(new_dos_attr & FILE_ATTRIBUTE_HIDDEN)) {
1430                         return False;
1431                 }
1432         }
1433         return True;
1434 }
1435
1436 /****************************************************************************
1437  Special FCB or DOS processing in the case of a sharing violation.
1438  Try and find a duplicated file handle.
1439 ****************************************************************************/
1440
1441 static NTSTATUS fcb_or_dos_open(struct smb_request *req,
1442                                 connection_struct *conn,
1443                                 files_struct *fsp_to_dup_into,
1444                                 const struct smb_filename *smb_fname,
1445                                 struct file_id id,
1446                                 uint16 file_pid,
1447                                 uint64_t vuid,
1448                                 uint32 access_mask,
1449                                 uint32 share_access,
1450                                 uint32 create_options)
1451 {
1452         files_struct *fsp;
1453
1454         DEBUG(5,("fcb_or_dos_open: attempting old open semantics for "
1455                  "file %s.\n", smb_fname_str_dbg(smb_fname)));
1456
1457         for(fsp = file_find_di_first(conn->sconn, id); fsp;
1458             fsp = file_find_di_next(fsp)) {
1459
1460                 DEBUG(10,("fcb_or_dos_open: checking file %s, fd = %d, "
1461                           "vuid = %llu, file_pid = %u, private_options = 0x%x "
1462                           "access_mask = 0x%x\n", fsp_str_dbg(fsp),
1463                           fsp->fh->fd, (unsigned long long)fsp->vuid,
1464                           (unsigned int)fsp->file_pid,
1465                           (unsigned int)fsp->fh->private_options,
1466                           (unsigned int)fsp->access_mask ));
1467
1468                 if (fsp->fh->fd != -1 &&
1469                     fsp->vuid == vuid &&
1470                     fsp->file_pid == file_pid &&
1471                     (fsp->fh->private_options & (NTCREATEX_OPTIONS_PRIVATE_DENY_DOS |
1472                                                  NTCREATEX_OPTIONS_PRIVATE_DENY_FCB)) &&
1473                     (fsp->access_mask & FILE_WRITE_DATA) &&
1474                     strequal(fsp->fsp_name->base_name, smb_fname->base_name) &&
1475                     strequal(fsp->fsp_name->stream_name,
1476                              smb_fname->stream_name)) {
1477                         DEBUG(10,("fcb_or_dos_open: file match\n"));
1478                         break;
1479                 }
1480         }
1481
1482         if (!fsp) {
1483                 return NT_STATUS_NOT_FOUND;
1484         }
1485
1486         /* quite an insane set of semantics ... */
1487         if (is_executable(smb_fname->base_name) &&
1488             (fsp->fh->private_options & NTCREATEX_OPTIONS_PRIVATE_DENY_DOS)) {
1489                 DEBUG(10,("fcb_or_dos_open: file fail due to is_executable.\n"));
1490                 return NT_STATUS_INVALID_PARAMETER;
1491         }
1492
1493         /* We need to duplicate this fsp. */
1494         return dup_file_fsp(req, fsp, access_mask, share_access,
1495                             create_options, fsp_to_dup_into);
1496 }
1497
1498 static void schedule_defer_open(struct share_mode_lock *lck,
1499                                 struct timeval request_time,
1500                                 struct smb_request *req)
1501 {
1502         struct deferred_open_record state;
1503
1504         /* This is a relative time, added to the absolute
1505            request_time value to get the absolute timeout time.
1506            Note that if this is the second or greater time we enter
1507            this codepath for this particular request mid then
1508            request_time is left as the absolute time of the *first*
1509            time this request mid was processed. This is what allows
1510            the request to eventually time out. */
1511
1512         struct timeval timeout;
1513
1514         /* Normally the smbd we asked should respond within
1515          * OPLOCK_BREAK_TIMEOUT seconds regardless of whether
1516          * the client did, give twice the timeout as a safety
1517          * measure here in case the other smbd is stuck
1518          * somewhere else. */
1519
1520         timeout = timeval_set(OPLOCK_BREAK_TIMEOUT*2, 0);
1521
1522         /* Nothing actually uses state.delayed_for_oplocks
1523            but it's handy to differentiate in debug messages
1524            between a 30 second delay due to oplock break, and
1525            a 1 second delay for share mode conflicts. */
1526
1527         state.delayed_for_oplocks = True;
1528         state.id = lck->data->id;
1529
1530         if (!request_timed_out(request_time, timeout)) {
1531                 defer_open(lck, request_time, timeout, req, &state);
1532         }
1533 }
1534
1535 /****************************************************************************
1536  Work out what access_mask to use from what the client sent us.
1537 ****************************************************************************/
1538
1539 static NTSTATUS smbd_calculate_maximum_allowed_access(
1540         connection_struct *conn,
1541         const struct smb_filename *smb_fname,
1542         uint32_t *p_access_mask)
1543 {
1544         struct security_descriptor *sd;
1545         uint32_t access_granted;
1546         NTSTATUS status;
1547
1548         if (get_current_uid(conn) == (uid_t)0) {
1549                 *p_access_mask |= FILE_GENERIC_ALL;
1550                 return NT_STATUS_OK;
1551         }
1552
1553         status = SMB_VFS_GET_NT_ACL(conn, smb_fname->base_name,
1554                                     (SECINFO_OWNER |
1555                                      SECINFO_GROUP |
1556                                      SECINFO_DACL),&sd);
1557
1558         if (NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
1559                 /*
1560                  * File did not exist
1561                  */
1562                 *p_access_mask = FILE_GENERIC_ALL;
1563                 return NT_STATUS_OK;
1564         }
1565         if (!NT_STATUS_IS_OK(status)) {
1566                 DEBUG(10,("smbd_calculate_access_mask: "
1567                           "Could not get acl on file %s: %s\n",
1568                           smb_fname_str_dbg(smb_fname),
1569                           nt_errstr(status)));
1570                 return NT_STATUS_ACCESS_DENIED;
1571         }
1572
1573         /*
1574          * Never test FILE_READ_ATTRIBUTES. se_access_check()
1575          * also takes care of owner WRITE_DAC and READ_CONTROL.
1576          */
1577         status = se_access_check(sd,
1578                                  get_current_nttok(conn),
1579                                  (*p_access_mask & ~FILE_READ_ATTRIBUTES),
1580                                  &access_granted);
1581
1582         TALLOC_FREE(sd);
1583
1584         if (!NT_STATUS_IS_OK(status)) {
1585                 DEBUG(10, ("smbd_calculate_access_mask: "
1586                            "Access denied on file %s: "
1587                            "when calculating maximum access\n",
1588                            smb_fname_str_dbg(smb_fname)));
1589                 return NT_STATUS_ACCESS_DENIED;
1590         }
1591         *p_access_mask = (access_granted | FILE_READ_ATTRIBUTES);
1592         return NT_STATUS_OK;
1593 }
1594
1595 NTSTATUS smbd_calculate_access_mask(connection_struct *conn,
1596                                     const struct smb_filename *smb_fname,
1597                                     uint32_t access_mask,
1598                                     uint32_t *access_mask_out)
1599 {
1600         NTSTATUS status;
1601         uint32_t orig_access_mask = access_mask;
1602         uint32_t rejected_share_access;
1603
1604         /*
1605          * Convert GENERIC bits to specific bits.
1606          */
1607
1608         se_map_generic(&access_mask, &file_generic_mapping);
1609
1610         /* Calculate MAXIMUM_ALLOWED_ACCESS if requested. */
1611         if (access_mask & MAXIMUM_ALLOWED_ACCESS) {
1612
1613                 status = smbd_calculate_maximum_allowed_access(
1614                         conn, smb_fname, &access_mask);
1615
1616                 if (!NT_STATUS_IS_OK(status)) {
1617                         return status;
1618                 }
1619
1620                 access_mask &= conn->share_access;
1621         }
1622
1623         rejected_share_access = access_mask & ~(conn->share_access);
1624
1625         if (rejected_share_access) {
1626                 DEBUG(10, ("smbd_calculate_access_mask: Access denied on "
1627                         "file %s: rejected by share access mask[0x%08X] "
1628                         "orig[0x%08X] mapped[0x%08X] reject[0x%08X]\n",
1629                         smb_fname_str_dbg(smb_fname),
1630                         conn->share_access,
1631                         orig_access_mask, access_mask,
1632                         rejected_share_access));
1633                 return NT_STATUS_ACCESS_DENIED;
1634         }
1635
1636         *access_mask_out = access_mask;
1637         return NT_STATUS_OK;
1638 }
1639
1640 /****************************************************************************
1641  Remove the deferred open entry under lock.
1642 ****************************************************************************/
1643
1644 void remove_deferred_open_entry(struct file_id id, uint64_t mid,
1645                                 struct server_id pid)
1646 {
1647         struct share_mode_lock *lck = get_existing_share_mode_lock(
1648                 talloc_tos(), id);
1649         if (lck == NULL) {
1650                 DEBUG(0, ("could not get share mode lock\n"));
1651                 return;
1652         }
1653         del_deferred_open_entry(lck, mid, pid);
1654         TALLOC_FREE(lck);
1655 }
1656
1657 /****************************************************************************
1658  Open a file with a share mode. Passed in an already created files_struct *.
1659 ****************************************************************************/
1660
1661 static NTSTATUS open_file_ntcreate(connection_struct *conn,
1662                             struct smb_request *req,
1663                             uint32 access_mask,         /* access bits (FILE_READ_DATA etc.) */
1664                             uint32 share_access,        /* share constants (FILE_SHARE_READ etc) */
1665                             uint32 create_disposition,  /* FILE_OPEN_IF etc. */
1666                             uint32 create_options,      /* options such as delete on close. */
1667                             uint32 new_dos_attributes,  /* attributes used for new file. */
1668                             int oplock_request,         /* internal Samba oplock codes. */
1669                                                         /* Information (FILE_EXISTS etc.) */
1670                             uint32_t private_flags,     /* Samba specific flags. */
1671                             int *pinfo,
1672                             files_struct *fsp)
1673 {
1674         struct smb_filename *smb_fname = fsp->fsp_name;
1675         int flags=0;
1676         int flags2=0;
1677         bool file_existed = VALID_STAT(smb_fname->st);
1678         bool def_acl = False;
1679         bool posix_open = False;
1680         bool new_file_created = False;
1681         bool clear_ads = false;
1682         NTSTATUS fsp_open = NT_STATUS_ACCESS_DENIED;
1683         mode_t new_unx_mode = (mode_t)0;
1684         mode_t unx_mode = (mode_t)0;
1685         int info;
1686         uint32 existing_dos_attributes = 0;
1687         struct timeval request_time = timeval_zero();
1688         struct share_mode_lock *lck = NULL;
1689         uint32 open_access_mask = access_mask;
1690         NTSTATUS status;
1691         char *parent_dir;
1692
1693         if (conn->printer) {
1694                 /*
1695                  * Printers are handled completely differently.
1696                  * Most of the passed parameters are ignored.
1697                  */
1698
1699                 if (pinfo) {
1700                         *pinfo = FILE_WAS_CREATED;
1701                 }
1702
1703                 DEBUG(10, ("open_file_ntcreate: printer open fname=%s\n",
1704                            smb_fname_str_dbg(smb_fname)));
1705
1706                 if (!req) {
1707                         DEBUG(0,("open_file_ntcreate: printer open without "
1708                                 "an SMB request!\n"));
1709                         return NT_STATUS_INTERNAL_ERROR;
1710                 }
1711
1712                 return print_spool_open(fsp, smb_fname->base_name,
1713                                         req->vuid);
1714         }
1715
1716         if (!parent_dirname(talloc_tos(), smb_fname->base_name, &parent_dir,
1717                             NULL)) {
1718                 return NT_STATUS_NO_MEMORY;
1719         }
1720
1721         if (new_dos_attributes & FILE_FLAG_POSIX_SEMANTICS) {
1722                 posix_open = True;
1723                 unx_mode = (mode_t)(new_dos_attributes & ~FILE_FLAG_POSIX_SEMANTICS);
1724                 new_dos_attributes = 0;
1725         } else {
1726                 /* Windows allows a new file to be created and
1727                    silently removes a FILE_ATTRIBUTE_DIRECTORY
1728                    sent by the client. Do the same. */
1729
1730                 new_dos_attributes &= ~FILE_ATTRIBUTE_DIRECTORY;
1731
1732                 /* We add FILE_ATTRIBUTE_ARCHIVE to this as this mode is only used if the file is
1733                  * created new. */
1734                 unx_mode = unix_mode(conn, new_dos_attributes | FILE_ATTRIBUTE_ARCHIVE,
1735                                      smb_fname, parent_dir);
1736         }
1737
1738         DEBUG(10, ("open_file_ntcreate: fname=%s, dos_attrs=0x%x "
1739                    "access_mask=0x%x share_access=0x%x "
1740                    "create_disposition = 0x%x create_options=0x%x "
1741                    "unix mode=0%o oplock_request=%d private_flags = 0x%x\n",
1742                    smb_fname_str_dbg(smb_fname), new_dos_attributes,
1743                    access_mask, share_access, create_disposition,
1744                    create_options, (unsigned int)unx_mode, oplock_request,
1745                    (unsigned int)private_flags));
1746
1747         if ((req == NULL) && ((oplock_request & INTERNAL_OPEN_ONLY) == 0)) {
1748                 DEBUG(0, ("No smb request but not an internal only open!\n"));
1749                 return NT_STATUS_INTERNAL_ERROR;
1750         }
1751
1752         /*
1753          * Only non-internal opens can be deferred at all
1754          */
1755
1756         if (req) {
1757                 void *ptr;
1758                 if (get_deferred_open_message_state(req,
1759                                 &request_time,
1760                                 &ptr)) {
1761
1762                         struct deferred_open_record *state = (struct deferred_open_record *)ptr;
1763                         /* Remember the absolute time of the original
1764                            request with this mid. We'll use it later to
1765                            see if this has timed out. */
1766
1767                         /* Remove the deferred open entry under lock. */
1768                         remove_deferred_open_entry(
1769                                 state->id, req->mid,
1770                                 messaging_server_id(req->sconn->msg_ctx));
1771
1772                         /* Ensure we don't reprocess this message. */
1773                         remove_deferred_open_message_smb(req->sconn, req->mid);
1774                 }
1775         }
1776
1777         if (!posix_open) {
1778                 new_dos_attributes &= SAMBA_ATTRIBUTES_MASK;
1779                 if (file_existed) {
1780                         existing_dos_attributes = dos_mode(conn, smb_fname);
1781                 }
1782         }
1783
1784         /* ignore any oplock requests if oplocks are disabled */
1785         if (!lp_oplocks(SNUM(conn)) ||
1786             IS_VETO_OPLOCK_PATH(conn, smb_fname->base_name)) {
1787                 /* Mask off everything except the private Samba bits. */
1788                 oplock_request &= SAMBA_PRIVATE_OPLOCK_MASK;
1789         }
1790
1791         /* this is for OS/2 long file names - say we don't support them */
1792         if (!lp_posix_pathnames() && strstr(smb_fname->base_name,".+,;=[].")) {
1793                 /* OS/2 Workplace shell fix may be main code stream in a later
1794                  * release. */
1795                 DEBUG(5,("open_file_ntcreate: OS/2 long filenames are not "
1796                          "supported.\n"));
1797                 if (use_nt_status()) {
1798                         return NT_STATUS_OBJECT_NAME_NOT_FOUND;
1799                 }
1800                 return NT_STATUS_DOS(ERRDOS, ERRcannotopen);
1801         }
1802
1803         switch( create_disposition ) {
1804                 /*
1805                  * Currently we're using FILE_SUPERSEDE as the same as
1806                  * FILE_OVERWRITE_IF but they really are
1807                  * different. FILE_SUPERSEDE deletes an existing file
1808                  * (requiring delete access) then recreates it.
1809                  */
1810                 case FILE_SUPERSEDE:
1811                         /* If file exists replace/overwrite. If file doesn't
1812                          * exist create. */
1813                         flags2 |= (O_CREAT | O_TRUNC);
1814                         clear_ads = true;
1815                         break;
1816
1817                 case FILE_OVERWRITE_IF:
1818                         /* If file exists replace/overwrite. If file doesn't
1819                          * exist create. */
1820                         flags2 |= (O_CREAT | O_TRUNC);
1821                         clear_ads = true;
1822                         break;
1823
1824                 case FILE_OPEN:
1825                         /* If file exists open. If file doesn't exist error. */
1826                         if (!file_existed) {
1827                                 DEBUG(5,("open_file_ntcreate: FILE_OPEN "
1828                                          "requested for file %s and file "
1829                                          "doesn't exist.\n",
1830                                          smb_fname_str_dbg(smb_fname)));
1831                                 errno = ENOENT;
1832                                 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
1833                         }
1834                         break;
1835
1836                 case FILE_OVERWRITE:
1837                         /* If file exists overwrite. If file doesn't exist
1838                          * error. */
1839                         if (!file_existed) {
1840                                 DEBUG(5,("open_file_ntcreate: FILE_OVERWRITE "
1841                                          "requested for file %s and file "
1842                                          "doesn't exist.\n",
1843                                          smb_fname_str_dbg(smb_fname) ));
1844                                 errno = ENOENT;
1845                                 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
1846                         }
1847                         flags2 |= O_TRUNC;
1848                         clear_ads = true;
1849                         break;
1850
1851                 case FILE_CREATE:
1852                         /* If file exists error. If file doesn't exist
1853                          * create. */
1854                         if (file_existed) {
1855                                 DEBUG(5,("open_file_ntcreate: FILE_CREATE "
1856                                          "requested for file %s and file "
1857                                          "already exists.\n",
1858                                          smb_fname_str_dbg(smb_fname)));
1859                                 if (S_ISDIR(smb_fname->st.st_ex_mode)) {
1860                                         errno = EISDIR;
1861                                 } else {
1862                                         errno = EEXIST;
1863                                 }
1864                                 return map_nt_error_from_unix(errno);
1865                         }
1866                         flags2 |= (O_CREAT|O_EXCL);
1867                         break;
1868
1869                 case FILE_OPEN_IF:
1870                         /* If file exists open. If file doesn't exist
1871                          * create. */
1872                         flags2 |= O_CREAT;
1873                         break;
1874
1875                 default:
1876                         return NT_STATUS_INVALID_PARAMETER;
1877         }
1878
1879         /* We only care about matching attributes on file exists and
1880          * overwrite. */
1881
1882         if (!posix_open && file_existed && ((create_disposition == FILE_OVERWRITE) ||
1883                              (create_disposition == FILE_OVERWRITE_IF))) {
1884                 if (!open_match_attributes(conn, existing_dos_attributes,
1885                                            new_dos_attributes,
1886                                            smb_fname->st.st_ex_mode,
1887                                            unx_mode, &new_unx_mode)) {
1888                         DEBUG(5,("open_file_ntcreate: attributes missmatch "
1889                                  "for file %s (%x %x) (0%o, 0%o)\n",
1890                                  smb_fname_str_dbg(smb_fname),
1891                                  existing_dos_attributes,
1892                                  new_dos_attributes,
1893                                  (unsigned int)smb_fname->st.st_ex_mode,
1894                                  (unsigned int)unx_mode ));
1895                         errno = EACCES;
1896                         return NT_STATUS_ACCESS_DENIED;
1897                 }
1898         }
1899
1900         status = smbd_calculate_access_mask(conn, smb_fname,
1901                                         access_mask,
1902                                         &access_mask); 
1903         if (!NT_STATUS_IS_OK(status)) {
1904                 DEBUG(10, ("open_file_ntcreate: smbd_calculate_access_mask "
1905                         "on file %s returned %s\n",
1906                         smb_fname_str_dbg(smb_fname), nt_errstr(status)));
1907                 return status;
1908         }
1909
1910         open_access_mask = access_mask;
1911
1912         if ((flags2 & O_TRUNC) || (oplock_request & FORCE_OPLOCK_BREAK_TO_NONE)) {
1913                 open_access_mask |= FILE_WRITE_DATA; /* This will cause oplock breaks. */
1914         }
1915
1916         DEBUG(10, ("open_file_ntcreate: fname=%s, after mapping "
1917                    "access_mask=0x%x\n", smb_fname_str_dbg(smb_fname),
1918                     access_mask));
1919
1920         /*
1921          * Note that we ignore the append flag as append does not
1922          * mean the same thing under DOS and Unix.
1923          */
1924
1925         if ((access_mask & (FILE_WRITE_DATA | FILE_APPEND_DATA)) ||
1926                         (oplock_request & FORCE_OPLOCK_BREAK_TO_NONE)) {
1927                 /* DENY_DOS opens are always underlying read-write on the
1928                    file handle, no matter what the requested access mask
1929                     says. */
1930                 if ((private_flags & NTCREATEX_OPTIONS_PRIVATE_DENY_DOS) ||
1931                         access_mask & (FILE_READ_ATTRIBUTES|FILE_READ_DATA|FILE_READ_EA|FILE_EXECUTE)) {
1932                         flags = O_RDWR;
1933                 } else {
1934                         flags = O_WRONLY;
1935                 }
1936         } else {
1937                 flags = O_RDONLY;
1938         }
1939
1940         /*
1941          * Currently we only look at FILE_WRITE_THROUGH for create options.
1942          */
1943
1944 #if defined(O_SYNC)
1945         if ((create_options & FILE_WRITE_THROUGH) && lp_strict_sync(SNUM(conn))) {
1946                 flags2 |= O_SYNC;
1947         }
1948 #endif /* O_SYNC */
1949
1950         if (posix_open && (access_mask & FILE_APPEND_DATA)) {
1951                 flags2 |= O_APPEND;
1952         }
1953
1954         if (!posix_open && !CAN_WRITE(conn)) {
1955                 /*
1956                  * We should really return a permission denied error if either
1957                  * O_CREAT or O_TRUNC are set, but for compatibility with
1958                  * older versions of Samba we just AND them out.
1959                  */
1960                 flags2 &= ~(O_CREAT|O_TRUNC);
1961         }
1962
1963         /*
1964          * Ensure we can't write on a read-only share or file.
1965          */
1966
1967         if (flags != O_RDONLY && file_existed &&
1968             (!CAN_WRITE(conn) || IS_DOS_READONLY(existing_dos_attributes))) {
1969                 DEBUG(5,("open_file_ntcreate: write access requested for "
1970                          "file %s on read only %s\n",
1971                          smb_fname_str_dbg(smb_fname),
1972                          !CAN_WRITE(conn) ? "share" : "file" ));
1973                 errno = EACCES;
1974                 return NT_STATUS_ACCESS_DENIED;
1975         }
1976
1977         fsp->file_id = vfs_file_id_from_sbuf(conn, &smb_fname->st);
1978         fsp->share_access = share_access;
1979         fsp->fh->private_options = private_flags;
1980         fsp->access_mask = open_access_mask; /* We change this to the
1981                                               * requested access_mask after
1982                                               * the open is done. */
1983         fsp->posix_open = posix_open;
1984
1985         /* Ensure no SAMBA_PRIVATE bits can be set. */
1986         fsp->oplock_type = (oplock_request & ~SAMBA_PRIVATE_OPLOCK_MASK);
1987
1988         if (timeval_is_zero(&request_time)) {
1989                 request_time = fsp->open_time;
1990         }
1991
1992         if (file_existed) {
1993                 struct share_mode_entry *batch_entry = NULL;
1994                 struct share_mode_entry *exclusive_entry = NULL;
1995                 bool got_level2_oplock = false;
1996                 bool got_a_none_oplock = false;
1997                 struct file_id id;
1998
1999                 struct timespec old_write_time = smb_fname->st.st_ex_mtime;
2000                 id = vfs_file_id_from_sbuf(conn, &smb_fname->st);
2001
2002                 lck = get_share_mode_lock(talloc_tos(), id,
2003                                           conn->connectpath,
2004                                           smb_fname, &old_write_time);
2005                 if (lck == NULL) {
2006                         DEBUG(0, ("Could not get share mode lock\n"));
2007                         return NT_STATUS_SHARING_VIOLATION;
2008                 }
2009
2010                 /* Get the types we need to examine. */
2011                 find_oplock_types(fsp,
2012                                 oplock_request,
2013                                 lck,
2014                                 &batch_entry,
2015                                 &exclusive_entry,
2016                                 &got_level2_oplock,
2017                                 &got_a_none_oplock);
2018
2019                 /* First pass - send break only on batch oplocks. */
2020                 if ((req != NULL) &&
2021                                 delay_for_batch_oplocks(fsp,
2022                                         req->mid,
2023                                         oplock_request,
2024                                         batch_entry)) {
2025                         schedule_defer_open(lck, request_time, req);
2026                         TALLOC_FREE(lck);
2027                         return NT_STATUS_SHARING_VIOLATION;
2028                 }
2029
2030                 /* Use the client requested access mask here, not the one we
2031                  * open with. */
2032                 status = open_mode_check(conn, lck, fsp->name_hash,
2033                                         access_mask, share_access,
2034                                          create_options, &file_existed);
2035
2036                 if (NT_STATUS_IS_OK(status)) {
2037                         /* We might be going to allow this open. Check oplock
2038                          * status again. */
2039                         /* Second pass - send break for both batch or
2040                          * exclusive oplocks. */
2041                         if ((req != NULL) &&
2042                                         delay_for_exclusive_oplocks(
2043                                                 fsp,
2044                                                 req->mid,
2045                                                 oplock_request,
2046                                                 exclusive_entry)) {
2047                                 schedule_defer_open(lck, request_time, req);
2048                                 TALLOC_FREE(lck);
2049                                 return NT_STATUS_SHARING_VIOLATION;
2050                         }
2051                 }
2052
2053                 if (NT_STATUS_EQUAL(status, NT_STATUS_DELETE_PENDING)) {
2054                         /* DELETE_PENDING is not deferred for a second */
2055                         TALLOC_FREE(lck);
2056                         return status;
2057                 }
2058
2059                 grant_fsp_oplock_type(fsp,
2060                                 oplock_request,
2061                                 got_level2_oplock,
2062                                 got_a_none_oplock);
2063
2064                 if (!NT_STATUS_IS_OK(status)) {
2065                         uint32 can_access_mask;
2066                         bool can_access = True;
2067
2068                         SMB_ASSERT(NT_STATUS_EQUAL(status, NT_STATUS_SHARING_VIOLATION));
2069
2070                         /* Check if this can be done with the deny_dos and fcb
2071                          * calls. */
2072                         if (private_flags &
2073                             (NTCREATEX_OPTIONS_PRIVATE_DENY_DOS|
2074                              NTCREATEX_OPTIONS_PRIVATE_DENY_FCB)) {
2075                                 if (req == NULL) {
2076                                         DEBUG(0, ("DOS open without an SMB "
2077                                                   "request!\n"));
2078                                         TALLOC_FREE(lck);
2079                                         return NT_STATUS_INTERNAL_ERROR;
2080                                 }
2081
2082                                 /* Use the client requested access mask here,
2083                                  * not the one we open with. */
2084                                 status = fcb_or_dos_open(req,
2085                                                         conn,
2086                                                         fsp,
2087                                                         smb_fname,
2088                                                         id,
2089                                                         req->smbpid,
2090                                                         req->vuid,
2091                                                         access_mask,
2092                                                         share_access,
2093                                                         create_options);
2094
2095                                 if (NT_STATUS_IS_OK(status)) {
2096                                         TALLOC_FREE(lck);
2097                                         if (pinfo) {
2098                                                 *pinfo = FILE_WAS_OPENED;
2099                                         }
2100                                         return NT_STATUS_OK;
2101                                 }
2102                         }
2103
2104                         /*
2105                          * This next line is a subtlety we need for
2106                          * MS-Access. If a file open will fail due to share
2107                          * permissions and also for security (access) reasons,
2108                          * we need to return the access failed error, not the
2109                          * share error. We can't open the file due to kernel
2110                          * oplock deadlock (it's possible we failed above on
2111                          * the open_mode_check()) so use a userspace check.
2112                          */
2113
2114                         if (flags & O_RDWR) {
2115                                 can_access_mask = FILE_READ_DATA|FILE_WRITE_DATA;
2116                         } else if (flags & O_WRONLY) {
2117                                 can_access_mask = FILE_WRITE_DATA;
2118                         } else {
2119                                 can_access_mask = FILE_READ_DATA;
2120                         }
2121
2122                         if (((can_access_mask & FILE_WRITE_DATA) &&
2123                                 !CAN_WRITE(conn)) ||
2124                                 !NT_STATUS_IS_OK(smbd_check_access_rights(conn,
2125                                                 smb_fname, can_access_mask))) {
2126                                 can_access = False;
2127                         }
2128
2129                         /*
2130                          * If we're returning a share violation, ensure we
2131                          * cope with the braindead 1 second delay.
2132                          */
2133
2134                         if (!(oplock_request & INTERNAL_OPEN_ONLY) &&
2135                             lp_defer_sharing_violations()) {
2136                                 struct timeval timeout;
2137                                 struct deferred_open_record state;
2138                                 int timeout_usecs;
2139
2140                                 /* this is a hack to speed up torture tests
2141                                    in 'make test' */
2142                                 timeout_usecs = lp_parm_int(SNUM(conn),
2143                                                             "smbd","sharedelay",
2144                                                             SHARING_VIOLATION_USEC_WAIT);
2145
2146                                 /* This is a relative time, added to the absolute
2147                                    request_time value to get the absolute timeout time.
2148                                    Note that if this is the second or greater time we enter
2149                                    this codepath for this particular request mid then
2150                                    request_time is left as the absolute time of the *first*
2151                                    time this request mid was processed. This is what allows
2152                                    the request to eventually time out. */
2153
2154                                 timeout = timeval_set(0, timeout_usecs);
2155
2156                                 /* Nothing actually uses state.delayed_for_oplocks
2157                                    but it's handy to differentiate in debug messages
2158                                    between a 30 second delay due to oplock break, and
2159                                    a 1 second delay for share mode conflicts. */
2160
2161                                 state.delayed_for_oplocks = False;
2162                                 state.id = id;
2163
2164                                 if ((req != NULL)
2165                                     && !request_timed_out(request_time,
2166                                                           timeout)) {
2167                                         defer_open(lck, request_time, timeout,
2168                                                    req, &state);
2169                                 }
2170                         }
2171
2172                         TALLOC_FREE(lck);
2173                         if (can_access) {
2174                                 /*
2175                                  * We have detected a sharing violation here
2176                                  * so return the correct error code
2177                                  */
2178                                 status = NT_STATUS_SHARING_VIOLATION;
2179                         } else {
2180                                 status = NT_STATUS_ACCESS_DENIED;
2181                         }
2182                         return status;
2183                 }
2184
2185                 /*
2186                  * We exit this block with the share entry *locked*.....
2187                  */
2188         }
2189
2190         SMB_ASSERT(!file_existed || (lck != NULL));
2191
2192         /*
2193          * Ensure we pay attention to default ACLs on directories if required.
2194          */
2195
2196         if ((flags2 & O_CREAT) && lp_inherit_acls(SNUM(conn)) &&
2197             (def_acl = directory_has_default_acl(conn, parent_dir))) {
2198                 unx_mode = (0777 & lp_create_mask(SNUM(conn)));
2199         }
2200
2201         DEBUG(4,("calling open_file with flags=0x%X flags2=0x%X mode=0%o, "
2202                 "access_mask = 0x%x, open_access_mask = 0x%x\n",
2203                  (unsigned int)flags, (unsigned int)flags2,
2204                  (unsigned int)unx_mode, (unsigned int)access_mask,
2205                  (unsigned int)open_access_mask));
2206
2207         /*
2208          * open_file strips any O_TRUNC flags itself.
2209          */
2210
2211         fsp_open = open_file(fsp, conn, req, parent_dir,
2212                              flags|flags2, unx_mode, access_mask,
2213                              open_access_mask);
2214
2215         if (!NT_STATUS_IS_OK(fsp_open)) {
2216                 TALLOC_FREE(lck);
2217                 return fsp_open;
2218         }
2219
2220         if (!file_existed) {
2221                 struct share_mode_entry *batch_entry = NULL;
2222                 struct share_mode_entry *exclusive_entry = NULL;
2223                 bool got_level2_oplock = false;
2224                 bool got_a_none_oplock = false;
2225                 struct timespec old_write_time = smb_fname->st.st_ex_mtime;
2226                 struct file_id id;
2227                 /*
2228                  * Deal with the race condition where two smbd's detect the
2229                  * file doesn't exist and do the create at the same time. One
2230                  * of them will win and set a share mode, the other (ie. this
2231                  * one) should check if the requested share mode for this
2232                  * create is allowed.
2233                  */
2234
2235                 /*
2236                  * Now the file exists and fsp is successfully opened,
2237                  * fsp->dev and fsp->inode are valid and should replace the
2238                  * dev=0,inode=0 from a non existent file. Spotted by
2239                  * Nadav Danieli <nadavd@exanet.com>. JRA.
2240                  */
2241
2242                 id = fsp->file_id;
2243
2244                 lck = get_share_mode_lock(talloc_tos(), id,
2245                                           conn->connectpath,
2246                                           smb_fname, &old_write_time);
2247
2248                 if (lck == NULL) {
2249                         DEBUG(0, ("open_file_ntcreate: Could not get share "
2250                                   "mode lock for %s\n",
2251                                   smb_fname_str_dbg(smb_fname)));
2252                         fd_close(fsp);
2253                         return NT_STATUS_SHARING_VIOLATION;
2254                 }
2255
2256                 /* Get the types we need to examine. */
2257                 find_oplock_types(fsp,
2258                                 oplock_request,
2259                                 lck,
2260                                 &batch_entry,
2261                                 &exclusive_entry,
2262                                 &got_level2_oplock,
2263                                 &got_a_none_oplock);
2264
2265                 /* First pass - send break only on batch oplocks. */
2266                 if ((req != NULL) &&
2267                                 delay_for_batch_oplocks(fsp,
2268                                         req->mid,
2269                                         oplock_request,
2270                                         batch_entry)) {
2271                         schedule_defer_open(lck, request_time, req);
2272                         TALLOC_FREE(lck);
2273                         fd_close(fsp);
2274                         return NT_STATUS_SHARING_VIOLATION;
2275                 }
2276
2277                 status = open_mode_check(conn, lck, fsp->name_hash,
2278                                         access_mask, share_access,
2279                                          create_options, &file_existed);
2280
2281                 if (NT_STATUS_IS_OK(status)) {
2282                         /* We might be going to allow this open. Check oplock
2283                          * status again. */
2284                         /* Second pass - send break for both batch or
2285                          * exclusive oplocks. */
2286                         if ((req != NULL) &&
2287                                         delay_for_exclusive_oplocks(
2288                                                 fsp,
2289                                                 req->mid,
2290                                                 oplock_request,
2291                                                 exclusive_entry)) {
2292                                 schedule_defer_open(lck, request_time, req);
2293                                 TALLOC_FREE(lck);
2294                                 fd_close(fsp);
2295                                 return NT_STATUS_SHARING_VIOLATION;
2296                         }
2297                 }
2298
2299                 if (!NT_STATUS_IS_OK(status)) {
2300                         struct deferred_open_record state;
2301
2302                         state.delayed_for_oplocks = False;
2303                         state.id = id;
2304
2305                         /* Do it all over again immediately. In the second
2306                          * round we will find that the file existed and handle
2307                          * the DELETE_PENDING and FCB cases correctly. No need
2308                          * to duplicate the code here. Essentially this is a
2309                          * "goto top of this function", but don't tell
2310                          * anybody... */
2311
2312                         if (req != NULL) {
2313                                 defer_open(lck, request_time, timeval_zero(),
2314                                            req, &state);
2315                         }
2316                         TALLOC_FREE(lck);
2317                         fd_close(fsp);
2318                         return status;
2319                 }
2320
2321                 grant_fsp_oplock_type(fsp,
2322                                 oplock_request,
2323                                 got_level2_oplock,
2324                                 got_a_none_oplock);
2325
2326                 /*
2327                  * We exit this block with the share entry *locked*.....
2328                  */
2329
2330         }
2331
2332         SMB_ASSERT(lck != NULL);
2333
2334         /* Delete streams if create_disposition requires it */
2335         if (file_existed && clear_ads &&
2336             !is_ntfs_stream_smb_fname(smb_fname)) {
2337                 status = delete_all_streams(conn, smb_fname->base_name);
2338                 if (!NT_STATUS_IS_OK(status)) {
2339                         TALLOC_FREE(lck);
2340                         fd_close(fsp);
2341                         return status;
2342                 }
2343         }
2344
2345         /* note that we ignore failure for the following. It is
2346            basically a hack for NFS, and NFS will never set one of
2347            these only read them. Nobody but Samba can ever set a deny
2348            mode and we have already checked our more authoritative
2349            locking database for permission to set this deny mode. If
2350            the kernel refuses the operations then the kernel is wrong.
2351            note that GPFS supports it as well - jmcd */
2352
2353         if (fsp->fh->fd != -1) {
2354                 int ret_flock;
2355                 ret_flock = SMB_VFS_KERNEL_FLOCK(fsp, share_access, access_mask);
2356                 if(ret_flock == -1 ){
2357
2358                         TALLOC_FREE(lck);
2359                         fd_close(fsp);
2360
2361                         return NT_STATUS_SHARING_VIOLATION;
2362                 }
2363         }
2364
2365         /*
2366          * At this point onwards, we can guarentee that the share entry
2367          * is locked, whether we created the file or not, and that the
2368          * deny mode is compatible with all current opens.
2369          */
2370
2371         /*
2372          * If requested, truncate the file.
2373          */
2374
2375         if (file_existed && (flags2&O_TRUNC)) {
2376                 /*
2377                  * We are modifing the file after open - update the stat
2378                  * struct..
2379                  */
2380                 if ((SMB_VFS_FTRUNCATE(fsp, 0) == -1) ||
2381                     (SMB_VFS_FSTAT(fsp, &smb_fname->st)==-1)) {
2382                         status = map_nt_error_from_unix(errno);
2383                         TALLOC_FREE(lck);
2384                         fd_close(fsp);
2385                         return status;
2386                 }
2387         }
2388
2389         /*
2390          * According to Samba4, SEC_FILE_READ_ATTRIBUTE is always granted,
2391          * but we don't have to store this - just ignore it on access check.
2392          */
2393         if (conn->sconn->using_smb2) {
2394                 /*
2395                  * SMB2 doesn't return it (according to Microsoft tests).
2396                  * Test Case: TestSuite_ScenarioNo009GrantedAccessTestS0
2397                  * File created with access = 0x7 (Read, Write, Delete)
2398                  * Query Info on file returns 0x87 (Read, Write, Delete, Read Attributes)
2399                  */
2400                 fsp->access_mask = access_mask;
2401         } else {
2402                 /* But SMB1 does. */
2403                 fsp->access_mask = access_mask | FILE_READ_ATTRIBUTES;
2404         }
2405
2406         if (file_existed) {
2407                 /* stat opens on existing files don't get oplocks. */
2408                 if (is_stat_open(open_access_mask)) {
2409                         fsp->oplock_type = NO_OPLOCK;
2410                 }
2411
2412                 if (flags2 & O_TRUNC) {
2413                         info = FILE_WAS_OVERWRITTEN;
2414                 } else {
2415                         info = FILE_WAS_OPENED;
2416                 }
2417         } else {
2418                 info = FILE_WAS_CREATED;
2419         }
2420
2421         if (pinfo) {
2422                 *pinfo = info;
2423         }
2424
2425         /*
2426          * Setup the oplock info in both the shared memory and
2427          * file structs.
2428          */
2429
2430         status = set_file_oplock(fsp, fsp->oplock_type);
2431         if (!NT_STATUS_IS_OK(status)) {
2432                 /*
2433                  * Could not get the kernel oplock or there are byte-range
2434                  * locks on the file.
2435                  */
2436                 fsp->oplock_type = NO_OPLOCK;
2437         }
2438
2439         set_share_mode(lck, fsp, get_current_uid(conn),
2440                         req ? req->mid : 0,
2441                        fsp->oplock_type);
2442
2443         /* Handle strange delete on close create semantics. */
2444         if (create_options & FILE_DELETE_ON_CLOSE) {
2445
2446                 status = can_set_delete_on_close(fsp, new_dos_attributes);
2447
2448                 if (!NT_STATUS_IS_OK(status)) {
2449                         /* Remember to delete the mode we just added. */
2450                         del_share_mode(lck, fsp);
2451                         TALLOC_FREE(lck);
2452                         fd_close(fsp);
2453                         return status;
2454                 }
2455                 /* Note that here we set the *inital* delete on close flag,
2456                    not the regular one. The magic gets handled in close. */
2457                 fsp->initial_delete_on_close = True;
2458         }
2459
2460         if (info == FILE_WAS_OVERWRITTEN
2461             || info == FILE_WAS_CREATED
2462             || info == FILE_WAS_SUPERSEDED) {
2463                 new_file_created = True;
2464         }
2465
2466         if (new_file_created) {
2467                 /* Files should be initially set as archive */
2468                 if (lp_map_archive(SNUM(conn)) ||
2469                     lp_store_dos_attributes(SNUM(conn))) {
2470                         if (!posix_open) {
2471                                 if (file_set_dosmode(conn, smb_fname,
2472                                             new_dos_attributes | FILE_ATTRIBUTE_ARCHIVE,
2473                                             parent_dir, true) == 0) {
2474                                         unx_mode = smb_fname->st.st_ex_mode;
2475                                 }
2476                         }
2477                 }
2478         }
2479
2480         /* Determine sparse flag. */
2481         if (posix_open) {
2482                 /* POSIX opens are sparse by default. */
2483                 fsp->is_sparse = true;
2484         } else {
2485                 fsp->is_sparse = (file_existed &&
2486                         (existing_dos_attributes & FILE_ATTRIBUTE_SPARSE));
2487         }
2488
2489         /*
2490          * Take care of inherited ACLs on created files - if default ACL not
2491          * selected.
2492          */
2493
2494         if (!posix_open && !file_existed && !def_acl) {
2495
2496                 int saved_errno = errno; /* We might get ENOSYS in the next
2497                                           * call.. */
2498
2499                 if (SMB_VFS_FCHMOD_ACL(fsp, unx_mode) == -1 &&
2500                     errno == ENOSYS) {
2501                         errno = saved_errno; /* Ignore ENOSYS */
2502                 }
2503
2504         } else if (new_unx_mode) {
2505
2506                 int ret = -1;
2507
2508                 /* Attributes need changing. File already existed. */
2509
2510                 {
2511                         int saved_errno = errno; /* We might get ENOSYS in the
2512                                                   * next call.. */
2513                         ret = SMB_VFS_FCHMOD_ACL(fsp, new_unx_mode);
2514
2515                         if (ret == -1 && errno == ENOSYS) {
2516                                 errno = saved_errno; /* Ignore ENOSYS */
2517                         } else {
2518                                 DEBUG(5, ("open_file_ntcreate: reset "
2519                                           "attributes of file %s to 0%o\n",
2520                                           smb_fname_str_dbg(smb_fname),
2521                                           (unsigned int)new_unx_mode));
2522                                 ret = 0; /* Don't do the fchmod below. */
2523                         }
2524                 }
2525
2526                 if ((ret == -1) &&
2527                     (SMB_VFS_FCHMOD(fsp, new_unx_mode) == -1))
2528                         DEBUG(5, ("open_file_ntcreate: failed to reset "
2529                                   "attributes of file %s to 0%o\n",
2530                                   smb_fname_str_dbg(smb_fname),
2531                                   (unsigned int)new_unx_mode));
2532         }
2533
2534         /* If this is a successful open, we must remove any deferred open
2535          * records. */
2536         if (req != NULL) {
2537                 del_deferred_open_entry(lck, req->mid,
2538                                         messaging_server_id(req->sconn->msg_ctx));
2539         }
2540         TALLOC_FREE(lck);
2541
2542         return NT_STATUS_OK;
2543 }
2544
2545
2546 /****************************************************************************
2547  Open a file for for write to ensure that we can fchmod it.
2548 ****************************************************************************/
2549
2550 NTSTATUS open_file_fchmod(connection_struct *conn,
2551                           struct smb_filename *smb_fname,
2552                           files_struct **result)
2553 {
2554         if (!VALID_STAT(smb_fname->st)) {
2555                 return NT_STATUS_INVALID_PARAMETER;
2556         }
2557
2558         return SMB_VFS_CREATE_FILE(
2559                 conn,                                   /* conn */
2560                 NULL,                                   /* req */
2561                 0,                                      /* root_dir_fid */
2562                 smb_fname,                              /* fname */
2563                 FILE_WRITE_DATA,                        /* access_mask */
2564                 (FILE_SHARE_READ | FILE_SHARE_WRITE |   /* share_access */
2565                     FILE_SHARE_DELETE),
2566                 FILE_OPEN,                              /* create_disposition*/
2567                 0,                                      /* create_options */
2568                 0,                                      /* file_attributes */
2569                 INTERNAL_OPEN_ONLY,                     /* oplock_request */
2570                 0,                                      /* allocation_size */
2571                 0,                                      /* private_flags */
2572                 NULL,                                   /* sd */
2573                 NULL,                                   /* ea_list */
2574                 result,                                 /* result */
2575                 NULL);                                  /* pinfo */
2576 }
2577
2578 static NTSTATUS mkdir_internal(connection_struct *conn,
2579                                struct smb_filename *smb_dname,
2580                                uint32 file_attributes)
2581 {
2582         mode_t mode;
2583         char *parent_dir = NULL;
2584         NTSTATUS status;
2585         bool posix_open = false;
2586         bool need_re_stat = false;
2587         uint32_t access_mask = SEC_DIR_ADD_SUBDIR;
2588
2589         if(access_mask & ~(conn->share_access)) {
2590                 DEBUG(5,("mkdir_internal: failing share access "
2591                          "%s\n", lp_servicename(SNUM(conn))));
2592                 return NT_STATUS_ACCESS_DENIED;
2593         }
2594
2595         if (!parent_dirname(talloc_tos(), smb_dname->base_name, &parent_dir,
2596                             NULL)) {
2597                 return NT_STATUS_NO_MEMORY;
2598         }
2599
2600         if (file_attributes & FILE_FLAG_POSIX_SEMANTICS) {
2601                 posix_open = true;
2602                 mode = (mode_t)(file_attributes & ~FILE_FLAG_POSIX_SEMANTICS);
2603         } else {
2604                 mode = unix_mode(conn, FILE_ATTRIBUTE_DIRECTORY, smb_dname, parent_dir);
2605         }
2606
2607         status = check_parent_access(conn,
2608                                         smb_dname,
2609                                         access_mask);
2610         if(!NT_STATUS_IS_OK(status)) {
2611                 DEBUG(5,("mkdir_internal: check_parent_access "
2612                         "on directory %s for path %s returned %s\n",
2613                         parent_dir,
2614                         smb_dname->base_name,
2615                         nt_errstr(status) ));
2616                 return status;
2617         }
2618
2619         if (SMB_VFS_MKDIR(conn, smb_dname->base_name, mode) != 0) {
2620                 return map_nt_error_from_unix(errno);
2621         }
2622
2623         /* Ensure we're checking for a symlink here.... */
2624         /* We don't want to get caught by a symlink racer. */
2625
2626         if (SMB_VFS_LSTAT(conn, smb_dname) == -1) {
2627                 DEBUG(2, ("Could not stat directory '%s' just created: %s\n",
2628                           smb_fname_str_dbg(smb_dname), strerror(errno)));
2629                 return map_nt_error_from_unix(errno);
2630         }
2631
2632         if (!S_ISDIR(smb_dname->st.st_ex_mode)) {
2633                 DEBUG(0, ("Directory '%s' just created is not a directory !\n",
2634                           smb_fname_str_dbg(smb_dname)));
2635                 return NT_STATUS_NOT_A_DIRECTORY;
2636         }
2637
2638         if (lp_store_dos_attributes(SNUM(conn))) {
2639                 if (!posix_open) {
2640                         file_set_dosmode(conn, smb_dname,
2641                                          file_attributes | FILE_ATTRIBUTE_DIRECTORY,
2642                                          parent_dir, true);
2643                 }
2644         }
2645
2646         if (lp_inherit_perms(SNUM(conn))) {
2647                 inherit_access_posix_acl(conn, parent_dir,
2648                                          smb_dname->base_name, mode);
2649                 need_re_stat = true;
2650         }
2651
2652         if (!posix_open) {
2653                 /*
2654                  * Check if high bits should have been set,
2655                  * then (if bits are missing): add them.
2656                  * Consider bits automagically set by UNIX, i.e. SGID bit from parent
2657                  * dir.
2658                  */
2659                 if ((mode & ~(S_IRWXU|S_IRWXG|S_IRWXO)) &&
2660                     (mode & ~smb_dname->st.st_ex_mode)) {
2661                         SMB_VFS_CHMOD(conn, smb_dname->base_name,
2662                                       (smb_dname->st.st_ex_mode |
2663                                           (mode & ~smb_dname->st.st_ex_mode)));
2664                         need_re_stat = true;
2665                 }
2666         }
2667
2668         /* Change the owner if required. */
2669         if (lp_inherit_owner(SNUM(conn))) {
2670                 change_dir_owner_to_parent(conn, parent_dir,
2671                                            smb_dname->base_name,
2672                                            &smb_dname->st);
2673                 need_re_stat = true;
2674         }
2675
2676         if (need_re_stat) {
2677                 if (SMB_VFS_LSTAT(conn, smb_dname) == -1) {
2678                         DEBUG(2, ("Could not stat directory '%s' just created: %s\n",
2679                           smb_fname_str_dbg(smb_dname), strerror(errno)));
2680                         return map_nt_error_from_unix(errno);
2681                 }
2682         }
2683
2684         notify_fname(conn, NOTIFY_ACTION_ADDED, FILE_NOTIFY_CHANGE_DIR_NAME,
2685                      smb_dname->base_name);
2686
2687         return NT_STATUS_OK;
2688 }
2689
2690 /****************************************************************************
2691  Ensure we didn't get symlink raced on opening a directory.
2692 ****************************************************************************/
2693
2694 bool check_same_stat(const SMB_STRUCT_STAT *sbuf1,
2695                         const SMB_STRUCT_STAT *sbuf2)
2696 {
2697         if (sbuf1->st_ex_uid != sbuf2->st_ex_uid ||
2698                         sbuf1->st_ex_gid != sbuf2->st_ex_gid ||
2699                         sbuf1->st_ex_dev != sbuf2->st_ex_dev ||
2700                         sbuf1->st_ex_ino != sbuf2->st_ex_ino) {
2701                 return false;
2702         }
2703         return true;
2704 }
2705
2706 /****************************************************************************
2707  Open a directory from an NT SMB call.
2708 ****************************************************************************/
2709
2710 static NTSTATUS open_directory(connection_struct *conn,
2711                                struct smb_request *req,
2712                                struct smb_filename *smb_dname,
2713                                uint32 access_mask,
2714                                uint32 share_access,
2715                                uint32 create_disposition,
2716                                uint32 create_options,
2717                                uint32 file_attributes,
2718                                int *pinfo,
2719                                files_struct **result)
2720 {
2721         files_struct *fsp = NULL;
2722         bool dir_existed = VALID_STAT(smb_dname->st) ? True : False;
2723         struct share_mode_lock *lck = NULL;
2724         NTSTATUS status;
2725         struct timespec mtimespec;
2726         int info = 0;
2727
2728         if (is_ntfs_stream_smb_fname(smb_dname)) {
2729                 DEBUG(2, ("open_directory: %s is a stream name!\n",
2730                           smb_fname_str_dbg(smb_dname)));
2731                 return NT_STATUS_NOT_A_DIRECTORY;
2732         }
2733
2734         if (!(file_attributes & FILE_FLAG_POSIX_SEMANTICS)) {
2735                 /* Ensure we have a directory attribute. */
2736                 file_attributes |= FILE_ATTRIBUTE_DIRECTORY;
2737         }
2738
2739         DEBUG(5,("open_directory: opening directory %s, access_mask = 0x%x, "
2740                  "share_access = 0x%x create_options = 0x%x, "
2741                  "create_disposition = 0x%x, file_attributes = 0x%x\n",
2742                  smb_fname_str_dbg(smb_dname),
2743                  (unsigned int)access_mask,
2744                  (unsigned int)share_access,
2745                  (unsigned int)create_options,
2746                  (unsigned int)create_disposition,
2747                  (unsigned int)file_attributes));
2748
2749         status = smbd_calculate_access_mask(conn, smb_dname,
2750                                             access_mask, &access_mask);
2751         if (!NT_STATUS_IS_OK(status)) {
2752                 DEBUG(10, ("open_directory: smbd_calculate_access_mask "
2753                         "on file %s returned %s\n",
2754                         smb_fname_str_dbg(smb_dname),
2755                         nt_errstr(status)));
2756                 return status;
2757         }
2758
2759         if ((access_mask & SEC_FLAG_SYSTEM_SECURITY) &&
2760                         !security_token_has_privilege(get_current_nttok(conn),
2761                                         SEC_PRIV_SECURITY)) {
2762                 DEBUG(10, ("open_directory: open on %s "
2763                         "failed - SEC_FLAG_SYSTEM_SECURITY denied.\n",
2764                         smb_fname_str_dbg(smb_dname)));
2765                 return NT_STATUS_PRIVILEGE_NOT_HELD;
2766         }
2767
2768         switch( create_disposition ) {
2769                 case FILE_OPEN:
2770
2771                         if (!dir_existed) {
2772                                 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
2773                         }
2774
2775                         info = FILE_WAS_OPENED;
2776                         break;
2777
2778                 case FILE_CREATE:
2779
2780                         /* If directory exists error. If directory doesn't
2781                          * exist create. */
2782
2783                         if (dir_existed) {
2784                                 status = NT_STATUS_OBJECT_NAME_COLLISION;
2785                                 DEBUG(2, ("open_directory: unable to create "
2786                                           "%s. Error was %s\n",
2787                                           smb_fname_str_dbg(smb_dname),
2788                                           nt_errstr(status)));
2789                                 return status;
2790                         }
2791
2792                         status = mkdir_internal(conn, smb_dname,
2793                                                 file_attributes);
2794
2795                         if (!NT_STATUS_IS_OK(status)) {
2796                                 DEBUG(2, ("open_directory: unable to create "
2797                                           "%s. Error was %s\n",
2798                                           smb_fname_str_dbg(smb_dname),
2799                                           nt_errstr(status)));
2800                                 return status;
2801                         }
2802
2803                         info = FILE_WAS_CREATED;
2804                         break;
2805
2806                 case FILE_OPEN_IF:
2807                         /*
2808                          * If directory exists open. If directory doesn't
2809                          * exist create.
2810                          */
2811
2812                         if (dir_existed) {
2813                                 status = NT_STATUS_OK;
2814                                 info = FILE_WAS_OPENED;
2815                         } else {
2816                                 status = mkdir_internal(conn, smb_dname,
2817                                                 file_attributes);
2818
2819                                 if (NT_STATUS_IS_OK(status)) {
2820                                         info = FILE_WAS_CREATED;
2821                                 } else {
2822                                         /* Cope with create race. */
2823                                         if (!NT_STATUS_EQUAL(status,
2824                                                         NT_STATUS_OBJECT_NAME_COLLISION)) {
2825                                                 DEBUG(2, ("open_directory: unable to create "
2826                                                         "%s. Error was %s\n",
2827                                                         smb_fname_str_dbg(smb_dname),
2828                                                         nt_errstr(status)));
2829                                                 return status;
2830                                         }
2831                                         info = FILE_WAS_OPENED;
2832                                 }
2833                         }
2834
2835                         break;
2836
2837                 case FILE_SUPERSEDE:
2838                 case FILE_OVERWRITE:
2839                 case FILE_OVERWRITE_IF:
2840                 default:
2841                         DEBUG(5,("open_directory: invalid create_disposition "
2842                                  "0x%x for directory %s\n",
2843                                  (unsigned int)create_disposition,
2844                                  smb_fname_str_dbg(smb_dname)));
2845                         return NT_STATUS_INVALID_PARAMETER;
2846         }
2847
2848         if(!S_ISDIR(smb_dname->st.st_ex_mode)) {
2849                 DEBUG(5,("open_directory: %s is not a directory !\n",
2850                          smb_fname_str_dbg(smb_dname)));
2851                 return NT_STATUS_NOT_A_DIRECTORY;
2852         }
2853
2854         if (info == FILE_WAS_OPENED) {
2855                 status = smbd_check_access_rights(conn, smb_dname, access_mask);
2856                 if (!NT_STATUS_IS_OK(status)) {
2857                         DEBUG(10, ("open_directory: smbd_check_access_rights on "
2858                                 "file %s failed with %s\n",
2859                                 smb_fname_str_dbg(smb_dname),
2860                                 nt_errstr(status)));
2861                         return status;
2862                 }
2863         }
2864
2865         status = file_new(req, conn, &fsp);
2866         if(!NT_STATUS_IS_OK(status)) {
2867                 return status;
2868         }
2869
2870         /*
2871          * Setup the files_struct for it.
2872          */
2873
2874         fsp->file_id = vfs_file_id_from_sbuf(conn, &smb_dname->st);
2875         fsp->vuid = req ? req->vuid : UID_FIELD_INVALID;
2876         fsp->file_pid = req ? req->smbpid : 0;
2877         fsp->can_lock = False;
2878         fsp->can_read = False;
2879         fsp->can_write = False;
2880
2881         fsp->share_access = share_access;
2882         fsp->fh->private_options = 0;
2883         /*
2884          * According to Samba4, SEC_FILE_READ_ATTRIBUTE is always granted,
2885          */
2886         fsp->access_mask = access_mask | FILE_READ_ATTRIBUTES;
2887         fsp->print_file = NULL;
2888         fsp->modified = False;
2889         fsp->oplock_type = NO_OPLOCK;
2890         fsp->sent_oplock_break = NO_BREAK_SENT;
2891         fsp->is_directory = True;
2892         fsp->posix_open = (file_attributes & FILE_FLAG_POSIX_SEMANTICS) ? True : False;
2893         status = fsp_set_smb_fname(fsp, smb_dname);
2894         if (!NT_STATUS_IS_OK(status)) {
2895                 file_free(req, fsp);
2896                 return status;
2897         }
2898
2899         mtimespec = smb_dname->st.st_ex_mtime;
2900
2901 #ifdef O_DIRECTORY
2902         status = fd_open(conn, fsp, O_RDONLY|O_DIRECTORY, 0);
2903 #else
2904         /* POSIX allows us to open a directory with O_RDONLY. */
2905         status = fd_open(conn, fsp, O_RDONLY, 0);
2906 #endif
2907         if (!NT_STATUS_IS_OK(status)) {
2908                 DEBUG(5, ("open_directory: Could not open fd for "
2909                         "%s (%s)\n",
2910                         smb_fname_str_dbg(smb_dname),
2911                         nt_errstr(status)));
2912                 file_free(req, fsp);
2913                 return status;
2914         }
2915
2916         status = vfs_stat_fsp(fsp);
2917         if (!NT_STATUS_IS_OK(status)) {
2918                 fd_close(fsp);
2919                 file_free(req, fsp);
2920                 return status;
2921         }
2922
2923         /* Ensure there was no race condition. */
2924         if (!check_same_stat(&smb_dname->st, &fsp->fsp_name->st)) {
2925                 DEBUG(5,("open_directory: stat struct differs for "
2926                         "directory %s.\n",
2927                         smb_fname_str_dbg(smb_dname)));
2928                 fd_close(fsp);
2929                 file_free(req, fsp);
2930                 return NT_STATUS_ACCESS_DENIED;
2931         }
2932
2933         lck = get_share_mode_lock(talloc_tos(), fsp->file_id,
2934                                   conn->connectpath, smb_dname,
2935                                   &mtimespec);
2936
2937         if (lck == NULL) {
2938                 DEBUG(0, ("open_directory: Could not get share mode lock for "
2939                           "%s\n", smb_fname_str_dbg(smb_dname)));
2940                 fd_close(fsp);
2941                 file_free(req, fsp);
2942                 return NT_STATUS_SHARING_VIOLATION;
2943         }
2944
2945         status = open_mode_check(conn, lck, fsp->name_hash,
2946                                 access_mask, share_access,
2947                                  create_options, &dir_existed);
2948
2949         if (!NT_STATUS_IS_OK(status)) {
2950                 TALLOC_FREE(lck);
2951                 fd_close(fsp);
2952                 file_free(req, fsp);
2953                 return status;
2954         }
2955
2956         set_share_mode(lck, fsp, get_current_uid(conn),
2957                         req ? req->mid : 0, NO_OPLOCK);
2958
2959         /* For directories the delete on close bit at open time seems
2960            always to be honored on close... See test 19 in Samba4 BASE-DELETE. */
2961         if (create_options & FILE_DELETE_ON_CLOSE) {
2962                 status = can_set_delete_on_close(fsp, 0);
2963                 if (!NT_STATUS_IS_OK(status) && !NT_STATUS_EQUAL(status, NT_STATUS_DIRECTORY_NOT_EMPTY)) {
2964                         TALLOC_FREE(lck);
2965                         fd_close(fsp);
2966                         file_free(req, fsp);
2967                         return status;
2968                 }
2969
2970                 if (NT_STATUS_IS_OK(status)) {
2971                         /* Note that here we set the *inital* delete on close flag,
2972                            not the regular one. The magic gets handled in close. */
2973                         fsp->initial_delete_on_close = True;
2974                 }
2975         }
2976
2977         TALLOC_FREE(lck);
2978
2979         if (pinfo) {
2980                 *pinfo = info;
2981         }
2982
2983         *result = fsp;
2984         return NT_STATUS_OK;
2985 }
2986
2987 NTSTATUS create_directory(connection_struct *conn, struct smb_request *req,
2988                           struct smb_filename *smb_dname)
2989 {
2990         NTSTATUS status;
2991         files_struct *fsp;
2992
2993         status = SMB_VFS_CREATE_FILE(
2994                 conn,                                   /* conn */
2995                 req,                                    /* req */
2996                 0,                                      /* root_dir_fid */
2997                 smb_dname,                              /* fname */
2998                 FILE_READ_ATTRIBUTES,                   /* access_mask */
2999                 FILE_SHARE_NONE,                        /* share_access */
3000                 FILE_CREATE,                            /* create_disposition*/
3001                 FILE_DIRECTORY_FILE,                    /* create_options */
3002                 FILE_ATTRIBUTE_DIRECTORY,               /* file_attributes */
3003                 0,                                      /* oplock_request */
3004                 0,                                      /* allocation_size */
3005                 0,                                      /* private_flags */
3006                 NULL,                                   /* sd */
3007                 NULL,                                   /* ea_list */
3008                 &fsp,                                   /* result */
3009                 NULL);                                  /* pinfo */
3010
3011         if (NT_STATUS_IS_OK(status)) {
3012                 close_file(req, fsp, NORMAL_CLOSE);
3013         }
3014
3015         return status;
3016 }
3017
3018 /****************************************************************************
3019  Receive notification that one of our open files has been renamed by another
3020  smbd process.
3021 ****************************************************************************/
3022
3023 void msg_file_was_renamed(struct messaging_context *msg,
3024                           void *private_data,
3025                           uint32_t msg_type,
3026                           struct server_id server_id,
3027                           DATA_BLOB *data)
3028 {
3029         files_struct *fsp;
3030         char *frm = (char *)data->data;
3031         struct file_id id;
3032         const char *sharepath;
3033         const char *base_name;
3034         const char *stream_name;
3035         struct smb_filename *smb_fname = NULL;
3036         size_t sp_len, bn_len;
3037         NTSTATUS status;
3038         struct smbd_server_connection *sconn =
3039                 talloc_get_type_abort(private_data,
3040                 struct smbd_server_connection);
3041
3042         if (data->data == NULL
3043             || data->length < MSG_FILE_RENAMED_MIN_SIZE + 2) {
3044                 DEBUG(0, ("msg_file_was_renamed: Got invalid msg len %d\n",
3045                           (int)data->length));
3046                 return;
3047         }
3048
3049         /* Unpack the message. */
3050         pull_file_id_24(frm, &id);
3051         sharepath = &frm[24];
3052         sp_len = strlen(sharepath);
3053         base_name = sharepath + sp_len + 1;
3054         bn_len = strlen(base_name);
3055         stream_name = sharepath + sp_len + 1 + bn_len + 1;
3056
3057         /* stream_name must always be NULL if there is no stream. */
3058         if (stream_name[0] == '\0') {
3059                 stream_name = NULL;
3060         }
3061
3062         status = create_synthetic_smb_fname(talloc_tos(), base_name,
3063                                             stream_name, NULL, &smb_fname);
3064         if (!NT_STATUS_IS_OK(status)) {
3065                 return;
3066         }
3067
3068         DEBUG(10,("msg_file_was_renamed: Got rename message for sharepath %s, new name %s, "
3069                 "file_id %s\n",
3070                 sharepath, smb_fname_str_dbg(smb_fname),
3071                 file_id_string_tos(&id)));
3072
3073         for(fsp = file_find_di_first(sconn, id); fsp;
3074             fsp = file_find_di_next(fsp)) {
3075                 if (memcmp(fsp->conn->connectpath, sharepath, sp_len) == 0) {
3076
3077                         DEBUG(10,("msg_file_was_renamed: renaming file fnum %d from %s -> %s\n",
3078                                 fsp->fnum, fsp_str_dbg(fsp),
3079                                 smb_fname_str_dbg(smb_fname)));
3080                         status = fsp_set_smb_fname(fsp, smb_fname);
3081                         if (!NT_STATUS_IS_OK(status)) {
3082                                 goto out;
3083                         }
3084                 } else {
3085                         /* TODO. JRA. */
3086                         /* Now we have the complete path we can work out if this is
3087                            actually within this share and adjust newname accordingly. */
3088                         DEBUG(10,("msg_file_was_renamed: share mismatch (sharepath %s "
3089                                 "not sharepath %s) "
3090                                 "fnum %d from %s -> %s\n",
3091                                 fsp->conn->connectpath,
3092                                 sharepath,
3093                                 fsp->fnum,
3094                                 fsp_str_dbg(fsp),
3095                                 smb_fname_str_dbg(smb_fname)));
3096                 }
3097         }
3098  out:
3099         TALLOC_FREE(smb_fname);
3100         return;
3101 }
3102
3103 /*
3104  * If a main file is opened for delete, all streams need to be checked for
3105  * !FILE_SHARE_DELETE. Do this by opening with DELETE_ACCESS.
3106  * If that works, delete them all by setting the delete on close and close.
3107  */
3108
3109 NTSTATUS open_streams_for_delete(connection_struct *conn,
3110                                         const char *fname)
3111 {
3112         struct stream_struct *stream_info = NULL;
3113         files_struct **streams = NULL;
3114         int i;
3115         unsigned int num_streams = 0;
3116         TALLOC_CTX *frame = talloc_stackframe();
3117         NTSTATUS status;
3118
3119         status = vfs_streaminfo(conn, NULL, fname, talloc_tos(),
3120                                 &num_streams, &stream_info);
3121
3122         if (NT_STATUS_EQUAL(status, NT_STATUS_NOT_IMPLEMENTED)
3123             || NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
3124                 DEBUG(10, ("no streams around\n"));
3125                 TALLOC_FREE(frame);
3126                 return NT_STATUS_OK;
3127         }
3128
3129         if (!NT_STATUS_IS_OK(status)) {
3130                 DEBUG(10, ("vfs_streaminfo failed: %s\n",
3131                            nt_errstr(status)));
3132                 goto fail;
3133         }
3134
3135         DEBUG(10, ("open_streams_for_delete found %d streams\n",
3136                    num_streams));
3137
3138         if (num_streams == 0) {
3139                 TALLOC_FREE(frame);
3140                 return NT_STATUS_OK;
3141         }
3142
3143         streams = talloc_array(talloc_tos(), files_struct *, num_streams);
3144         if (streams == NULL) {
3145                 DEBUG(0, ("talloc failed\n"));
3146                 status = NT_STATUS_NO_MEMORY;
3147                 goto fail;
3148         }
3149
3150         for (i=0; i<num_streams; i++) {
3151                 struct smb_filename *smb_fname = NULL;
3152
3153                 if (strequal(stream_info[i].name, "::$DATA")) {
3154                         streams[i] = NULL;
3155                         continue;
3156                 }
3157
3158                 status = create_synthetic_smb_fname(talloc_tos(), fname,
3159                                                     stream_info[i].name,
3160                                                     NULL, &smb_fname);
3161                 if (!NT_STATUS_IS_OK(status)) {
3162                         goto fail;
3163                 }
3164
3165                 if (SMB_VFS_STAT(conn, smb_fname) == -1) {
3166                         DEBUG(10, ("Unable to stat stream: %s\n",
3167                                    smb_fname_str_dbg(smb_fname)));
3168                 }
3169
3170                 status = SMB_VFS_CREATE_FILE(
3171                          conn,                  /* conn */
3172                          NULL,                  /* req */
3173                          0,                     /* root_dir_fid */
3174                          smb_fname,             /* fname */
3175                          DELETE_ACCESS,         /* access_mask */
3176                          (FILE_SHARE_READ |     /* share_access */
3177                              FILE_SHARE_WRITE | FILE_SHARE_DELETE),
3178                          FILE_OPEN,             /* create_disposition*/
3179                          0,                     /* create_options */
3180                          FILE_ATTRIBUTE_NORMAL, /* file_attributes */
3181                          0,                     /* oplock_request */
3182                          0,                     /* allocation_size */
3183                          NTCREATEX_OPTIONS_PRIVATE_STREAM_DELETE, /* private_flags */
3184                          NULL,                  /* sd */
3185                          NULL,                  /* ea_list */
3186                          &streams[i],           /* result */
3187                          NULL);                 /* pinfo */
3188
3189                 if (!NT_STATUS_IS_OK(status)) {
3190                         DEBUG(10, ("Could not open stream %s: %s\n",
3191                                    smb_fname_str_dbg(smb_fname),
3192                                    nt_errstr(status)));
3193
3194                         TALLOC_FREE(smb_fname);
3195                         break;
3196                 }
3197                 TALLOC_FREE(smb_fname);
3198         }
3199
3200         /*
3201          * don't touch the variable "status" beyond this point :-)
3202          */
3203
3204         for (i -= 1 ; i >= 0; i--) {
3205                 if (streams[i] == NULL) {
3206                         continue;
3207                 }
3208
3209                 DEBUG(10, ("Closing stream # %d, %s\n", i,
3210                            fsp_str_dbg(streams[i])));
3211                 close_file(NULL, streams[i], NORMAL_CLOSE);
3212         }
3213
3214  fail:
3215         TALLOC_FREE(frame);
3216         return status;
3217 }
3218
3219 /*********************************************************************
3220  Create a default ACL by inheriting from the parent. If no inheritance
3221  from the parent available, don't set anything. This will leave the actual
3222  permissions the new file or directory already got from the filesystem
3223  as the NT ACL when read.
3224 *********************************************************************/
3225
3226 static NTSTATUS inherit_new_acl(files_struct *fsp)
3227 {
3228         TALLOC_CTX *ctx = talloc_tos();
3229         char *parent_name = NULL;
3230         struct security_descriptor *parent_desc = NULL;
3231         NTSTATUS status = NT_STATUS_OK;
3232         struct security_descriptor *psd = NULL;
3233         struct dom_sid *owner_sid = NULL;
3234         struct dom_sid *group_sid = NULL;
3235         uint32_t security_info_sent = (SECINFO_OWNER | SECINFO_GROUP | SECINFO_DACL);
3236         bool inherit_owner = lp_inherit_owner(SNUM(fsp->conn));
3237         bool inheritable_components = false;
3238         size_t size = 0;
3239
3240         if (!parent_dirname(ctx, fsp->fsp_name->base_name, &parent_name, NULL)) {
3241                 return NT_STATUS_NO_MEMORY;
3242         }
3243
3244         status = SMB_VFS_GET_NT_ACL(fsp->conn,
3245                                 parent_name,
3246                                 (SECINFO_OWNER | SECINFO_GROUP | SECINFO_DACL),
3247                                 &parent_desc);
3248         if (!NT_STATUS_IS_OK(status)) {
3249                 return status;
3250         }
3251
3252         inheritable_components = sd_has_inheritable_components(parent_desc,
3253                                         fsp->is_directory);
3254
3255         if (!inheritable_components && !inherit_owner) {
3256                 /* Nothing to inherit and not setting owner. */
3257                 return NT_STATUS_OK;
3258         }
3259
3260         /* Create an inherited descriptor from the parent. */
3261
3262         if (DEBUGLEVEL >= 10) {
3263                 DEBUG(10,("inherit_new_acl: parent acl for %s is:\n",
3264                         fsp_str_dbg(fsp) ));
3265                 NDR_PRINT_DEBUG(security_descriptor, parent_desc);
3266         }
3267
3268         /* Inherit from parent descriptor if "inherit owner" set. */
3269         if (inherit_owner) {
3270                 owner_sid = parent_desc->owner_sid;
3271                 group_sid = parent_desc->group_sid;
3272         }
3273
3274         if (owner_sid == NULL) {
3275                 owner_sid = &fsp->conn->session_info->security_token->sids[PRIMARY_USER_SID_INDEX];
3276         }
3277         if (group_sid == NULL) {
3278                 group_sid = &fsp->conn->session_info->security_token->sids[PRIMARY_GROUP_SID_INDEX];
3279         }
3280
3281         status = se_create_child_secdesc(ctx,
3282                         &psd,
3283                         &size,
3284                         parent_desc,
3285                         owner_sid,
3286                         group_sid,
3287                         fsp->is_directory);
3288         if (!NT_STATUS_IS_OK(status)) {
3289                 return status;
3290         }
3291
3292         /* If inheritable_components == false,
3293            se_create_child_secdesc()
3294            creates a security desriptor with a NULL dacl
3295            entry, but with SEC_DESC_DACL_PRESENT. We need
3296            to remove that flag. */
3297
3298         if (!inheritable_components) {
3299                 security_info_sent &= ~SECINFO_DACL;
3300                 psd->type &= ~SEC_DESC_DACL_PRESENT;
3301         }
3302
3303         if (DEBUGLEVEL >= 10) {
3304                 DEBUG(10,("inherit_new_acl: child acl for %s is:\n",
3305                         fsp_str_dbg(fsp) ));
3306                 NDR_PRINT_DEBUG(security_descriptor, psd);
3307         }
3308
3309         if (inherit_owner) {
3310                 /* We need to be root to force this. */
3311                 become_root();
3312         }
3313         status = SMB_VFS_FSET_NT_ACL(fsp,
3314                         security_info_sent,
3315                         psd);
3316         if (inherit_owner) {
3317                 unbecome_root();
3318         }
3319         return status;
3320 }
3321
3322 /*
3323  * Wrapper around open_file_ntcreate and open_directory
3324  */
3325
3326 static NTSTATUS create_file_unixpath(connection_struct *conn,
3327                                      struct smb_request *req,
3328                                      struct smb_filename *smb_fname,
3329                                      uint32_t access_mask,
3330                                      uint32_t share_access,
3331                                      uint32_t create_disposition,
3332                                      uint32_t create_options,
3333                                      uint32_t file_attributes,
3334                                      uint32_t oplock_request,
3335                                      uint64_t allocation_size,
3336                                      uint32_t private_flags,
3337                                      struct security_descriptor *sd,
3338                                      struct ea_list *ea_list,
3339
3340                                      files_struct **result,
3341                                      int *pinfo)
3342 {
3343         int info = FILE_WAS_OPENED;
3344         files_struct *base_fsp = NULL;
3345         files_struct *fsp = NULL;
3346         NTSTATUS status;
3347
3348         DEBUG(10,("create_file_unixpath: access_mask = 0x%x "
3349                   "file_attributes = 0x%x, share_access = 0x%x, "
3350                   "create_disposition = 0x%x create_options = 0x%x "
3351                   "oplock_request = 0x%x private_flags = 0x%x "
3352                   "ea_list = 0x%p, sd = 0x%p, "
3353                   "fname = %s\n",
3354                   (unsigned int)access_mask,
3355                   (unsigned int)file_attributes,
3356                   (unsigned int)share_access,
3357                   (unsigned int)create_disposition,
3358                   (unsigned int)create_options,
3359                   (unsigned int)oplock_request,
3360                   (unsigned int)private_flags,
3361                   ea_list, sd, smb_fname_str_dbg(smb_fname)));
3362
3363         if (create_options & FILE_OPEN_BY_FILE_ID) {
3364                 status = NT_STATUS_NOT_SUPPORTED;
3365                 goto fail;
3366         }
3367
3368         if (create_options & NTCREATEX_OPTIONS_INVALID_PARAM_MASK) {
3369                 status = NT_STATUS_INVALID_PARAMETER;
3370                 goto fail;
3371         }
3372
3373         if (req == NULL) {
3374                 oplock_request |= INTERNAL_OPEN_ONLY;
3375         }
3376
3377         if ((conn->fs_capabilities & FILE_NAMED_STREAMS)
3378             && (access_mask & DELETE_ACCESS)
3379             && !is_ntfs_stream_smb_fname(smb_fname)) {
3380                 /*
3381                  * We can't open a file with DELETE access if any of the
3382                  * streams is open without FILE_SHARE_DELETE
3383                  */
3384                 status = open_streams_for_delete(conn, smb_fname->base_name);
3385
3386                 if (!NT_STATUS_IS_OK(status)) {
3387                         goto fail;
3388                 }
3389         }
3390
3391         if ((access_mask & SEC_FLAG_SYSTEM_SECURITY) &&
3392                         !security_token_has_privilege(get_current_nttok(conn),
3393                                         SEC_PRIV_SECURITY)) {
3394                 DEBUG(10, ("create_file_unixpath: open on %s "
3395                         "failed - SEC_FLAG_SYSTEM_SECURITY denied.\n",
3396                         smb_fname_str_dbg(smb_fname)));
3397                 status = NT_STATUS_PRIVILEGE_NOT_HELD;
3398                 goto fail;
3399         }
3400
3401         if ((conn->fs_capabilities & FILE_NAMED_STREAMS)
3402             && is_ntfs_stream_smb_fname(smb_fname)
3403             && (!(private_flags & NTCREATEX_OPTIONS_PRIVATE_STREAM_DELETE))) {
3404                 uint32 base_create_disposition;
3405                 struct smb_filename *smb_fname_base = NULL;
3406
3407                 if (create_options & FILE_DIRECTORY_FILE) {
3408                         status = NT_STATUS_NOT_A_DIRECTORY;
3409                         goto fail;
3410                 }
3411
3412                 switch (create_disposition) {
3413                 case FILE_OPEN:
3414                         base_create_disposition = FILE_OPEN;
3415                         break;
3416                 default:
3417                         base_create_disposition = FILE_OPEN_IF;
3418                         break;
3419                 }
3420
3421                 /* Create an smb_filename with stream_name == NULL. */
3422                 status = create_synthetic_smb_fname(talloc_tos(),
3423                                                     smb_fname->base_name,
3424                                                     NULL, NULL,
3425                                                     &smb_fname_base);
3426                 if (!NT_STATUS_IS_OK(status)) {
3427                         goto fail;
3428                 }
3429
3430                 if (SMB_VFS_STAT(conn, smb_fname_base) == -1) {
3431                         DEBUG(10, ("Unable to stat stream: %s\n",
3432                                    smb_fname_str_dbg(smb_fname_base)));
3433                 }
3434
3435                 /* Open the base file. */
3436                 status = create_file_unixpath(conn, NULL, smb_fname_base, 0,
3437                                               FILE_SHARE_READ
3438                                               | FILE_SHARE_WRITE
3439                                               | FILE_SHARE_DELETE,
3440                                               base_create_disposition,
3441                                               0, 0, 0, 0, 0, NULL, NULL,
3442                                               &base_fsp, NULL);
3443                 TALLOC_FREE(smb_fname_base);
3444
3445                 if (!NT_STATUS_IS_OK(status)) {
3446                         DEBUG(10, ("create_file_unixpath for base %s failed: "
3447                                    "%s\n", smb_fname->base_name,
3448                                    nt_errstr(status)));
3449                         goto fail;
3450                 }
3451                 /* we don't need to low level fd */
3452                 fd_close(base_fsp);
3453         }
3454
3455         /*
3456          * If it's a request for a directory open, deal with it separately.
3457          */
3458
3459         if (create_options & FILE_DIRECTORY_FILE) {
3460
3461                 if (create_options & FILE_NON_DIRECTORY_FILE) {
3462                         status = NT_STATUS_INVALID_PARAMETER;
3463                         goto fail;
3464                 }
3465
3466                 /* Can't open a temp directory. IFS kit test. */
3467                 if (!(file_attributes & FILE_FLAG_POSIX_SEMANTICS) &&
3468                      (file_attributes & FILE_ATTRIBUTE_TEMPORARY)) {
3469                         status = NT_STATUS_INVALID_PARAMETER;
3470                         goto fail;
3471                 }
3472
3473                 /*
3474                  * We will get a create directory here if the Win32
3475                  * app specified a security descriptor in the
3476                  * CreateDirectory() call.
3477                  */
3478
3479                 oplock_request = 0;
3480                 status = open_directory(
3481                         conn, req, smb_fname, access_mask, share_access,
3482                         create_disposition, create_options, file_attributes,
3483                         &info, &fsp);
3484         } else {
3485
3486                 /*
3487                  * Ordinary file case.
3488                  */
3489
3490                 status = file_new(req, conn, &fsp);
3491                 if(!NT_STATUS_IS_OK(status)) {
3492                         goto fail;
3493                 }
3494
3495                 status = fsp_set_smb_fname(fsp, smb_fname);
3496                 if (!NT_STATUS_IS_OK(status)) {
3497                         goto fail;
3498                 }
3499
3500                 /*
3501                  * We're opening the stream element of a base_fsp
3502                  * we already opened. Set up the base_fsp pointer.
3503                  */
3504                 if (base_fsp) {
3505                         fsp->base_fsp = base_fsp;
3506                 }
3507
3508                 status = open_file_ntcreate(conn,
3509                                             req,
3510                                             access_mask,
3511                                             share_access,
3512                                             create_disposition,
3513                                             create_options,
3514                                             file_attributes,
3515                                             oplock_request,
3516                                             private_flags,
3517                                             &info,
3518                                             fsp);
3519
3520                 if(!NT_STATUS_IS_OK(status)) {
3521                         file_free(req, fsp);
3522                         fsp = NULL;
3523                 }
3524
3525                 if (NT_STATUS_EQUAL(status, NT_STATUS_FILE_IS_A_DIRECTORY)) {
3526
3527                         /* A stream open never opens a directory */
3528
3529                         if (base_fsp) {
3530                                 status = NT_STATUS_FILE_IS_A_DIRECTORY;
3531                                 goto fail;
3532                         }
3533
3534                         /*
3535                          * Fail the open if it was explicitly a non-directory
3536                          * file.
3537                          */
3538
3539                         if (create_options & FILE_NON_DIRECTORY_FILE) {
3540                                 status = NT_STATUS_FILE_IS_A_DIRECTORY;
3541                                 goto fail;
3542                         }
3543
3544                         oplock_request = 0;
3545                         status = open_directory(
3546                                 conn, req, smb_fname, access_mask,
3547                                 share_access, create_disposition,
3548                                 create_options, file_attributes,
3549                                 &info, &fsp);
3550                 }
3551         }
3552
3553         if (!NT_STATUS_IS_OK(status)) {
3554                 goto fail;
3555         }
3556
3557         fsp->base_fsp = base_fsp;
3558
3559         if ((ea_list != NULL) &&
3560             ((info == FILE_WAS_CREATED) || (info == FILE_WAS_OVERWRITTEN))) {
3561                 status = set_ea(conn, fsp, fsp->fsp_name, ea_list);
3562                 if (!NT_STATUS_IS_OK(status)) {
3563                         goto fail;
3564                 }
3565         }
3566
3567         if (!fsp->is_directory && S_ISDIR(fsp->fsp_name->st.st_ex_mode)) {
3568                 status = NT_STATUS_ACCESS_DENIED;
3569                 goto fail;
3570         }
3571
3572         /* Save the requested allocation size. */
3573         if ((info == FILE_WAS_CREATED) || (info == FILE_WAS_OVERWRITTEN)) {
3574                 if (allocation_size
3575                     && (allocation_size > fsp->fsp_name->st.st_ex_size)) {
3576                         fsp->initial_allocation_size = smb_roundup(
3577                                 fsp->conn, allocation_size);
3578                         if (fsp->is_directory) {
3579                                 /* Can't set allocation size on a directory. */
3580                                 status = NT_STATUS_ACCESS_DENIED;
3581                                 goto fail;
3582                         }
3583                         if (vfs_allocate_file_space(
3584                                     fsp, fsp->initial_allocation_size) == -1) {
3585                                 status = NT_STATUS_DISK_FULL;
3586                                 goto fail;
3587                         }
3588                 } else {
3589                         fsp->initial_allocation_size = smb_roundup(
3590                                 fsp->conn, (uint64_t)fsp->fsp_name->st.st_ex_size);
3591                 }
3592         }
3593
3594         if ((info == FILE_WAS_CREATED) && lp_nt_acl_support(SNUM(conn)) &&
3595                                 fsp->base_fsp == NULL) {
3596                 if (sd != NULL) {
3597                         /*
3598                          * According to the MS documentation, the only time the security
3599                          * descriptor is applied to the opened file is iff we *created* the
3600                          * file; an existing file stays the same.
3601                          *
3602                          * Also, it seems (from observation) that you can open the file with
3603                          * any access mask but you can still write the sd. We need to override
3604                          * the granted access before we call set_sd
3605                          * Patch for bug #2242 from Tom Lackemann <cessnatomny@yahoo.com>.
3606                          */
3607
3608                         uint32_t sec_info_sent;
3609                         uint32_t saved_access_mask = fsp->access_mask;
3610
3611                         sec_info_sent = get_sec_info(sd);
3612
3613                         fsp->access_mask = FILE_GENERIC_ALL;
3614
3615                         /* Convert all the generic bits. */
3616                         security_acl_map_generic(sd->dacl, &file_generic_mapping);
3617                         security_acl_map_generic(sd->sacl, &file_generic_mapping);
3618
3619                         if (sec_info_sent & (SECINFO_OWNER|
3620                                                 SECINFO_GROUP|
3621                                                 SECINFO_DACL|
3622                                                 SECINFO_SACL)) {
3623                                 status = SMB_VFS_FSET_NT_ACL(fsp, sec_info_sent, sd);
3624                         }
3625
3626                         fsp->access_mask = saved_access_mask;
3627
3628                         if (!NT_STATUS_IS_OK(status)) {
3629                                 goto fail;
3630                         }
3631                 } else if (lp_inherit_acls(SNUM(conn))) {
3632                         /* Inherit from parent. Errors here are not fatal. */
3633                         status = inherit_new_acl(fsp);
3634                         if (!NT_STATUS_IS_OK(status)) {
3635                                 DEBUG(10,("inherit_new_acl: failed for %s with %s\n",
3636                                         fsp_str_dbg(fsp),
3637                                         nt_errstr(status) ));
3638                         }
3639                 }
3640         }
3641
3642         DEBUG(10, ("create_file_unixpath: info=%d\n", info));
3643
3644         *result = fsp;
3645         if (pinfo != NULL) {
3646                 *pinfo = info;
3647         }
3648
3649         smb_fname->st = fsp->fsp_name->st;
3650
3651         return NT_STATUS_OK;
3652
3653  fail:
3654         DEBUG(10, ("create_file_unixpath: %s\n", nt_errstr(status)));
3655
3656         if (fsp != NULL) {
3657                 if (base_fsp && fsp->base_fsp == base_fsp) {
3658                         /*
3659                          * The close_file below will close
3660                          * fsp->base_fsp.
3661                          */
3662                         base_fsp = NULL;
3663                 }
3664                 close_file(req, fsp, ERROR_CLOSE);
3665                 fsp = NULL;
3666         }
3667         if (base_fsp != NULL) {
3668                 close_file(req, base_fsp, ERROR_CLOSE);
3669                 base_fsp = NULL;
3670         }
3671         return status;
3672 }
3673
3674 /*
3675  * Calculate the full path name given a relative fid.
3676  */
3677 NTSTATUS get_relative_fid_filename(connection_struct *conn,
3678                                    struct smb_request *req,
3679                                    uint16_t root_dir_fid,
3680                                    const struct smb_filename *smb_fname,
3681                                    struct smb_filename **smb_fname_out)
3682 {
3683         files_struct *dir_fsp;
3684         char *parent_fname = NULL;
3685         char *new_base_name = NULL;
3686         NTSTATUS status;
3687
3688         if (root_dir_fid == 0 || !smb_fname) {
3689                 status = NT_STATUS_INTERNAL_ERROR;
3690                 goto out;
3691         }
3692
3693         dir_fsp = file_fsp(req, root_dir_fid);
3694
3695         if (dir_fsp == NULL) {
3696                 status = NT_STATUS_INVALID_HANDLE;
3697                 goto out;
3698         }
3699
3700         if (is_ntfs_stream_smb_fname(dir_fsp->fsp_name)) {
3701                 status = NT_STATUS_INVALID_HANDLE;
3702                 goto out;
3703         }
3704
3705         if (!dir_fsp->is_directory) {
3706
3707                 /*
3708                  * Check to see if this is a mac fork of some kind.
3709                  */
3710
3711                 if ((conn->fs_capabilities & FILE_NAMED_STREAMS) &&
3712                     is_ntfs_stream_smb_fname(smb_fname)) {
3713                         status = NT_STATUS_OBJECT_PATH_NOT_FOUND;
3714                         goto out;
3715                 }
3716
3717                 /*
3718                   we need to handle the case when we get a
3719                   relative open relative to a file and the
3720                   pathname is blank - this is a reopen!
3721                   (hint from demyn plantenberg)
3722                 */
3723
3724                 status = NT_STATUS_INVALID_HANDLE;
3725                 goto out;
3726         }
3727
3728         if (ISDOT(dir_fsp->fsp_name->base_name)) {
3729                 /*
3730                  * We're at the toplevel dir, the final file name
3731                  * must not contain ./, as this is filtered out
3732                  * normally by srvstr_get_path and unix_convert
3733                  * explicitly rejects paths containing ./.
3734                  */
3735                 parent_fname = talloc_strdup(talloc_tos(), "");
3736                 if (parent_fname == NULL) {
3737                         status = NT_STATUS_NO_MEMORY;
3738                         goto out;
3739                 }
3740         } else {
3741                 size_t dir_name_len = strlen(dir_fsp->fsp_name->base_name);
3742
3743                 /*
3744                  * Copy in the base directory name.
3745                  */
3746
3747                 parent_fname = talloc_array(talloc_tos(), char,
3748                     dir_name_len+2);
3749                 if (parent_fname == NULL) {
3750                         status = NT_STATUS_NO_MEMORY;
3751                         goto out;
3752                 }
3753                 memcpy(parent_fname, dir_fsp->fsp_name->base_name,
3754                     dir_name_len+1);
3755
3756                 /*
3757                  * Ensure it ends in a '/'.
3758                  * We used TALLOC_SIZE +2 to add space for the '/'.
3759                  */
3760
3761                 if(dir_name_len
3762                     && (parent_fname[dir_name_len-1] != '\\')
3763                     && (parent_fname[dir_name_len-1] != '/')) {
3764                         parent_fname[dir_name_len] = '/';
3765                         parent_fname[dir_name_len+1] = '\0';
3766                 }
3767         }
3768
3769         new_base_name = talloc_asprintf(talloc_tos(), "%s%s", parent_fname,
3770                                         smb_fname->base_name);
3771         if (new_base_name == NULL) {
3772                 status = NT_STATUS_NO_MEMORY;
3773                 goto out;
3774         }
3775
3776         status = filename_convert(req,
3777                                 conn,
3778                                 req->flags2 & FLAGS2_DFS_PATHNAMES,
3779                                 new_base_name,
3780                                 0,
3781                                 NULL,
3782                                 smb_fname_out);
3783         if (!NT_STATUS_IS_OK(status)) {
3784                 goto out;
3785         }
3786
3787  out:
3788         TALLOC_FREE(parent_fname);
3789         TALLOC_FREE(new_base_name);
3790         return status;
3791 }
3792
3793 NTSTATUS create_file_default(connection_struct *conn,
3794                              struct smb_request *req,
3795                              uint16_t root_dir_fid,
3796                              struct smb_filename *smb_fname,
3797                              uint32_t access_mask,
3798                              uint32_t share_access,
3799                              uint32_t create_disposition,
3800                              uint32_t create_options,
3801                              uint32_t file_attributes,
3802                              uint32_t oplock_request,
3803                              uint64_t allocation_size,
3804                              uint32_t private_flags,
3805                              struct security_descriptor *sd,
3806                              struct ea_list *ea_list,
3807                              files_struct **result,
3808                              int *pinfo)
3809 {
3810         int info = FILE_WAS_OPENED;
3811         files_struct *fsp = NULL;
3812         NTSTATUS status;
3813         bool stream_name = false;
3814
3815         DEBUG(10,("create_file: access_mask = 0x%x "
3816                   "file_attributes = 0x%x, share_access = 0x%x, "
3817                   "create_disposition = 0x%x create_options = 0x%x "
3818                   "oplock_request = 0x%x "
3819                   "private_flags = 0x%x "
3820                   "root_dir_fid = 0x%x, ea_list = 0x%p, sd = 0x%p, "
3821                   "fname = %s\n",
3822                   (unsigned int)access_mask,
3823                   (unsigned int)file_attributes,
3824                   (unsigned int)share_access,
3825                   (unsigned int)create_disposition,
3826                   (unsigned int)create_options,
3827                   (unsigned int)oplock_request,
3828                   (unsigned int)private_flags,
3829                   (unsigned int)root_dir_fid,
3830                   ea_list, sd, smb_fname_str_dbg(smb_fname)));
3831
3832         /*
3833          * Calculate the filename from the root_dir_if if necessary.
3834          */
3835
3836         if (root_dir_fid != 0) {
3837                 struct smb_filename *smb_fname_out = NULL;
3838                 status = get_relative_fid_filename(conn, req, root_dir_fid,
3839                                                    smb_fname, &smb_fname_out);
3840                 if (!NT_STATUS_IS_OK(status)) {
3841                         goto fail;
3842                 }
3843                 smb_fname = smb_fname_out;
3844         }
3845
3846         /*
3847          * Check to see if this is a mac fork of some kind.
3848          */
3849
3850         stream_name = is_ntfs_stream_smb_fname(smb_fname);
3851         if (stream_name) {
3852                 enum FAKE_FILE_TYPE fake_file_type;
3853
3854                 fake_file_type = is_fake_file(smb_fname);
3855
3856                 if (fake_file_type != FAKE_FILE_TYPE_NONE) {
3857
3858                         /*
3859                          * Here we go! support for changing the disk quotas
3860                          * --metze
3861                          *
3862                          * We need to fake up to open this MAGIC QUOTA file
3863                          * and return a valid FID.
3864                          *
3865                          * w2k close this file directly after openening xp
3866                          * also tries a QUERY_FILE_INFO on the file and then
3867                          * close it
3868                          */
3869                         status = open_fake_file(req, conn, req->vuid,
3870                                                 fake_file_type, smb_fname,
3871                                                 access_mask, &fsp);
3872                         if (!NT_STATUS_IS_OK(status)) {
3873                                 goto fail;
3874                         }
3875
3876                         ZERO_STRUCT(smb_fname->st);
3877                         goto done;
3878                 }
3879
3880                 if (!(conn->fs_capabilities & FILE_NAMED_STREAMS)) {
3881                         status = NT_STATUS_OBJECT_NAME_NOT_FOUND;
3882                         goto fail;
3883                 }
3884         }
3885
3886         if (is_ntfs_default_stream_smb_fname(smb_fname)) {
3887                 int ret;
3888                 smb_fname->stream_name = NULL;
3889                 /* We have to handle this error here. */
3890                 if (create_options & FILE_DIRECTORY_FILE) {
3891                         status = NT_STATUS_NOT_A_DIRECTORY;
3892                         goto fail;
3893                 }
3894                 if (lp_posix_pathnames()) {
3895                         ret = SMB_VFS_LSTAT(conn, smb_fname);
3896                 } else {
3897                         ret = SMB_VFS_STAT(conn, smb_fname);
3898                 }
3899
3900                 if (ret == 0 && VALID_STAT_OF_DIR(smb_fname->st)) {
3901                         status = NT_STATUS_FILE_IS_A_DIRECTORY;
3902                         goto fail;
3903                 }
3904         }
3905
3906         status = create_file_unixpath(
3907                 conn, req, smb_fname, access_mask, share_access,
3908                 create_disposition, create_options, file_attributes,
3909                 oplock_request, allocation_size, private_flags,
3910                 sd, ea_list,
3911                 &fsp, &info);
3912
3913         if (!NT_STATUS_IS_OK(status)) {
3914                 goto fail;
3915         }
3916
3917  done:
3918         DEBUG(10, ("create_file: info=%d\n", info));
3919
3920         *result = fsp;
3921         if (pinfo != NULL) {
3922                 *pinfo = info;
3923         }
3924         return NT_STATUS_OK;
3925
3926  fail:
3927         DEBUG(10, ("create_file: %s\n", nt_errstr(status)));
3928
3929         if (fsp != NULL) {
3930                 close_file(req, fsp, ERROR_CLOSE);
3931                 fsp = NULL;
3932         }
3933         return status;
3934 }