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