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