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