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