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