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