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