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