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